1 /**************************************************************************
2 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
4 * Author: The ALICE Off-line Project. *
5 * Contributors are mentioned in the code where appropriate. *
7 * Permission to use, copy, modify and distribute this software and its *
8 * documentation strictly for non-commercial purposes is hereby granted *
9 * without fee, provided that the above copyright notice appears in all *
10 * copies and that both the copyright notice and this permission notice *
11 * appear in the supporting documentation. The authors make no claims *
12 * about the suitability of this software for any purpose. It is *
13 * provided "as is" without express or implied warranty. *
14 **************************************************************************/
19 // This class is the main manager for AliShuttle.
20 // It organizes the data retrieval from DCS and call the
21 // interface methods of AliPreprocessor.
22 // For every detector in AliShuttleConfgi (see AliShuttleConfig),
23 // data for its set of aliases is retrieved. If there is registered
24 // AliPreprocessor for this detector then it will be used
25 // accroding to the schema (see AliPreprocessor).
26 // If there isn't registered AliPreprocessor than the retrieved
27 // data is stored automatically to the undelying AliCDBStorage.
28 // For detSpec is used the alias name.
31 #include "AliShuttle.h"
33 #include "AliCDBManager.h"
34 #include "AliCDBStorage.h"
36 #include "AliCDBRunRange.h"
37 #include "AliCDBPath.h"
38 #include "AliCDBEntry.h"
39 #include "AliShuttleConfig.h"
40 #include "DCSClient/AliDCSClient.h"
42 #include "AliPreprocessor.h"
43 #include "AliShuttleStatus.h"
44 #include "AliShuttleLogbookEntry.h"
49 #include <TTimeStamp.h>
50 #include <TObjString.h>
51 #include <TSQLServer.h>
52 #include <TSQLResult.h>
55 #include <TSystemDirectory.h>
56 #include <TSystemFile.h>
59 #include <TGridResult.h>
61 #include <TMonaLisaWriter.h>
65 #include <sys/types.h>
72 //______________________________________________________________________________________________
73 AliShuttle::AliShuttle(const AliShuttleConfig* config,
74 UInt_t timeout, Int_t retries):
76 fTimeout(timeout), fRetries(retries),
86 fReadTestMode(kFALSE),
87 fOutputRedirected(kFALSE)
90 // config: AliShuttleConfig used
91 // timeout: timeout used for AliDCSClient connection
92 // retries: the number of retries in case of connection error.
95 if (!fConfig->IsValid()) AliFatal("********** !!!!! Invalid configuration !!!!! **********");
96 for(int iSys=0;iSys<4;iSys++) {
99 fFXSlist[iSys].SetOwner(kTRUE);
101 fPreprocessorMap.SetOwner(kTRUE);
103 for (UInt_t iDet=0; iDet<NDetectors(); iDet++)
104 fFirstUnprocessed[iDet] = kFALSE;
106 fMonitoringMutex = new TMutex();
109 //______________________________________________________________________________________________
110 AliShuttle::~AliShuttle()
116 fPreprocessorMap.DeleteAll();
117 for(int iSys=0;iSys<4;iSys++)
119 fServer[iSys]->Close();
120 delete fServer[iSys];
129 if (fMonitoringMutex)
131 delete fMonitoringMutex;
132 fMonitoringMutex = 0;
136 //______________________________________________________________________________________________
137 void AliShuttle::RegisterPreprocessor(AliPreprocessor* preprocessor)
140 // Registers new AliPreprocessor.
141 // It uses GetName() for indentificator of the pre processor.
142 // The pre processor is registered it there isn't any other
143 // with the same identificator (GetName()).
146 const char* detName = preprocessor->GetName();
147 if(GetDetPos(detName) < 0)
148 AliFatal(Form("********** !!!!! Invalid detector name: %s !!!!! **********", detName));
150 if (fPreprocessorMap.GetValue(detName)) {
151 AliWarning(Form("AliPreprocessor %s is already registered!", detName));
155 fPreprocessorMap.Add(new TObjString(detName), preprocessor);
157 //______________________________________________________________________________________________
158 Bool_t AliShuttle::Store(const AliCDBPath& path, TObject* object,
159 AliCDBMetaData* metaData, Int_t validityStart, Bool_t validityInfinite)
161 // Stores a CDB object in the storage for offline reconstruction. Objects that are not needed for
162 // offline reconstruction, but should be stored anyway (e.g. for debugging) should NOT be stored
163 // using this function. Use StoreReferenceData instead!
164 // It calls StoreLocally function which temporarily stores the data locally; when the preprocessor
165 // finishes the data are transferred to the main storage (Grid).
167 return StoreLocally(fgkLocalCDB, path, object, metaData, validityStart, validityInfinite);
170 //______________________________________________________________________________________________
171 Bool_t AliShuttle::StoreReferenceData(const AliCDBPath& path, TObject* object, AliCDBMetaData* metaData)
173 // Stores a CDB object in the storage for reference data. This objects will not be available during
174 // offline reconstrunction. Use this function for reference data only!
175 // It calls StoreLocally function which temporarily stores the data locally; when the preprocessor
176 // finishes the data are transferred to the main storage (Grid).
178 return StoreLocally(fgkLocalRefStorage, path, object, metaData);
181 //______________________________________________________________________________________________
182 Bool_t AliShuttle::StoreLocally(const TString& localUri,
183 const AliCDBPath& path, TObject* object, AliCDBMetaData* metaData,
184 Int_t validityStart, Bool_t validityInfinite)
186 // Store object temporarily in local storage. Parameters are passed by Store and StoreReferenceData functions.
187 // when the preprocessor finishes the data are transferred to the main storage (Grid).
188 // The parameters are:
189 // 1) Uri of the backup storage (Local)
190 // 2) the object's path.
191 // 3) the object to be stored
192 // 4) the metaData to be associated with the object
193 // 5) the validity start run number w.r.t. the current run,
194 // if the data is valid only for this run leave the default 0
195 // 6) specifies if the calibration data is valid for infinity (this means until updated),
196 // typical for calibration runs, the default is kFALSE
198 // returns 0 if fail, 1 otherwise
200 if (fTestMode & kErrorStorage)
202 Log(fCurrentDetector, "StoreLocally - In TESTMODE - Simulating error while storing locally");
206 const char* cdbType = (localUri == fgkLocalCDB) ? "CDB" : "Reference";
208 Int_t firstRun = GetCurrentRun() - validityStart;
210 AliWarning("First valid run happens to be less than 0! Setting it to 0.");
215 if(validityInfinite) {
216 lastRun = AliCDBRunRange::Infinity();
218 lastRun = GetCurrentRun();
221 // Version is set to current run, it will be used later to transfer data to Grid
222 AliCDBId id(path, firstRun, lastRun, GetCurrentRun(), -1);
224 if(! dynamic_cast<TObjString*> (metaData->GetProperty("RunUsed(TObjString)"))){
225 TObjString runUsed = Form("%d", GetCurrentRun());
226 metaData->SetProperty("RunUsed(TObjString)", runUsed.Clone());
229 Bool_t result = kFALSE;
231 if (!(AliCDBManager::Instance()->GetStorage(localUri))) {
232 Log("SHUTTLE", Form("StoreLocally - Cannot activate local %s storage", cdbType));
234 result = AliCDBManager::Instance()->GetStorage(localUri)
235 ->Put(object, id, metaData);
240 Log(fCurrentDetector, Form("StoreLocally - Can't store object <%s>!", id.ToString().Data()));
246 //______________________________________________________________________________________________
247 Bool_t AliShuttle::StoreOCDB()
250 // Called when preprocessor ends successfully or when previous storage attempt failed (kStoreError status)
251 // Calls underlying StoreOCDB(const char*) function twice, for OCDB and Reference storage.
252 // Then calls StoreRefFilesToGrid to store reference files.
255 if (fTestMode & kErrorGrid)
257 Log("SHUTTLE", "StoreOCDB - In TESTMODE - Simulating error while storing in the Grid");
258 Log(fCurrentDetector, "StoreOCDB - In TESTMODE - Simulating error while storing in the Grid");
262 Log("SHUTTLE","StoreOCDB - Storing OCDB data ...");
263 Bool_t resultCDB = StoreOCDB(fgkMainCDB);
265 Log("SHUTTLE","StoreOCDB - Storing reference data ...");
266 Bool_t resultRef = StoreOCDB(fgkMainRefStorage);
268 Log("SHUTTLE","StoreOCDB - Storing reference files ...");
269 Bool_t resultRefFiles = CopyFilesToGrid("reference");
271 Bool_t resultMetadata = kTRUE;
272 if(fCurrentDetector == "GRP")
274 Log("StoreOCDB - SHUTTLE","Storing Run Metadata file ...");
275 resultMetadata = CopyFilesToGrid("metadata");
278 return resultCDB && resultRef && resultRefFiles && resultMetadata;
281 //______________________________________________________________________________________________
282 Bool_t AliShuttle::StoreOCDB(const TString& gridURI)
285 // Called by StoreOCDB(), performs actual storage to the main OCDB and reference storages (Grid)
288 TObjArray* gridIds=0;
290 Bool_t result = kTRUE;
292 const char* type = 0;
294 if(gridURI == fgkMainCDB) {
296 localURI = fgkLocalCDB;
297 } else if(gridURI == fgkMainRefStorage) {
299 localURI = fgkLocalRefStorage;
301 AliError(Form("Invalid storage URI: %s", gridURI.Data()));
305 AliCDBManager* man = AliCDBManager::Instance();
307 AliCDBStorage *gridSto = man->GetStorage(gridURI);
310 Form("StoreOCDB - cannot activate main %s storage", type));
314 gridIds = gridSto->GetQueryCDBList();
316 // get objects previously stored in local CDB
317 AliCDBStorage *localSto = man->GetStorage(localURI);
320 Form("StoreOCDB - cannot activate local %s storage", type));
323 AliCDBPath aPath(GetOfflineDetName(fCurrentDetector.Data()),"*","*");
324 // Local objects were stored with current run as Grid version!
325 TList* localEntries = localSto->GetAll(aPath.GetPath(), GetCurrentRun(), GetCurrentRun());
326 localEntries->SetOwner(1);
328 // loop on local stored objects
329 TIter localIter(localEntries);
330 AliCDBEntry *aLocEntry = 0;
331 while((aLocEntry = dynamic_cast<AliCDBEntry*> (localIter.Next()))){
332 aLocEntry->SetOwner(1);
333 AliCDBId aLocId = aLocEntry->GetId();
334 aLocEntry->SetVersion(-1);
335 aLocEntry->SetSubVersion(-1);
337 // If local object is valid up to infinity we store it only if it is
338 // the first unprocessed run!
339 if (aLocId.GetLastRun() == AliCDBRunRange::Infinity() &&
340 !fFirstUnprocessed[GetDetPos(fCurrentDetector)])
342 Log("SHUTTLE", Form("StoreOCDB - %s: object %s has validity infinite but "
343 "there are previous unprocessed runs!",
344 fCurrentDetector.Data(), aLocId.GetPath().Data()));
349 // loop on Grid valid Id's
350 Bool_t store = kTRUE;
351 TIter gridIter(gridIds);
352 AliCDBId* aGridId = 0;
353 while((aGridId = dynamic_cast<AliCDBId*> (gridIter.Next()))){
354 if(aGridId->GetPath() != aLocId.GetPath()) continue;
355 // skip all objects valid up to infinity
356 if(aGridId->GetLastRun() == AliCDBRunRange::Infinity()) continue;
357 // if we get here, it means there's already some more recent object stored on Grid!
362 // If we get here, the file can be stored!
363 Bool_t storeOk = gridSto->Put(aLocEntry);
364 if(!store || storeOk){
368 Log(fCurrentDetector.Data(),
369 Form("StoreOCDB - A more recent object already exists in %s storage: <%s>",
370 type, aGridId->ToString().Data()));
373 Form("StoreOCDB - Object <%s> successfully put into %s storage",
374 aLocId.ToString().Data(), type));
375 Log(fCurrentDetector.Data(),
376 Form("StoreOCDB - Object <%s> successfully put into %s storage",
377 aLocId.ToString().Data(), type));
380 // removing local filename...
382 localSto->IdToFilename(aLocId, filename);
383 Log("SHUTTLE", Form("StoreOCDB - Removing local file %s", filename.Data()));
384 RemoveFile(filename.Data());
388 Form("StoreOCDB - Grid %s storage of object <%s> failed",
389 type, aLocId.ToString().Data()));
390 Log(fCurrentDetector.Data(),
391 Form("StoreOCDB - Grid %s storage of object <%s> failed",
392 type, aLocId.ToString().Data()));
396 localEntries->Clear();
401 //______________________________________________________________________________________________
402 Bool_t AliShuttle::CleanReferenceStorage(const char* detector)
404 // clears the directory used to store reference files of a given subdetector
406 AliCDBManager* man = AliCDBManager::Instance();
407 AliCDBStorage* sto = man->GetStorage(fgkLocalRefStorage);
408 TString localBaseFolder = sto->GetBaseFolder();
410 TString targetDir = GetRefFilePrefix(localBaseFolder.Data(), detector);
412 Log("SHUTTLE", Form("CleanReferenceStorage - Cleaning %s", targetDir.Data()));
415 begin.Form("%d_", GetCurrentRun());
417 TSystemDirectory* baseDir = new TSystemDirectory("/", targetDir);
421 TList* dirList = baseDir->GetListOfFiles();
424 if (!dirList) return kTRUE;
426 if (dirList->GetEntries() < 3)
432 Int_t nDirs = 0, nDel = 0;
433 TIter dirIter(dirList);
434 TSystemFile* entry = 0;
436 Bool_t success = kTRUE;
438 while ((entry = dynamic_cast<TSystemFile*> (dirIter.Next())))
440 if (entry->IsDirectory())
443 TString fileName(entry->GetName());
444 if (!fileName.BeginsWith(begin))
450 Int_t result = gSystem->Unlink(fileName.Data());
454 Log("SHUTTLE", Form("CleanReferenceStorage - Could not delete file %s!", fileName.Data()));
462 Log("SHUTTLE", Form("CleanReferenceStorage - %d (over %d) reference files in folder %s were deleted.",
463 nDel, nDirs, targetDir.Data()));
474 Int_t result = gSystem->GetPathInfo(targetDir, 0, (Long64_t*) 0, 0, 0);
478 result = gSystem->Exec(Form("rm -rf %s", targetDir.Data()));
481 Log("SHUTTLE", Form("CleanReferenceStorage - Could not clean directory %s", targetDir.Data()));
486 result = gSystem->mkdir(targetDir, kTRUE);
489 Log("SHUTTLE", Form("CleanReferenceStorage - Error creating base directory %s", targetDir.Data()));
496 //______________________________________________________________________________________________
497 Bool_t AliShuttle::StoreReferenceFile(const char* detector, const char* localFile, const char* gridFileName)
500 // Stores reference file directly (without opening it). This function stores the file locally.
502 // The file is stored under the following location:
503 // <base folder of local reference storage>/<DET>/<RUN#>_<gridFileName>
504 // where <gridFileName> is the second parameter given to the function
507 if (fTestMode & kErrorStorage)
509 Log(fCurrentDetector, "StoreReferenceFile - In TESTMODE - Simulating error while storing locally");
513 AliCDBManager* man = AliCDBManager::Instance();
514 AliCDBStorage* sto = man->GetStorage(fgkLocalRefStorage);
516 TString localBaseFolder = sto->GetBaseFolder();
518 TString target = GetRefFilePrefix(localBaseFolder.Data(), detector);
519 target.Append(Form("/%d_%s", GetCurrentRun(), gridFileName));
521 return CopyFileLocally(localFile, target);
524 //______________________________________________________________________________________________
525 Bool_t AliShuttle::StoreRunMetadataFile(const char* localFile, const char* gridFileName)
528 // Stores Run metadata file to the Grid, in the run folder
530 // Only GRP can call this function.
532 if (fTestMode & kErrorStorage)
534 Log(fCurrentDetector, "StoreRunMetaDataFile - In TESTMODE - Simulating error while storing locally");
538 AliCDBManager* man = AliCDBManager::Instance();
539 AliCDBStorage* sto = man->GetStorage(fgkLocalRefStorage);
541 TString localBaseFolder = sto->GetBaseFolder();
543 // Build Run level folder
544 // folder = /alice/data/year/lhcPeriod/runNb/raw
547 TString lhcPeriod = GetLHCPeriod();
548 if (lhcPeriod.Length() == 0)
550 Log("SHUTTLE","StoreRunMetaDataFile - LHCPeriod not found in logbook!");
554 // TODO partitions with one detector only write data into LHCperiod_DET
555 TString partition = GetRunParameter("detector");
557 if (partition.Length() > 0 && partition != "ALICE")
559 lhcPeriod.Append(Form("_%s", partition.Data()));
560 Log(fCurrentDetector, Form("Run data tags merged file will be written in %s",
564 TString target = Form("%s/GRP/RunMetadata/alice/data/%d/%s/%09d/raw/%s",
565 localBaseFolder.Data(), GetCurrentYear(),
566 lhcPeriod.Data(), GetCurrentRun(), gridFileName);
568 return CopyFileLocally(localFile, target);
571 //______________________________________________________________________________________________
572 Bool_t AliShuttle::CopyFileLocally(const char* localFile, const TString& target)
575 // Stores file locally. Called by StoreReferenceFile and StoreRunMetadataFile
576 // Files are temporarily stored in the local reference storage. When the preprocessor
577 // finishes, the Shuttle calls CopyFilesToGrid to transfer the files to AliEn
578 // (in reference or run level folders)
581 TString targetDir(target(0, target.Last('/')));
583 //try to open base dir folder, if it does not exist
584 void* dir = gSystem->OpenDirectory(targetDir.Data());
586 if (gSystem->mkdir(targetDir.Data(), kTRUE)) {
587 Log("SHUTTLE", Form("CopyFileLocally - Can't open directory <%s>", targetDir.Data()));
592 gSystem->FreeDirectory(dir);
597 result = gSystem->GetPathInfo(localFile, 0, (Long64_t*) 0, 0, 0);
600 Log("SHUTTLE", Form("CopyFileLocally - %s does not exist", localFile));
604 result = gSystem->GetPathInfo(target, 0, (Long64_t*) 0, 0, 0);
607 Log("SHUTTLE", Form("CopyFileLocally - target file %s already exist, removing...", target.Data()));
608 if (gSystem->Unlink(target.Data()))
610 Log("SHUTTLE", Form("CopyFileLocally - Could not remove existing target file %s!", target.Data()));
615 result = gSystem->CopyFile(localFile, target);
619 Log("SHUTTLE", Form("CopyFileLocally - File %s stored locally to %s", localFile, target.Data()));
624 Log("SHUTTLE", Form("CopyFileLocally - Could not store file %s to %s! Error code = %d",
625 localFile, target.Data(), result));
633 //______________________________________________________________________________________________
634 Bool_t AliShuttle::CopyFilesToGrid(const char* type)
637 // Transfers local files to the Grid. Local files can be reference files
638 // or run metadata file (from GRP only).
640 // According to the type (ref, metadata) the files are stored under the following location:
641 // ref --> <base folder of reference storage>/<DET>/<RUN#>_<gridFileName>
642 // metadata --> <run data folder>/<MetadataFileName>
645 AliCDBManager* man = AliCDBManager::Instance();
646 AliCDBStorage* sto = man->GetStorage(fgkLocalRefStorage);
649 TString localBaseFolder = sto->GetBaseFolder();
655 if (strcmp(type, "reference") == 0)
657 dir = GetRefFilePrefix(localBaseFolder.Data(), fCurrentDetector.Data());
658 AliCDBStorage* gridSto = man->GetStorage(fgkMainRefStorage);
661 TString gridBaseFolder = gridSto->GetBaseFolder();
662 alienDir = GetRefFilePrefix(gridBaseFolder.Data(), fCurrentDetector.Data());
663 begin = Form("%d_", GetCurrentRun());
665 else if (strcmp(type, "metadata") == 0)
668 TString lhcPeriod = GetLHCPeriod();
670 if (lhcPeriod.Length() == 0)
672 Log("SHUTTLE","CopyFilesToGrid - LHCPeriod not found in logbook!");
676 // TODO partitions with one detector only write data into LHCperiod_DET
677 TString partition = GetRunParameter("detector");
679 if (partition.Length() > 0 && partition != "ALICE")
681 lhcPeriod.Append(Form("_%s", partition.Data()));
684 dir = Form("%s/GRP/RunMetadata/alice/data/%d/%s/%09d/raw",
685 localBaseFolder.Data(), GetCurrentYear(),
686 lhcPeriod.Data(), GetCurrentRun());
687 alienDir = dir(dir.Index("/alice/data/"), dir.Length());
693 Log("SHUTTLE", "CopyFilesToGrid - Unexpected: type label must be reference or metadata!");
697 TSystemDirectory* baseDir = new TSystemDirectory("/", dir);
701 TList* dirList = baseDir->GetListOfFiles();
704 if (!dirList) return kTRUE;
706 if (dirList->GetEntries() < 3)
714 Log("SHUTTLE", "CopyFilesToGrid - Connection to Grid failed: Cannot continue!");
719 Int_t nDirs = 0, nTransfer = 0;
720 TIter dirIter(dirList);
721 TSystemFile* entry = 0;
723 Bool_t success = kTRUE;
724 Bool_t first = kTRUE;
726 while ((entry = dynamic_cast<TSystemFile*> (dirIter.Next())))
728 if (entry->IsDirectory())
731 TString fileName(entry->GetName());
732 if (!fileName.BeginsWith(begin))
740 // check that folder exists, otherwise create it
741 TGridResult* result = gGrid->Ls(alienDir.Data(), "a");
749 if (!result->GetFileName(1)) // TODO: It looks like element 0 is always 0!!
751 // TODO It does not work currently! Bug in TAliEn::Mkdir
752 // TODO Manually fixed in local root v5-16-00
753 if (!gGrid->Mkdir(alienDir.Data(),"-p",0))
755 Log("SHUTTLE", Form("CopyFilesToGrid - Cannot create directory %s",
760 Log("SHUTTLE",Form("CopyFilesToGrid - Folder %s created", alienDir.Data()));
764 Log("SHUTTLE",Form("CopyFilesToGrid - Folder %s found", alienDir.Data()));
768 TString fullLocalPath;
769 fullLocalPath.Form("%s/%s", dir.Data(), fileName.Data());
771 TString fullGridPath;
772 fullGridPath.Form("alien://%s/%s", alienDir.Data(), fileName.Data());
774 Bool_t result = TFile::Cp(fullLocalPath, fullGridPath);
778 Log("SHUTTLE", Form("CopyFilesToGrid - Copying local file %s to %s succeeded!",
779 fullLocalPath.Data(), fullGridPath.Data()));
780 RemoveFile(fullLocalPath);
785 Log("SHUTTLE", Form("CopyFilesToGrid - Copying local file %s to %s FAILED!",
786 fullLocalPath.Data(), fullGridPath.Data()));
791 Log("SHUTTLE", Form("CopyFilesToGrid - %d (over %d) files in folder %s copied to Grid.",
792 nTransfer, nDirs, dir.Data()));
799 //______________________________________________________________________________________________
800 const char* AliShuttle::GetRefFilePrefix(const char* base, const char* detector)
803 // Get folder name of reference files
806 TString offDetStr(GetOfflineDetName(detector));
808 if (offDetStr == "ITS" || offDetStr == "MUON" || offDetStr == "PHOS")
810 dir.Form("%s/%s/%s", base, offDetStr.Data(), detector);
812 dir.Form("%s/%s", base, offDetStr.Data());
820 //______________________________________________________________________________________________
821 void AliShuttle::CleanLocalStorage(const TString& uri)
824 // Called in case the preprocessor is declared failed. Remove remaining objects from the local storages.
827 const char* type = 0;
828 if(uri == fgkLocalCDB) {
830 } else if(uri == fgkLocalRefStorage) {
833 AliError(Form("Invalid storage URI: %s", uri.Data()));
837 AliCDBManager* man = AliCDBManager::Instance();
839 // open local storage
840 AliCDBStorage *localSto = man->GetStorage(uri);
843 Form("CleanLocalStorage - cannot activate local %s storage", type));
847 TString filename(Form("%s/%s/*/Run*_v%d_s*.root",
848 localSto->GetBaseFolder().Data(), GetOfflineDetName(fCurrentDetector.Data()), GetCurrentRun()));
850 AliDebug(2, Form("filename = %s", filename.Data()));
852 Log("SHUTTLE", Form("Removing remaining local files for run %d and detector %s ...",
853 GetCurrentRun(), fCurrentDetector.Data()));
855 RemoveFile(filename.Data());
859 //______________________________________________________________________________________________
860 void AliShuttle::RemoveFile(const char* filename)
863 // removes local file
866 TString command(Form("rm -f %s", filename));
868 Int_t result = gSystem->Exec(command.Data());
871 Log("SHUTTLE", Form("RemoveFile - %s: Cannot remove file %s!",
872 fCurrentDetector.Data(), filename));
876 //______________________________________________________________________________________________
877 AliShuttleStatus* AliShuttle::ReadShuttleStatus()
880 // Reads the AliShuttleStatus from the CDB
888 fStatusEntry = AliCDBManager::Instance()->GetStorage(GetLocalCDB())
889 ->Get(Form("/SHUTTLE/STATUS/%s", fCurrentDetector.Data()), GetCurrentRun());
891 if (!fStatusEntry) return 0;
892 fStatusEntry->SetOwner(1);
894 AliShuttleStatus* status = dynamic_cast<AliShuttleStatus*> (fStatusEntry->GetObject());
896 AliError("Invalid object stored to CDB!");
903 //______________________________________________________________________________________________
904 Bool_t AliShuttle::WriteShuttleStatus(AliShuttleStatus* status)
907 // writes the status for one subdetector
915 Int_t run = GetCurrentRun();
917 AliCDBId id(AliCDBPath("SHUTTLE", "STATUS", fCurrentDetector), run, run);
919 fStatusEntry = new AliCDBEntry(status, id, new AliCDBMetaData);
920 fStatusEntry->SetOwner(1);
922 UInt_t result = AliCDBManager::Instance()->GetStorage(fgkLocalCDB)->Put(fStatusEntry);
925 Log("SHUTTLE", Form("WriteShuttleStatus - Failed for %s, run %d",
926 fCurrentDetector.Data(), run));
935 //______________________________________________________________________________________________
936 void AliShuttle::UpdateShuttleStatus(AliShuttleStatus::Status newStatus, Bool_t increaseCount)
939 // changes the AliShuttleStatus for the given detector and run to the given status
943 AliError("UNEXPECTED: fStatusEntry empty");
947 AliShuttleStatus* status = dynamic_cast<AliShuttleStatus*> (fStatusEntry->GetObject());
950 Log("SHUTTLE", "UpdateShuttleStatus - UNEXPECTED: status could not be read from current CDB entry");
954 TString actionStr = Form("UpdateShuttleStatus - %s: Changing state from %s to %s",
955 fCurrentDetector.Data(),
956 status->GetStatusName(),
957 status->GetStatusName(newStatus));
958 Log("SHUTTLE", actionStr);
959 SetLastAction(actionStr);
961 status->SetStatus(newStatus);
962 if (increaseCount) status->IncreaseCount();
964 AliCDBManager::Instance()->GetStorage(fgkLocalCDB)->Put(fStatusEntry);
969 //______________________________________________________________________________________________
970 void AliShuttle::SendMLInfo()
973 // sends ML information about the current status of the current detector being processed
976 AliShuttleStatus* status = dynamic_cast<AliShuttleStatus*> (fStatusEntry->GetObject());
979 Log("SHUTTLE", "SendMLInfo - UNEXPECTED: status could not be read from current CDB entry");
983 TMonaLisaText mlStatus(Form("%s_status", fCurrentDetector.Data()), status->GetStatusName());
984 TMonaLisaValue mlRetryCount(Form("%s_count", fCurrentDetector.Data()), status->GetCount());
987 mlList.Add(&mlStatus);
988 mlList.Add(&mlRetryCount);
991 mlID.Form("%d", GetCurrentRun());
992 fMonaLisa->SendParameters(&mlList, mlID);
995 //______________________________________________________________________________________________
996 Bool_t AliShuttle::ContinueProcessing()
998 // this function reads the AliShuttleStatus information from CDB and
999 // checks if the processing should be continued
1000 // if yes it returns kTRUE and updates the AliShuttleStatus with nextStatus
1002 if (!fConfig->HostProcessDetector(fCurrentDetector)) return kFALSE;
1004 AliPreprocessor* aPreprocessor =
1005 dynamic_cast<AliPreprocessor*> (fPreprocessorMap.GetValue(fCurrentDetector));
1008 Log("SHUTTLE", Form("ContinueProcessing - %s: no preprocessor registered", fCurrentDetector.Data()));
1012 AliShuttleLogbookEntry::Status entryStatus =
1013 fLogbookEntry->GetDetectorStatus(fCurrentDetector);
1015 if(entryStatus != AliShuttleLogbookEntry::kUnprocessed) {
1016 Log("SHUTTLE", Form("ContinueProcessing - %s is %s",
1017 fCurrentDetector.Data(),
1018 fLogbookEntry->GetDetectorStatusName(entryStatus)));
1022 // if we get here, according to Shuttle logbook subdetector is in UNPROCESSED state
1024 // check if current run is first unprocessed run for current detector
1025 if (fConfig->StrictRunOrder(fCurrentDetector) &&
1026 !fFirstUnprocessed[GetDetPos(fCurrentDetector)])
1028 if (fTestMode == kNone)
1030 Log("SHUTTLE", Form("ContinueProcessing - %s requires strict run ordering"
1031 " but this is not the first unprocessed run!"));
1036 Log("SHUTTLE", Form("ContinueProcessing - In TESTMODE - "
1037 "Although %s requires strict run ordering "
1038 "and this is not the first unprocessed run, "
1039 "the SHUTTLE continues"));
1043 AliShuttleStatus* status = ReadShuttleStatus();
1046 Log("SHUTTLE", Form("ContinueProcessing - %s: Processing first time",
1047 fCurrentDetector.Data()));
1048 status = new AliShuttleStatus(AliShuttleStatus::kStarted);
1049 return WriteShuttleStatus(status);
1052 // The following two cases shouldn't happen if Shuttle Logbook was correctly updated.
1053 // If it happens it may mean Logbook updating failed... let's do it now!
1054 if (status->GetStatus() == AliShuttleStatus::kDone ||
1055 status->GetStatus() == AliShuttleStatus::kFailed){
1056 Log("SHUTTLE", Form("ContinueProcessing - %s is already %s. Updating Shuttle Logbook",
1057 fCurrentDetector.Data(),
1058 status->GetStatusName(status->GetStatus())));
1059 UpdateShuttleLogbook(fCurrentDetector.Data(),
1060 status->GetStatusName(status->GetStatus()));
1064 if (status->GetStatus() == AliShuttleStatus::kStoreStarted || status->GetStatus() == AliShuttleStatus::kStoreError) {
1066 Form("ContinueProcessing - %s: Grid storage of one or more "
1067 "objects failed. Trying again now",
1068 fCurrentDetector.Data()));
1069 UpdateShuttleStatus(AliShuttleStatus::kStoreStarted);
1071 Log("SHUTTLE", Form("ContinueProcessing - %s: all objects "
1072 "successfully stored into main storage",
1073 fCurrentDetector.Data()));
1074 UpdateShuttleStatus(AliShuttleStatus::kDone);
1075 UpdateShuttleLogbook(fCurrentDetector, "DONE");
1078 Form("ContinueProcessing - %s: Grid storage failed again",
1079 fCurrentDetector.Data()));
1080 UpdateShuttleStatus(AliShuttleStatus::kStoreError);
1085 // if we get here, there is a restart
1086 Bool_t cont = kFALSE;
1089 if (status->GetCount() >= fConfig->GetMaxRetries()) {
1090 Log("SHUTTLE", Form("ContinueProcessing - %s failed %d times in status %s - "
1091 "Updating Shuttle Logbook", fCurrentDetector.Data(),
1092 status->GetCount(), status->GetStatusName()));
1093 UpdateShuttleLogbook(fCurrentDetector.Data(), "FAILED");
1094 UpdateShuttleStatus(AliShuttleStatus::kFailed);
1096 // there may still be objects in local OCDB and reference storage
1097 // and FXS databases may be not updated: do it now!
1099 // TODO Currently disabled, we want to keep files in case of failure!
1100 // CleanLocalStorage(fgkLocalCDB);
1101 // CleanLocalStorage(fgkLocalRefStorage);
1102 // UpdateTableFailCase();
1104 // Send mail to detector expert!
1105 Log("SHUTTLE", Form("ContinueProcessing - Sending mail to %s expert...",
1106 fCurrentDetector.Data()));
1108 Log("SHUTTLE", Form("ContinueProcessing - Could not send mail to %s expert",
1109 fCurrentDetector.Data()));
1112 Log("SHUTTLE", Form("ContinueProcessing - %s: restarting. "
1113 "Aborted before with %s. Retry number %d.", fCurrentDetector.Data(),
1114 status->GetStatusName(), status->GetCount()));
1115 Bool_t increaseCount = kTRUE;
1116 if (status->GetStatus() == AliShuttleStatus::kDCSError ||
1117 status->GetStatus() == AliShuttleStatus::kDCSStarted)
1118 increaseCount = kFALSE;
1120 UpdateShuttleStatus(AliShuttleStatus::kStarted, increaseCount);
1127 //______________________________________________________________________________________________
1128 Bool_t AliShuttle::Process(AliShuttleLogbookEntry* entry)
1131 // Makes data retrieval for all detectors in the configuration.
1132 // entry: Shuttle logbook entry, contains run paramenters and status of detectors
1133 // (Unprocessed, Inactive, Failed or Done).
1134 // Returns kFALSE in case of error occured and kTRUE otherwise
1137 if (!entry) return kFALSE;
1139 fLogbookEntry = entry;
1141 Log("SHUTTLE", Form("\t\t\t^*^*^*^*^*^*^*^*^*^*^*^* run %d: START ^*^*^*^*^*^*^*^*^*^*^*^*",
1144 // Send the information to ML
1145 TMonaLisaText mlStatus("SHUTTLE_status", "Processing");
1146 TMonaLisaText mlRunType("SHUTTLE_runtype", Form("%s (%s)", entry->GetRunType(), entry->GetRunParameter("log")));
1149 mlList.Add(&mlStatus);
1150 mlList.Add(&mlRunType);
1153 mlID.Form("%d", GetCurrentRun());
1154 fMonaLisa->SendParameters(&mlList, mlID);
1156 if (fLogbookEntry->IsDone())
1158 Log("SHUTTLE","Process - Shuttle is already DONE. Updating logbook");
1159 UpdateShuttleLogbook("shuttle_done");
1164 // read test mode if flag is set
1168 TString logEntry(entry->GetRunParameter("log"));
1169 //printf("log entry = %s\n", logEntry.Data());
1170 TString searchStr("Testmode: ");
1171 Int_t pos = logEntry.Index(searchStr.Data());
1172 //printf("%d\n", pos);
1175 TSubString subStr = logEntry(pos + searchStr.Length(), logEntry.Length());
1176 //printf("%s\n", subStr.String().Data());
1177 TString newStr(subStr.Data());
1178 TObjArray* token = newStr.Tokenize(' ');
1182 TObjString* tmpStr = dynamic_cast<TObjString*> (token->First());
1185 Int_t testMode = tmpStr->String().Atoi();
1188 Log("SHUTTLE", Form("Process - Enabling test mode %d", testMode));
1189 SetTestMode((TestMode) testMode);
1197 fLogbookEntry->Print("all");
1200 Bool_t hasError = kFALSE;
1202 // Set the CDB and Reference folders according to the year and LHC period
1203 TString lhcPeriod(GetLHCPeriod());
1204 if (lhcPeriod.Length() == 0)
1206 Log("SHUTTLE","Process - LHCPeriod not found in logbook!");
1210 if (fgkMainCDB.Length() == 0)
1211 fgkMainCDB = Form("alien://folder=/alice/data/%d/%s/OCDB?user=alidaq?cacheFold=/tmp/OCDBCache",
1212 GetCurrentYear(), lhcPeriod.Data());
1214 if (fgkMainRefStorage.Length() == 0)
1215 fgkMainRefStorage = Form("alien://folder=/alice/data/%d/%s/Reference?user=alidaq?cacheFold=/tmp/OCDBCache",
1216 GetCurrentYear(), lhcPeriod.Data());
1218 // Loop on detectors in the configuration
1219 TIter iter(fConfig->GetDetectors());
1220 TObjString* aDetector = 0;
1222 Bool_t first = kTRUE;
1224 while ((aDetector = (TObjString*) iter.Next()))
1226 fCurrentDetector = aDetector->String();
1228 if (ContinueProcessing() == kFALSE) continue;
1232 // only read QueryCDB when needed and only once
1233 AliCDBStorage *mainCDBSto = AliCDBManager::Instance()->GetStorage(fgkMainCDB);
1234 if(mainCDBSto) mainCDBSto->QueryCDB(GetCurrentRun());
1235 AliCDBStorage *mainRefSto = AliCDBManager::Instance()->GetStorage(fgkMainRefStorage);
1236 if(mainRefSto) mainRefSto->QueryCDB(GetCurrentRun());
1240 Log("SHUTTLE", Form("\t\t\t****** run %d - %s: START ******",
1241 GetCurrentRun(), aDetector->GetName()));
1243 for(Int_t iSys=0;iSys<3;iSys++) fFXSCalled[iSys]=kFALSE;
1245 Log(fCurrentDetector.Data(), "Process - Starting processing");
1251 Log("SHUTTLE", "Process - ERROR: Forking failed");
1256 Log("SHUTTLE", Form("Process - In parent process of %d - %s: Starting monitoring",
1257 GetCurrentRun(), aDetector->GetName()));
1259 Long_t begin = time(0);
1261 int status; // to be used with waitpid, on purpose an int (not Int_t)!
1262 while (waitpid(pid, &status, WNOHANG) == 0)
1264 Long_t expiredTime = time(0) - begin;
1266 if (expiredTime > fConfig->GetPPTimeOut())
1269 tmp.Form("Process - Process of %s time out. "
1270 "Run time: %d seconds. Killing...",
1271 fCurrentDetector.Data(), expiredTime);
1272 Log("SHUTTLE", tmp);
1273 Log(fCurrentDetector, tmp);
1277 UpdateShuttleStatus(AliShuttleStatus::kPPTimeOut);
1280 gSystem->Sleep(1000);
1284 gSystem->Sleep(1000);
1287 checkStr.Form("ps -o vsize --pid %d | tail -n 1", pid);
1288 FILE* pipe = gSystem->OpenPipe(checkStr, "r");
1291 Log("SHUTTLE", Form("Process - Error: "
1292 "Could not open pipe to %s", checkStr.Data()));
1297 if (!fgets(buffer, 100, pipe))
1299 Log("SHUTTLE", "Process - Error: ps did not return anything");
1300 gSystem->ClosePipe(pipe);
1303 gSystem->ClosePipe(pipe);
1305 //Log("SHUTTLE", Form("ps returned %s", buffer));
1308 if ((sscanf(buffer, "%d\n", &mem) != 1) || !mem)
1310 Log("SHUTTLE", "Process - Error: Could not parse output of ps");
1314 if (expiredTime % 60 == 0)
1316 Log("SHUTTLE", Form("Process - %s: Checking process. "
1317 "Run time: %d seconds - Memory consumption: %d KB",
1318 fCurrentDetector.Data(), expiredTime, mem));
1322 if (mem > fConfig->GetPPMaxMem())
1325 tmp.Form("Process - Process exceeds maximum allowed memory "
1326 "(%d KB > %d KB). Killing...",
1327 mem, fConfig->GetPPMaxMem());
1328 Log("SHUTTLE", tmp);
1329 Log(fCurrentDetector, tmp);
1333 UpdateShuttleStatus(AliShuttleStatus::kPPOutOfMemory);
1336 gSystem->Sleep(1000);
1341 Log("SHUTTLE", Form("Process - In parent process of %d - %s: Client has terminated.",
1342 GetCurrentRun(), aDetector->GetName()));
1344 if (WIFEXITED(status))
1346 Int_t returnCode = WEXITSTATUS(status);
1348 Log("SHUTTLE", Form("Process - %s: the return code is %d", fCurrentDetector.Data(),
1351 if (returnCode == 0) hasError = kTRUE;
1357 Log("SHUTTLE", Form("Process - In client process of %d - %s", GetCurrentRun(),
1358 aDetector->GetName()));
1360 Log("SHUTTLE", Form("Process - Redirecting output to %s log",fCurrentDetector.Data()));
1362 if ((freopen(GetLogFileName(fCurrentDetector), "a", stdout)) == 0)
1364 Log("SHUTTLE", "Process - Could not freopen stdout");
1368 fOutputRedirected = kTRUE;
1369 if ((dup2(fileno(stdout), fileno(stderr))) < 0)
1370 Log("SHUTTLE", "Process - Could not redirect stderr");
1374 TString wd = gSystem->WorkingDirectory();
1375 TString tmpDir = Form("%s/%s_%d_process", GetShuttleTempDir(),
1376 fCurrentDetector.Data(), GetCurrentRun());
1378 Int_t result = gSystem->GetPathInfo(tmpDir.Data(), 0, (Long64_t*) 0, 0, 0);
1379 if (!result) // temp dir already exists!
1381 Log(fCurrentDetector.Data(),
1382 Form("Process - %s dir already exists! Removing...", tmpDir.Data()));
1383 gSystem->Exec(Form("rm -rf %s",tmpDir.Data()));
1386 if (gSystem->mkdir(tmpDir.Data(), 1))
1388 Log(fCurrentDetector.Data(), "Process - could not make temp directory!!");
1392 if (!gSystem->ChangeDirectory(tmpDir.Data()))
1394 Log(fCurrentDetector.Data(), "Process - could not change directory!!");
1398 Bool_t success = ProcessCurrentDetector();
1400 gSystem->ChangeDirectory(wd.Data());
1402 if (success) // Preprocessor finished successfully!
1404 // remove temporary folder or DCS map
1405 if (!fConfig->KeepTempFolder())
1407 gSystem->Exec(Form("rm -rf %s",tmpDir.Data()));
1408 } else if (!fConfig->KeepDCSMap())
1410 gSystem->Exec(Form("rm -f %s/DCSMap.root",tmpDir.Data()));
1413 // Update time_processed field in FXS DB
1414 if (UpdateTable() == kFALSE)
1415 Log("SHUTTLE", Form("Process - %s: Could not update FXS databases!",
1416 fCurrentDetector.Data()));
1418 // Transfer the data from local storage to main storage (Grid)
1419 UpdateShuttleStatus(AliShuttleStatus::kStoreStarted);
1420 if (StoreOCDB() == kFALSE)
1423 Form("\t\t\t****** run %d - %s: STORAGE ERROR ******",
1424 GetCurrentRun(), aDetector->GetName()));
1425 UpdateShuttleStatus(AliShuttleStatus::kStoreError);
1429 Form("\t\t\t****** run %d - %s: DONE ******",
1430 GetCurrentRun(), aDetector->GetName()));
1431 UpdateShuttleStatus(AliShuttleStatus::kDone);
1432 UpdateShuttleLogbook(fCurrentDetector, "DONE");
1437 Form("\t\t\t****** run %d - %s: PP ERROR ******",
1438 GetCurrentRun(), aDetector->GetName()));
1441 for (UInt_t iSys=0; iSys<3; iSys++)
1443 if (fFXSCalled[iSys]) fFXSlist[iSys].Clear();
1446 Log("SHUTTLE", Form("Process - Client process of %d - %s is exiting now with %d.",
1447 GetCurrentRun(), aDetector->GetName(), success));
1449 // the client exits here
1450 gSystem->Exit(success);
1452 AliError("We should never get here!!!");
1456 Log("SHUTTLE", Form("\t\t\t^*^*^*^*^*^*^*^*^*^*^*^* run %d: FINISH ^*^*^*^*^*^*^*^*^*^*^*^*",
1459 //check if shuttle is done for this run, if so update logbook
1460 TObjArray checkEntryArray;
1461 checkEntryArray.SetOwner(1);
1462 TString whereClause = Form("where run=%d", GetCurrentRun());
1463 if (!QueryShuttleLogbook(whereClause.Data(), checkEntryArray) ||
1464 checkEntryArray.GetEntries() == 0) {
1465 Log("SHUTTLE", Form("Process - Warning: Cannot check status of run %d on Shuttle logbook!",
1467 return hasError == kFALSE;
1470 AliShuttleLogbookEntry* checkEntry = dynamic_cast<AliShuttleLogbookEntry*>
1471 (checkEntryArray.At(0));
1475 if (checkEntry->IsDone())
1477 Log("SHUTTLE","Process - Shuttle is DONE. Updating logbook");
1478 UpdateShuttleLogbook("shuttle_done");
1482 for (UInt_t iDet=0; iDet<NDetectors(); iDet++)
1484 if (checkEntry->GetDetectorStatus(iDet) == AliShuttleLogbookEntry::kUnprocessed)
1486 AliDebug(2, Form("Run %d: setting %s as \"not first time unprocessed\"",
1487 checkEntry->GetRun(), GetDetName(iDet)));
1488 fFirstUnprocessed[iDet] = kFALSE;
1496 return hasError == kFALSE;
1499 //______________________________________________________________________________________________
1500 Bool_t AliShuttle::ProcessCurrentDetector()
1503 // Makes data retrieval just for a specific detector (fCurrentDetector).
1504 // Threre should be a configuration for this detector.
1506 Log("SHUTTLE", Form("ProcessCurrentDetector - Retrieving values for %s, run %d",
1507 fCurrentDetector.Data(), GetCurrentRun()));
1509 TString wd = gSystem->WorkingDirectory();
1511 if (!CleanReferenceStorage(fCurrentDetector.Data()))
1514 gSystem->ChangeDirectory(wd.Data());
1516 TMap* dcsMap = new TMap();
1518 // call preprocessor
1519 AliPreprocessor* aPreprocessor =
1520 dynamic_cast<AliPreprocessor*> (fPreprocessorMap.GetValue(fCurrentDetector));
1522 aPreprocessor->Initialize(GetCurrentRun(), GetCurrentStartTime(), GetCurrentEndTime());
1524 Bool_t processDCS = aPreprocessor->ProcessDCS();
1528 Log(fCurrentDetector, "ProcessCurrentDetector -"
1529 " The preprocessor requested to skip the retrieval of DCS values");
1531 else if (fTestMode & kSkipDCS)
1533 Log(fCurrentDetector, "ProcessCurrentDetector - In TESTMODE: Skipping DCS processing");
1535 else if (fTestMode & kErrorDCS)
1537 Log(fCurrentDetector, "ProcessCurrentDetector - In TESTMODE: Simulating DCS error");
1538 UpdateShuttleStatus(AliShuttleStatus::kDCSStarted);
1539 UpdateShuttleStatus(AliShuttleStatus::kDCSError);
1544 UpdateShuttleStatus(AliShuttleStatus::kDCSStarted);
1546 // Query DCS archive
1547 Int_t nServers = fConfig->GetNServers(fCurrentDetector);
1549 for (int iServ=0; iServ<nServers; iServ++)
1552 TString host(fConfig->GetDCSHost(fCurrentDetector, iServ));
1553 Int_t port = fConfig->GetDCSPort(fCurrentDetector, iServ);
1554 Int_t multiSplit = fConfig->GetMultiSplit(fCurrentDetector, iServ);
1556 Log(fCurrentDetector, Form("ProcessCurrentDetector -"
1557 " Querying DCS Amanda server %s:%d (%d of %d)",
1558 host.Data(), port, iServ+1, nServers));
1563 if (fConfig->GetDCSAliases(fCurrentDetector, iServ)->GetEntries() > 0)
1565 aliasMap = GetValueSet(host, port,
1566 fConfig->GetDCSAliases(fCurrentDetector, iServ),
1567 kAlias, multiSplit);
1570 Log(fCurrentDetector,
1571 Form("ProcessCurrentDetector -"
1572 " Error retrieving DCS aliases from server %s."
1573 " Sending mail to DCS experts!", host.Data()));
1574 UpdateShuttleStatus(AliShuttleStatus::kDCSError);
1576 if (!SendMailToDCS())
1577 Log("SHUTTLE", Form("ProcessCurrentDetector - "
1578 "Could not send mail to DCS experts!"));
1585 if (fConfig->GetDCSDataPoints(fCurrentDetector, iServ)->GetEntries() > 0)
1587 dpMap = GetValueSet(host, port,
1588 fConfig->GetDCSDataPoints(fCurrentDetector, iServ),
1592 Log(fCurrentDetector,
1593 Form("ProcessCurrentDetector -"
1594 " Error retrieving DCS data points from server %s."
1595 " Sending mail to DCS experts!", host.Data()));
1596 UpdateShuttleStatus(AliShuttleStatus::kDCSError);
1598 if (!SendMailToDCS())
1599 Log("SHUTTLE", Form("ProcessCurrentDetector - "
1600 "Could not send mail to DCS experts!"));
1602 if (aliasMap) delete aliasMap;
1608 // merge aliasMap and dpMap into dcsMap
1610 TIter iter(aliasMap);
1611 TObjString* key = 0;
1612 while ((key = (TObjString*) iter.Next()))
1613 dcsMap->Add(key, aliasMap->GetValue(key->String()));
1615 aliasMap->SetOwner(kFALSE);
1621 TObjString* key = 0;
1622 while ((key = (TObjString*) iter.Next()))
1623 dcsMap->Add(key, dpMap->GetValue(key->String()));
1625 dpMap->SetOwner(kFALSE);
1631 // save map into file, to help debugging in case of preprocessor error
1632 TFile* f = TFile::Open("DCSMap.root","recreate");
1634 dcsMap->Write("DCSMap", TObject::kSingleKey);
1638 // DCS Archive DB processing successful. Call Preprocessor!
1639 UpdateShuttleStatus(AliShuttleStatus::kPPStarted);
1641 UInt_t returnValue = aPreprocessor->Process(dcsMap);
1643 if (returnValue > 0) // Preprocessor error!
1645 Log(fCurrentDetector, Form("ProcessCurrentDetector - "
1646 "Preprocessor failed. Process returned %d.", returnValue));
1647 UpdateShuttleStatus(AliShuttleStatus::kPPError);
1648 dcsMap->DeleteAll();
1654 UpdateShuttleStatus(AliShuttleStatus::kPPDone);
1655 Log(fCurrentDetector, Form("ProcessCurrentDetector - %s preprocessor returned success",
1656 fCurrentDetector.Data()));
1658 dcsMap->DeleteAll();
1664 //______________________________________________________________________________________________
1665 void AliShuttle::CountOpenRuns()
1667 // Query DAQ's Shuttle logbook and sends the number of open runs to ML
1669 // check connection, in case connect
1674 sqlQuery = Form("select count(*) from %s where shuttle_done=0", fConfig->GetShuttlelbTable());
1676 TSQLResult* aResult = fServer[3]->Query(sqlQuery);
1678 AliError(Form("Can't execute query <%s>!", sqlQuery.Data()));
1682 AliDebug(2,Form("Query = %s", sqlQuery.Data()));
1684 if (aResult->GetRowCount() == 0) {
1685 AliError(Form("No result for query %s received", sqlQuery.Data()));
1689 if (aResult->GetFieldCount() != 1) {
1690 AliError(Form("Invalid field count for query %s received", sqlQuery.Data()));
1694 TSQLRow* aRow = aResult->Next();
1696 AliError(Form("Could not receive result of query %s", sqlQuery.Data()));
1700 TString result(aRow->GetField(0), aRow->GetFieldLength(0));
1701 Int_t count = result.Atoi();
1703 Log("SHUTTLE", Form("%d unprocessed runs", count));
1708 TMonaLisaValue mlStatus("SHUTTLE_openruns", count);
1711 mlList.Add(&mlStatus);
1713 fMonaLisa->SendParameters(&mlList, "__PROCESSINGINFO__");
1716 //______________________________________________________________________________________________
1717 Bool_t AliShuttle::QueryShuttleLogbook(const char* whereClause,
1720 // Query DAQ's Shuttle logbook and fills detector status object.
1721 // Call QueryRunParameters to query DAQ logbook for run parameters.
1724 entries.SetOwner(1);
1726 // check connection, in case connect
1727 if (!Connect(3)) return kFALSE;
1730 sqlQuery = Form("select * from %s %s order by run", fConfig->GetShuttlelbTable(), whereClause);
1732 TSQLResult* aResult = fServer[3]->Query(sqlQuery);
1734 AliError(Form("Can't execute query <%s>!", sqlQuery.Data()));
1738 AliDebug(2,Form("Query = %s", sqlQuery.Data()));
1740 if(aResult->GetRowCount() == 0) {
1741 Log("SHUTTLE", "No entries in Shuttle Logbook match request");
1746 // TODO Check field count!
1747 const UInt_t nCols = 23;
1748 if (aResult->GetFieldCount() != (Int_t) nCols) {
1749 Log("SHUTTLE", "Invalid SQL result field number!");
1755 while ((aRow = aResult->Next())) {
1756 TString runString(aRow->GetField(0), aRow->GetFieldLength(0));
1757 Int_t run = runString.Atoi();
1759 AliShuttleLogbookEntry *entry = QueryRunParameters(run);
1763 // loop on detectors
1764 for(UInt_t ii = 0; ii < nCols; ii++)
1765 entry->SetDetectorStatus(aResult->GetFieldName(ii), aRow->GetField(ii));
1767 entries.AddLast(entry);
1775 //______________________________________________________________________________________________
1776 AliShuttleLogbookEntry* AliShuttle::QueryRunParameters(Int_t run)
1779 // Retrieve run parameters written in the DAQ logbook and sets them into AliShuttleLogbookEntry object
1782 // check connection, in case connect
1787 sqlQuery.Form("select * from %s where run=%d", fConfig->GetDAQlbTable(), run);
1789 TSQLResult* aResult = fServer[3]->Query(sqlQuery);
1791 Log("SHUTTLE", Form("Can't execute query <%s>!", sqlQuery.Data()));
1795 if (aResult->GetRowCount() == 0) {
1796 Log("SHUTTLE", Form("QueryRunParameters - No entry in DAQ Logbook for run %d. Skipping", run));
1801 if (aResult->GetRowCount() > 1) {
1802 Log("SHUTTLE", Form("QueryRunParameters - UNEXPECTED: "
1803 "more than one entry in DAQ Logbook for run %d!", run));
1808 TSQLRow* aRow = aResult->Next();
1811 Log("SHUTTLE", Form("QueryRunParameters - Could not retrieve row for run %d. Skipping", run));
1816 AliShuttleLogbookEntry* entry = new AliShuttleLogbookEntry(run);
1818 for (Int_t ii = 0; ii < aResult->GetFieldCount(); ii++)
1819 entry->SetRunParameter(aResult->GetFieldName(ii), aRow->GetField(ii));
1821 UInt_t startTime = entry->GetStartTime();
1822 UInt_t endTime = entry->GetEndTime();
1824 // if (!startTime || !endTime || startTime > endTime)
1827 // Form("QueryRunParameters - Invalid parameters for Run %d: startTime = %d, endTime = %d. Skipping!",
1828 // run, startTime, endTime));
1830 // Log("SHUTTLE", Form("Marking SHUTTLE done for run %d", run));
1831 // fLogbookEntry = entry;
1832 // if (!UpdateShuttleLogbook("shuttle_done"))
1834 // AliError(Form("Could not update logbook for run %d !", run));
1836 // fLogbookEntry = 0;
1847 Form("QueryRunParameters - Invalid parameters for Run %d: "
1848 "startTime = %d, endTime = %d. Skipping!",
1849 run, startTime, endTime));
1851 Log("SHUTTLE", Form("Marking SHUTTLE done for run %d", run));
1852 fLogbookEntry = entry;
1853 if (!UpdateShuttleLogbook("shuttle_ignored"))
1855 AliError(Form("Could not update logbook for run %d !", run));
1865 if (startTime && !endTime)
1867 // TODO Here we don't mark SHUTTLE done, because this may mean
1868 //the run is still ongoing!!
1870 Form("QueryRunParameters - Invalid parameters for Run %d: "
1871 "startTime = %d, endTime = %d. Skipping (Shuttle won't be marked as DONE)!",
1872 run, startTime, endTime));
1874 //Log("SHUTTLE", Form("Marking SHUTTLE done for run %d", run));
1875 //fLogbookEntry = entry;
1876 //if (!UpdateShuttleLogbook("shuttle_done"))
1878 // AliError(Form("Could not update logbook for run %d !", run));
1880 //fLogbookEntry = 0;
1888 if (startTime && endTime && (startTime > endTime))
1891 Form("QueryRunParameters - Invalid parameters for Run %d: "
1892 "startTime = %d, endTime = %d. Skipping!",
1893 run, startTime, endTime));
1895 Log("SHUTTLE", Form("Marking SHUTTLE done for run %d", run));
1896 fLogbookEntry = entry;
1897 if (!UpdateShuttleLogbook("shuttle_ignored"))
1899 AliError(Form("Could not update logbook for run %d !", run));
1909 TString totEventsStr = entry->GetRunParameter("totalEvents");
1910 Int_t totEvents = totEventsStr.Atoi();
1914 Form("QueryRunParameters - Run %d has 0 events - Skipping!", run));
1916 Log("SHUTTLE", Form("Marking SHUTTLE done for run %d", run));
1917 fLogbookEntry = entry;
1918 if (!UpdateShuttleLogbook("shuttle_ignored"))
1920 AliError(Form("Could not update logbook for run %d !", run));
1936 //______________________________________________________________________________________________
1937 TMap* AliShuttle::GetValueSet(const char* host, Int_t port, const TSeqCollection* entries,
1938 DCSType type, Int_t multiSplit)
1940 // Retrieve all "entry" data points from the DCS server
1941 // host, port: TSocket connection parameters
1942 // entries: list of name of the alias or data point
1943 // type: kAlias or kDP
1944 // returns TMap of values, 0 when failure
1946 AliDCSClient client(host, port, fTimeout, fRetries, multiSplit);
1951 result = client.GetAliasValues(entries, GetCurrentStartTime(),
1952 GetCurrentEndTime());
1954 else if (type == kDP)
1956 result = client.GetDPValues(entries, GetCurrentStartTime(),
1957 GetCurrentEndTime());
1962 Log(fCurrentDetector.Data(), Form("GetValueSet - Can't get entries! Reason: %s",
1963 client.GetErrorString(client.GetResultErrorCode())));
1964 if (client.GetResultErrorCode() == AliDCSClient::fgkServerError)
1965 Log(fCurrentDetector.Data(), Form("GetValueSet - Server error code: %s",
1966 client.GetServerError().Data()));
1974 //______________________________________________________________________________________________
1975 const char* AliShuttle::GetFile(Int_t system, const char* detector,
1976 const char* id, const char* source)
1978 // Get calibration file from file exchange servers
1979 // First queris the FXS database for the file name, using the run, detector, id and source info
1980 // then calls RetrieveFile(filename) for actual copy to local disk
1981 // run: current run being processed (given by Logbook entry fLogbookEntry)
1982 // detector: the Preprocessor name
1983 // id: provided as a parameter by the Preprocessor
1984 // source: provided by the Preprocessor through GetFileSources function
1986 // check if test mode should simulate a FXS error
1987 if (fTestMode & kErrorFXSFiles)
1989 Log(detector, Form("GetFile - In TESTMODE - Simulating error while connecting to %s FXS", GetSystemName(system)));
1993 // check connection, in case connect
1994 if (!Connect(system))
1996 Log(detector, Form("GetFile - Couldn't connect to %s FXS database", GetSystemName(system)));
2000 // Query preparation
2001 TString sourceName(source);
2003 TString sqlQueryStart = Form("select filePath,size,fileChecksum from %s where",
2004 fConfig->GetFXSdbTable(system));
2005 TString whereClause = Form("run=%d and detector=\"%s\" and fileId=\"%s\"",
2006 GetCurrentRun(), detector, id);
2010 whereClause += Form(" and DAQsource=\"%s\"", source);
2012 else if (system == kDCS)
2016 else if (system == kHLT)
2018 whereClause += Form(" and DDLnumbers=\"%s\"", source);
2022 TString sqlQuery = Form("%s %s", sqlQueryStart.Data(), whereClause.Data());
2024 AliDebug(2, Form("SQL query: \n%s",sqlQuery.Data()));
2027 TSQLResult* aResult = 0;
2028 aResult = dynamic_cast<TSQLResult*> (fServer[system]->Query(sqlQuery));
2030 Log(detector, Form("GetFileName - Can't execute SQL query to %s database for: id = %s, source = %s",
2031 GetSystemName(system), id, sourceName.Data()));
2035 if(aResult->GetRowCount() == 0)
2038 Form("GetFileName - No entry in %s FXS db for: id = %s, source = %s",
2039 GetSystemName(system), id, sourceName.Data()));
2044 if (aResult->GetRowCount() > 1) {
2046 Form("GetFileName - More than one entry in %s FXS db for: id = %s, source = %s",
2047 GetSystemName(system), id, sourceName.Data()));
2052 if (aResult->GetFieldCount() != nFields) {
2054 Form("GetFileName - Wrong field count in %s FXS db for: id = %s, source = %s",
2055 GetSystemName(system), id, sourceName.Data()));
2060 TSQLRow* aRow = dynamic_cast<TSQLRow*> (aResult->Next());
2063 Log(detector, Form("GetFileName - Empty set result in %s FXS db from query: id = %s, source = %s",
2064 GetSystemName(system), id, sourceName.Data()));
2069 TString filePath(aRow->GetField(0), aRow->GetFieldLength(0));
2070 TString fileSize(aRow->GetField(1), aRow->GetFieldLength(1));
2071 TString fileChecksum(aRow->GetField(2), aRow->GetFieldLength(2));
2076 AliDebug(2, Form("filePath = %s; size = %s, fileChecksum = %s",
2077 filePath.Data(), fileSize.Data(), fileChecksum.Data()));
2079 // retrieved file is renamed to make it unique
2080 TString localFileName = Form("%s/%s_%d_process/%s_%s_%d_%s_%s.shuttle",
2081 GetShuttleTempDir(), detector, GetCurrentRun(),
2082 GetSystemName(system), detector, GetCurrentRun(),
2083 id, sourceName.Data());
2086 // file retrieval from FXS
2087 UInt_t nRetries = 0;
2088 UInt_t maxRetries = 3;
2089 Bool_t result = kFALSE;
2091 // copy!! if successful TSystem::Exec returns 0
2092 while(nRetries++ < maxRetries) {
2093 AliDebug(2, Form("Trying to copy file. Retry # %d", nRetries));
2094 result = RetrieveFile(system, filePath.Data(), localFileName.Data());
2097 Log(detector, Form("GetFileName - Copy of file %s from %s FXS failed",
2098 filePath.Data(), GetSystemName(system)));
2102 if (fileSize.Length()>0)
2104 // compare filesize of local file with the one stored in the FXS DB
2105 TString command=("stat --format=%s");
2106 Int_t sizeComp = gSystem->Exec(Form("%s %s |grep %s 2>&1 > /dev/null",
2107 command.Data(), localFileName.Data(),fileSize.Data()));
2111 Log(detector, Form("GetFileName - size of file %s does not match with local copy!",
2118 Log(fCurrentDetector, Form("GetFile - size of file %s not set in %s database, skipping comparison",
2119 filePath.Data(), GetSystemName(system)));
2122 if (fileChecksum.Length()>0)
2124 // compare md5sum of local file with the one stored in the FXS DB
2125 Int_t md5Comp = gSystem->Exec(Form("md5sum %s |grep %s 2>&1 > /dev/null",
2126 localFileName.Data(), fileChecksum.Data()));
2130 Log(detector, Form("GetFileName - md5sum of file %s does not match with local copy!",
2136 Log(fCurrentDetector, Form("GetFile - md5sum of file %s not set in %s database, skipping comparison",
2137 filePath.Data(), GetSystemName(system)));
2142 if(!result) return 0;
2144 fFXSCalled[system]=kTRUE;
2145 TObjString *fileParams = new TObjString(Form("%s#!?!#%s", id, sourceName.Data()));
2146 fFXSlist[system].Add(fileParams);
2148 static TString staticLocalFileName;
2149 staticLocalFileName.Form("%s", localFileName.Data());
2151 Log(fCurrentDetector, Form("GetFile - Retrieved file with id %s and "
2152 "source %s from %s to %s", id, source,
2153 GetSystemName(system), localFileName.Data()));
2155 return staticLocalFileName.Data();
2158 //______________________________________________________________________________________________
2159 Bool_t AliShuttle::RetrieveFile(UInt_t system, const char* fxsFileName, const char* localFileName)
2162 // Copies file from FXS to local Shuttle machine
2165 // check temp directory: trying to cd to temp; if it does not exist, create it
2166 AliDebug(2, Form("Copy file %s from %s FXS into %s",
2167 GetSystemName(system), fxsFileName, localFileName));
2169 TString tmpDir(localFileName);
2171 tmpDir = tmpDir(0,tmpDir.Last('/'));
2173 Int_t noDir = gSystem->GetPathInfo(tmpDir.Data(), 0, (Long64_t*) 0, 0, 0);
2174 if (noDir) // temp dir does not exists!
2176 if (gSystem->mkdir(tmpDir.Data(), 1))
2178 Log(fCurrentDetector.Data(), "RetrieveFile - could not make temp directory!!");
2183 TString baseFXSFolder;
2186 baseFXSFolder = "FES/";
2188 else if (system == kDCS)
2192 else if (system == kHLT)
2194 baseFXSFolder = "/opt/FXS/";
2198 TString command = Form("scp -oPort=%d -2 %s@%s:%s%s %s",
2199 fConfig->GetFXSPort(system),
2200 fConfig->GetFXSUser(system),
2201 fConfig->GetFXSHost(system),
2202 baseFXSFolder.Data(),
2206 AliDebug(2, Form("%s",command.Data()));
2208 Bool_t result = (gSystem->Exec(command.Data()) == 0);
2213 //______________________________________________________________________________________________
2214 TList* AliShuttle::GetFileSources(Int_t system, const char* detector, const char* id)
2217 // Get sources producing the condition file Id from file exchange servers
2218 // if id is NULL all sources are returned (distinct)
2223 Log(detector, Form("GetFileSources - Querying %s FXS for files with id %s produced by %s", GetSystemName(system), id, detector));
2225 Log(detector, Form("GetFileSources - Querying %s FXS for files produced by %s", GetSystemName(system), detector));
2228 // check if test mode should simulate a FXS error
2229 if (fTestMode & kErrorFXSSources)
2231 Log(detector, Form("GetFileSources - In TESTMODE - Simulating error while connecting to %s FXS", GetSystemName(system)));
2237 Log(detector, "GetFileSources - WARNING: DCS system has only one source of data!");
2238 TList *list = new TList();
2240 list->Add(new TObjString(" "));
2244 // check connection, in case connect
2245 if (!Connect(system))
2247 Log(detector, Form("GetFileSources - Couldn't connect to %s FXS database", GetSystemName(system)));
2251 TString sourceName = 0;
2254 sourceName = "DAQsource";
2255 } else if (system == kHLT)
2257 sourceName = "DDLnumbers";
2260 TString sqlQueryStart = Form("select distinct %s from %s where", sourceName.Data(), fConfig->GetFXSdbTable(system));
2261 TString whereClause = Form("run=%d and detector=\"%s\"",
2262 GetCurrentRun(), detector);
2264 whereClause += Form(" and fileId=\"%s\"", id);
2265 TString sqlQuery = Form("%s %s", sqlQueryStart.Data(), whereClause.Data());
2267 AliDebug(2, Form("SQL query: \n%s",sqlQuery.Data()));
2270 TSQLResult* aResult;
2271 aResult = fServer[system]->Query(sqlQuery);
2273 Log(detector, Form("GetFileSources - Can't execute SQL query to %s database for id: %s",
2274 GetSystemName(system), id));
2278 TList *list = new TList();
2281 if (aResult->GetRowCount() == 0)
2284 Form("GetFileSources - No entry in %s FXS table for id: %s", GetSystemName(system), id));
2289 Log(detector, Form("GetFileSources - Found %d sources", aResult->GetRowCount()));
2292 while ((aRow = aResult->Next()))
2295 TString source(aRow->GetField(0), aRow->GetFieldLength(0));
2296 AliDebug(2, Form("%s = %s", sourceName.Data(), source.Data()));
2297 list->Add(new TObjString(source));
2306 //______________________________________________________________________________________________
2307 TList* AliShuttle::GetFileIDs(Int_t system, const char* detector, const char* source)
2310 // Get all ids of condition files produced by a given source from file exchange servers
2313 Log(detector, Form("GetFileIDs - Retrieving ids with source %s with %s", source, GetSystemName(system)));
2315 // check if test mode should simulate a FXS error
2316 if (fTestMode & kErrorFXSSources)
2318 Log(detector, Form("GetFileIDs - In TESTMODE - Simulating error while connecting to %s FXS", GetSystemName(system)));
2322 // check connection, in case connect
2323 if (!Connect(system))
2325 Log(detector, Form("GetFileIDs - Couldn't connect to %s FXS database", GetSystemName(system)));
2329 TString sourceName = 0;
2332 sourceName = "DAQsource";
2333 } else if (system == kHLT)
2335 sourceName = "DDLnumbers";
2338 TString sqlQueryStart = Form("select fileId from %s where", fConfig->GetFXSdbTable(system));
2339 TString whereClause = Form("run=%d and detector=\"%s\"",
2340 GetCurrentRun(), detector);
2341 if (sourceName.Length() > 0 && source)
2342 whereClause += Form(" and %s=\"%s\"", sourceName.Data(), source);
2343 TString sqlQuery = Form("%s %s", sqlQueryStart.Data(), whereClause.Data());
2345 AliDebug(2, Form("SQL query: \n%s",sqlQuery.Data()));
2348 TSQLResult* aResult;
2349 aResult = fServer[system]->Query(sqlQuery);
2351 Log(detector, Form("GetFileIDs - Can't execute SQL query to %s database for source: %s",
2352 GetSystemName(system), source));
2356 TList *list = new TList();
2359 if (aResult->GetRowCount() == 0)
2362 Form("GetFileIDs - No entry in %s FXS table for source: %s", GetSystemName(system), source));
2367 Log(detector, Form("GetFileIDs - Found %d ids", aResult->GetRowCount()));
2371 while ((aRow = aResult->Next()))
2374 TString id(aRow->GetField(0), aRow->GetFieldLength(0));
2375 AliDebug(2, Form("fileId = %s", id.Data()));
2376 list->Add(new TObjString(id));
2385 //______________________________________________________________________________________________
2386 Bool_t AliShuttle::Connect(Int_t system)
2388 // Connect to MySQL Server of the system's FXS MySQL databases
2389 // DAQ Logbook, Shuttle Logbook and DAQ FXS db are on the same host
2392 // check connection: if already connected return
2393 if(fServer[system] && fServer[system]->IsConnected()) return kTRUE;
2395 TString dbHost, dbUser, dbPass, dbName;
2397 if (system < 3) // FXS db servers
2399 dbHost = Form("mysql://%s:%d", fConfig->GetFXSdbHost(system), fConfig->GetFXSdbPort(system));
2400 dbUser = fConfig->GetFXSdbUser(system);
2401 dbPass = fConfig->GetFXSdbPass(system);
2402 dbName = fConfig->GetFXSdbName(system);
2403 } else { // Run & Shuttle logbook servers
2404 // TODO Will the Shuttle logbook server be the same as the Run logbook server ???
2405 dbHost = Form("mysql://%s:%d", fConfig->GetDAQlbHost(), fConfig->GetDAQlbPort());
2406 dbUser = fConfig->GetDAQlbUser();
2407 dbPass = fConfig->GetDAQlbPass();
2408 dbName = fConfig->GetDAQlbDB();
2411 fServer[system] = TSQLServer::Connect(dbHost.Data(), dbUser.Data(), dbPass.Data());
2412 if (!fServer[system] || !fServer[system]->IsConnected()) {
2415 AliError(Form("Can't establish connection to FXS database for %s",
2416 AliShuttleInterface::GetSystemName(system)));
2418 AliError("Can't establish connection to Run logbook.");
2420 if(fServer[system]) delete fServer[system];
2425 TSQLResult* aResult=0;
2428 aResult = fServer[kDAQ]->GetTables(dbName.Data());
2431 aResult = fServer[kDCS]->GetTables(dbName.Data());
2434 aResult = fServer[kHLT]->GetTables(dbName.Data());
2437 aResult = fServer[3]->GetTables(dbName.Data());
2445 //______________________________________________________________________________________________
2446 Bool_t AliShuttle::UpdateTable()
2449 // Update FXS table filling time_processed field in all rows corresponding to current run and detector
2452 Bool_t result = kTRUE;
2454 for (UInt_t system=0; system<3; system++)
2456 if(!fFXSCalled[system]) continue;
2458 // check connection, in case connect
2459 if (!Connect(system))
2461 Log(fCurrentDetector, Form("UpdateTable - Couldn't connect to %s FXS database", GetSystemName(system)));
2466 TTimeStamp now; // now
2468 // Loop on FXS list entries
2469 TIter iter(&fFXSlist[system]);
2470 TObjString *aFXSentry=0;
2471 while ((aFXSentry = dynamic_cast<TObjString*> (iter.Next())))
2473 TString aFXSentrystr = aFXSentry->String();
2474 TObjArray *aFXSarray = aFXSentrystr.Tokenize("#!?!#");
2475 if (!aFXSarray || aFXSarray->GetEntries() != 2 )
2477 Log(fCurrentDetector, Form("UpdateTable - error updating %s FXS entry. Check string: <%s>",
2478 GetSystemName(system), aFXSentrystr.Data()));
2479 if(aFXSarray) delete aFXSarray;
2483 const char* fileId = ((TObjString*) aFXSarray->At(0))->GetName();
2484 const char* source = ((TObjString*) aFXSarray->At(1))->GetName();
2486 TString whereClause;
2489 whereClause = Form("where run=%d and detector=\"%s\" and fileId=\"%s\" and DAQsource=\"%s\";",
2490 GetCurrentRun(), fCurrentDetector.Data(), fileId, source);
2492 else if (system == kDCS)
2494 whereClause = Form("where run=%d and detector=\"%s\" and fileId=\"%s\";",
2495 GetCurrentRun(), fCurrentDetector.Data(), fileId);
2497 else if (system == kHLT)
2499 whereClause = Form("where run=%d and detector=\"%s\" and fileId=\"%s\" and DDLnumbers=\"%s\";",
2500 GetCurrentRun(), fCurrentDetector.Data(), fileId, source);
2505 TString sqlQuery = Form("update %s set time_processed=%d %s", fConfig->GetFXSdbTable(system),
2506 now.GetSec(), whereClause.Data());
2508 AliDebug(2, Form("SQL query: \n%s",sqlQuery.Data()));
2511 TSQLResult* aResult;
2512 aResult = dynamic_cast<TSQLResult*> (fServer[system]->Query(sqlQuery));
2515 Log(fCurrentDetector, Form("UpdateTable - %s db: can't execute SQL query <%s>",
2516 GetSystemName(system), sqlQuery.Data()));
2527 //______________________________________________________________________________________________
2528 Bool_t AliShuttle::UpdateTableFailCase()
2530 // Update FXS table filling time_processed field in all rows corresponding to current run and detector
2531 // this is called in case the preprocessor is declared failed for the current run, because
2532 // the fields are updated only in case of success
2534 Bool_t result = kTRUE;
2536 for (UInt_t system=0; system<3; system++)
2538 // check connection, in case connect
2539 if (!Connect(system))
2541 Log(fCurrentDetector, Form("UpdateTableFailCase - Couldn't connect to %s FXS database",
2542 GetSystemName(system)));
2547 TTimeStamp now; // now
2549 // Loop on FXS list entries
2551 TString whereClause = Form("where run=%d and detector=\"%s\";",
2552 GetCurrentRun(), fCurrentDetector.Data());
2555 TString sqlQuery = Form("update %s set time_processed=%d %s", fConfig->GetFXSdbTable(system),
2556 now.GetSec(), whereClause.Data());
2558 AliDebug(2, Form("SQL query: \n%s",sqlQuery.Data()));
2561 TSQLResult* aResult;
2562 aResult = dynamic_cast<TSQLResult*> (fServer[system]->Query(sqlQuery));
2565 Log(fCurrentDetector, Form("UpdateTableFailCase - %s db: can't execute SQL query <%s>",
2566 GetSystemName(system), sqlQuery.Data()));
2576 //______________________________________________________________________________________________
2577 Bool_t AliShuttle::UpdateShuttleLogbook(const char* detector, const char* status)
2580 // Update Shuttle logbook filling detector or shuttle_done column
2581 // ex. of usage: UpdateShuttleLogbook("PHOS", "DONE") or UpdateShuttleLogbook("shuttle_done")
2584 // check connection, in case connect
2586 Log("SHUTTLE", "UpdateShuttleLogbook - Couldn't connect to DAQ Logbook.");
2590 TString detName(detector);
2592 if (detName == "shuttle_done" || detName == "shuttle_ignored")
2594 setClause = "set shuttle_done=1";
2596 if (detName == "shuttle_done")
2598 // Send the information to ML
2599 TMonaLisaText mlStatus("SHUTTLE_status", "Done");
2602 mlList.Add(&mlStatus);
2605 mlID.Form("%d", GetCurrentRun());
2606 fMonaLisa->SendParameters(&mlList, mlID);
2609 TString statusStr(status);
2610 if(statusStr.Contains("done", TString::kIgnoreCase) ||
2611 statusStr.Contains("failed", TString::kIgnoreCase)){
2612 setClause = Form("set %s=\"%s\"", detector, status);
2615 Form("UpdateShuttleLogbook - Invalid status <%s> for detector %s",
2621 TString whereClause = Form("where run=%d", GetCurrentRun());
2623 TString sqlQuery = Form("update %s %s %s",
2624 fConfig->GetShuttlelbTable(), setClause.Data(), whereClause.Data());
2626 AliDebug(2, Form("SQL query: \n%s",sqlQuery.Data()));
2629 TSQLResult* aResult;
2630 aResult = dynamic_cast<TSQLResult*> (fServer[3]->Query(sqlQuery));
2632 Log("SHUTTLE", Form("UpdateShuttleLogbook - Can't execute query <%s>", sqlQuery.Data()));
2640 //______________________________________________________________________________________________
2641 Int_t AliShuttle::GetCurrentRun() const
2644 // Get current run from logbook entry
2647 return fLogbookEntry ? fLogbookEntry->GetRun() : -1;
2650 //______________________________________________________________________________________________
2651 UInt_t AliShuttle::GetCurrentStartTime() const
2654 // get current start time
2657 return fLogbookEntry ? fLogbookEntry->GetStartTime() : 0;
2660 //______________________________________________________________________________________________
2661 UInt_t AliShuttle::GetCurrentEndTime() const
2664 // get current end time from logbook entry
2667 return fLogbookEntry ? fLogbookEntry->GetEndTime() : 0;
2670 //______________________________________________________________________________________________
2671 UInt_t AliShuttle::GetCurrentYear() const
2674 // Get current year from logbook entry
2677 if (!fLogbookEntry) return 0;
2679 TTimeStamp startTime(GetCurrentStartTime());
2680 TString year = Form("%d",startTime.GetDate());
2686 //______________________________________________________________________________________________
2687 const char* AliShuttle::GetLHCPeriod() const
2690 // Get current LHC period from logbook entry
2693 if (!fLogbookEntry) return 0;
2695 return fLogbookEntry->GetRunParameter("LHCperiod");
2698 //______________________________________________________________________________________________
2699 void AliShuttle::Log(const char* detector, const char* message)
2702 // Fill log string with a message
2705 TString logRunDir = GetShuttleLogDir();
2706 if (GetCurrentRun() >=0)
2707 logRunDir += Form("/%d", GetCurrentRun());
2709 void* dir = gSystem->OpenDirectory(logRunDir.Data());
2711 if (gSystem->mkdir(logRunDir.Data(), kTRUE)) {
2712 AliError(Form("Can't open directory <%s>", GetShuttleLogDir()));
2717 gSystem->FreeDirectory(dir);
2720 TString toLog = Form("%s (%d): %s - ", TTimeStamp(time(0)).AsString("s"), getpid(), detector);
2721 if (GetCurrentRun() >= 0)
2722 toLog += Form("run %d - ", GetCurrentRun());
2723 toLog += Form("%s", message);
2725 AliInfo(toLog.Data());
2727 // if we redirect the log output already to the file, leave here
2728 if (fOutputRedirected && strcmp(detector, "SHUTTLE") != 0)
2731 TString fileName = GetLogFileName(detector);
2733 gSystem->ExpandPathName(fileName);
2736 logFile.open(fileName, ofstream::out | ofstream::app);
2738 if (!logFile.is_open()) {
2739 AliError(Form("Could not open file %s", fileName.Data()));
2743 logFile << toLog.Data() << "\n";
2748 //______________________________________________________________________________________________
2749 TString AliShuttle::GetLogFileName(const char* detector) const
2752 // returns the name of the log file for a given sub detector
2757 if (GetCurrentRun() >= 0)
2759 fileName.Form("%s/%d/%s_%d.log", GetShuttleLogDir(), GetCurrentRun(),
2760 detector, GetCurrentRun());
2762 fileName.Form("%s/%s.log", GetShuttleLogDir(), detector);
2768 //______________________________________________________________________________________________
2769 void AliShuttle::SendAlive()
2771 // sends alive message to ML
2773 TMonaLisaText mlStatus("SHUTTLE_status", "Alive");
2776 mlList.Add(&mlStatus);
2778 fMonaLisa->SendParameters(&mlList, "__PROCESSINGINFO__");
2781 //______________________________________________________________________________________________
2782 Bool_t AliShuttle::Collect(Int_t run)
2785 // Collects conditions data for all UNPROCESSED run written to DAQ LogBook in case of run = -1 (default)
2786 // If a dedicated run is given this run is processed
2788 // In operational mode, this is the Shuttle function triggered by the EOR signal.
2792 Log("SHUTTLE","Collect - Shuttle called. Collecting conditions data for unprocessed runs");
2794 Log("SHUTTLE", Form("Collect - Shuttle called. Collecting conditions data for run %d", run));
2796 SetLastAction("Starting");
2798 // create ML instance
2800 fMonaLisa = new TMonaLisaWriter(fConfig->GetMonitorHost(), fConfig->GetMonitorTable());
2805 TString whereClause("where shuttle_done=0");
2807 whereClause += Form(" and run=%d", run);
2809 TObjArray shuttleLogbookEntries;
2810 if (!QueryShuttleLogbook(whereClause, shuttleLogbookEntries))
2812 Log("SHUTTLE", "Collect - Can't retrieve entries from Shuttle logbook");
2816 if (shuttleLogbookEntries.GetEntries() == 0)
2819 Log("SHUTTLE","Collect - Found no UNPROCESSED runs in Shuttle logbook");
2821 Log("SHUTTLE", Form("Collect - Run %d is already DONE "
2822 "or it does not exist in Shuttle logbook", run));
2826 for (UInt_t iDet=0; iDet<NDetectors(); iDet++)
2827 fFirstUnprocessed[iDet] = kTRUE;
2831 // query Shuttle logbook for earlier runs, check if some detectors are unprocessed,
2832 // flag them into fFirstUnprocessed array
2833 TString whereClause(Form("where shuttle_done=0 and run < %d", run));
2834 TObjArray tmpLogbookEntries;
2835 if (!QueryShuttleLogbook(whereClause, tmpLogbookEntries))
2837 Log("SHUTTLE", "Collect - Can't retrieve entries from Shuttle logbook");
2841 TIter iter(&tmpLogbookEntries);
2842 AliShuttleLogbookEntry* anEntry = 0;
2843 while ((anEntry = dynamic_cast<AliShuttleLogbookEntry*> (iter.Next())))
2845 for (UInt_t iDet=0; iDet<NDetectors(); iDet++)
2847 if (anEntry->GetDetectorStatus(iDet) == AliShuttleLogbookEntry::kUnprocessed)
2849 AliDebug(2, Form("Run %d: setting %s as \"not first time unprocessed\"",
2850 anEntry->GetRun(), GetDetName(iDet)));
2851 fFirstUnprocessed[iDet] = kFALSE;
2859 if (!RetrieveConditionsData(shuttleLogbookEntries))
2861 Log("SHUTTLE", "Collect - Process of at least one run failed");
2866 Log("SHUTTLE", "Collect - Requested run(s) successfully processed");
2871 //______________________________________________________________________________________________
2872 Bool_t AliShuttle::RetrieveConditionsData(const TObjArray& dateEntries)
2875 // Retrieve conditions data for all runs that aren't processed yet
2878 Bool_t hasError = kFALSE;
2880 TIter iter(&dateEntries);
2881 AliShuttleLogbookEntry* anEntry;
2883 while ((anEntry = (AliShuttleLogbookEntry*) iter.Next())){
2884 if (!Process(anEntry)){
2888 // clean SHUTTLE temp directory
2889 //TString filename = Form("%s/*.shuttle", GetShuttleTempDir());
2890 //RemoveFile(filename.Data());
2893 return hasError == kFALSE;
2896 //______________________________________________________________________________________________
2897 ULong_t AliShuttle::GetTimeOfLastAction() const
2900 // Gets time of last action
2905 fMonitoringMutex->Lock();
2907 tmp = fLastActionTime;
2909 fMonitoringMutex->UnLock();
2914 //______________________________________________________________________________________________
2915 const TString AliShuttle::GetLastAction() const
2918 // returns a string description of the last action
2923 fMonitoringMutex->Lock();
2927 fMonitoringMutex->UnLock();
2932 //______________________________________________________________________________________________
2933 void AliShuttle::SetLastAction(const char* action)
2936 // updates the monitoring variables
2939 fMonitoringMutex->Lock();
2941 fLastAction = action;
2942 fLastActionTime = time(0);
2944 fMonitoringMutex->UnLock();
2947 //______________________________________________________________________________________________
2948 const char* AliShuttle::GetRunParameter(const char* param)
2951 // returns run parameter read from DAQ logbook
2954 if(!fLogbookEntry) {
2955 AliError("No logbook entry!");
2959 return fLogbookEntry->GetRunParameter(param);
2962 //______________________________________________________________________________________________
2963 AliCDBEntry* AliShuttle::GetFromOCDB(const char* detector, const AliCDBPath& path)
2966 // returns object from OCDB valid for current run
2969 if (fTestMode & kErrorOCDB)
2971 Log(detector, "GetFromOCDB - In TESTMODE - Simulating error with OCDB");
2975 AliCDBStorage *sto = AliCDBManager::Instance()->GetStorage(fgkMainCDB);
2978 Log(detector, "GetFromOCDB - Cannot activate main OCDB for query!");
2982 return dynamic_cast<AliCDBEntry*> (sto->Get(path, GetCurrentRun()));
2985 //______________________________________________________________________________________________
2986 Bool_t AliShuttle::SendMail()
2989 // sends a mail to the subdetector expert in case of preprocessor error
2992 if (fTestMode != kNone)
2995 if (!fConfig->SendMail()) return kTRUE;
2998 TIter iterExperts(fConfig->GetResponsibles(fCurrentDetector));
2999 TObjString *anExpert=0;
3000 while ((anExpert = (TObjString*) iterExperts.Next()))
3002 to += Form("%s,", anExpert->GetName());
3004 if (to.Length() > 0)
3005 to.Remove(to.Length()-1);
3006 AliDebug(2, Form("to: %s",to.Data()));
3009 Log("SHUTTLE", "List of detector responsibles not set!");
3013 void* dir = gSystem->OpenDirectory(GetShuttleLogDir());
3016 if (gSystem->mkdir(GetShuttleLogDir(), kTRUE))
3018 Log("SHUTTLE", Form("SendMail - Can't open directory <%s>", GetShuttleLogDir()));
3023 gSystem->FreeDirectory(dir);
3026 TString bodyFileName;
3027 bodyFileName.Form("%s/mail.body", GetShuttleLogDir());
3028 gSystem->ExpandPathName(bodyFileName);
3031 mailBody.open(bodyFileName, ofstream::out);
3033 if (!mailBody.is_open())
3035 Log("SHUTTLE", Form("Could not open mail body file %s", bodyFileName.Data()));
3040 TIter iterAdmins(fConfig->GetAdmins(AliShuttleConfig::kGlobal));
3041 TObjString *anAdmin=0;
3042 while ((anAdmin = (TObjString*) iterAdmins.Next()))
3044 cc += Form("%s,", anAdmin->GetName());
3046 if (cc.Length() > 0)
3047 cc.Remove(to.Length()-1);
3048 AliDebug(2, Form("cc: %s",to.Data()));
3050 TString subject = Form("%s Shuttle preprocessor FAILED in run %d (run type = %s)!",
3051 fCurrentDetector.Data(), GetCurrentRun(), GetRunType());
3052 AliDebug(2, Form("subject: %s", subject.Data()));
3054 TString body = Form("Dear %s expert(s), \n\n", fCurrentDetector.Data());
3055 body += Form("SHUTTLE just detected that your preprocessor "
3056 "failed processing run %d (run type = %s)!!\n\n",
3057 GetCurrentRun(), GetRunType());
3058 body += Form("Please check %s status on the SHUTTLE monitoring page: \n\n",
3059 fCurrentDetector.Data());
3060 if (fConfig->GetRunMode() == AliShuttleConfig::kTest)
3062 body += Form("\thttp://pcalimonitor.cern.ch:8889/shuttle.jsp?time=168 \n\n");
3064 body += Form("\thttp://pcalimonitor.cern.ch/shuttle.jsp?instance=PROD&time=168 \n\n");
3068 TString logFolder = "logs";
3069 if (fConfig->GetRunMode() == AliShuttleConfig::kProd)
3070 logFolder += "_PROD";
3073 body += Form("Find the %s log for the current run on \n\n"
3074 "\thttp://pcalishuttle01.cern.ch:8880/%s/%d/%s_%d.log \n\n",
3075 fCurrentDetector.Data(), logFolder.Data(), GetCurrentRun(),
3076 fCurrentDetector.Data(), GetCurrentRun());
3077 body += Form("The last 10 lines of %s log file are following:\n\n", fCurrentDetector.Data());
3079 AliDebug(2, Form("Body begin: %s", body.Data()));
3081 mailBody << body.Data();
3083 mailBody.open(bodyFileName, ofstream::out | ofstream::app);
3085 TString logFileName = Form("%s/%d/%s_%d.log", GetShuttleLogDir(),
3086 GetCurrentRun(), fCurrentDetector.Data(), GetCurrentRun());
3087 TString tailCommand = Form("tail -n 10 %s >> %s", logFileName.Data(), bodyFileName.Data());
3088 if (gSystem->Exec(tailCommand.Data()))
3090 mailBody << Form("%s log file not found ...\n\n", fCurrentDetector.Data());
3093 TString endBody = Form("------------------------------------------------------\n\n");
3094 endBody += Form("In case of problems please contact the SHUTTLE core team.\n\n");
3095 endBody += "Please do not answer this message directly, it is automatically generated.\n\n";
3096 endBody += "Greetings,\n\n \t\t\tthe SHUTTLE\n";
3098 AliDebug(2, Form("Body end: %s", endBody.Data()));
3100 mailBody << endBody.Data();
3105 TString mailCommand = Form("mail -s \"%s\" -c %s %s < %s",
3109 bodyFileName.Data());
3110 AliDebug(2, Form("mail command: %s", mailCommand.Data()));
3112 Bool_t result = gSystem->Exec(mailCommand.Data());
3117 //______________________________________________________________________________________________
3118 Bool_t AliShuttle::SendMailToDCS()
3121 // sends a mail to the DCS Amanda experts in case of DCS data point retrieval error
3124 if (fTestMode != kNone)
3127 if (!fConfig->SendMail()) return kTRUE;
3129 void* dir = gSystem->OpenDirectory(GetShuttleLogDir());
3132 if (gSystem->mkdir(GetShuttleLogDir(), kTRUE))
3134 Log("SHUTTLE", Form("SendMailToDCS - Can't open directory <%s>", GetShuttleLogDir()));
3139 gSystem->FreeDirectory(dir);
3142 TString bodyFileName;
3143 bodyFileName.Form("%s/mail.body", GetShuttleLogDir());
3144 gSystem->ExpandPathName(bodyFileName);
3147 mailBody.open(bodyFileName, ofstream::out);
3149 if (!mailBody.is_open())
3151 Log("SHUTTLE", Form("SendMailToDCS - Could not open mail body file %s", bodyFileName.Data()));
3156 TIter iterExperts(fConfig->GetAdmins(AliShuttleConfig::kAmanda));
3157 TObjString *anExpert=0;
3158 while ((anExpert = (TObjString*) iterExperts.Next()))
3160 to += Form("%s,", anExpert->GetName());
3162 if (to.Length() > 0)
3163 to.Remove(to.Length()-1);
3164 AliDebug(2, Form("to: %s",to.Data()));
3167 Log("SHUTTLE", "List of Amanda server administrators not set!");
3172 TIter iterAdmins(fConfig->GetAdmins(AliShuttleConfig::kGlobal));
3173 TObjString *anAdmin=0;
3174 while ((anAdmin = (TObjString*) iterAdmins.Next()))
3176 cc += Form("%s,", anAdmin->GetName());
3178 if (cc.Length() > 0)
3179 cc.Remove(to.Length()-1);
3180 AliDebug(2, Form("cc: %s",to.Data()));
3182 TString subject = Form("Retrieval of data points for %s FAILED in run %d !",
3183 fCurrentDetector.Data(), GetCurrentRun());
3184 AliDebug(2, Form("subject: %s", subject.Data()));
3186 TString body = Form("Dear DCS experts, \n\n");
3187 body += Form("SHUTTLE couldn\'t retrieve the data points for detector %s "
3188 "in run %d!!\n\n", fCurrentDetector.Data(), GetCurrentRun());
3189 body += Form("Please check %s status on the SHUTTLE monitoring page: \n\n",
3190 fCurrentDetector.Data());
3191 if (fConfig->GetRunMode() == AliShuttleConfig::kTest)
3193 body += Form("\thttp://pcalimonitor.cern.ch:8889/shuttle.jsp?time=168 \n\n");
3195 body += Form("\thttp://pcalimonitor.cern.ch/shuttle.jsp?instance=PROD?time=168 \n\n");
3198 TString logFolder = "logs";
3199 if (fConfig->GetRunMode() == AliShuttleConfig::kProd)
3200 logFolder += "_PROD";
3203 body += Form("Find the %s log for the current run on \n\n"
3204 "\thttp://pcalishuttle01.cern.ch:8880/%s/%d/%s_%d.log \n\n",
3205 fCurrentDetector.Data(), logFolder.Data(), GetCurrentRun(),
3206 fCurrentDetector.Data(), GetCurrentRun());
3207 body += Form("The last 10 lines of %s log file are following:\n\n", fCurrentDetector.Data());
3209 AliDebug(2, Form("Body begin: %s", body.Data()));
3211 mailBody << body.Data();
3213 mailBody.open(bodyFileName, ofstream::out | ofstream::app);
3215 TString logFileName = Form("%s/%d/%s_%d.log", GetShuttleLogDir(), GetCurrentRun(),
3216 fCurrentDetector.Data(), GetCurrentRun());
3217 TString tailCommand = Form("tail -n 10 %s >> %s", logFileName.Data(), bodyFileName.Data());
3218 if (gSystem->Exec(tailCommand.Data()))
3220 mailBody << Form("%s log file not found ...\n\n", fCurrentDetector.Data());
3223 TString endBody = Form("------------------------------------------------------\n\n");
3224 endBody += Form("In case of problems please contact the SHUTTLE core team.\n\n");
3225 endBody += "Please do not answer this message directly, it is automatically generated.\n\n";
3226 endBody += "Greetings,\n\n \t\t\tthe SHUTTLE\n";
3228 AliDebug(2, Form("Body end: %s", endBody.Data()));
3230 mailBody << endBody.Data();
3235 TString mailCommand = Form("mail -s \"%s\" -c %s %s < %s",
3239 bodyFileName.Data());
3240 AliDebug(2, Form("mail command: %s", mailCommand.Data()));
3242 Bool_t result = gSystem->Exec(mailCommand.Data());
3247 //______________________________________________________________________________________________
3248 const char* AliShuttle::GetRunType()
3251 // returns run type read from "run type" logbook
3254 if(!fLogbookEntry) {
3255 AliError("No logbook entry!");
3259 return fLogbookEntry->GetRunType();
3262 //______________________________________________________________________________________________
3263 Bool_t AliShuttle::GetHLTStatus()
3265 // Return HLT status (ON=1 OFF=0)
3266 // Converts the HLT status from the status string read in the run logbook (not just a bool)
3268 if(!fLogbookEntry) {
3269 AliError("No logbook entry!");
3273 // TODO implement when HLTStatus is inserted in run logbook
3274 //TString hltStatus = fLogbookEntry->GetRunParameter("HLTStatus");
3275 //if(hltStatus == "OFF") {return kFALSE};
3280 //______________________________________________________________________________________________
3281 void AliShuttle::SetShuttleTempDir(const char* tmpDir)
3284 // sets Shuttle temp directory
3287 fgkShuttleTempDir = gSystem->ExpandPathName(tmpDir);
3290 //______________________________________________________________________________________________
3291 void AliShuttle::SetShuttleLogDir(const char* logDir)
3294 // sets Shuttle log directory
3297 fgkShuttleLogDir = gSystem->ExpandPathName(logDir);