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;
954 fStatusEntry = AliCDBManager::Instance()->GetStorage(GetLocalCDB())
955 ->Get(Form("/SHUTTLE/%s/%d", fCurrentDetector.Data(), path1), GetCurrentRun());
957 if (!fStatusEntry) return 0;
958 fStatusEntry->SetOwner(1);
960 AliShuttleStatus* status = dynamic_cast<AliShuttleStatus*> (fStatusEntry->GetObject());
962 AliError("Invalid object stored to CDB!");
969 //______________________________________________________________________________________________
970 Bool_t AliShuttle::WriteShuttleStatus(AliShuttleStatus* status)
973 // writes the status for one subdetector
981 Int_t run = GetCurrentRun();
982 Int_t path1 = run/10000;
983 TString path1_string = Form("%d",path1);
985 AliCDBId id(AliCDBPath("SHUTTLE", fCurrentDetector, path1_string), run, run);
987 fStatusEntry = new AliCDBEntry(status, id, new AliCDBMetaData);
988 fStatusEntry->SetOwner(1);
990 Int_t logLevel = AliLog::GetGlobalLogLevel();
991 AliLog::SetGlobalLogLevel(AliLog::kError);
993 UInt_t result = AliCDBManager::Instance()->GetStorage(fgkLocalCDB)->Put(fStatusEntry);
995 AliLog::SetGlobalLogLevel((AliLog::EType_t)logLevel);
998 Log("SHUTTLE", Form("WriteShuttleStatus - Failed for %s, run %d",
999 fCurrentDetector.Data(), run));
1008 //______________________________________________________________________________________________
1009 void AliShuttle::UpdateShuttleStatus(AliShuttleStatus::Status newStatus, Bool_t increaseCount)
1012 // changes the AliShuttleStatus for the given detector and run to the given status
1016 AliError("UNEXPECTED: fStatusEntry empty");
1020 AliShuttleStatus* status = dynamic_cast<AliShuttleStatus*> (fStatusEntry->GetObject());
1023 Log("SHUTTLE", "UpdateShuttleStatus - UNEXPECTED: status could not be read from current CDB entry");
1027 TString actionStr = Form("UpdateShuttleStatus - %s: Changing state from %s to %s",
1028 fCurrentDetector.Data(),
1029 status->GetStatusName(),
1030 status->GetStatusName(newStatus));
1031 Log("SHUTTLE", actionStr);
1032 SetLastAction(actionStr);
1034 status->SetStatus(newStatus);
1035 if (increaseCount) status->IncreaseCount();
1037 Int_t logLevel = AliLog::GetGlobalLogLevel();
1038 AliLog::SetGlobalLogLevel(AliLog::kError);
1040 AliCDBManager::Instance()->GetStorage(fgkLocalCDB)->Put(fStatusEntry);
1042 AliLog::SetGlobalLogLevel((AliLog::EType_t)logLevel);
1047 //______________________________________________________________________________________________
1048 void AliShuttle::SendMLDetInfo()
1051 // sends ML information about the current status of the current detector being processed
1054 AliShuttleStatus* status = dynamic_cast<AliShuttleStatus*> (fStatusEntry->GetObject());
1057 Log("SHUTTLE", "SendMLDetInfo - UNEXPECTED: status could not be read from current CDB entry");
1061 TMonaLisaText mlStatus(Form("%s_status", fCurrentDetector.Data()), status->GetStatusName());
1062 TMonaLisaValue mlRetryCount(Form("%s_count", fCurrentDetector.Data()), status->GetCount());
1065 mlList.Add(&mlStatus);
1066 mlList.Add(&mlRetryCount);
1069 mlID.Form("%d", GetCurrentRun());
1070 fMonaLisa->SendParameters(&mlList, mlID);
1073 //______________________________________________________________________________________________
1074 Bool_t AliShuttle::ContinueProcessing()
1076 // this function reads the AliShuttleStatus information from CDB and
1077 // checks if the processing should be continued
1078 // if yes it returns kTRUE and updates the AliShuttleStatus with nextStatus
1080 if (!fConfig->HostProcessDetector(fCurrentDetector))
1083 AliPreprocessor* aPreprocessor =
1084 dynamic_cast<AliPreprocessor*> (fPreprocessorMap.GetValue(fCurrentDetector));
1087 Log("SHUTTLE", Form("ContinueProcessing - %s: no preprocessor registered", fCurrentDetector.Data()));
1091 AliShuttleLogbookEntry::Status entryStatus =
1092 fLogbookEntry->GetDetectorStatus(fCurrentDetector);
1094 if (entryStatus != AliShuttleLogbookEntry::kUnprocessed) {
1095 Log("SHUTTLE", Form("ContinueProcessing - %s is %s",
1096 fCurrentDetector.Data(),
1097 fLogbookEntry->GetDetectorStatusName(entryStatus)));
1101 // if we get here, according to Shuttle logbook subdetector is in UNPROCESSED state
1103 // check if current run is first unprocessed run for current detector
1104 if (fConfig->StrictRunOrder(fCurrentDetector) &&
1105 !fFirstUnprocessed[GetDetPos(fCurrentDetector)])
1107 if (fTestMode == kNone)
1109 Log("SHUTTLE", Form("ContinueProcessing - %s requires strict run ordering"
1110 " but this is not the first unprocessed run!",fCurrentDetector.Data()));
1115 Log("SHUTTLE", Form("ContinueProcessing - In TESTMODE - "
1116 "Although %s requires strict run ordering "
1117 "and this is not the first unprocessed run, "
1118 "the SHUTTLE continues",fCurrentDetector.Data()));
1122 // Is the subdetector processed first time for this run?
1123 fFirstProcessing = kFALSE;
1125 AliShuttleStatus* status = ReadShuttleStatus();
1128 Log("SHUTTLE", Form("ContinueProcessing - %s: Processing first time",
1129 fCurrentDetector.Data()));
1130 status = new AliShuttleStatus(AliShuttleStatus::kStarted);
1131 fFirstProcessing = kTRUE;
1132 return WriteShuttleStatus(status);
1135 // The following case shouldn't happen if Shuttle Logbook was correctly updated.
1136 // If it happens it may mean Logbook updating failed... let's do it now!
1137 if (status->GetStatus() == AliShuttleStatus::kDone ||
1138 status->GetStatus() == AliShuttleStatus::kFailed ||
1139 status->GetStatus() == AliShuttleStatus::kSkipped) {
1140 Log("SHUTTLE", Form("ContinueProcessing - %s is already %s. Updating Shuttle Logbook",
1141 fCurrentDetector.Data(),
1142 status->GetStatusName(status->GetStatus())));
1144 if (status->GetStatus() == AliShuttleStatus::kSkipped)
1146 UpdateShuttleLogbook(fCurrentDetector.Data(), "DONE");
1149 UpdateShuttleLogbook(fCurrentDetector.Data(), status->GetStatusName(status->GetStatus()));
1154 if (status->GetStatus() == AliShuttleStatus::kStoreStarted || status->GetStatus() == AliShuttleStatus::kStoreDelayed ||status->GetStatus() == AliShuttleStatus::kStoreError) {
1156 Form("ContinueProcessing - %s: Grid storage of one or more "
1157 "objects failed. Trying again now",
1158 fCurrentDetector.Data()));
1163 // if we get here, there is a restart
1164 Bool_t cont = kFALSE;
1167 if (status->GetCount() >= fConfig->GetMaxRetries()) {
1168 Log("SHUTTLE", Form("ContinueProcessing - %s failed %d times in status %s - "
1169 "Updating Shuttle Logbook", fCurrentDetector.Data(),
1170 status->GetCount(), status->GetStatusName()));
1171 UpdateShuttleLogbook(fCurrentDetector.Data(), "FAILED");
1172 UpdateShuttleStatus(AliShuttleStatus::kFailed);
1174 // there may still be objects in local OCDB and reference storage
1175 // and FXS databases may be not updated: do it now!
1177 // TODO Currently disabled, we want to keep files in case of failure!
1178 // CleanLocalStorage(fgkLocalCDB);
1179 // CleanLocalStorage(fgkLocalRefStorage);
1180 // UpdateTableFailCase();
1182 // Send mail to detector expert!
1183 Log("SHUTTLE", Form("ContinueProcessing - Sending mail to %s expert...",
1184 fCurrentDetector.Data()));
1185 // det experts in to
1187 TIter *iterExperts = 0;
1188 iterExperts = new TIter(fConfig->GetResponsibles(fCurrentDetector));
1189 TObjString *anExpert=0;
1190 while ((anExpert = (TObjString*) iterExperts->Next()))
1192 to += Form("%s, \n", anExpert->GetName());
1196 if (to.Length() > 0)
1197 to.Remove(to.Length()-3);
1198 AliDebug(2, Form("to: %s",to.Data()));
1201 Log("SHUTTLE", Form("List of %s responsibles not set!", fCurrentDetector.Data()));
1205 Log(fCurrentDetector.Data(), Form("ContinueProcessing - Sending mail to %s expert(s):",
1206 fCurrentDetector.Data()));
1207 Log(fCurrentDetector.Data(), Form("\n%s", to.Data()));
1208 if (!SendMail(kPPEMail))
1209 Log("SHUTTLE", Form("ContinueProcessing - Could not send mail to %s expert",
1210 fCurrentDetector.Data()));
1213 Log("SHUTTLE", Form("ContinueProcessing - %s: restarting. "
1214 "Aborted before with %s. Retry number %d.", fCurrentDetector.Data(),
1215 status->GetStatusName(), status->GetCount()));
1216 Bool_t increaseCount = kTRUE;
1217 if (status->GetStatus() == AliShuttleStatus::kDCSError ||
1218 status->GetStatus() == AliShuttleStatus::kDCSStarted ||
1219 status->GetStatus() == AliShuttleStatus::kFXSError ||
1220 status->GetStatus() == AliShuttleStatus::kOCDBError)
1221 increaseCount = kFALSE;
1223 UpdateShuttleStatus(AliShuttleStatus::kStarted, increaseCount);
1230 //______________________________________________________________________________________________
1231 void AliShuttle::SendMLRunInfo(const char* status)
1234 // Send information about this run to ML
1236 TMonaLisaText mlStatus("SHUTTLE_status", status);
1237 TString runType(fLogbookEntry->GetRunType());
1238 if (strlen(fLogbookEntry->GetRunParameter("log")) > 0){
1241 runType += fLogbookEntry->GetRunParameter("log");
1244 if (fLogbookEntry->GetDATestMode()){
1245 runType += " (DATest)";
1247 TMonaLisaText mlRunType("SHUTTLE_runtype", runType);
1250 mlList.Add(&mlStatus);
1251 mlList.Add(&mlRunType);
1254 mlID.Form("%d", GetCurrentRun());
1255 fMonaLisa->SendParameters(&mlList, mlID);
1258 //______________________________________________________________________________________________
1259 Int_t AliShuttle::GetMem(Int_t pid)
1261 // invokes ps to get the memory consumption of the process <pid>
1262 // returns -1 in case of error
1265 checkStr.Form("ps -o vsize --pid %d | tail -n 1", pid);
1266 FILE* pipe = gSystem->OpenPipe(checkStr, "r");
1269 Log("SHUTTLE", Form("Process - Error: "
1270 "Could not open pipe to %s", checkStr.Data()));
1275 if (!fgets(buffer, 100, pipe))
1277 Log("SHUTTLE", "Process - Error: ps did not return anything");
1278 gSystem->ClosePipe(pipe);
1281 gSystem->ClosePipe(pipe);
1283 //Log("SHUTTLE", Form("ps returned %s", buffer));
1286 if ((sscanf(buffer, "%d\n", &mem) != 1) || !mem)
1288 Log("SHUTTLE", "Process - Error: Could not parse output of ps");
1295 //______________________________________________________________________________________________
1296 Bool_t AliShuttle::Process(AliShuttleLogbookEntry* entry)
1299 // Makes data retrieval for all detectors in the configuration.
1300 // entry: Shuttle logbook entry, contains run paramenters and status of detectors
1301 // (Unprocessed, Inactive, Failed or Done).
1302 // Returns kFALSE in case of error occured and kTRUE otherwise
1305 if (!entry) return kFALSE;
1307 fLogbookEntry = entry;
1309 Log("SHUTTLE", Form("\t\t\t^*^*^*^*^*^*^*^*^*^*^*^* run %d: START ^*^*^*^*^*^*^*^*^*^*^*^*",
1314 // Send the information to ML
1315 SendMLRunInfo("Processing");
1317 if (fLogbookEntry->IsDone())
1319 Log("SHUTTLE","Process - Shuttle is already DONE. Updating logbook");
1320 UpdateShuttleLogbook("shuttle_done");
1325 // read test mode if flag is set
1329 TString logEntry(entry->GetRunParameter("log"));
1330 //printf("log entry = %s\n", logEntry.Data());
1331 TString searchStr("Testmode: ");
1332 Int_t pos = logEntry.Index(searchStr.Data());
1333 //printf("%d\n", pos);
1336 TSubString subStr = logEntry(pos + searchStr.Length(), logEntry.Length());
1337 //printf("%s\n", subStr.String().Data());
1338 TString newStr(subStr.Data());
1339 TObjArray* token = newStr.Tokenize(' ');
1343 TObjString* tmpStr = dynamic_cast<TObjString*> (token->First());
1346 Int_t testMode = tmpStr->String().Atoi();
1349 Log("SHUTTLE", Form("Process - Enabling test mode %d", testMode));
1350 SetTestMode((TestMode) testMode);
1358 fLogbookEntry->Print("all");
1361 Bool_t hasError = kFALSE;
1363 // Set the CDB and Reference folders according to the year
1365 // build cdb paths (repeat each time, run might be a DATest run)
1366 if (!fLogbookEntry->GetDATestMode()){
1367 fgkMainCDB.Form("alien://folder=%s%d/OCDB?user=alidaq?cacheFold=/tmp/OCDBCache",
1368 fConfig->GetAlienPath(), GetCurrentYear());
1370 fgkMainRefStorage.Form("alien://folder=%s%d/Reference?user=alidaq?cacheFold=/tmp/OCDBCache",
1371 fConfig->GetAlienPath(), GetCurrentYear());
1374 fgkMainCDB.Form("alien://folder=%s%d/DATest/OCDB?user=alidaq?cacheFold=/tmp/OCDBCache",
1375 fConfig->GetAlienPath(), GetCurrentYear());
1377 fgkMainRefStorage.Form("alien://folder=%s%d/DATest/Reference?user=alidaq?cacheFold=/tmp/OCDBCache",
1378 fConfig->GetAlienPath(), GetCurrentYear());
1381 AliDebug(2,Form("Main CDB storage = %s",fgkMainCDB.Data()));
1382 AliDebug(2,Form("Main Reference storage = %s",fgkMainRefStorage.Data()));
1384 // Loop on detectors in the configuration
1385 TIter iter(fConfig->GetDetectors());
1386 TObjString* aDetector = 0;
1388 Bool_t first = kTRUE;
1390 while ((aDetector = (TObjString*) iter.Next()))
1392 fCurrentDetector = aDetector->String();
1394 if (ContinueProcessing() == kFALSE)
1399 // only read QueryCDB when needed and only once
1400 AliCDBStorage *mainCDBSto = AliCDBManager::Instance()->GetStorage(fgkMainCDB);
1401 if(mainCDBSto) mainCDBSto->QueryCDB(GetCurrentRun());
1402 AliCDBStorage *mainRefSto = AliCDBManager::Instance()->GetStorage(fgkMainRefStorage);
1403 if(mainRefSto) mainRefSto->QueryCDB(GetCurrentRun());
1407 Log("SHUTTLE", Form("\t\t\t****** run %d - %s: START ******",
1408 GetCurrentRun(), aDetector->GetName()));
1410 for(Int_t iSys=0;iSys<4;iSys++) fFXSCalled[iSys]=kFALSE;
1412 Int_t initialMem = GetMem(getpid());
1413 Log("SHUTTLE", Form("Memory consumption before forking is %d", initialMem));
1415 Log(fCurrentDetector.Data(), "Process - Starting processing");
1421 Log("SHUTTLE", "Process - ERROR: Forking failed");
1426 Log("SHUTTLE", Form("Process - In parent process of %d - %s: Starting monitoring",
1427 GetCurrentRun(), aDetector->GetName()));
1429 Long_t begin = time(0);
1431 int status; // to be used with waitpid, on purpose an int (not Int_t)!
1432 while (waitpid(pid, &status, WNOHANG) == 0)
1434 Long_t expiredTime = time(0) - begin;
1436 if (expiredTime > fConfig->GetPPTimeOut())
1439 AliShuttleStatus *currentStatus = ReadShuttleStatus();
1440 AliShuttleStatus::Status newStatus = AliShuttleStatus::kInvalid;
1442 if (currentStatus->GetStatus() == AliShuttleStatus::kDCSStarted)
1444 // in case the pp goes in TimeOut while retrieving the DCS DPs
1445 // set status to kDCSError
1447 logMsg.Form("Process - Process of %s timed out while retrieving the DCS DataPoints. Run time: %ld seconds. Killing... and setting status to DCSError.",
1448 fCurrentDetector.Data(), expiredTime);
1449 newStatus = AliShuttleStatus::kDCSError;
1451 else if (currentStatus->GetStatus() <= AliShuttleStatus::kPPDone)
1453 // in case pp not yet done set status to kPPTimeOut
1455 logMsg.Form("Process - Process of %s timed out. Run time: %ld seconds. Killing...",
1456 fCurrentDetector.Data(), expiredTime);
1457 newStatus = AliShuttleStatus::kPPTimeOut;
1459 else if (currentStatus->GetStatus() == AliShuttleStatus::kStoreStarted)
1461 // in case the pp goes in TimeOut while storing the objects in the OCDB
1462 // set status to kStoreError
1464 logMsg.Form("Process - Process of %s timed out while storing the OCDB object. Run time: %ld seconds. Killing... and setting status to StoreError.",
1465 fCurrentDetector.Data(), expiredTime);
1466 newStatus = AliShuttleStatus::kStoreError;
1470 // in other cases don't change the status
1472 logMsg.Form("Process - Process of %s timed out in status = %s. Run time: %ld seconds. Killing... without changing the status",
1473 fCurrentDetector.Data(), currentStatus->GetStatusName(), expiredTime);
1476 Log("SHUTTLE", logMsg);
1477 Log(fCurrentDetector, logMsg);
1481 if (newStatus != AliShuttleStatus::kInvalid)
1482 UpdateShuttleStatus(newStatus);
1485 gSystem->Sleep(1000);
1489 gSystem->Sleep(1000);
1491 Int_t mem = GetMem(pid);
1500 if (expiredTime % 60 == 0)
1502 Log("SHUTTLE", Form("Process - %s: Checking process. "
1503 "Run time: %ld seconds - Memory consumption: %d KB",
1504 fCurrentDetector.Data(), expiredTime, mem));
1508 if (mem > fConfig->GetPPMaxMem())
1511 tmp.Form("Process - Process exceeds maximum allowed memory "
1512 "(%d KB > %d KB). Killing...",
1513 mem, fConfig->GetPPMaxMem());
1514 Log("SHUTTLE", tmp);
1515 Log(fCurrentDetector, tmp);
1519 UpdateShuttleStatus(AliShuttleStatus::kPPOutOfMemory);
1522 gSystem->Sleep(1000);
1527 Log("SHUTTLE", Form("Process - In parent process of %d - %s: Client has terminated.",
1528 GetCurrentRun(), aDetector->GetName()));
1530 if (WIFEXITED(status))
1532 Int_t returnCode = WEXITSTATUS(status);
1534 Log("SHUTTLE", Form("Process - %s: the return code is %d", fCurrentDetector.Data(),
1537 if (returnCode == 0) hasError = kTRUE;
1543 Log("SHUTTLE", Form("Process - In child process of %d - %s", GetCurrentRun(),
1544 aDetector->GetName()));
1546 Log("SHUTTLE", Form("Process - Redirecting output to %s log",fCurrentDetector.Data()));
1548 if ((freopen(GetLogFileName(fCurrentDetector), "a", stdout)) == 0)
1550 Log("SHUTTLE", "Process - Could not freopen stdout");
1554 fOutputRedirected = kTRUE;
1555 if ((dup2(fileno(stdout), fileno(stderr))) < 0)
1556 Log("SHUTTLE", "Process - Could not redirect stderr");
1560 Log("SHUTTLE", "Executing TGrid::Connect");
1561 TGrid::Connect("alien://");
1563 TString wd = gSystem->WorkingDirectory();
1564 Int_t dir_lev1 = GetCurrentRun()/10000;
1565 TString tmpDir = Form("%s/%d/%d/%s_process", GetShuttleTempDir(),
1566 dir_lev1, GetCurrentRun(), fCurrentDetector.Data());
1568 Int_t result = gSystem->GetPathInfo(tmpDir.Data(), 0, (Long64_t*) 0, 0, 0);
1569 if (!result) // temp dir already exists!
1571 Log(fCurrentDetector.Data(),
1572 Form("Process - %s dir already exists! Removing...", tmpDir.Data()));
1573 gSystem->Exec(Form("rm -rf %s",tmpDir.Data()));
1576 if (gSystem->mkdir(tmpDir.Data(), 1))
1578 Log(fCurrentDetector.Data(), "Process - could not make temp directory!!");
1582 if (!gSystem->ChangeDirectory(tmpDir.Data()))
1584 Log(fCurrentDetector.Data(), "Process - could not change directory!!");
1588 Int_t success = ProcessCurrentDetector();
1590 gSystem->ChangeDirectory(wd.Data());
1592 if (success == 1) // Preprocessor finished successfully!
1594 // remove temporary folder or DCS map
1595 if (!fConfig->KeepTempFolder())
1597 gSystem->Exec(Form("rm -rf %s",tmpDir.Data()));
1598 } else if (!fConfig->KeepDCSMap())
1600 gSystem->Exec(Form("rm -f %s/DCSMap.root",tmpDir.Data()));
1603 // Update time_processed field in FXS DB
1604 if (UpdateTable() == kFALSE)
1605 Log("SHUTTLE", Form("Process - %s: Could not update FXS databases!",
1606 fCurrentDetector.Data()));
1608 // Transfer the data from local storage to main storage (Grid)
1609 if (StoreOCDB() == kFALSE)
1612 else if (success == 0)
1615 Form("\t\t\t****** run %d - %s: ERROR ******",
1616 GetCurrentRun(), aDetector->GetName()));
1619 for (UInt_t iSys=0; iSys<4; iSys++)
1621 if (fFXSCalled[iSys]) fFXSlist[iSys].Clear();
1624 Log("SHUTTLE", Form("Process - Client process of %d - %s is exiting now with %d.",
1625 GetCurrentRun(), aDetector->GetName(), success));
1627 // the client exits here
1628 gSystem->Exit(success);
1630 AliError("We should never get here!!!");
1634 Log("SHUTTLE", Form("\t\t\t^*^*^*^*^*^*^*^*^*^*^*^* run %d: FINISH ^*^*^*^*^*^*^*^*^*^*^*^*",
1637 //check if shuttle is done for this run, if so update logbook
1638 TObjArray checkEntryArray;
1639 checkEntryArray.SetOwner(1);
1640 TString whereClause = Form("where run=%d", GetCurrentRun());
1641 if (!QueryShuttleLogbook(whereClause.Data(), checkEntryArray) ||
1642 checkEntryArray.GetEntries() == 0) {
1643 Log("SHUTTLE", Form("Process - Warning: Cannot check status of run %d on Shuttle logbook!",
1645 return hasError == kFALSE;
1648 AliShuttleLogbookEntry* checkEntry = dynamic_cast<AliShuttleLogbookEntry*>
1649 (checkEntryArray.At(0));
1653 if (checkEntry->IsDone())
1655 Log("SHUTTLE","Process - Shuttle is DONE. Updating logbook");
1656 UpdateShuttleLogbook("shuttle_done");
1660 for (UInt_t iDet=0; iDet<NDetectors(); iDet++)
1662 if (checkEntry->GetDetectorStatus(iDet) == AliShuttleLogbookEntry::kUnprocessed)
1664 AliDebug(2, Form("Run %d: setting %s as \"not first time unprocessed\"",
1665 checkEntry->GetRun(), GetDetName(iDet)));
1666 fFirstUnprocessed[iDet] = kFALSE;
1669 SendMLRunInfo("Pending");
1675 return hasError == kFALSE;
1678 //______________________________________________________________________________________________
1679 Int_t AliShuttle::ProcessCurrentDetector()
1682 // Makes data retrieval just for a specific detector (fCurrentDetector).
1683 // Threre should be a configuration for this detector.
1685 Log("SHUTTLE", Form("ProcessCurrentDetector - Retrieving values for %s, run %d",
1686 fCurrentDetector.Data(), GetCurrentRun()));
1688 TString wd = gSystem->WorkingDirectory();
1690 if (!CleanReferenceStorage(fCurrentDetector.Data()))
1693 gSystem->ChangeDirectory(wd.Data());
1695 // call preprocessor
1696 AliPreprocessor* aPreprocessor =
1697 dynamic_cast<AliPreprocessor*> (fPreprocessorMap.GetValue(fCurrentDetector));
1699 // check if the preprocessor wants to process this run type
1700 if (aPreprocessor->ProcessRunType() == kFALSE)
1702 UpdateShuttleStatus(AliShuttleStatus::kSkipped);
1703 UpdateShuttleLogbook(fCurrentDetector, "DONE");
1704 if (!UpdateTableSkippedCase(fCurrentDetector.Data()))
1706 AliError(Form("Could not update FXS tables for run %d !", GetCurrentRun()));
1708 Log(fCurrentDetector, Form("ProcessCurrentDetector - %s preprocessor is not interested in this run type", fCurrentDetector.Data()));
1713 // checking if OCDB is reachable
1714 AliCDBEntry* testEntry = GetFromOCDB("SHUTTLE","GRP/CTP/DummyConfig");
1716 // OCDB is not accessible, going in OCDBError for current detector
1717 AliError("OCDB Test entry not accessible");
1718 UpdateShuttleStatus(AliShuttleStatus::kOCDBError);
1722 TMap* dcsMap = new TMap();
1724 aPreprocessor->Initialize(GetCurrentRun(), GetCurrentStartTime(), GetCurrentEndTime());
1726 Bool_t processDCS = aPreprocessor->ProcessDCS();
1730 Log(fCurrentDetector, "ProcessCurrentDetector -"
1731 " The preprocessor requested to skip the retrieval of DCS values");
1733 else if (fTestMode & kSkipDCS)
1735 Log(fCurrentDetector, "ProcessCurrentDetector - In TESTMODE: Skipping DCS processing");
1737 else if (fTestMode & kErrorDCS)
1739 Log(fCurrentDetector, "ProcessCurrentDetector - In TESTMODE: Simulating DCS error");
1740 UpdateShuttleStatus(AliShuttleStatus::kDCSStarted);
1741 UpdateShuttleStatus(AliShuttleStatus::kDCSError);
1746 UpdateShuttleStatus(AliShuttleStatus::kDCSStarted);
1748 // Query DCS archive
1749 Int_t nServers = fConfig->GetNServers(fCurrentDetector);
1751 for (int iServ=0; iServ<nServers; iServ++)
1754 TString host(fConfig->GetDCSHost(fCurrentDetector, iServ));
1755 Int_t port = fConfig->GetDCSPort(fCurrentDetector, iServ);
1756 Int_t multiSplit = fConfig->GetMultiSplit(fCurrentDetector, iServ);
1758 Log(fCurrentDetector, Form("ProcessCurrentDetector -"
1759 " Querying DCS Amanda server %s:%d (%d of %d)",
1760 host.Data(), port, iServ+1, nServers));
1765 if (fConfig->GetDCSAliases(fCurrentDetector, iServ)->GetEntries() > 0)
1767 Log(fCurrentDetector, Form("Querying %d DCS aliases", fConfig->GetDCSAliases(fCurrentDetector, iServ)->GetEntries()));
1768 aliasMap = GetValueSet(host, port,
1769 fConfig->GetDCSAliases(fCurrentDetector, iServ),
1770 kAlias, multiSplit);
1773 Log(fCurrentDetector,
1774 Form("ProcessCurrentDetector -"
1775 " Error retrieving DCS aliases from server %s."
1776 " Sending mail to DCS experts!", host.Data()));
1777 UpdateShuttleStatus(AliShuttleStatus::kDCSError);
1779 if (!SendMail(kDCSEMail))
1780 Log("SHUTTLE", Form("ProcessCurrentDetector - "
1781 "Could not send mail to DCS experts!"));
1788 if (fConfig->GetDCSDataPoints(fCurrentDetector, iServ)->GetEntries() > 0)
1790 Log(fCurrentDetector, Form("Querying %d DCS data points", fConfig->GetDCSDataPoints(fCurrentDetector, iServ)->GetEntries()));
1791 dpMap = GetValueSet(host, port,
1792 fConfig->GetDCSDataPoints(fCurrentDetector, iServ),
1796 Log(fCurrentDetector,
1797 Form("ProcessCurrentDetector -"
1798 " Error retrieving DCS data points from server %s."
1799 " Sending mail to DCS experts!", host.Data()));
1800 UpdateShuttleStatus(AliShuttleStatus::kDCSError);
1802 if (!SendMail(kDCSEMail))
1803 Log("SHUTTLE", Form("ProcessCurrentDetector - "
1804 "Could not send mail to DCS experts!"));
1806 if (aliasMap) delete aliasMap;
1812 // merge aliasMap and dpMap into dcsMap
1814 TIter iter(aliasMap);
1815 TObjString* key = 0;
1816 while ((key = (TObjString*) iter.Next()))
1817 dcsMap->Add(key, aliasMap->GetValue(key->String()));
1819 aliasMap->SetOwner(kFALSE);
1825 TObjString* key = 0;
1826 while ((key = (TObjString*) iter.Next()))
1827 dcsMap->Add(key, dpMap->GetValue(key->String()));
1829 dpMap->SetOwner(kFALSE);
1835 // save map into file, to help debugging in case of preprocessor error
1836 TFile* f = TFile::Open("DCSMap.root","recreate");
1838 dcsMap->Write("DCSMap", TObject::kSingleKey);
1842 // DCS Archive DB processing successful. Call Preprocessor!
1843 UpdateShuttleStatus(AliShuttleStatus::kPPStarted);
1845 fFXSError = -1; // this variable is kTRUE after ::Process if an FXS error occured
1847 UInt_t returnValue = aPreprocessor->Process(dcsMap);
1849 if (fFXSError!=-1) {
1850 UpdateShuttleStatus(AliShuttleStatus::kFXSError);
1851 SendMail(kFXSEMail, fFXSError);
1852 dcsMap->DeleteAll();
1857 if (returnValue > 0) // Preprocessor error!
1859 Log(fCurrentDetector, Form("ProcessCurrentDetector - "
1860 "Preprocessor failed. Process returned %d.", returnValue));
1861 UpdateShuttleStatus(AliShuttleStatus::kPPError);
1862 dcsMap->DeleteAll();
1868 UpdateShuttleStatus(AliShuttleStatus::kPPDone);
1869 Log(fCurrentDetector, Form("ProcessCurrentDetector - %s preprocessor returned success",
1870 fCurrentDetector.Data()));
1872 dcsMap->DeleteAll();
1878 //______________________________________________________________________________________________
1879 void AliShuttle::CountOpenRuns()
1881 // Query DAQ's Shuttle logbook and sends the number of open runs to ML
1885 // check connection, in case connect
1890 sqlQuery = Form("select count(*) from %s where shuttle_done=0", fConfig->GetShuttlelbTable());
1892 TSQLResult* aResult = fServer[4]->Query(sqlQuery);
1894 AliError(Form("Can't execute query <%s>!", sqlQuery.Data()));
1898 AliDebug(2,Form("Query = %s", sqlQuery.Data()));
1900 if (aResult->GetRowCount() == 0) {
1901 AliError(Form("No result for query %s received", sqlQuery.Data()));
1905 if (aResult->GetFieldCount() != 1) {
1906 AliError(Form("Invalid field count for query %s received", sqlQuery.Data()));
1910 TSQLRow* aRow = aResult->Next();
1912 AliError(Form("Could not receive result of query %s", sqlQuery.Data()));
1916 TString result(aRow->GetField(0), aRow->GetFieldLength(0));
1917 Int_t count = result.Atoi();
1919 Log("SHUTTLE", Form("%d unprocessed runs", count));
1924 TMonaLisaValue mlStatus("SHUTTLE_openruns", count);
1927 mlList.Add(&mlStatus);
1929 fMonaLisa->SendParameters(&mlList, "__PROCESSINGINFO__");
1932 //______________________________________________________________________________________________
1933 Bool_t AliShuttle::QueryShuttleLogbook(const char* whereClause,
1936 // Query DAQ's Shuttle logbook and fills detector status object.
1937 // Call QueryRunParameters to query DAQ logbook for run parameters.
1940 entries.SetOwner(1);
1942 // check connection, in case connect
1943 if (!Connect(4)) return kFALSE;
1946 sqlQuery = Form("select * from %s %s order by run", fConfig->GetShuttlelbTable(), whereClause);
1948 TSQLResult* aResult = fServer[4]->Query(sqlQuery);
1950 AliError(Form("Can't execute query <%s>!", sqlQuery.Data()));
1954 AliDebug(2,Form("Query = %s", sqlQuery.Data()));
1956 if(aResult->GetRowCount() == 0) {
1957 Log("SHUTTLE", "No entries in Shuttle Logbook match request");
1962 // TODO Check field count!
1963 const UInt_t nCols = 26;
1964 if (aResult->GetFieldCount() != (Int_t) nCols) {
1965 Log("SHUTTLE", "Invalid SQL result field number!");
1971 while ((aRow = aResult->Next())) {
1972 TString runString(aRow->GetField(0), aRow->GetFieldLength(0));
1973 Int_t run = runString.Atoi();
1975 AliShuttleLogbookEntry *entry = QueryRunParameters(run);
1979 // DA test mode flag
1980 TString daTestModeString(aRow->GetField(2), aRow->GetFieldLength(2)); // field 2 = DA test mode flag
1981 Bool_t daTestMode = (Bool_t)daTestModeString.Atoi();
1982 entry->SetDATestMode(daTestMode);
1984 // loop on detectors
1985 for(UInt_t ii = 0; ii < nCols; ii++)
1986 entry->SetDetectorStatus(aResult->GetFieldName(ii), aRow->GetField(ii));
1988 entries.AddLast(entry);
1996 //______________________________________________________________________________________________
1997 AliShuttleLogbookEntry* AliShuttle::QueryRunParameters(Int_t run)
2000 // Retrieve run parameters written in the DAQ logbook and sets them into AliShuttleLogbookEntry object
2003 // check connection, in case connect
2008 sqlQuery.Form("select * from %s where run=%d", fConfig->GetDAQlbTable(), run);
2010 TSQLResult* aResult = fServer[4]->Query(sqlQuery);
2012 Log("SHUTTLE", Form("Can't execute query <%s>!", sqlQuery.Data()));
2016 if (aResult->GetRowCount() == 0) {
2017 Log("SHUTTLE", Form("QueryRunParameters - No entry in DAQ Logbook for run %d. Skipping", run));
2022 if (aResult->GetRowCount() > 1) {
2023 Log("SHUTTLE", Form("QueryRunParameters - UNEXPECTED: "
2024 "more than one entry in DAQ Logbook for run %d!", run));
2029 TSQLRow* aRow = aResult->Next();
2032 Log("SHUTTLE", Form("QueryRunParameters - Could not retrieve row for run %d. Skipping", run));
2037 AliShuttleLogbookEntry* entry = new AliShuttleLogbookEntry(run);
2039 for (Int_t ii = 0; ii < aResult->GetFieldCount(); ii++)
2040 entry->SetRunParameter(aResult->GetFieldName(ii), aRow->GetField(ii));
2045 UInt_t startTime = entry->GetStartTime();
2046 UInt_t endTime = entry->GetEndTime();
2047 Bool_t ecsSuccess = entry->GetECSSuccess();
2048 TString runType = entry->GetRunType();
2049 TString tmpdaqstartTime = entry->GetRunParameter("DAQ_time_start");
2050 TString recordingFlagString = entry->GetRunParameter("GDCmStreamRecording");
2051 UInt_t recordingFlag = recordingFlagString.Atoi();
2052 UInt_t daqstartTime = tmpdaqstartTime.Atoi();
2054 UInt_t now = time(0);
2055 Int_t dcsDelay = fConfig->GetDCSDelay()+fConfig->GetDCSQueryOffset();
2057 Bool_t skip = kFALSE;
2059 // runs are processed if
2060 // a) runType is PHYSICS and ecsSuccess is set
2061 // b) runType is not PHYSICS and (ecsSuccess is set or DAQ_time_start is non-0)
2062 // effectively this means that all runs are processed that started properly (ecsSucess behaviour is different for PHYSICS and non-PHYSICS runs (check with ECS!)
2063 if (startTime != 0 && endTime != 0) {
2064 if (endTime > startTime) {
2065 if (endTime >= now - dcsDelay) {
2066 Log("SHUTTLE", Form("Skipping run %d for now, because DCS buffer time is not yet expired", run));
2068 if ((runType == "PHYSICS" || runType == "STANDALONE") && recordingFlag == 0){
2069 Log("SHUTTLE", Form("QueryRunParameters - Run type for run %d is %s but the recording is OFF - Skipping!", run, runType.Data()));
2073 if (runType == "PHYSICS") {
2077 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")));
2081 if (ecsSuccess || daqstartTime > 0) {
2082 if (ecsSuccess == kFALSE)
2083 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")));
2086 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")));
2093 Log("SHUTTLE", Form("QueryRunParameters - Invalid parameters for run %d: startTime equal to endTime: %d %d - Skipping!", run, startTime, endTime));
2097 Log("SHUTTLE", Form("QueryRunParameters - Invalid parameters for Run %d: "
2098 "startTime = %d, endTime = %d. Skipping (Shuttle won't be marked as DONE)!",
2099 run, startTime, endTime));
2104 Log("SHUTTLE", Form("Marking SHUTTLE skipped for run %d", run));
2105 fLogbookEntry = entry;
2106 if (!UpdateShuttleLogbook("shuttle_skipped"))
2108 AliError(Form("Could not update logbook for run %d !", run));
2110 if (!UpdateTableSkippedCase("ALL"))
2112 AliError(Form("Could not update FXS tables for run %d !", run));
2121 //______________________________________________________________________________________________
2122 TMap* AliShuttle::GetValueSet(const char* host, Int_t port, const TSeqCollection* entries,
2123 DCSType type, Int_t multiSplit)
2125 // Retrieve all "entry" data points from the DCS server
2126 // host, port: TSocket connection parameters
2127 // entries: list of name of the alias or data point
2128 // type: kAlias or kDP
2129 // returns TMap of values, 0 when failure
2131 AliDCSClient client(host, port, fTimeout, fRetries, multiSplit);
2136 //result = client.GetAliasValues(entries, GetCurrentStartTime()-offset,
2137 // GetCurrentEndTime()+offset);
2138 result = client.GetAliasValues(entries, GetStartTimeDCSQuery(),
2139 GetEndTimeDCSQuery());
2141 else if (type == kDP)
2143 //result = client.GetDPValues(entries, GetCurrentStartTime()-offset,
2144 // GetCurrentEndTime()+offset);
2145 result = client.GetDPValues(entries, GetStartTimeDCSQuery(),
2146 GetEndTimeDCSQuery());
2151 Log(fCurrentDetector.Data(), Form("GetValueSet - Can't get entries! Reason: %s",
2152 client.GetErrorString(client.GetResultErrorCode())));
2153 if (client.GetResultErrorCode() == AliDCSClient::fgkServerError)
2154 Log(fCurrentDetector.Data(), Form("GetValueSet - Server error code: %s",
2155 client.GetServerError().Data()));
2163 //______________________________________________________________________________________________
2164 const char* AliShuttle::GetFile(Int_t system, const char* detector,
2165 const char* id, const char* source)
2167 // Get calibration file from file exchange servers
2168 // First queris the FXS database for the file name, using the run, detector, id and source info
2169 // then calls RetrieveFile(filename) for actual copy to local disk
2170 // run: current run being processed (given by Logbook entry fLogbookEntry)
2171 // detector: the Preprocessor name
2172 // id: provided as a parameter by the Preprocessor
2173 // source: provided by the Preprocessor through GetFileSources function
2175 // check if test mode should simulate a FXS error
2176 if (fTestMode & kErrorFXSFiles)
2178 Log(detector, Form("GetFile - In TESTMODE - Simulating error while connecting to %s FXS", GetSystemName(system)));
2182 // check connection, in case connect
2183 if (!Connect(system))
2185 Log(detector, Form("GetFile - Couldn't connect to %s FXS database", GetSystemName(system)));
2190 // Query preparation
2191 TString sourceName(source);
2193 TString sqlQueryStart = Form("select filePath,size,fileChecksum from %s where",
2194 fConfig->GetFXSdbTable(system));
2195 TString whereClause = Form("run=%d and detector=\"%s\" and fileId=\"%s\"",
2196 GetCurrentRun(), detector, id);
2198 if (system == kDAQ || system == kDQM)
2200 whereClause += Form(" and DAQsource=\"%s\"", source);
2202 else if (system == kDCS)
2206 else if (system == kHLT)
2208 whereClause += Form(" and DDLnumbers=\"%s\"", source);
2211 TString sqlQuery = Form("%s %s", sqlQueryStart.Data(), whereClause.Data());
2213 AliDebug(2, Form("SQL query: \n%s",sqlQuery.Data()));
2216 TSQLResult* aResult = 0;
2217 aResult = dynamic_cast<TSQLResult*> (fServer[system]->Query(sqlQuery));
2219 Log(detector, Form("GetFile - Can't execute SQL query to %s database for: id = %s, source = %s",
2220 GetSystemName(system), id, sourceName.Data()));
2225 if (aResult->GetRowCount() == 0)
2228 Form("GetFile - No entry in %s FXS db for: id = %s, source = %s",
2229 GetSystemName(system), id, sourceName.Data()));
2234 if (aResult->GetRowCount() > 1) {
2236 Form("GetFile - More than one entry in %s FXS db for: id = %s, source = %s",
2237 GetSystemName(system), id, sourceName.Data()));
2243 if (aResult->GetFieldCount() != nFields) {
2245 Form("GetFileName - Wrong field count in %s FXS db for: id = %s, source = %s",
2246 GetSystemName(system), id, sourceName.Data()));
2252 TSQLRow* aRow = dynamic_cast<TSQLRow*> (aResult->Next());
2255 Log(detector, Form("GetFile - Empty set result in %s FXS db from query: id = %s, source = %s",
2256 GetSystemName(system), id, sourceName.Data()));
2262 TString filePath(aRow->GetField(0), aRow->GetFieldLength(0));
2263 TString fileSize(aRow->GetField(1), aRow->GetFieldLength(1));
2264 TString fileChecksum(aRow->GetField(2), aRow->GetFieldLength(2));
2269 AliDebug(2, Form("filePath = %s; size = %s, fileChecksum = %s",
2270 filePath.Data(), fileSize.Data(), fileChecksum.Data()));
2272 // retrieved file is renamed to make it unique
2273 Int_t dir_lev1 = GetCurrentRun()/10000;
2274 TString localFileName = Form("%s/%d/%d/%s_process/%s_%s_%d_%s_%s.shuttle",
2275 GetShuttleTempDir(), dir_lev1, GetCurrentRun(), detector,
2276 GetSystemName(system), detector, GetCurrentRun(),
2277 id, sourceName.Data());
2278 Log("SHUTTLE",Form("file from FXS = %s",localFileName.Data()));
2281 // file retrieval from FXS
2282 UInt_t nRetries = 0;
2283 UInt_t maxRetries = 3;
2284 Bool_t result = kFALSE;
2286 // copy!! if successful TSystem::Exec returns 0
2287 while (nRetries++ < maxRetries) {
2288 AliDebug(2, Form("Trying to copy file. Retry # %d", nRetries));
2289 result = RetrieveFile(system, filePath.Data(), localFileName.Data());
2292 Log(detector, Form("GetFile - Copy of file %s from %s FXS failed",
2293 filePath.Data(), GetSystemName(system)));
2297 if (fileSize.Length()>0)
2299 // compare filesize of local file with the one stored in the FXS DB
2301 Int_t sizeComp = gSystem->GetPathInfo(localFileName.Data(), 0, &size, 0, 0);
2303 if (sizeComp != 0 || size != fileSize.Atoi())
2305 Log(detector, Form("GetFile - size of file %s does not match with local copy!",
2312 Log(fCurrentDetector, Form("GetFile - size of file %s not set in %s database, skipping comparison",
2313 filePath.Data(), GetSystemName(system)));
2316 if (fileChecksum.Length()>0)
2318 // compare md5sum of local file with the one stored in the FXS DB
2319 if(fileChecksum.Contains(' ')) fileChecksum.Resize(fileChecksum.First(' '));
2320 Int_t md5Comp = gSystem->Exec(Form("md5sum %s |grep %s > /dev/null 2> /dev/null",
2321 localFileName.Data(), fileChecksum.Data()));
2325 Log(detector, Form("GetFile - md5sum of file %s does not match with local copy!",
2331 Log(fCurrentDetector, Form("GetFile - md5sum of file %s not set in %s database, skipping comparison",
2332 filePath.Data(), GetSystemName(system)));
2343 fFXSCalled[system]=kTRUE;
2344 TObjString *fileParams = new TObjString(Form("%s#!?!#%s", id, sourceName.Data()));
2345 fFXSlist[system].Add(fileParams);
2347 static TString staticLocalFileName;
2348 staticLocalFileName.Form("%s", localFileName.Data());
2350 Log(fCurrentDetector, Form("GetFile - Retrieved file with id %s and "
2351 "source %s from %s to %s", id, source,
2352 GetSystemName(system), localFileName.Data()));
2354 return staticLocalFileName.Data();
2357 //______________________________________________________________________________________________
2358 Bool_t AliShuttle::RetrieveFile(UInt_t system, const char* fxsFileName, const char* localFileName)
2361 // Copies file from FXS to local Shuttle machine
2364 // check temp directory: trying to cd to temp; if it does not exist, create it
2365 AliDebug(2, Form("Copy file %s from %s FXS into %s",
2366 GetSystemName(system), fxsFileName, localFileName));
2368 TString tmpDir(localFileName);
2370 tmpDir = tmpDir(0,tmpDir.Last('/'));
2372 Int_t noDir = gSystem->GetPathInfo(tmpDir.Data(), 0, (Long64_t*) 0, 0, 0);
2373 if (noDir) // temp dir does not exists!
2375 if (gSystem->mkdir(tmpDir.Data(), 1))
2377 Log(fCurrentDetector.Data(), "RetrieveFile - could not make temp directory!!");
2382 TString command = Form("scp -oPort=%d -2 %s@%s:%s/%s %s",
2383 fConfig->GetFXSPort(system),
2384 fConfig->GetFXSUser(system),
2385 fConfig->GetFXSHost(system),
2386 fConfig->GetFXSBaseFolder(system),
2390 AliDebug(2, Form("%s",command.Data()));
2392 Bool_t result = (gSystem->Exec(command.Data()) == 0);
2397 //______________________________________________________________________________________________
2398 TList* AliShuttle::GetFileSources(Int_t system, const char* detector, const char* id)
2401 // Get sources producing the condition file Id from file exchange servers
2402 // if id is NULL all sources are returned (distinct)
2407 Log(detector, Form("GetFileSources - Querying %s FXS for files with id %s produced by %s", GetSystemName(system), id, detector));
2409 Log(detector, Form("GetFileSources - Querying %s FXS for files produced by %s", GetSystemName(system), detector));
2412 // check if test mode should simulate a FXS error
2413 if (fTestMode & kErrorFXSSources)
2415 Log(detector, Form("GetFileSources - In TESTMODE - Simulating error while connecting to %s FXS", GetSystemName(system)));
2421 Log(detector, "GetFileSources - WARNING: DCS system has only one source of data!");
2422 TList *list = new TList();
2424 list->Add(new TObjString(" "));
2428 // check connection, in case connect
2429 if (!Connect(system))
2431 Log(detector, Form("GetFileSources - Couldn't connect to %s FXS database", GetSystemName(system)));
2436 TString sourceName = "";
2437 if (system == kDAQ || system == kDQM)
2439 sourceName = "DAQsource";
2440 } else if (system == kHLT)
2442 sourceName = "DDLnumbers";
2445 TString sqlQueryStart = Form("select distinct %s from %s where", sourceName.Data(), fConfig->GetFXSdbTable(system));
2446 TString whereClause = Form("run=%d and detector=\"%s\"",
2447 GetCurrentRun(), detector);
2449 whereClause += Form(" and fileId=\"%s\"", id);
2450 TString sqlQuery = Form("%s %s", sqlQueryStart.Data(), whereClause.Data());
2452 AliDebug(2, Form("SQL query: \n%s",sqlQuery.Data()));
2455 TSQLResult* aResult;
2456 aResult = fServer[system]->Query(sqlQuery);
2458 Log(detector, Form("GetFileSources - Can't execute SQL query to %s database for id: %s",
2459 GetSystemName(system), id));
2464 TList *list = new TList();
2467 if (aResult->GetRowCount() == 0)
2470 Form("GetFileSources - No entry in %s FXS table for id: %s", GetSystemName(system), id));
2475 Log(detector, Form("GetFileSources - Found %d sources", aResult->GetRowCount()));
2478 while ((aRow = aResult->Next()))
2481 TString source(aRow->GetField(0), aRow->GetFieldLength(0));
2482 AliDebug(2, Form("%s = %s", sourceName.Data(), source.Data()));
2483 list->Add(new TObjString(source));
2492 //______________________________________________________________________________________________
2493 TList* AliShuttle::GetFileIDs(Int_t system, const char* detector, const char* source)
2496 // Get all ids of condition files produced by a given source from file exchange servers
2499 Log(detector, Form("GetFileIDs - Retrieving ids with source %s with %s", source, GetSystemName(system)));
2501 // check if test mode should simulate a FXS error
2502 if (fTestMode & kErrorFXSSources)
2504 Log(detector, Form("GetFileIDs - In TESTMODE - Simulating error while connecting to %s FXS", GetSystemName(system)));
2508 // check connection, in case connect
2509 if (!Connect(system))
2511 Log(detector, Form("GetFileIDs - Couldn't connect to %s FXS database", GetSystemName(system)));
2515 TString sourceName = "";
2518 sourceName = "DAQsource";
2519 } else if (system == kHLT)
2521 sourceName = "DDLnumbers";
2524 TString sqlQueryStart = Form("select fileId from %s where", fConfig->GetFXSdbTable(system));
2525 TString whereClause = Form("run=%d and detector=\"%s\"",
2526 GetCurrentRun(), detector);
2527 if (sourceName.Length() > 0 && source)
2528 whereClause += Form(" and %s=\"%s\"", sourceName.Data(), source);
2529 TString sqlQuery = Form("%s %s", sqlQueryStart.Data(), whereClause.Data());
2531 AliDebug(2, Form("SQL query: \n%s",sqlQuery.Data()));
2534 TSQLResult* aResult;
2535 aResult = fServer[system]->Query(sqlQuery);
2537 Log(detector, Form("GetFileIDs - Can't execute SQL query to %s database for source: %s",
2538 GetSystemName(system), source));
2542 TList *list = new TList();
2545 if (aResult->GetRowCount() == 0)
2548 Form("GetFileIDs - No entry in %s FXS table for source: %s", GetSystemName(system), source));
2553 Log(detector, Form("GetFileIDs - Found %d ids", aResult->GetRowCount()));
2557 while ((aRow = aResult->Next()))
2560 TString id(aRow->GetField(0), aRow->GetFieldLength(0));
2561 AliDebug(2, Form("fileId = %s", id.Data()));
2562 list->Add(new TObjString(id));
2571 //______________________________________________________________________________________________
2572 Bool_t AliShuttle::Connect(Int_t system)
2574 // Connect to MySQL Server of the system's FXS MySQL databases
2575 // DAQ Logbook, Shuttle Logbook and DAQ FXS db are on the same host
2578 // check connection: if already connected return
2580 if(fServer[system] && fServer[system]->IsConnected()) {
2582 if (fServer[system]->PingVerify()==kTRUE){ // connection is still alive
2586 AliWarning(Form("Connection got lost to FXS database for %s. Closing and reconnecting.",
2587 AliShuttleInterface::GetSystemName(system)));
2588 fServer[system]->Close();
2589 delete fServer[system];
2590 fServer[system] = 0x0;
2594 TString dbHost, dbUser, dbPass, dbName;
2596 if (system < 4) // FXS db servers
2598 dbHost = Form("mysql://%s:%d", fConfig->GetFXSdbHost(system), fConfig->GetFXSdbPort(system));
2599 dbUser = fConfig->GetFXSdbUser(system);
2600 dbPass = fConfig->GetFXSdbPass(system);
2601 dbName = fConfig->GetFXSdbName(system);
2602 } else { // Run & Shuttle logbook servers
2603 // TODO Will the Shuttle logbook server be the same as the Run logbook server ???
2604 dbHost = Form("mysql://%s:%d", fConfig->GetDAQlbHost(), fConfig->GetDAQlbPort());
2605 dbUser = fConfig->GetDAQlbUser();
2606 dbPass = fConfig->GetDAQlbPass();
2607 dbName = fConfig->GetDAQlbDB();
2610 fServer[system] = TSQLServer::Connect(dbHost.Data(), dbUser.Data(), dbPass.Data());
2611 if (!fServer[system] || !fServer[system]->IsConnected()) {
2614 AliError(Form("Can't establish connection to FXS database for %s",
2615 AliShuttleInterface::GetSystemName(system)));
2617 AliError("Can't establish connection to Run logbook.");
2619 if(fServer[system]) delete fServer[system];
2624 TSQLResult* aResult=0;
2627 aResult = fServer[kDAQ]->GetTables(dbName.Data());
2630 aResult = fServer[kDCS]->GetTables(dbName.Data());
2633 aResult = fServer[kHLT]->GetTables(dbName.Data());
2636 aResult = fServer[kDQM]->GetTables(dbName.Data());
2639 aResult = fServer[4]->GetTables(dbName.Data());
2647 //______________________________________________________________________________________________
2648 Bool_t AliShuttle::UpdateTable()
2651 // Update FXS table filling time_processed field in all rows corresponding to current run and detector
2654 Bool_t result = kTRUE;
2656 for (UInt_t system=0; system<4; system++)
2658 if(!fFXSCalled[system]) continue;
2660 // check connection, in case connect
2661 if (!Connect(system))
2663 Log(fCurrentDetector, Form("UpdateTable - Couldn't connect to %s FXS database", GetSystemName(system)));
2668 TTimeStamp now; // now
2670 // Loop on FXS list entries
2671 TIter iter(&fFXSlist[system]);
2672 TObjString *aFXSentry=0;
2673 while ((aFXSentry = dynamic_cast<TObjString*> (iter.Next())))
2675 TString aFXSentrystr = aFXSentry->String();
2676 TObjArray *aFXSarray = aFXSentrystr.Tokenize("#!?!#");
2677 if (!aFXSarray || aFXSarray->GetEntries() != 2 )
2679 Log(fCurrentDetector, Form("UpdateTable - error updating %s FXS entry. Check string: <%s>",
2680 GetSystemName(system), aFXSentrystr.Data()));
2681 if(aFXSarray) delete aFXSarray;
2685 const char* fileId = ((TObjString*) aFXSarray->At(0))->GetName();
2686 const char* source = ((TObjString*) aFXSarray->At(1))->GetName();
2688 TString whereClause;
2689 if (system == kDAQ || system == kDQM)
2691 whereClause = Form("where run=%d and detector=\"%s\" and fileId=\"%s\" and DAQsource=\"%s\";",
2692 GetCurrentRun(), fCurrentDetector.Data(), fileId, source);
2694 else if (system == kDCS)
2696 whereClause = Form("where run=%d and detector=\"%s\" and fileId=\"%s\";",
2697 GetCurrentRun(), fCurrentDetector.Data(), fileId);
2699 else if (system == kHLT)
2701 whereClause = Form("where run=%d and detector=\"%s\" and fileId=\"%s\" and DDLnumbers=\"%s\";",
2702 GetCurrentRun(), fCurrentDetector.Data(), fileId, source);
2707 TString sqlQuery = Form("update %s set time_processed=%ld %s", fConfig->GetFXSdbTable(system),
2708 (ULong_t)now.GetSec(), whereClause.Data());
2710 AliDebug(2, Form("SQL query: \n%s",sqlQuery.Data()));
2713 TSQLResult* aResult;
2714 aResult = dynamic_cast<TSQLResult*> (fServer[system]->Query(sqlQuery));
2717 Log(fCurrentDetector, Form("UpdateTable - %s db: can't execute SQL query <%s>",
2718 GetSystemName(system), sqlQuery.Data()));
2729 //_______________________________________________________________________________
2730 Bool_t AliShuttle::UpdateTableSkippedCase(const char* detector)
2733 // Update FXS table filling time_processed field in all rows corresponding to current run and detector
2734 // if detector = "ALL" update all detectors
2737 Bool_t result = kTRUE;
2739 TString detName(detector);
2741 for (UInt_t system=0; system<4; system++)
2744 // check connection, in case connect
2745 if (!Connect(system))
2747 Log(fCurrentDetector, Form("UpdateTableSkippedCase - Couldn't connect to %s FXS database", GetSystemName(system)));
2752 TTimeStamp now; // now
2754 // Loop on FXS list entries
2755 TIter iter(&fFXSlist[system]);
2757 TString whereClause;
2758 if (detName == "ALL") whereClause = Form("where run=%d and time_processed IS NULL;",GetCurrentRun());
2759 else whereClause = Form("where run=%d and detector=\"%s\" and time_processed IS NULL;",GetCurrentRun(), detector);
2761 //Log("SHUTTLE",Form(" whereClause = %s ",whereClause.Data()));
2763 TString sqlQuery = Form("update %s set time_processed=%ld %s", fConfig->GetFXSdbTable(system),
2764 (ULong_t)now.GetSec(), whereClause.Data());
2766 AliDebug(2, Form("SQL query: \n%s",sqlQuery.Data()));
2769 TSQLResult* aResult;
2770 aResult = dynamic_cast<TSQLResult*> (fServer[system]->Query(sqlQuery));
2773 Log("SHUTTLE", Form("UpdateTableSkippedCase - %s db: can't execute SQL query <%s>",
2774 GetSystemName(system), sqlQuery.Data()));
2784 //______________________________________________________________________________________________
2785 Bool_t AliShuttle::UpdateTableFailCase()
2787 // Update FXS table filling time_processed field in all rows corresponding to current run and detector
2788 // this is called in case the preprocessor is declared failed for the current run, because
2789 // the fields are updated only in case of success
2791 Bool_t result = kTRUE;
2793 for (UInt_t system=0; system<4; system++)
2795 // check connection, in case connect
2796 if (!Connect(system))
2798 Log(fCurrentDetector, Form("UpdateTableFailCase - Couldn't connect to %s FXS database",
2799 GetSystemName(system)));
2804 TTimeStamp now; // now
2806 // Loop on FXS list entries
2808 TString whereClause = Form("where run=%d and detector=\"%s\";",
2809 GetCurrentRun(), fCurrentDetector.Data());
2812 TString sqlQuery = Form("update %s set time_processed=%ld %s", fConfig->GetFXSdbTable(system),
2813 (ULong_t)now.GetSec(), whereClause.Data());
2815 AliDebug(2, Form("SQL query: \n%s",sqlQuery.Data()));
2818 TSQLResult* aResult;
2819 aResult = dynamic_cast<TSQLResult*> (fServer[system]->Query(sqlQuery));
2822 Log(fCurrentDetector, Form("UpdateTableFailCase - %s db: can't execute SQL query <%s>",
2823 GetSystemName(system), sqlQuery.Data()));
2833 //______________________________________________________________________________________________
2834 Bool_t AliShuttle::UpdateShuttleLogbook(const char* detector, const char* status)
2837 // Update Shuttle logbook filling detector or shuttle_done column
2838 // ex. of usage: UpdateShuttleLogbook("PHOS", "DONE") or UpdateShuttleLogbook("shuttle_done")
2841 // check connection, in case connect
2843 Log("SHUTTLE", "UpdateShuttleLogbook - Couldn't connect to DAQ Logbook.");
2847 TString detName(detector);
2849 if (detName == "shuttle_done" || detName == "shuttle_skipped")
2851 setClause = "set shuttle_done=1";
2853 if (detName == "shuttle_done")
2855 if (TouchFile() != kTRUE)
2857 SendMLRunInfo("Pending");
2861 SendMLRunInfo("Done");
2864 SendMLRunInfo("Skipped");
2867 TString statusStr(status);
2868 if(statusStr.Contains("done", TString::kIgnoreCase) ||
2869 statusStr.Contains("failed", TString::kIgnoreCase)){
2870 setClause = Form("set %s=\"%s\"", detector, status);
2873 Form("UpdateShuttleLogbook - Invalid status <%s> for detector %s",
2879 TString whereClause = Form("where run=%d", GetCurrentRun());
2881 TString sqlQuery = Form("update %s %s %s",
2882 fConfig->GetShuttlelbTable(), setClause.Data(), whereClause.Data());
2884 AliDebug(2, Form("SQL query: \n%s",sqlQuery.Data()));
2887 TSQLResult* aResult;
2888 aResult = dynamic_cast<TSQLResult*> (fServer[4]->Query(sqlQuery));
2890 Log("SHUTTLE", Form("UpdateShuttleLogbook - Can't execute query <%s>", sqlQuery.Data()));
2898 //______________________________________________________________________________________________
2899 Int_t AliShuttle::GetCurrentRun() const
2902 // Get current run from logbook entry
2905 return fLogbookEntry ? fLogbookEntry->GetRun() : -1;
2908 //______________________________________________________________________________________________
2909 UInt_t AliShuttle::GetCurrentStartTime() const
2912 // get current start time
2915 return fLogbookEntry ? fLogbookEntry->GetStartTime() : 0;
2918 //______________________________________________________________________________________________
2919 UInt_t AliShuttle::GetCurrentEndTime() const
2922 // get current end time from logbook entry
2925 return fLogbookEntry ? fLogbookEntry->GetEndTime() : 0;
2927 //______________________________________________________________________________________________
2928 UInt_t AliShuttle::GetCurrentYear() const
2931 // Get current year from logbook entry
2934 if (!fLogbookEntry) return 0;
2936 TTimeStamp startTime(GetCurrentStartTime());
2937 TString year = Form("%d",startTime.GetDate());
2943 //______________________________________________________________________________________________
2944 const char* AliShuttle::GetLHCPeriod() const
2947 // Get current LHC period from logbook entry
2950 if (!fLogbookEntry) return 0;
2952 return fLogbookEntry->GetRunParameter("LHCperiod");
2955 //______________________________________________________________________________________________
2956 void AliShuttle::Log(const char* detector, const char* message, UInt_t level)
2959 // Fill log string with a message
2962 TString logRunDir = GetShuttleLogDir();
2963 if (GetCurrentRun() >=0) {
2964 Int_t logDir_lev1 = GetCurrentRun()/10000;
2965 logRunDir += Form("/%d/%d", logDir_lev1, GetCurrentRun());
2967 void* dir = gSystem->OpenDirectory(logRunDir.Data());
2969 if (gSystem->mkdir(logRunDir.Data(), kTRUE)) {
2970 AliError(Form("Can't open directory <%s>", GetShuttleLogDir()));
2975 gSystem->FreeDirectory(dir);
2978 TString toLog = Form("%s UTC (%d): %s - ", TTimeStamp(time(0)).AsString("s"), getpid(), detector);
2979 if (GetCurrentRun() >= 0)
2980 toLog += Form("run %d - ", GetCurrentRun());
2981 toLog += Form("%s", message);
2983 AliLog::Message(level, toLog, MODULENAME(), ClassName(), FUNCTIONNAME(), __FILE__, __LINE__);
2985 // if we redirect the log output already to the file, leave here
2986 if (fOutputRedirected && strcmp(detector, "SHUTTLE") != 0)
2989 TString fileName = GetLogFileName(detector);
2991 gSystem->ExpandPathName(fileName);
2994 logFile.open(fileName, ofstream::out | ofstream::app);
2996 if (!logFile.is_open()) {
2997 AliError(Form("Could not open file %s", fileName.Data()));
3001 logFile << toLog.Data() << "\n";
3006 //______________________________________________________________________________________________
3007 TString AliShuttle::GetLogFileName(const char* detector) const
3010 // returns the name of the log file for a given sub detector
3015 if (GetCurrentRun() >= 0)
3017 Int_t logDir_lev1 = GetCurrentRun()/10000;
3018 fileName.Form("%s/%d/%d/%s.log", GetShuttleLogDir(), logDir_lev1, GetCurrentRun(),
3021 fileName.Form("%s/%s.log", GetShuttleLogDir(), detector);
3027 //______________________________________________________________________________________________
3028 void AliShuttle::SendAlive()
3030 // sends alive message to ML
3032 TMonaLisaText mlStatus("SHUTTLE_status", "Alive");
3035 mlList.Add(&mlStatus);
3037 fMonaLisa->SendParameters(&mlList, "__PROCESSINGINFO__");
3040 //______________________________________________________________________________________________
3041 Bool_t AliShuttle::Collect(Int_t run)
3044 // Collects conditions data for all UNPROCESSED run written to DAQ LogBook in case of run = -1 (default)
3045 // If a dedicated run is given this run is processed
3047 // In operational mode, this is the Shuttle function triggered by the EOR signal.
3051 Log("SHUTTLE","Collect - Shuttle called. Collecting conditions data for unprocessed runs");
3053 Log("SHUTTLE", Form("Collect - Shuttle called. Collecting conditions data for run %d", run));
3055 SetLastAction("Starting");
3057 // create ML instance
3059 fMonaLisa = new TMonaLisaWriter(fConfig->GetMonitorHost(), fConfig->GetMonitorTable());
3063 TString whereClause("where shuttle_done=0");
3065 whereClause += Form(" and run=%d", run);
3067 TObjArray shuttleLogbookEntries;
3068 if (!QueryShuttleLogbook(whereClause, shuttleLogbookEntries))
3070 Log("SHUTTLE", "Collect - Can't retrieve entries from Shuttle logbook");
3074 if (shuttleLogbookEntries.GetEntries() == 0)
3077 Log("SHUTTLE","Collect - Found no UNPROCESSED runs in Shuttle logbook");
3079 Log("SHUTTLE", Form("Collect - Run %d is already DONE "
3080 "or it does not exist in Shuttle logbook", run));
3084 for (UInt_t iDet=0; iDet<NDetectors(); iDet++)
3085 fFirstUnprocessed[iDet] = kTRUE;
3089 // query Shuttle logbook for earlier runs, check if some detectors are unprocessed,
3090 // flag them into fFirstUnprocessed array
3091 TString whereClauseBis(Form("where shuttle_done=0 and run < %d", run));
3092 TObjArray tmpLogbookEntries;
3093 if (!QueryShuttleLogbook(whereClauseBis, tmpLogbookEntries))
3095 Log("SHUTTLE", "Collect - Can't retrieve entries from Shuttle logbook");
3099 TIter iter(&tmpLogbookEntries);
3100 AliShuttleLogbookEntry* anEntry = 0;
3101 while ((anEntry = dynamic_cast<AliShuttleLogbookEntry*> (iter.Next())))
3103 for (UInt_t iDet=0; iDet<NDetectors(); iDet++)
3105 if (anEntry->GetDetectorStatus(iDet) == AliShuttleLogbookEntry::kUnprocessed)
3107 AliDebug(2, Form("Run %d: setting %s as \"not first time unprocessed\"",
3108 anEntry->GetRun(), GetDetName(iDet)));
3109 fFirstUnprocessed[iDet] = kFALSE;
3117 if (!RetrieveConditionsData(shuttleLogbookEntries))
3119 Log("SHUTTLE", "Collect - Process of at least one run failed");
3124 Log("SHUTTLE", "Collect - Requested run(s) successfully processed");
3129 //______________________________________________________________________________________________
3130 Bool_t AliShuttle::RetrieveConditionsData(const TObjArray& dateEntries)
3133 // Retrieve conditions data for all runs that aren't processed yet
3136 Bool_t hasError = kFALSE;
3138 TIter iter(&dateEntries);
3139 AliShuttleLogbookEntry* anEntry;
3141 while ((anEntry = (AliShuttleLogbookEntry*) iter.Next())){
3142 if (!Process(anEntry)){
3146 // clean SHUTTLE temp directory
3147 //TString filename = Form("%s/*.shuttle", GetShuttleTempDir());
3148 //RemoveFile(filename.Data());
3151 return hasError == kFALSE;
3154 //______________________________________________________________________________________________
3155 ULong_t AliShuttle::GetTimeOfLastAction() const
3158 // Gets time of last action
3163 fMonitoringMutex->Lock();
3165 tmp = fLastActionTime;
3167 fMonitoringMutex->UnLock();
3172 //______________________________________________________________________________________________
3173 const TString AliShuttle::GetLastAction() const
3176 // returns a string description of the last action
3181 fMonitoringMutex->Lock();
3185 fMonitoringMutex->UnLock();
3190 //______________________________________________________________________________________________
3191 void AliShuttle::SetLastAction(const char* action)
3194 // updates the monitoring variables
3197 fMonitoringMutex->Lock();
3199 fLastAction = action;
3200 fLastActionTime = time(0);
3202 fMonitoringMutex->UnLock();
3205 //______________________________________________________________________________________________
3206 const char* AliShuttle::GetRunParameter(const char* param)
3209 // returns run parameter read from DAQ logbook
3212 if(!fLogbookEntry) {
3213 AliError("No logbook entry!");
3217 return fLogbookEntry->GetRunParameter(param);
3220 //______________________________________________________________________________________________
3221 AliCDBEntry* AliShuttle::GetFromOCDB(const char* detector, const AliCDBPath& path)
3224 // returns object from OCDB valid for current run
3227 if (fTestMode & kErrorOCDB)
3229 Log(detector, "GetFromOCDB - In TESTMODE - Simulating error with OCDB");
3233 AliCDBStorage *sto = AliCDBManager::Instance()->GetStorage(fgkMainCDB);
3236 Log(detector, "GetFromOCDB - Cannot activate main OCDB for query!");
3240 return dynamic_cast<AliCDBEntry*> (sto->Get(path, GetCurrentRun()));
3243 //______________________________________________________________________________________________
3244 Bool_t AliShuttle::SendMail(EMailTarget target, Int_t system)
3247 // sends a mail to the subdetector expert in case of preprocessor error
3250 if (fTestMode != kNone)
3253 if (!fConfig->SendMail())
3256 if (target == kDCSEMail || target == kFXSEMail) {
3257 if (!fFirstProcessing)
3261 Int_t runMode = (Int_t)fConfig->GetRunMode();
3263 if (runMode == 0) tmpStr = " Nightly Test:";
3264 else tmpStr = " Data Taking:";
3265 void* dir = gSystem->OpenDirectory(GetShuttleLogDir());
3268 if (gSystem->mkdir(GetShuttleLogDir(), kTRUE))
3270 Log("SHUTTLE", Form("SendMail - Can't open directory <%s>", GetShuttleLogDir()));
3275 gSystem->FreeDirectory(dir);
3278 // det experts in to
3280 TIter *iterExperts = 0;
3281 if (target == kDCSEMail) {
3282 iterExperts = new TIter(fConfig->GetAdmins(AliShuttleConfig::kAmanda));
3284 else if (target == kFXSEMail) {
3285 iterExperts = new TIter(fConfig->GetAdmins(system));
3288 TObjString *anExpert=0;
3289 while ((anExpert = (TObjString*) iterExperts->Next()))
3291 to += Form("%s,", anExpert->GetName());
3296 // add subdetector experts
3297 iterExperts = new TIter(fConfig->GetResponsibles(fCurrentDetector));
3298 TObjString *anExpert=0;
3299 while ((anExpert = (TObjString*) iterExperts->Next()))
3301 to += Form("%s,", anExpert->GetName());
3305 if (to.Length() > 0)
3306 to.Remove(to.Length()-1);
3307 AliDebug(2, Form("to: %s",to.Data()));
3310 Log("SHUTTLE", Form("List of %d responsibles not set!", (Int_t) target));
3314 // SHUTTLE responsibles in cc
3316 TIter iterAdmins(fConfig->GetAdmins(AliShuttleConfig::kGlobal));
3317 TObjString *anAdmin=0;
3318 while ((anAdmin = (TObjString*) iterAdmins.Next()))
3320 cc += Form("%s,", anAdmin->GetName());
3322 if (cc.Length() > 0)
3323 cc.Remove(cc.Length()-1);
3324 AliDebug(2, Form("cc: %s",to.Data()));
3327 TString bodyFileName;
3328 bodyFileName.Form("%s/mail.body", GetShuttleLogDir());
3329 gSystem->ExpandPathName(bodyFileName);
3332 mailBody.open(bodyFileName, ofstream::out);
3334 if (!mailBody.is_open())
3336 Log("SHUTTLE", Form("Could not open mail body file %s", bodyFileName.Data()));
3344 if (target == kDCSEMail){
3345 subject = Form("%s CRITICAL Retrieval of data points for %s FAILED in run %d !",
3346 tmpStr.Data(), fCurrentDetector.Data(), GetCurrentRun());
3347 AliDebug(2, Form("subject: %s", subject.Data()));
3349 body = Form("Dear DCS experts, \n\n");
3350 body += Form("SHUTTLE couldn\'t retrieve the data points for detector %s "
3351 "in run %d!!\n\n", fCurrentDetector.Data(), GetCurrentRun());
3353 else if (target == kFXSEMail){
3354 subject = Form("%s CRITICAL FXS communication for %s FAILED in run %d !",
3355 tmpStr.Data(), fCurrentDetector.Data(), GetCurrentRun());
3356 AliDebug(2, Form("subject: %s", subject.Data()));
3358 if (system == kDAQ) sys="DAQ";
3359 else if (system == kDCS) sys="DCS";
3360 else if (system == kHLT) sys="HLT";
3361 else if (system == kDQM) sys="DQM";
3363 body = Form("Dear %s FXS experts, \n\n",sys.Data());
3364 body += Form("SHUTTLE couldn\'t retrieve data from the FXS for detector %s "
3365 "in run %d!!\n\n", fCurrentDetector.Data(), GetCurrentRun());
3366 body += Form("The contacted server was:\nDB: %s\nFXS:%s\n\n", fConfig->GetFXSdbHost(system), fConfig->GetFXSHost(system));
3369 subject = Form("%s %s Shuttle preprocessor FAILED in run %d (run type = %s)!",
3370 tmpStr.Data(), fCurrentDetector.Data(), GetCurrentRun(), GetRunType());
3371 AliDebug(2, Form("subject: %s", subject.Data()));
3373 body = Form("Dear %s expert(s), \n\n", fCurrentDetector.Data());
3374 body += Form("SHUTTLE just detected that your preprocessor "
3375 "failed processing run %d (run type = %s)!!\n\n",
3376 GetCurrentRun(), GetRunType());
3379 body += Form("Please check %s status on the SHUTTLE monitoring page: \n\n",
3380 fCurrentDetector.Data());
3381 if (fConfig->GetRunMode() == AliShuttleConfig::kTest)
3383 body += Form("\thttp://pcalimonitor.cern.ch/shuttle.jsp?time=24 \n\n");
3385 body += Form("\thttp://pcalimonitor.cern.ch/shuttle.jsp?instance=PROD&time=24 \n\n");
3389 TString logFolder = "logs";
3390 if (fConfig->GetRunMode() == AliShuttleConfig::kProd)
3391 logFolder += "_PROD";
3394 body += Form("Find the %s log for the current run on \n\n"
3395 "\thttp://pcalishuttle02.cern.ch/%s/%d/%d/%s.log \n\n",
3396 fCurrentDetector.Data(), logFolder.Data(), GetCurrentRun()/10000,
3397 GetCurrentRun(), fCurrentDetector.Data());
3398 body += Form("The last 15 lines of %s log file are following:\n\n", fCurrentDetector.Data());
3400 AliDebug(2, Form("Body begin: %s", body.Data()));
3402 mailBody << body.Data();
3404 mailBody.open(bodyFileName, ofstream::out | ofstream::app);
3406 TString logFileName = Form("%s/%d/%d/%s.log", GetShuttleLogDir(),
3407 GetCurrentRun()/10000, GetCurrentRun(), fCurrentDetector.Data());
3408 TString tailCommand = Form("tail -n 15 %s >> %s", logFileName.Data(), bodyFileName.Data());
3409 if (gSystem->Exec(tailCommand.Data()))
3411 mailBody << Form("%s log file not found ...\n\n", fCurrentDetector.Data());
3414 TString endBody = Form("------------------------------------------------------\n\n");
3415 endBody += Form("In case of problems please contact the SHUTTLE core team.\n\n");
3416 endBody += "Please do not answer this message directly, it is automatically generated.\n\n";
3417 endBody += "Greetings,\n\n \t\t\tthe SHUTTLE\n";
3419 AliDebug(2, Form("Body end: %s", endBody.Data()));
3421 mailBody << endBody.Data();
3426 TString mailCommand = Form("mail -s \"%s\" -c %s %s < %s",
3430 bodyFileName.Data());
3431 AliDebug(2, Form("mail command: %s", mailCommand.Data()));
3433 Bool_t result = gSystem->Exec(mailCommand.Data());
3437 //______________________________________________________________________________________________
3438 const char* AliShuttle::GetRunType()
3441 // returns run type read from "run type" logbook
3444 if(!fLogbookEntry) {
3445 AliError("No logbook entry!");
3449 return fLogbookEntry->GetRunType();
3452 //______________________________________________________________________________________________
3453 Bool_t AliShuttle::GetHLTStatus()
3455 // Return HLT status (ON=1 OFF=0)
3456 // Converts the HLT status from the mode string read in the run logbook (not just a bool)
3458 if(!fLogbookEntry) {
3459 AliError("No logbook entry!");
3463 // TODO implement when HLTMode is inserted in run logbook
3464 TString hltMode = fLogbookEntry->GetRunParameter("HLTmode");
3465 TSubString firstChar = hltMode(0,1);
3466 AliDebug(2,Form("First char = %s ",firstChar.Data()));
3467 if (firstChar == "A") {
3470 else if ((firstChar == "B") || (firstChar == "C") || (firstChar == "D") || (firstChar == "E")) {
3474 Log("SHUTTLE","Unexpected HLT mode! Returning 0....");
3479 //______________________________________________________________________________________________
3480 const char* AliShuttle::GetTriggerConfiguration()
3482 // Receives the trigger configuration from the DAQ logbook for the current run
3484 // check connection, if needed reconnect
3489 sqlQuery.Form("SELECT configFile FROM logbook_trigger_config WHERE run = %d", GetCurrentRun());
3490 TSQLResult* result = fServer[4]->Query(sqlQuery);
3493 Log("SHUTTLE", Form("ERROR: Can't execute query <%s>!", sqlQuery.Data()));
3497 if (result->GetRowCount() == 0)
3499 Log("SHUTTLE", "WARNING: Trigger configuration not found in logbook_trigger_config");
3504 TSQLRow* row = result->Next();
3507 Log("SHUTTLE", "ERROR: Could not receive logbook_trigger_config data");
3512 // static, so that pointer remains valid when it is returned to the calling class
3513 static TString triggerConfig(row->GetField(0));
3521 Log("SHUTTLE", Form("Found trigger configuration: %s", triggerConfig.Data()));
3523 return triggerConfig;
3526 //______________________________________________________________________________________________
3527 const char* AliShuttle::GetCTPTimeParams()
3529 // Receives the CTP time parameters from the DAQ logbook for the current run
3531 // check connection, if needed reconnect
3536 sqlQuery.Form("SELECT alignmentFile FROM logbook_trigger_config WHERE run = %d", GetCurrentRun());
3537 TSQLResult* result = fServer[4]->Query(sqlQuery);
3540 Log("SHUTTLE", Form("ERROR: Can't execute query <%s>!", sqlQuery.Data()));
3544 if (result->GetRowCount() == 0)
3546 Log("SHUTTLE", "WARNING: CTP time params not found in logbook_trigger_config");
3551 TSQLRow* row = result->Next();
3554 Log("SHUTTLE", "ERROR: Could not receive logbook_trigger_config data");
3559 // static, so that pointer remains valid when it is returned to the calling class
3560 static TString triggerTimeParams(row->GetField(0));
3568 Log("SHUTTLE", Form("Found trigger time parameters: %s", triggerTimeParams.Data()));
3570 return triggerTimeParams;
3573 //______________________________________________________________________________________________
3574 const char* AliShuttle::GetTriggerDetectorMask()
3576 // Receives the trigger detector mask from DAQ logbook
3578 // check connection, if needed reconnect
3583 sqlQuery.Form("SELECT BIN(BIT_OR(inputDetectorMask)) from logbook_trigger_clusters WHERE run = %d;", GetCurrentRun());
3584 TSQLResult* result = fServer[4]->Query(sqlQuery);
3587 Log("SHUTTLE", Form("ERROR: Can't execute query <%s>!", sqlQuery.Data()));
3591 if (result->GetRowCount() == 0)
3593 Log("SHUTTLE", "ERROR: Trigger Detector Mask not found in logbook_trigger_clusters");
3598 TSQLRow* row = result->Next();
3601 Log("SHUTTLE", "ERROR: Could not receive logbook_trigger_clusters data");
3606 // static, so that pointer remains valid when it is returned to the calling class
3607 static TString triggerDetectorMask(row->GetField(0));
3615 Log("SHUTTLE", Form("Found Trigger Detector Mask: %s", triggerDetectorMask.Data()));
3617 return triggerDetectorMask;
3620 //______________________________________________________________________________________________
3621 void AliShuttle::SetShuttleTempDir(const char* tmpDir)
3624 // sets Shuttle temp directory
3627 fgkShuttleTempDir = gSystem->ExpandPathName(tmpDir);
3630 //______________________________________________________________________________________________
3631 void AliShuttle::SetShuttleLogDir(const char* logDir)
3634 // sets Shuttle log directory
3637 fgkShuttleLogDir = gSystem->ExpandPathName(logDir);
3639 //______________________________________________________________________________________________
3640 Bool_t AliShuttle::TouchFile()
3643 // touching a file on the grid if run has been DONE
3648 Log("SHUTTLE",Form("No TGrid connection estabilished!"));
3649 Log("SHUTTLE",Form("Could not touch file for run %i",GetCurrentRun()));
3654 dir.Form("%s%d/SHUTTLE_DONE", fConfig->GetAlienPath(), GetCurrentYear());
3655 // checking whether directory for touch command exists
3657 commandLs.Form("ls %s",dir.Data());
3658 TGridResult *resultLs = dynamic_cast<TGridResult*>(gGrid->Command(commandLs));
3660 Log("SHUTTLE",Form("No result for %s command, returning without touching",commandLs.Data()));
3663 TMap *mapLs = dynamic_cast<TMap*>(resultLs->At(0));
3665 Log("SHUTTLE",Form("No map for %s command, returning without touching",commandLs.Data()));
3670 TObjString *valueLsPath = dynamic_cast<TObjString*>(mapLs->GetValue("path"));
3671 if (!valueLsPath || (valueLsPath->GetString()).CompareTo(dir)!=1){
3672 Log("SHUTTLE",Form("No directory %s found, creating it",dir.Data()));
3674 // creating the directory
3676 Bool_t boolMkdir = gGrid->Mkdir(dir.Data());
3678 Log("SHUTTLE",Form("Impossible to create dir %s in alien catalogue for run %i!",dir.Data(),GetCurrentRun()));
3683 Log("SHUTTLE",Form("Directory %s successfully created in alien catalogue for run %i",dir.Data(),GetCurrentRun()));
3686 Log("SHUTTLE",Form("Directory %s correctly found for run %i",dir.Data(),GetCurrentRun()));
3693 command.Form("touch %s/%i", dir.Data(), GetCurrentRun());
3694 Log("SHUTTLE", Form("Creating entry in file catalog: %s", command.Data()));
3695 TGridResult *resultTouch = dynamic_cast<TGridResult*>(gGrid->Command(command));
3697 Log("SHUTTLE",Form("No result for touching command, returning without touching for run %i",GetCurrentRun()));
3700 TMap *mapTouch = dynamic_cast<TMap*>(resultTouch->At(0));
3702 Log("SHUTTLE",Form("No map for touching command, returning without touching for run %i",GetCurrentRun()));
3707 TObjString *valueTouch = dynamic_cast<TObjString*>(mapTouch->GetValue("__result__"));
3709 Log("SHUTTLE",Form("No value for \"__result__\" key set in the map for touching command, returning without touching for run %i",GetCurrentRun()));
3714 if (valueTouch->GetString()!="1"){
3715 Log("SHUTTLE",Form("Failing the touching command, returning without touching for run %i",GetCurrentRun()));
3722 Log("SHUTTLE", "Sucessfully touched the file");
3725 //______________________________________________________________________________________________
3726 UInt_t AliShuttle::GetStartTimeDCSQuery()
3728 // Return Start Time for the DCS query
3730 // The call is delegated to AliShuttleInterface
3732 return GetCurrentStartTime()-fConfig->GetDCSQueryOffset();
3734 //______________________________________________________________________________________________
3735 UInt_t AliShuttle::GetEndTimeDCSQuery()
3737 // Return End Time for the DCS query
3739 // The call is delegated to AliShuttleInterface
3741 return GetCurrentEndTime()+fConfig->GetDCSQueryOffset();
3743 //______________________________________________________________________________________________
3744 void AliShuttle::SendMLFromDet(const char* value)
3747 // Sending an information coming from the current detector to ML
3750 TMonaLisaText mlText(Form("%s_RunCondition", fCurrentDetector.Data()), value);
3753 mlList.Add(&mlText);
3756 mlID.Form("%d", GetCurrentRun());
3757 fMonaLisa->SendParameters(&mlList, mlID);
3761 //______________________________________________________________________________________________
3762 TString* AliShuttle::GetLTUConfig(const char* det)
3765 // Getting ltuFineDelay1, ltuFineDelay2, ltuBCDelay for detector det from logbook_detectors table in logbook
3772 sqlQuery.Form("select LTUFineDelay1, LTUFineDelay2, LTUBCDelayAdd from logbook_detectors WHERE run_number = %d and detector = \"%s\";", GetCurrentRun(),det);
3774 TSQLResult* result = fServer[4]->Query(sqlQuery);
3776 Log("SHUTTLE","ERROR: No result found for the LTU configuration query");
3779 if (result->GetRowCount() == 0){
3780 Log("SHUTTLE",Form("ERROR: LTU configuration not found in logbook_detectors for detector %s, returning null pointer",det));
3784 if (result->GetFieldCount() != 3){
3785 Log("SHUTTLE",Form("ERROR: not all the required fields are there for the LTU configuration for detector %s (only %d found), returning a null pointer",det, result->GetFieldCount()));
3789 TSQLRow* row = result->Next();
3791 Printf("ERROR: Could not receive logbook_detectors data, returning null pointer");
3795 TString* ltuConfigString = new TString[3];
3797 ltuConfigString[0] = row->GetField(0);
3798 ltuConfigString[1] = row->GetField(1);
3799 ltuConfigString[2] = row->GetField(2);
3801 return ltuConfigString;