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<5;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<5;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
204 if (fTestMode & kErrorStorage)
206 Log(fCurrentDetector, "StoreLocally - In TESTMODE - Simulating error while storing locally");
210 const char* cdbType = (localUri == fgkLocalCDB) ? "CDB" : "Reference";
212 Int_t firstRun = GetCurrentRun() - validityStart;
214 AliWarning("First valid run happens to be less than 0! Setting it to 0.");
219 if(validityInfinite) {
220 lastRun = AliCDBRunRange::Infinity();
222 lastRun = GetCurrentRun();
225 // Version is set to current run, it will be used later to transfer data to Grid
226 AliCDBId id(path, firstRun, lastRun, GetCurrentRun(), -1);
228 if(! dynamic_cast<TObjString*> (metaData->GetProperty("RunUsed(TObjString)"))){
229 TObjString runUsed = Form("%d", GetCurrentRun());
230 metaData->SetProperty("RunUsed(TObjString)", runUsed.Clone());
233 Bool_t result = kFALSE;
235 if (!(AliCDBManager::Instance()->GetStorage(localUri))) {
236 Log("SHUTTLE", Form("StoreLocally - Cannot activate local %s storage", cdbType));
238 Int_t logLevel = AliLog::GetGlobalLogLevel();
239 AliLog::SetGlobalLogLevel(AliLog::kError);
240 result = AliCDBManager::Instance()->GetStorage(localUri)
241 ->Put(object, id, metaData);
242 AliLog::SetGlobalLogLevel((AliLog::EType_t)logLevel);
247 Log(fCurrentDetector, Form("StoreLocally - Can't store object <%s>!", id.ToString().Data()));
254 //______________________________________________________________________________________________
255 Bool_t AliShuttle::StoreOCDB()
258 // Called when preprocessor ends successfully or when previous storage attempt failed (kStoreError status)
259 // Calls underlying StoreOCDB(const char*) function twice, for OCDB and Reference storage.
260 // Then calls StoreRefFilesToGrid to store reference files.
263 UpdateShuttleStatus(AliShuttleStatus::kStoreStarted);
265 if (fTestMode & kErrorGrid)
267 Log("SHUTTLE", "StoreOCDB - In TESTMODE - Simulating error while storing in the Grid");
268 Log(fCurrentDetector, "StoreOCDB - In TESTMODE - Simulating error while storing in the Grid");
272 Log("SHUTTLE","StoreOCDB - Storing OCDB data ...");
273 Int_t resultCDB = StoreOCDB(fgkMainCDB);
275 Log("SHUTTLE","StoreOCDB - Storing reference data ...");
276 Int_t resultRef = StoreOCDB(fgkMainRefStorage);
278 Log("SHUTTLE","StoreOCDB - Storing reference files ...");
279 Bool_t resultRefFiles = CopyFilesToGrid("reference");
281 Bool_t resultMetadata = kTRUE;
282 if(fCurrentDetector == "GRP")
284 Log("SHUTTLE","StoreOCDB - Storing Run Metadata file ...");
285 resultMetadata = CopyFilesToGrid("metadata");
288 Int_t storeResult = 0;
290 if (resultCDB < 0 || resultRef < 0 || resultRefFiles == kFALSE || resultMetadata == kFALSE)
292 else if (resultCDB > 0 || resultRef > 0)
298 Form("\t\t\t****** run %d - %s: STORAGE ERROR ******",
299 GetCurrentRun(), fCurrentDetector.Data()));
300 UpdateShuttleStatus(AliShuttleStatus::kStoreError);
302 else if (storeResult > 0)
305 Form("\t\t\t****** run %d - %s: STORAGE DELAYED ******",
306 GetCurrentRun(), fCurrentDetector.Data()));
307 UpdateShuttleStatus(AliShuttleStatus::kStoreDelayed);
309 else if (storeResult == 0)
312 Form("\t\t\t****** run %d - %s: DONE ******",
313 GetCurrentRun(), fCurrentDetector.Data()));
314 UpdateShuttleStatus(AliShuttleStatus::kDone);
315 UpdateShuttleLogbook(fCurrentDetector, "DONE");
318 return (storeResult == 0);
321 //______________________________________________________________________________________________
322 Int_t AliShuttle::StoreOCDB(const TString& gridURI)
325 // Called by StoreOCDB(), performs actual storage to the main OCDB and reference storages (Grid)
328 // -2 initialization error
331 // 1 storage delayed (e.g. previous unprocessed runs)
334 TObjArray* gridIds=0;
336 Bool_t result = kTRUE;
337 Bool_t delayed = kFALSE;
339 const char* type = 0;
341 if(gridURI == fgkMainCDB) {
343 localURI = fgkLocalCDB;
344 } else if(gridURI == fgkMainRefStorage) {
346 localURI = fgkLocalRefStorage;
348 AliError(Form("Invalid storage URI: %s", gridURI.Data()));
352 AliCDBManager* man = AliCDBManager::Instance();
354 AliCDBStorage *gridSto = man->GetStorage(gridURI);
357 Form("StoreOCDB - cannot activate main %s storage", type));
360 gridSto->SetMirrorSEs(fgkMirrorSEs.Data());
362 gridIds = gridSto->GetQueryCDBList();
364 // get objects previously stored in local CDB
365 AliCDBStorage *localSto = man->GetStorage(localURI);
368 Form("StoreOCDB - cannot activate local %s storage", type));
371 AliCDBPath aPath(GetOfflineDetName(fCurrentDetector.Data()),"*","*");
372 // Local objects were stored with current run as Grid version!
373 TList* localEntries = localSto->GetAll(aPath.GetPath(), GetCurrentRun(), GetCurrentRun());
374 localEntries->SetOwner(1);
376 // loop on local stored objects
377 TIter localIter(localEntries);
378 AliCDBEntry *aLocEntry = 0;
379 while((aLocEntry = dynamic_cast<AliCDBEntry*> (localIter.Next()))){
380 aLocEntry->SetOwner(1);
381 AliCDBId aLocId = aLocEntry->GetId();
382 aLocEntry->SetVersion(-1);
383 aLocEntry->SetSubVersion(-1);
385 Log(fCurrentDetector.Data(), Form("Attempting to store %s", aLocId.ToString().Data()));
387 // If local object is valid up to infinity we store it only if it is
388 // the first unprocessed run!
389 if (aLocId.GetLastRun() == AliCDBRunRange::Infinity() &&
390 !fFirstUnprocessed[GetDetPos(fCurrentDetector)])
392 Log("SHUTTLE", Form("StoreOCDB - %s: object %s has validity infinite but "
393 "there are previous unprocessed runs!",
394 fCurrentDetector.Data(), aLocId.GetPath().Data()));
395 Log(fCurrentDetector.Data(), Form("StoreOCDB - %s: object %s has validity infinite but "
396 "there are previous unprocessed runs!",
397 fCurrentDetector.Data(), aLocId.GetPath().Data()));
402 // loop on Grid valid Id's
403 Bool_t store = kTRUE;
404 TIter gridIter(gridIds);
405 AliCDBId* aGridId = 0;
406 while ((aGridId = dynamic_cast<AliCDBId*> (gridIter.Next()))) {
407 if (aGridId->GetPath() != aLocId.GetPath())
409 // skip all objects valid up to infinity
410 if (aGridId->GetLastRun() == AliCDBRunRange::Infinity())
413 // if we get here, it means there's already some more recent object stored on Grid!
414 Log(fCurrentDetector.Data(),
415 Form("StoreOCDB - A more recent object already exists in %s storage: <%s>",
416 type, aGridId->ToString().Data()));
422 Bool_t storeOk = kFALSE;
425 Log(fCurrentDetector.Data(), Form("Prechecks succeeded. Ready to store %s", aLocId.ToString().Data()));
426 storeOk = gridSto->Put(aLocEntry);
429 Form("StoreOCDB - Object <%s> successfully put into %s storage",
430 aLocId.ToString().Data(), type));
431 Log(fCurrentDetector.Data(),
432 Form("StoreOCDB - Object <%s> successfully put into %s storage",
433 aLocId.ToString().Data(), type));
436 Form("StoreOCDB - Grid %s storage of object <%s> failed",
437 type, aLocId.ToString().Data()));
438 Log(fCurrentDetector.Data(),
439 Form("StoreOCDB - Grid %s storage of object <%s> failed",
440 type, aLocId.ToString().Data()));
445 if (!store || storeOk) {
446 // removing local file...
448 localSto->IdToFilename(aLocId, filename);
449 Log("SHUTTLE", Form("StoreOCDB - Removing local file %s", filename.Data()));
450 RemoveFile(filename.Data());
453 localEntries->Clear();
455 Int_t returnCode = 0;
457 if (result == kFALSE)
459 else if (delayed != kFALSE)
462 Log("SHUTTLE", Form("StoreOCDB - Returning with %d (result = %d, delayed = %d)", returnCode, result, delayed));
463 Log(fCurrentDetector.Data(), Form("StoreOCDB - Returning with %d (result = %d, delayed = %d)", returnCode, result, delayed));
468 //______________________________________________________________________________________________
469 Bool_t AliShuttle::CleanReferenceStorage(const char* detector)
471 // clears the directory used to store reference files of a given subdetector
473 AliCDBManager* man = AliCDBManager::Instance();
474 AliCDBStorage* sto = man->GetStorage(fgkLocalRefStorage);
475 TString localBaseFolder = sto->GetBaseFolder();
477 TString targetDir = GetRefFilePrefix(localBaseFolder.Data(), detector);
479 Log("SHUTTLE", Form("CleanReferenceStorage - Cleaning %s", targetDir.Data()));
482 begin.Form("%d_", GetCurrentRun());
484 TSystemDirectory* baseDir = new TSystemDirectory("/", targetDir);
488 TList* dirList = baseDir->GetListOfFiles();
491 if (!dirList) return kTRUE;
493 if (dirList->GetEntries() < 3) // to be changed to 4?
499 Int_t nDirs = 0, nDel = 0;
500 TIter dirIter(dirList);
501 TSystemFile* entry = 0;
503 Bool_t success = kTRUE;
505 while ((entry = dynamic_cast<TSystemFile*> (dirIter.Next())))
507 if (entry->IsDirectory())
510 TString fileName(entry->GetName());
511 if (!fileName.BeginsWith(begin))
517 Int_t result = gSystem->Unlink(fileName.Data());
521 Log("SHUTTLE", Form("CleanReferenceStorage - Could not delete file %s!", fileName.Data()));
529 Log("SHUTTLE", Form("CleanReferenceStorage - %d (over %d) reference files in folder %s were deleted.",
530 nDel, nDirs, targetDir.Data()));
541 Int_t result = gSystem->GetPathInfo(targetDir, 0, (Long64_t*) 0, 0, 0);
545 result = gSystem->Exec(Form("rm -rf %s", targetDir.Data()));
548 Log("SHUTTLE", Form("CleanReferenceStorage - Could not clean directory %s", targetDir.Data()));
553 result = gSystem->mkdir(targetDir, kTRUE);
556 Log("SHUTTLE", Form("CleanReferenceStorage - Error creating base directory %s", targetDir.Data()));
563 //______________________________________________________________________________________________
564 Bool_t AliShuttle::StoreReferenceFile(const char* detector, const char* localFile, const char* gridFileName)
567 // Stores reference file directly (without opening it). This function stores the file locally.
569 // The file is stored under the following location:
570 // <base folder of local reference storage>/<DET>/<RUN#>_<gridFileName>
571 // where <gridFileName> is the second parameter given to the function
574 if (fTestMode & kErrorStorage)
576 Log(fCurrentDetector, "StoreReferenceFile - In TESTMODE - Simulating error while storing locally");
580 AliCDBManager* man = AliCDBManager::Instance();
581 AliCDBStorage* sto = man->GetStorage(fgkLocalRefStorage);
583 TString localBaseFolder = sto->GetBaseFolder();
585 TString target = GetRefFilePrefix(localBaseFolder.Data(), detector);
586 target.Append(Form("/%d_%s", GetCurrentRun(), gridFileName));
588 return CopyFileLocally(localFile, target);
591 //______________________________________________________________________________________________
592 Bool_t AliShuttle::StoreRunMetadataFile(const char* localFile, const char* gridFileName)
595 // Stores Run metadata file to the Grid, in the run folder
597 // Only GRP can call this function.
599 if (fTestMode & kErrorStorage)
601 Log(fCurrentDetector, "StoreRunMetaDataFile - In TESTMODE - Simulating error while storing locally");
605 AliCDBManager* man = AliCDBManager::Instance();
606 AliCDBStorage* sto = man->GetStorage(fgkLocalRefStorage);
608 TString localBaseFolder = sto->GetBaseFolder();
610 // Build Run level folder
611 // folder = /alice/data/year/lhcPeriod/runNb/raw
614 TString lhcPeriod = GetLHCPeriod();
615 if (lhcPeriod.Length() == 0)
617 Log("SHUTTLE","StoreRunMetaDataFile - LHCPeriod not found in logbook!");
621 // TODO partitions with one detector only write data into LHCperiod_DET
622 TString partition = GetRunParameter("detector");
624 if (partition.Length() > 0 && partition != "ALICE")
626 lhcPeriod.Append(Form("_%s", partition.Data()));
627 Log(fCurrentDetector, Form("Run data tags merged file will be written in %s",
631 TString target = Form("%s/GRP/RunMetadata%s%d/%s/%09d/raw/%s",
632 localBaseFolder.Data(), fConfig->GetAlienPath(), GetCurrentYear(),
633 lhcPeriod.Data(), GetCurrentRun(), gridFileName);
635 return CopyFileLocally(localFile, target);
638 //______________________________________________________________________________________________
639 Bool_t AliShuttle::CopyFileLocally(const char* localFile, const TString& target)
642 // Stores file locally. Called by StoreReferenceFile and StoreRunMetadataFile
643 // Files are temporarily stored in the local reference storage. When the preprocessor
644 // finishes, the Shuttle calls CopyFilesToGrid to transfer the files to AliEn
645 // (in reference or run level folders)
648 TString targetDir(target(0, target.Last('/')));
650 //try to open base dir folder, if it does not exist
651 void* dir = gSystem->OpenDirectory(targetDir.Data());
653 if (gSystem->mkdir(targetDir.Data(), kTRUE)) {
654 Log("SHUTTLE", Form("CopyFileLocally - Can't open directory <%s>", targetDir.Data()));
659 gSystem->FreeDirectory(dir);
664 result = gSystem->GetPathInfo(localFile, 0, (Long64_t*) 0, 0, 0);
667 Log("SHUTTLE", Form("CopyFileLocally - %s does not exist", localFile));
671 result = gSystem->GetPathInfo(target, 0, (Long64_t*) 0, 0, 0);
674 Log("SHUTTLE", Form("CopyFileLocally - target file %s already exist, removing...", target.Data()));
675 if (gSystem->Unlink(target.Data()))
677 Log("SHUTTLE", Form("CopyFileLocally - Could not remove existing target file %s!", target.Data()));
682 result = gSystem->CopyFile(localFile, target);
686 Log("SHUTTLE", Form("CopyFileLocally - File %s stored locally to %s", localFile, target.Data()));
691 Log("SHUTTLE", Form("CopyFileLocally - Could not store file %s to %s! Error code = %d",
692 localFile, target.Data(), result));
700 //______________________________________________________________________________________________
701 Bool_t AliShuttle::CopyFilesToGrid(const char* type)
704 // Transfers local files to the Grid. Local files can be reference files
705 // or run metadata file (from GRP only).
707 // According to the type (ref, metadata) the files are stored under the following location:
708 // ref --> <base folder of reference storage>/<DET>/<RUN#>_<gridFileName>
709 // metadata --> <run data folder>/<MetadataFileName>
712 AliCDBManager* man = AliCDBManager::Instance();
713 AliCDBStorage* sto = man->GetStorage(fgkLocalRefStorage);
716 TString localBaseFolder = sto->GetBaseFolder();
722 if (strcmp(type, "reference") == 0)
724 dir = GetRefFilePrefix(localBaseFolder.Data(), fCurrentDetector.Data());
725 AliCDBStorage* gridSto = man->GetStorage(fgkMainRefStorage);
728 TString gridBaseFolder = gridSto->GetBaseFolder();
729 alienDir = GetRefFilePrefix(gridBaseFolder.Data(), fCurrentDetector.Data());
730 begin = Form("%d_", GetCurrentRun());
732 else if (strcmp(type, "metadata") == 0)
735 TString lhcPeriod = GetLHCPeriod();
737 if (lhcPeriod.Length() == 0)
739 Log("SHUTTLE","CopyFilesToGrid - LHCPeriod not found in logbook!");
743 // TODO partitions with one detector only write data into LHCperiod_DET
744 TString partition = GetRunParameter("detector");
746 if (partition.Length() > 0 && partition != "ALICE")
748 lhcPeriod.Append(Form("_%s", partition.Data()));
751 dir = Form("%s/GRP/RunMetadata%s%d/%s/%09d/raw",
752 localBaseFolder.Data(), fConfig->GetAlienPath(), GetCurrentYear(),
753 lhcPeriod.Data(), GetCurrentRun());
754 alienDir = dir(dir.Index(fConfig->GetAlienPath()), dir.Length());
760 Log("SHUTTLE", "CopyFilesToGrid - Unexpected: type label must be reference or metadata!");
764 TSystemDirectory* baseDir = new TSystemDirectory("/", dir);
768 TList* dirList = baseDir->GetListOfFiles();
771 if (!dirList) return kTRUE;
773 if (dirList->GetEntries() < 3)
781 Log("SHUTTLE", "CopyFilesToGrid - Connection to Grid failed: Cannot continue!");
786 Int_t nDirs = 0, nTransfer = 0;
787 TIter dirIter(dirList);
788 TSystemFile* entry = 0;
790 Bool_t success = kTRUE;
791 Bool_t first = kTRUE;
793 while ((entry = dynamic_cast<TSystemFile*> (dirIter.Next())))
795 if (entry->IsDirectory())
798 TString fileName(entry->GetName());
799 if (!fileName.BeginsWith(begin))
807 // check that folder exists, otherwise create it
808 TGridResult* result = gGrid->Ls(alienDir.Data(), "a");
816 if (!result->GetFileName(1)) // TODO: It looks like element 0 is always 0!!
818 // TODO It does not work currently! Bug in TAliEn::Mkdir
819 // TODO Manually fixed in local root v5-16-00
820 if (!gGrid->Mkdir(alienDir.Data(),"-p",0))
822 Log("SHUTTLE", Form("CopyFilesToGrid - Cannot create directory %s",
827 Log("SHUTTLE",Form("CopyFilesToGrid - Folder %s created", alienDir.Data()));
831 Log("SHUTTLE",Form("CopyFilesToGrid - Folder %s found", alienDir.Data()));
835 TString fullLocalPath;
836 fullLocalPath.Form("%s/%s", dir.Data(), fileName.Data());
838 TString fullGridPath;
839 fullGridPath.Form("alien://%s/%s", alienDir.Data(), fileName.Data());
841 Bool_t result = TFile::Cp(fullLocalPath, fullGridPath);
845 Log("SHUTTLE", Form("CopyFilesToGrid - Copying local file %s to %s succeeded!",
846 fullLocalPath.Data(), fullGridPath.Data()));
847 RemoveFile(fullLocalPath);
852 Log("SHUTTLE", Form("CopyFilesToGrid - Copying local file %s to %s FAILED!",
853 fullLocalPath.Data(), fullGridPath.Data()));
858 Log("SHUTTLE", Form("CopyFilesToGrid - %d (over %d) files in folder %s copied to Grid.",
859 nTransfer, nDirs, dir.Data()));
866 //______________________________________________________________________________________________
867 const char* AliShuttle::GetRefFilePrefix(const char* base, const char* detector)
870 // Get folder name of reference files
873 TString offDetStr(GetOfflineDetName(detector));
875 if (offDetStr == "ITS" || offDetStr == "MUON" || offDetStr == "PHOS")
877 dir.Form("%s/%s/%s", base, offDetStr.Data(), detector);
879 dir.Form("%s/%s", base, offDetStr.Data());
885 //______________________________________________________________________________________________
886 void AliShuttle::CleanLocalStorage(const TString& uri)
889 // Called in case the preprocessor is declared failed. Remove remaining objects from the local storages.
892 const char* type = 0;
893 if(uri == fgkLocalCDB) {
895 } else if(uri == fgkLocalRefStorage) {
898 AliError(Form("Invalid storage URI: %s", uri.Data()));
902 AliCDBManager* man = AliCDBManager::Instance();
904 // open local storage
905 AliCDBStorage *localSto = man->GetStorage(uri);
908 Form("CleanLocalStorage - cannot activate local %s storage", type));
912 TString filename(Form("%s/%s/*/Run*_v%d_s*.root",
913 localSto->GetBaseFolder().Data(), GetOfflineDetName(fCurrentDetector.Data()), GetCurrentRun()));
915 AliDebug(2, Form("filename = %s", filename.Data()));
917 Log("SHUTTLE", Form("Removing remaining local files for run %d and detector %s ...",
918 GetCurrentRun(), fCurrentDetector.Data()));
920 RemoveFile(filename.Data());
924 //______________________________________________________________________________________________
925 void AliShuttle::RemoveFile(const char* filename)
928 // removes local file
931 TString command(Form("rm -f %s", filename));
933 Int_t result = gSystem->Exec(command.Data());
936 Log("SHUTTLE", Form("RemoveFile - %s: Cannot remove file %s!",
937 fCurrentDetector.Data(), filename));
941 //______________________________________________________________________________________________
942 AliShuttleStatus* AliShuttle::ReadShuttleStatus()
945 // Reads the AliShuttleStatus from the CDB
953 Int_t path1 = GetCurrentRun()/10000;
955 fStatusEntry = AliCDBManager::Instance()->GetStorage(GetLocalCDB())
956 ->Get(Form("/SHUTTLE/%s/%d", fCurrentDetector.Data(), path1), GetCurrentRun());
957 } catch(std::exception& x) {
958 AliInfo("%s",x.what());
961 if (!fStatusEntry) return 0;
962 fStatusEntry->SetOwner(1);
964 AliShuttleStatus* status = dynamic_cast<AliShuttleStatus*> (fStatusEntry->GetObject());
966 AliError("Invalid object stored to CDB!");
973 //______________________________________________________________________________________________
974 Bool_t AliShuttle::WriteShuttleStatus(AliShuttleStatus* status)
977 // writes the status for one subdetector
985 Int_t run = GetCurrentRun();
986 Int_t path1 = run/10000;
987 TString path1_string = Form("%d",path1);
989 AliCDBId id(AliCDBPath("SHUTTLE", fCurrentDetector, path1_string), run, run);
991 fStatusEntry = new AliCDBEntry(status, id, new AliCDBMetaData);
992 fStatusEntry->SetOwner(1);
994 Int_t logLevel = AliLog::GetGlobalLogLevel();
995 AliLog::SetGlobalLogLevel(AliLog::kError);
997 UInt_t result = AliCDBManager::Instance()->GetStorage(fgkLocalCDB)->Put(fStatusEntry);
999 AliLog::SetGlobalLogLevel((AliLog::EType_t)logLevel);
1002 Log("SHUTTLE", Form("WriteShuttleStatus - Failed for %s, run %d",
1003 fCurrentDetector.Data(), run));
1012 //______________________________________________________________________________________________
1013 void AliShuttle::UpdateShuttleStatus(AliShuttleStatus::Status newStatus, Bool_t increaseCount)
1016 // changes the AliShuttleStatus for the given detector and run to the given status
1020 AliError("UNEXPECTED: fStatusEntry empty");
1024 AliShuttleStatus* status = dynamic_cast<AliShuttleStatus*> (fStatusEntry->GetObject());
1027 Log("SHUTTLE", "UpdateShuttleStatus - UNEXPECTED: status could not be read from current CDB entry");
1031 TString actionStr = Form("UpdateShuttleStatus - %s: Changing state from %s to %s",
1032 fCurrentDetector.Data(),
1033 status->GetStatusName(),
1034 status->GetStatusName(newStatus));
1035 Log("SHUTTLE", actionStr);
1036 SetLastAction(actionStr);
1038 status->SetStatus(newStatus);
1039 if (increaseCount) status->IncreaseCount();
1041 Int_t logLevel = AliLog::GetGlobalLogLevel();
1042 AliLog::SetGlobalLogLevel(AliLog::kError);
1044 AliCDBManager::Instance()->GetStorage(fgkLocalCDB)->Put(fStatusEntry);
1046 AliLog::SetGlobalLogLevel((AliLog::EType_t)logLevel);
1051 //______________________________________________________________________________________________
1052 void AliShuttle::SendMLDetInfo()
1055 // sends ML information about the current status of the current detector being processed
1058 AliShuttleStatus* status = dynamic_cast<AliShuttleStatus*> (fStatusEntry->GetObject());
1061 Log("SHUTTLE", "SendMLDetInfo - UNEXPECTED: status could not be read from current CDB entry");
1065 TMonaLisaText mlStatus(Form("%s_status", fCurrentDetector.Data()), status->GetStatusName());
1066 TMonaLisaValue mlRetryCount(Form("%s_count", fCurrentDetector.Data()), status->GetCount());
1069 mlList.Add(&mlStatus);
1070 mlList.Add(&mlRetryCount);
1073 mlID.Form("%d", GetCurrentRun());
1074 fMonaLisa->SendParameters(&mlList, mlID);
1077 //______________________________________________________________________________________________
1078 Bool_t AliShuttle::ContinueProcessing()
1080 // this function reads the AliShuttleStatus information from CDB and
1081 // checks if the processing should be continued
1082 // if yes it returns kTRUE and updates the AliShuttleStatus with nextStatus
1084 if (!fConfig->HostProcessDetector(fCurrentDetector))
1087 AliPreprocessor* aPreprocessor =
1088 dynamic_cast<AliPreprocessor*> (fPreprocessorMap.GetValue(fCurrentDetector));
1091 Log("SHUTTLE", Form("ContinueProcessing - %s: no preprocessor registered", fCurrentDetector.Data()));
1095 AliShuttleLogbookEntry::Status entryStatus =
1096 fLogbookEntry->GetDetectorStatus(fCurrentDetector);
1098 if (entryStatus != AliShuttleLogbookEntry::kUnprocessed) {
1099 Log("SHUTTLE", Form("ContinueProcessing - %s is %s",
1100 fCurrentDetector.Data(),
1101 fLogbookEntry->GetDetectorStatusName(entryStatus)));
1105 // if we get here, according to Shuttle logbook subdetector is in UNPROCESSED state
1107 // check if current run is first unprocessed run for current detector
1108 if (fConfig->StrictRunOrder(fCurrentDetector) &&
1109 !fFirstUnprocessed[GetDetPos(fCurrentDetector)])
1111 if (fTestMode == kNone)
1113 Log("SHUTTLE", Form("ContinueProcessing - %s requires strict run ordering"
1114 " but this is not the first unprocessed run!",fCurrentDetector.Data()));
1119 Log("SHUTTLE", Form("ContinueProcessing - In TESTMODE - "
1120 "Although %s requires strict run ordering "
1121 "and this is not the first unprocessed run, "
1122 "the SHUTTLE continues",fCurrentDetector.Data()));
1126 // Is the subdetector processed first time for this run?
1127 fFirstProcessing = kFALSE;
1129 AliShuttleStatus* status = ReadShuttleStatus();
1132 Log("SHUTTLE", Form("ContinueProcessing - %s: Processing first time",
1133 fCurrentDetector.Data()));
1134 status = new AliShuttleStatus(AliShuttleStatus::kStarted);
1135 fFirstProcessing = kTRUE;
1136 return WriteShuttleStatus(status);
1139 // The following case shouldn't happen if Shuttle Logbook was correctly updated.
1140 // If it happens it may mean Logbook updating failed... let's do it now!
1141 if (status->GetStatus() == AliShuttleStatus::kDone ||
1142 status->GetStatus() == AliShuttleStatus::kFailed ||
1143 status->GetStatus() == AliShuttleStatus::kSkipped) {
1144 Log("SHUTTLE", Form("ContinueProcessing - %s is already %s. Updating Shuttle Logbook",
1145 fCurrentDetector.Data(),
1146 status->GetStatusName(status->GetStatus())));
1148 if (status->GetStatus() == AliShuttleStatus::kSkipped)
1150 UpdateShuttleLogbook(fCurrentDetector.Data(), "DONE");
1153 UpdateShuttleLogbook(fCurrentDetector.Data(), status->GetStatusName(status->GetStatus()));
1158 if (status->GetStatus() == AliShuttleStatus::kStoreStarted || status->GetStatus() == AliShuttleStatus::kStoreDelayed ||status->GetStatus() == AliShuttleStatus::kStoreError) {
1160 Form("ContinueProcessing - %s: Grid storage of one or more "
1161 "objects failed. Trying again now",
1162 fCurrentDetector.Data()));
1167 // if we get here, there is a restart
1168 Bool_t cont = kFALSE;
1171 if (status->GetCount() >= fConfig->GetMaxRetries()) {
1172 Log("SHUTTLE", Form("ContinueProcessing - %s failed %d times in status %s - "
1173 "Updating Shuttle Logbook", fCurrentDetector.Data(),
1174 status->GetCount(), status->GetStatusName()));
1175 UpdateShuttleLogbook(fCurrentDetector.Data(), "FAILED");
1176 UpdateShuttleStatus(AliShuttleStatus::kFailed);
1178 // there may still be objects in local OCDB and reference storage
1179 // and FXS databases may be not updated: do it now!
1181 // TODO Currently disabled, we want to keep files in case of failure!
1182 // CleanLocalStorage(fgkLocalCDB);
1183 // CleanLocalStorage(fgkLocalRefStorage);
1184 // UpdateTableFailCase();
1186 // Send mail to detector expert!
1187 Log("SHUTTLE", Form("ContinueProcessing - Sending mail to %s expert...",
1188 fCurrentDetector.Data()));
1189 // det experts in to
1191 TIter *iterExperts = 0;
1192 iterExperts = new TIter(fConfig->GetResponsibles(fCurrentDetector));
1193 TObjString *anExpert=0;
1194 while ((anExpert = (TObjString*) iterExperts->Next()))
1196 to += Form("%s, \n", anExpert->GetName());
1200 if (to.Length() > 0)
1201 to.Remove(to.Length()-3);
1202 AliDebug(2, Form("to: %s",to.Data()));
1205 Log("SHUTTLE", Form("List of %s responsibles not set!", fCurrentDetector.Data()));
1209 Log(fCurrentDetector.Data(), Form("ContinueProcessing - Sending mail to %s expert(s):",
1210 fCurrentDetector.Data()));
1211 Log(fCurrentDetector.Data(), Form("\n%s", to.Data()));
1212 if (!SendMail(kPPEMail))
1213 Log("SHUTTLE", Form("ContinueProcessing - Could not send mail to %s expert",
1214 fCurrentDetector.Data()));
1217 Log("SHUTTLE", Form("ContinueProcessing - %s: restarting. "
1218 "Aborted before with %s. Retry number %d.", fCurrentDetector.Data(),
1219 status->GetStatusName(), status->GetCount()));
1220 Bool_t increaseCount = kTRUE;
1221 if (status->GetStatus() == AliShuttleStatus::kDCSError ||
1222 status->GetStatus() == AliShuttleStatus::kDCSStarted ||
1223 status->GetStatus() == AliShuttleStatus::kFXSError ||
1224 status->GetStatus() == AliShuttleStatus::kOCDBError)
1225 increaseCount = kFALSE;
1227 UpdateShuttleStatus(AliShuttleStatus::kStarted, increaseCount);
1234 //______________________________________________________________________________________________
1235 void AliShuttle::SendMLRunInfo(const char* status)
1238 // Send information about this run to ML
1240 TMonaLisaText mlStatus("SHUTTLE_status", status);
1241 TString runType(fLogbookEntry->GetRunType());
1242 if (strlen(fLogbookEntry->GetRunParameter("log")) > 0){
1245 runType += fLogbookEntry->GetRunParameter("log");
1248 if (fLogbookEntry->GetDATestMode()){
1249 runType += " (DATest)";
1251 TMonaLisaText mlRunType("SHUTTLE_runtype", runType);
1254 mlList.Add(&mlStatus);
1255 mlList.Add(&mlRunType);
1258 mlID.Form("%d", GetCurrentRun());
1259 fMonaLisa->SendParameters(&mlList, mlID);
1262 //______________________________________________________________________________________________
1263 Int_t AliShuttle::GetMem(Int_t pid)
1265 // invokes ps to get the memory consumption of the process <pid>
1266 // returns -1 in case of error
1269 checkStr.Form("ps -o vsize --pid %d | tail -n 1", pid);
1270 FILE* pipe = gSystem->OpenPipe(checkStr, "r");
1273 Log("SHUTTLE", Form("Process - Error: "
1274 "Could not open pipe to %s", checkStr.Data()));
1279 if (!fgets(buffer, 100, pipe))
1281 Log("SHUTTLE", "Process - Error: ps did not return anything");
1282 gSystem->ClosePipe(pipe);
1285 gSystem->ClosePipe(pipe);
1287 //Log("SHUTTLE", Form("ps returned %s", buffer));
1290 if ((sscanf(buffer, "%d\n", &mem) != 1) || !mem)
1292 Log("SHUTTLE", "Process - Error: Could not parse output of ps");
1299 //______________________________________________________________________________________________
1300 Bool_t AliShuttle::Process(AliShuttleLogbookEntry* entry)
1303 // Makes data retrieval for all detectors in the configuration.
1304 // entry: Shuttle logbook entry, contains run paramenters and status of detectors
1305 // (Unprocessed, Inactive, Failed or Done).
1306 // Returns kFALSE in case of error occured and kTRUE otherwise
1309 if (!entry) return kFALSE;
1311 fLogbookEntry = entry;
1313 Log("SHUTTLE", Form("\t\t\t^*^*^*^*^*^*^*^*^*^*^*^* run %d: START ^*^*^*^*^*^*^*^*^*^*^*^*",
1318 // Send the information to ML
1319 SendMLRunInfo("Processing");
1321 if (fLogbookEntry->IsDone())
1323 Log("SHUTTLE","Process - Shuttle is already DONE. Updating logbook");
1324 UpdateShuttleLogbook("shuttle_done");
1329 // read test mode if flag is set
1333 TString logEntry(entry->GetRunParameter("log"));
1334 //printf("log entry = %s\n", logEntry.Data());
1335 TString searchStr("Testmode: ");
1336 Int_t pos = logEntry.Index(searchStr.Data());
1337 //printf("%d\n", pos);
1340 TSubString subStr = logEntry(pos + searchStr.Length(), logEntry.Length());
1341 //printf("%s\n", subStr.String().Data());
1342 TString newStr(subStr.Data());
1343 TObjArray* token = newStr.Tokenize(' ');
1347 TObjString* tmpStr = dynamic_cast<TObjString*> (token->First());
1350 Int_t testMode = tmpStr->String().Atoi();
1353 Log("SHUTTLE", Form("Process - Enabling test mode %d", testMode));
1354 SetTestMode((TestMode) testMode);
1362 fLogbookEntry->Print("all");
1365 Bool_t hasError = kFALSE;
1367 // Set the CDB and Reference folders according to the year
1369 // build cdb paths (repeat each time, run might be a DATest run)
1370 if (!fLogbookEntry->GetDATestMode()){
1371 fgkMainCDB.Form("alien://folder=%s%d/OCDB?user=alidaq?cacheFold=/tmp/OCDBCache",
1372 fConfig->GetAlienPath(), GetCurrentYear());
1374 fgkMainRefStorage.Form("alien://folder=%s%d/Reference?user=alidaq?cacheFold=/tmp/OCDBCache",
1375 fConfig->GetAlienPath(), GetCurrentYear());
1378 fgkMainCDB.Form("alien://folder=%s%d/DATest/OCDB?user=alidaq?cacheFold=/tmp/OCDBCache",
1379 fConfig->GetAlienPath(), GetCurrentYear());
1381 fgkMainRefStorage.Form("alien://folder=%s%d/DATest/Reference?user=alidaq?cacheFold=/tmp/OCDBCache",
1382 fConfig->GetAlienPath(), GetCurrentYear());
1385 AliDebug(2,Form("Main CDB storage = %s",fgkMainCDB.Data()));
1386 AliDebug(2,Form("Main Reference storage = %s",fgkMainRefStorage.Data()));
1388 // Loop on detectors in the configuration
1389 TIter iter(fConfig->GetDetectors());
1390 TObjString* aDetector = 0;
1392 Bool_t first = kTRUE;
1394 while ((aDetector = (TObjString*) iter.Next()))
1396 fCurrentDetector = aDetector->String();
1398 if (ContinueProcessing() == kFALSE)
1403 // only read QueryCDB when needed and only once
1404 AliCDBStorage *mainCDBSto = AliCDBManager::Instance()->GetStorage(fgkMainCDB);
1405 if(mainCDBSto) mainCDBSto->QueryCDB(GetCurrentRun());
1406 AliCDBStorage *mainRefSto = AliCDBManager::Instance()->GetStorage(fgkMainRefStorage);
1407 if(mainRefSto) mainRefSto->QueryCDB(GetCurrentRun());
1411 Log("SHUTTLE", Form("\t\t\t****** run %d - %s: START ******",
1412 GetCurrentRun(), aDetector->GetName()));
1414 for(Int_t iSys=0;iSys<4;iSys++) fFXSCalled[iSys]=kFALSE;
1416 Int_t initialMem = GetMem(getpid());
1417 Log("SHUTTLE", Form("Memory consumption before forking is %d", initialMem));
1419 Log(fCurrentDetector.Data(), "Process - Starting processing");
1425 Log("SHUTTLE", "Process - ERROR: Forking failed");
1430 Log("SHUTTLE", Form("Process - In parent process of %d - %s: Starting monitoring",
1431 GetCurrentRun(), aDetector->GetName()));
1433 Long_t begin = time(0);
1435 int status; // to be used with waitpid, on purpose an int (not Int_t)!
1436 while (waitpid(pid, &status, WNOHANG) == 0)
1438 Long_t expiredTime = time(0) - begin;
1440 // the run-dependent timeout is the timeout from the configuration plus a twentieth of
1441 // the run duration, e.g. 3 additional minutes for 1h run or 1/2h for a 10h run
1442 Int_t runDepTimeOut = fConfig->GetPPTimeOut() + (GetCurrentEndTime() - GetCurrentStartTime()) * 0.05;
1443 if (expiredTime > runDepTimeOut)
1446 AliShuttleStatus *currentStatus = ReadShuttleStatus();
1447 AliShuttleStatus::Status newStatus = AliShuttleStatus::kInvalid;
1449 if (currentStatus->GetStatus() == AliShuttleStatus::kDCSStarted)
1451 // in case the pp goes in TimeOut while retrieving the DCS DPs
1452 // set status to kDCSError
1454 logMsg.Form("Process - Process of %s timed out while retrieving the DCS DataPoints. Run time: %ld seconds. Killing... and setting status to DCSError.",
1455 fCurrentDetector.Data(), expiredTime);
1456 newStatus = AliShuttleStatus::kDCSError;
1458 else if (currentStatus->GetStatus() <= AliShuttleStatus::kPPDone)
1460 // in case pp not yet done set status to kPPTimeOut
1462 logMsg.Form("Process - Process of %s timed out. Run time: %ld seconds. Killing...",
1463 fCurrentDetector.Data(), expiredTime);
1464 newStatus = AliShuttleStatus::kPPTimeOut;
1466 else if (currentStatus->GetStatus() == AliShuttleStatus::kStoreStarted)
1468 // in case the pp goes in TimeOut while storing the objects in the OCDB
1469 // set status to kStoreError
1471 logMsg.Form("Process - Process of %s timed out while storing the OCDB object. Run time: %ld seconds. Killing... and setting status to StoreError.",
1472 fCurrentDetector.Data(), expiredTime);
1473 newStatus = AliShuttleStatus::kStoreError;
1477 // in other cases don't change the status
1479 logMsg.Form("Process - Process of %s timed out in status = %s. Run time: %ld seconds. Killing... without changing the status",
1480 fCurrentDetector.Data(), currentStatus->GetStatusName(), expiredTime);
1483 Log("SHUTTLE", logMsg);
1484 Log(fCurrentDetector, logMsg);
1488 if (newStatus != AliShuttleStatus::kInvalid)
1489 UpdateShuttleStatus(newStatus);
1492 gSystem->Sleep(1000);
1496 gSystem->Sleep(1000);
1498 Int_t mem = GetMem(pid);
1507 if (expiredTime % 60 == 0)
1509 Log("SHUTTLE", Form("Process - %s: Checking process. "
1510 "Run time: %ld seconds - Memory consumption: %d KB",
1511 fCurrentDetector.Data(), expiredTime, mem));
1515 if (mem > fConfig->GetPPMaxMem())
1518 tmp.Form("Process - Process exceeds maximum allowed memory "
1519 "(%d KB > %d KB). Killing...",
1520 mem, fConfig->GetPPMaxMem());
1521 Log("SHUTTLE", tmp);
1522 Log(fCurrentDetector, tmp);
1526 UpdateShuttleStatus(AliShuttleStatus::kPPOutOfMemory);
1529 gSystem->Sleep(1000);
1534 Log("SHUTTLE", Form("Process - In parent process of %d - %s: Client has terminated.",
1535 GetCurrentRun(), aDetector->GetName()));
1537 if (WIFEXITED(status))
1539 Int_t returnCode = WEXITSTATUS(status);
1541 Log("SHUTTLE", Form("Process - %s: the return code is %d", fCurrentDetector.Data(),
1544 if (returnCode == 0) hasError = kTRUE;
1550 Log("SHUTTLE", Form("Process - In child process of %d - %s", GetCurrentRun(),
1551 aDetector->GetName()));
1553 Log("SHUTTLE", Form("Process - Redirecting output to %s log",fCurrentDetector.Data()));
1555 if ((freopen(GetLogFileName(fCurrentDetector), "a", stdout)) == 0)
1557 Log("SHUTTLE", "Process - Could not freopen stdout");
1561 fOutputRedirected = kTRUE;
1562 if ((dup2(fileno(stdout), fileno(stderr))) < 0)
1563 Log("SHUTTLE", "Process - Could not redirect stderr");
1567 Log("SHUTTLE", "Executing TGrid::Connect");
1568 TGrid::Connect("alien://");
1570 TString wd = gSystem->WorkingDirectory();
1571 Int_t dir_lev1 = GetCurrentRun()/10000;
1572 TString tmpDir = Form("%s/%d/%d/%s_process", GetShuttleTempDir(),
1573 dir_lev1, GetCurrentRun(), fCurrentDetector.Data());
1575 Int_t result = gSystem->GetPathInfo(tmpDir.Data(), 0, (Long64_t*) 0, 0, 0);
1576 if (!result) // temp dir already exists!
1578 Log(fCurrentDetector.Data(),
1579 Form("Process - %s dir already exists! Removing...", tmpDir.Data()));
1580 gSystem->Exec(Form("rm -rf %s",tmpDir.Data()));
1583 if (gSystem->mkdir(tmpDir.Data(), 1))
1585 Log(fCurrentDetector.Data(), "Process - could not make temp directory!!");
1589 if (!gSystem->ChangeDirectory(tmpDir.Data()))
1591 Log(fCurrentDetector.Data(), "Process - could not change directory!!");
1595 Int_t success = ProcessCurrentDetector();
1597 gSystem->ChangeDirectory(wd.Data());
1599 if (success == 1) // Preprocessor finished successfully!
1601 // remove temporary folder or DCS map
1602 if (!fConfig->KeepTempFolder())
1604 gSystem->Exec(Form("rm -rf %s",tmpDir.Data()));
1605 } else if (!fConfig->KeepDCSMap())
1607 gSystem->Exec(Form("rm -f %s/DCSMap.root",tmpDir.Data()));
1610 // Update time_processed field in FXS DB
1611 if (UpdateTable() == kFALSE)
1612 Log("SHUTTLE", Form("Process - %s: Could not update FXS databases!",
1613 fCurrentDetector.Data()));
1615 // Transfer the data from local storage to main storage (Grid)
1616 if (StoreOCDB() == kFALSE)
1619 else if (success == 0)
1622 Form("\t\t\t****** run %d - %s: ERROR ******",
1623 GetCurrentRun(), aDetector->GetName()));
1626 for (UInt_t iSys=0; iSys<4; iSys++)
1628 if (fFXSCalled[iSys]) fFXSlist[iSys].Clear();
1631 Log("SHUTTLE", Form("Process - Client process of %d - %s is exiting now with %d.",
1632 GetCurrentRun(), aDetector->GetName(), success));
1634 // the client exits here
1635 gSystem->Exit(success);
1637 AliError("We should never get here!!!");
1641 Log("SHUTTLE", Form("\t\t\t^*^*^*^*^*^*^*^*^*^*^*^* run %d: FINISH ^*^*^*^*^*^*^*^*^*^*^*^*",
1644 //check if shuttle is done for this run, if so update logbook
1645 TObjArray checkEntryArray;
1646 checkEntryArray.SetOwner(1);
1647 TString whereClause = Form("where run=%d", GetCurrentRun());
1648 if (!QueryShuttleLogbook(whereClause.Data(), checkEntryArray) ||
1649 checkEntryArray.GetEntries() == 0) {
1650 Log("SHUTTLE", Form("Process - Warning: Cannot check status of run %d on Shuttle logbook!",
1652 return hasError == kFALSE;
1655 AliShuttleLogbookEntry* checkEntry = dynamic_cast<AliShuttleLogbookEntry*>
1656 (checkEntryArray.At(0));
1660 if (checkEntry->IsDone())
1662 Log("SHUTTLE","Process - Shuttle is DONE. Updating logbook");
1663 UpdateShuttleLogbook("shuttle_done");
1667 for (UInt_t iDet=0; iDet<NDetectors(); iDet++)
1669 if (checkEntry->GetDetectorStatus(iDet) == AliShuttleLogbookEntry::kUnprocessed)
1671 AliDebug(2, Form("Run %d: setting %s as \"not first time unprocessed\"",
1672 checkEntry->GetRun(), GetDetName(iDet)));
1673 fFirstUnprocessed[iDet] = kFALSE;
1676 SendMLRunInfo("Pending");
1682 return hasError == kFALSE;
1685 //______________________________________________________________________________________________
1686 Int_t AliShuttle::ProcessCurrentDetector()
1689 // Makes data retrieval just for a specific detector (fCurrentDetector).
1690 // Threre should be a configuration for this detector.
1692 Log("SHUTTLE", Form("ProcessCurrentDetector - Retrieving values for %s, run %d",
1693 fCurrentDetector.Data(), GetCurrentRun()));
1695 TString wd = gSystem->WorkingDirectory();
1697 if (!CleanReferenceStorage(fCurrentDetector.Data()))
1700 gSystem->ChangeDirectory(wd.Data());
1702 // call preprocessor
1703 AliPreprocessor* aPreprocessor =
1704 dynamic_cast<AliPreprocessor*> (fPreprocessorMap.GetValue(fCurrentDetector));
1706 // check if the preprocessor wants to process this run type
1707 if (aPreprocessor->ProcessRunType() == kFALSE)
1709 UpdateShuttleStatus(AliShuttleStatus::kSkipped);
1710 UpdateShuttleLogbook(fCurrentDetector, "DONE");
1711 if (!UpdateTableSkippedCase(fCurrentDetector.Data()))
1713 AliError(Form("Could not update FXS tables for run %d !", GetCurrentRun()));
1715 Log(fCurrentDetector, Form("ProcessCurrentDetector - %s preprocessor is not interested in this run type", fCurrentDetector.Data()));
1720 // checking if OCDB is reachable
1721 AliCDBEntry* testEntry = GetFromOCDB("SHUTTLE","GRP/CTP/DummyConfig");
1723 // OCDB is not accessible, going in OCDBError for current detector
1724 AliError("OCDB Test entry not accessible");
1725 UpdateShuttleStatus(AliShuttleStatus::kOCDBError);
1729 TMap* dcsMap = new TMap();
1731 aPreprocessor->Initialize(GetCurrentRun(), GetCurrentStartTime(), GetCurrentEndTime());
1733 Bool_t processDCS = aPreprocessor->ProcessDCS();
1737 Log(fCurrentDetector, "ProcessCurrentDetector -"
1738 " The preprocessor requested to skip the retrieval of DCS values");
1740 else if (fTestMode & kSkipDCS)
1742 Log(fCurrentDetector, "ProcessCurrentDetector - In TESTMODE: Skipping DCS processing");
1744 else if (fTestMode & kErrorDCS)
1746 Log(fCurrentDetector, "ProcessCurrentDetector - In TESTMODE: Simulating DCS error");
1747 UpdateShuttleStatus(AliShuttleStatus::kDCSStarted);
1748 UpdateShuttleStatus(AliShuttleStatus::kDCSError);
1753 UpdateShuttleStatus(AliShuttleStatus::kDCSStarted);
1755 // Query DCS archive
1756 Int_t nServers = fConfig->GetNServers(fCurrentDetector);
1758 for (int iServ=0; iServ<nServers; iServ++)
1761 TString host(fConfig->GetDCSHost(fCurrentDetector, iServ));
1762 Int_t port = fConfig->GetDCSPort(fCurrentDetector, iServ);
1763 Int_t multiSplit = fConfig->GetMultiSplit(fCurrentDetector, iServ);
1765 Log(fCurrentDetector, Form("ProcessCurrentDetector -"
1766 " Querying DCS Amanda server %s:%d (%d of %d)",
1767 host.Data(), port, iServ+1, nServers));
1772 if (fConfig->GetDCSAliases(fCurrentDetector, iServ)->GetEntries() > 0)
1774 Log(fCurrentDetector, Form("Querying %d DCS aliases", fConfig->GetDCSAliases(fCurrentDetector, iServ)->GetEntries()));
1775 aliasMap = GetValueSet(host, port,
1776 fConfig->GetDCSAliases(fCurrentDetector, iServ),
1777 kAlias, multiSplit);
1780 Log(fCurrentDetector,
1781 Form("ProcessCurrentDetector -"
1782 " Error retrieving DCS aliases from server %s."
1783 " Sending mail to DCS experts!", host.Data()));
1784 UpdateShuttleStatus(AliShuttleStatus::kDCSError);
1786 if (!SendMail(kDCSEMail))
1787 Log("SHUTTLE", Form("ProcessCurrentDetector - "
1788 "Could not send mail to DCS experts!"));
1795 if (fConfig->GetDCSDataPoints(fCurrentDetector, iServ)->GetEntries() > 0)
1797 Log(fCurrentDetector, Form("Querying %d DCS data points", fConfig->GetDCSDataPoints(fCurrentDetector, iServ)->GetEntries()));
1798 dpMap = GetValueSet(host, port,
1799 fConfig->GetDCSDataPoints(fCurrentDetector, iServ),
1803 Log(fCurrentDetector,
1804 Form("ProcessCurrentDetector -"
1805 " Error retrieving DCS data points from server %s."
1806 " Sending mail to DCS experts!", host.Data()));
1807 UpdateShuttleStatus(AliShuttleStatus::kDCSError);
1809 if (!SendMail(kDCSEMail))
1810 Log("SHUTTLE", Form("ProcessCurrentDetector - "
1811 "Could not send mail to DCS experts!"));
1813 if (aliasMap) delete aliasMap;
1819 // merge aliasMap and dpMap into dcsMap
1821 TIter iter(aliasMap);
1822 TObjString* key = 0;
1823 while ((key = (TObjString*) iter.Next()))
1824 dcsMap->Add(key, aliasMap->GetValue(key->String()));
1826 aliasMap->SetOwner(kFALSE);
1832 TObjString* key = 0;
1833 while ((key = (TObjString*) iter.Next()))
1834 dcsMap->Add(key, dpMap->GetValue(key->String()));
1836 dpMap->SetOwner(kFALSE);
1842 // save map into file, to help debugging in case of preprocessor error
1843 TFile* f = TFile::Open("DCSMap.root","recreate");
1845 dcsMap->Write("DCSMap", TObject::kSingleKey);
1849 // DCS Archive DB processing successful. Call Preprocessor!
1850 UpdateShuttleStatus(AliShuttleStatus::kPPStarted);
1852 fFXSError = -1; // this variable is kTRUE after ::Process if an FXS error occured
1854 UInt_t returnValue = aPreprocessor->Process(dcsMap);
1856 if (fFXSError!=-1) {
1857 UpdateShuttleStatus(AliShuttleStatus::kFXSError);
1858 SendMail(kFXSEMail, fFXSError);
1859 dcsMap->DeleteAll();
1864 if (returnValue > 0) // Preprocessor error!
1866 Log(fCurrentDetector, Form("ProcessCurrentDetector - "
1867 "Preprocessor failed. Process returned %d.", returnValue));
1868 UpdateShuttleStatus(AliShuttleStatus::kPPError);
1869 dcsMap->DeleteAll();
1875 UpdateShuttleStatus(AliShuttleStatus::kPPDone);
1876 Log(fCurrentDetector, Form("ProcessCurrentDetector - %s preprocessor returned success",
1877 fCurrentDetector.Data()));
1879 dcsMap->DeleteAll();
1885 //______________________________________________________________________________________________
1886 void AliShuttle::CountOpenRuns()
1888 // Query DAQ's Shuttle logbook and sends the number of open runs to ML
1892 // check connection, in case connect
1897 sqlQuery = Form("select count(*) from %s where shuttle_done=0", fConfig->GetShuttlelbTable());
1899 TSQLResult* aResult = fServer[4]->Query(sqlQuery);
1901 AliError(Form("Can't execute query <%s>!", sqlQuery.Data()));
1905 AliDebug(2,Form("Query = %s", sqlQuery.Data()));
1907 if (aResult->GetRowCount() == 0) {
1908 AliError(Form("No result for query %s received", sqlQuery.Data()));
1912 if (aResult->GetFieldCount() != 1) {
1913 AliError(Form("Invalid field count for query %s received", sqlQuery.Data()));
1917 TSQLRow* aRow = aResult->Next();
1919 AliError(Form("Could not receive result of query %s", sqlQuery.Data()));
1923 TString result(aRow->GetField(0), aRow->GetFieldLength(0));
1924 Int_t count = result.Atoi();
1926 Log("SHUTTLE", Form("%d unprocessed runs", count));
1931 TMonaLisaValue mlStatus("SHUTTLE_openruns", count);
1934 mlList.Add(&mlStatus);
1936 fMonaLisa->SendParameters(&mlList, "__PROCESSINGINFO__");
1939 //______________________________________________________________________________________________
1940 Bool_t AliShuttle::QueryShuttleLogbook(const char* whereClause,
1943 // Query DAQ's Shuttle logbook and fills detector status object.
1944 // Call QueryRunParameters to query DAQ logbook for run parameters.
1947 entries.SetOwner(1);
1949 // check connection, in case connect
1950 if (!Connect(4)) return kFALSE;
1953 sqlQuery = Form("select * from %s %s order by run", fConfig->GetShuttlelbTable(), whereClause);
1955 TSQLResult* aResult = fServer[4]->Query(sqlQuery);
1957 AliError(Form("Can't execute query <%s>!", sqlQuery.Data()));
1961 AliDebug(2,Form("Query = %s", sqlQuery.Data()));
1963 if(aResult->GetRowCount() == 0) {
1964 Log("SHUTTLE", "No entries in Shuttle Logbook match request");
1969 // TODO Check field count!
1970 const UInt_t nCols = 26;
1971 if (aResult->GetFieldCount() != (Int_t) nCols) {
1972 Log("SHUTTLE", "Invalid SQL result field number!");
1978 while ((aRow = aResult->Next())) {
1979 TString runString(aRow->GetField(0), aRow->GetFieldLength(0));
1980 Int_t run = runString.Atoi();
1982 AliShuttleLogbookEntry *entry = QueryRunParameters(run);
1986 // DA test mode flag
1987 TString daTestModeString(aRow->GetField(2), aRow->GetFieldLength(2)); // field 2 = DA test mode flag
1988 Bool_t daTestMode = (Bool_t)daTestModeString.Atoi();
1989 entry->SetDATestMode(daTestMode);
1991 // loop on detectors
1992 for(UInt_t ii = 0; ii < nCols; ii++)
1993 entry->SetDetectorStatus(aResult->GetFieldName(ii), aRow->GetField(ii));
1995 entries.AddLast(entry);
2003 //______________________________________________________________________________________________
2004 AliShuttleLogbookEntry* AliShuttle::QueryRunParameters(Int_t run)
2007 // Retrieve run parameters written in the DAQ logbook and sets them into AliShuttleLogbookEntry object
2010 // check connection, in case connect
2015 sqlQuery.Form("select * from %s where run=%d", fConfig->GetDAQlbTable(), run);
2017 TSQLResult* aResult = fServer[4]->Query(sqlQuery);
2019 Log("SHUTTLE", Form("Can't execute query <%s>!", sqlQuery.Data()));
2023 if (aResult->GetRowCount() == 0) {
2024 Log("SHUTTLE", Form("QueryRunParameters - No entry in DAQ Logbook for run %d. Skipping", run));
2029 if (aResult->GetRowCount() > 1) {
2030 Log("SHUTTLE", Form("QueryRunParameters - UNEXPECTED: "
2031 "more than one entry in DAQ Logbook for run %d!", run));
2036 TSQLRow* aRow = aResult->Next();
2039 Log("SHUTTLE", Form("QueryRunParameters - Could not retrieve row for run %d. Skipping", run));
2044 AliShuttleLogbookEntry* entry = new AliShuttleLogbookEntry(run);
2046 for (Int_t ii = 0; ii < aResult->GetFieldCount(); ii++)
2047 entry->SetRunParameter(aResult->GetFieldName(ii), aRow->GetField(ii));
2052 UInt_t startTime = entry->GetStartTime();
2053 UInt_t endTime = entry->GetEndTime();
2054 Bool_t ecsSuccess = entry->GetECSSuccess();
2055 TString runType = entry->GetRunType();
2056 TString tmpdaqstartTime = entry->GetRunParameter("DAQ_time_start");
2057 TString recordingFlagString = entry->GetRunParameter("GDCmStreamRecording");
2058 UInt_t recordingFlag = recordingFlagString.Atoi();
2059 UInt_t daqstartTime = tmpdaqstartTime.Atoi();
2061 UInt_t now = time(0);
2062 Int_t dcsDelay = fConfig->GetDCSDelay()+fConfig->GetDCSQueryOffset();
2064 Bool_t skip = kFALSE;
2066 // runs are processed if
2067 // a) runType is PHYSICS and ecsSuccess is set
2068 // b) runType is not PHYSICS and (ecsSuccess is set or DAQ_time_start is non-0)
2069 // effectively this means that all runs are processed that started properly (ecsSucess behaviour is different for PHYSICS and non-PHYSICS runs (check with ECS!)
2070 if (startTime != 0 && endTime != 0) {
2071 if (endTime > startTime) {
2072 if (endTime >= now - dcsDelay) {
2073 Log("SHUTTLE", Form("Skipping run %d for now, because DCS buffer time is not yet expired", run));
2075 if ((runType == "PHYSICS" || runType == "STANDALONE") && recordingFlag == 0){
2076 Log("SHUTTLE", Form("QueryRunParameters - Run type for run %d is %s but the recording is OFF - Skipping!", run, runType.Data()));
2080 if (runType == "PHYSICS") {
2084 Log("SHUTTLE", Form("QueryRunParameters - Run type for run %d is PHYSICS but ECS success flag not set (Reason = %s) - Skipping!", run, entry->GetRunParameter("eor_reason")));
2088 if (ecsSuccess || daqstartTime > 0) {
2089 if (ecsSuccess == kFALSE)
2090 Log("SHUTTLE", Form("Processing run %d although in status ECS failure (Reason: %s), since run type != PHYSICS and DAQ_time_start != 0", run, entry->GetRunParameter("eor_reason")));
2093 Log("SHUTTLE", Form("QueryRunParameters - Run type for run %d is %s, ECS success flag was not set (Reason = %s) and DAQ_time_start was NULL - Skipping!", run, runType.Data(), entry->GetRunParameter("eor_reason")));
2100 Log("SHUTTLE", Form("QueryRunParameters - Invalid parameters for run %d: startTime equal to endTime: %d %d - Skipping!", run, startTime, endTime));
2104 Log("SHUTTLE", Form("QueryRunParameters - Invalid parameters for Run %d: "
2105 "startTime = %d, endTime = %d. Skipping (Shuttle won't be marked as DONE)!",
2106 run, startTime, endTime));
2111 Log("SHUTTLE", Form("Marking SHUTTLE skipped for run %d", run));
2112 fLogbookEntry = entry;
2113 if (!UpdateShuttleLogbook("shuttle_skipped"))
2115 AliError(Form("Could not update logbook for run %d !", run));
2117 if (!UpdateTableSkippedCase("ALL"))
2119 AliError(Form("Could not update FXS tables for run %d !", run));
2128 //______________________________________________________________________________________________
2129 TMap* AliShuttle::GetValueSet(const char* host, Int_t port, const TSeqCollection* entries,
2130 DCSType type, Int_t multiSplit)
2132 // Retrieve all "entry" data points from the DCS server
2133 // host, port: TSocket connection parameters
2134 // entries: list of name of the alias or data point
2135 // type: kAlias or kDP
2136 // returns TMap of values, 0 when failure
2138 AliDCSClient client(host, port, fTimeout, fRetries, multiSplit);
2143 //result = client.GetAliasValues(entries, GetCurrentStartTime()-offset,
2144 // GetCurrentEndTime()+offset);
2145 result = client.GetAliasValues(entries, GetStartTimeDCSQuery(),
2146 GetEndTimeDCSQuery());
2148 else if (type == kDP)
2150 //result = client.GetDPValues(entries, GetCurrentStartTime()-offset,
2151 // GetCurrentEndTime()+offset);
2152 result = client.GetDPValues(entries, GetStartTimeDCSQuery(),
2153 GetEndTimeDCSQuery());
2158 Log(fCurrentDetector.Data(), Form("GetValueSet - Can't get entries! Reason: %s",
2159 client.GetErrorString(client.GetResultErrorCode())));
2160 if (client.GetResultErrorCode() == AliDCSClient::fgkServerError)
2161 Log(fCurrentDetector.Data(), Form("GetValueSet - Server error code: %s",
2162 client.GetServerError().Data()));
2170 //______________________________________________________________________________________________
2171 const char* AliShuttle::GetFile(Int_t system, const char* detector,
2172 const char* id, const char* source)
2174 // Get calibration file from file exchange servers
2175 // First queris the FXS database for the file name, using the run, detector, id and source info
2176 // then calls RetrieveFile(filename) for actual copy to local disk
2177 // run: current run being processed (given by Logbook entry fLogbookEntry)
2178 // detector: the Preprocessor name
2179 // id: provided as a parameter by the Preprocessor
2180 // source: provided by the Preprocessor through GetFileSources function
2182 // check if test mode should simulate a FXS error
2183 if (fTestMode & kErrorFXSFiles)
2185 Log(detector, Form("GetFile - In TESTMODE - Simulating error while connecting to %s FXS", GetSystemName(system)));
2189 // check connection, in case connect
2190 if (!Connect(system))
2192 Log(detector, Form("GetFile - Couldn't connect to %s FXS database", GetSystemName(system)));
2197 // Query preparation
2198 TString sourceName(source);
2200 TString sqlQueryStart = Form("select filePath,size,fileChecksum from %s where",
2201 fConfig->GetFXSdbTable(system));
2202 TString whereClause = Form("run=%d and detector=\"%s\" and fileId=\"%s\"",
2203 GetCurrentRun(), detector, id);
2205 if (system == kDAQ || system == kDQM)
2207 whereClause += Form(" and DAQsource=\"%s\"", source);
2209 else if (system == kDCS)
2213 else if (system == kHLT)
2215 whereClause += Form(" and DDLnumbers=\"%s\"", source);
2218 TString sqlQuery = Form("%s %s", sqlQueryStart.Data(), whereClause.Data());
2220 AliDebug(2, Form("SQL query: \n%s",sqlQuery.Data()));
2223 TSQLResult* aResult = 0;
2224 aResult = dynamic_cast<TSQLResult*> (fServer[system]->Query(sqlQuery));
2226 Log(detector, Form("GetFile - Can't execute SQL query to %s database for: id = %s, source = %s",
2227 GetSystemName(system), id, sourceName.Data()));
2232 if (aResult->GetRowCount() == 0)
2235 Form("GetFile - No entry in %s FXS db for: id = %s, source = %s",
2236 GetSystemName(system), id, sourceName.Data()));
2241 if (aResult->GetRowCount() > 1) {
2243 Form("GetFile - More than one entry in %s FXS db for: id = %s, source = %s",
2244 GetSystemName(system), id, sourceName.Data()));
2250 if (aResult->GetFieldCount() != nFields) {
2252 Form("GetFileName - Wrong field count in %s FXS db for: id = %s, source = %s",
2253 GetSystemName(system), id, sourceName.Data()));
2259 TSQLRow* aRow = dynamic_cast<TSQLRow*> (aResult->Next());
2262 Log(detector, Form("GetFile - Empty set result in %s FXS db from query: id = %s, source = %s",
2263 GetSystemName(system), id, sourceName.Data()));
2269 TString filePath(aRow->GetField(0), aRow->GetFieldLength(0));
2270 TString fileSize(aRow->GetField(1), aRow->GetFieldLength(1));
2271 TString fileChecksum(aRow->GetField(2), aRow->GetFieldLength(2));
2276 AliDebug(2, Form("filePath = %s; size = %s, fileChecksum = %s",
2277 filePath.Data(), fileSize.Data(), fileChecksum.Data()));
2279 // retrieved file is renamed to make it unique
2280 Int_t dir_lev1 = GetCurrentRun()/10000;
2281 TString localFileName = Form("%s/%d/%d/%s_process/%s_%s_%d_%s_%s.shuttle",
2282 GetShuttleTempDir(), dir_lev1, GetCurrentRun(), detector,
2283 GetSystemName(system), detector, GetCurrentRun(),
2284 id, sourceName.Data());
2285 Log("SHUTTLE",Form("file from FXS = %s",localFileName.Data()));
2288 // file retrieval from FXS
2289 UInt_t nRetries = 0;
2290 UInt_t maxRetries = 3;
2291 Bool_t result = kFALSE;
2293 // copy!! if successful TSystem::Exec returns 0
2294 while (nRetries++ < maxRetries) {
2295 AliDebug(2, Form("Trying to copy file. Retry # %d", nRetries));
2296 result = RetrieveFile(system, filePath.Data(), localFileName.Data());
2299 Log(detector, Form("GetFile - Copy of file %s from %s FXS failed",
2300 filePath.Data(), GetSystemName(system)));
2304 if (fileSize.Length()>0)
2306 // compare filesize of local file with the one stored in the FXS DB
2308 Int_t sizeComp = gSystem->GetPathInfo(localFileName.Data(), 0, &size, 0, 0);
2310 if (sizeComp != 0 || size != fileSize.Atoi())
2312 Log(detector, Form("GetFile - size of file %s does not match with local copy!",
2319 Log(fCurrentDetector, Form("GetFile - size of file %s not set in %s database, skipping comparison",
2320 filePath.Data(), GetSystemName(system)));
2323 if (fileChecksum.Length()>0)
2325 // compare md5sum of local file with the one stored in the FXS DB
2326 if(fileChecksum.Contains(' ')) fileChecksum.Resize(fileChecksum.First(' '));
2327 Int_t md5Comp = gSystem->Exec(Form("md5sum %s |grep %s > /dev/null 2> /dev/null",
2328 localFileName.Data(), fileChecksum.Data()));
2332 Log(detector, Form("GetFile - md5sum of file %s does not match with local copy!",
2338 Log(fCurrentDetector, Form("GetFile - md5sum of file %s not set in %s database, skipping comparison",
2339 filePath.Data(), GetSystemName(system)));
2350 fFXSCalled[system]=kTRUE;
2351 TObjString *fileParams = new TObjString(Form("%s#!?!#%s", id, sourceName.Data()));
2352 fFXSlist[system].Add(fileParams);
2354 static TString staticLocalFileName;
2355 staticLocalFileName.Form("%s", localFileName.Data());
2357 Log(fCurrentDetector, Form("GetFile - Retrieved file with id %s and "
2358 "source %s from %s to %s", id, source,
2359 GetSystemName(system), localFileName.Data()));
2361 return staticLocalFileName.Data();
2364 //______________________________________________________________________________________________
2365 Bool_t AliShuttle::RetrieveFile(UInt_t system, const char* fxsFileName, const char* localFileName)
2368 // Copies file from FXS to local Shuttle machine
2371 // check temp directory: trying to cd to temp; if it does not exist, create it
2372 AliDebug(2, Form("Copy file %s from %s FXS into %s",
2373 GetSystemName(system), fxsFileName, localFileName));
2375 TString tmpDir(localFileName);
2377 tmpDir = tmpDir(0,tmpDir.Last('/'));
2379 Int_t noDir = gSystem->GetPathInfo(tmpDir.Data(), 0, (Long64_t*) 0, 0, 0);
2380 if (noDir) // temp dir does not exists!
2382 if (gSystem->mkdir(tmpDir.Data(), 1))
2384 Log(fCurrentDetector.Data(), "RetrieveFile - could not make temp directory!!");
2389 TString command = Form("scp -oPort=%d -2 %s@%s:%s/%s %s",
2390 fConfig->GetFXSPort(system),
2391 fConfig->GetFXSUser(system),
2392 fConfig->GetFXSHost(system),
2393 fConfig->GetFXSBaseFolder(system),
2397 AliDebug(2, Form("%s",command.Data()));
2399 Bool_t result = (gSystem->Exec(command.Data()) == 0);
2404 //______________________________________________________________________________________________
2405 TList* AliShuttle::GetFileSources(Int_t system, const char* detector, const char* id)
2408 // Get sources producing the condition file Id from file exchange servers
2409 // if id is NULL all sources are returned (distinct)
2414 Log(detector, Form("GetFileSources - Querying %s FXS for files with id %s produced by %s", GetSystemName(system), id, detector));
2416 Log(detector, Form("GetFileSources - Querying %s FXS for files produced by %s", GetSystemName(system), detector));
2419 // check if test mode should simulate a FXS error
2420 if (fTestMode & kErrorFXSSources)
2422 Log(detector, Form("GetFileSources - In TESTMODE - Simulating error while connecting to %s FXS", GetSystemName(system)));
2428 Log(detector, "GetFileSources - WARNING: DCS system has only one source of data!");
2429 TList *list = new TList();
2431 list->Add(new TObjString(" "));
2435 // check connection, in case connect
2436 if (!Connect(system))
2438 Log(detector, Form("GetFileSources - Couldn't connect to %s FXS database", GetSystemName(system)));
2443 TString sourceName = "";
2444 if (system == kDAQ || system == kDQM)
2446 sourceName = "DAQsource";
2447 } else if (system == kHLT)
2449 sourceName = "DDLnumbers";
2452 TString sqlQueryStart = Form("select distinct %s from %s where", sourceName.Data(), fConfig->GetFXSdbTable(system));
2453 TString whereClause = Form("run=%d and detector=\"%s\"",
2454 GetCurrentRun(), detector);
2456 whereClause += Form(" and fileId=\"%s\"", id);
2457 TString sqlQuery = Form("%s %s", sqlQueryStart.Data(), whereClause.Data());
2459 AliDebug(2, Form("SQL query: \n%s",sqlQuery.Data()));
2462 TSQLResult* aResult;
2463 aResult = fServer[system]->Query(sqlQuery);
2465 Log(detector, Form("GetFileSources - Can't execute SQL query to %s database for id: %s",
2466 GetSystemName(system), id));
2471 TList *list = new TList();
2474 if (aResult->GetRowCount() == 0)
2477 Form("GetFileSources - No entry in %s FXS table for id: %s", GetSystemName(system), id));
2482 Log(detector, Form("GetFileSources - Found %d sources", aResult->GetRowCount()));
2485 while ((aRow = aResult->Next()))
2488 TString source(aRow->GetField(0), aRow->GetFieldLength(0));
2489 AliDebug(2, Form("%s = %s", sourceName.Data(), source.Data()));
2490 list->Add(new TObjString(source));
2499 //______________________________________________________________________________________________
2500 TList* AliShuttle::GetFileIDs(Int_t system, const char* detector, const char* source)
2503 // Get all ids of condition files produced by a given source from file exchange servers
2506 Log(detector, Form("GetFileIDs - Retrieving ids with source %s with %s", source, GetSystemName(system)));
2508 // check if test mode should simulate a FXS error
2509 if (fTestMode & kErrorFXSSources)
2511 Log(detector, Form("GetFileIDs - In TESTMODE - Simulating error while connecting to %s FXS", GetSystemName(system)));
2515 // check connection, in case connect
2516 if (!Connect(system))
2518 Log(detector, Form("GetFileIDs - Couldn't connect to %s FXS database", GetSystemName(system)));
2522 TString sourceName = "";
2525 sourceName = "DAQsource";
2526 } else if (system == kHLT)
2528 sourceName = "DDLnumbers";
2531 TString sqlQueryStart = Form("select fileId from %s where", fConfig->GetFXSdbTable(system));
2532 TString whereClause = Form("run=%d and detector=\"%s\"",
2533 GetCurrentRun(), detector);
2534 if (sourceName.Length() > 0 && source)
2535 whereClause += Form(" and %s=\"%s\"", sourceName.Data(), source);
2536 TString sqlQuery = Form("%s %s", sqlQueryStart.Data(), whereClause.Data());
2538 AliDebug(2, Form("SQL query: \n%s",sqlQuery.Data()));
2541 TSQLResult* aResult;
2542 aResult = fServer[system]->Query(sqlQuery);
2544 Log(detector, Form("GetFileIDs - Can't execute SQL query to %s database for source: %s",
2545 GetSystemName(system), source));
2549 TList *list = new TList();
2552 if (aResult->GetRowCount() == 0)
2555 Form("GetFileIDs - No entry in %s FXS table for source: %s", GetSystemName(system), source));
2560 Log(detector, Form("GetFileIDs - Found %d ids", aResult->GetRowCount()));
2564 while ((aRow = aResult->Next()))
2567 TString id(aRow->GetField(0), aRow->GetFieldLength(0));
2568 AliDebug(2, Form("fileId = %s", id.Data()));
2569 list->Add(new TObjString(id));
2578 //______________________________________________________________________________________________
2579 Bool_t AliShuttle::Connect(Int_t system)
2581 // Connect to MySQL Server of the system's FXS MySQL databases
2582 // DAQ Logbook, Shuttle Logbook and DAQ FXS db are on the same host
2585 // check connection: if already connected return
2587 if(fServer[system] && fServer[system]->IsConnected()) {
2589 if (fServer[system]->PingVerify()==kTRUE){ // connection is still alive
2593 AliWarning(Form("Connection got lost to FXS database for %s. Closing and reconnecting.",
2594 AliShuttleInterface::GetSystemName(system)));
2595 fServer[system]->Close();
2596 delete fServer[system];
2597 fServer[system] = 0x0;
2601 TString dbHost, dbUser, dbPass, dbName;
2603 if (system < 4) // FXS db servers
2605 dbHost = Form("mysql://%s:%d", fConfig->GetFXSdbHost(system), fConfig->GetFXSdbPort(system));
2606 dbUser = fConfig->GetFXSdbUser(system);
2607 dbPass = fConfig->GetFXSdbPass(system);
2608 dbName = fConfig->GetFXSdbName(system);
2609 } else { // Run & Shuttle logbook servers
2610 // TODO Will the Shuttle logbook server be the same as the Run logbook server ???
2611 dbHost = Form("mysql://%s:%d", fConfig->GetDAQlbHost(), fConfig->GetDAQlbPort());
2612 dbUser = fConfig->GetDAQlbUser();
2613 dbPass = fConfig->GetDAQlbPass();
2614 dbName = fConfig->GetDAQlbDB();
2617 fServer[system] = TSQLServer::Connect(dbHost.Data(), dbUser.Data(), dbPass.Data());
2618 if (!fServer[system] || !fServer[system]->IsConnected()) {
2621 AliError(Form("Can't establish connection to FXS database for %s",
2622 AliShuttleInterface::GetSystemName(system)));
2624 AliError("Can't establish connection to Run logbook.");
2626 if(fServer[system]) delete fServer[system];
2631 TSQLResult* aResult=0;
2634 aResult = fServer[kDAQ]->GetTables(dbName.Data());
2637 aResult = fServer[kDCS]->GetTables(dbName.Data());
2640 aResult = fServer[kHLT]->GetTables(dbName.Data());
2643 aResult = fServer[kDQM]->GetTables(dbName.Data());
2646 aResult = fServer[4]->GetTables(dbName.Data());
2654 //______________________________________________________________________________________________
2655 Bool_t AliShuttle::UpdateTable()
2658 // Update FXS table filling time_processed field in all rows corresponding to current run and detector
2661 Bool_t result = kTRUE;
2663 for (UInt_t system=0; system<4; system++)
2665 if(!fFXSCalled[system]) continue;
2667 // check connection, in case connect
2668 if (!Connect(system))
2670 Log(fCurrentDetector, Form("UpdateTable - Couldn't connect to %s FXS database", GetSystemName(system)));
2675 TTimeStamp now; // now
2677 // Loop on FXS list entries
2678 TIter iter(&fFXSlist[system]);
2679 TObjString *aFXSentry=0;
2680 while ((aFXSentry = dynamic_cast<TObjString*> (iter.Next())))
2682 TString aFXSentrystr = aFXSentry->String();
2683 TObjArray *aFXSarray = aFXSentrystr.Tokenize("#!?!#");
2684 if (!aFXSarray || aFXSarray->GetEntries() != 2 )
2686 Log(fCurrentDetector, Form("UpdateTable - error updating %s FXS entry. Check string: <%s>",
2687 GetSystemName(system), aFXSentrystr.Data()));
2688 if(aFXSarray) delete aFXSarray;
2692 const char* fileId = ((TObjString*) aFXSarray->At(0))->GetName();
2693 const char* source = ((TObjString*) aFXSarray->At(1))->GetName();
2695 TString whereClause;
2696 if (system == kDAQ || system == kDQM)
2698 whereClause = Form("where run=%d and detector=\"%s\" and fileId=\"%s\" and DAQsource=\"%s\";",
2699 GetCurrentRun(), fCurrentDetector.Data(), fileId, source);
2701 else if (system == kDCS)
2703 whereClause = Form("where run=%d and detector=\"%s\" and fileId=\"%s\";",
2704 GetCurrentRun(), fCurrentDetector.Data(), fileId);
2706 else if (system == kHLT)
2708 whereClause = Form("where run=%d and detector=\"%s\" and fileId=\"%s\" and DDLnumbers=\"%s\";",
2709 GetCurrentRun(), fCurrentDetector.Data(), fileId, source);
2714 TString sqlQuery = Form("update %s set time_processed=%ld %s", fConfig->GetFXSdbTable(system),
2715 (ULong_t)now.GetSec(), whereClause.Data());
2717 AliDebug(2, Form("SQL query: \n%s",sqlQuery.Data()));
2720 TSQLResult* aResult;
2721 aResult = dynamic_cast<TSQLResult*> (fServer[system]->Query(sqlQuery));
2724 Log(fCurrentDetector, Form("UpdateTable - %s db: can't execute SQL query <%s>",
2725 GetSystemName(system), sqlQuery.Data()));
2736 //_______________________________________________________________________________
2737 Bool_t AliShuttle::UpdateTableSkippedCase(const char* detector)
2740 // Update FXS table filling time_processed field in all rows corresponding to current run and detector
2741 // if detector = "ALL" update all detectors
2744 Bool_t result = kTRUE;
2746 TString detName(detector);
2748 for (UInt_t system=0; system<4; system++)
2751 // check connection, in case connect
2752 if (!Connect(system))
2754 Log(fCurrentDetector, Form("UpdateTableSkippedCase - Couldn't connect to %s FXS database", GetSystemName(system)));
2759 TTimeStamp now; // now
2761 // Loop on FXS list entries
2762 TIter iter(&fFXSlist[system]);
2764 TString whereClause;
2765 if (detName == "ALL") whereClause = Form("where run=%d and time_processed IS NULL;",GetCurrentRun());
2766 else whereClause = Form("where run=%d and detector=\"%s\" and time_processed IS NULL;",GetCurrentRun(), detector);
2768 //Log("SHUTTLE",Form(" whereClause = %s ",whereClause.Data()));
2770 TString sqlQuery = Form("update %s set time_processed=%ld %s", fConfig->GetFXSdbTable(system),
2771 (ULong_t)now.GetSec(), whereClause.Data());
2773 AliDebug(2, Form("SQL query: \n%s",sqlQuery.Data()));
2776 TSQLResult* aResult;
2777 aResult = dynamic_cast<TSQLResult*> (fServer[system]->Query(sqlQuery));
2780 Log("SHUTTLE", Form("UpdateTableSkippedCase - %s db: can't execute SQL query <%s>",
2781 GetSystemName(system), sqlQuery.Data()));
2791 //______________________________________________________________________________________________
2792 Bool_t AliShuttle::UpdateTableFailCase()
2794 // Update FXS table filling time_processed field in all rows corresponding to current run and detector
2795 // this is called in case the preprocessor is declared failed for the current run, because
2796 // the fields are updated only in case of success
2798 Bool_t result = kTRUE;
2800 for (UInt_t system=0; system<4; system++)
2802 // check connection, in case connect
2803 if (!Connect(system))
2805 Log(fCurrentDetector, Form("UpdateTableFailCase - Couldn't connect to %s FXS database",
2806 GetSystemName(system)));
2811 TTimeStamp now; // now
2813 // Loop on FXS list entries
2815 TString whereClause = Form("where run=%d and detector=\"%s\";",
2816 GetCurrentRun(), fCurrentDetector.Data());
2819 TString sqlQuery = Form("update %s set time_processed=%ld %s", fConfig->GetFXSdbTable(system),
2820 (ULong_t)now.GetSec(), whereClause.Data());
2822 AliDebug(2, Form("SQL query: \n%s",sqlQuery.Data()));
2825 TSQLResult* aResult;
2826 aResult = dynamic_cast<TSQLResult*> (fServer[system]->Query(sqlQuery));
2829 Log(fCurrentDetector, Form("UpdateTableFailCase - %s db: can't execute SQL query <%s>",
2830 GetSystemName(system), sqlQuery.Data()));
2840 //______________________________________________________________________________________________
2841 Bool_t AliShuttle::UpdateShuttleLogbook(const char* detector, const char* status)
2844 // Update Shuttle logbook filling detector or shuttle_done column
2845 // ex. of usage: UpdateShuttleLogbook("PHOS", "DONE") or UpdateShuttleLogbook("shuttle_done")
2848 // check connection, in case connect
2850 Log("SHUTTLE", "UpdateShuttleLogbook - Couldn't connect to DAQ Logbook.");
2854 TString detName(detector);
2856 if (detName == "shuttle_done" || detName == "shuttle_skipped")
2858 setClause = "set shuttle_done=1";
2860 if (detName == "shuttle_done")
2862 if (TouchFile() != kTRUE)
2864 SendMLRunInfo("Pending");
2868 SendMLRunInfo("Done");
2871 SendMLRunInfo("Skipped");
2874 TString statusStr(status);
2875 if(statusStr.Contains("done", TString::kIgnoreCase) ||
2876 statusStr.Contains("failed", TString::kIgnoreCase)){
2877 setClause = Form("set %s=\"%s\"", detector, status);
2880 Form("UpdateShuttleLogbook - Invalid status <%s> for detector %s",
2886 TString whereClause = Form("where run=%d", GetCurrentRun());
2888 TString sqlQuery = Form("update %s %s %s",
2889 fConfig->GetShuttlelbTable(), setClause.Data(), whereClause.Data());
2891 AliDebug(2, Form("SQL query: \n%s",sqlQuery.Data()));
2894 TSQLResult* aResult;
2895 aResult = dynamic_cast<TSQLResult*> (fServer[4]->Query(sqlQuery));
2897 Log("SHUTTLE", Form("UpdateShuttleLogbook - Can't execute query <%s>", sqlQuery.Data()));
2905 //______________________________________________________________________________________________
2906 Int_t AliShuttle::GetCurrentRun() const
2909 // Get current run from logbook entry
2912 return fLogbookEntry ? fLogbookEntry->GetRun() : -1;
2915 //______________________________________________________________________________________________
2916 UInt_t AliShuttle::GetCurrentStartTime() const
2919 // get current start time
2922 return fLogbookEntry ? fLogbookEntry->GetStartTime() : 0;
2925 //______________________________________________________________________________________________
2926 UInt_t AliShuttle::GetCurrentEndTime() const
2929 // get current end time from logbook entry
2932 return fLogbookEntry ? fLogbookEntry->GetEndTime() : 0;
2934 //______________________________________________________________________________________________
2935 UInt_t AliShuttle::GetCurrentYear() const
2938 // Get current year from logbook entry
2941 if (!fLogbookEntry) return 0;
2943 TTimeStamp startTime(GetCurrentStartTime());
2944 TString year = Form("%d",startTime.GetDate());
2950 //______________________________________________________________________________________________
2951 const char* AliShuttle::GetLHCPeriod() const
2954 // Get current LHC period from logbook entry
2957 if (!fLogbookEntry) return 0;
2959 return fLogbookEntry->GetRunParameter("LHCperiod");
2962 //______________________________________________________________________________________________
2963 void AliShuttle::Log(const char* detector, const char* message, UInt_t level)
2966 // Fill log string with a message
2969 TString logRunDir = GetShuttleLogDir();
2970 if (GetCurrentRun() >=0) {
2971 Int_t logDir_lev1 = GetCurrentRun()/10000;
2972 logRunDir += Form("/%d/%d", logDir_lev1, GetCurrentRun());
2974 void* dir = gSystem->OpenDirectory(logRunDir.Data());
2976 if (gSystem->mkdir(logRunDir.Data(), kTRUE)) {
2977 AliError(Form("Can't open directory <%s>", GetShuttleLogDir()));
2982 gSystem->FreeDirectory(dir);
2985 TString toLog = Form("%s UTC (%d): %s - ", TTimeStamp(time(0)).AsString("s"), getpid(), detector);
2986 if (GetCurrentRun() >= 0)
2987 toLog += Form("run %d - ", GetCurrentRun());
2988 toLog += Form("%s", message);
2990 AliLog::Message(level, toLog, MODULENAME(), ClassName(), FUNCTIONNAME(), __FILE__, __LINE__);
2992 // if we redirect the log output already to the file, leave here
2993 if (fOutputRedirected && strcmp(detector, "SHUTTLE") != 0)
2996 TString fileName = GetLogFileName(detector);
2998 gSystem->ExpandPathName(fileName);
3001 logFile.open(fileName, ofstream::out | ofstream::app);
3003 if (!logFile.is_open()) {
3004 AliError(Form("Could not open file %s", fileName.Data()));
3008 logFile << toLog.Data() << "\n";
3013 //______________________________________________________________________________________________
3014 TString AliShuttle::GetLogFileName(const char* detector) const
3017 // returns the name of the log file for a given sub detector
3022 if (GetCurrentRun() >= 0)
3024 Int_t logDir_lev1 = GetCurrentRun()/10000;
3025 fileName.Form("%s/%d/%d/%s.log", GetShuttleLogDir(), logDir_lev1, GetCurrentRun(),
3028 fileName.Form("%s/%s.log", GetShuttleLogDir(), detector);
3034 //______________________________________________________________________________________________
3035 void AliShuttle::SendAlive()
3037 // sends alive message to ML
3039 TMonaLisaText mlStatus("SHUTTLE_status", "Alive");
3042 mlList.Add(&mlStatus);
3044 fMonaLisa->SendParameters(&mlList, "__PROCESSINGINFO__");
3047 //______________________________________________________________________________________________
3048 Bool_t AliShuttle::Collect(Int_t run)
3051 // Collects conditions data for all UNPROCESSED run written to DAQ LogBook in case of run = -1 (default)
3052 // If a dedicated run is given this run is processed
3054 // In operational mode, this is the Shuttle function triggered by the EOR signal.
3058 Log("SHUTTLE","Collect - Shuttle called. Collecting conditions data for unprocessed runs");
3060 Log("SHUTTLE", Form("Collect - Shuttle called. Collecting conditions data for run %d", run));
3062 SetLastAction("Starting");
3064 // create ML instance
3066 fMonaLisa = new TMonaLisaWriter(fConfig->GetMonitorHost(), fConfig->GetMonitorTable());
3070 TString whereClause("where shuttle_done=0");
3072 whereClause += Form(" and run=%d", run);
3074 TObjArray shuttleLogbookEntries;
3075 if (!QueryShuttleLogbook(whereClause, shuttleLogbookEntries))
3077 Log("SHUTTLE", "Collect - Can't retrieve entries from Shuttle logbook");
3081 if (shuttleLogbookEntries.GetEntries() == 0)
3084 Log("SHUTTLE","Collect - Found no UNPROCESSED runs in Shuttle logbook");
3086 Log("SHUTTLE", Form("Collect - Run %d is already DONE "
3087 "or it does not exist in Shuttle logbook", run));
3091 for (UInt_t iDet=0; iDet<NDetectors(); iDet++)
3092 fFirstUnprocessed[iDet] = kTRUE;
3096 // query Shuttle logbook for earlier runs, check if some detectors are unprocessed,
3097 // flag them into fFirstUnprocessed array
3098 TString whereClauseBis(Form("where shuttle_done=0 and run < %d", run));
3099 TObjArray tmpLogbookEntries;
3100 if (!QueryShuttleLogbook(whereClauseBis, tmpLogbookEntries))
3102 Log("SHUTTLE", "Collect - Can't retrieve entries from Shuttle logbook");
3106 TIter iter(&tmpLogbookEntries);
3107 AliShuttleLogbookEntry* anEntry = 0;
3108 while ((anEntry = dynamic_cast<AliShuttleLogbookEntry*> (iter.Next())))
3110 for (UInt_t iDet=0; iDet<NDetectors(); iDet++)
3112 if (anEntry->GetDetectorStatus(iDet) == AliShuttleLogbookEntry::kUnprocessed)
3114 AliDebug(2, Form("Run %d: setting %s as \"not first time unprocessed\"",
3115 anEntry->GetRun(), GetDetName(iDet)));
3116 fFirstUnprocessed[iDet] = kFALSE;
3124 if (!RetrieveConditionsData(shuttleLogbookEntries))
3126 Log("SHUTTLE", "Collect - Process of at least one run failed");
3131 Log("SHUTTLE", "Collect - Requested run(s) successfully processed");
3136 //______________________________________________________________________________________________
3137 Bool_t AliShuttle::RetrieveConditionsData(const TObjArray& dateEntries)
3140 // Retrieve conditions data for all runs that aren't processed yet
3143 Bool_t hasError = kFALSE;
3145 TIter iter(&dateEntries);
3146 AliShuttleLogbookEntry* anEntry;
3148 while ((anEntry = (AliShuttleLogbookEntry*) iter.Next())){
3149 if (!Process(anEntry)){
3153 // clean SHUTTLE temp directory
3154 //TString filename = Form("%s/*.shuttle", GetShuttleTempDir());
3155 //RemoveFile(filename.Data());
3158 return hasError == kFALSE;
3161 //______________________________________________________________________________________________
3162 ULong_t AliShuttle::GetTimeOfLastAction() const
3165 // Gets time of last action
3170 fMonitoringMutex->Lock();
3172 tmp = fLastActionTime;
3174 fMonitoringMutex->UnLock();
3179 //______________________________________________________________________________________________
3180 const TString AliShuttle::GetLastAction() const
3183 // returns a string description of the last action
3188 fMonitoringMutex->Lock();
3192 fMonitoringMutex->UnLock();
3197 //______________________________________________________________________________________________
3198 void AliShuttle::SetLastAction(const char* action)
3201 // updates the monitoring variables
3204 fMonitoringMutex->Lock();
3206 fLastAction = action;
3207 fLastActionTime = time(0);
3209 fMonitoringMutex->UnLock();
3212 //______________________________________________________________________________________________
3213 const char* AliShuttle::GetRunParameter(const char* param)
3216 // returns run parameter read from DAQ logbook
3219 if(!fLogbookEntry) {
3220 AliError("No logbook entry!");
3224 return fLogbookEntry->GetRunParameter(param);
3227 //______________________________________________________________________________________________
3228 AliCDBEntry* AliShuttle::GetFromOCDB(const char* detector, const AliCDBPath& path)
3231 // returns object from OCDB valid for current run
3234 if (fTestMode & kErrorOCDB)
3236 Log(detector, "GetFromOCDB - In TESTMODE - Simulating error with OCDB");
3240 AliCDBStorage *sto = AliCDBManager::Instance()->GetStorage(fgkMainCDB);
3243 Log(detector, "GetFromOCDB - Cannot activate main OCDB for query!");
3247 return dynamic_cast<AliCDBEntry*> (sto->Get(path, GetCurrentRun()));
3250 //______________________________________________________________________________________________
3251 Bool_t AliShuttle::SendMail(EMailTarget target, Int_t system)
3254 // sends a mail to the subdetector expert in case of preprocessor error
3257 if (fTestMode != kNone)
3260 if (!fConfig->SendMail())
3263 if (target == kDCSEMail || target == kFXSEMail) {
3264 if (!fFirstProcessing)
3268 Int_t runMode = (Int_t)fConfig->GetRunMode();
3270 if (runMode == 0) tmpStr = " Nightly Test:";
3271 else tmpStr = " Data Taking:";
3272 void* dir = gSystem->OpenDirectory(GetShuttleLogDir());
3275 if (gSystem->mkdir(GetShuttleLogDir(), kTRUE))
3277 Log("SHUTTLE", Form("SendMail - Can't open directory <%s>", GetShuttleLogDir()));
3282 gSystem->FreeDirectory(dir);
3285 // det experts in to
3287 TIter *iterExperts = 0;
3288 if (target == kDCSEMail) {
3289 iterExperts = new TIter(fConfig->GetAdmins(AliShuttleConfig::kAmanda));
3291 else if (target == kFXSEMail) {
3292 iterExperts = new TIter(fConfig->GetAdmins(system));
3295 TObjString *anExpert=0;
3296 while ((anExpert = (TObjString*) iterExperts->Next()))
3298 to += Form("%s,", anExpert->GetName());
3303 // add subdetector experts
3304 iterExperts = new TIter(fConfig->GetResponsibles(fCurrentDetector));
3305 TObjString *anExpert=0;
3306 while ((anExpert = (TObjString*) iterExperts->Next()))
3308 to += Form("%s,", anExpert->GetName());
3312 if (to.Length() > 0)
3313 to.Remove(to.Length()-1);
3314 AliDebug(2, Form("to: %s",to.Data()));
3317 Log("SHUTTLE", Form("List of %d responsibles not set!", (Int_t) target));
3321 // SHUTTLE responsibles in cc
3323 TIter iterAdmins(fConfig->GetAdmins(AliShuttleConfig::kGlobal));
3324 TObjString *anAdmin=0;
3325 while ((anAdmin = (TObjString*) iterAdmins.Next()))
3327 cc += Form("%s,", anAdmin->GetName());
3329 if (cc.Length() > 0)
3330 cc.Remove(cc.Length()-1);
3331 AliDebug(2, Form("cc: %s",to.Data()));
3334 TString bodyFileName;
3335 bodyFileName.Form("%s/mail.body", GetShuttleLogDir());
3336 gSystem->ExpandPathName(bodyFileName);
3339 mailBody.open(bodyFileName, ofstream::out);
3341 if (!mailBody.is_open())
3343 Log("SHUTTLE", Form("Could not open mail body file %s", bodyFileName.Data()));
3351 if (target == kDCSEMail){
3352 subject = Form("%s CRITICAL Retrieval of data points for %s FAILED in run %d !",
3353 tmpStr.Data(), fCurrentDetector.Data(), GetCurrentRun());
3354 AliDebug(2, Form("subject: %s", subject.Data()));
3356 body = Form("Dear DCS experts, \n\n");
3357 body += Form("SHUTTLE couldn\'t retrieve the data points for detector %s "
3358 "in run %d!!\n\n", fCurrentDetector.Data(), GetCurrentRun());
3360 else if (target == kFXSEMail){
3361 subject = Form("%s CRITICAL FXS communication for %s FAILED in run %d !",
3362 tmpStr.Data(), fCurrentDetector.Data(), GetCurrentRun());
3363 AliDebug(2, Form("subject: %s", subject.Data()));
3365 if (system == kDAQ) sys="DAQ";
3366 else if (system == kDCS) sys="DCS";
3367 else if (system == kHLT) sys="HLT";
3368 else if (system == kDQM) sys="DQM";
3370 body = Form("Dear %s FXS experts, \n\n",sys.Data());
3371 body += Form("SHUTTLE couldn\'t retrieve data from the FXS for detector %s "
3372 "in run %d!!\n\n", fCurrentDetector.Data(), GetCurrentRun());
3373 body += Form("The contacted server was:\nDB: %s\nFXS:%s\n\n", fConfig->GetFXSdbHost(system), fConfig->GetFXSHost(system));
3376 subject = Form("%s %s Shuttle preprocessor FAILED in run %d (run type = %s)!",
3377 tmpStr.Data(), fCurrentDetector.Data(), GetCurrentRun(), GetRunType());
3378 AliDebug(2, Form("subject: %s", subject.Data()));
3380 body = Form("Dear %s expert(s), \n\n", fCurrentDetector.Data());
3381 body += Form("SHUTTLE just detected that your preprocessor "
3382 "failed processing run %d (run type = %s)!!\n\n",
3383 GetCurrentRun(), GetRunType());
3386 body += Form("Please check %s status on the SHUTTLE monitoring page: \n\n",
3387 fCurrentDetector.Data());
3388 if (fConfig->GetRunMode() == AliShuttleConfig::kTest)
3390 body += Form("\thttp://pcalimonitor.cern.ch/shuttle.jsp?time=24 \n\n");
3392 body += Form("\thttp://pcalimonitor.cern.ch/shuttle.jsp?instance=PROD&time=24 \n\n");
3396 TString logFolder = "logs";
3397 if (fConfig->GetRunMode() == AliShuttleConfig::kProd)
3398 logFolder += "_PROD";
3401 body += Form("Find the %s log for the current run on \n\n"
3402 "\thttp://pcalishuttle02.cern.ch/%s/%d/%d/%s.log \n\n",
3403 fCurrentDetector.Data(), logFolder.Data(), GetCurrentRun()/10000,
3404 GetCurrentRun(), fCurrentDetector.Data());
3405 body += Form("The last 15 lines of %s log file are following:\n\n", fCurrentDetector.Data());
3407 AliDebug(2, Form("Body begin: %s", body.Data()));
3409 mailBody << body.Data();
3411 mailBody.open(bodyFileName, ofstream::out | ofstream::app);
3413 TString logFileName = Form("%s/%d/%d/%s.log", GetShuttleLogDir(),
3414 GetCurrentRun()/10000, GetCurrentRun(), fCurrentDetector.Data());
3415 TString tailCommand = Form("tail -n 15 %s >> %s", logFileName.Data(), bodyFileName.Data());
3416 if (gSystem->Exec(tailCommand.Data()))
3418 mailBody << Form("%s log file not found ...\n\n", fCurrentDetector.Data());
3421 TString endBody = Form("------------------------------------------------------\n\n");
3422 endBody += Form("In case of problems please contact the SHUTTLE core team.\n\n");
3423 endBody += "Please do not answer this message directly, it is automatically generated.\n\n";
3424 endBody += "Greetings,\n\n \t\t\tthe SHUTTLE\n";
3426 AliDebug(2, Form("Body end: %s", endBody.Data()));
3428 mailBody << endBody.Data();
3433 TString mailCommand = Form("mail -s \"%s\" -c %s %s < %s",
3437 bodyFileName.Data());
3438 AliDebug(2, Form("mail command: %s", mailCommand.Data()));
3440 Bool_t result = gSystem->Exec(mailCommand.Data());
3444 //______________________________________________________________________________________________
3445 const char* AliShuttle::GetRunType()
3448 // returns run type read from "run type" logbook
3451 if(!fLogbookEntry) {
3452 AliError("No logbook entry!");
3456 return fLogbookEntry->GetRunType();
3459 //______________________________________________________________________________________________
3460 Bool_t AliShuttle::GetHLTStatus()
3462 // Return HLT status (ON=1 OFF=0)
3463 // Converts the HLT status from the mode string read in the run logbook (not just a bool)
3465 if(!fLogbookEntry) {
3466 AliError("No logbook entry!");
3470 // TODO implement when HLTMode is inserted in run logbook
3471 TString hltMode = fLogbookEntry->GetRunParameter("HLTmode");
3472 TSubString firstChar = hltMode(0,1);
3473 AliDebug(2,Form("First char = %s ",firstChar.Data()));
3474 if (firstChar == "A") {
3477 else if ((firstChar == "B") || (firstChar == "C") || (firstChar == "D") || (firstChar == "E")) {
3481 Log("SHUTTLE","Unexpected HLT mode! Returning 0....");
3486 //______________________________________________________________________________________________
3487 const char* AliShuttle::GetTriggerConfiguration()