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>
61 #include <TMonaLisaWriter.h>
65 #include <sys/types.h>
72 //______________________________________________________________________________________________
73 AliShuttle::AliShuttle(const AliShuttleConfig* config,
74 UInt_t timeout, Int_t retries):
76 fTimeout(timeout), fRetries(retries),
88 fReadTestMode(kFALSE),
89 fOutputRedirected(kFALSE)
92 // config: AliShuttleConfig used
93 // timeout: timeout used for AliDCSClient connection
94 // retries: the number of retries in case of connection error.
97 if (!fConfig->IsValid()) AliFatal("********** !!!!! Invalid configuration !!!!! **********");
98 for(int iSys=0;iSys<4;iSys++) {
101 fFXSlist[iSys].SetOwner(kTRUE);
103 fPreprocessorMap.SetOwner(kTRUE);
105 for (UInt_t iDet=0; iDet<NDetectors(); iDet++)
106 fFirstUnprocessed[iDet] = kFALSE;
108 fMonitoringMutex = new TMutex();
111 //______________________________________________________________________________________________
112 AliShuttle::~AliShuttle()
118 fPreprocessorMap.DeleteAll();
119 for(int iSys=0;iSys<4;iSys++)
121 fServer[iSys]->Close();
122 delete fServer[iSys];
131 if (fMonitoringMutex)
133 delete fMonitoringMutex;
134 fMonitoringMutex = 0;
138 //______________________________________________________________________________________________
139 void AliShuttle::RegisterPreprocessor(AliPreprocessor* preprocessor)
142 // Registers new AliPreprocessor.
143 // It uses GetName() for indentificator of the pre processor.
144 // The pre processor is registered it there isn't any other
145 // with the same identificator (GetName()).
148 const char* detName = preprocessor->GetName();
149 if(GetDetPos(detName) < 0)
150 AliFatal(Form("********** !!!!! Invalid detector name: %s !!!!! **********", detName));
152 if (fPreprocessorMap.GetValue(detName)) {
153 AliWarning(Form("AliPreprocessor %s is already registered!", detName));
157 fPreprocessorMap.Add(new TObjString(detName), preprocessor);
159 //______________________________________________________________________________________________
160 Bool_t AliShuttle::Store(const AliCDBPath& path, TObject* object,
161 AliCDBMetaData* metaData, Int_t validityStart, Bool_t validityInfinite)
163 // Stores a CDB object in the storage for offline reconstruction. Objects that are not needed for
164 // offline reconstruction, but should be stored anyway (e.g. for debugging) should NOT be stored
165 // using this function. Use StoreReferenceData instead!
166 // It calls StoreLocally function which temporarily stores the data locally; when the preprocessor
167 // finishes the data are transferred to the main storage (Grid).
169 return StoreLocally(fgkLocalCDB, path, object, metaData, validityStart, validityInfinite);
172 //______________________________________________________________________________________________
173 Bool_t AliShuttle::StoreReferenceData(const AliCDBPath& path, TObject* object, AliCDBMetaData* metaData)
175 // Stores a CDB object in the storage for reference data. This objects will not be available during
176 // offline reconstrunction. Use this function for reference data only!
177 // It calls StoreLocally function which temporarily stores the data locally; when the preprocessor
178 // finishes the data are transferred to the main storage (Grid).
180 return StoreLocally(fgkLocalRefStorage, path, object, metaData);
183 //______________________________________________________________________________________________
184 Bool_t AliShuttle::StoreLocally(const TString& localUri,
185 const AliCDBPath& path, TObject* object, AliCDBMetaData* metaData,
186 Int_t validityStart, Bool_t validityInfinite)
188 // Store object temporarily in local storage. Parameters are passed by Store and StoreReferenceData functions.
189 // when the preprocessor finishes the data are transferred to the main storage (Grid).
190 // The parameters are:
191 // 1) Uri of the backup storage (Local)
192 // 2) the object's path.
193 // 3) the object to be stored
194 // 4) the metaData to be associated with the object
195 // 5) the validity start run number w.r.t. the current run,
196 // if the data is valid only for this run leave the default 0
197 // 6) specifies if the calibration data is valid for infinity (this means until updated),
198 // typical for calibration runs, the default is kFALSE
200 // returns 0 if fail, 1 otherwise
202 if (fTestMode & kErrorStorage)
204 Log(fCurrentDetector, "StoreLocally - In TESTMODE - Simulating error while storing locally");
208 const char* cdbType = (localUri == fgkLocalCDB) ? "CDB" : "Reference";
210 Int_t firstRun = GetCurrentRun() - validityStart;
212 AliWarning("First valid run happens to be less than 0! Setting it to 0.");
217 if(validityInfinite) {
218 lastRun = AliCDBRunRange::Infinity();
220 lastRun = GetCurrentRun();
223 // Version is set to current run, it will be used later to transfer data to Grid
224 AliCDBId id(path, firstRun, lastRun, GetCurrentRun(), -1);
226 if(! dynamic_cast<TObjString*> (metaData->GetProperty("RunUsed(TObjString)"))){
227 TObjString runUsed = Form("%d", GetCurrentRun());
228 metaData->SetProperty("RunUsed(TObjString)", runUsed.Clone());
231 Bool_t result = kFALSE;
233 if (!(AliCDBManager::Instance()->GetStorage(localUri))) {
234 Log("SHUTTLE", Form("StoreLocally - Cannot activate local %s storage", cdbType));
236 result = AliCDBManager::Instance()->GetStorage(localUri)
237 ->Put(object, id, metaData);
242 Log(fCurrentDetector, Form("StoreLocally - Can't store object <%s>!", id.ToString().Data()));
248 //______________________________________________________________________________________________
249 Bool_t AliShuttle::StoreOCDB()
252 // Called when preprocessor ends successfully or when previous storage attempt failed (kStoreError status)
253 // Calls underlying StoreOCDB(const char*) function twice, for OCDB and Reference storage.
254 // Then calls StoreRefFilesToGrid to store reference files.
257 UpdateShuttleStatus(AliShuttleStatus::kStoreStarted);
259 if (fTestMode & kErrorGrid)
261 Log("SHUTTLE", "StoreOCDB - In TESTMODE - Simulating error while storing in the Grid");
262 Log(fCurrentDetector, "StoreOCDB - In TESTMODE - Simulating error while storing in the Grid");
266 Log("SHUTTLE","StoreOCDB - Storing OCDB data ...");
267 Int_t resultCDB = StoreOCDB(fgkMainCDB);
269 Log("SHUTTLE","StoreOCDB - Storing reference data ...");
270 Int_t resultRef = StoreOCDB(fgkMainRefStorage);
272 Log("SHUTTLE","StoreOCDB - Storing reference files ...");
273 Bool_t resultRefFiles = CopyFilesToGrid("reference");
275 Bool_t resultMetadata = kTRUE;
276 if(fCurrentDetector == "GRP")
278 Log("StoreOCDB - SHUTTLE","Storing Run Metadata file ...");
279 resultMetadata = CopyFilesToGrid("metadata");
282 Int_t storeResult = 0;
284 if (resultCDB < 0 || resultRef < 0 || resultRefFiles == kFALSE || resultMetadata == kFALSE)
286 else if (resultCDB > 0 || resultRef > 0)
292 Form("\t\t\t****** run %d - %s: STORAGE ERROR ******",
293 GetCurrentRun(), fCurrentDetector.Data()));
294 UpdateShuttleStatus(AliShuttleStatus::kStoreError);
296 else if (storeResult > 0)
299 Form("\t\t\t****** run %d - %s: STORAGE DELAYED ******",
300 GetCurrentRun(), fCurrentDetector.Data()));
301 UpdateShuttleStatus(AliShuttleStatus::kStoreDelayed);
303 else if (storeResult == 0)
306 Form("\t\t\t****** run %d - %s: DONE ******",
307 GetCurrentRun(), fCurrentDetector.Data()));
308 UpdateShuttleStatus(AliShuttleStatus::kDone);
309 UpdateShuttleLogbook(fCurrentDetector, "DONE");
312 return (storeResult == 0);
315 //______________________________________________________________________________________________
316 Int_t AliShuttle::StoreOCDB(const TString& gridURI)
319 // Called by StoreOCDB(), performs actual storage to the main OCDB and reference storages (Grid)
322 // -2 initialization error
325 // 1 storage delayed (e.g. previous unprocessed runs)
328 TObjArray* gridIds=0;
330 Bool_t result = kTRUE;
331 Bool_t delayed = kFALSE;
333 const char* type = 0;
335 if(gridURI == fgkMainCDB) {
337 localURI = fgkLocalCDB;
338 } else if(gridURI == fgkMainRefStorage) {
340 localURI = fgkLocalRefStorage;
342 AliError(Form("Invalid storage URI: %s", gridURI.Data()));
346 AliCDBManager* man = AliCDBManager::Instance();
348 AliCDBStorage *gridSto = man->GetStorage(gridURI);
351 Form("StoreOCDB - cannot activate main %s storage", type));
355 gridIds = gridSto->GetQueryCDBList();
357 // get objects previously stored in local CDB
358 AliCDBStorage *localSto = man->GetStorage(localURI);
361 Form("StoreOCDB - cannot activate local %s storage", type));
364 AliCDBPath aPath(GetOfflineDetName(fCurrentDetector.Data()),"*","*");
365 // Local objects were stored with current run as Grid version!
366 TList* localEntries = localSto->GetAll(aPath.GetPath(), GetCurrentRun(), GetCurrentRun());
367 localEntries->SetOwner(1);
369 // loop on local stored objects
370 TIter localIter(localEntries);
371 AliCDBEntry *aLocEntry = 0;
372 while((aLocEntry = dynamic_cast<AliCDBEntry*> (localIter.Next()))){
373 aLocEntry->SetOwner(1);
374 AliCDBId aLocId = aLocEntry->GetId();
375 aLocEntry->SetVersion(-1);
376 aLocEntry->SetSubVersion(-1);
378 // If local object is valid up to infinity we store it only if it is
379 // the first unprocessed run!
380 if (aLocId.GetLastRun() == AliCDBRunRange::Infinity() &&
381 !fFirstUnprocessed[GetDetPos(fCurrentDetector)])
383 Log("SHUTTLE", Form("StoreOCDB - %s: object %s has validity infinite but "
384 "there are previous unprocessed runs!",
385 fCurrentDetector.Data(), aLocId.GetPath().Data()));
386 Log(fCurrentDetector.Data(), Form("StoreOCDB - %s: object %s has validity infinite but "
387 "there are previous unprocessed runs!",
388 fCurrentDetector.Data(), aLocId.GetPath().Data()));
393 // loop on Grid valid Id's
394 Bool_t store = kTRUE;
395 TIter gridIter(gridIds);
396 AliCDBId* aGridId = 0;
397 while((aGridId = dynamic_cast<AliCDBId*> (gridIter.Next()))){
398 if(aGridId->GetPath() != aLocId.GetPath()) continue;
399 // skip all objects valid up to infinity
400 if(aGridId->GetLastRun() == AliCDBRunRange::Infinity()) continue;
401 // if we get here, it means there's already some more recent object stored on Grid!
406 // If we get here, the file can be stored!
407 Bool_t storeOk = gridSto->Put(aLocEntry);
408 if(!store || storeOk){
412 Log(fCurrentDetector.Data(),
413 Form("StoreOCDB - A more recent object already exists in %s storage: <%s>",
414 type, aGridId->ToString().Data()));
417 Form("StoreOCDB - Object <%s> successfully put into %s storage",
418 aLocId.ToString().Data(), type));
419 Log(fCurrentDetector.Data(),
420 Form("StoreOCDB - Object <%s> successfully put into %s storage",
421 aLocId.ToString().Data(), type));
424 // removing local filename...
426 localSto->IdToFilename(aLocId, filename);
427 Log("SHUTTLE", Form("StoreOCDB - Removing local file %s", filename.Data()));
428 RemoveFile(filename.Data());
432 Form("StoreOCDB - Grid %s storage of object <%s> failed",
433 type, aLocId.ToString().Data()));
434 Log(fCurrentDetector.Data(),
435 Form("StoreOCDB - Grid %s storage of object <%s> failed",
436 type, aLocId.ToString().Data()));
440 localEntries->Clear();
442 Int_t returnCode = 0;
444 if (result == kFALSE)
446 else if (delayed != kFALSE)
449 Log("SHUTTLE", Form("StoreOCDB - Returning with %d (result = %d, delayed = %d)", returnCode, result, delayed));
450 Log(fCurrentDetector.Data(), Form("StoreOCDB - Returning with %d (result = %d, delayed = %d)", returnCode, result, delayed));
455 //______________________________________________________________________________________________
456 Bool_t AliShuttle::CleanReferenceStorage(const char* detector)
458 // clears the directory used to store reference files of a given subdetector
460 AliCDBManager* man = AliCDBManager::Instance();
461 AliCDBStorage* sto = man->GetStorage(fgkLocalRefStorage);
462 TString localBaseFolder = sto->GetBaseFolder();
464 TString targetDir = GetRefFilePrefix(localBaseFolder.Data(), detector);
466 Log("SHUTTLE", Form("CleanReferenceStorage - Cleaning %s", targetDir.Data()));
469 begin.Form("%d_", GetCurrentRun());
471 TSystemDirectory* baseDir = new TSystemDirectory("/", targetDir);
475 TList* dirList = baseDir->GetListOfFiles();
478 if (!dirList) return kTRUE;
480 if (dirList->GetEntries() < 3)
486 Int_t nDirs = 0, nDel = 0;
487 TIter dirIter(dirList);
488 TSystemFile* entry = 0;
490 Bool_t success = kTRUE;
492 while ((entry = dynamic_cast<TSystemFile*> (dirIter.Next())))
494 if (entry->IsDirectory())
497 TString fileName(entry->GetName());
498 if (!fileName.BeginsWith(begin))
504 Int_t result = gSystem->Unlink(fileName.Data());
508 Log("SHUTTLE", Form("CleanReferenceStorage - Could not delete file %s!", fileName.Data()));
516 Log("SHUTTLE", Form("CleanReferenceStorage - %d (over %d) reference files in folder %s were deleted.",
517 nDel, nDirs, targetDir.Data()));
528 Int_t result = gSystem->GetPathInfo(targetDir, 0, (Long64_t*) 0, 0, 0);
532 result = gSystem->Exec(Form("rm -rf %s", targetDir.Data()));
535 Log("SHUTTLE", Form("CleanReferenceStorage - Could not clean directory %s", targetDir.Data()));
540 result = gSystem->mkdir(targetDir, kTRUE);
543 Log("SHUTTLE", Form("CleanReferenceStorage - Error creating base directory %s", targetDir.Data()));
550 //______________________________________________________________________________________________
551 Bool_t AliShuttle::StoreReferenceFile(const char* detector, const char* localFile, const char* gridFileName)
554 // Stores reference file directly (without opening it). This function stores the file locally.
556 // The file is stored under the following location:
557 // <base folder of local reference storage>/<DET>/<RUN#>_<gridFileName>
558 // where <gridFileName> is the second parameter given to the function
561 if (fTestMode & kErrorStorage)
563 Log(fCurrentDetector, "StoreReferenceFile - In TESTMODE - Simulating error while storing locally");
567 AliCDBManager* man = AliCDBManager::Instance();
568 AliCDBStorage* sto = man->GetStorage(fgkLocalRefStorage);
570 TString localBaseFolder = sto->GetBaseFolder();
572 TString target = GetRefFilePrefix(localBaseFolder.Data(), detector);
573 target.Append(Form("/%d_%s", GetCurrentRun(), gridFileName));
575 return CopyFileLocally(localFile, target);
578 //______________________________________________________________________________________________
579 Bool_t AliShuttle::StoreRunMetadataFile(const char* localFile, const char* gridFileName)
582 // Stores Run metadata file to the Grid, in the run folder
584 // Only GRP can call this function.
586 if (fTestMode & kErrorStorage)
588 Log(fCurrentDetector, "StoreRunMetaDataFile - In TESTMODE - Simulating error while storing locally");
592 AliCDBManager* man = AliCDBManager::Instance();
593 AliCDBStorage* sto = man->GetStorage(fgkLocalRefStorage);
595 TString localBaseFolder = sto->GetBaseFolder();
597 // Build Run level folder
598 // folder = /alice/data/year/lhcPeriod/runNb/raw
601 TString lhcPeriod = GetLHCPeriod();
602 if (lhcPeriod.Length() == 0)
604 Log("SHUTTLE","StoreRunMetaDataFile - LHCPeriod not found in logbook!");
608 // TODO partitions with one detector only write data into LHCperiod_DET
609 TString partition = GetRunParameter("detector");
611 if (partition.Length() > 0 && partition != "ALICE")
613 lhcPeriod.Append(Form("_%s", partition.Data()));
614 Log(fCurrentDetector, Form("Run data tags merged file will be written in %s",
618 TString target = Form("%s/GRP/RunMetadata/alice/data/%d/%s/%09d/raw/%s",
619 localBaseFolder.Data(), GetCurrentYear(),
620 lhcPeriod.Data(), GetCurrentRun(), gridFileName);
622 return CopyFileLocally(localFile, target);
625 //______________________________________________________________________________________________
626 Bool_t AliShuttle::CopyFileLocally(const char* localFile, const TString& target)
629 // Stores file locally. Called by StoreReferenceFile and StoreRunMetadataFile
630 // Files are temporarily stored in the local reference storage. When the preprocessor
631 // finishes, the Shuttle calls CopyFilesToGrid to transfer the files to AliEn
632 // (in reference or run level folders)
635 TString targetDir(target(0, target.Last('/')));
637 //try to open base dir folder, if it does not exist
638 void* dir = gSystem->OpenDirectory(targetDir.Data());
640 if (gSystem->mkdir(targetDir.Data(), kTRUE)) {
641 Log("SHUTTLE", Form("CopyFileLocally - Can't open directory <%s>", targetDir.Data()));
646 gSystem->FreeDirectory(dir);
651 result = gSystem->GetPathInfo(localFile, 0, (Long64_t*) 0, 0, 0);
654 Log("SHUTTLE", Form("CopyFileLocally - %s does not exist", localFile));
658 result = gSystem->GetPathInfo(target, 0, (Long64_t*) 0, 0, 0);
661 Log("SHUTTLE", Form("CopyFileLocally - target file %s already exist, removing...", target.Data()));
662 if (gSystem->Unlink(target.Data()))
664 Log("SHUTTLE", Form("CopyFileLocally - Could not remove existing target file %s!", target.Data()));
669 result = gSystem->CopyFile(localFile, target);
673 Log("SHUTTLE", Form("CopyFileLocally - File %s stored locally to %s", localFile, target.Data()));
678 Log("SHUTTLE", Form("CopyFileLocally - Could not store file %s to %s! Error code = %d",
679 localFile, target.Data(), result));
687 //______________________________________________________________________________________________
688 Bool_t AliShuttle::CopyFilesToGrid(const char* type)
691 // Transfers local files to the Grid. Local files can be reference files
692 // or run metadata file (from GRP only).
694 // According to the type (ref, metadata) the files are stored under the following location:
695 // ref --> <base folder of reference storage>/<DET>/<RUN#>_<gridFileName>
696 // metadata --> <run data folder>/<MetadataFileName>
699 AliCDBManager* man = AliCDBManager::Instance();
700 AliCDBStorage* sto = man->GetStorage(fgkLocalRefStorage);
703 TString localBaseFolder = sto->GetBaseFolder();
709 if (strcmp(type, "reference") == 0)
711 dir = GetRefFilePrefix(localBaseFolder.Data(), fCurrentDetector.Data());
712 AliCDBStorage* gridSto = man->GetStorage(fgkMainRefStorage);
715 TString gridBaseFolder = gridSto->GetBaseFolder();
716 alienDir = GetRefFilePrefix(gridBaseFolder.Data(), fCurrentDetector.Data());
717 begin = Form("%d_", GetCurrentRun());
719 else if (strcmp(type, "metadata") == 0)
722 TString lhcPeriod = GetLHCPeriod();
724 if (lhcPeriod.Length() == 0)
726 Log("SHUTTLE","CopyFilesToGrid - LHCPeriod not found in logbook!");
730 // TODO partitions with one detector only write data into LHCperiod_DET
731 TString partition = GetRunParameter("detector");
733 if (partition.Length() > 0 && partition != "ALICE")
735 lhcPeriod.Append(Form("_%s", partition.Data()));
738 dir = Form("%s/GRP/RunMetadata/alice/data/%d/%s/%09d/raw",
739 localBaseFolder.Data(), GetCurrentYear(),
740 lhcPeriod.Data(), GetCurrentRun());
741 alienDir = dir(dir.Index("/alice/data/"), dir.Length());
747 Log("SHUTTLE", "CopyFilesToGrid - Unexpected: type label must be reference or metadata!");
751 TSystemDirectory* baseDir = new TSystemDirectory("/", dir);
755 TList* dirList = baseDir->GetListOfFiles();
758 if (!dirList) return kTRUE;
760 if (dirList->GetEntries() < 3)
768 Log("SHUTTLE", "CopyFilesToGrid - Connection to Grid failed: Cannot continue!");
773 Int_t nDirs = 0, nTransfer = 0;
774 TIter dirIter(dirList);
775 TSystemFile* entry = 0;
777 Bool_t success = kTRUE;
778 Bool_t first = kTRUE;
780 while ((entry = dynamic_cast<TSystemFile*> (dirIter.Next())))
782 if (entry->IsDirectory())
785 TString fileName(entry->GetName());
786 if (!fileName.BeginsWith(begin))
794 // check that folder exists, otherwise create it
795 TGridResult* result = gGrid->Ls(alienDir.Data(), "a");
803 if (!result->GetFileName(1)) // TODO: It looks like element 0 is always 0!!
805 // TODO It does not work currently! Bug in TAliEn::Mkdir
806 // TODO Manually fixed in local root v5-16-00
807 if (!gGrid->Mkdir(alienDir.Data(),"-p",0))
809 Log("SHUTTLE", Form("CopyFilesToGrid - Cannot create directory %s",
814 Log("SHUTTLE",Form("CopyFilesToGrid - Folder %s created", alienDir.Data()));
818 Log("SHUTTLE",Form("CopyFilesToGrid - Folder %s found", alienDir.Data()));
822 TString fullLocalPath;
823 fullLocalPath.Form("%s/%s", dir.Data(), fileName.Data());
825 TString fullGridPath;
826 fullGridPath.Form("alien://%s/%s", alienDir.Data(), fileName.Data());
828 Bool_t result = TFile::Cp(fullLocalPath, fullGridPath);
832 Log("SHUTTLE", Form("CopyFilesToGrid - Copying local file %s to %s succeeded!",
833 fullLocalPath.Data(), fullGridPath.Data()));
834 RemoveFile(fullLocalPath);
839 Log("SHUTTLE", Form("CopyFilesToGrid - Copying local file %s to %s FAILED!",
840 fullLocalPath.Data(), fullGridPath.Data()));
845 Log("SHUTTLE", Form("CopyFilesToGrid - %d (over %d) files in folder %s copied to Grid.",
846 nTransfer, nDirs, dir.Data()));
853 //______________________________________________________________________________________________
854 const char* AliShuttle::GetRefFilePrefix(const char* base, const char* detector)
857 // Get folder name of reference files
860 TString offDetStr(GetOfflineDetName(detector));
862 if (offDetStr == "ITS" || offDetStr == "MUON" || offDetStr == "PHOS")
864 dir.Form("%s/%s/%s", base, offDetStr.Data(), detector);
866 dir.Form("%s/%s", base, offDetStr.Data());
874 //______________________________________________________________________________________________
875 void AliShuttle::CleanLocalStorage(const TString& uri)
878 // Called in case the preprocessor is declared failed. Remove remaining objects from the local storages.
881 const char* type = 0;
882 if(uri == fgkLocalCDB) {
884 } else if(uri == fgkLocalRefStorage) {
887 AliError(Form("Invalid storage URI: %s", uri.Data()));
891 AliCDBManager* man = AliCDBManager::Instance();
893 // open local storage
894 AliCDBStorage *localSto = man->GetStorage(uri);
897 Form("CleanLocalStorage - cannot activate local %s storage", type));
901 TString filename(Form("%s/%s/*/Run*_v%d_s*.root",
902 localSto->GetBaseFolder().Data(), GetOfflineDetName(fCurrentDetector.Data()), GetCurrentRun()));
904 AliDebug(2, Form("filename = %s", filename.Data()));
906 Log("SHUTTLE", Form("Removing remaining local files for run %d and detector %s ...",
907 GetCurrentRun(), fCurrentDetector.Data()));
909 RemoveFile(filename.Data());
913 //______________________________________________________________________________________________
914 void AliShuttle::RemoveFile(const char* filename)
917 // removes local file
920 TString command(Form("rm -f %s", filename));
922 Int_t result = gSystem->Exec(command.Data());
925 Log("SHUTTLE", Form("RemoveFile - %s: Cannot remove file %s!",
926 fCurrentDetector.Data(), filename));
930 //______________________________________________________________________________________________
931 AliShuttleStatus* AliShuttle::ReadShuttleStatus()
934 // Reads the AliShuttleStatus from the CDB
942 fStatusEntry = AliCDBManager::Instance()->GetStorage(GetLocalCDB())
943 ->Get(Form("/SHUTTLE/STATUS/%s", fCurrentDetector.Data()), GetCurrentRun());
945 if (!fStatusEntry) return 0;
946 fStatusEntry->SetOwner(1);
948 AliShuttleStatus* status = dynamic_cast<AliShuttleStatus*> (fStatusEntry->GetObject());
950 AliError("Invalid object stored to CDB!");
957 //______________________________________________________________________________________________
958 Bool_t AliShuttle::WriteShuttleStatus(AliShuttleStatus* status)
961 // writes the status for one subdetector
969 Int_t run = GetCurrentRun();
971 AliCDBId id(AliCDBPath("SHUTTLE", "STATUS", fCurrentDetector), run, run);
973 fStatusEntry = new AliCDBEntry(status, id, new AliCDBMetaData);
974 fStatusEntry->SetOwner(1);
976 UInt_t result = AliCDBManager::Instance()->GetStorage(fgkLocalCDB)->Put(fStatusEntry);
979 Log("SHUTTLE", Form("WriteShuttleStatus - Failed for %s, run %d",
980 fCurrentDetector.Data(), run));
989 //______________________________________________________________________________________________
990 void AliShuttle::UpdateShuttleStatus(AliShuttleStatus::Status newStatus, Bool_t increaseCount)
993 // changes the AliShuttleStatus for the given detector and run to the given status
997 AliError("UNEXPECTED: fStatusEntry empty");
1001 AliShuttleStatus* status = dynamic_cast<AliShuttleStatus*> (fStatusEntry->GetObject());
1004 Log("SHUTTLE", "UpdateShuttleStatus - UNEXPECTED: status could not be read from current CDB entry");
1008 TString actionStr = Form("UpdateShuttleStatus - %s: Changing state from %s to %s",
1009 fCurrentDetector.Data(),
1010 status->GetStatusName(),
1011 status->GetStatusName(newStatus));
1012 Log("SHUTTLE", actionStr);
1013 SetLastAction(actionStr);
1015 status->SetStatus(newStatus);
1016 if (increaseCount) status->IncreaseCount();
1018 AliCDBManager::Instance()->GetStorage(fgkLocalCDB)->Put(fStatusEntry);
1023 //______________________________________________________________________________________________
1024 void AliShuttle::SendMLInfo()
1027 // sends ML information about the current status of the current detector being processed
1030 AliShuttleStatus* status = dynamic_cast<AliShuttleStatus*> (fStatusEntry->GetObject());
1033 Log("SHUTTLE", "SendMLInfo - UNEXPECTED: status could not be read from current CDB entry");
1037 TMonaLisaText mlStatus(Form("%s_status", fCurrentDetector.Data()), status->GetStatusName());
1038 TMonaLisaValue mlRetryCount(Form("%s_count", fCurrentDetector.Data()), status->GetCount());
1041 mlList.Add(&mlStatus);
1042 mlList.Add(&mlRetryCount);
1045 mlID.Form("%d", GetCurrentRun());
1046 fMonaLisa->SendParameters(&mlList, mlID);
1049 //______________________________________________________________________________________________
1050 Bool_t AliShuttle::ContinueProcessing()
1052 // this function reads the AliShuttleStatus information from CDB and
1053 // checks if the processing should be continued
1054 // if yes it returns kTRUE and updates the AliShuttleStatus with nextStatus
1056 if (!fConfig->HostProcessDetector(fCurrentDetector))
1059 AliPreprocessor* aPreprocessor =
1060 dynamic_cast<AliPreprocessor*> (fPreprocessorMap.GetValue(fCurrentDetector));
1063 Log("SHUTTLE", Form("ContinueProcessing - %s: no preprocessor registered", fCurrentDetector.Data()));
1067 AliShuttleLogbookEntry::Status entryStatus =
1068 fLogbookEntry->GetDetectorStatus(fCurrentDetector);
1070 if (entryStatus != AliShuttleLogbookEntry::kUnprocessed) {
1071 Log("SHUTTLE", Form("ContinueProcessing - %s is %s",
1072 fCurrentDetector.Data(),
1073 fLogbookEntry->GetDetectorStatusName(entryStatus)));
1077 // if we get here, according to Shuttle logbook subdetector is in UNPROCESSED state
1079 // check if current run is first unprocessed run for current detector
1080 if (fConfig->StrictRunOrder(fCurrentDetector) &&
1081 !fFirstUnprocessed[GetDetPos(fCurrentDetector)])
1083 if (fTestMode == kNone)
1085 Log("SHUTTLE", Form("ContinueProcessing - %s requires strict run ordering"
1086 " but this is not the first unprocessed run!"));
1091 Log("SHUTTLE", Form("ContinueProcessing - In TESTMODE - "
1092 "Although %s requires strict run ordering "
1093 "and this is not the first unprocessed run, "
1094 "the SHUTTLE continues"));
1098 // Is the subdetector processed first time for this run?
1099 fFirstProcessing = kFALSE;
1101 AliShuttleStatus* status = ReadShuttleStatus();
1104 Log("SHUTTLE", Form("ContinueProcessing - %s: Processing first time",
1105 fCurrentDetector.Data()));
1106 status = new AliShuttleStatus(AliShuttleStatus::kStarted);
1107 fFirstProcessing = kTRUE;
1108 return WriteShuttleStatus(status);
1111 // The following case shouldn't happen if Shuttle Logbook was correctly updated.
1112 // If it happens it may mean Logbook updating failed... let's do it now!
1113 if (status->GetStatus() == AliShuttleStatus::kDone ||
1114 status->GetStatus() == AliShuttleStatus::kFailed ||
1115 status->GetStatus() == AliShuttleStatus::kSkipped) {
1116 Log("SHUTTLE", Form("ContinueProcessing - %s is already %s. Updating Shuttle Logbook",
1117 fCurrentDetector.Data(),
1118 status->GetStatusName(status->GetStatus())));
1120 if (status->GetStatus() == AliShuttleStatus::kSkipped)
1122 UpdateShuttleLogbook(fCurrentDetector.Data(), "DONE");
1125 UpdateShuttleLogbook(fCurrentDetector.Data(), status->GetStatusName(status->GetStatus()));
1130 if (status->GetStatus() == AliShuttleStatus::kStoreStarted || status->GetStatus() == AliShuttleStatus::kStoreDelayed ||status->GetStatus() == AliShuttleStatus::kStoreError) {
1132 Form("ContinueProcessing - %s: Grid storage of one or more "
1133 "objects failed. Trying again now",
1134 fCurrentDetector.Data()));
1139 // if we get here, there is a restart
1140 Bool_t cont = kFALSE;
1143 if (status->GetCount() >= fConfig->GetMaxRetries()) {
1144 Log("SHUTTLE", Form("ContinueProcessing - %s failed %d times in status %s - "
1145 "Updating Shuttle Logbook", fCurrentDetector.Data(),
1146 status->GetCount(), status->GetStatusName()));
1147 UpdateShuttleLogbook(fCurrentDetector.Data(), "FAILED");
1148 UpdateShuttleStatus(AliShuttleStatus::kFailed);
1150 // there may still be objects in local OCDB and reference storage
1151 // and FXS databases may be not updated: do it now!
1153 // TODO Currently disabled, we want to keep files in case of failure!
1154 // CleanLocalStorage(fgkLocalCDB);
1155 // CleanLocalStorage(fgkLocalRefStorage);
1156 // UpdateTableFailCase();
1158 // Send mail to detector expert!
1159 Log("SHUTTLE", Form("ContinueProcessing - Sending mail to %s expert...",
1160 fCurrentDetector.Data()));
1161 if (!SendMail(kPPEMail))
1162 Log("SHUTTLE", Form("ContinueProcessing - Could not send mail to %s expert",
1163 fCurrentDetector.Data()));
1166 Log("SHUTTLE", Form("ContinueProcessing - %s: restarting. "
1167 "Aborted before with %s. Retry number %d.", fCurrentDetector.Data(),
1168 status->GetStatusName(), status->GetCount()));
1169 Bool_t increaseCount = kTRUE;
1170 if (status->GetStatus() == AliShuttleStatus::kDCSError ||
1171 status->GetStatus() == AliShuttleStatus::kDCSStarted ||
1172 status->GetStatus() == AliShuttleStatus::kFXSError)
1173 increaseCount = kFALSE;
1175 UpdateShuttleStatus(AliShuttleStatus::kStarted, increaseCount);
1182 //______________________________________________________________________________________________
1183 Bool_t AliShuttle::Process(AliShuttleLogbookEntry* entry)
1186 // Makes data retrieval for all detectors in the configuration.
1187 // entry: Shuttle logbook entry, contains run paramenters and status of detectors
1188 // (Unprocessed, Inactive, Failed or Done).
1189 // Returns kFALSE in case of error occured and kTRUE otherwise
1192 if (!entry) return kFALSE;
1194 fLogbookEntry = entry;
1196 Log("SHUTTLE", Form("\t\t\t^*^*^*^*^*^*^*^*^*^*^*^* run %d: START ^*^*^*^*^*^*^*^*^*^*^*^*",
1199 // Send the information to ML
1202 TMonaLisaText mlStatus("SHUTTLE_status", "Processing");
1203 TString runType(entry->GetRunType());
1204 if (strlen(entry->GetRunParameter("log")) > 0){
1207 runType += entry->GetRunParameter("log");
1210 TMonaLisaText mlRunType("SHUTTLE_runtype", runType);
1213 mlList.Add(&mlStatus);
1214 mlList.Add(&mlRunType);
1217 mlID.Form("%d", GetCurrentRun());
1218 fMonaLisa->SendParameters(&mlList, mlID);
1220 if (fLogbookEntry->IsDone())
1222 Log("SHUTTLE","Process - Shuttle is already DONE. Updating logbook");
1223 UpdateShuttleLogbook("shuttle_done");
1228 // read test mode if flag is set
1232 TString logEntry(entry->GetRunParameter("log"));
1233 //printf("log entry = %s\n", logEntry.Data());
1234 TString searchStr("Testmode: ");
1235 Int_t pos = logEntry.Index(searchStr.Data());
1236 //printf("%d\n", pos);
1239 TSubString subStr = logEntry(pos + searchStr.Length(), logEntry.Length());
1240 //printf("%s\n", subStr.String().Data());
1241 TString newStr(subStr.Data());
1242 TObjArray* token = newStr.Tokenize(' ');
1246 TObjString* tmpStr = dynamic_cast<TObjString*> (token->First());
1249 Int_t testMode = tmpStr->String().Atoi();
1252 Log("SHUTTLE", Form("Process - Enabling test mode %d", testMode));
1253 SetTestMode((TestMode) testMode);
1261 fLogbookEntry->Print("all");
1264 Bool_t hasError = kFALSE;
1266 // Set the CDB and Reference folders according to the year and LHC period
1267 TString lhcPeriod(GetLHCPeriod());
1268 if (lhcPeriod.Length() == 0)
1270 Log("SHUTTLE","Process - LHCPeriod not found in logbook!");
1274 if (fgkMainCDB.Length() == 0)
1275 fgkMainCDB = Form("alien://folder=/alice/data/%d/%s/OCDB?user=alidaq?cacheFold=/tmp/OCDBCache",
1276 GetCurrentYear(), lhcPeriod.Data());
1278 if (fgkMainRefStorage.Length() == 0)
1279 fgkMainRefStorage = Form("alien://folder=/alice/data/%d/%s/Reference?user=alidaq?cacheFold=/tmp/OCDBCache",
1280 GetCurrentYear(), lhcPeriod.Data());
1282 // Loop on detectors in the configuration
1283 TIter iter(fConfig->GetDetectors());
1284 TObjString* aDetector = 0;
1286 Bool_t first = kTRUE;
1288 while ((aDetector = (TObjString*) iter.Next()))
1290 fCurrentDetector = aDetector->String();
1292 if (ContinueProcessing() == kFALSE)
1297 // only read QueryCDB when needed and only once
1298 AliCDBStorage *mainCDBSto = AliCDBManager::Instance()->GetStorage(fgkMainCDB);
1299 if(mainCDBSto) mainCDBSto->QueryCDB(GetCurrentRun());
1300 AliCDBStorage *mainRefSto = AliCDBManager::Instance()->GetStorage(fgkMainRefStorage);
1301 if(mainRefSto) mainRefSto->QueryCDB(GetCurrentRun());
1305 Log("SHUTTLE", Form("\t\t\t****** run %d - %s: START ******",
1306 GetCurrentRun(), aDetector->GetName()));
1308 for(Int_t iSys=0;iSys<3;iSys++) fFXSCalled[iSys]=kFALSE;
1310 Log(fCurrentDetector.Data(), "Process - Starting processing");
1316 Log("SHUTTLE", "Process - ERROR: Forking failed");
1321 Log("SHUTTLE", Form("Process - In parent process of %d - %s: Starting monitoring",
1322 GetCurrentRun(), aDetector->GetName()));
1324 Long_t begin = time(0);
1326 int status; // to be used with waitpid, on purpose an int (not Int_t)!
1327 while (waitpid(pid, &status, WNOHANG) == 0)
1329 Long_t expiredTime = time(0) - begin;
1331 if (expiredTime > fConfig->GetPPTimeOut())
1334 tmp.Form("Process - Process of %s time out. "
1335 "Run time: %d seconds. Killing...",
1336 fCurrentDetector.Data(), expiredTime);
1337 Log("SHUTTLE", tmp);
1338 Log(fCurrentDetector, tmp);
1342 UpdateShuttleStatus(AliShuttleStatus::kPPTimeOut);
1345 gSystem->Sleep(1000);
1349 gSystem->Sleep(1000);
1352 checkStr.Form("ps -o vsize --pid %d | tail -n 1", pid);
1353 FILE* pipe = gSystem->OpenPipe(checkStr, "r");
1356 Log("SHUTTLE", Form("Process - Error: "
1357 "Could not open pipe to %s", checkStr.Data()));
1362 if (!fgets(buffer, 100, pipe))
1364 Log("SHUTTLE", "Process - Error: ps did not return anything");
1365 gSystem->ClosePipe(pipe);
1368 gSystem->ClosePipe(pipe);
1370 //Log("SHUTTLE", Form("ps returned %s", buffer));
1373 if ((sscanf(buffer, "%d\n", &mem) != 1) || !mem)
1375 Log("SHUTTLE", "Process - Error: Could not parse output of ps");
1379 if (expiredTime % 60 == 0)
1381 Log("SHUTTLE", Form("Process - %s: Checking process. "
1382 "Run time: %d seconds - Memory consumption: %d KB",
1383 fCurrentDetector.Data(), expiredTime, mem));
1387 if (mem > fConfig->GetPPMaxMem())
1390 tmp.Form("Process - Process exceeds maximum allowed memory "
1391 "(%d KB > %d KB). Killing...",
1392 mem, fConfig->GetPPMaxMem());
1393 Log("SHUTTLE", tmp);
1394 Log(fCurrentDetector, tmp);
1398 UpdateShuttleStatus(AliShuttleStatus::kPPOutOfMemory);
1401 gSystem->Sleep(1000);
1406 Log("SHUTTLE", Form("Process - In parent process of %d - %s: Client has terminated.",
1407 GetCurrentRun(), aDetector->GetName()));
1409 if (WIFEXITED(status))
1411 Int_t returnCode = WEXITSTATUS(status);
1413 Log("SHUTTLE", Form("Process - %s: the return code is %d", fCurrentDetector.Data(),
1416 if (returnCode == 0) hasError = kTRUE;
1422 Log("SHUTTLE", Form("Process - In client process of %d - %s", GetCurrentRun(),
1423 aDetector->GetName()));
1425 Log("SHUTTLE", Form("Process - Redirecting output to %s log",fCurrentDetector.Data()));
1427 if ((freopen(GetLogFileName(fCurrentDetector), "a", stdout)) == 0)
1429 Log("SHUTTLE", "Process - Could not freopen stdout");
1433 fOutputRedirected = kTRUE;
1434 if ((dup2(fileno(stdout), fileno(stderr))) < 0)
1435 Log("SHUTTLE", "Process - Could not redirect stderr");
1439 TString wd = gSystem->WorkingDirectory();
1440 TString tmpDir = Form("%s/%s_%d_process", GetShuttleTempDir(),
1441 fCurrentDetector.Data(), GetCurrentRun());
1443 Int_t result = gSystem->GetPathInfo(tmpDir.Data(), 0, (Long64_t*) 0, 0, 0);
1444 if (!result) // temp dir already exists!
1446 Log(fCurrentDetector.Data(),
1447 Form("Process - %s dir already exists! Removing...", tmpDir.Data()));
1448 gSystem->Exec(Form("rm -rf %s",tmpDir.Data()));
1451 if (gSystem->mkdir(tmpDir.Data(), 1))
1453 Log(fCurrentDetector.Data(), "Process - could not make temp directory!!");
1457 if (!gSystem->ChangeDirectory(tmpDir.Data()))
1459 Log(fCurrentDetector.Data(), "Process - could not change directory!!");
1463 Int_t success = ProcessCurrentDetector();
1465 gSystem->ChangeDirectory(wd.Data());
1467 if (success == 1) // Preprocessor finished successfully!
1469 // remove temporary folder or DCS map
1470 if (!fConfig->KeepTempFolder())
1472 gSystem->Exec(Form("rm -rf %s",tmpDir.Data()));
1473 } else if (!fConfig->KeepDCSMap())
1475 gSystem->Exec(Form("rm -f %s/DCSMap.root",tmpDir.Data()));
1478 // Update time_processed field in FXS DB
1479 if (UpdateTable() == kFALSE)
1480 Log("SHUTTLE", Form("Process - %s: Could not update FXS databases!",
1481 fCurrentDetector.Data()));
1483 // Transfer the data from local storage to main storage (Grid)
1484 if (StoreOCDB() == kFALSE)
1487 else if (success == 0)
1490 Form("\t\t\t****** run %d - %s: PP ERROR ******",
1491 GetCurrentRun(), aDetector->GetName()));
1494 for (UInt_t iSys=0; iSys<3; iSys++)
1496 if (fFXSCalled[iSys]) fFXSlist[iSys].Clear();
1499 Log("SHUTTLE", Form("Process - Client process of %d - %s is exiting now with %d.",
1500 GetCurrentRun(), aDetector->GetName(), success));
1502 // the client exits here
1503 gSystem->Exit(success);
1505 AliError("We should never get here!!!");
1509 Log("SHUTTLE", Form("\t\t\t^*^*^*^*^*^*^*^*^*^*^*^* run %d: FINISH ^*^*^*^*^*^*^*^*^*^*^*^*",
1512 //check if shuttle is done for this run, if so update logbook
1513 TObjArray checkEntryArray;
1514 checkEntryArray.SetOwner(1);
1515 TString whereClause = Form("where run=%d", GetCurrentRun());
1516 if (!QueryShuttleLogbook(whereClause.Data(), checkEntryArray) ||
1517 checkEntryArray.GetEntries() == 0) {
1518 Log("SHUTTLE", Form("Process - Warning: Cannot check status of run %d on Shuttle logbook!",
1520 return hasError == kFALSE;
1523 AliShuttleLogbookEntry* checkEntry = dynamic_cast<AliShuttleLogbookEntry*>
1524 (checkEntryArray.At(0));
1528 if (checkEntry->IsDone())
1530 Log("SHUTTLE","Process - Shuttle is DONE. Updating logbook");
1531 UpdateShuttleLogbook("shuttle_done");
1535 for (UInt_t iDet=0; iDet<NDetectors(); iDet++)
1537 if (checkEntry->GetDetectorStatus(iDet) == AliShuttleLogbookEntry::kUnprocessed)
1539 AliDebug(2, Form("Run %d: setting %s as \"not first time unprocessed\"",
1540 checkEntry->GetRun(), GetDetName(iDet)));
1541 fFirstUnprocessed[iDet] = kFALSE;
1544 TMonaLisaText mlStatusPending("SHUTTLE_status", "Pending");
1546 mlList.Add(&mlStatusPending);
1547 fMonaLisa->SendParameters(&mlList, mlID);
1553 return hasError == kFALSE;
1556 //______________________________________________________________________________________________
1557 Int_t AliShuttle::ProcessCurrentDetector()
1560 // Makes data retrieval just for a specific detector (fCurrentDetector).
1561 // Threre should be a configuration for this detector.
1563 Log("SHUTTLE", Form("ProcessCurrentDetector - Retrieving values for %s, run %d",
1564 fCurrentDetector.Data(), GetCurrentRun()));
1566 TString wd = gSystem->WorkingDirectory();
1568 if (!CleanReferenceStorage(fCurrentDetector.Data()))
1571 gSystem->ChangeDirectory(wd.Data());
1573 // call preprocessor
1574 AliPreprocessor* aPreprocessor =
1575 dynamic_cast<AliPreprocessor*> (fPreprocessorMap.GetValue(fCurrentDetector));
1577 // check if the preprocessor wants to process this run type
1578 if (aPreprocessor->ProcessRunType() == kFALSE)
1580 UpdateShuttleStatus(AliShuttleStatus::kSkipped);
1581 UpdateShuttleLogbook(fCurrentDetector, "DONE");
1582 Log(fCurrentDetector, Form("ProcessCurrentDetector - %s preprocessor is not interested in this run type", fCurrentDetector.Data()));
1587 TMap* dcsMap = new TMap();
1589 aPreprocessor->Initialize(GetCurrentRun(), GetCurrentStartTime(), GetCurrentEndTime());
1591 Bool_t processDCS = aPreprocessor->ProcessDCS();
1595 Log(fCurrentDetector, "ProcessCurrentDetector -"
1596 " The preprocessor requested to skip the retrieval of DCS values");
1598 else if (fTestMode & kSkipDCS)
1600 Log(fCurrentDetector, "ProcessCurrentDetector - In TESTMODE: Skipping DCS processing");
1602 else if (fTestMode & kErrorDCS)
1604 Log(fCurrentDetector, "ProcessCurrentDetector - In TESTMODE: Simulating DCS error");
1605 UpdateShuttleStatus(AliShuttleStatus::kDCSStarted);
1606 UpdateShuttleStatus(AliShuttleStatus::kDCSError);
1611 UpdateShuttleStatus(AliShuttleStatus::kDCSStarted);
1613 // Query DCS archive
1614 Int_t nServers = fConfig->GetNServers(fCurrentDetector);
1616 for (int iServ=0; iServ<nServers; iServ++)
1619 TString host(fConfig->GetDCSHost(fCurrentDetector, iServ));
1620 Int_t port = fConfig->GetDCSPort(fCurrentDetector, iServ);
1621 Int_t multiSplit = fConfig->GetMultiSplit(fCurrentDetector, iServ);
1623 Log(fCurrentDetector, Form("ProcessCurrentDetector -"
1624 " Querying DCS Amanda server %s:%d (%d of %d)",
1625 host.Data(), port, iServ+1, nServers));
1630 if (fConfig->GetDCSAliases(fCurrentDetector, iServ)->GetEntries() > 0)
1632 aliasMap = GetValueSet(host, port,
1633 fConfig->GetDCSAliases(fCurrentDetector, iServ),
1634 kAlias, multiSplit);
1637 Log(fCurrentDetector,
1638 Form("ProcessCurrentDetector -"
1639 " Error retrieving DCS aliases from server %s."
1640 " Sending mail to DCS experts!", host.Data()));
1641 UpdateShuttleStatus(AliShuttleStatus::kDCSError);
1643 if (!SendMail(kDCSEMail))
1644 Log("SHUTTLE", Form("ProcessCurrentDetector - "
1645 "Could not send mail to DCS experts!"));
1652 if (fConfig->GetDCSDataPoints(fCurrentDetector, iServ)->GetEntries() > 0)
1654 dpMap = GetValueSet(host, port,
1655 fConfig->GetDCSDataPoints(fCurrentDetector, iServ),
1659 Log(fCurrentDetector,
1660 Form("ProcessCurrentDetector -"
1661 " Error retrieving DCS data points from server %s."
1662 " Sending mail to DCS experts!", host.Data()));
1663 UpdateShuttleStatus(AliShuttleStatus::kDCSError);
1665 if (!SendMail(kDCSEMail))
1666 Log("SHUTTLE", Form("ProcessCurrentDetector - "
1667 "Could not send mail to DCS experts!"));
1669 if (aliasMap) delete aliasMap;
1675 // merge aliasMap and dpMap into dcsMap
1677 TIter iter(aliasMap);
1678 TObjString* key = 0;
1679 while ((key = (TObjString*) iter.Next()))
1680 dcsMap->Add(key, aliasMap->GetValue(key->String()));
1682 aliasMap->SetOwner(kFALSE);
1688 TObjString* key = 0;
1689 while ((key = (TObjString*) iter.Next()))
1690 dcsMap->Add(key, dpMap->GetValue(key->String()));
1692 dpMap->SetOwner(kFALSE);
1698 // save map into file, to help debugging in case of preprocessor error
1699 TFile* f = TFile::Open("DCSMap.root","recreate");
1701 dcsMap->Write("DCSMap", TObject::kSingleKey);
1705 // DCS Archive DB processing successful. Call Preprocessor!
1706 UpdateShuttleStatus(AliShuttleStatus::kPPStarted);
1708 fFXSError = -1; // this variable is kTRUE after ::Process if an FXS error occured
1710 UInt_t returnValue = aPreprocessor->Process(dcsMap);
1712 if (fFXSError!=-1) {
1713 UpdateShuttleStatus(AliShuttleStatus::kFXSError);
1714 SendMail(kFXSEMail, fFXSError);
1715 dcsMap->DeleteAll();
1720 if (returnValue > 0) // Preprocessor error!
1722 Log(fCurrentDetector, Form("ProcessCurrentDetector - "
1723 "Preprocessor failed. Process returned %d.", returnValue));
1724 UpdateShuttleStatus(AliShuttleStatus::kPPError);
1725 dcsMap->DeleteAll();
1731 UpdateShuttleStatus(AliShuttleStatus::kPPDone);
1732 Log(fCurrentDetector, Form("ProcessCurrentDetector - %s preprocessor returned success",
1733 fCurrentDetector.Data()));
1735 dcsMap->DeleteAll();
1741 //______________________________________________________________________________________________
1742 void AliShuttle::CountOpenRuns()
1744 // Query DAQ's Shuttle logbook and sends the number of open runs to ML
1746 // check connection, in case connect
1751 sqlQuery = Form("select count(*) from %s where shuttle_done=0", fConfig->GetShuttlelbTable());
1753 TSQLResult* aResult = fServer[3]->Query(sqlQuery);
1755 AliError(Form("Can't execute query <%s>!", sqlQuery.Data()));
1759 AliDebug(2,Form("Query = %s", sqlQuery.Data()));
1761 if (aResult->GetRowCount() == 0) {
1762 AliError(Form("No result for query %s received", sqlQuery.Data()));
1766 if (aResult->GetFieldCount() != 1) {
1767 AliError(Form("Invalid field count for query %s received", sqlQuery.Data()));
1771 TSQLRow* aRow = aResult->Next();
1773 AliError(Form("Could not receive result of query %s", sqlQuery.Data()));
1777 TString result(aRow->GetField(0), aRow->GetFieldLength(0));
1778 Int_t count = result.Atoi();
1780 Log("SHUTTLE", Form("%d unprocessed runs", count));
1785 TMonaLisaValue mlStatus("SHUTTLE_openruns", count);
1788 mlList.Add(&mlStatus);
1790 fMonaLisa->SendParameters(&mlList, "__PROCESSINGINFO__");
1793 //______________________________________________________________________________________________
1794 Bool_t AliShuttle::QueryShuttleLogbook(const char* whereClause,
1797 // Query DAQ's Shuttle logbook and fills detector status object.
1798 // Call QueryRunParameters to query DAQ logbook for run parameters.
1801 entries.SetOwner(1);
1803 // check connection, in case connect
1804 if (!Connect(3)) return kFALSE;
1807 sqlQuery = Form("select * from %s %s order by run", fConfig->GetShuttlelbTable(), whereClause);
1809 TSQLResult* aResult = fServer[3]->Query(sqlQuery);
1811 AliError(Form("Can't execute query <%s>!", sqlQuery.Data()));
1815 AliDebug(2,Form("Query = %s", sqlQuery.Data()));
1817 if(aResult->GetRowCount() == 0) {
1818 Log("SHUTTLE", "No entries in Shuttle Logbook match request");
1823 // TODO Check field count!
1824 const UInt_t nCols = 23;
1825 if (aResult->GetFieldCount() != (Int_t) nCols) {
1826 Log("SHUTTLE", "Invalid SQL result field number!");
1832 while ((aRow = aResult->Next())) {
1833 TString runString(aRow->GetField(0), aRow->GetFieldLength(0));
1834 Int_t run = runString.Atoi();
1836 AliShuttleLogbookEntry *entry = QueryRunParameters(run);
1840 // loop on detectors
1841 for(UInt_t ii = 0; ii < nCols; ii++)
1842 entry->SetDetectorStatus(aResult->GetFieldName(ii), aRow->GetField(ii));
1844 entries.AddLast(entry);
1852 //______________________________________________________________________________________________
1853 AliShuttleLogbookEntry* AliShuttle::QueryRunParameters(Int_t run)
1856 // Retrieve run parameters written in the DAQ logbook and sets them into AliShuttleLogbookEntry object
1859 // check connection, in case connect
1864 sqlQuery.Form("select * from %s where run=%d", fConfig->GetDAQlbTable(), run);
1866 TSQLResult* aResult = fServer[3]->Query(sqlQuery);
1868 Log("SHUTTLE", Form("Can't execute query <%s>!", sqlQuery.Data()));
1872 if (aResult->GetRowCount() == 0) {
1873 Log("SHUTTLE", Form("QueryRunParameters - No entry in DAQ Logbook for run %d. Skipping", run));
1878 if (aResult->GetRowCount() > 1) {
1879 Log("SHUTTLE", Form("QueryRunParameters - UNEXPECTED: "
1880 "more than one entry in DAQ Logbook for run %d!", run));
1885 TSQLRow* aRow = aResult->Next();
1888 Log("SHUTTLE", Form("QueryRunParameters - Could not retrieve row for run %d. Skipping", run));
1893 AliShuttleLogbookEntry* entry = new AliShuttleLogbookEntry(run);
1895 for (Int_t ii = 0; ii < aResult->GetFieldCount(); ii++)
1896 entry->SetRunParameter(aResult->GetFieldName(ii), aRow->GetField(ii));
1901 UInt_t startTime = entry->GetStartTime();
1902 UInt_t endTime = entry->GetEndTime();
1904 TString totEventsStr = entry->GetRunParameter("totalEvents");
1905 Int_t totEvents = totEventsStr.Atoi();
1907 if (startTime != 0 && endTime != 0 && endTime > startTime && totEvents > 0)
1911 Form("QueryRunParameters - Invalid parameters for Run %d: "
1912 "startTime = %d, endTime = %d. Skipping (Shuttle won't be marked as DONE)!",
1913 run, startTime, endTime));
1916 Log("SHUTTLE", Form("QueryRunParameters - Run %d has 0 events - Skipping!", run));
1918 //Log("SHUTTLE", Form("Marking SHUTTLE done for run %d", run));
1919 //fLogbookEntry = entry;
1920 //if (!UpdateShuttleLogbook("shuttle_done"))
1922 // AliError(Form("Could not update logbook for run %d !", run));
1924 //fLogbookEntry = 0;
1930 //______________________________________________________________________________________________
1931 TMap* AliShuttle::GetValueSet(const char* host, Int_t port, const TSeqCollection* entries,
1932 DCSType type, Int_t multiSplit)
1934 // Retrieve all "entry" data points from the DCS server
1935 // host, port: TSocket connection parameters
1936 // entries: list of name of the alias or data point
1937 // type: kAlias or kDP
1938 // returns TMap of values, 0 when failure
1940 AliDCSClient client(host, port, fTimeout, fRetries, multiSplit);
1945 result = client.GetAliasValues(entries, GetCurrentStartTime(),
1946 GetCurrentEndTime());
1948 else if (type == kDP)
1950 result = client.GetDPValues(entries, GetCurrentStartTime(),
1951 GetCurrentEndTime());
1956 Log(fCurrentDetector.Data(), Form("GetValueSet - Can't get entries! Reason: %s",
1957 client.GetErrorString(client.GetResultErrorCode())));
1958 if (client.GetResultErrorCode() == AliDCSClient::fgkServerError)
1959 Log(fCurrentDetector.Data(), Form("GetValueSet - Server error code: %s",
1960 client.GetServerError().Data()));
1968 //______________________________________________________________________________________________
1969 const char* AliShuttle::GetFile(Int_t system, const char* detector,
1970 const char* id, const char* source)
1972 // Get calibration file from file exchange servers
1973 // First queris the FXS database for the file name, using the run, detector, id and source info
1974 // then calls RetrieveFile(filename) for actual copy to local disk
1975 // run: current run being processed (given by Logbook entry fLogbookEntry)
1976 // detector: the Preprocessor name
1977 // id: provided as a parameter by the Preprocessor
1978 // source: provided by the Preprocessor through GetFileSources function
1980 // check if test mode should simulate a FXS error
1981 if (fTestMode & kErrorFXSFiles)
1983 Log(detector, Form("GetFile - In TESTMODE - Simulating error while connecting to %s FXS", GetSystemName(system)));
1987 // check connection, in case connect
1988 if (!Connect(system))
1990 Log(detector, Form("GetFile - Couldn't connect to %s FXS database", GetSystemName(system)));
1995 // Query preparation
1996 TString sourceName(source);
1998 TString sqlQueryStart = Form("select filePath,size,fileChecksum from %s where",
1999 fConfig->GetFXSdbTable(system));
2000 TString whereClause = Form("run=%d and detector=\"%s\" and fileId=\"%s\"",
2001 GetCurrentRun(), detector, id);
2005 whereClause += Form(" and DAQsource=\"%s\"", source);
2007 else if (system == kDCS)
2011 else if (system == kHLT)
2013 whereClause += Form(" and DDLnumbers=\"%s\"", source);
2016 TString sqlQuery = Form("%s %s", sqlQueryStart.Data(), whereClause.Data());
2018 AliDebug(2, Form("SQL query: \n%s",sqlQuery.Data()));
2021 TSQLResult* aResult = 0;
2022 aResult = dynamic_cast<TSQLResult*> (fServer[system]->Query(sqlQuery));
2024 Log(detector, Form("GetFile - Can't execute SQL query to %s database for: id = %s, source = %s",
2025 GetSystemName(system), id, sourceName.Data()));
2030 if (aResult->GetRowCount() == 0)
2033 Form("GetFile - No entry in %s FXS db for: id = %s, source = %s",
2034 GetSystemName(system), id, sourceName.Data()));
2039 if (aResult->GetRowCount() > 1) {
2041 Form("GetFile - More than one entry in %s FXS db for: id = %s, source = %s",
2042 GetSystemName(system), id, sourceName.Data()));
2048 if (aResult->GetFieldCount() != nFields) {
2050 Form("GetFileName - Wrong field count in %s FXS db for: id = %s, source = %s",
2051 GetSystemName(system), id, sourceName.Data()));
2057 TSQLRow* aRow = dynamic_cast<TSQLRow*> (aResult->Next());
2060 Log(detector, Form("GetFile - Empty set result in %s FXS db from query: id = %s, source = %s",
2061 GetSystemName(system), id, sourceName.Data()));
2067 TString filePath(aRow->GetField(0), aRow->GetFieldLength(0));
2068 TString fileSize(aRow->GetField(1), aRow->GetFieldLength(1));
2069 TString fileChecksum(aRow->GetField(2), aRow->GetFieldLength(2));
2074 AliDebug(2, Form("filePath = %s; size = %s, fileChecksum = %s",
2075 filePath.Data(), fileSize.Data(), fileChecksum.Data()));
2077 // retrieved file is renamed to make it unique
2078 TString localFileName = Form("%s/%s_%d_process/%s_%s_%d_%s_%s.shuttle",
2079 GetShuttleTempDir(), detector, GetCurrentRun(),
2080 GetSystemName(system), detector, GetCurrentRun(),
2081 id, sourceName.Data());
2084 // file retrieval from FXS
2085 UInt_t nRetries = 0;
2086 UInt_t maxRetries = 3;
2087 Bool_t result = kFALSE;
2089 // copy!! if successful TSystem::Exec returns 0
2090 while (nRetries++ < maxRetries) {
2091 AliDebug(2, Form("Trying to copy file. Retry # %d", nRetries));
2092 result = RetrieveFile(system, filePath.Data(), localFileName.Data());
2095 Log(detector, Form("GetFile - Copy of file %s from %s FXS failed",
2096 filePath.Data(), GetSystemName(system)));
2100 if (fileSize.Length()>0)
2102 // compare filesize of local file with the one stored in the FXS DB
2104 Int_t sizeComp = gSystem->GetPathInfo(localFileName.Data(), 0, &size, 0, 0);
2106 if (sizeComp != 0 || size != fileSize.Atoi())
2108 Log(detector, Form("GetFile - size of file %s does not match with local copy!",
2115 Log(fCurrentDetector, Form("GetFile - size of file %s not set in %s database, skipping comparison",
2116 filePath.Data(), GetSystemName(system)));
2119 if (fileChecksum.Length()>0)
2121 // compare md5sum of local file with the one stored in the FXS DB
2122 if(fileChecksum.Contains(' ')) fileChecksum.Resize(fileChecksum.First(' '));
2123 Int_t md5Comp = gSystem->Exec(Form("md5sum %s |grep %s > /dev/null 2> /dev/null",
2124 localFileName.Data(), fileChecksum.Data()));
2128 Log(detector, Form("GetFile - md5sum of file %s does not match with local copy!",
2134 Log(fCurrentDetector, Form("GetFile - md5sum of file %s not set in %s database, skipping comparison",
2135 filePath.Data(), GetSystemName(system)));
2146 fFXSCalled[system]=kTRUE;
2147 TObjString *fileParams = new TObjString(Form("%s#!?!#%s", id, sourceName.Data()));
2148 fFXSlist[system].Add(fileParams);
2150 static TString staticLocalFileName;
2151 staticLocalFileName.Form("%s", localFileName.Data());
2153 Log(fCurrentDetector, Form("GetFile - Retrieved file with id %s and "
2154 "source %s from %s to %s", id, source,
2155 GetSystemName(system), localFileName.Data()));
2157 return staticLocalFileName.Data();
2160 //______________________________________________________________________________________________
2161 Bool_t AliShuttle::RetrieveFile(UInt_t system, const char* fxsFileName, const char* localFileName)
2164 // Copies file from FXS to local Shuttle machine
2167 // check temp directory: trying to cd to temp; if it does not exist, create it
2168 AliDebug(2, Form("Copy file %s from %s FXS into %s",
2169 GetSystemName(system), fxsFileName, localFileName));
2171 TString tmpDir(localFileName);
2173 tmpDir = tmpDir(0,tmpDir.Last('/'));
2175 Int_t noDir = gSystem->GetPathInfo(tmpDir.Data(), 0, (Long64_t*) 0, 0, 0);
2176 if (noDir) // temp dir does not exists!
2178 if (gSystem->mkdir(tmpDir.Data(), 1))
2180 Log(fCurrentDetector.Data(), "RetrieveFile - could not make temp directory!!");
2185 TString command = Form("scp -oPort=%d -2 %s@%s:%s/%s %s",
2186 fConfig->GetFXSPort(system),
2187 fConfig->GetFXSUser(system),
2188 fConfig->GetFXSHost(system),
2189 fConfig->GetFXSBaseFolder(system),
2193 AliDebug(2, Form("%s",command.Data()));
2195 Bool_t result = (gSystem->Exec(command.Data()) == 0);
2200 //______________________________________________________________________________________________
2201 TList* AliShuttle::GetFileSources(Int_t system, const char* detector, const char* id)
2204 // Get sources producing the condition file Id from file exchange servers
2205 // if id is NULL all sources are returned (distinct)
2210 Log(detector, Form("GetFileSources - Querying %s FXS for files with id %s produced by %s", GetSystemName(system), id, detector));
2212 Log(detector, Form("GetFileSources - Querying %s FXS for files produced by %s", GetSystemName(system), detector));
2215 // check if test mode should simulate a FXS error
2216 if (fTestMode & kErrorFXSSources)
2218 Log(detector, Form("GetFileSources - In TESTMODE - Simulating error while connecting to %s FXS", GetSystemName(system)));
2224 Log(detector, "GetFileSources - WARNING: DCS system has only one source of data!");
2225 TList *list = new TList();
2227 list->Add(new TObjString(" "));
2231 // check connection, in case connect
2232 if (!Connect(system))
2234 Log(detector, Form("GetFileSources - Couldn't connect to %s FXS database", GetSystemName(system)));
2239 TString sourceName = 0;
2242 sourceName = "DAQsource";
2243 } else if (system == kHLT)
2245 sourceName = "DDLnumbers";
2248 TString sqlQueryStart = Form("select distinct %s from %s where", sourceName.Data(), fConfig->GetFXSdbTable(system));
2249 TString whereClause = Form("run=%d and detector=\"%s\"",
2250 GetCurrentRun(), detector);
2252 whereClause += Form(" and fileId=\"%s\"", id);
2253 TString sqlQuery = Form("%s %s", sqlQueryStart.Data(), whereClause.Data());
2255 AliDebug(2, Form("SQL query: \n%s",sqlQuery.Data()));
2258 TSQLResult* aResult;
2259 aResult = fServer[system]->Query(sqlQuery);
2261 Log(detector, Form("GetFileSources - Can't execute SQL query to %s database for id: %s",
2262 GetSystemName(system), id));
2267 TList *list = new TList();
2270 if (aResult->GetRowCount() == 0)
2273 Form("GetFileSources - No entry in %s FXS table for id: %s", GetSystemName(system), id));
2278 Log(detector, Form("GetFileSources - Found %d sources", aResult->GetRowCount()));
2281 while ((aRow = aResult->Next()))
2284 TString source(aRow->GetField(0), aRow->GetFieldLength(0));
2285 AliDebug(2, Form("%s = %s", sourceName.Data(), source.Data()));
2286 list->Add(new TObjString(source));
2295 //______________________________________________________________________________________________
2296 TList* AliShuttle::GetFileIDs(Int_t system, const char* detector, const char* source)
2299 // Get all ids of condition files produced by a given source from file exchange servers
2302 Log(detector, Form("GetFileIDs - Retrieving ids with source %s with %s", source, GetSystemName(system)));
2304 // check if test mode should simulate a FXS error
2305 if (fTestMode & kErrorFXSSources)
2307 Log(detector, Form("GetFileIDs - In TESTMODE - Simulating error while connecting to %s FXS", GetSystemName(system)));
2311 // check connection, in case connect
2312 if (!Connect(system))
2314 Log(detector, Form("GetFileIDs - Couldn't connect to %s FXS database", GetSystemName(system)));
2318 TString sourceName = 0;
2321 sourceName = "DAQsource";
2322 } else if (system == kHLT)
2324 sourceName = "DDLnumbers";
2327 TString sqlQueryStart = Form("select fileId from %s where", fConfig->GetFXSdbTable(system));
2328 TString whereClause = Form("run=%d and detector=\"%s\"",
2329 GetCurrentRun(), detector);
2330 if (sourceName.Length() > 0 && source)
2331 whereClause += Form(" and %s=\"%s\"", sourceName.Data(), source);
2332 TString sqlQuery = Form("%s %s", sqlQueryStart.Data(), whereClause.Data());
2334 AliDebug(2, Form("SQL query: \n%s",sqlQuery.Data()));
2337 TSQLResult* aResult;
2338 aResult = fServer[system]->Query(sqlQuery);
2340 Log(detector, Form("GetFileIDs - Can't execute SQL query to %s database for source: %s",
2341 GetSystemName(system), source));
2345 TList *list = new TList();
2348 if (aResult->GetRowCount() == 0)
2351 Form("GetFileIDs - No entry in %s FXS table for source: %s", GetSystemName(system), source));
2356 Log(detector, Form("GetFileIDs - Found %d ids", aResult->GetRowCount()));
2360 while ((aRow = aResult->Next()))
2363 TString id(aRow->GetField(0), aRow->GetFieldLength(0));
2364 AliDebug(2, Form("fileId = %s", id.Data()));
2365 list->Add(new TObjString(id));
2374 //______________________________________________________________________________________________
2375 Bool_t AliShuttle::Connect(Int_t system)
2377 // Connect to MySQL Server of the system's FXS MySQL databases
2378 // DAQ Logbook, Shuttle Logbook and DAQ FXS db are on the same host
2381 // check connection: if already connected return
2382 if(fServer[system] && fServer[system]->IsConnected()) return kTRUE;
2384 TString dbHost, dbUser, dbPass, dbName;
2386 if (system < 3) // FXS db servers
2388 dbHost = Form("mysql://%s:%d", fConfig->GetFXSdbHost(system), fConfig->GetFXSdbPort(system));
2389 dbUser = fConfig->GetFXSdbUser(system);
2390 dbPass = fConfig->GetFXSdbPass(system);
2391 dbName = fConfig->GetFXSdbName(system);
2392 } else { // Run & Shuttle logbook servers
2393 // TODO Will the Shuttle logbook server be the same as the Run logbook server ???
2394 dbHost = Form("mysql://%s:%d", fConfig->GetDAQlbHost(), fConfig->GetDAQlbPort());
2395 dbUser = fConfig->GetDAQlbUser();
2396 dbPass = fConfig->GetDAQlbPass();
2397 dbName = fConfig->GetDAQlbDB();
2400 fServer[system] = TSQLServer::Connect(dbHost.Data(), dbUser.Data(), dbPass.Data());
2401 if (!fServer[system] || !fServer[system]->IsConnected()) {
2404 AliError(Form("Can't establish connection to FXS database for %s",
2405 AliShuttleInterface::GetSystemName(system)));
2407 AliError("Can't establish connection to Run logbook.");
2409 if(fServer[system]) delete fServer[system];
2414 TSQLResult* aResult=0;
2417 aResult = fServer[kDAQ]->GetTables(dbName.Data());
2420 aResult = fServer[kDCS]->GetTables(dbName.Data());
2423 aResult = fServer[kHLT]->GetTables(dbName.Data());
2426 aResult = fServer[3]->GetTables(dbName.Data());
2434 //______________________________________________________________________________________________
2435 Bool_t AliShuttle::UpdateTable()
2438 // Update FXS table filling time_processed field in all rows corresponding to current run and detector
2441 Bool_t result = kTRUE;
2443 for (UInt_t system=0; system<3; system++)
2445 if(!fFXSCalled[system]) continue;
2447 // check connection, in case connect
2448 if (!Connect(system))
2450 Log(fCurrentDetector, Form("UpdateTable - Couldn't connect to %s FXS database", GetSystemName(system)));
2455 TTimeStamp now; // now
2457 // Loop on FXS list entries
2458 TIter iter(&fFXSlist[system]);
2459 TObjString *aFXSentry=0;
2460 while ((aFXSentry = dynamic_cast<TObjString*> (iter.Next())))
2462 TString aFXSentrystr = aFXSentry->String();
2463 TObjArray *aFXSarray = aFXSentrystr.Tokenize("#!?!#");
2464 if (!aFXSarray || aFXSarray->GetEntries() != 2 )
2466 Log(fCurrentDetector, Form("UpdateTable - error updating %s FXS entry. Check string: <%s>",
2467 GetSystemName(system), aFXSentrystr.Data()));
2468 if(aFXSarray) delete aFXSarray;
2472 const char* fileId = ((TObjString*) aFXSarray->At(0))->GetName();
2473 const char* source = ((TObjString*) aFXSarray->At(1))->GetName();
2475 TString whereClause;
2478 whereClause = Form("where run=%d and detector=\"%s\" and fileId=\"%s\" and DAQsource=\"%s\";",
2479 GetCurrentRun(), fCurrentDetector.Data(), fileId, source);
2481 else if (system == kDCS)
2483 whereClause = Form("where run=%d and detector=\"%s\" and fileId=\"%s\";",
2484 GetCurrentRun(), fCurrentDetector.Data(), fileId);
2486 else if (system == kHLT)
2488 whereClause = Form("where run=%d and detector=\"%s\" and fileId=\"%s\" and DDLnumbers=\"%s\";",
2489 GetCurrentRun(), fCurrentDetector.Data(), fileId, source);
2494 TString sqlQuery = Form("update %s set time_processed=%d %s", fConfig->GetFXSdbTable(system),
2495 now.GetSec(), whereClause.Data());
2497 AliDebug(2, Form("SQL query: \n%s",sqlQuery.Data()));
2500 TSQLResult* aResult;
2501 aResult = dynamic_cast<TSQLResult*> (fServer[system]->Query(sqlQuery));
2504 Log(fCurrentDetector, Form("UpdateTable - %s db: can't execute SQL query <%s>",
2505 GetSystemName(system), sqlQuery.Data()));
2516 //______________________________________________________________________________________________
2517 Bool_t AliShuttle::UpdateTableFailCase()
2519 // Update FXS table filling time_processed field in all rows corresponding to current run and detector
2520 // this is called in case the preprocessor is declared failed for the current run, because
2521 // the fields are updated only in case of success
2523 Bool_t result = kTRUE;
2525 for (UInt_t system=0; system<3; system++)
2527 // check connection, in case connect
2528 if (!Connect(system))
2530 Log(fCurrentDetector, Form("UpdateTableFailCase - Couldn't connect to %s FXS database",
2531 GetSystemName(system)));
2536 TTimeStamp now; // now
2538 // Loop on FXS list entries
2540 TString whereClause = Form("where run=%d and detector=\"%s\";",
2541 GetCurrentRun(), fCurrentDetector.Data());
2544 TString sqlQuery = Form("update %s set time_processed=%d %s", fConfig->GetFXSdbTable(system),
2545 now.GetSec(), whereClause.Data());
2547 AliDebug(2, Form("SQL query: \n%s",sqlQuery.Data()));
2550 TSQLResult* aResult;
2551 aResult = dynamic_cast<TSQLResult*> (fServer[system]->Query(sqlQuery));
2554 Log(fCurrentDetector, Form("UpdateTableFailCase - %s db: can't execute SQL query <%s>",
2555 GetSystemName(system), sqlQuery.Data()));
2565 //______________________________________________________________________________________________
2566 Bool_t AliShuttle::UpdateShuttleLogbook(const char* detector, const char* status)
2569 // Update Shuttle logbook filling detector or shuttle_done column
2570 // ex. of usage: UpdateShuttleLogbook("PHOS", "DONE") or UpdateShuttleLogbook("shuttle_done")
2573 // check connection, in case connect
2575 Log("SHUTTLE", "UpdateShuttleLogbook - Couldn't connect to DAQ Logbook.");
2579 TString detName(detector);
2581 if (detName == "shuttle_done" || detName == "shuttle_ignored")
2583 setClause = "set shuttle_done=1";
2585 if (detName == "shuttle_done")
2587 // Send the information to ML
2588 TMonaLisaText mlStatus("SHUTTLE_status", "Done");
2591 mlList.Add(&mlStatus);
2594 mlID.Form("%d", GetCurrentRun());
2595 fMonaLisa->SendParameters(&mlList, mlID);
2598 TString statusStr(status);
2599 if(statusStr.Contains("done", TString::kIgnoreCase) ||
2600 statusStr.Contains("failed", TString::kIgnoreCase)){
2601 setClause = Form("set %s=\"%s\"", detector, status);
2604 Form("UpdateShuttleLogbook - Invalid status <%s> for detector %s",
2610 TString whereClause = Form("where run=%d", GetCurrentRun());
2612 TString sqlQuery = Form("update %s %s %s",
2613 fConfig->GetShuttlelbTable(), setClause.Data(), whereClause.Data());
2615 AliDebug(2, Form("SQL query: \n%s",sqlQuery.Data()));
2618 TSQLResult* aResult;
2619 aResult = dynamic_cast<TSQLResult*> (fServer[3]->Query(sqlQuery));
2621 Log("SHUTTLE", Form("UpdateShuttleLogbook - Can't execute query <%s>", sqlQuery.Data()));
2629 //______________________________________________________________________________________________
2630 Int_t AliShuttle::GetCurrentRun() const
2633 // Get current run from logbook entry
2636 return fLogbookEntry ? fLogbookEntry->GetRun() : -1;
2639 //______________________________________________________________________________________________
2640 UInt_t AliShuttle::GetCurrentStartTime() const
2643 // get current start time
2646 return fLogbookEntry ? fLogbookEntry->GetStartTime() : 0;
2649 //______________________________________________________________________________________________
2650 UInt_t AliShuttle::GetCurrentEndTime() const
2653 // get current end time from logbook entry
2656 return fLogbookEntry ? fLogbookEntry->GetEndTime() : 0;
2659 //______________________________________________________________________________________________
2660 UInt_t AliShuttle::GetCurrentYear() const
2663 // Get current year from logbook entry
2666 if (!fLogbookEntry) return 0;
2668 TTimeStamp startTime(GetCurrentStartTime());
2669 TString year = Form("%d",startTime.GetDate());
2675 //______________________________________________________________________________________________
2676 const char* AliShuttle::GetLHCPeriod() const
2679 // Get current LHC period from logbook entry
2682 if (!fLogbookEntry) return 0;
2684 return fLogbookEntry->GetRunParameter("LHCperiod");
2687 //______________________________________________________________________________________________
2688 void AliShuttle::Log(const char* detector, const char* message)
2691 // Fill log string with a message
2694 TString logRunDir = GetShuttleLogDir();
2695 if (GetCurrentRun() >=0)
2696 logRunDir += Form("/%d", GetCurrentRun());
2698 void* dir = gSystem->OpenDirectory(logRunDir.Data());
2700 if (gSystem->mkdir(logRunDir.Data(), kTRUE)) {
2701 AliError(Form("Can't open directory <%s>", GetShuttleLogDir()));
2706 gSystem->FreeDirectory(dir);
2709 TString toLog = Form("%s (%d): %s - ", TTimeStamp(time(0)).AsString("s"), getpid(), detector);
2710 if (GetCurrentRun() >= 0)
2711 toLog += Form("run %d - ", GetCurrentRun());
2712 toLog += Form("%s", message);
2714 AliInfo(toLog.Data());
2716 // if we redirect the log output already to the file, leave here
2717 if (fOutputRedirected && strcmp(detector, "SHUTTLE") != 0)
2720 TString fileName = GetLogFileName(detector);
2722 gSystem->ExpandPathName(fileName);
2725 logFile.open(fileName, ofstream::out | ofstream::app);
2727 if (!logFile.is_open()) {
2728 AliError(Form("Could not open file %s", fileName.Data()));
2732 logFile << toLog.Data() << "\n";
2737 //______________________________________________________________________________________________
2738 TString AliShuttle::GetLogFileName(const char* detector) const
2741 // returns the name of the log file for a given sub detector
2746 if (GetCurrentRun() >= 0)
2748 fileName.Form("%s/%d/%s_%d.log", GetShuttleLogDir(), GetCurrentRun(),
2749 detector, GetCurrentRun());
2751 fileName.Form("%s/%s.log", GetShuttleLogDir(), detector);
2757 //______________________________________________________________________________________________
2758 void AliShuttle::SendAlive()
2760 // sends alive message to ML
2762 TMonaLisaText mlStatus("SHUTTLE_status", "Alive");
2765 mlList.Add(&mlStatus);
2767 fMonaLisa->SendParameters(&mlList, "__PROCESSINGINFO__");
2770 //______________________________________________________________________________________________
2771 Bool_t AliShuttle::Collect(Int_t run)
2774 // Collects conditions data for all UNPROCESSED run written to DAQ LogBook in case of run = -1 (default)
2775 // If a dedicated run is given this run is processed
2777 // In operational mode, this is the Shuttle function triggered by the EOR signal.
2781 Log("SHUTTLE","Collect - Shuttle called. Collecting conditions data for unprocessed runs");
2783 Log("SHUTTLE", Form("Collect - Shuttle called. Collecting conditions data for run %d", run));
2785 SetLastAction("Starting");
2787 // create ML instance
2789 fMonaLisa = new TMonaLisaWriter(fConfig->GetMonitorHost(), fConfig->GetMonitorTable());
2794 TString whereClause("where shuttle_done=0");
2796 whereClause += Form(" and run=%d", run);
2798 TObjArray shuttleLogbookEntries;
2799 if (!QueryShuttleLogbook(whereClause, shuttleLogbookEntries))
2801 Log("SHUTTLE", "Collect - Can't retrieve entries from Shuttle logbook");
2805 if (shuttleLogbookEntries.GetEntries() == 0)
2808 Log("SHUTTLE","Collect - Found no UNPROCESSED runs in Shuttle logbook");
2810 Log("SHUTTLE", Form("Collect - Run %d is already DONE "
2811 "or it does not exist in Shuttle logbook", run));
2815 for (UInt_t iDet=0; iDet<NDetectors(); iDet++)
2816 fFirstUnprocessed[iDet] = kTRUE;
2820 // query Shuttle logbook for earlier runs, check if some detectors are unprocessed,
2821 // flag them into fFirstUnprocessed array
2822 TString whereClause(Form("where shuttle_done=0 and run < %d", run));
2823 TObjArray tmpLogbookEntries;
2824 if (!QueryShuttleLogbook(whereClause, tmpLogbookEntries))
2826 Log("SHUTTLE", "Collect - Can't retrieve entries from Shuttle logbook");
2830 TIter iter(&tmpLogbookEntries);
2831 AliShuttleLogbookEntry* anEntry = 0;
2832 while ((anEntry = dynamic_cast<AliShuttleLogbookEntry*> (iter.Next())))
2834 for (UInt_t iDet=0; iDet<NDetectors(); iDet++)
2836 if (anEntry->GetDetectorStatus(iDet) == AliShuttleLogbookEntry::kUnprocessed)
2838 AliDebug(2, Form("Run %d: setting %s as \"not first time unprocessed\"",
2839 anEntry->GetRun(), GetDetName(iDet)));
2840 fFirstUnprocessed[iDet] = kFALSE;
2848 if (!RetrieveConditionsData(shuttleLogbookEntries))
2850 Log("SHUTTLE", "Collect - Process of at least one run failed");
2855 Log("SHUTTLE", "Collect - Requested run(s) successfully processed");
2860 //______________________________________________________________________________________________
2861 Bool_t AliShuttle::RetrieveConditionsData(const TObjArray& dateEntries)
2864 // Retrieve conditions data for all runs that aren't processed yet
2867 Bool_t hasError = kFALSE;
2869 TIter iter(&dateEntries);
2870 AliShuttleLogbookEntry* anEntry;
2872 while ((anEntry = (AliShuttleLogbookEntry*) iter.Next())){
2873 if (!Process(anEntry)){
2877 // clean SHUTTLE temp directory
2878 //TString filename = Form("%s/*.shuttle", GetShuttleTempDir());
2879 //RemoveFile(filename.Data());
2882 return hasError == kFALSE;
2885 //______________________________________________________________________________________________
2886 ULong_t AliShuttle::GetTimeOfLastAction() const
2889 // Gets time of last action
2894 fMonitoringMutex->Lock();
2896 tmp = fLastActionTime;
2898 fMonitoringMutex->UnLock();
2903 //______________________________________________________________________________________________
2904 const TString AliShuttle::GetLastAction() const
2907 // returns a string description of the last action
2912 fMonitoringMutex->Lock();
2916 fMonitoringMutex->UnLock();
2921 //______________________________________________________________________________________________
2922 void AliShuttle::SetLastAction(const char* action)
2925 // updates the monitoring variables
2928 fMonitoringMutex->Lock();
2930 fLastAction = action;
2931 fLastActionTime = time(0);
2933 fMonitoringMutex->UnLock();
2936 //______________________________________________________________________________________________
2937 const char* AliShuttle::GetRunParameter(const char* param)
2940 // returns run parameter read from DAQ logbook
2943 if(!fLogbookEntry) {
2944 AliError("No logbook entry!");
2948 return fLogbookEntry->GetRunParameter(param);
2951 //______________________________________________________________________________________________
2952 AliCDBEntry* AliShuttle::GetFromOCDB(const char* detector, const AliCDBPath& path)
2955 // returns object from OCDB valid for current run
2958 if (fTestMode & kErrorOCDB)
2960 Log(detector, "GetFromOCDB - In TESTMODE - Simulating error with OCDB");
2964 AliCDBStorage *sto = AliCDBManager::Instance()->GetStorage(fgkMainCDB);
2967 Log(detector, "GetFromOCDB - Cannot activate main OCDB for query!");
2971 return dynamic_cast<AliCDBEntry*> (sto->Get(path, GetCurrentRun()));
2974 //______________________________________________________________________________________________
2975 Bool_t AliShuttle::SendMail(EMailTarget target, Int_t system)
2978 // sends a mail to the subdetector expert in case of preprocessor error
2981 if (fTestMode != kNone)
2984 if (!fConfig->SendMail())
2987 if (target == kDCSEMail || target == kFXSEMail) {
2988 if (!fFirstProcessing)
2992 void* dir = gSystem->OpenDirectory(GetShuttleLogDir());
2995 if (gSystem->mkdir(GetShuttleLogDir(), kTRUE))
2997 Log("SHUTTLE", Form("SendMail - Can't open directory <%s>", GetShuttleLogDir()));
3002 gSystem->FreeDirectory(dir);
3005 // det experts in to
3008 if (target == kDCSEMail) {
3009 iterExperts = new TIter(fConfig->GetAdmins(AliShuttleConfig::kAmanda));
3011 else if (target == kFXSEMail) {
3012 iterExperts = new TIter(fConfig->GetAdmins(system));
3015 iterExperts = new TIter(fConfig->GetResponsibles(fCurrentDetector));
3017 TObjString *anExpert=0;
3018 while ((anExpert = (TObjString*) iterExperts->Next()))
3020 to += Form("%s,", anExpert->GetName());
3023 if (to.Length() > 0)
3024 to.Remove(to.Length()-1);
3025 AliDebug(2, Form("to: %s",to.Data()));
3028 Log("SHUTTLE", Form("List of %d responsibles not set!", (Int_t) target));
3032 // SHUTTLE responsibles in cc
3034 TIter iterAdmins(fConfig->GetAdmins(AliShuttleConfig::kGlobal));
3035 TObjString *anAdmin=0;
3036 while ((anAdmin = (TObjString*) iterAdmins.Next()))
3038 cc += Form("%s,", anAdmin->GetName());
3040 if (cc.Length() > 0)
3041 cc.Remove(cc.Length()-1);
3042 AliDebug(2, Form("cc: %s",to.Data()));
3045 TString bodyFileName;
3046 bodyFileName.Form("%s/mail.body", GetShuttleLogDir());
3047 gSystem->ExpandPathName(bodyFileName);
3050 mailBody.open(bodyFileName, ofstream::out);
3052 if (!mailBody.is_open())
3054 Log("SHUTTLE", Form("Could not open mail body file %s", bodyFileName.Data()));
3062 if (target == kDCSEMail){
3063 subject = Form("Retrieval of data points for %s FAILED in run %d !",
3064 fCurrentDetector.Data(), GetCurrentRun());
3065 AliDebug(2, Form("subject: %s", subject.Data()));
3067 body = Form("Dear DCS experts, \n\n");
3068 body += Form("SHUTTLE couldn\'t retrieve the data points for detector %s "
3069 "in run %d!!\n\n", fCurrentDetector.Data(), GetCurrentRun());
3071 else if (target == kFXSEMail){
3072 subject = Form("FXS communication for %s FAILED in run %d !",
3073 fCurrentDetector.Data(), GetCurrentRun());
3074 AliDebug(2, Form("subject: %s", subject.Data()));
3076 if (system == kDAQ) sys="DAQ";
3077 else if (system == kDCS) sys="DCS";
3078 else if (system == kHLT) sys="HLT";
3080 body = Form("Dear %s FXS experts, \n\n",sys.Data());
3081 body += Form("SHUTTLE couldn\'t retrieve data from the FXS for detector %s "
3082 "in run %d!!\n\n", fCurrentDetector.Data(), GetCurrentRun());
3085 subject = Form("%s Shuttle preprocessor FAILED in run %d (run type = %s)!",
3086 fCurrentDetector.Data(), GetCurrentRun(), GetRunType());
3087 AliDebug(2, Form("subject: %s", subject.Data()));
3089 body = Form("Dear %s expert(s), \n\n", fCurrentDetector.Data());
3090 body += Form("SHUTTLE just detected that your preprocessor "
3091 "failed processing run %d (run type = %s)!!\n\n",
3092 GetCurrentRun(), GetRunType());
3095 body += Form("Please check %s status on the SHUTTLE monitoring page: \n\n",
3096 fCurrentDetector.Data());
3097 if (fConfig->GetRunMode() == AliShuttleConfig::kTest)
3099 body += Form("\thttp://pcalimonitor.cern.ch:8889/shuttle.jsp?time=168 \n\n");
3101 body += Form("\thttp://pcalimonitor.cern.ch/shuttle.jsp?instance=PROD&time=168 \n\n");
3105 TString logFolder = "logs";
3106 if (fConfig->GetRunMode() == AliShuttleConfig::kProd)
3107 logFolder += "_PROD";
3110 body += Form("Find the %s log for the current run on \n\n"
3111 "\thttp://pcalishuttle01.cern.ch:8880/%s/%d/%s_%d.log \n\n",
3112 fCurrentDetector.Data(), logFolder.Data(), GetCurrentRun(),
3113 fCurrentDetector.Data(), GetCurrentRun());
3114 body += Form("The last 10 lines of %s log file are following:\n\n", fCurrentDetector.Data());
3116 AliDebug(2, Form("Body begin: %s", body.Data()));
3118 mailBody << body.Data();
3120 mailBody.open(bodyFileName, ofstream::out | ofstream::app);
3122 TString logFileName = Form("%s/%d/%s_%d.log", GetShuttleLogDir(),
3123 GetCurrentRun(), fCurrentDetector.Data(), GetCurrentRun());
3124 TString tailCommand = Form("tail -n 10 %s >> %s", logFileName.Data(), bodyFileName.Data());
3125 if (gSystem->Exec(tailCommand.Data()))
3127 mailBody << Form("%s log file not found ...\n\n", fCurrentDetector.Data());
3130 TString endBody = Form("------------------------------------------------------\n\n");
3131 endBody += Form("In case of problems please contact the SHUTTLE core team.\n\n");
3132 endBody += "Please do not answer this message directly, it is automatically generated.\n\n";
3133 endBody += "Greetings,\n\n \t\t\tthe SHUTTLE\n";
3135 AliDebug(2, Form("Body end: %s", endBody.Data()));
3137 mailBody << endBody.Data();
3142 TString mailCommand = Form("mail -s \"%s\" -c %s %s < %s",
3146 bodyFileName.Data());
3147 AliDebug(2, Form("mail command: %s", mailCommand.Data()));
3149 Bool_t result = gSystem->Exec(mailCommand.Data());
3154 //______________________________________________________________________________________________
3155 const char* AliShuttle::GetRunType()
3158 // returns run type read from "run type" logbook
3161 if(!fLogbookEntry) {
3162 AliError("No logbook entry!");
3166 return fLogbookEntry->GetRunType();
3169 //______________________________________________________________________________________________
3170 Bool_t AliShuttle::GetHLTStatus()
3172 // Return HLT status (ON=1 OFF=0)
3173 // Converts the HLT status from the mode string read in the run logbook (not just a bool)
3175 if(!fLogbookEntry) {
3176 AliError("No logbook entry!");
3180 // TODO implement when HLTMode is inserted in run logbook
3181 TString hltMode = fLogbookEntry->GetRunParameter("HLTMode");
3182 TSubString firstChar = hltMode(0,1);
3183 AliDebug(2,Form("First char = %s ",firstChar.Data()));
3184 if (firstChar == "A") {
3187 else if ((firstChar == "B") || (firstChar == "C") || (firstChar == "D") || (firstChar == "E")) {
3191 Log("SHUTTLE","Unexpected HLT mode! Returning 0....");
3195 //______________________________________________________________________________________________
3196 void AliShuttle::SetShuttleTempDir(const char* tmpDir)
3199 // sets Shuttle temp directory
3202 fgkShuttleTempDir = gSystem->ExpandPathName(tmpDir);
3205 //______________________________________________________________________________________________
3206 void AliShuttle::SetShuttleLogDir(const char* logDir)
3209 // sets Shuttle log directory
3212 fgkShuttleLogDir = gSystem->ExpandPathName(logDir);