1 /**************************************************************************
2 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
4 * Author: The ALICE Off-line Project. *
5 * Contributors are mentioned in the code where appropriate. *
7 * Permission to use, copy, modify and distribute this software and its *
8 * documentation strictly for non-commercial purposes is hereby granted *
9 * without fee, provided that the above copyright notice appears in all *
10 * copies and that both the copyright notice and this permission notice *
11 * appear in the supporting documentation. The authors make no claims *
12 * about the suitability of this software for any purpose. It is *
13 * provided "as is" without express or implied warranty. *
14 **************************************************************************/
19 // This class is the main manager for AliShuttle.
20 // It organizes the data retrieval from DCS and call the
21 // interface methods of AliPreprocessor.
22 // For every detector in AliShuttleConfgi (see AliShuttleConfig),
23 // data for its set of aliases is retrieved. If there is registered
24 // AliPreprocessor for this detector then it will be used
25 // accroding to the schema (see AliPreprocessor).
26 // If there isn't registered AliPreprocessor than the retrieved
27 // data is stored automatically to the undelying AliCDBStorage.
28 // For detSpec is used the alias name.
31 #include "AliShuttle.h"
33 #include "AliCDBManager.h"
34 #include "AliCDBStorage.h"
36 #include "AliCDBRunRange.h"
37 #include "AliCDBPath.h"
38 #include "AliCDBEntry.h"
39 #include "AliShuttleConfig.h"
40 #include "DCSClient/AliDCSClient.h"
42 #include "AliPreprocessor.h"
43 #include "AliShuttleStatus.h"
44 #include "AliShuttleLogbookEntry.h"
49 #include <TTimeStamp.h>
50 #include <TObjString.h>
51 #include <TSQLServer.h>
52 #include <TSQLResult.h>
55 #include <TSystemDirectory.h>
56 #include <TSystemFile.h>
59 #include <TGridResult.h>
62 #include <TMonaLisaWriter.h>
66 #include <sys/types.h>
73 //______________________________________________________________________________________________
74 AliShuttle::AliShuttle(const AliShuttleConfig* config,
75 UInt_t timeout, Int_t retries):
77 fTimeout(timeout), fRetries(retries),
89 fReadTestMode(kFALSE),
90 fOutputRedirected(kFALSE)
93 // config: AliShuttleConfig used
94 // timeout: timeout used for AliDCSClient connection
95 // retries: the number of retries in case of connection error.
98 if (!fConfig->IsValid()) AliFatal("********** !!!!! Invalid configuration !!!!! **********");
99 for(int iSys=0;iSys<4;iSys++) {
102 fFXSlist[iSys].SetOwner(kTRUE);
104 fPreprocessorMap.SetOwner(kTRUE);
106 for (UInt_t iDet=0; iDet<NDetectors(); iDet++)
107 fFirstUnprocessed[iDet] = kFALSE;
109 fMonitoringMutex = new TMutex();
112 //______________________________________________________________________________________________
113 AliShuttle::~AliShuttle()
119 fPreprocessorMap.DeleteAll();
120 for(int iSys=0;iSys<4;iSys++)
122 fServer[iSys]->Close();
123 delete fServer[iSys];
132 if (fMonitoringMutex)
134 delete fMonitoringMutex;
135 fMonitoringMutex = 0;
139 //______________________________________________________________________________________________
140 void AliShuttle::RegisterPreprocessor(AliPreprocessor* preprocessor)
143 // Registers new AliPreprocessor.
144 // It uses GetName() for indentificator of the pre processor.
145 // The pre processor is registered it there isn't any other
146 // with the same identificator (GetName()).
149 const char* detName = preprocessor->GetName();
150 if(GetDetPos(detName) < 0)
151 AliFatal(Form("********** !!!!! Invalid detector name: %s !!!!! **********", detName));
153 if (fPreprocessorMap.GetValue(detName)) {
154 AliWarning(Form("AliPreprocessor %s is already registered!", detName));
158 fPreprocessorMap.Add(new TObjString(detName), preprocessor);
160 //______________________________________________________________________________________________
161 Bool_t AliShuttle::Store(const AliCDBPath& path, TObject* object,
162 AliCDBMetaData* metaData, Int_t validityStart, Bool_t validityInfinite)
164 // Stores a CDB object in the storage for offline reconstruction. Objects that are not needed for
165 // offline reconstruction, but should be stored anyway (e.g. for debugging) should NOT be stored
166 // using this function. Use StoreReferenceData instead!
167 // It calls StoreLocally function which temporarily stores the data locally; when the preprocessor
168 // finishes the data are transferred to the main storage (Grid).
170 return StoreLocally(fgkLocalCDB, path, object, metaData, validityStart, validityInfinite);
173 //______________________________________________________________________________________________
174 Bool_t AliShuttle::StoreReferenceData(const AliCDBPath& path, TObject* object, AliCDBMetaData* metaData)
176 // Stores a CDB object in the storage for reference data. This objects will not be available during
177 // offline reconstrunction. Use this function for reference data only!
178 // It calls StoreLocally function which temporarily stores the data locally; when the preprocessor
179 // finishes the data are transferred to the main storage (Grid).
181 return StoreLocally(fgkLocalRefStorage, path, object, metaData);
184 //______________________________________________________________________________________________
185 Bool_t AliShuttle::StoreLocally(const TString& localUri,
186 const AliCDBPath& path, TObject* object, AliCDBMetaData* metaData,
187 Int_t validityStart, Bool_t validityInfinite)
189 // Store object temporarily in local storage. Parameters are passed by Store and StoreReferenceData functions.
190 // when the preprocessor finishes the data are transferred to the main storage (Grid).
191 // The parameters are:
192 // 1) Uri of the backup storage (Local)
193 // 2) the object's path.
194 // 3) the object to be stored
195 // 4) the metaData to be associated with the object
196 // 5) the validity start run number w.r.t. the current run,
197 // if the data is valid only for this run leave the default 0
198 // 6) specifies if the calibration data is valid for infinity (this means until updated),
199 // typical for calibration runs, the default is kFALSE
201 // returns 0 if fail, 1 otherwise
203 if (fTestMode & kErrorStorage)
205 Log(fCurrentDetector, "StoreLocally - In TESTMODE - Simulating error while storing locally");
209 const char* cdbType = (localUri == fgkLocalCDB) ? "CDB" : "Reference";
211 Int_t firstRun = GetCurrentRun() - validityStart;
213 AliWarning("First valid run happens to be less than 0! Setting it to 0.");
218 if(validityInfinite) {
219 lastRun = AliCDBRunRange::Infinity();
221 lastRun = GetCurrentRun();
224 // Version is set to current run, it will be used later to transfer data to Grid
225 AliCDBId id(path, firstRun, lastRun, GetCurrentRun(), -1);
227 if(! dynamic_cast<TObjString*> (metaData->GetProperty("RunUsed(TObjString)"))){
228 TObjString runUsed = Form("%d", GetCurrentRun());
229 metaData->SetProperty("RunUsed(TObjString)", runUsed.Clone());
232 Bool_t result = kFALSE;
234 if (!(AliCDBManager::Instance()->GetStorage(localUri))) {
235 Log("SHUTTLE", Form("StoreLocally - Cannot activate local %s storage", cdbType));
237 result = AliCDBManager::Instance()->GetStorage(localUri)
238 ->Put(object, id, metaData);
243 Log(fCurrentDetector, Form("StoreLocally - Can't store object <%s>!", id.ToString().Data()));
249 //______________________________________________________________________________________________
250 Bool_t AliShuttle::StoreOCDB()
253 // Called when preprocessor ends successfully or when previous storage attempt failed (kStoreError status)
254 // Calls underlying StoreOCDB(const char*) function twice, for OCDB and Reference storage.
255 // Then calls StoreRefFilesToGrid to store reference files.
258 UpdateShuttleStatus(AliShuttleStatus::kStoreStarted);
260 if (fTestMode & kErrorGrid)
262 Log("SHUTTLE", "StoreOCDB - In TESTMODE - Simulating error while storing in the Grid");
263 Log(fCurrentDetector, "StoreOCDB - In TESTMODE - Simulating error while storing in the Grid");
267 Log("SHUTTLE","StoreOCDB - Storing OCDB data ...");
268 Int_t resultCDB = StoreOCDB(fgkMainCDB);
270 Log("SHUTTLE","StoreOCDB - Storing reference data ...");
271 Int_t resultRef = StoreOCDB(fgkMainRefStorage);
273 Log("SHUTTLE","StoreOCDB - Storing reference files ...");
274 Bool_t resultRefFiles = CopyFilesToGrid("reference");
276 Bool_t resultMetadata = kTRUE;
277 if(fCurrentDetector == "GRP")
279 Log("StoreOCDB - SHUTTLE","Storing Run Metadata file ...");
280 resultMetadata = CopyFilesToGrid("metadata");
283 Int_t storeResult = 0;
285 if (resultCDB < 0 || resultRef < 0 || resultRefFiles == kFALSE || resultMetadata == kFALSE)
287 else if (resultCDB > 0 || resultRef > 0)
293 Form("\t\t\t****** run %d - %s: STORAGE ERROR ******",
294 GetCurrentRun(), fCurrentDetector.Data()));
295 UpdateShuttleStatus(AliShuttleStatus::kStoreError);
297 else if (storeResult > 0)
300 Form("\t\t\t****** run %d - %s: STORAGE DELAYED ******",
301 GetCurrentRun(), fCurrentDetector.Data()));
302 UpdateShuttleStatus(AliShuttleStatus::kStoreDelayed);
304 else if (storeResult == 0)
307 Form("\t\t\t****** run %d - %s: DONE ******",
308 GetCurrentRun(), fCurrentDetector.Data()));
309 UpdateShuttleStatus(AliShuttleStatus::kDone);
310 UpdateShuttleLogbook(fCurrentDetector, "DONE");
313 return (storeResult == 0);
316 //______________________________________________________________________________________________
317 Int_t AliShuttle::StoreOCDB(const TString& gridURI)
320 // Called by StoreOCDB(), performs actual storage to the main OCDB and reference storages (Grid)
323 // -2 initialization error
326 // 1 storage delayed (e.g. previous unprocessed runs)
329 TObjArray* gridIds=0;
331 Bool_t result = kTRUE;
332 Bool_t delayed = kFALSE;
334 const char* type = 0;
336 if(gridURI == fgkMainCDB) {
338 localURI = fgkLocalCDB;
339 } else if(gridURI == fgkMainRefStorage) {
341 localURI = fgkLocalRefStorage;
343 AliError(Form("Invalid storage URI: %s", gridURI.Data()));
347 AliCDBManager* man = AliCDBManager::Instance();
349 AliCDBStorage *gridSto = man->GetStorage(gridURI);
352 Form("StoreOCDB - cannot activate main %s storage", type));
356 gridIds = gridSto->GetQueryCDBList();
358 // get objects previously stored in local CDB
359 AliCDBStorage *localSto = man->GetStorage(localURI);
362 Form("StoreOCDB - cannot activate local %s storage", type));
365 AliCDBPath aPath(GetOfflineDetName(fCurrentDetector.Data()),"*","*");
366 // Local objects were stored with current run as Grid version!
367 TList* localEntries = localSto->GetAll(aPath.GetPath(), GetCurrentRun(), GetCurrentRun());
368 localEntries->SetOwner(1);
370 // loop on local stored objects
371 TIter localIter(localEntries);
372 AliCDBEntry *aLocEntry = 0;
373 while((aLocEntry = dynamic_cast<AliCDBEntry*> (localIter.Next()))){
374 aLocEntry->SetOwner(1);
375 AliCDBId aLocId = aLocEntry->GetId();
376 aLocEntry->SetVersion(-1);
377 aLocEntry->SetSubVersion(-1);
379 // If local object is valid up to infinity we store it only if it is
380 // the first unprocessed run!
381 if (aLocId.GetLastRun() == AliCDBRunRange::Infinity() &&
382 !fFirstUnprocessed[GetDetPos(fCurrentDetector)])
384 Log("SHUTTLE", Form("StoreOCDB - %s: object %s has validity infinite but "
385 "there are previous unprocessed runs!",
386 fCurrentDetector.Data(), aLocId.GetPath().Data()));
387 Log(fCurrentDetector.Data(), Form("StoreOCDB - %s: object %s has validity infinite but "
388 "there are previous unprocessed runs!",
389 fCurrentDetector.Data(), aLocId.GetPath().Data()));
394 // loop on Grid valid Id's
395 Bool_t store = kTRUE;
396 TIter gridIter(gridIds);
397 AliCDBId* aGridId = 0;
398 while((aGridId = dynamic_cast<AliCDBId*> (gridIter.Next()))){
399 if(aGridId->GetPath() != aLocId.GetPath()) continue;
400 // skip all objects valid up to infinity
401 if(aGridId->GetLastRun() == AliCDBRunRange::Infinity()) continue;
402 // if we get here, it means there's already some more recent object stored on Grid!
407 // If we get here, the file can be stored!
408 Bool_t storeOk = gridSto->Put(aLocEntry);
409 if(!store || storeOk){
413 Log(fCurrentDetector.Data(),
414 Form("StoreOCDB - A more recent object already exists in %s storage: <%s>",
415 type, aGridId->ToString().Data()));
418 Form("StoreOCDB - Object <%s> successfully put into %s storage",
419 aLocId.ToString().Data(), type));
420 Log(fCurrentDetector.Data(),
421 Form("StoreOCDB - Object <%s> successfully put into %s storage",
422 aLocId.ToString().Data(), type));
425 // removing local filename...
427 localSto->IdToFilename(aLocId, filename);
428 Log("SHUTTLE", Form("StoreOCDB - Removing local file %s", filename.Data()));
429 RemoveFile(filename.Data());
433 Form("StoreOCDB - Grid %s storage of object <%s> failed",
434 type, aLocId.ToString().Data()));
435 Log(fCurrentDetector.Data(),
436 Form("StoreOCDB - Grid %s storage of object <%s> failed",
437 type, aLocId.ToString().Data()));
441 localEntries->Clear();
443 Int_t returnCode = 0;
445 if (result == kFALSE)
447 else if (delayed != kFALSE)
450 Log("SHUTTLE", Form("StoreOCDB - Returning with %d (result = %d, delayed = %d)", returnCode, result, delayed));
451 Log(fCurrentDetector.Data(), Form("StoreOCDB - Returning with %d (result = %d, delayed = %d)", returnCode, result, delayed));
456 //______________________________________________________________________________________________
457 Bool_t AliShuttle::CleanReferenceStorage(const char* detector)
459 // clears the directory used to store reference files of a given subdetector
461 AliCDBManager* man = AliCDBManager::Instance();
462 AliCDBStorage* sto = man->GetStorage(fgkLocalRefStorage);
463 TString localBaseFolder = sto->GetBaseFolder();
465 TString targetDir = GetRefFilePrefix(localBaseFolder.Data(), detector);
467 Log("SHUTTLE", Form("CleanReferenceStorage - Cleaning %s", targetDir.Data()));
470 begin.Form("%d_", GetCurrentRun());
472 TSystemDirectory* baseDir = new TSystemDirectory("/", targetDir);
476 TList* dirList = baseDir->GetListOfFiles();
479 if (!dirList) return kTRUE;
481 if (dirList->GetEntries() < 3)
487 Int_t nDirs = 0, nDel = 0;
488 TIter dirIter(dirList);
489 TSystemFile* entry = 0;
491 Bool_t success = kTRUE;
493 while ((entry = dynamic_cast<TSystemFile*> (dirIter.Next())))
495 if (entry->IsDirectory())
498 TString fileName(entry->GetName());
499 if (!fileName.BeginsWith(begin))
505 Int_t result = gSystem->Unlink(fileName.Data());
509 Log("SHUTTLE", Form("CleanReferenceStorage - Could not delete file %s!", fileName.Data()));
517 Log("SHUTTLE", Form("CleanReferenceStorage - %d (over %d) reference files in folder %s were deleted.",
518 nDel, nDirs, targetDir.Data()));
529 Int_t result = gSystem->GetPathInfo(targetDir, 0, (Long64_t*) 0, 0, 0);
533 result = gSystem->Exec(Form("rm -rf %s", targetDir.Data()));
536 Log("SHUTTLE", Form("CleanReferenceStorage - Could not clean directory %s", targetDir.Data()));
541 result = gSystem->mkdir(targetDir, kTRUE);
544 Log("SHUTTLE", Form("CleanReferenceStorage - Error creating base directory %s", targetDir.Data()));
551 //______________________________________________________________________________________________
552 Bool_t AliShuttle::StoreReferenceFile(const char* detector, const char* localFile, const char* gridFileName)
555 // Stores reference file directly (without opening it). This function stores the file locally.
557 // The file is stored under the following location:
558 // <base folder of local reference storage>/<DET>/<RUN#>_<gridFileName>
559 // where <gridFileName> is the second parameter given to the function
562 if (fTestMode & kErrorStorage)
564 Log(fCurrentDetector, "StoreReferenceFile - In TESTMODE - Simulating error while storing locally");
568 AliCDBManager* man = AliCDBManager::Instance();
569 AliCDBStorage* sto = man->GetStorage(fgkLocalRefStorage);
571 TString localBaseFolder = sto->GetBaseFolder();
573 TString target = GetRefFilePrefix(localBaseFolder.Data(), detector);
574 target.Append(Form("/%d_%s", GetCurrentRun(), gridFileName));
576 return CopyFileLocally(localFile, target);
579 //______________________________________________________________________________________________
580 Bool_t AliShuttle::StoreRunMetadataFile(const char* localFile, const char* gridFileName)
583 // Stores Run metadata file to the Grid, in the run folder
585 // Only GRP can call this function.
587 if (fTestMode & kErrorStorage)
589 Log(fCurrentDetector, "StoreRunMetaDataFile - In TESTMODE - Simulating error while storing locally");
593 AliCDBManager* man = AliCDBManager::Instance();
594 AliCDBStorage* sto = man->GetStorage(fgkLocalRefStorage);
596 TString localBaseFolder = sto->GetBaseFolder();
598 // Build Run level folder
599 // folder = /alice/data/year/lhcPeriod/runNb/raw
602 TString lhcPeriod = GetLHCPeriod();
603 if (lhcPeriod.Length() == 0)
605 Log("SHUTTLE","StoreRunMetaDataFile - LHCPeriod not found in logbook!");
609 // TODO partitions with one detector only write data into LHCperiod_DET
610 TString partition = GetRunParameter("detector");
612 if (partition.Length() > 0 && partition != "ALICE")
614 lhcPeriod.Append(Form("_%s", partition.Data()));
615 Log(fCurrentDetector, Form("Run data tags merged file will be written in %s",
619 TString target = Form("%s/GRP/RunMetadata%s%d/%s/%09d/raw/%s",
620 localBaseFolder.Data(), fConfig->GetAlienPath(), GetCurrentYear(),
621 lhcPeriod.Data(), GetCurrentRun(), gridFileName);
623 return CopyFileLocally(localFile, target);
626 //______________________________________________________________________________________________
627 Bool_t AliShuttle::CopyFileLocally(const char* localFile, const TString& target)
630 // Stores file locally. Called by StoreReferenceFile and StoreRunMetadataFile
631 // Files are temporarily stored in the local reference storage. When the preprocessor
632 // finishes, the Shuttle calls CopyFilesToGrid to transfer the files to AliEn
633 // (in reference or run level folders)
636 TString targetDir(target(0, target.Last('/')));
638 //try to open base dir folder, if it does not exist
639 void* dir = gSystem->OpenDirectory(targetDir.Data());
641 if (gSystem->mkdir(targetDir.Data(), kTRUE)) {
642 Log("SHUTTLE", Form("CopyFileLocally - Can't open directory <%s>", targetDir.Data()));
647 gSystem->FreeDirectory(dir);
652 result = gSystem->GetPathInfo(localFile, 0, (Long64_t*) 0, 0, 0);
655 Log("SHUTTLE", Form("CopyFileLocally - %s does not exist", localFile));
659 result = gSystem->GetPathInfo(target, 0, (Long64_t*) 0, 0, 0);
662 Log("SHUTTLE", Form("CopyFileLocally - target file %s already exist, removing...", target.Data()));
663 if (gSystem->Unlink(target.Data()))
665 Log("SHUTTLE", Form("CopyFileLocally - Could not remove existing target file %s!", target.Data()));
670 result = gSystem->CopyFile(localFile, target);
674 Log("SHUTTLE", Form("CopyFileLocally - File %s stored locally to %s", localFile, target.Data()));
679 Log("SHUTTLE", Form("CopyFileLocally - Could not store file %s to %s! Error code = %d",
680 localFile, target.Data(), result));
688 //______________________________________________________________________________________________
689 Bool_t AliShuttle::CopyFilesToGrid(const char* type)
692 // Transfers local files to the Grid. Local files can be reference files
693 // or run metadata file (from GRP only).
695 // According to the type (ref, metadata) the files are stored under the following location:
696 // ref --> <base folder of reference storage>/<DET>/<RUN#>_<gridFileName>
697 // metadata --> <run data folder>/<MetadataFileName>
700 AliCDBManager* man = AliCDBManager::Instance();
701 AliCDBStorage* sto = man->GetStorage(fgkLocalRefStorage);
704 TString localBaseFolder = sto->GetBaseFolder();
710 if (strcmp(type, "reference") == 0)
712 dir = GetRefFilePrefix(localBaseFolder.Data(), fCurrentDetector.Data());
713 AliCDBStorage* gridSto = man->GetStorage(fgkMainRefStorage);
716 TString gridBaseFolder = gridSto->GetBaseFolder();
717 alienDir = GetRefFilePrefix(gridBaseFolder.Data(), fCurrentDetector.Data());
718 begin = Form("%d_", GetCurrentRun());
720 else if (strcmp(type, "metadata") == 0)
723 TString lhcPeriod = GetLHCPeriod();
725 if (lhcPeriod.Length() == 0)
727 Log("SHUTTLE","CopyFilesToGrid - LHCPeriod not found in logbook!");
731 // TODO partitions with one detector only write data into LHCperiod_DET
732 TString partition = GetRunParameter("detector");
734 if (partition.Length() > 0 && partition != "ALICE")
736 lhcPeriod.Append(Form("_%s", partition.Data()));
739 dir = Form("%s/GRP/RunMetadata%s%d/%s/%09d/raw",
740 localBaseFolder.Data(), fConfig->GetAlienPath(), GetCurrentYear(),
741 lhcPeriod.Data(), GetCurrentRun());
742 alienDir = dir(dir.Index(fConfig->GetAlienPath()), dir.Length());
748 Log("SHUTTLE", "CopyFilesToGrid - Unexpected: type label must be reference or metadata!");
752 TSystemDirectory* baseDir = new TSystemDirectory("/", dir);
756 TList* dirList = baseDir->GetListOfFiles();
759 if (!dirList) return kTRUE;
761 if (dirList->GetEntries() < 3)
769 Log("SHUTTLE", "CopyFilesToGrid - Connection to Grid failed: Cannot continue!");
774 Int_t nDirs = 0, nTransfer = 0;
775 TIter dirIter(dirList);
776 TSystemFile* entry = 0;
778 Bool_t success = kTRUE;
779 Bool_t first = kTRUE;
781 while ((entry = dynamic_cast<TSystemFile*> (dirIter.Next())))
783 if (entry->IsDirectory())
786 TString fileName(entry->GetName());
787 if (!fileName.BeginsWith(begin))
795 // check that folder exists, otherwise create it
796 TGridResult* result = gGrid->Ls(alienDir.Data(), "a");
804 if (!result->GetFileName(1)) // TODO: It looks like element 0 is always 0!!
806 // TODO It does not work currently! Bug in TAliEn::Mkdir
807 // TODO Manually fixed in local root v5-16-00
808 if (!gGrid->Mkdir(alienDir.Data(),"-p",0))
810 Log("SHUTTLE", Form("CopyFilesToGrid - Cannot create directory %s",
815 Log("SHUTTLE",Form("CopyFilesToGrid - Folder %s created", alienDir.Data()));
819 Log("SHUTTLE",Form("CopyFilesToGrid - Folder %s found", alienDir.Data()));
823 TString fullLocalPath;
824 fullLocalPath.Form("%s/%s", dir.Data(), fileName.Data());
826 TString fullGridPath;
827 fullGridPath.Form("alien://%s/%s", alienDir.Data(), fileName.Data());
829 Bool_t result = TFile::Cp(fullLocalPath, fullGridPath);
833 Log("SHUTTLE", Form("CopyFilesToGrid - Copying local file %s to %s succeeded!",
834 fullLocalPath.Data(), fullGridPath.Data()));
835 RemoveFile(fullLocalPath);
840 Log("SHUTTLE", Form("CopyFilesToGrid - Copying local file %s to %s FAILED!",
841 fullLocalPath.Data(), fullGridPath.Data()));
846 Log("SHUTTLE", Form("CopyFilesToGrid - %d (over %d) files in folder %s copied to Grid.",
847 nTransfer, nDirs, dir.Data()));
854 //______________________________________________________________________________________________
855 const char* AliShuttle::GetRefFilePrefix(const char* base, const char* detector)
858 // Get folder name of reference files
861 TString offDetStr(GetOfflineDetName(detector));
863 if (offDetStr == "ITS" || offDetStr == "MUON" || offDetStr == "PHOS")
865 dir.Form("%s/%s/%s", base, offDetStr.Data(), detector);
867 dir.Form("%s/%s", base, offDetStr.Data());
875 //______________________________________________________________________________________________
876 void AliShuttle::CleanLocalStorage(const TString& uri)
879 // Called in case the preprocessor is declared failed. Remove remaining objects from the local storages.
882 const char* type = 0;
883 if(uri == fgkLocalCDB) {
885 } else if(uri == fgkLocalRefStorage) {
888 AliError(Form("Invalid storage URI: %s", uri.Data()));
892 AliCDBManager* man = AliCDBManager::Instance();
894 // open local storage
895 AliCDBStorage *localSto = man->GetStorage(uri);
898 Form("CleanLocalStorage - cannot activate local %s storage", type));
902 TString filename(Form("%s/%s/*/Run*_v%d_s*.root",
903 localSto->GetBaseFolder().Data(), GetOfflineDetName(fCurrentDetector.Data()), GetCurrentRun()));
905 AliDebug(2, Form("filename = %s", filename.Data()));
907 Log("SHUTTLE", Form("Removing remaining local files for run %d and detector %s ...",
908 GetCurrentRun(), fCurrentDetector.Data()));
910 RemoveFile(filename.Data());
914 //______________________________________________________________________________________________
915 void AliShuttle::RemoveFile(const char* filename)
918 // removes local file
921 TString command(Form("rm -f %s", filename));
923 Int_t result = gSystem->Exec(command.Data());
926 Log("SHUTTLE", Form("RemoveFile - %s: Cannot remove file %s!",
927 fCurrentDetector.Data(), filename));
931 //______________________________________________________________________________________________
932 AliShuttleStatus* AliShuttle::ReadShuttleStatus()
935 // Reads the AliShuttleStatus from the CDB
943 fStatusEntry = AliCDBManager::Instance()->GetStorage(GetLocalCDB())
944 ->Get(Form("/SHUTTLE/STATUS/%s", fCurrentDetector.Data()), GetCurrentRun());
946 if (!fStatusEntry) return 0;
947 fStatusEntry->SetOwner(1);
949 AliShuttleStatus* status = dynamic_cast<AliShuttleStatus*> (fStatusEntry->GetObject());
951 AliError("Invalid object stored to CDB!");
958 //______________________________________________________________________________________________
959 Bool_t AliShuttle::WriteShuttleStatus(AliShuttleStatus* status)
962 // writes the status for one subdetector
970 Int_t run = GetCurrentRun();
972 AliCDBId id(AliCDBPath("SHUTTLE", "STATUS", fCurrentDetector), run, run);
974 fStatusEntry = new AliCDBEntry(status, id, new AliCDBMetaData);
975 fStatusEntry->SetOwner(1);
977 UInt_t result = AliCDBManager::Instance()->GetStorage(fgkLocalCDB)->Put(fStatusEntry);
980 Log("SHUTTLE", Form("WriteShuttleStatus - Failed for %s, run %d",
981 fCurrentDetector.Data(), run));
990 //______________________________________________________________________________________________
991 void AliShuttle::UpdateShuttleStatus(AliShuttleStatus::Status newStatus, Bool_t increaseCount)
994 // changes the AliShuttleStatus for the given detector and run to the given status
998 AliError("UNEXPECTED: fStatusEntry empty");
1002 AliShuttleStatus* status = dynamic_cast<AliShuttleStatus*> (fStatusEntry->GetObject());
1005 Log("SHUTTLE", "UpdateShuttleStatus - UNEXPECTED: status could not be read from current CDB entry");
1009 TString actionStr = Form("UpdateShuttleStatus - %s: Changing state from %s to %s",
1010 fCurrentDetector.Data(),
1011 status->GetStatusName(),
1012 status->GetStatusName(newStatus));
1013 Log("SHUTTLE", actionStr);
1014 SetLastAction(actionStr);
1016 status->SetStatus(newStatus);
1017 if (increaseCount) status->IncreaseCount();
1019 AliCDBManager::Instance()->GetStorage(fgkLocalCDB)->Put(fStatusEntry);
1024 //______________________________________________________________________________________________
1025 void AliShuttle::SendMLDetInfo()
1028 // sends ML information about the current status of the current detector being processed
1031 AliShuttleStatus* status = dynamic_cast<AliShuttleStatus*> (fStatusEntry->GetObject());
1034 Log("SHUTTLE", "SendMLDetInfo - UNEXPECTED: status could not be read from current CDB entry");
1038 TMonaLisaText mlStatus(Form("%s_status", fCurrentDetector.Data()), status->GetStatusName());
1039 TMonaLisaValue mlRetryCount(Form("%s_count", fCurrentDetector.Data()), status->GetCount());
1042 mlList.Add(&mlStatus);
1043 mlList.Add(&mlRetryCount);
1046 mlID.Form("%d", GetCurrentRun());
1047 fMonaLisa->SendParameters(&mlList, mlID);
1050 //______________________________________________________________________________________________
1051 Bool_t AliShuttle::ContinueProcessing()
1053 // this function reads the AliShuttleStatus information from CDB and
1054 // checks if the processing should be continued
1055 // if yes it returns kTRUE and updates the AliShuttleStatus with nextStatus
1057 if (!fConfig->HostProcessDetector(fCurrentDetector))
1060 AliPreprocessor* aPreprocessor =
1061 dynamic_cast<AliPreprocessor*> (fPreprocessorMap.GetValue(fCurrentDetector));
1064 Log("SHUTTLE", Form("ContinueProcessing - %s: no preprocessor registered", fCurrentDetector.Data()));
1068 AliShuttleLogbookEntry::Status entryStatus =
1069 fLogbookEntry->GetDetectorStatus(fCurrentDetector);
1071 if (entryStatus != AliShuttleLogbookEntry::kUnprocessed) {
1072 Log("SHUTTLE", Form("ContinueProcessing - %s is %s",
1073 fCurrentDetector.Data(),
1074 fLogbookEntry->GetDetectorStatusName(entryStatus)));
1078 // if we get here, according to Shuttle logbook subdetector is in UNPROCESSED state
1080 // check if current run is first unprocessed run for current detector
1081 if (fConfig->StrictRunOrder(fCurrentDetector) &&
1082 !fFirstUnprocessed[GetDetPos(fCurrentDetector)])
1084 if (fTestMode == kNone)
1086 Log("SHUTTLE", Form("ContinueProcessing - %s requires strict run ordering"
1087 " but this is not the first unprocessed run!"));
1092 Log("SHUTTLE", Form("ContinueProcessing - In TESTMODE - "
1093 "Although %s requires strict run ordering "
1094 "and this is not the first unprocessed run, "
1095 "the SHUTTLE continues"));
1099 // Is the subdetector processed first time for this run?
1100 fFirstProcessing = kFALSE;
1102 AliShuttleStatus* status = ReadShuttleStatus();
1105 Log("SHUTTLE", Form("ContinueProcessing - %s: Processing first time",
1106 fCurrentDetector.Data()));
1107 status = new AliShuttleStatus(AliShuttleStatus::kStarted);
1108 fFirstProcessing = kTRUE;
1109 return WriteShuttleStatus(status);
1112 // The following case shouldn't happen if Shuttle Logbook was correctly updated.
1113 // If it happens it may mean Logbook updating failed... let's do it now!
1114 if (status->GetStatus() == AliShuttleStatus::kDone ||
1115 status->GetStatus() == AliShuttleStatus::kFailed ||
1116 status->GetStatus() == AliShuttleStatus::kSkipped) {
1117 Log("SHUTTLE", Form("ContinueProcessing - %s is already %s. Updating Shuttle Logbook",
1118 fCurrentDetector.Data(),
1119 status->GetStatusName(status->GetStatus())));
1121 if (status->GetStatus() == AliShuttleStatus::kSkipped)
1123 UpdateShuttleLogbook(fCurrentDetector.Data(), "DONE");
1126 UpdateShuttleLogbook(fCurrentDetector.Data(), status->GetStatusName(status->GetStatus()));
1131 if (status->GetStatus() == AliShuttleStatus::kStoreStarted || status->GetStatus() == AliShuttleStatus::kStoreDelayed ||status->GetStatus() == AliShuttleStatus::kStoreError) {
1133 Form("ContinueProcessing - %s: Grid storage of one or more "
1134 "objects failed. Trying again now",
1135 fCurrentDetector.Data()));
1140 // if we get here, there is a restart
1141 Bool_t cont = kFALSE;
1144 if (status->GetCount() >= fConfig->GetMaxRetries()) {
1145 Log("SHUTTLE", Form("ContinueProcessing - %s failed %d times in status %s - "
1146 "Updating Shuttle Logbook", fCurrentDetector.Data(),
1147 status->GetCount(), status->GetStatusName()));
1148 UpdateShuttleLogbook(fCurrentDetector.Data(), "FAILED");
1149 UpdateShuttleStatus(AliShuttleStatus::kFailed);
1151 // there may still be objects in local OCDB and reference storage
1152 // and FXS databases may be not updated: do it now!
1154 // TODO Currently disabled, we want to keep files in case of failure!
1155 // CleanLocalStorage(fgkLocalCDB);
1156 // CleanLocalStorage(fgkLocalRefStorage);
1157 // UpdateTableFailCase();
1159 // Send mail to detector expert!
1160 Log("SHUTTLE", Form("ContinueProcessing - Sending mail to %s expert...",
1161 fCurrentDetector.Data()));
1162 if (!SendMail(kPPEMail))
1163 Log("SHUTTLE", Form("ContinueProcessing - Could not send mail to %s expert",
1164 fCurrentDetector.Data()));
1167 Log("SHUTTLE", Form("ContinueProcessing - %s: restarting. "
1168 "Aborted before with %s. Retry number %d.", fCurrentDetector.Data(),
1169 status->GetStatusName(), status->GetCount()));
1170 Bool_t increaseCount = kTRUE;
1171 if (status->GetStatus() == AliShuttleStatus::kDCSError ||
1172 status->GetStatus() == AliShuttleStatus::kDCSStarted ||
1173 status->GetStatus() == AliShuttleStatus::kFXSError)
1174 increaseCount = kFALSE;
1176 UpdateShuttleStatus(AliShuttleStatus::kStarted, increaseCount);
1183 //______________________________________________________________________________________________
1184 void AliShuttle::SendMLRunInfo(const char* status)
1187 // Send information about this run to ML
1189 TMonaLisaText mlStatus("SHUTTLE_status", status);
1190 TString runType(fLogbookEntry->GetRunType());
1191 if (strlen(fLogbookEntry->GetRunParameter("log")) > 0){
1194 runType += fLogbookEntry->GetRunParameter("log");
1197 TMonaLisaText mlRunType("SHUTTLE_runtype", runType);
1200 mlList.Add(&mlStatus);
1201 mlList.Add(&mlRunType);
1204 mlID.Form("%d", GetCurrentRun());
1205 fMonaLisa->SendParameters(&mlList, mlID);
1208 //______________________________________________________________________________________________
1209 Bool_t AliShuttle::Process(AliShuttleLogbookEntry* entry)
1212 // Makes data retrieval for all detectors in the configuration.
1213 // entry: Shuttle logbook entry, contains run paramenters and status of detectors
1214 // (Unprocessed, Inactive, Failed or Done).
1215 // Returns kFALSE in case of error occured and kTRUE otherwise
1218 if (!entry) return kFALSE;
1220 fLogbookEntry = entry;
1222 Log("SHUTTLE", Form("\t\t\t^*^*^*^*^*^*^*^*^*^*^*^* run %d: START ^*^*^*^*^*^*^*^*^*^*^*^*",
1227 // Send the information to ML
1228 SendMLRunInfo("Processing");
1230 if (fLogbookEntry->IsDone())
1232 Log("SHUTTLE","Process - Shuttle is already DONE. Updating logbook");
1233 UpdateShuttleLogbook("shuttle_done");
1238 // read test mode if flag is set
1242 TString logEntry(entry->GetRunParameter("log"));
1243 //printf("log entry = %s\n", logEntry.Data());
1244 TString searchStr("Testmode: ");
1245 Int_t pos = logEntry.Index(searchStr.Data());
1246 //printf("%d\n", pos);
1249 TSubString subStr = logEntry(pos + searchStr.Length(), logEntry.Length());
1250 //printf("%s\n", subStr.String().Data());
1251 TString newStr(subStr.Data());
1252 TObjArray* token = newStr.Tokenize(' ');
1256 TObjString* tmpStr = dynamic_cast<TObjString*> (token->First());
1259 Int_t testMode = tmpStr->String().Atoi();
1262 Log("SHUTTLE", Form("Process - Enabling test mode %d", testMode));
1263 SetTestMode((TestMode) testMode);
1271 fLogbookEntry->Print("all");
1274 Bool_t hasError = kFALSE;
1276 // Set the CDB and Reference folders according to the year and LHC period
1277 TString lhcPeriod(GetLHCPeriod());
1278 if (lhcPeriod.Length() == 0)
1280 Log("SHUTTLE","Process - LHCPeriod not found in logbook!");
1284 // build cdb paths (repeat each time, LHCperiod might have changed)
1285 fgkMainCDB.Form("alien://folder=%s%d/%s/OCDB?user=alidaq?cacheFold=/tmp/OCDBCache",
1286 fConfig->GetAlienPath(), GetCurrentYear(), lhcPeriod.Data());
1288 fgkMainRefStorage.Form("alien://folder=%s%d/%s/Reference?user=alidaq?cacheFold=/tmp/OCDBCache",
1289 fConfig->GetAlienPath(), GetCurrentYear(), lhcPeriod.Data());
1291 // Loop on detectors in the configuration
1292 TIter iter(fConfig->GetDetectors());
1293 TObjString* aDetector = 0;
1295 Bool_t first = kTRUE;
1297 while ((aDetector = (TObjString*) iter.Next()))
1299 fCurrentDetector = aDetector->String();
1301 if (ContinueProcessing() == kFALSE)
1306 // only read QueryCDB when needed and only once
1307 AliCDBStorage *mainCDBSto = AliCDBManager::Instance()->GetStorage(fgkMainCDB);
1308 if(mainCDBSto) mainCDBSto->QueryCDB(GetCurrentRun());
1309 AliCDBStorage *mainRefSto = AliCDBManager::Instance()->GetStorage(fgkMainRefStorage);
1310 if(mainRefSto) mainRefSto->QueryCDB(GetCurrentRun());
1314 Log("SHUTTLE", Form("\t\t\t****** run %d - %s: START ******",
1315 GetCurrentRun(), aDetector->GetName()));
1317 for(Int_t iSys=0;iSys<3;iSys++) fFXSCalled[iSys]=kFALSE;
1319 Log(fCurrentDetector.Data(), "Process - Starting processing");
1325 Log("SHUTTLE", "Process - ERROR: Forking failed");
1330 Log("SHUTTLE", Form("Process - In parent process of %d - %s: Starting monitoring",
1331 GetCurrentRun(), aDetector->GetName()));
1333 Long_t begin = time(0);
1335 int status; // to be used with waitpid, on purpose an int (not Int_t)!
1336 while (waitpid(pid, &status, WNOHANG) == 0)
1338 Long_t expiredTime = time(0) - begin;
1340 if (expiredTime > fConfig->GetPPTimeOut())
1343 tmp.Form("Process - Process of %s time out. "
1344 "Run time: %d seconds. Killing...",
1345 fCurrentDetector.Data(), expiredTime);
1346 Log("SHUTTLE", tmp);
1347 Log(fCurrentDetector, tmp);
1351 UpdateShuttleStatus(AliShuttleStatus::kPPTimeOut);
1354 gSystem->Sleep(1000);
1358 gSystem->Sleep(1000);
1361 checkStr.Form("ps -o vsize --pid %d | tail -n 1", pid);
1362 FILE* pipe = gSystem->OpenPipe(checkStr, "r");
1365 Log("SHUTTLE", Form("Process - Error: "
1366 "Could not open pipe to %s", checkStr.Data()));
1371 if (!fgets(buffer, 100, pipe))
1373 Log("SHUTTLE", "Process - Error: ps did not return anything");
1374 gSystem->ClosePipe(pipe);
1377 gSystem->ClosePipe(pipe);
1379 //Log("SHUTTLE", Form("ps returned %s", buffer));
1382 if ((sscanf(buffer, "%d\n", &mem) != 1) || !mem)
1384 Log("SHUTTLE", "Process - Error: Could not parse output of ps");
1388 if (expiredTime % 60 == 0)
1390 Log("SHUTTLE", Form("Process - %s: Checking process. "
1391 "Run time: %d seconds - Memory consumption: %d KB",
1392 fCurrentDetector.Data(), expiredTime, mem));
1396 if (mem > fConfig->GetPPMaxMem())
1399 tmp.Form("Process - Process exceeds maximum allowed memory "
1400 "(%d KB > %d KB). Killing...",
1401 mem, fConfig->GetPPMaxMem());
1402 Log("SHUTTLE", tmp);
1403 Log(fCurrentDetector, tmp);
1407 UpdateShuttleStatus(AliShuttleStatus::kPPOutOfMemory);
1410 gSystem->Sleep(1000);
1415 Log("SHUTTLE", Form("Process - In parent process of %d - %s: Client has terminated.",
1416 GetCurrentRun(), aDetector->GetName()));
1418 if (WIFEXITED(status))
1420 Int_t returnCode = WEXITSTATUS(status);
1422 Log("SHUTTLE", Form("Process - %s: the return code is %d", fCurrentDetector.Data(),
1425 if (returnCode == 0) hasError = kTRUE;
1431 Log("SHUTTLE", Form("Process - In child process of %d - %s", GetCurrentRun(),
1432 aDetector->GetName()));
1434 Log("SHUTTLE", Form("Process - Redirecting output to %s log",fCurrentDetector.Data()));
1436 if ((freopen(GetLogFileName(fCurrentDetector), "a", stdout)) == 0)
1438 Log("SHUTTLE", "Process - Could not freopen stdout");
1442 fOutputRedirected = kTRUE;
1443 if ((dup2(fileno(stdout), fileno(stderr))) < 0)
1444 Log("SHUTTLE", "Process - Could not redirect stderr");
1448 TString wd = gSystem->WorkingDirectory();
1449 TString tmpDir = Form("%s/%s_%d_process", GetShuttleTempDir(),
1450 fCurrentDetector.Data(), GetCurrentRun());
1452 Int_t result = gSystem->GetPathInfo(tmpDir.Data(), 0, (Long64_t*) 0, 0, 0);
1453 if (!result) // temp dir already exists!
1455 Log(fCurrentDetector.Data(),
1456 Form("Process - %s dir already exists! Removing...", tmpDir.Data()));
1457 gSystem->Exec(Form("rm -rf %s",tmpDir.Data()));
1460 if (gSystem->mkdir(tmpDir.Data(), 1))
1462 Log(fCurrentDetector.Data(), "Process - could not make temp directory!!");
1466 if (!gSystem->ChangeDirectory(tmpDir.Data()))
1468 Log(fCurrentDetector.Data(), "Process - could not change directory!!");
1472 Int_t success = ProcessCurrentDetector();
1474 gSystem->ChangeDirectory(wd.Data());
1476 if (success == 1) // Preprocessor finished successfully!
1478 // remove temporary folder or DCS map
1479 if (!fConfig->KeepTempFolder())
1481 gSystem->Exec(Form("rm -rf %s",tmpDir.Data()));
1482 } else if (!fConfig->KeepDCSMap())
1484 gSystem->Exec(Form("rm -f %s/DCSMap.root",tmpDir.Data()));
1487 // Update time_processed field in FXS DB
1488 if (UpdateTable() == kFALSE)
1489 Log("SHUTTLE", Form("Process - %s: Could not update FXS databases!",
1490 fCurrentDetector.Data()));
1492 // Transfer the data from local storage to main storage (Grid)
1493 if (StoreOCDB() == kFALSE)
1496 else if (success == 0)
1499 Form("\t\t\t****** run %d - %s: PP ERROR ******",
1500 GetCurrentRun(), aDetector->GetName()));
1503 for (UInt_t iSys=0; iSys<3; iSys++)
1505 if (fFXSCalled[iSys]) fFXSlist[iSys].Clear();
1508 Log("SHUTTLE", Form("Process - Client process of %d - %s is exiting now with %d.",
1509 GetCurrentRun(), aDetector->GetName(), success));
1511 // the client exits here
1512 gSystem->Exit(success);
1514 AliError("We should never get here!!!");
1518 Log("SHUTTLE", Form("\t\t\t^*^*^*^*^*^*^*^*^*^*^*^* run %d: FINISH ^*^*^*^*^*^*^*^*^*^*^*^*",
1521 //check if shuttle is done for this run, if so update logbook
1522 TObjArray checkEntryArray;
1523 checkEntryArray.SetOwner(1);
1524 TString whereClause = Form("where run=%d", GetCurrentRun());
1525 if (!QueryShuttleLogbook(whereClause.Data(), checkEntryArray) ||
1526 checkEntryArray.GetEntries() == 0) {
1527 Log("SHUTTLE", Form("Process - Warning: Cannot check status of run %d on Shuttle logbook!",
1529 return hasError == kFALSE;
1532 AliShuttleLogbookEntry* checkEntry = dynamic_cast<AliShuttleLogbookEntry*>
1533 (checkEntryArray.At(0));
1537 if (checkEntry->IsDone())
1539 Log("SHUTTLE","Process - Shuttle is DONE. Updating logbook");
1540 UpdateShuttleLogbook("shuttle_done");
1544 for (UInt_t iDet=0; iDet<NDetectors(); iDet++)
1546 if (checkEntry->GetDetectorStatus(iDet) == AliShuttleLogbookEntry::kUnprocessed)
1548 AliDebug(2, Form("Run %d: setting %s as \"not first time unprocessed\"",
1549 checkEntry->GetRun(), GetDetName(iDet)));
1550 fFirstUnprocessed[iDet] = kFALSE;
1553 SendMLRunInfo("Pending");
1559 return hasError == kFALSE;
1562 //______________________________________________________________________________________________
1563 Int_t AliShuttle::ProcessCurrentDetector()
1566 // Makes data retrieval just for a specific detector (fCurrentDetector).
1567 // Threre should be a configuration for this detector.
1569 Log("SHUTTLE", Form("ProcessCurrentDetector - Retrieving values for %s, run %d",
1570 fCurrentDetector.Data(), GetCurrentRun()));
1572 TString wd = gSystem->WorkingDirectory();
1574 if (!CleanReferenceStorage(fCurrentDetector.Data()))
1577 gSystem->ChangeDirectory(wd.Data());
1579 // call preprocessor
1580 AliPreprocessor* aPreprocessor =
1581 dynamic_cast<AliPreprocessor*> (fPreprocessorMap.GetValue(fCurrentDetector));
1583 // check if the preprocessor wants to process this run type
1584 if (aPreprocessor->ProcessRunType() == kFALSE)
1586 UpdateShuttleStatus(AliShuttleStatus::kSkipped);
1587 UpdateShuttleLogbook(fCurrentDetector, "DONE");
1588 Log(fCurrentDetector, Form("ProcessCurrentDetector - %s preprocessor is not interested in this run type", fCurrentDetector.Data()));
1593 TMap* dcsMap = new TMap();
1595 aPreprocessor->Initialize(GetCurrentRun(), GetCurrentStartTime(), GetCurrentEndTime());
1597 Bool_t processDCS = aPreprocessor->ProcessDCS();
1601 Log(fCurrentDetector, "ProcessCurrentDetector -"
1602 " The preprocessor requested to skip the retrieval of DCS values");
1604 else if (fTestMode & kSkipDCS)
1606 Log(fCurrentDetector, "ProcessCurrentDetector - In TESTMODE: Skipping DCS processing");
1608 else if (fTestMode & kErrorDCS)
1610 Log(fCurrentDetector, "ProcessCurrentDetector - In TESTMODE: Simulating DCS error");
1611 UpdateShuttleStatus(AliShuttleStatus::kDCSStarted);
1612 UpdateShuttleStatus(AliShuttleStatus::kDCSError);
1617 UpdateShuttleStatus(AliShuttleStatus::kDCSStarted);
1619 // Query DCS archive
1620 Int_t nServers = fConfig->GetNServers(fCurrentDetector);
1622 for (int iServ=0; iServ<nServers; iServ++)
1625 TString host(fConfig->GetDCSHost(fCurrentDetector, iServ));
1626 Int_t port = fConfig->GetDCSPort(fCurrentDetector, iServ);
1627 Int_t multiSplit = fConfig->GetMultiSplit(fCurrentDetector, iServ);
1629 Log(fCurrentDetector, Form("ProcessCurrentDetector -"
1630 " Querying DCS Amanda server %s:%d (%d of %d)",
1631 host.Data(), port, iServ+1, nServers));
1636 if (fConfig->GetDCSAliases(fCurrentDetector, iServ)->GetEntries() > 0)
1638 aliasMap = GetValueSet(host, port,
1639 fConfig->GetDCSAliases(fCurrentDetector, iServ),
1640 kAlias, multiSplit);
1643 Log(fCurrentDetector,
1644 Form("ProcessCurrentDetector -"
1645 " Error retrieving DCS aliases from server %s."
1646 " Sending mail to DCS experts!", host.Data()));
1647 UpdateShuttleStatus(AliShuttleStatus::kDCSError);
1649 if (!SendMail(kDCSEMail))
1650 Log("SHUTTLE", Form("ProcessCurrentDetector - "
1651 "Could not send mail to DCS experts!"));
1658 if (fConfig->GetDCSDataPoints(fCurrentDetector, iServ)->GetEntries() > 0)
1660 dpMap = GetValueSet(host, port,
1661 fConfig->GetDCSDataPoints(fCurrentDetector, iServ),
1665 Log(fCurrentDetector,
1666 Form("ProcessCurrentDetector -"
1667 " Error retrieving DCS data points from server %s."
1668 " Sending mail to DCS experts!", host.Data()));
1669 UpdateShuttleStatus(AliShuttleStatus::kDCSError);
1671 if (!SendMail(kDCSEMail))
1672 Log("SHUTTLE", Form("ProcessCurrentDetector - "
1673 "Could not send mail to DCS experts!"));
1675 if (aliasMap) delete aliasMap;
1681 // merge aliasMap and dpMap into dcsMap
1683 TIter iter(aliasMap);
1684 TObjString* key = 0;
1685 while ((key = (TObjString*) iter.Next()))
1686 dcsMap->Add(key, aliasMap->GetValue(key->String()));
1688 aliasMap->SetOwner(kFALSE);
1694 TObjString* key = 0;
1695 while ((key = (TObjString*) iter.Next()))
1696 dcsMap->Add(key, dpMap->GetValue(key->String()));
1698 dpMap->SetOwner(kFALSE);
1704 // save map into file, to help debugging in case of preprocessor error
1705 TFile* f = TFile::Open("DCSMap.root","recreate");
1707 dcsMap->Write("DCSMap", TObject::kSingleKey);
1711 // DCS Archive DB processing successful. Call Preprocessor!
1712 UpdateShuttleStatus(AliShuttleStatus::kPPStarted);
1714 fFXSError = -1; // this variable is kTRUE after ::Process if an FXS error occured
1716 UInt_t returnValue = aPreprocessor->Process(dcsMap);
1718 if (fFXSError!=-1) {
1719 UpdateShuttleStatus(AliShuttleStatus::kFXSError);
1720 SendMail(kFXSEMail, fFXSError);
1721 dcsMap->DeleteAll();
1726 if (returnValue > 0) // Preprocessor error!
1728 Log(fCurrentDetector, Form("ProcessCurrentDetector - "
1729 "Preprocessor failed. Process returned %d.", returnValue));
1730 UpdateShuttleStatus(AliShuttleStatus::kPPError);
1731 dcsMap->DeleteAll();
1737 UpdateShuttleStatus(AliShuttleStatus::kPPDone);
1738 Log(fCurrentDetector, Form("ProcessCurrentDetector - %s preprocessor returned success",
1739 fCurrentDetector.Data()));
1741 dcsMap->DeleteAll();
1747 //______________________________________________________________________________________________
1748 void AliShuttle::CountOpenRuns()
1750 // Query DAQ's Shuttle logbook and sends the number of open runs to ML
1752 // check connection, in case connect
1757 sqlQuery = Form("select count(*) from %s where shuttle_done=0", fConfig->GetShuttlelbTable());
1759 TSQLResult* aResult = fServer[3]->Query(sqlQuery);
1761 AliError(Form("Can't execute query <%s>!", sqlQuery.Data()));
1765 AliDebug(2,Form("Query = %s", sqlQuery.Data()));
1767 if (aResult->GetRowCount() == 0) {
1768 AliError(Form("No result for query %s received", sqlQuery.Data()));
1772 if (aResult->GetFieldCount() != 1) {
1773 AliError(Form("Invalid field count for query %s received", sqlQuery.Data()));
1777 TSQLRow* aRow = aResult->Next();
1779 AliError(Form("Could not receive result of query %s", sqlQuery.Data()));
1783 TString result(aRow->GetField(0), aRow->GetFieldLength(0));
1784 Int_t count = result.Atoi();
1786 Log("SHUTTLE", Form("%d unprocessed runs", count));
1791 TMonaLisaValue mlStatus("SHUTTLE_openruns", count);
1794 mlList.Add(&mlStatus);
1796 fMonaLisa->SendParameters(&mlList, "__PROCESSINGINFO__");
1799 //______________________________________________________________________________________________
1800 Bool_t AliShuttle::QueryShuttleLogbook(const char* whereClause,
1803 // Query DAQ's Shuttle logbook and fills detector status object.
1804 // Call QueryRunParameters to query DAQ logbook for run parameters.
1807 entries.SetOwner(1);
1809 // check connection, in case connect
1810 if (!Connect(3)) return kFALSE;
1813 sqlQuery = Form("select * from %s %s order by run", fConfig->GetShuttlelbTable(), whereClause);
1815 TSQLResult* aResult = fServer[3]->Query(sqlQuery);
1817 AliError(Form("Can't execute query <%s>!", sqlQuery.Data()));
1821 AliDebug(2,Form("Query = %s", sqlQuery.Data()));
1823 if(aResult->GetRowCount() == 0) {
1824 Log("SHUTTLE", "No entries in Shuttle Logbook match request");
1829 // TODO Check field count!
1830 const UInt_t nCols = 23;
1831 if (aResult->GetFieldCount() != (Int_t) nCols) {
1832 Log("SHUTTLE", "Invalid SQL result field number!");
1838 while ((aRow = aResult->Next())) {
1839 TString runString(aRow->GetField(0), aRow->GetFieldLength(0));
1840 Int_t run = runString.Atoi();
1842 AliShuttleLogbookEntry *entry = QueryRunParameters(run);
1846 // loop on detectors
1847 for(UInt_t ii = 0; ii < nCols; ii++)
1848 entry->SetDetectorStatus(aResult->GetFieldName(ii), aRow->GetField(ii));
1850 entries.AddLast(entry);
1858 //______________________________________________________________________________________________
1859 AliShuttleLogbookEntry* AliShuttle::QueryRunParameters(Int_t run)
1862 // Retrieve run parameters written in the DAQ logbook and sets them into AliShuttleLogbookEntry object
1865 // check connection, in case connect
1870 sqlQuery.Form("select * from %s where run=%d", fConfig->GetDAQlbTable(), run);
1872 TSQLResult* aResult = fServer[3]->Query(sqlQuery);
1874 Log("SHUTTLE", Form("Can't execute query <%s>!", sqlQuery.Data()));
1878 if (aResult->GetRowCount() == 0) {
1879 Log("SHUTTLE", Form("QueryRunParameters - No entry in DAQ Logbook for run %d. Skipping", run));
1884 if (aResult->GetRowCount() > 1) {
1885 Log("SHUTTLE", Form("QueryRunParameters - UNEXPECTED: "
1886 "more than one entry in DAQ Logbook for run %d!", run));
1891 TSQLRow* aRow = aResult->Next();
1894 Log("SHUTTLE", Form("QueryRunParameters - Could not retrieve row for run %d. Skipping", run));
1899 AliShuttleLogbookEntry* entry = new AliShuttleLogbookEntry(run);
1901 for (Int_t ii = 0; ii < aResult->GetFieldCount(); ii++)
1902 entry->SetRunParameter(aResult->GetFieldName(ii), aRow->GetField(ii));
1907 UInt_t startTime = entry->GetStartTime();
1908 UInt_t endTime = entry->GetEndTime();
1909 Bool_t ecsSuccess = entry->GetECSSuccess();
1911 TString totEventsStr = entry->GetRunParameter("totalEvents");
1912 Int_t totEvents = totEventsStr.Atoi();
1914 // runs are accepted if they have ecsSuccess set or more than 1 event
1915 if (startTime != 0 && endTime != 0 && endTime > startTime && (totEvents > 1 || ecsSuccess))
1917 if (ecsSuccess == kFALSE)
1918 Log("SHUTTLE", Form("Processing run %d although in status ECS failure, Reason: %s", run, entry->GetRunParameter("eor_reason")));
1922 Bool_t skip = kFALSE;
1926 Log("SHUTTLE", Form("QueryRunParameters - Run %d has 1 event or less - Skipping!", run));
1931 Log("SHUTTLE", Form("QueryRunParameters - Invalid parameters for Run %d: "
1932 "startTime = %d, endTime = %d. Skipping (Shuttle won't be marked as DONE)!",
1933 run, startTime, endTime));
1938 Log("SHUTTLE", Form("Marking SHUTTLE skipped for run %d", run));
1939 fLogbookEntry = entry;
1940 if (!UpdateShuttleLogbook("shuttle_skipped"))
1942 AliError(Form("Could not update logbook for run %d !", run));
1951 //______________________________________________________________________________________________
1952 TMap* AliShuttle::GetValueSet(const char* host, Int_t port, const TSeqCollection* entries,
1953 DCSType type, Int_t multiSplit)
1955 // Retrieve all "entry" data points from the DCS server
1956 // host, port: TSocket connection parameters
1957 // entries: list of name of the alias or data point
1958 // type: kAlias or kDP
1959 // returns TMap of values, 0 when failure
1961 AliDCSClient client(host, port, fTimeout, fRetries, multiSplit);
1966 result = client.GetAliasValues(entries, GetCurrentStartTime(),
1967 GetCurrentEndTime());
1969 else if (type == kDP)
1971 result = client.GetDPValues(entries, GetCurrentStartTime(),
1972 GetCurrentEndTime());
1977 Log(fCurrentDetector.Data(), Form("GetValueSet - Can't get entries! Reason: %s",
1978 client.GetErrorString(client.GetResultErrorCode())));
1979 if (client.GetResultErrorCode() == AliDCSClient::fgkServerError)
1980 Log(fCurrentDetector.Data(), Form("GetValueSet - Server error code: %s",
1981 client.GetServerError().Data()));
1989 //______________________________________________________________________________________________
1990 const char* AliShuttle::GetFile(Int_t system, const char* detector,
1991 const char* id, const char* source)
1993 // Get calibration file from file exchange servers
1994 // First queris the FXS database for the file name, using the run, detector, id and source info
1995 // then calls RetrieveFile(filename) for actual copy to local disk
1996 // run: current run being processed (given by Logbook entry fLogbookEntry)
1997 // detector: the Preprocessor name
1998 // id: provided as a parameter by the Preprocessor
1999 // source: provided by the Preprocessor through GetFileSources function
2001 // check if test mode should simulate a FXS error
2002 if (fTestMode & kErrorFXSFiles)
2004 Log(detector, Form("GetFile - In TESTMODE - Simulating error while connecting to %s FXS", GetSystemName(system)));
2008 // check connection, in case connect
2009 if (!Connect(system))
2011 Log(detector, Form("GetFile - Couldn't connect to %s FXS database", GetSystemName(system)));
2016 // Query preparation
2017 TString sourceName(source);
2019 TString sqlQueryStart = Form("select filePath,size,fileChecksum from %s where",
2020 fConfig->GetFXSdbTable(system));
2021 TString whereClause = Form("run=%d and detector=\"%s\" and fileId=\"%s\"",
2022 GetCurrentRun(), detector, id);
2026 whereClause += Form(" and DAQsource=\"%s\"", source);
2028 else if (system == kDCS)
2032 else if (system == kHLT)
2034 whereClause += Form(" and DDLnumbers=\"%s\"", source);
2037 TString sqlQuery = Form("%s %s", sqlQueryStart.Data(), whereClause.Data());
2039 AliDebug(2, Form("SQL query: \n%s",sqlQuery.Data()));
2042 TSQLResult* aResult = 0;
2043 aResult = dynamic_cast<TSQLResult*> (fServer[system]->Query(sqlQuery));
2045 Log(detector, Form("GetFile - Can't execute SQL query to %s database for: id = %s, source = %s",
2046 GetSystemName(system), id, sourceName.Data()));
2051 if (aResult->GetRowCount() == 0)
2054 Form("GetFile - No entry in %s FXS db for: id = %s, source = %s",
2055 GetSystemName(system), id, sourceName.Data()));
2060 if (aResult->GetRowCount() > 1) {
2062 Form("GetFile - More than one entry in %s FXS db for: id = %s, source = %s",
2063 GetSystemName(system), id, sourceName.Data()));
2069 if (aResult->GetFieldCount() != nFields) {
2071 Form("GetFileName - Wrong field count in %s FXS db for: id = %s, source = %s",
2072 GetSystemName(system), id, sourceName.Data()));
2078 TSQLRow* aRow = dynamic_cast<TSQLRow*> (aResult->Next());
2081 Log(detector, Form("GetFile - Empty set result in %s FXS db from query: id = %s, source = %s",
2082 GetSystemName(system), id, sourceName.Data()));
2088 TString filePath(aRow->GetField(0), aRow->GetFieldLength(0));
2089 TString fileSize(aRow->GetField(1), aRow->GetFieldLength(1));
2090 TString fileChecksum(aRow->GetField(2), aRow->GetFieldLength(2));
2095 AliDebug(2, Form("filePath = %s; size = %s, fileChecksum = %s",
2096 filePath.Data(), fileSize.Data(), fileChecksum.Data()));
2098 // retrieved file is renamed to make it unique
2099 TString localFileName = Form("%s/%s_%d_process/%s_%s_%d_%s_%s.shuttle",
2100 GetShuttleTempDir(), detector, GetCurrentRun(),
2101 GetSystemName(system), detector, GetCurrentRun(),
2102 id, sourceName.Data());
2105 // file retrieval from FXS
2106 UInt_t nRetries = 0;
2107 UInt_t maxRetries = 3;
2108 Bool_t result = kFALSE;
2110 // copy!! if successful TSystem::Exec returns 0
2111 while (nRetries++ < maxRetries) {
2112 AliDebug(2, Form("Trying to copy file. Retry # %d", nRetries));
2113 result = RetrieveFile(system, filePath.Data(), localFileName.Data());
2116 Log(detector, Form("GetFile - Copy of file %s from %s FXS failed",
2117 filePath.Data(), GetSystemName(system)));
2121 if (fileSize.Length()>0)
2123 // compare filesize of local file with the one stored in the FXS DB
2125 Int_t sizeComp = gSystem->GetPathInfo(localFileName.Data(), 0, &size, 0, 0);
2127 if (sizeComp != 0 || size != fileSize.Atoi())
2129 Log(detector, Form("GetFile - size of file %s does not match with local copy!",
2136 Log(fCurrentDetector, Form("GetFile - size of file %s not set in %s database, skipping comparison",
2137 filePath.Data(), GetSystemName(system)));
2140 if (fileChecksum.Length()>0)
2142 // compare md5sum of local file with the one stored in the FXS DB
2143 if(fileChecksum.Contains(' ')) fileChecksum.Resize(fileChecksum.First(' '));
2144 Int_t md5Comp = gSystem->Exec(Form("md5sum %s |grep %s > /dev/null 2> /dev/null",
2145 localFileName.Data(), fileChecksum.Data()));
2149 Log(detector, Form("GetFile - md5sum of file %s does not match with local copy!",
2155 Log(fCurrentDetector, Form("GetFile - md5sum of file %s not set in %s database, skipping comparison",
2156 filePath.Data(), GetSystemName(system)));
2167 fFXSCalled[system]=kTRUE;
2168 TObjString *fileParams = new TObjString(Form("%s#!?!#%s", id, sourceName.Data()));
2169 fFXSlist[system].Add(fileParams);
2171 static TString staticLocalFileName;
2172 staticLocalFileName.Form("%s", localFileName.Data());
2174 Log(fCurrentDetector, Form("GetFile - Retrieved file with id %s and "
2175 "source %s from %s to %s", id, source,
2176 GetSystemName(system), localFileName.Data()));
2178 return staticLocalFileName.Data();
2181 //______________________________________________________________________________________________
2182 Bool_t AliShuttle::RetrieveFile(UInt_t system, const char* fxsFileName, const char* localFileName)
2185 // Copies file from FXS to local Shuttle machine
2188 // check temp directory: trying to cd to temp; if it does not exist, create it
2189 AliDebug(2, Form("Copy file %s from %s FXS into %s",
2190 GetSystemName(system), fxsFileName, localFileName));
2192 TString tmpDir(localFileName);
2194 tmpDir = tmpDir(0,tmpDir.Last('/'));
2196 Int_t noDir = gSystem->GetPathInfo(tmpDir.Data(), 0, (Long64_t*) 0, 0, 0);
2197 if (noDir) // temp dir does not exists!
2199 if (gSystem->mkdir(tmpDir.Data(), 1))
2201 Log(fCurrentDetector.Data(), "RetrieveFile - could not make temp directory!!");
2206 TString command = Form("scp -oPort=%d -2 %s@%s:%s/%s %s",
2207 fConfig->GetFXSPort(system),
2208 fConfig->GetFXSUser(system),
2209 fConfig->GetFXSHost(system),
2210 fConfig->GetFXSBaseFolder(system),
2214 AliDebug(2, Form("%s",command.Data()));
2216 Bool_t result = (gSystem->Exec(command.Data()) == 0);
2221 //______________________________________________________________________________________________
2222 TList* AliShuttle::GetFileSources(Int_t system, const char* detector, const char* id)
2225 // Get sources producing the condition file Id from file exchange servers
2226 // if id is NULL all sources are returned (distinct)
2231 Log(detector, Form("GetFileSources - Querying %s FXS for files with id %s produced by %s", GetSystemName(system), id, detector));
2233 Log(detector, Form("GetFileSources - Querying %s FXS for files produced by %s", GetSystemName(system), detector));
2236 // check if test mode should simulate a FXS error
2237 if (fTestMode & kErrorFXSSources)
2239 Log(detector, Form("GetFileSources - In TESTMODE - Simulating error while connecting to %s FXS", GetSystemName(system)));
2245 Log(detector, "GetFileSources - WARNING: DCS system has only one source of data!");
2246 TList *list = new TList();
2248 list->Add(new TObjString(" "));
2252 // check connection, in case connect
2253 if (!Connect(system))
2255 Log(detector, Form("GetFileSources - Couldn't connect to %s FXS database", GetSystemName(system)));
2260 TString sourceName = 0;
2263 sourceName = "DAQsource";
2264 } else if (system == kHLT)
2266 sourceName = "DDLnumbers";
2269 TString sqlQueryStart = Form("select distinct %s from %s where", sourceName.Data(), fConfig->GetFXSdbTable(system));
2270 TString whereClause = Form("run=%d and detector=\"%s\"",
2271 GetCurrentRun(), detector);
2273 whereClause += Form(" and fileId=\"%s\"", id);
2274 TString sqlQuery = Form("%s %s", sqlQueryStart.Data(), whereClause.Data());
2276 AliDebug(2, Form("SQL query: \n%s",sqlQuery.Data()));
2279 TSQLResult* aResult;
2280 aResult = fServer[system]->Query(sqlQuery);
2282 Log(detector, Form("GetFileSources - Can't execute SQL query to %s database for id: %s",
2283 GetSystemName(system), id));
2288 TList *list = new TList();
2291 if (aResult->GetRowCount() == 0)
2294 Form("GetFileSources - No entry in %s FXS table for id: %s", GetSystemName(system), id));
2299 Log(detector, Form("GetFileSources - Found %d sources", aResult->GetRowCount()));
2302 while ((aRow = aResult->Next()))
2305 TString source(aRow->GetField(0), aRow->GetFieldLength(0));
2306 AliDebug(2, Form("%s = %s", sourceName.Data(), source.Data()));
2307 list->Add(new TObjString(source));
2316 //______________________________________________________________________________________________
2317 TList* AliShuttle::GetFileIDs(Int_t system, const char* detector, const char* source)
2320 // Get all ids of condition files produced by a given source from file exchange servers
2323 Log(detector, Form("GetFileIDs - Retrieving ids with source %s with %s", source, GetSystemName(system)));
2325 // check if test mode should simulate a FXS error
2326 if (fTestMode & kErrorFXSSources)
2328 Log(detector, Form("GetFileIDs - In TESTMODE - Simulating error while connecting to %s FXS", GetSystemName(system)));
2332 // check connection, in case connect
2333 if (!Connect(system))
2335 Log(detector, Form("GetFileIDs - Couldn't connect to %s FXS database", GetSystemName(system)));
2339 TString sourceName = 0;
2342 sourceName = "DAQsource";
2343 } else if (system == kHLT)
2345 sourceName = "DDLnumbers";
2348 TString sqlQueryStart = Form("select fileId from %s where", fConfig->GetFXSdbTable(system));
2349 TString whereClause = Form("run=%d and detector=\"%s\"",
2350 GetCurrentRun(), detector);
2351 if (sourceName.Length() > 0 && source)
2352 whereClause += Form(" and %s=\"%s\"", sourceName.Data(), source);
2353 TString sqlQuery = Form("%s %s", sqlQueryStart.Data(), whereClause.Data());
2355 AliDebug(2, Form("SQL query: \n%s",sqlQuery.Data()));
2358 TSQLResult* aResult;
2359 aResult = fServer[system]->Query(sqlQuery);
2361 Log(detector, Form("GetFileIDs - Can't execute SQL query to %s database for source: %s",
2362 GetSystemName(system), source));
2366 TList *list = new TList();
2369 if (aResult->GetRowCount() == 0)
2372 Form("GetFileIDs - No entry in %s FXS table for source: %s", GetSystemName(system), source));
2377 Log(detector, Form("GetFileIDs - Found %d ids", aResult->GetRowCount()));
2381 while ((aRow = aResult->Next()))
2384 TString id(aRow->GetField(0), aRow->GetFieldLength(0));
2385 AliDebug(2, Form("fileId = %s", id.Data()));
2386 list->Add(new TObjString(id));
2395 //______________________________________________________________________________________________
2396 Bool_t AliShuttle::Connect(Int_t system)
2398 // Connect to MySQL Server of the system's FXS MySQL databases
2399 // DAQ Logbook, Shuttle Logbook and DAQ FXS db are on the same host
2402 // check connection: if already connected return
2403 if(fServer[system] && fServer[system]->IsConnected()) return kTRUE;
2405 TString dbHost, dbUser, dbPass, dbName;
2407 if (system < 3) // FXS db servers
2409 dbHost = Form("mysql://%s:%d", fConfig->GetFXSdbHost(system), fConfig->GetFXSdbPort(system));
2410 dbUser = fConfig->GetFXSdbUser(system);
2411 dbPass = fConfig->GetFXSdbPass(system);
2412 dbName = fConfig->GetFXSdbName(system);
2413 } else { // Run & Shuttle logbook servers
2414 // TODO Will the Shuttle logbook server be the same as the Run logbook server ???
2415 dbHost = Form("mysql://%s:%d", fConfig->GetDAQlbHost(), fConfig->GetDAQlbPort());
2416 dbUser = fConfig->GetDAQlbUser();
2417 dbPass = fConfig->GetDAQlbPass();
2418 dbName = fConfig->GetDAQlbDB();
2421 fServer[system] = TSQLServer::Connect(dbHost.Data(), dbUser.Data(), dbPass.Data());
2422 if (!fServer[system] || !fServer[system]->IsConnected()) {
2425 AliError(Form("Can't establish connection to FXS database for %s",
2426 AliShuttleInterface::GetSystemName(system)));
2428 AliError("Can't establish connection to Run logbook.");
2430 if(fServer[system]) delete fServer[system];
2435 TSQLResult* aResult=0;
2438 aResult = fServer[kDAQ]->GetTables(dbName.Data());
2441 aResult = fServer[kDCS]->GetTables(dbName.Data());
2444 aResult = fServer[kHLT]->GetTables(dbName.Data());
2447 aResult = fServer[3]->GetTables(dbName.Data());
2455 //______________________________________________________________________________________________
2456 Bool_t AliShuttle::UpdateTable()
2459 // Update FXS table filling time_processed field in all rows corresponding to current run and detector
2462 Bool_t result = kTRUE;
2464 for (UInt_t system=0; system<3; system++)
2466 if(!fFXSCalled[system]) continue;
2468 // check connection, in case connect
2469 if (!Connect(system))
2471 Log(fCurrentDetector, Form("UpdateTable - Couldn't connect to %s FXS database", GetSystemName(system)));
2476 TTimeStamp now; // now
2478 // Loop on FXS list entries
2479 TIter iter(&fFXSlist[system]);
2480 TObjString *aFXSentry=0;
2481 while ((aFXSentry = dynamic_cast<TObjString*> (iter.Next())))
2483 TString aFXSentrystr = aFXSentry->String();
2484 TObjArray *aFXSarray = aFXSentrystr.Tokenize("#!?!#");
2485 if (!aFXSarray || aFXSarray->GetEntries() != 2 )
2487 Log(fCurrentDetector, Form("UpdateTable - error updating %s FXS entry. Check string: <%s>",
2488 GetSystemName(system), aFXSentrystr.Data()));
2489 if(aFXSarray) delete aFXSarray;
2493 const char* fileId = ((TObjString*) aFXSarray->At(0))->GetName();
2494 const char* source = ((TObjString*) aFXSarray->At(1))->GetName();
2496 TString whereClause;
2499 whereClause = Form("where run=%d and detector=\"%s\" and fileId=\"%s\" and DAQsource=\"%s\";",
2500 GetCurrentRun(), fCurrentDetector.Data(), fileId, source);
2502 else if (system == kDCS)
2504 whereClause = Form("where run=%d and detector=\"%s\" and fileId=\"%s\";",
2505 GetCurrentRun(), fCurrentDetector.Data(), fileId);
2507 else if (system == kHLT)
2509 whereClause = Form("where run=%d and detector=\"%s\" and fileId=\"%s\" and DDLnumbers=\"%s\";",
2510 GetCurrentRun(), fCurrentDetector.Data(), fileId, source);
2515 TString sqlQuery = Form("update %s set time_processed=%d %s", fConfig->GetFXSdbTable(system),
2516 now.GetSec(), whereClause.Data());
2518 AliDebug(2, Form("SQL query: \n%s",sqlQuery.Data()));
2521 TSQLResult* aResult;
2522 aResult = dynamic_cast<TSQLResult*> (fServer[system]->Query(sqlQuery));
2525 Log(fCurrentDetector, Form("UpdateTable - %s db: can't execute SQL query <%s>",
2526 GetSystemName(system), sqlQuery.Data()));
2537 //______________________________________________________________________________________________
2538 Bool_t AliShuttle::UpdateTableFailCase()
2540 // Update FXS table filling time_processed field in all rows corresponding to current run and detector
2541 // this is called in case the preprocessor is declared failed for the current run, because
2542 // the fields are updated only in case of success
2544 Bool_t result = kTRUE;
2546 for (UInt_t system=0; system<3; system++)
2548 // check connection, in case connect
2549 if (!Connect(system))
2551 Log(fCurrentDetector, Form("UpdateTableFailCase - Couldn't connect to %s FXS database",
2552 GetSystemName(system)));
2557 TTimeStamp now; // now
2559 // Loop on FXS list entries
2561 TString whereClause = Form("where run=%d and detector=\"%s\";",
2562 GetCurrentRun(), fCurrentDetector.Data());
2565 TString sqlQuery = Form("update %s set time_processed=%d %s", fConfig->GetFXSdbTable(system),
2566 now.GetSec(), whereClause.Data());
2568 AliDebug(2, Form("SQL query: \n%s",sqlQuery.Data()));
2571 TSQLResult* aResult;
2572 aResult = dynamic_cast<TSQLResult*> (fServer[system]->Query(sqlQuery));
2575 Log(fCurrentDetector, Form("UpdateTableFailCase - %s db: can't execute SQL query <%s>",
2576 GetSystemName(system), sqlQuery.Data()));
2586 //______________________________________________________________________________________________
2587 Bool_t AliShuttle::UpdateShuttleLogbook(const char* detector, const char* status)
2590 // Update Shuttle logbook filling detector or shuttle_done column
2591 // ex. of usage: UpdateShuttleLogbook("PHOS", "DONE") or UpdateShuttleLogbook("shuttle_done")
2594 // check connection, in case connect
2596 Log("SHUTTLE", "UpdateShuttleLogbook - Couldn't connect to DAQ Logbook.");
2600 TString detName(detector);
2602 if (detName == "shuttle_done" || detName == "shuttle_skipped")
2604 setClause = "set shuttle_done=1";
2606 if (detName == "shuttle_done")
2608 if (TouchFile() != kTRUE)
2611 SendMLRunInfo("Done");
2614 SendMLRunInfo("Skipped");
2617 TString statusStr(status);
2618 if(statusStr.Contains("done", TString::kIgnoreCase) ||
2619 statusStr.Contains("failed", TString::kIgnoreCase)){
2620 setClause = Form("set %s=\"%s\"", detector, status);
2623 Form("UpdateShuttleLogbook - Invalid status <%s> for detector %s",
2629 TString whereClause = Form("where run=%d", GetCurrentRun());
2631 TString sqlQuery = Form("update %s %s %s",
2632 fConfig->GetShuttlelbTable(), setClause.Data(), whereClause.Data());
2634 AliDebug(2, Form("SQL query: \n%s",sqlQuery.Data()));
2637 TSQLResult* aResult;
2638 aResult = dynamic_cast<TSQLResult*> (fServer[3]->Query(sqlQuery));
2640 Log("SHUTTLE", Form("UpdateShuttleLogbook - Can't execute query <%s>", sqlQuery.Data()));
2648 //______________________________________________________________________________________________
2649 Int_t AliShuttle::GetCurrentRun() const
2652 // Get current run from logbook entry
2655 return fLogbookEntry ? fLogbookEntry->GetRun() : -1;
2658 //______________________________________________________________________________________________
2659 UInt_t AliShuttle::GetCurrentStartTime() const
2662 // get current start time
2665 return fLogbookEntry ? fLogbookEntry->GetStartTime() : 0;
2668 //______________________________________________________________________________________________
2669 UInt_t AliShuttle::GetCurrentEndTime() const
2672 // get current end time from logbook entry
2675 return fLogbookEntry ? fLogbookEntry->GetEndTime() : 0;
2678 //______________________________________________________________________________________________
2679 UInt_t AliShuttle::GetCurrentYear() const
2682 // Get current year from logbook entry
2685 if (!fLogbookEntry) return 0;
2687 TTimeStamp startTime(GetCurrentStartTime());
2688 TString year = Form("%d",startTime.GetDate());
2694 //______________________________________________________________________________________________
2695 const char* AliShuttle::GetLHCPeriod() const
2698 // Get current LHC period from logbook entry
2701 if (!fLogbookEntry) return 0;
2703 return fLogbookEntry->GetRunParameter("LHCperiod");
2706 //______________________________________________________________________________________________
2707 void AliShuttle::Log(const char* detector, const char* message)
2710 // Fill log string with a message
2713 TString logRunDir = GetShuttleLogDir();
2714 if (GetCurrentRun() >=0)
2715 logRunDir += Form("/%d", GetCurrentRun());
2717 void* dir = gSystem->OpenDirectory(logRunDir.Data());
2719 if (gSystem->mkdir(logRunDir.Data(), kTRUE)) {
2720 AliError(Form("Can't open directory <%s>", GetShuttleLogDir()));
2725 gSystem->FreeDirectory(dir);
2728 TString toLog = Form("%s UTC (%d): %s - ", TTimeStamp(time(0)).AsString("s"), getpid(), detector);
2729 if (GetCurrentRun() >= 0)
2730 toLog += Form("run %d - ", GetCurrentRun());
2731 toLog += Form("%s", message);
2733 AliInfo(toLog.Data());
2735 // if we redirect the log output already to the file, leave here
2736 if (fOutputRedirected && strcmp(detector, "SHUTTLE") != 0)
2739 TString fileName = GetLogFileName(detector);
2741 gSystem->ExpandPathName(fileName);
2744 logFile.open(fileName, ofstream::out | ofstream::app);
2746 if (!logFile.is_open()) {
2747 AliError(Form("Could not open file %s", fileName.Data()));
2751 logFile << toLog.Data() << "\n";
2756 //______________________________________________________________________________________________
2757 TString AliShuttle::GetLogFileName(const char* detector) const
2760 // returns the name of the log file for a given sub detector
2765 if (GetCurrentRun() >= 0)
2767 fileName.Form("%s/%d/%s_%d.log", GetShuttleLogDir(), GetCurrentRun(),
2768 detector, GetCurrentRun());
2770 fileName.Form("%s/%s.log", GetShuttleLogDir(), detector);
2776 //______________________________________________________________________________________________
2777 void AliShuttle::SendAlive()
2779 // sends alive message to ML
2781 TMonaLisaText mlStatus("SHUTTLE_status", "Alive");
2784 mlList.Add(&mlStatus);
2786 fMonaLisa->SendParameters(&mlList, "__PROCESSINGINFO__");
2789 //______________________________________________________________________________________________
2790 Bool_t AliShuttle::Collect(Int_t run)
2793 // Collects conditions data for all UNPROCESSED run written to DAQ LogBook in case of run = -1 (default)
2794 // If a dedicated run is given this run is processed
2796 // In operational mode, this is the Shuttle function triggered by the EOR signal.
2800 Log("SHUTTLE","Collect - Shuttle called. Collecting conditions data for unprocessed runs");
2802 Log("SHUTTLE", Form("Collect - Shuttle called. Collecting conditions data for run %d", run));
2804 SetLastAction("Starting");
2806 // create ML instance
2808 fMonaLisa = new TMonaLisaWriter(fConfig->GetMonitorHost(), fConfig->GetMonitorTable());
2813 TString whereClause("where shuttle_done=0");
2815 whereClause += Form(" and run=%d", run);
2817 TObjArray shuttleLogbookEntries;
2818 if (!QueryShuttleLogbook(whereClause, shuttleLogbookEntries))
2820 Log("SHUTTLE", "Collect - Can't retrieve entries from Shuttle logbook");
2824 if (shuttleLogbookEntries.GetEntries() == 0)
2827 Log("SHUTTLE","Collect - Found no UNPROCESSED runs in Shuttle logbook");
2829 Log("SHUTTLE", Form("Collect - Run %d is already DONE "
2830 "or it does not exist in Shuttle logbook", run));
2834 for (UInt_t iDet=0; iDet<NDetectors(); iDet++)
2835 fFirstUnprocessed[iDet] = kTRUE;
2839 // query Shuttle logbook for earlier runs, check if some detectors are unprocessed,
2840 // flag them into fFirstUnprocessed array
2841 TString whereClauseBis(Form("where shuttle_done=0 and run < %d", run));
2842 TObjArray tmpLogbookEntries;
2843 if (!QueryShuttleLogbook(whereClauseBis, tmpLogbookEntries))
2845 Log("SHUTTLE", "Collect - Can't retrieve entries from Shuttle logbook");
2849 TIter iter(&tmpLogbookEntries);
2850 AliShuttleLogbookEntry* anEntry = 0;
2851 while ((anEntry = dynamic_cast<AliShuttleLogbookEntry*> (iter.Next())))
2853 for (UInt_t iDet=0; iDet<NDetectors(); iDet++)
2855 if (anEntry->GetDetectorStatus(iDet) == AliShuttleLogbookEntry::kUnprocessed)
2857 AliDebug(2, Form("Run %d: setting %s as \"not first time unprocessed\"",
2858 anEntry->GetRun(), GetDetName(iDet)));
2859 fFirstUnprocessed[iDet] = kFALSE;
2867 if (!RetrieveConditionsData(shuttleLogbookEntries))
2869 Log("SHUTTLE", "Collect - Process of at least one run failed");
2874 Log("SHUTTLE", "Collect - Requested run(s) successfully processed");
2879 //______________________________________________________________________________________________
2880 Bool_t AliShuttle::RetrieveConditionsData(const TObjArray& dateEntries)
2883 // Retrieve conditions data for all runs that aren't processed yet
2886 Bool_t hasError = kFALSE;
2888 TIter iter(&dateEntries);
2889 AliShuttleLogbookEntry* anEntry;
2891 while ((anEntry = (AliShuttleLogbookEntry*) iter.Next())){
2892 if (!Process(anEntry)){
2896 // clean SHUTTLE temp directory
2897 //TString filename = Form("%s/*.shuttle", GetShuttleTempDir());
2898 //RemoveFile(filename.Data());
2901 return hasError == kFALSE;
2904 //______________________________________________________________________________________________
2905 ULong_t AliShuttle::GetTimeOfLastAction() const
2908 // Gets time of last action
2913 fMonitoringMutex->Lock();
2915 tmp = fLastActionTime;
2917 fMonitoringMutex->UnLock();
2922 //______________________________________________________________________________________________
2923 const TString AliShuttle::GetLastAction() const
2926 // returns a string description of the last action
2931 fMonitoringMutex->Lock();
2935 fMonitoringMutex->UnLock();
2940 //______________________________________________________________________________________________
2941 void AliShuttle::SetLastAction(const char* action)
2944 // updates the monitoring variables
2947 fMonitoringMutex->Lock();
2949 fLastAction = action;
2950 fLastActionTime = time(0);
2952 fMonitoringMutex->UnLock();
2955 //______________________________________________________________________________________________
2956 const char* AliShuttle::GetRunParameter(const char* param)
2959 // returns run parameter read from DAQ logbook
2962 if(!fLogbookEntry) {
2963 AliError("No logbook entry!");
2967 return fLogbookEntry->GetRunParameter(param);
2970 //______________________________________________________________________________________________
2971 AliCDBEntry* AliShuttle::GetFromOCDB(const char* detector, const AliCDBPath& path)
2974 // returns object from OCDB valid for current run
2977 if (fTestMode & kErrorOCDB)
2979 Log(detector, "GetFromOCDB - In TESTMODE - Simulating error with OCDB");
2983 AliCDBStorage *sto = AliCDBManager::Instance()->GetStorage(fgkMainCDB);
2986 Log(detector, "GetFromOCDB - Cannot activate main OCDB for query!");
2990 return dynamic_cast<AliCDBEntry*> (sto->Get(path, GetCurrentRun()));
2993 //______________________________________________________________________________________________
2994 Bool_t AliShuttle::SendMail(EMailTarget target, Int_t system)
2997 // sends a mail to the subdetector expert in case of preprocessor error
3000 if (fTestMode != kNone)
3003 if (!fConfig->SendMail())
3006 if (target == kDCSEMail || target == kFXSEMail) {
3007 if (!fFirstProcessing)
3011 Int_t runMode = (Int_t)fConfig->GetRunMode();
3013 if (runMode == 0) tmpStr = " Nightly Test:";
3014 else tmpStr = " Data Taking:";
3015 void* dir = gSystem->OpenDirectory(GetShuttleLogDir());
3018 if (gSystem->mkdir(GetShuttleLogDir(), kTRUE))
3020 Log("SHUTTLE", Form("SendMail - Can't open directory <%s>", GetShuttleLogDir()));
3025 gSystem->FreeDirectory(dir);
3028 // det experts in to
3030 TIter *iterExperts = 0;
3031 if (target == kDCSEMail) {
3032 iterExperts = new TIter(fConfig->GetAdmins(AliShuttleConfig::kAmanda));
3034 else if (target == kFXSEMail) {
3035 iterExperts = new TIter(fConfig->GetAdmins(system));
3038 TObjString *anExpert=0;
3039 while ((anExpert = (TObjString*) iterExperts->Next()))
3041 to += Form("%s,", anExpert->GetName());
3046 // add subdetector experts
3047 iterExperts = new TIter(fConfig->GetResponsibles(fCurrentDetector));
3048 TObjString *anExpert=0;
3049 while ((anExpert = (TObjString*) iterExperts->Next()))
3051 to += Form("%s,", anExpert->GetName());
3055 if (to.Length() > 0)
3056 to.Remove(to.Length()-1);
3057 AliDebug(2, Form("to: %s",to.Data()));
3060 Log("SHUTTLE", Form("List of %d responsibles not set!", (Int_t) target));
3064 // SHUTTLE responsibles in cc
3066 TIter iterAdmins(fConfig->GetAdmins(AliShuttleConfig::kGlobal));
3067 TObjString *anAdmin=0;
3068 while ((anAdmin = (TObjString*) iterAdmins.Next()))
3070 cc += Form("%s,", anAdmin->GetName());