43d1ffd43e798b917456fe976d0124b4be7453b4
[u/mrichter/AliRoot.git] / SHUTTLE / AliShuttle.cxx
1 /**************************************************************************
2  * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
3  *                                                                        *
4  * Author: The ALICE Off-line Project.                                    *
5  * Contributors are mentioned in the code where appropriate.              *
6  *                                                                        *
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  **************************************************************************/
15
16 /* $Id$ */
17
18 //
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.
29 //
30
31 #include "AliShuttle.h"
32
33 #include "AliCDBManager.h"
34 #include "AliCDBStorage.h"
35 #include "AliCDBId.h"
36 #include "AliCDBRunRange.h"
37 #include "AliCDBPath.h"
38 #include "AliCDBEntry.h"
39 #include "AliShuttleConfig.h"
40 #include "DCSClient/AliDCSClient.h"
41 #include "AliLog.h"
42 #include "AliPreprocessor.h"
43 #include "AliShuttleStatus.h"
44 #include "AliShuttleLogbookEntry.h"
45
46 #include <TSystem.h>
47 #include <TObject.h>
48 #include <TString.h>
49 #include <TTimeStamp.h>
50 #include <TObjString.h>
51 #include <TSQLServer.h>
52 #include <TSQLResult.h>
53 #include <TSQLRow.h>
54 #include <TMutex.h>
55 #include <TSystemDirectory.h>
56 #include <TSystemFile.h>
57 #include <TFile.h>
58 #include <TGrid.h>
59 #include <TGridResult.h>
60 #include <TMap.h>
61
62 #include <TMonaLisaWriter.h>
63
64 #include <fstream>
65
66 #include <sys/types.h>
67 #include <sys/wait.h>
68
69 #include <signal.h>
70
71 ClassImp(AliShuttle)
72
73 //______________________________________________________________________________________________
74 AliShuttle::AliShuttle(const AliShuttleConfig* config,
75                 UInt_t timeout, Int_t retries):
76 fConfig(config),
77 fTimeout(timeout), fRetries(retries),
78 fPreprocessorMap(),
79 fLogbookEntry(0),
80 fCurrentDetector(),
81 fFirstProcessing(0),
82 fFXSError(-1),
83 fStatusEntry(0),
84 fMonitoringMutex(0),
85 fLastActionTime(0),
86 fLastAction(),
87 fMonaLisa(0),
88 fTestMode(kNone),
89 fReadTestMode(kFALSE),
90 fOutputRedirected(kFALSE)
91 {
92         //
93         // config: AliShuttleConfig used
94         // timeout: timeout used for AliDCSClient connection
95         // retries: the number of retries in case of connection error.
96         //
97
98         if (!fConfig->IsValid()) AliFatal("********** !!!!! Invalid configuration !!!!! **********");
99         for(int iSys=0;iSys<5;iSys++) {
100                 fServer[iSys]=0;
101                 if (iSys < 4)
102                         fFXSlist[iSys].SetOwner(kTRUE);
103         }
104         fPreprocessorMap.SetOwner(kTRUE);
105
106         for (UInt_t iDet=0; iDet<NDetectors(); iDet++)
107                 fFirstUnprocessed[iDet] = kFALSE;
108
109         fMonitoringMutex = new TMutex();
110 }
111
112 //______________________________________________________________________________________________
113 AliShuttle::~AliShuttle()
114 {
115         //
116         // destructor
117         //
118
119         fPreprocessorMap.DeleteAll();
120         for(int iSys=0;iSys<5;iSys++)
121                 if(fServer[iSys]) {
122                         fServer[iSys]->Close();
123                         delete fServer[iSys];
124                         fServer[iSys] = 0;
125                 }
126
127         if (fStatusEntry){
128                 delete fStatusEntry;
129                 fStatusEntry = 0;
130         }
131         
132         if (fMonitoringMutex) 
133         {
134                 delete fMonitoringMutex;
135                 fMonitoringMutex = 0;
136         }
137 }
138
139 //______________________________________________________________________________________________
140 void AliShuttle::RegisterPreprocessor(AliPreprocessor* preprocessor)
141 {
142         //
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()).
147         //
148
149         const char* detName = preprocessor->GetName();
150         if(GetDetPos(detName) < 0)
151                 AliFatal(Form("********** !!!!! Invalid detector name: %s !!!!! **********", detName));
152
153         if (fPreprocessorMap.GetValue(detName)) {
154                 AliWarning(Form("AliPreprocessor %s is already registered!", detName));
155                 return;
156         }
157
158         fPreprocessorMap.Add(new TObjString(detName), preprocessor);
159 }
160 //______________________________________________________________________________________________
161 Bool_t AliShuttle::Store(const AliCDBPath& path, TObject* object,
162                 AliCDBMetaData* metaData, Int_t validityStart, Bool_t validityInfinite)
163 {
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).
169
170         return StoreLocally(fgkLocalCDB, path, object, metaData, validityStart, validityInfinite);
171 }
172
173 //______________________________________________________________________________________________
174 Bool_t AliShuttle::StoreReferenceData(const AliCDBPath& path, TObject* object, AliCDBMetaData* metaData)
175 {
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).
180
181         return StoreLocally(fgkLocalRefStorage, path, object, metaData);
182 }
183
184 //______________________________________________________________________________________________
185 Bool_t AliShuttle::StoreLocally(const TString& localUri,
186                         const AliCDBPath& path, TObject* object, AliCDBMetaData* metaData,
187                         Int_t validityStart, Bool_t validityInfinite)
188 {
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
200         //
201         // returns 0 if fail, 1 otherwise
202
203
204         if (fTestMode & kErrorStorage)
205         {
206                 Log(fCurrentDetector, "StoreLocally - In TESTMODE - Simulating error while storing locally");
207                 return kFALSE;
208         }
209         
210         const char* cdbType = (localUri == fgkLocalCDB) ? "CDB" : "Reference";
211
212         Int_t firstRun = GetCurrentRun() - validityStart;
213         if(firstRun < 0) {
214                 AliWarning("First valid run happens to be less than 0! Setting it to 0.");
215                 firstRun=0;
216         }
217
218         Int_t lastRun = -1;
219         if(validityInfinite) {
220                 lastRun = AliCDBRunRange::Infinity();
221         } else {
222                 lastRun = GetCurrentRun();
223         }
224
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);
227
228         if(! dynamic_cast<TObjString*> (metaData->GetProperty("RunUsed(TObjString)"))){
229                 TObjString runUsed = Form("%d", GetCurrentRun());
230                 metaData->SetProperty("RunUsed(TObjString)", runUsed.Clone());
231         }
232
233         Bool_t result = kFALSE;
234
235         if (!(AliCDBManager::Instance()->GetStorage(localUri))) {
236                 Log("SHUTTLE", Form("StoreLocally - Cannot activate local %s storage", cdbType));
237         } else {
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);
243         }
244
245         if(!result) {
246
247                 Log(fCurrentDetector, Form("StoreLocally - Can't store object <%s>!", id.ToString().Data()));
248         }
249
250
251         return result;
252 }
253
254 //______________________________________________________________________________________________
255 Bool_t AliShuttle::StoreOCDB()
256 {
257         //
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. 
261         //
262         
263         UpdateShuttleStatus(AliShuttleStatus::kStoreStarted);
264                         
265         if (fTestMode & kErrorGrid)
266         {
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");
269                 return kFALSE;
270         }
271         
272         Log("SHUTTLE","StoreOCDB - Storing OCDB data ...");
273         Int_t resultCDB = StoreOCDB(fgkMainCDB);
274
275         Log("SHUTTLE","StoreOCDB - Storing reference data ...");
276         Int_t resultRef = StoreOCDB(fgkMainRefStorage);
277         
278         Log("SHUTTLE","StoreOCDB - Storing reference files ...");
279         Bool_t resultRefFiles = CopyFilesToGrid("reference");
280         
281         Bool_t resultMetadata = kTRUE;
282         if(fCurrentDetector == "GRP") 
283         {
284                 Log("SHUTTLE","StoreOCDB - Storing Run Metadata file ...");
285                 resultMetadata = CopyFilesToGrid("metadata");
286         }
287         
288         Int_t storeResult = 0;
289         
290         if (resultCDB < 0 || resultRef < 0 || resultRefFiles == kFALSE || resultMetadata == kFALSE)
291                 storeResult = -1;
292         else if (resultCDB > 0 || resultRef > 0)
293                 storeResult = 1;
294                 
295         if (storeResult < 0)
296         {
297                 Log("SHUTTLE", 
298                         Form("\t\t\t****** run %d - %s: STORAGE ERROR ******",
299                                 GetCurrentRun(), fCurrentDetector.Data()));
300                 UpdateShuttleStatus(AliShuttleStatus::kStoreError);
301         } 
302         else if (storeResult > 0)
303         {
304                 Log("SHUTTLE", 
305                         Form("\t\t\t****** run %d - %s: STORAGE DELAYED ******",
306                                 GetCurrentRun(), fCurrentDetector.Data()));
307                 UpdateShuttleStatus(AliShuttleStatus::kStoreDelayed);
308         }
309         else if (storeResult == 0) 
310         {
311                 Log("SHUTTLE", 
312                         Form("\t\t\t****** run %d - %s: DONE ******",
313                                 GetCurrentRun(), fCurrentDetector.Data()));
314                 UpdateShuttleStatus(AliShuttleStatus::kDone);
315                 UpdateShuttleLogbook(fCurrentDetector, "DONE");
316         }
317
318         return (storeResult == 0);
319 }
320
321 //______________________________________________________________________________________________
322 Int_t AliShuttle::StoreOCDB(const TString& gridURI)
323 {
324         //
325         // Called by StoreOCDB(), performs actual storage to the main OCDB and reference storages (Grid)
326         //
327         // Return code:
328         //   -2 initialization error
329         //   -1 storage error
330         //   0  success
331         //   1  storage delayed (e.g. previous unprocessed runs)
332         //
333
334         TObjArray* gridIds=0;
335
336         Bool_t result = kTRUE;
337         Bool_t delayed = kFALSE;
338
339         const char* type = 0;
340         TString localURI;
341         if(gridURI == fgkMainCDB) {
342                 type = "OCDB";
343                 localURI = fgkLocalCDB;
344         } else if(gridURI == fgkMainRefStorage) {
345                 type = "reference";
346                 localURI = fgkLocalRefStorage;
347         } else {
348                 AliError(Form("Invalid storage URI: %s", gridURI.Data()));
349                 return -2;
350         }
351
352         AliCDBManager* man = AliCDBManager::Instance();
353
354         AliCDBStorage *gridSto = man->GetStorage(gridURI);
355         if(!gridSto) {
356                 Log("SHUTTLE",
357                         Form("StoreOCDB - cannot activate main %s storage", type));
358                 return -2;
359         }
360         gridSto->SetMirrorSEs(fgkMirrorSEs.Data());
361
362         gridIds = gridSto->GetQueryCDBList();
363
364         // get objects previously stored in local CDB
365         AliCDBStorage *localSto = man->GetStorage(localURI);
366         if(!localSto) {
367                 Log("SHUTTLE",
368                         Form("StoreOCDB - cannot activate local %s storage", type));
369                 return -2;
370         }
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);
375
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);
384                                                 
385                 Log(fCurrentDetector.Data(), Form("Attempting to store %s", aLocId.ToString().Data()));
386
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)])
391                 {
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()));
398                         delayed = kTRUE;
399                         continue;
400                 }
401
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()) 
408                                 continue;
409                         // skip all objects valid up to infinity
410                         if (aGridId->GetLastRun() == AliCDBRunRange::Infinity()) 
411                                 continue;
412                         
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()));
417                         
418                         store = kFALSE;
419                         break;
420                 }
421
422                 Bool_t storeOk = kFALSE;
423                 if (store)
424                 {
425                         Log(fCurrentDetector.Data(), Form("Prechecks succeeded. Ready to store %s", aLocId.ToString().Data()));
426                         storeOk = gridSto->Put(aLocEntry);
427                         if (storeOk) {
428                                 Log("SHUTTLE",
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));
434                         } else  {
435                                 Log("SHUTTLE",
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()));
441                                 result = kFALSE;
442                         }
443                 }
444                 
445                 if (!store || storeOk) {
446                         // removing local file...
447                         TString filename;
448                         localSto->IdToFilename(aLocId, filename);
449                         Log("SHUTTLE", Form("StoreOCDB - Removing local file %s", filename.Data()));
450                         RemoveFile(filename.Data());
451                 }
452         }
453         localEntries->Clear();
454
455         Int_t returnCode = 0;
456         
457         if (result == kFALSE)
458                 returnCode = -1;
459         else if (delayed != kFALSE)
460                 returnCode =  1;
461
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));
464         
465         return returnCode;
466 }
467
468 //______________________________________________________________________________________________
469 Bool_t AliShuttle::CleanReferenceStorage(const char* detector)
470 {
471         // clears the directory used to store reference files of a given subdetector
472   
473         AliCDBManager* man = AliCDBManager::Instance();
474         AliCDBStorage* sto = man->GetStorage(fgkLocalRefStorage);
475         TString localBaseFolder = sto->GetBaseFolder();
476
477         TString targetDir = GetRefFilePrefix(localBaseFolder.Data(), detector);
478         
479         Log("SHUTTLE", Form("CleanReferenceStorage - Cleaning %s", targetDir.Data()));
480
481         TString begin;
482         begin.Form("%d_", GetCurrentRun());
483         
484         TSystemDirectory* baseDir = new TSystemDirectory("/", targetDir);
485         if (!baseDir)
486                 return kTRUE;
487                 
488         TList* dirList = baseDir->GetListOfFiles();
489         delete baseDir;
490         
491         if (!dirList) return kTRUE;
492                         
493         if (dirList->GetEntries() < 3) // to be changed to 4?
494         {
495                 delete dirList;
496                 return kTRUE;
497         }
498                                 
499         Int_t nDirs = 0, nDel = 0;
500         TIter dirIter(dirList);
501         TSystemFile* entry = 0;
502
503         Bool_t success = kTRUE;
504         
505         while ((entry = dynamic_cast<TSystemFile*> (dirIter.Next())))
506         {                                       
507                 if (entry->IsDirectory())
508                         continue;
509                 
510                 TString fileName(entry->GetName());
511                 if (!fileName.BeginsWith(begin))
512                         continue;
513                         
514                 nDirs++;
515                                                 
516                 // delete file
517                 Int_t result = gSystem->Unlink(fileName.Data());
518                 
519                 if (result)
520                 {
521                         Log("SHUTTLE", Form("CleanReferenceStorage - Could not delete file %s!", fileName.Data()));
522                         success = kFALSE;
523                 } else {
524                         nDel++;
525                 }
526         }
527
528         if(nDirs > 0)
529                 Log("SHUTTLE", Form("CleanReferenceStorage - %d (over %d) reference files in folder %s were deleted.", 
530                         nDel, nDirs, targetDir.Data()));
531
532                 
533         delete dirList;
534         return success;
535
536
537
538
539
540
541   Int_t result = gSystem->GetPathInfo(targetDir, 0, (Long64_t*) 0, 0, 0);
542   if (result == 0)
543   {
544     // delete directory
545     result = gSystem->Exec(Form("rm -rf %s", targetDir.Data()));
546     if (result != 0)
547     {  
548       Log("SHUTTLE", Form("CleanReferenceStorage - Could not clean directory %s", targetDir.Data()));
549       return kFALSE;
550     }
551   }
552
553   result = gSystem->mkdir(targetDir, kTRUE);
554   if (result != 0)
555   {
556     Log("SHUTTLE", Form("CleanReferenceStorage - Error creating base directory %s", targetDir.Data()));
557     return kFALSE;
558   }
559         
560   return kTRUE;
561 }
562
563 //______________________________________________________________________________________________
564 Bool_t AliShuttle::StoreReferenceFile(const char* detector, const char* localFile, const char* gridFileName)
565 {
566         //
567         // Stores reference file directly (without opening it). This function stores the file locally.
568         //
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
572         // 
573         
574         if (fTestMode & kErrorStorage)
575         {
576                 Log(fCurrentDetector, "StoreReferenceFile - In TESTMODE - Simulating error while storing locally");
577                 return kFALSE;
578         }
579         
580         AliCDBManager* man = AliCDBManager::Instance();
581         AliCDBStorage* sto = man->GetStorage(fgkLocalRefStorage);
582         
583         TString localBaseFolder = sto->GetBaseFolder();
584         
585         TString target = GetRefFilePrefix(localBaseFolder.Data(), detector);    
586         target.Append(Form("/%d_%s", GetCurrentRun(), gridFileName));
587         
588         return CopyFileLocally(localFile, target);
589 }
590
591 //______________________________________________________________________________________________
592 Bool_t AliShuttle::StoreRunMetadataFile(const char* localFile, const char* gridFileName)
593 {
594         //
595         // Stores Run metadata file to the Grid, in the run folder
596         //
597         // Only GRP can call this function.
598         
599         if (fTestMode & kErrorStorage)
600         {
601                 Log(fCurrentDetector, "StoreRunMetaDataFile - In TESTMODE - Simulating error while storing locally");
602                 return kFALSE;
603         }
604         
605         AliCDBManager* man = AliCDBManager::Instance();
606         AliCDBStorage* sto = man->GetStorage(fgkLocalRefStorage);
607         
608         TString localBaseFolder = sto->GetBaseFolder();
609         
610         // Build Run level folder
611         // folder = /alice/data/year/lhcPeriod/runNb/raw
612         
613                 
614         TString lhcPeriod = GetLHCPeriod();     
615         if (lhcPeriod.Length() == 0) 
616         {
617                 Log("SHUTTLE","StoreRunMetaDataFile - LHCPeriod not found in logbook!");
618                 return 0;
619         }
620         
621         // TODO partitions with one detector only write data into LHCperiod_DET
622         TString partition = GetRunParameter("detector");
623         
624         if (partition.Length() > 0 && partition != "ALICE")
625         {
626                 lhcPeriod.Append(Form("_%s", partition.Data()));
627                 Log(fCurrentDetector, Form("Run data tags merged file will be written in %s", 
628                                 lhcPeriod.Data()));
629         }
630                 
631         TString target = Form("%s/GRP/RunMetadata%s%d/%s/%09d/raw/%s", 
632                                 localBaseFolder.Data(), fConfig->GetAlienPath(), GetCurrentYear(), 
633                                 lhcPeriod.Data(), GetCurrentRun(), gridFileName);
634                                         
635         return CopyFileLocally(localFile, target);
636 }
637
638 //______________________________________________________________________________________________
639 Bool_t AliShuttle::CopyFileLocally(const char* localFile, const TString& target)
640 {
641         //
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)
646         //
647         
648         TString targetDir(target(0, target.Last('/')));
649         
650         //try to open base dir folder, if it does not exist
651         void* dir = gSystem->OpenDirectory(targetDir.Data());
652         if (dir == NULL) {
653                 if (gSystem->mkdir(targetDir.Data(), kTRUE)) {
654                         Log("SHUTTLE", Form("CopyFileLocally - Can't open directory <%s>", targetDir.Data()));
655                         return kFALSE;
656                 }
657
658         } else {
659                 gSystem->FreeDirectory(dir);
660         }
661         
662         Int_t result = 0;
663         
664         result = gSystem->GetPathInfo(localFile, 0, (Long64_t*) 0, 0, 0);
665         if (result)
666         {
667                 Log("SHUTTLE", Form("CopyFileLocally - %s does not exist", localFile));
668                 return kFALSE;
669         }
670
671         result = gSystem->GetPathInfo(target, 0, (Long64_t*) 0, 0, 0);
672         if (!result)
673         {
674                 Log("SHUTTLE", Form("CopyFileLocally - target file %s already exist, removing...", target.Data()));
675                 if (gSystem->Unlink(target.Data()))
676                 {
677                         Log("SHUTTLE", Form("CopyFileLocally - Could not remove existing target file %s!", target.Data()));
678                         return kFALSE;
679                 }
680         }       
681         
682         result = gSystem->CopyFile(localFile, target);
683
684         if (result == 0)
685         {
686                 Log("SHUTTLE", Form("CopyFileLocally - File %s stored locally to %s", localFile, target.Data()));
687                 return kTRUE;
688         }
689         else
690         {
691                 Log("SHUTTLE", Form("CopyFileLocally - Could not store file %s to %s! Error code = %d", 
692                                 localFile, target.Data(), result));
693                 return kFALSE;
694         }       
695
696
697
698 }
699
700 //______________________________________________________________________________________________
701 Bool_t AliShuttle::CopyFilesToGrid(const char* type)
702 {
703         //
704         // Transfers local files to the Grid. Local files can be reference files 
705         // or run metadata file (from GRP only).
706         //
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>
710         //
711                 
712         AliCDBManager* man = AliCDBManager::Instance();
713         AliCDBStorage* sto = man->GetStorage(fgkLocalRefStorage);
714         if (!sto)
715                 return kFALSE;
716         TString localBaseFolder = sto->GetBaseFolder();
717         
718         TString dir;
719         TString alienDir;
720         TString begin;
721         
722         if (strcmp(type, "reference") == 0) 
723         {
724                 dir = GetRefFilePrefix(localBaseFolder.Data(), fCurrentDetector.Data());
725                 AliCDBStorage* gridSto = man->GetStorage(fgkMainRefStorage);
726                 if (!gridSto)
727                         return kFALSE;
728                 TString gridBaseFolder = gridSto->GetBaseFolder();
729                 alienDir = GetRefFilePrefix(gridBaseFolder.Data(), fCurrentDetector.Data());
730                 begin = Form("%d_", GetCurrentRun());
731         } 
732         else if (strcmp(type, "metadata") == 0)
733         {
734                         
735                 TString lhcPeriod = GetLHCPeriod();
736         
737                 if (lhcPeriod.Length() == 0) 
738                 {
739                         Log("SHUTTLE","CopyFilesToGrid - LHCPeriod not found in logbook!");
740                         return 0;
741                 }
742                 
743                 // TODO partitions with one detector only write data into LHCperiod_DET
744                 TString partition = GetRunParameter("detector");
745         
746                 if (partition.Length() > 0 && partition != "ALICE")
747                 {
748                         lhcPeriod.Append(Form("_%s", partition.Data()));
749                 }
750                 
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());
755                 
756                 begin = "";
757         }
758         else 
759         {
760                 Log("SHUTTLE", "CopyFilesToGrid - Unexpected: type label must be reference or metadata!");
761                 return kFALSE;
762         }
763                 
764         TSystemDirectory* baseDir = new TSystemDirectory("/", dir);
765         if (!baseDir)
766                 return kTRUE;
767                 
768         TList* dirList = baseDir->GetListOfFiles();
769         delete baseDir;
770         
771         if (!dirList) return kTRUE;
772                 
773         if (dirList->GetEntries() < 3) 
774         {
775                 delete dirList;
776                 return kTRUE;
777         }
778                         
779         if (!gGrid)
780         { 
781                 Log("SHUTTLE", "CopyFilesToGrid - Connection to Grid failed: Cannot continue!");
782                 delete dirList;
783                 return kFALSE;
784         }
785         
786         Int_t nDirs = 0, nTransfer = 0;
787         TIter dirIter(dirList);
788         TSystemFile* entry = 0;
789
790         Bool_t success = kTRUE;
791         Bool_t first = kTRUE;
792         
793         while ((entry = dynamic_cast<TSystemFile*> (dirIter.Next())))
794         {                       
795                 if (entry->IsDirectory())
796                         continue;
797                         
798                 TString fileName(entry->GetName());
799                 if (!fileName.BeginsWith(begin))
800                         continue;
801                         
802                 nDirs++;
803                         
804                 if (first)
805                 {
806                         first = kFALSE;
807                         // check that folder exists, otherwise create it
808                         TGridResult* result = gGrid->Ls(alienDir.Data(), "a");
809                         
810                         if (!result)
811                         {
812                                 delete dirList;
813                                 return kFALSE;
814                         }
815                         
816                         if (!result->GetFileName(1)) // TODO: It looks like element 0 is always 0!!
817                         {
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))
821                                 {
822                                         Log("SHUTTLE", Form("CopyFilesToGrid - Cannot create directory %s",
823                                                         alienDir.Data()));
824                                         delete dirList;
825                                         return kFALSE;
826                                 } else {
827                                         Log("SHUTTLE",Form("CopyFilesToGrid - Folder %s created", alienDir.Data()));
828                                 }
829                                 
830                         } else {
831                                         Log("SHUTTLE",Form("CopyFilesToGrid - Folder %s found", alienDir.Data()));
832                         }
833                 }
834                         
835                 TString fullLocalPath;
836                 fullLocalPath.Form("%s/%s", dir.Data(), fileName.Data());
837                 
838                 TString fullGridPath;
839                 fullGridPath.Form("alien://%s/%s", alienDir.Data(), fileName.Data());
840
841                 Bool_t result = TFile::Cp(fullLocalPath, fullGridPath);
842                 
843                 if (result)
844                 {
845                         Log("SHUTTLE", Form("CopyFilesToGrid - Copying local file %s to %s succeeded!", 
846                                                 fullLocalPath.Data(), fullGridPath.Data()));
847                         RemoveFile(fullLocalPath);
848                         nTransfer++;
849                 }
850                 else
851                 {
852                         Log("SHUTTLE", Form("CopyFilesToGrid - Copying local file %s to %s FAILED!", 
853                                                 fullLocalPath.Data(), fullGridPath.Data()));
854                         success = kFALSE;
855                 }
856         }
857
858         Log("SHUTTLE", Form("CopyFilesToGrid - %d (over %d) files in folder %s copied to Grid.", 
859                                                 nTransfer, nDirs, dir.Data()));
860
861                 
862         delete dirList;
863         return success;
864 }
865
866 //______________________________________________________________________________________________
867 const char* AliShuttle::GetRefFilePrefix(const char* base, const char* detector)
868 {
869         //
870         // Get folder name of reference files 
871         //
872
873         TString offDetStr(GetOfflineDetName(detector));
874         static TString dir;
875         if (offDetStr == "ITS" || offDetStr == "MUON" || offDetStr == "PHOS")
876         {
877                 dir.Form("%s/%s/%s", base, offDetStr.Data(), detector);
878         } else {
879                 dir.Form("%s/%s", base, offDetStr.Data());
880         }
881         
882         return dir.Data();
883 }
884
885 //______________________________________________________________________________________________
886 void AliShuttle::CleanLocalStorage(const TString& uri)
887 {
888         //
889         // Called in case the preprocessor is declared failed. Remove remaining objects from the local storages.
890         //
891
892         const char* type = 0;
893         if(uri == fgkLocalCDB) {
894                 type = "OCDB";
895         } else if(uri == fgkLocalRefStorage) {
896                 type = "Reference";
897         } else {
898                 AliError(Form("Invalid storage URI: %s", uri.Data()));
899                 return;
900         }
901
902         AliCDBManager* man = AliCDBManager::Instance();
903
904         // open local storage
905         AliCDBStorage *localSto = man->GetStorage(uri);
906         if(!localSto) {
907                 Log("SHUTTLE",
908                         Form("CleanLocalStorage - cannot activate local %s storage", type));
909                 return;
910         }
911
912         TString filename(Form("%s/%s/*/Run*_v%d_s*.root",
913                 localSto->GetBaseFolder().Data(), GetOfflineDetName(fCurrentDetector.Data()), GetCurrentRun()));
914
915         AliDebug(2, Form("filename = %s", filename.Data()));
916
917         Log("SHUTTLE", Form("Removing remaining local files for run %d and detector %s ...",
918                 GetCurrentRun(), fCurrentDetector.Data()));
919
920         RemoveFile(filename.Data());
921
922 }
923
924 //______________________________________________________________________________________________
925 void AliShuttle::RemoveFile(const char* filename)
926 {
927         //
928         // removes local file
929         //
930
931         TString command(Form("rm -f %s", filename));
932
933         Int_t result = gSystem->Exec(command.Data());
934         if(result != 0)
935         {
936                 Log("SHUTTLE", Form("RemoveFile - %s: Cannot remove file %s!",
937                         fCurrentDetector.Data(), filename));
938         }
939 }
940
941 //______________________________________________________________________________________________
942 AliShuttleStatus* AliShuttle::ReadShuttleStatus()
943 {
944         //
945         // Reads the AliShuttleStatus from the CDB
946         //
947
948         if (fStatusEntry){
949                 delete fStatusEntry;
950                 fStatusEntry = 0;
951         }
952
953         Int_t path1 = GetCurrentRun()/10000;
954         try{
955                 fStatusEntry = AliCDBManager::Instance()->GetStorage(GetLocalCDB())
956                         ->Get(Form("/SHUTTLE/%s/%d", fCurrentDetector.Data(), path1), GetCurrentRun());
957         } catch(std::exception& x) {
958                 AliInfo("%s",x.what());
959         }
960
961         if (!fStatusEntry) return 0;
962         fStatusEntry->SetOwner(1);
963
964         AliShuttleStatus* status = dynamic_cast<AliShuttleStatus*> (fStatusEntry->GetObject());
965         if (!status) {
966                 AliError("Invalid object stored to CDB!");
967                 return 0;
968         }
969
970         return status;
971 }
972
973 //______________________________________________________________________________________________
974 Bool_t AliShuttle::WriteShuttleStatus(AliShuttleStatus* status)
975 {
976         //
977         // writes the status for one subdetector
978         //
979
980         if (fStatusEntry){
981                 delete fStatusEntry;
982                 fStatusEntry = 0;
983         }
984
985         Int_t run = GetCurrentRun();
986         Int_t path1 = run/10000;
987         TString path1_string = Form("%d",path1);
988
989         AliCDBId id(AliCDBPath("SHUTTLE", fCurrentDetector, path1_string), run, run);
990
991         fStatusEntry = new AliCDBEntry(status, id, new AliCDBMetaData);
992         fStatusEntry->SetOwner(1);
993
994         Int_t logLevel = AliLog::GetGlobalLogLevel();
995         AliLog::SetGlobalLogLevel(AliLog::kError);
996
997         UInt_t result = AliCDBManager::Instance()->GetStorage(fgkLocalCDB)->Put(fStatusEntry);
998
999         AliLog::SetGlobalLogLevel((AliLog::EType_t)logLevel);
1000
1001         if (!result) {
1002                 Log("SHUTTLE", Form("WriteShuttleStatus - Failed for %s, run %d",
1003                                                 fCurrentDetector.Data(), run));
1004                 return kFALSE;
1005         }
1006         
1007         SendMLDetInfo();
1008
1009         return kTRUE;
1010 }
1011
1012 //______________________________________________________________________________________________
1013 void AliShuttle::UpdateShuttleStatus(AliShuttleStatus::Status newStatus, Bool_t increaseCount)
1014 {
1015         //
1016         // changes the AliShuttleStatus for the given detector and run to the given status
1017         //
1018
1019         if (!fStatusEntry){
1020                 AliError("UNEXPECTED: fStatusEntry empty");
1021                 return;
1022         }
1023
1024         AliShuttleStatus* status = dynamic_cast<AliShuttleStatus*> (fStatusEntry->GetObject());
1025
1026         if (!status){
1027                 Log("SHUTTLE", "UpdateShuttleStatus - UNEXPECTED: status could not be read from current CDB entry");
1028                 return;
1029         }
1030
1031         TString actionStr = Form("UpdateShuttleStatus - %s: Changing state from %s to %s",
1032                                 fCurrentDetector.Data(),
1033                                 status->GetStatusName(),
1034                                 status->GetStatusName(newStatus));
1035         Log("SHUTTLE", actionStr);
1036         SetLastAction(actionStr);
1037
1038         status->SetStatus(newStatus);
1039         if (increaseCount) status->IncreaseCount();
1040
1041         Int_t logLevel = AliLog::GetGlobalLogLevel();
1042         AliLog::SetGlobalLogLevel(AliLog::kError);
1043
1044         AliCDBManager::Instance()->GetStorage(fgkLocalCDB)->Put(fStatusEntry);
1045
1046         AliLog::SetGlobalLogLevel((AliLog::EType_t)logLevel);
1047
1048         SendMLDetInfo();
1049 }
1050
1051 //______________________________________________________________________________________________
1052 void AliShuttle::SendMLDetInfo()
1053 {
1054         //
1055         // sends ML information about the current status of the current detector being processed
1056         //
1057         
1058         AliShuttleStatus* status = dynamic_cast<AliShuttleStatus*> (fStatusEntry->GetObject());
1059         
1060         if (!status){
1061                 Log("SHUTTLE", "SendMLDetInfo - UNEXPECTED: status could not be read from current CDB entry");
1062                 return;
1063         }
1064         
1065         TMonaLisaText  mlStatus(Form("%s_status", fCurrentDetector.Data()), status->GetStatusName());
1066         TMonaLisaValue mlRetryCount(Form("%s_count", fCurrentDetector.Data()), status->GetCount());
1067
1068         TList mlList;
1069         mlList.Add(&mlStatus);
1070         mlList.Add(&mlRetryCount);
1071
1072         TString mlID;
1073         mlID.Form("%d", GetCurrentRun());
1074         fMonaLisa->SendParameters(&mlList, mlID);
1075 }
1076
1077 //______________________________________________________________________________________________
1078 Bool_t AliShuttle::ContinueProcessing()
1079 {
1080         // this function reads the AliShuttleStatus information from CDB and
1081         // checks if the processing should be continued
1082         // if yes it returns kTRUE and updates the AliShuttleStatus with nextStatus
1083
1084         if (!fConfig->HostProcessDetector(fCurrentDetector))
1085                 return kFALSE;
1086
1087         AliPreprocessor* aPreprocessor =
1088                 dynamic_cast<AliPreprocessor*> (fPreprocessorMap.GetValue(fCurrentDetector));
1089         if (!aPreprocessor)
1090         {
1091                 Log("SHUTTLE", Form("ContinueProcessing - %s: no preprocessor registered", fCurrentDetector.Data()));
1092                 return kFALSE;
1093         }
1094
1095         AliShuttleLogbookEntry::Status entryStatus =
1096                 fLogbookEntry->GetDetectorStatus(fCurrentDetector);
1097
1098         if (entryStatus != AliShuttleLogbookEntry::kUnprocessed) {
1099                 Log("SHUTTLE", Form("ContinueProcessing - %s is %s",
1100                                 fCurrentDetector.Data(),
1101                                 fLogbookEntry->GetDetectorStatusName(entryStatus)));
1102                 return kFALSE;
1103         }
1104
1105         // if we get here, according to Shuttle logbook subdetector is in UNPROCESSED state
1106
1107         // check if current run is first unprocessed run for current detector
1108         if (fConfig->StrictRunOrder(fCurrentDetector) &&
1109                 !fFirstUnprocessed[GetDetPos(fCurrentDetector)])
1110         {
1111                 if (fTestMode == kNone)
1112                 {
1113                         Log("SHUTTLE", Form("ContinueProcessing - %s requires strict run ordering"
1114                                             " but this is not the first unprocessed run!",fCurrentDetector.Data()));
1115                         return kFALSE;
1116                 }
1117                 else
1118                 {
1119                         Log("SHUTTLE", Form("ContinueProcessing - In TESTMODE - "
1120                                         "Although %s requires strict run ordering "
1121                                         "and this is not the first unprocessed run, "
1122                                             "the SHUTTLE continues",fCurrentDetector.Data()));
1123                 }
1124         }
1125
1126         // Is the subdetector processed first time for this run?
1127         fFirstProcessing = kFALSE;
1128
1129         AliShuttleStatus* status = ReadShuttleStatus();
1130         if (!status) {
1131                 // first time
1132                 Log("SHUTTLE", Form("ContinueProcessing - %s: Processing first time",
1133                                 fCurrentDetector.Data()));
1134                 status = new AliShuttleStatus(AliShuttleStatus::kStarted);
1135                 fFirstProcessing = kTRUE;
1136                 return WriteShuttleStatus(status);
1137         }
1138
1139         // The following case shouldn't happen if Shuttle Logbook was correctly updated.
1140         // If it happens it may mean Logbook updating failed... let's do it now!
1141         if (status->GetStatus() == AliShuttleStatus::kDone ||
1142             status->GetStatus() == AliShuttleStatus::kFailed ||
1143             status->GetStatus() == AliShuttleStatus::kSkipped) {
1144                 Log("SHUTTLE", Form("ContinueProcessing - %s is already %s. Updating Shuttle Logbook",
1145                                         fCurrentDetector.Data(),
1146                                         status->GetStatusName(status->GetStatus())));
1147                 
1148                 if (status->GetStatus() == AliShuttleStatus::kSkipped)
1149                 {
1150                         UpdateShuttleLogbook(fCurrentDetector.Data(), "DONE");
1151                 }
1152                 else
1153                         UpdateShuttleLogbook(fCurrentDetector.Data(), status->GetStatusName(status->GetStatus()));
1154                         
1155                 return kFALSE;
1156         }
1157
1158         if (status->GetStatus() == AliShuttleStatus::kStoreStarted || status->GetStatus() == AliShuttleStatus::kStoreDelayed ||status->GetStatus() == AliShuttleStatus::kStoreError) {
1159                 Log("SHUTTLE",
1160                         Form("ContinueProcessing - %s: Grid storage of one or more "
1161                                 "objects failed. Trying again now",
1162                                 fCurrentDetector.Data()));
1163                 StoreOCDB();
1164                 return kFALSE;
1165         }
1166
1167         // if we get here, there is a restart
1168         Bool_t cont = kFALSE;
1169
1170         // abort conditions
1171         if (status->GetCount() >= fConfig->GetMaxRetries()) {
1172                 Log("SHUTTLE", Form("ContinueProcessing - %s failed %d times in status %s - "
1173                                 "Updating Shuttle Logbook", fCurrentDetector.Data(),
1174                                 status->GetCount(), status->GetStatusName()));
1175                 UpdateShuttleLogbook(fCurrentDetector.Data(), "FAILED");
1176                 UpdateShuttleStatus(AliShuttleStatus::kFailed);
1177
1178                 // there may still be objects in local OCDB and reference storage
1179                 // and FXS databases may be not updated: do it now!
1180                 
1181                 // TODO Currently disabled, we want to keep files in case of failure!
1182                 // CleanLocalStorage(fgkLocalCDB);
1183                 // CleanLocalStorage(fgkLocalRefStorage);
1184                 // UpdateTableFailCase();
1185                 
1186                 // Send mail to detector expert!
1187                 Log("SHUTTLE", Form("ContinueProcessing - Sending mail to %s expert...", 
1188                                     fCurrentDetector.Data()));
1189                 // det experts in to
1190                 TString to="";
1191                 TIter *iterExperts = 0;
1192                 iterExperts = new TIter(fConfig->GetResponsibles(fCurrentDetector));
1193                 TObjString *anExpert=0;
1194                 while ((anExpert = (TObjString*) iterExperts->Next()))
1195                         {
1196                                 to += Form("%s, \n", anExpert->GetName());
1197                         }
1198                 delete iterExperts;
1199                 
1200                 if (to.Length() > 0)
1201                         to.Remove(to.Length()-3);
1202                 AliDebug(2, Form("to: %s",to.Data()));
1203
1204                 if (to.IsNull()) {
1205                         Log("SHUTTLE", Form("List of %s responsibles not set!", fCurrentDetector.Data()));
1206                         return kFALSE;
1207                 }
1208
1209                 Log(fCurrentDetector.Data(), Form("ContinueProcessing - Sending mail to %s expert(s):", 
1210                                     fCurrentDetector.Data()));
1211                 Log(fCurrentDetector.Data(), Form("\n%s", to.Data()));
1212                 if (!SendMail(kPPEMail))
1213                         Log("SHUTTLE", Form("ContinueProcessing - Could not send mail to %s expert",
1214                                             fCurrentDetector.Data()));
1215
1216         } else {
1217                 Log("SHUTTLE", Form("ContinueProcessing - %s: restarting. "
1218                                 "Aborted before with %s. Retry number %d.", fCurrentDetector.Data(),
1219                                 status->GetStatusName(), status->GetCount()));
1220                 Bool_t increaseCount = kTRUE;
1221                 if (status->GetStatus() == AliShuttleStatus::kDCSError || 
1222                     status->GetStatus() == AliShuttleStatus::kDCSStarted ||
1223                     status->GetStatus() == AliShuttleStatus::kFXSError ||
1224                     status->GetStatus() == AliShuttleStatus::kOCDBError)
1225                                 increaseCount = kFALSE;
1226                                 
1227                 UpdateShuttleStatus(AliShuttleStatus::kStarted, increaseCount);
1228                 cont = kTRUE;
1229         }
1230
1231         return cont;
1232 }
1233
1234 //______________________________________________________________________________________________
1235 void AliShuttle::SendMLRunInfo(const char* status)
1236 {
1237         // 
1238         // Send information about this run to ML
1239         
1240         TMonaLisaText  mlStatus("SHUTTLE_status", status);
1241         TString runType(fLogbookEntry->GetRunType());
1242         if (strlen(fLogbookEntry->GetRunParameter("log")) > 0){
1243
1244                 runType += "(";
1245                 runType += fLogbookEntry->GetRunParameter("log");
1246                 runType += ")";
1247         }
1248         if (fLogbookEntry->GetDATestMode()){
1249                 runType += " (DATest)";
1250         }
1251         TMonaLisaText  mlRunType("SHUTTLE_runtype", runType);
1252
1253         TList mlList;
1254         mlList.Add(&mlStatus);
1255         mlList.Add(&mlRunType);
1256
1257         TString mlID;
1258         mlID.Form("%d", GetCurrentRun());
1259         fMonaLisa->SendParameters(&mlList, mlID);       
1260 }
1261
1262 //______________________________________________________________________________________________
1263 Int_t AliShuttle::GetMem(Int_t pid)
1264 {
1265         // invokes ps to get the memory consumption of the process <pid>
1266         // returns -1 in case of error
1267         
1268         TString checkStr;
1269         checkStr.Form("ps -o vsize --pid %d | tail -n 1", pid);
1270         FILE* pipe = gSystem->OpenPipe(checkStr, "r");
1271         if (!pipe)
1272         {
1273                 Log("SHUTTLE", Form("Process - Error: "
1274                         "Could not open pipe to %s", checkStr.Data()));
1275                 return -1;
1276         }
1277                 
1278         char buffer[100];
1279         if (!fgets(buffer, 100, pipe))
1280         {
1281                 Log("SHUTTLE", "Process - Error: ps did not return anything");
1282                 gSystem->ClosePipe(pipe);
1283                 return -1;
1284         }
1285         gSystem->ClosePipe(pipe);
1286         
1287         //Log("SHUTTLE", Form("ps returned %s", buffer));
1288         
1289         Int_t mem = 0;
1290         if ((sscanf(buffer, "%d\n", &mem) != 1) || !mem)
1291         {
1292                 Log("SHUTTLE", "Process - Error: Could not parse output of ps");
1293                 return -1;
1294         }
1295         
1296         return mem;
1297 }
1298
1299 //______________________________________________________________________________________________
1300 Bool_t AliShuttle::Process(AliShuttleLogbookEntry* entry)
1301 {
1302         //
1303         // Makes data retrieval for all detectors in the configuration.
1304         // entry: Shuttle logbook entry, contains run paramenters and status of detectors
1305         // (Unprocessed, Inactive, Failed or Done).
1306         // Returns kFALSE in case of error occured and kTRUE otherwise
1307         //
1308
1309         if (!entry) return kFALSE;
1310
1311         fLogbookEntry = entry;
1312
1313         Log("SHUTTLE", Form("\t\t\t^*^*^*^*^*^*^*^*^*^*^*^* run %d: START ^*^*^*^*^*^*^*^*^*^*^*^*",
1314                                         GetCurrentRun()));
1315
1316         CountOpenRuns();
1317         
1318         // Send the information to ML
1319         SendMLRunInfo("Processing");
1320
1321         if (fLogbookEntry->IsDone())
1322         {
1323                 Log("SHUTTLE","Process - Shuttle is already DONE. Updating logbook");
1324                 UpdateShuttleLogbook("shuttle_done");
1325                 fLogbookEntry = 0;
1326                 return kTRUE;
1327         }
1328
1329         // read test mode if flag is set
1330         if (fReadTestMode)
1331         {
1332                 fTestMode = kNone;
1333                 TString logEntry(entry->GetRunParameter("log"));
1334                 //printf("log entry = %s\n", logEntry.Data());
1335                 TString searchStr("Testmode: ");
1336                 Int_t pos = logEntry.Index(searchStr.Data());
1337                 //printf("%d\n", pos);
1338                 if (pos >= 0)
1339                 {
1340                         TSubString subStr = logEntry(pos + searchStr.Length(), logEntry.Length());
1341                         //printf("%s\n", subStr.String().Data());
1342                         TString newStr(subStr.Data());
1343                         TObjArray* token = newStr.Tokenize(' ');
1344                         if (token)
1345                         {
1346                                 //token->Print();
1347                                 TObjString* tmpStr = dynamic_cast<TObjString*> (token->First());
1348                                 if (tmpStr)
1349                                 {
1350                                         Int_t testMode = tmpStr->String().Atoi();
1351                                         if (testMode > 0)
1352                                         {
1353                                                 Log("SHUTTLE", Form("Process - Enabling test mode %d", testMode));
1354                                                 SetTestMode((TestMode) testMode);
1355                                         }
1356                                 }
1357                                 delete token;          
1358                         }
1359                 }
1360         }
1361                 
1362         fLogbookEntry->Print("all");
1363
1364         // Initialization
1365         Bool_t hasError = kFALSE;
1366
1367         // Set the CDB and Reference folders according to the year
1368
1369         // build cdb paths (repeat each time, run might be a DATest run)
1370         if (!fLogbookEntry->GetDATestMode()){
1371                 fgkMainCDB.Form("alien://folder=%s%d/OCDB?user=alidaq?cacheFold=/tmp/OCDBCache", 
1372                                 fConfig->GetAlienPath(), GetCurrentYear());
1373                 
1374                 fgkMainRefStorage.Form("alien://folder=%s%d/Reference?user=alidaq?cacheFold=/tmp/OCDBCache", 
1375                                        fConfig->GetAlienPath(), GetCurrentYear());
1376         }
1377         else {
1378                 fgkMainCDB.Form("alien://folder=%s%d/DATest/OCDB?user=alidaq?cacheFold=/tmp/OCDBCache",
1379                                 fConfig->GetAlienPath(), GetCurrentYear());
1380                 
1381                 fgkMainRefStorage.Form("alien://folder=%s%d/DATest/Reference?user=alidaq?cacheFold=/tmp/OCDBCache",
1382                                        fConfig->GetAlienPath(), GetCurrentYear());
1383         }
1384
1385         AliDebug(2,Form("Main CDB storage = %s",fgkMainCDB.Data()));
1386         AliDebug(2,Form("Main Reference storage = %s",fgkMainRefStorage.Data()));
1387
1388         // Loop on detectors in the configuration
1389         TIter iter(fConfig->GetDetectors());
1390         TObjString* aDetector = 0;
1391
1392         Bool_t first = kTRUE;
1393
1394         while ((aDetector = (TObjString*) iter.Next()))
1395         {
1396                 fCurrentDetector = aDetector->String();
1397
1398                 if (ContinueProcessing() == kFALSE) 
1399                         continue;
1400                 
1401                 if (first)
1402                 {
1403                   // only read QueryCDB when needed and only once
1404                   AliCDBStorage *mainCDBSto = AliCDBManager::Instance()->GetStorage(fgkMainCDB);
1405                   if(mainCDBSto) mainCDBSto->QueryCDB(GetCurrentRun());
1406                   AliCDBStorage *mainRefSto = AliCDBManager::Instance()->GetStorage(fgkMainRefStorage);
1407                   if(mainRefSto) mainRefSto->QueryCDB(GetCurrentRun());
1408                   first = kFALSE;
1409                 }
1410
1411                 Log("SHUTTLE", Form("\t\t\t****** run %d - %s: START  ******",
1412                                                 GetCurrentRun(), aDetector->GetName()));
1413
1414                 for(Int_t iSys=0;iSys<4;iSys++) fFXSCalled[iSys]=kFALSE;
1415                 
1416                 Int_t initialMem = GetMem(getpid());
1417                 Log("SHUTTLE", Form("Memory consumption before forking is %d", initialMem));
1418
1419                 Log(fCurrentDetector.Data(), "Process - Starting processing");
1420
1421                 Int_t pid = fork();
1422
1423                 if (pid < 0)
1424                 {
1425                         Log("SHUTTLE", "Process - ERROR: Forking failed");
1426                 }
1427                 else if (pid > 0)
1428                 {
1429                         // parent
1430                         Log("SHUTTLE", Form("Process - In parent process of %d - %s: Starting monitoring",
1431                                                         GetCurrentRun(), aDetector->GetName()));
1432
1433                         Long_t begin = time(0);
1434
1435                         int status; // to be used with waitpid, on purpose an int (not Int_t)!
1436                         while (waitpid(pid, &status, WNOHANG) == 0)
1437                         {
1438                                 Long_t expiredTime = time(0) - begin;
1439
1440                                 // the run-dependent timeout is the timeout from the configuration plus a twentieth of
1441                                 // the run duration, e.g. 3 additional minutes for 1h run or 1/2h for a 10h run
1442                                 Int_t runDepTimeOut = fConfig->GetPPTimeOut() + (GetCurrentEndTime() - GetCurrentStartTime()) * 0.05;
1443                                 if (expiredTime > runDepTimeOut)
1444                                 {
1445                                         TString logMsg;
1446                                         AliShuttleStatus *currentStatus = ReadShuttleStatus();
1447                                         AliShuttleStatus::Status newStatus = AliShuttleStatus::kInvalid;
1448                                         
1449                                         if (currentStatus->GetStatus() == AliShuttleStatus::kDCSStarted)
1450                                         {
1451                                                 // in case the pp goes in TimeOut while retrieving the DCS DPs
1452                                                 // set status to kDCSError
1453                                                 
1454                                                 logMsg.Form("Process - Process of %s timed out while retrieving the DCS DataPoints. Run time: %ld seconds. Killing... and setting status to DCSError.",
1455                                                                 fCurrentDetector.Data(), expiredTime);
1456                                                 newStatus = AliShuttleStatus::kDCSError;
1457                                         }
1458                                         else if (currentStatus->GetStatus() <= AliShuttleStatus::kPPDone)
1459                                         {
1460                                                 // in case pp not yet done set status to kPPTimeOut
1461                                         
1462                                                 logMsg.Form("Process - Process of %s timed out. Run time: %ld seconds. Killing...",
1463                                                                 fCurrentDetector.Data(), expiredTime);
1464                                                 newStatus = AliShuttleStatus::kPPTimeOut;
1465                                         }
1466                                         else if (currentStatus->GetStatus() == AliShuttleStatus::kStoreStarted)
1467                                         {
1468                                                 // in case the pp goes in TimeOut while storing the objects in the OCDB
1469                                                 // set status to kStoreError
1470                                                 
1471                                                 logMsg.Form("Process - Process of %s timed out while storing the OCDB object. Run time: %ld seconds. Killing... and setting status to StoreError.",
1472                                                                 fCurrentDetector.Data(), expiredTime);
1473                                                 newStatus = AliShuttleStatus::kStoreError;
1474                                         }
1475                                         else 
1476                                         {
1477                                                 // in other cases don't change the status
1478                                                 
1479                                                 logMsg.Form("Process - Process of %s timed out in status = %s. Run time: %ld seconds. Killing... without changing the status",
1480                                                                 fCurrentDetector.Data(), currentStatus->GetStatusName(), expiredTime);
1481                                         }
1482                                 
1483                                         Log("SHUTTLE", logMsg);
1484                                         Log(fCurrentDetector, logMsg);
1485
1486                                         kill(pid, 9);
1487
1488                                         if (newStatus != AliShuttleStatus::kInvalid)
1489                                                 UpdateShuttleStatus(newStatus);
1490                                         hasError = kTRUE;
1491
1492                                         gSystem->Sleep(1000);
1493                                 }
1494                                 else
1495                                 {
1496                                         gSystem->Sleep(1000);
1497                                         
1498                                         Int_t mem = GetMem(pid);
1499
1500                                         if (mem < 0)
1501                                                 continue;
1502                                                 
1503                                         mem -= initialMem;
1504                                         if (mem < 0)
1505                                                 mem = 0;
1506                                         
1507                                         if (expiredTime % 60 == 0)
1508                                         {
1509                                                 Log("SHUTTLE", Form("Process - %s: Checking process. "
1510                                                         "Run time: %ld seconds - Memory consumption: %d KB",
1511                                                         fCurrentDetector.Data(), expiredTime, mem));
1512                                                 SendAlive();
1513                                         }
1514                                         
1515                                         if (mem > fConfig->GetPPMaxMem())
1516                                         {
1517                                                 TString tmp;
1518                                                 tmp.Form("Process - Process exceeds maximum allowed memory "
1519                                                         "(%d KB > %d KB). Killing...",
1520                                                         mem, fConfig->GetPPMaxMem());
1521                                                 Log("SHUTTLE", tmp);
1522                                                 Log(fCurrentDetector, tmp);
1523         
1524                                                 kill(pid, 9);
1525         
1526                                                 UpdateShuttleStatus(AliShuttleStatus::kPPOutOfMemory);
1527                                                 hasError = kTRUE;
1528         
1529                                                 gSystem->Sleep(1000);
1530                                         }
1531                                 }
1532                         }
1533
1534                         Log("SHUTTLE", Form("Process - In parent process of %d - %s: Client has terminated.",
1535                                                                 GetCurrentRun(), aDetector->GetName()));
1536
1537                         if (WIFEXITED(status))
1538                         {
1539                                 Int_t returnCode = WEXITSTATUS(status);
1540
1541                                 Log("SHUTTLE", Form("Process - %s: the return code is %d", fCurrentDetector.Data(),
1542                                                                                 returnCode));
1543
1544                                 if (returnCode == 0) hasError = kTRUE;
1545                         }
1546                 }
1547                 else if (pid == 0)
1548                 {
1549                         // child
1550                         Log("SHUTTLE", Form("Process - In child process of %d - %s", GetCurrentRun(),
1551                                 aDetector->GetName()));
1552
1553                         Log("SHUTTLE", Form("Process - Redirecting output to %s log",fCurrentDetector.Data()));
1554
1555                         if ((freopen(GetLogFileName(fCurrentDetector), "a", stdout)) == 0)
1556                         {
1557                                 Log("SHUTTLE", "Process - Could not freopen stdout");
1558                         }
1559                         else
1560                         {
1561                                 fOutputRedirected = kTRUE;
1562                                 if ((dup2(fileno(stdout), fileno(stderr))) < 0)
1563                                         Log("SHUTTLE", "Process - Could not redirect stderr");
1564                                 
1565                         }
1566
1567                         Log("SHUTTLE", "Executing TGrid::Connect");
1568                         TGrid::Connect("alien://");
1569                         
1570                         TString wd = gSystem->WorkingDirectory();
1571                         Int_t dir_lev1 = GetCurrentRun()/10000;
1572                         TString tmpDir = Form("%s/%d/%d/%s_process", GetShuttleTempDir(), 
1573                                 dir_lev1, GetCurrentRun(), fCurrentDetector.Data());
1574                         
1575                         Int_t result = gSystem->GetPathInfo(tmpDir.Data(), 0, (Long64_t*) 0, 0, 0);
1576                         if (!result) // temp dir already exists!
1577                         {
1578                                 Log(fCurrentDetector.Data(), 
1579                                         Form("Process - %s dir already exists! Removing...", tmpDir.Data()));
1580                                 gSystem->Exec(Form("rm -rf %s",tmpDir.Data()));         
1581                         } 
1582                         
1583                         if (gSystem->mkdir(tmpDir.Data(), 1))
1584                         {
1585                                 Log(fCurrentDetector.Data(), "Process - could not make temp directory!!");
1586                                 gSystem->Exit(1);
1587                         }
1588                         
1589                         if (!gSystem->ChangeDirectory(tmpDir.Data())) 
1590                         {
1591                                 Log(fCurrentDetector.Data(), "Process - could not change directory!!");
1592                                 gSystem->Exit(1);                       
1593                         }
1594                         
1595                         Int_t success = ProcessCurrentDetector();
1596
1597                         gSystem->ChangeDirectory(wd.Data());
1598                                                 
1599                         if (success == 1) // Preprocessor finished successfully!
1600                         { 
1601                                 // remove temporary folder or DCS map
1602                                 if (!fConfig->KeepTempFolder())
1603                                 {
1604                                         gSystem->Exec(Form("rm -rf %s",tmpDir.Data()));
1605                                 } else if (!fConfig->KeepDCSMap())
1606                                 {
1607                                         gSystem->Exec(Form("rm -f %s/DCSMap.root",tmpDir.Data()));
1608                                 }
1609                                 
1610                                 // Update time_processed field in FXS DB
1611                                 if (UpdateTable() == kFALSE)
1612                                         Log("SHUTTLE", Form("Process - %s: Could not update FXS databases!", 
1613                                                         fCurrentDetector.Data()));
1614
1615                                 // Transfer the data from local storage to main storage (Grid)
1616                                 if (StoreOCDB() == kFALSE)
1617                                         success = kFALSE;
1618                         } 
1619                         else if (success == 0)
1620                         {
1621                                 Log("SHUTTLE", 
1622                                         Form("\t\t\t****** run %d - %s: ERROR ******",
1623                                                 GetCurrentRun(), aDetector->GetName()));
1624                         }
1625
1626                         for (UInt_t iSys=0; iSys<4; iSys++)
1627                         {
1628                                 if (fFXSCalled[iSys]) fFXSlist[iSys].Clear();
1629                         }
1630
1631                         Log("SHUTTLE", Form("Process - Client process of %d - %s is exiting now with %d.",
1632                                                         GetCurrentRun(), aDetector->GetName(), success));
1633
1634                         // the client exits here
1635                         gSystem->Exit(success);
1636
1637                         AliError("We should never get here!!!");
1638                 }
1639         }
1640
1641         Log("SHUTTLE", Form("\t\t\t^*^*^*^*^*^*^*^*^*^*^*^* run %d: FINISH ^*^*^*^*^*^*^*^*^*^*^*^*",
1642                                                         GetCurrentRun()));
1643
1644         //check if shuttle is done for this run, if so update logbook
1645         TObjArray checkEntryArray;
1646         checkEntryArray.SetOwner(1);
1647         TString whereClause = Form("where run=%d", GetCurrentRun());
1648         if (!QueryShuttleLogbook(whereClause.Data(), checkEntryArray) || 
1649                         checkEntryArray.GetEntries() == 0) {
1650                 Log("SHUTTLE", Form("Process - Warning: Cannot check status of run %d on Shuttle logbook!",
1651                                                 GetCurrentRun()));
1652                 return hasError == kFALSE;
1653         }
1654
1655         AliShuttleLogbookEntry* checkEntry = dynamic_cast<AliShuttleLogbookEntry*>
1656                                                 (checkEntryArray.At(0));
1657
1658         if (checkEntry)
1659         {
1660                 if (checkEntry->IsDone())
1661                 {
1662                         Log("SHUTTLE","Process - Shuttle is DONE. Updating logbook");
1663                         UpdateShuttleLogbook("shuttle_done");
1664                 }
1665                 else
1666                 {
1667                         for (UInt_t iDet=0; iDet<NDetectors(); iDet++)
1668                         {
1669                                 if (checkEntry->GetDetectorStatus(iDet) == AliShuttleLogbookEntry::kUnprocessed)
1670                                 {
1671                                         AliDebug(2, Form("Run %d: setting %s as \"not first time unprocessed\"",
1672                                                         checkEntry->GetRun(), GetDetName(iDet)));
1673                                         fFirstUnprocessed[iDet] = kFALSE;
1674                                 }
1675                         }
1676                         SendMLRunInfo("Pending");
1677                 }
1678         }
1679
1680         fLogbookEntry = 0;
1681
1682         return hasError == kFALSE;
1683 }
1684
1685 //______________________________________________________________________________________________
1686 Int_t AliShuttle::ProcessCurrentDetector()
1687 {
1688         //
1689         // Makes data retrieval just for a specific detector (fCurrentDetector).
1690         // Threre should be a configuration for this detector.
1691
1692         Log("SHUTTLE", Form("ProcessCurrentDetector - Retrieving values for %s, run %d", 
1693                                                 fCurrentDetector.Data(), GetCurrentRun()));
1694
1695         TString wd = gSystem->WorkingDirectory();
1696         
1697         if (!CleanReferenceStorage(fCurrentDetector.Data()))
1698                 return 0;
1699         
1700         gSystem->ChangeDirectory(wd.Data());
1701         
1702         // call preprocessor
1703         AliPreprocessor* aPreprocessor =
1704                 dynamic_cast<AliPreprocessor*> (fPreprocessorMap.GetValue(fCurrentDetector));
1705
1706         // check if the preprocessor wants to process this run type
1707         if (aPreprocessor->ProcessRunType() == kFALSE)
1708         {
1709                 UpdateShuttleStatus(AliShuttleStatus::kSkipped);
1710                 UpdateShuttleLogbook(fCurrentDetector, "DONE");
1711                 if (!UpdateTableSkippedCase(fCurrentDetector.Data()))
1712                 {
1713                         AliError(Form("Could not update FXS tables for run %d !", GetCurrentRun()));
1714                 }
1715                 Log(fCurrentDetector, Form("ProcessCurrentDetector - %s preprocessor is not interested in this run type", fCurrentDetector.Data()));
1716         
1717                 return 2;
1718         }
1719         
1720         // checking if OCDB is reachable
1721         AliCDBEntry* testEntry = GetFromOCDB("SHUTTLE","GRP/CTP/DummyConfig");
1722         if (!testEntry){
1723                 // OCDB is not accessible, going in OCDBError for current detector
1724                 AliError("OCDB Test entry not accessible");
1725                 UpdateShuttleStatus(AliShuttleStatus::kOCDBError);
1726                 return 0;
1727         }
1728
1729         TMap* dcsMap = new TMap();
1730         
1731         aPreprocessor->Initialize(GetCurrentRun(), GetCurrentStartTime(), GetCurrentEndTime());
1732
1733         Bool_t processDCS = aPreprocessor->ProcessDCS();
1734
1735         if (!processDCS)
1736         {
1737                 Log(fCurrentDetector, "ProcessCurrentDetector -"
1738                         " The preprocessor requested to skip the retrieval of DCS values");
1739         }
1740         else if (fTestMode & kSkipDCS)
1741         {
1742                 Log(fCurrentDetector, "ProcessCurrentDetector - In TESTMODE: Skipping DCS processing");
1743         } 
1744         else if (fTestMode & kErrorDCS)
1745         {
1746                 Log(fCurrentDetector, "ProcessCurrentDetector - In TESTMODE: Simulating DCS error");
1747                 UpdateShuttleStatus(AliShuttleStatus::kDCSStarted);
1748                 UpdateShuttleStatus(AliShuttleStatus::kDCSError);
1749                 delete dcsMap;
1750                 return 0;
1751         } else {
1752
1753                 UpdateShuttleStatus(AliShuttleStatus::kDCSStarted);
1754
1755                 // Query DCS archive
1756                 Int_t nServers = fConfig->GetNServers(fCurrentDetector);
1757                 
1758                 for (int iServ=0; iServ<nServers; iServ++)
1759                 {
1760                 
1761                         TString host(fConfig->GetDCSHost(fCurrentDetector, iServ));
1762                         Int_t port = fConfig->GetDCSPort(fCurrentDetector, iServ);
1763                         Int_t multiSplit = fConfig->GetMultiSplit(fCurrentDetector, iServ);
1764
1765                         Log(fCurrentDetector, Form("ProcessCurrentDetector -"
1766                                         " Querying DCS Amanda server %s:%d (%d of %d)", 
1767                                         host.Data(), port, iServ+1, nServers));
1768                         
1769                         TMap* aliasMap = 0;
1770                         TMap* dpMap = 0;
1771
1772                         if (fConfig->GetDCSAliases(fCurrentDetector, iServ)->GetEntries() > 0)
1773                         {
1774                                 Log(fCurrentDetector, Form("Querying %d DCS aliases", fConfig->GetDCSAliases(fCurrentDetector, iServ)->GetEntries()));
1775                                 aliasMap = GetValueSet(host, port, 
1776                                                 fConfig->GetDCSAliases(fCurrentDetector, iServ), 
1777                                                 kAlias, multiSplit);
1778                                 if (!aliasMap)
1779                                 {
1780                                         Log(fCurrentDetector, 
1781                                                 Form("ProcessCurrentDetector -"
1782                                                         " Error retrieving DCS aliases from server %s."
1783                                                         " Sending mail to DCS experts!", host.Data()));
1784                                         UpdateShuttleStatus(AliShuttleStatus::kDCSError);
1785                                         
1786                                         if (!SendMail(kDCSEMail))
1787                                                 Log("SHUTTLE", Form("ProcessCurrentDetector - "
1788                                                                     "Could not send mail to DCS experts!"));
1789
1790                                         delete dcsMap;
1791                                         return 0;
1792                                 }
1793                         }
1794                         
1795                         if (fConfig->GetDCSDataPoints(fCurrentDetector, iServ)->GetEntries() > 0)
1796                         {
1797                                 Log(fCurrentDetector, Form("Querying %d DCS data points", fConfig->GetDCSDataPoints(fCurrentDetector, iServ)->GetEntries()));
1798                                 dpMap = GetValueSet(host, port, 
1799                                                 fConfig->GetDCSDataPoints(fCurrentDetector, iServ), 
1800                                                 kDP, multiSplit);
1801                                 if (!dpMap)
1802                                 {
1803                                         Log(fCurrentDetector, 
1804                                                 Form("ProcessCurrentDetector -"
1805                                                         " Error retrieving DCS data points from server %s."
1806                                                         " Sending mail to DCS experts!", host.Data()));
1807                                         UpdateShuttleStatus(AliShuttleStatus::kDCSError);
1808                                         
1809                                         if (!SendMail(kDCSEMail))
1810                                                 Log("SHUTTLE", Form("ProcessCurrentDetector - "
1811                                                                     "Could not send mail to DCS experts!"));
1812                                         
1813                                         if (aliasMap) delete aliasMap;
1814                                         delete dcsMap;
1815                                         return 0;
1816                                 }                               
1817                         }
1818                         
1819                         // merge aliasMap and dpMap into dcsMap
1820                         if(aliasMap) {
1821                                 TIter iter(aliasMap);
1822                                 TObjString* key = 0;
1823                                 while ((key = (TObjString*) iter.Next()))
1824                                         dcsMap->Add(key, aliasMap->GetValue(key->String()));
1825                                 
1826                                 aliasMap->SetOwner(kFALSE);
1827                                 delete aliasMap;
1828                         }       
1829                         
1830                         if(dpMap) {
1831                                 TIter iter(dpMap);
1832                                 TObjString* key = 0;
1833                                 while ((key = (TObjString*) iter.Next()))
1834                                         dcsMap->Add(key, dpMap->GetValue(key->String()));
1835                                 
1836                                 dpMap->SetOwner(kFALSE);
1837                                 delete dpMap;
1838                         }
1839                 }
1840         }
1841         
1842         // save map into file, to help debugging in case of preprocessor error
1843         TFile* f = TFile::Open("DCSMap.root","recreate");
1844         f->cd();
1845         dcsMap->Write("DCSMap", TObject::kSingleKey);
1846         f->Close();
1847         delete f;
1848         
1849         // DCS Archive DB processing successful. Call Preprocessor!
1850         UpdateShuttleStatus(AliShuttleStatus::kPPStarted);
1851
1852         fFXSError = -1; // this variable is kTRUE after ::Process if an FXS error occured
1853         
1854         UInt_t returnValue = aPreprocessor->Process(dcsMap);
1855         
1856         if (fFXSError!=-1) {
1857                 UpdateShuttleStatus(AliShuttleStatus::kFXSError);
1858                 SendMail(kFXSEMail, fFXSError);
1859                 dcsMap->DeleteAll();
1860                 delete dcsMap;
1861                 return 0;
1862         }
1863
1864         if (returnValue > 0) // Preprocessor error!
1865         {
1866                 Log(fCurrentDetector, Form("ProcessCurrentDetector - "
1867                                 "Preprocessor failed. Process returned %d.", returnValue));
1868                 UpdateShuttleStatus(AliShuttleStatus::kPPError);
1869                 dcsMap->DeleteAll();
1870                 delete dcsMap;
1871                 return 0;
1872         }
1873         
1874         // preprocessor ok!
1875         UpdateShuttleStatus(AliShuttleStatus::kPPDone);
1876         Log(fCurrentDetector, Form("ProcessCurrentDetector - %s preprocessor returned success",
1877                                 fCurrentDetector.Data()));
1878
1879         dcsMap->DeleteAll();
1880         delete dcsMap;
1881
1882         return 1;
1883 }
1884
1885 //______________________________________________________________________________________________
1886 void AliShuttle::CountOpenRuns()
1887 {
1888         // Query DAQ's Shuttle logbook and sends the number of open runs to ML
1889         
1890         SendAlive();
1891         
1892         // check connection, in case connect
1893         if (!Connect(4)) 
1894                 return;
1895
1896         TString sqlQuery;
1897         sqlQuery = Form("select count(*) from %s where shuttle_done=0", fConfig->GetShuttlelbTable());
1898         
1899         TSQLResult* aResult = fServer[4]->Query(sqlQuery);
1900         if (!aResult) {
1901                 AliError(Form("Can't execute query <%s>!", sqlQuery.Data()));
1902                 return;
1903         }
1904
1905         AliDebug(2,Form("Query = %s", sqlQuery.Data()));
1906         
1907         if (aResult->GetRowCount() == 0) {
1908                 AliError(Form("No result for query %s received", sqlQuery.Data()));
1909                 return;
1910         }
1911
1912         if (aResult->GetFieldCount() != 1) {
1913                 AliError(Form("Invalid field count for query %s received", sqlQuery.Data()));
1914                 return;
1915         }
1916
1917         TSQLRow* aRow = aResult->Next();
1918         if (!aRow) {
1919                 AliError(Form("Could not receive result of query %s", sqlQuery.Data()));
1920                 return;
1921         }
1922         
1923         TString result(aRow->GetField(0), aRow->GetFieldLength(0));
1924         Int_t count = result.Atoi();
1925         
1926         Log("SHUTTLE", Form("%d unprocessed runs", count));
1927         
1928         delete aRow;
1929         delete aResult;
1930
1931         TMonaLisaValue mlStatus("SHUTTLE_openruns", count);
1932
1933         TList mlList;
1934         mlList.Add(&mlStatus);
1935
1936         fMonaLisa->SendParameters(&mlList, "__PROCESSINGINFO__");
1937 }
1938
1939 //______________________________________________________________________________________________
1940 Bool_t AliShuttle::QueryShuttleLogbook(const char* whereClause,
1941                 TObjArray& entries)
1942 {
1943         // Query DAQ's Shuttle logbook and fills detector status object.
1944         // Call QueryRunParameters to query DAQ logbook for run parameters.
1945         //
1946
1947         entries.SetOwner(1);
1948
1949         // check connection, in case connect
1950         if (!Connect(4)) return kFALSE;
1951
1952         TString sqlQuery;
1953         sqlQuery = Form("select * from %s %s order by run", fConfig->GetShuttlelbTable(), whereClause);
1954
1955         TSQLResult* aResult = fServer[4]->Query(sqlQuery);
1956         if (!aResult) {
1957                 AliError(Form("Can't execute query <%s>!", sqlQuery.Data()));
1958                 return kFALSE;
1959         }
1960
1961         AliDebug(2,Form("Query = %s", sqlQuery.Data()));
1962
1963         if(aResult->GetRowCount() == 0) {
1964                 Log("SHUTTLE", "No entries in Shuttle Logbook match request");
1965                 delete aResult;
1966                 return kTRUE;
1967         }
1968
1969         // TODO Check field count!
1970         const UInt_t nCols = 26;
1971         if (aResult->GetFieldCount() != (Int_t) nCols) {
1972                 Log("SHUTTLE", "Invalid SQL result field number!");
1973                 delete aResult;
1974                 return kFALSE;
1975         }
1976
1977         TSQLRow* aRow;
1978         while ((aRow = aResult->Next())) {
1979                 TString runString(aRow->GetField(0), aRow->GetFieldLength(0));
1980                 Int_t run = runString.Atoi();
1981
1982                 AliShuttleLogbookEntry *entry = QueryRunParameters(run);
1983                 if (!entry)
1984                         continue;
1985
1986                 // DA test mode flag
1987                 TString daTestModeString(aRow->GetField(2), aRow->GetFieldLength(2)); // field 2 = DA test mode flag 
1988                 Bool_t daTestMode = (Bool_t)daTestModeString.Atoi();
1989                 entry->SetDATestMode(daTestMode);
1990
1991                 // loop on detectors
1992                 for(UInt_t ii = 0; ii < nCols; ii++)
1993                         entry->SetDetectorStatus(aResult->GetFieldName(ii), aRow->GetField(ii));
1994
1995                 entries.AddLast(entry);
1996                 delete aRow;
1997         }
1998
1999         delete aResult;
2000         return kTRUE;
2001 }
2002
2003 //______________________________________________________________________________________________
2004 AliShuttleLogbookEntry* AliShuttle::QueryRunParameters(Int_t run)
2005 {
2006         //
2007         // Retrieve run parameters written in the DAQ logbook and sets them into AliShuttleLogbookEntry object
2008         //
2009
2010         // check connection, in case connect
2011         if (!Connect(4))
2012                 return 0;
2013
2014         TString sqlQuery;
2015         sqlQuery.Form("select * from %s where run=%d", fConfig->GetDAQlbTable(), run);
2016
2017         TSQLResult* aResult = fServer[4]->Query(sqlQuery);
2018         if (!aResult) {
2019                 Log("SHUTTLE", Form("Can't execute query <%s>!", sqlQuery.Data()));
2020                 return 0;
2021         }
2022
2023         if (aResult->GetRowCount() == 0) {
2024                 Log("SHUTTLE", Form("QueryRunParameters - No entry in DAQ Logbook for run %d. Skipping", run));
2025                 delete aResult;
2026                 return 0;
2027         }
2028
2029         if (aResult->GetRowCount() > 1) {
2030                 Log("SHUTTLE", Form("QueryRunParameters - UNEXPECTED: "
2031                                 "more than one entry in DAQ Logbook for run %d!", run));
2032                 delete aResult;
2033                 return 0;
2034         }
2035
2036         TSQLRow* aRow = aResult->Next();
2037         if (!aRow)
2038         {
2039                 Log("SHUTTLE", Form("QueryRunParameters - Could not retrieve row for run %d. Skipping", run));
2040                 delete aResult;
2041                 return 0;
2042         }
2043
2044         AliShuttleLogbookEntry* entry = new AliShuttleLogbookEntry(run);
2045
2046         for (Int_t ii = 0; ii < aResult->GetFieldCount(); ii++)
2047                 entry->SetRunParameter(aResult->GetFieldName(ii), aRow->GetField(ii));
2048
2049         delete aRow;
2050         delete aResult;
2051         
2052         UInt_t startTime = entry->GetStartTime();
2053         UInt_t endTime = entry->GetEndTime();
2054         Bool_t ecsSuccess = entry->GetECSSuccess();
2055         TString runType = entry->GetRunType();
2056         TString tmpdaqstartTime = entry->GetRunParameter("DAQ_time_start");
2057         TString recordingFlagString = entry->GetRunParameter("GDCmStreamRecording");
2058         UInt_t recordingFlag = recordingFlagString.Atoi();
2059         UInt_t daqstartTime = tmpdaqstartTime.Atoi();
2060         
2061         UInt_t now = time(0);
2062         Int_t dcsDelay = fConfig->GetDCSDelay()+fConfig->GetDCSQueryOffset();
2063
2064         Bool_t skip = kFALSE;
2065                                 
2066         // runs are processed if
2067         //   a) runType is PHYSICS and ecsSuccess is set
2068         //   b) runType is not PHYSICS and (ecsSuccess is set or DAQ_time_start is non-0)
2069         // effectively this means that all runs are processed that started properly (ecsSucess behaviour is different for PHYSICS and non-PHYSICS runs (check with ECS!)
2070         if (startTime != 0 && endTime != 0) {
2071                 if (endTime > startTime) { 
2072                         if (endTime >= now - dcsDelay) {
2073                                 Log("SHUTTLE", Form("Skipping run %d for now, because DCS buffer time is not yet expired", run));
2074                         } else {
2075                                 if ((runType == "PHYSICS" || runType == "STANDALONE") && recordingFlag == 0){
2076                                         Log("SHUTTLE", Form("QueryRunParameters - Run type for run %d is %s but the recording is OFF - Skipping!", run, runType.Data()));
2077                                         skip = kTRUE;
2078                                 } 
2079                                 else {
2080                                         if (runType == "PHYSICS") {
2081                                                 if (ecsSuccess) {
2082                                                         return entry;
2083                                                 } else {
2084                                                         Log("SHUTTLE", Form("QueryRunParameters - Run type for run %d is PHYSICS but ECS success flag not set (Reason = %s) - Skipping!", run, entry->GetRunParameter("eor_reason")));
2085                                                         skip = kTRUE;
2086                                                 } 
2087                                         } else {
2088                                                 if (ecsSuccess || daqstartTime > 0) {
2089                                                         if (ecsSuccess == kFALSE)
2090                                                                 Log("SHUTTLE", Form("Processing run %d although in status ECS failure (Reason: %s), since run type != PHYSICS and DAQ_time_start != 0", run, entry->GetRunParameter("eor_reason")));
2091                                                         return entry;
2092                                                 } else {
2093                                                         Log("SHUTTLE", Form("QueryRunParameters - Run type for run %d is %s, ECS success flag was not set (Reason = %s) and DAQ_time_start was NULL - Skipping!", run, runType.Data(), entry->GetRunParameter("eor_reason")));
2094                                                         skip = kTRUE;
2095                                                 }
2096                                         }
2097                                 }
2098                         }
2099                 } else {
2100                         Log("SHUTTLE", Form("QueryRunParameters - Invalid parameters for run %d: startTime equal to endTime: %d %d - Skipping!", run, startTime, endTime));
2101                         skip = kTRUE;
2102                 }
2103         } else {
2104           Log("SHUTTLE", Form("QueryRunParameters - Invalid parameters for Run %d: "
2105                               "startTime = %d, endTime = %d. Skipping (Shuttle won't be marked as DONE)!",
2106                               run, startTime, endTime));
2107         }
2108         
2109         if (skip)
2110         {
2111                 Log("SHUTTLE", Form("Marking SHUTTLE skipped for run %d", run));
2112                 fLogbookEntry = entry;
2113                 if (!UpdateShuttleLogbook("shuttle_skipped"))
2114                 {
2115                         AliError(Form("Could not update logbook for run %d !", run));
2116                 }
2117                 if (!UpdateTableSkippedCase("ALL"))
2118                 {
2119                         AliError(Form("Could not update FXS tables for run %d !", run));
2120                 }
2121                 fLogbookEntry = 0;
2122         }
2123                         
2124         delete entry;
2125         return 0;
2126 }
2127
2128 //______________________________________________________________________________________________
2129 TMap* AliShuttle::GetValueSet(const char* host, Int_t port, const TSeqCollection* entries,
2130                               DCSType type, Int_t multiSplit)
2131 {
2132         // Retrieve all "entry" data points from the DCS server
2133         // host, port: TSocket connection parameters
2134         // entries: list of name of the alias or data point
2135         // type: kAlias or kDP
2136         // returns TMap of values, 0 when failure
2137         
2138         AliDCSClient client(host, port, fTimeout, fRetries, multiSplit);
2139
2140         TMap* result = 0;
2141         if (type == kAlias)
2142         {
2143                 //result = client.GetAliasValues(entries, GetCurrentStartTime()-offset, 
2144                 //      GetCurrentEndTime()+offset);
2145                 result = client.GetAliasValues(entries, GetStartTimeDCSQuery(), 
2146                         GetEndTimeDCSQuery());
2147         } 
2148         else if (type == kDP)
2149         {
2150                 //result = client.GetDPValues(entries, GetCurrentStartTime()-offset, 
2151                 //      GetCurrentEndTime()+offset);
2152                 result = client.GetDPValues(entries, GetStartTimeDCSQuery(), 
2153                         GetEndTimeDCSQuery());
2154         }
2155
2156         if (result == 0)
2157         {
2158                 Log(fCurrentDetector.Data(), Form("GetValueSet - Can't get entries! Reason: %s",
2159                         client.GetErrorString(client.GetResultErrorCode())));
2160                 if (client.GetResultErrorCode() == AliDCSClient::fgkServerError)        
2161                         Log(fCurrentDetector.Data(), Form("GetValueSet - Server error code: %s",
2162                                 client.GetServerError().Data()));
2163
2164                 return 0;
2165         }
2166                 
2167         return result;
2168 }
2169
2170 //______________________________________________________________________________________________
2171 const char* AliShuttle::GetFile(Int_t system, const char* detector,
2172                 const char* id, const char* source)
2173 {
2174         // Get calibration file from file exchange servers
2175         // First queris the FXS database for the file name, using the run, detector, id and source info
2176         // then calls RetrieveFile(filename) for actual copy to local disk
2177         // run: current run being processed (given by Logbook entry fLogbookEntry)
2178         // detector: the Preprocessor name
2179         // id: provided as a parameter by the Preprocessor
2180         // source: provided by the Preprocessor through GetFileSources function
2181
2182         // check if test mode should simulate a FXS error
2183         if (fTestMode & kErrorFXSFiles)
2184         {
2185                 Log(detector, Form("GetFile - In TESTMODE - Simulating error while connecting to %s FXS", GetSystemName(system)));
2186                 return 0;
2187         }
2188         
2189         // check connection, in case connect
2190         if (!Connect(system))
2191         {
2192                 Log(detector, Form("GetFile - Couldn't connect to %s FXS database", GetSystemName(system)));
2193                 fFXSError = system;
2194                 return 0;
2195         }
2196
2197         // Query preparation
2198         TString sourceName(source);
2199         Int_t nFields = 3;
2200         TString sqlQueryStart = Form("select filePath,size,fileChecksum from %s where",
2201                                                                 fConfig->GetFXSdbTable(system));
2202         TString whereClause = Form("run=%d and detector=\"%s\" and fileId=\"%s\"",
2203                                                                 GetCurrentRun(), detector, id);
2204
2205         if (system == kDAQ || system == kDQM)
2206         {
2207                 whereClause += Form(" and DAQsource=\"%s\"", source);
2208         }
2209         else if (system == kDCS)
2210         {
2211                 sourceName="none";
2212         }
2213         else if (system == kHLT)
2214         {
2215                 whereClause += Form(" and DDLnumbers=\"%s\"", source);
2216         }
2217
2218         TString sqlQuery = Form("%s %s", sqlQueryStart.Data(), whereClause.Data());
2219
2220         AliDebug(2, Form("SQL query: \n%s",sqlQuery.Data()));
2221
2222         // Query execution
2223         TSQLResult* aResult = 0;
2224         aResult = dynamic_cast<TSQLResult*> (fServer[system]->Query(sqlQuery));
2225         if (!aResult) {
2226                 Log(detector, Form("GetFile - Can't execute SQL query to %s database for: id = %s, source = %s",
2227                                 GetSystemName(system), id, sourceName.Data()));
2228                 fFXSError = system;
2229                 return 0;
2230         }
2231
2232         if (aResult->GetRowCount() == 0)
2233         {
2234                 Log(detector,
2235                         Form("GetFile - No entry in %s FXS db for: id = %s, source = %s",
2236                                 GetSystemName(system), id, sourceName.Data()));
2237                 delete aResult;
2238                 return 0;
2239         }
2240
2241         if (aResult->GetRowCount() > 1) {
2242                 Log(detector,
2243                         Form("GetFile - More than one entry in %s FXS db for: id = %s, source = %s",
2244                                 GetSystemName(system), id, sourceName.Data()));
2245                 fFXSError = system;
2246                 delete aResult;
2247                 return 0;
2248         }
2249
2250         if (aResult->GetFieldCount() != nFields) {
2251                 Log(detector,
2252                         Form("GetFileName - Wrong field count in %s FXS db for: id = %s, source = %s",
2253                                 GetSystemName(system), id, sourceName.Data()));
2254                 fFXSError = system;
2255                 delete aResult;
2256                 return 0;
2257         }
2258
2259         TSQLRow* aRow = dynamic_cast<TSQLRow*> (aResult->Next());
2260
2261         if (!aRow){
2262                 Log(detector, Form("GetFile - Empty set result in %s FXS db from query: id = %s, source = %s",
2263                                 GetSystemName(system), id, sourceName.Data()));
2264                 fFXSError = system;
2265                 delete aResult;
2266                 return 0;
2267         }
2268
2269         TString filePath(aRow->GetField(0), aRow->GetFieldLength(0));
2270         TString fileSize(aRow->GetField(1), aRow->GetFieldLength(1));
2271         TString fileChecksum(aRow->GetField(2), aRow->GetFieldLength(2));
2272
2273         delete aResult;
2274         delete aRow;
2275
2276         AliDebug(2, Form("filePath = %s; size = %s, fileChecksum = %s",
2277                                 filePath.Data(), fileSize.Data(), fileChecksum.Data()));
2278
2279         // retrieved file is renamed to make it unique
2280         Int_t dir_lev1 = GetCurrentRun()/10000;
2281         TString localFileName = Form("%s/%d/%d/%s_process/%s_%s_%d_%s_%s.shuttle",
2282                                      GetShuttleTempDir(), dir_lev1, GetCurrentRun(), detector,
2283                                         GetSystemName(system), detector, GetCurrentRun(), 
2284                                         id, sourceName.Data());
2285         Log("SHUTTLE",Form("file from FXS = %s",localFileName.Data())); 
2286
2287
2288         // file retrieval from FXS
2289         UInt_t nRetries = 0;
2290         UInt_t maxRetries = 3;
2291         Bool_t result = kFALSE;
2292
2293         // copy!! if successful TSystem::Exec returns 0
2294         while (nRetries++ < maxRetries) {
2295                 AliDebug(2, Form("Trying to copy file. Retry # %d", nRetries));
2296                 result = RetrieveFile(system, filePath.Data(), localFileName.Data());
2297                 if (!result)
2298                 {
2299                         Log(detector, Form("GetFile - Copy of file %s from %s FXS failed",
2300                                         filePath.Data(), GetSystemName(system)));
2301                         continue;
2302                 } 
2303
2304                 if (fileSize.Length()>0)
2305                 {
2306                         // compare filesize of local file with the one stored in the FXS DB
2307                         Long_t size = -1;
2308                         Int_t sizeComp = gSystem->GetPathInfo(localFileName.Data(), 0, &size, 0, 0);
2309
2310                         if (sizeComp != 0 || size != fileSize.Atoi())
2311                         {
2312                                 Log(detector, Form("GetFile - size of file %s does not match with local copy!",
2313                                                         filePath.Data()));
2314                                 result = kFALSE;
2315                                 continue;
2316                         }
2317
2318                 } else {
2319                         Log(fCurrentDetector, Form("GetFile - size of file %s not set in %s database, skipping comparison",
2320                                                 filePath.Data(), GetSystemName(system)));
2321                 }
2322
2323                 if (fileChecksum.Length()>0)
2324                 {
2325                         // compare md5sum of local file with the one stored in the FXS DB
2326                         if(fileChecksum.Contains(' ')) fileChecksum.Resize(fileChecksum.First(' '));
2327                         Int_t md5Comp = gSystem->Exec(Form("md5sum %s |grep %s > /dev/null 2> /dev/null",
2328                                                 localFileName.Data(), fileChecksum.Data()));
2329
2330                         if (md5Comp != 0)
2331                         {
2332                                 Log(detector, Form("GetFile - md5sum of file %s does not match with local copy!",
2333                                                         filePath.Data()));
2334                                 result = kFALSE;
2335                                 continue;
2336                         }
2337                 } else {
2338                         Log(fCurrentDetector, Form("GetFile - md5sum of file %s not set in %s database, skipping comparison",
2339                                                         filePath.Data(), GetSystemName(system)));
2340                 }
2341                 if (result) break;
2342         }
2343
2344         if (!result) 
2345         {
2346                 fFXSError = system;
2347                 return 0;
2348         }
2349
2350         fFXSCalled[system]=kTRUE;
2351         TObjString *fileParams = new TObjString(Form("%s#!?!#%s", id, sourceName.Data()));
2352         fFXSlist[system].Add(fileParams);
2353
2354         static TString staticLocalFileName;
2355         staticLocalFileName.Form("%s", localFileName.Data());
2356         
2357         Log(fCurrentDetector, Form("GetFile - Retrieved file with id %s and "
2358                         "source %s from %s to %s", id, source, 
2359                         GetSystemName(system), localFileName.Data()));
2360                         
2361         return staticLocalFileName.Data();
2362 }
2363
2364 //______________________________________________________________________________________________
2365 Bool_t AliShuttle::RetrieveFile(UInt_t system, const char* fxsFileName, const char* localFileName)
2366 {
2367         //
2368         // Copies file from FXS to local Shuttle machine
2369         //
2370
2371         // check temp directory: trying to cd to temp; if it does not exist, create it
2372         AliDebug(2, Form("Copy file %s from %s FXS into %s",
2373                         GetSystemName(system), fxsFileName, localFileName));
2374                         
2375         TString tmpDir(localFileName);
2376         
2377         tmpDir = tmpDir(0,tmpDir.Last('/'));
2378
2379         Int_t noDir = gSystem->GetPathInfo(tmpDir.Data(), 0, (Long64_t*) 0, 0, 0);
2380         if (noDir) // temp dir does not exists!
2381         {
2382                 if (gSystem->mkdir(tmpDir.Data(), 1))
2383                 {
2384                         Log(fCurrentDetector.Data(), "RetrieveFile - could not make temp directory!!");
2385                         return kFALSE;
2386                 }
2387         }
2388
2389         TString command = Form("scp -oPort=%d -2 %s@%s:%s/%s %s",
2390                 fConfig->GetFXSPort(system),
2391                 fConfig->GetFXSUser(system),
2392                 fConfig->GetFXSHost(system),
2393                 fConfig->GetFXSBaseFolder(system),
2394                 fxsFileName,
2395                 localFileName);
2396
2397         AliDebug(2, Form("%s",command.Data()));
2398
2399         Bool_t result = (gSystem->Exec(command.Data()) == 0);
2400
2401         return result;
2402 }
2403
2404 //______________________________________________________________________________________________
2405 TList* AliShuttle::GetFileSources(Int_t system, const char* detector, const char* id)
2406 {
2407         //
2408         // Get sources producing the condition file Id from file exchange servers
2409         // if id is NULL all sources are returned (distinct)
2410         //
2411
2412         if (id)
2413         {
2414                 Log(detector, Form("GetFileSources - Querying %s FXS for files with id %s produced by %s", GetSystemName(system), id, detector));
2415         } else {
2416                 Log(detector, Form("GetFileSources - Querying %s FXS for files produced by %s", GetSystemName(system), detector));
2417         }
2418         
2419         // check if test mode should simulate a FXS error
2420         if (fTestMode & kErrorFXSSources)
2421         {
2422                 Log(detector, Form("GetFileSources - In TESTMODE - Simulating error while connecting to %s FXS", GetSystemName(system)));
2423                 return 0;
2424         }
2425
2426         if (system == kDCS)
2427         {
2428                 Log(detector, "GetFileSources - WARNING: DCS system has only one source of data!");
2429                 TList *list = new TList();
2430                 list->SetOwner(1);
2431                 list->Add(new TObjString(" "));
2432                 return list;
2433         }
2434
2435         // check connection, in case connect
2436         if (!Connect(system))
2437         {
2438                 Log(detector, Form("GetFileSources - Couldn't connect to %s FXS database", GetSystemName(system)));
2439                 fFXSError = system;
2440                 return NULL;
2441         }
2442
2443         TString sourceName = "";
2444         if (system == kDAQ || system == kDQM)
2445         {
2446                 sourceName = "DAQsource";
2447         } else if (system == kHLT)
2448         {
2449                 sourceName = "DDLnumbers";
2450         }
2451
2452         TString sqlQueryStart = Form("select distinct %s from %s where", sourceName.Data(), fConfig->GetFXSdbTable(system));
2453         TString whereClause = Form("run=%d and detector=\"%s\"",
2454                                 GetCurrentRun(), detector);
2455         if (id)
2456                 whereClause += Form(" and fileId=\"%s\"", id);
2457         TString sqlQuery = Form("%s %s", sqlQueryStart.Data(), whereClause.Data());
2458
2459         AliDebug(2, Form("SQL query: \n%s",sqlQuery.Data()));
2460
2461         // Query execution
2462         TSQLResult* aResult;
2463         aResult = fServer[system]->Query(sqlQuery);
2464         if (!aResult) {
2465                 Log(detector, Form("GetFileSources - Can't execute SQL query to %s database for id: %s",
2466                                 GetSystemName(system), id));
2467                 fFXSError = system;
2468                 return 0;
2469         }
2470
2471         TList *list = new TList();
2472         list->SetOwner(1);
2473         
2474         if (aResult->GetRowCount() == 0)
2475         {
2476                 Log(detector,
2477                         Form("GetFileSources - No entry in %s FXS table for id: %s", GetSystemName(system), id));
2478                 delete aResult;
2479                 return list;
2480         }
2481
2482         Log(detector, Form("GetFileSources - Found %d sources", aResult->GetRowCount()));
2483
2484         TSQLRow* aRow;
2485         while ((aRow = aResult->Next()))
2486         {
2487
2488                 TString source(aRow->GetField(0), aRow->GetFieldLength(0));
2489                 AliDebug(2, Form("%s = %s", sourceName.Data(), source.Data()));
2490                 list->Add(new TObjString(source));
2491                 delete aRow;
2492         }
2493
2494         delete aResult;
2495
2496         return list;
2497 }
2498
2499 //______________________________________________________________________________________________
2500 TList* AliShuttle::GetFileIDs(Int_t system, const char* detector, const char* source)
2501 {
2502         //
2503         // Get all ids of condition files produced by a given source from file exchange servers
2504         //
2505         
2506         Log(detector, Form("GetFileIDs - Retrieving ids with source %s with %s", source, GetSystemName(system)));
2507
2508         // check if test mode should simulate a FXS error
2509         if (fTestMode & kErrorFXSSources)
2510         {
2511                 Log(detector, Form("GetFileIDs - In TESTMODE - Simulating error while connecting to %s FXS", GetSystemName(system)));
2512                 return 0;
2513         }
2514
2515         // check connection, in case connect
2516         if (!Connect(system))
2517         {
2518                 Log(detector, Form("GetFileIDs - Couldn't connect to %s FXS database", GetSystemName(system)));
2519                 return NULL;
2520         }
2521
2522         TString sourceName = "";
2523         if (system == kDAQ)
2524         {
2525                 sourceName = "DAQsource";
2526         } else if (system == kHLT)
2527         {
2528                 sourceName = "DDLnumbers";
2529         }
2530
2531         TString sqlQueryStart = Form("select fileId from %s where", fConfig->GetFXSdbTable(system));
2532         TString whereClause = Form("run=%d and detector=\"%s\"",
2533                                 GetCurrentRun(), detector);
2534         if (sourceName.Length() > 0 && source)
2535                 whereClause += Form(" and %s=\"%s\"", sourceName.Data(), source);
2536         TString sqlQuery = Form("%s %s", sqlQueryStart.Data(), whereClause.Data());
2537
2538         AliDebug(2, Form("SQL query: \n%s",sqlQuery.Data()));
2539
2540         // Query execution
2541         TSQLResult* aResult;
2542         aResult = fServer[system]->Query(sqlQuery);
2543         if (!aResult) {
2544                 Log(detector, Form("GetFileIDs - Can't execute SQL query to %s database for source: %s",
2545                                 GetSystemName(system), source));
2546                 return 0;
2547         }
2548
2549         TList *list = new TList();
2550         list->SetOwner(1);
2551         
2552         if (aResult->GetRowCount() == 0)
2553         {
2554                 Log(detector,
2555                         Form("GetFileIDs - No entry in %s FXS table for source: %s", GetSystemName(system), source));
2556                 delete aResult;
2557                 return list;
2558         }
2559
2560         Log(detector, Form("GetFileIDs - Found %d ids", aResult->GetRowCount()));
2561
2562         TSQLRow* aRow;
2563
2564         while ((aRow = aResult->Next()))
2565         {
2566
2567                 TString id(aRow->GetField(0), aRow->GetFieldLength(0));
2568                 AliDebug(2, Form("fileId = %s", id.Data()));
2569                 list->Add(new TObjString(id));
2570                 delete aRow;
2571         }
2572
2573         delete aResult;
2574
2575         return list;
2576 }
2577
2578 //______________________________________________________________________________________________
2579 Bool_t AliShuttle::Connect(Int_t system)
2580 {
2581         // Connect to MySQL Server of the system's FXS MySQL databases
2582         // DAQ Logbook, Shuttle Logbook and DAQ FXS db are on the same host
2583         //
2584
2585         // check connection: if already connected return
2586
2587         if(fServer[system] && fServer[system]->IsConnected()) {
2588                 // ping the server              
2589                 if (fServer[system]->PingVerify()==kTRUE){ // connection is still alive
2590                         return kTRUE;
2591                 }               
2592                 else{
2593                         AliWarning(Form("Connection got lost to FXS database for %s. Closing and reconnecting.",
2594                                         AliShuttleInterface::GetSystemName(system)));
2595                         fServer[system]->Close();
2596                         delete fServer[system];
2597                         fServer[system] = 0x0;
2598                 }
2599         }
2600
2601         TString dbHost, dbUser, dbPass, dbName;
2602
2603         if (system < 4) // FXS db servers
2604         {
2605                 dbHost = Form("mysql://%s:%d", fConfig->GetFXSdbHost(system), fConfig->GetFXSdbPort(system));
2606                 dbUser = fConfig->GetFXSdbUser(system);
2607                 dbPass = fConfig->GetFXSdbPass(system);
2608                 dbName =   fConfig->GetFXSdbName(system);
2609         } else { // Run & Shuttle logbook servers
2610         // TODO Will the Shuttle logbook server be the same as the Run logbook server ???
2611                 dbHost = Form("mysql://%s:%d", fConfig->GetDAQlbHost(), fConfig->GetDAQlbPort());
2612                 dbUser = fConfig->GetDAQlbUser();
2613                 dbPass = fConfig->GetDAQlbPass();
2614                 dbName =   fConfig->GetDAQlbDB();
2615         }
2616
2617         fServer[system] = TSQLServer::Connect(dbHost.Data(), dbUser.Data(), dbPass.Data());
2618                 if (!fServer[system] || !fServer[system]->IsConnected()) {
2619                 if(system < 4)
2620                 {
2621                 AliError(Form("Can't establish connection to FXS database for %s",
2622                                         AliShuttleInterface::GetSystemName(system)));
2623                 } else {
2624                 AliError("Can't establish connection to Run logbook.");
2625                 }
2626                 if(fServer[system]) delete fServer[system];
2627                 return kFALSE;
2628         }
2629
2630         // Get tables
2631         TSQLResult* aResult=0;
2632         switch(system){
2633                 case kDAQ:
2634                         aResult = fServer[kDAQ]->GetTables(dbName.Data());
2635                         break;
2636                 case kDCS:
2637                         aResult = fServer[kDCS]->GetTables(dbName.Data());
2638                         break;
2639                 case kHLT:
2640                         aResult = fServer[kHLT]->GetTables(dbName.Data());
2641                         break;
2642                 case kDQM:
2643                         aResult = fServer[kDQM]->GetTables(dbName.Data());
2644                         break;
2645                 default:
2646                         aResult = fServer[4]->GetTables(dbName.Data());
2647                         break;
2648         }
2649
2650         delete aResult;
2651         return kTRUE;
2652 }
2653
2654 //______________________________________________________________________________________________
2655 Bool_t AliShuttle::UpdateTable()
2656 {
2657         //
2658         // Update FXS table filling time_processed field in all rows corresponding to current run and detector
2659         //
2660
2661         Bool_t result = kTRUE;
2662
2663         for (UInt_t system=0; system<4; system++)
2664         {
2665                 if(!fFXSCalled[system]) continue;
2666
2667                 // check connection, in case connect
2668                 if (!Connect(system))
2669                 {
2670                         Log(fCurrentDetector, Form("UpdateTable - Couldn't connect to %s FXS database", GetSystemName(system)));
2671                         result = kFALSE;
2672                         continue;
2673                 }
2674
2675                 TTimeStamp now; // now
2676
2677                 // Loop on FXS list entries
2678                 TIter iter(&fFXSlist[system]);
2679                 TObjString *aFXSentry=0;
2680                 while ((aFXSentry = dynamic_cast<TObjString*> (iter.Next())))
2681                 {
2682                         TString aFXSentrystr = aFXSentry->String();
2683                         TObjArray *aFXSarray = aFXSentrystr.Tokenize("#!?!#");
2684                         if (!aFXSarray || aFXSarray->GetEntries() != 2 )
2685                         {
2686                                 Log(fCurrentDetector, Form("UpdateTable - error updating %s FXS entry. Check string: <%s>",
2687                                         GetSystemName(system), aFXSentrystr.Data()));
2688                                 if(aFXSarray) delete aFXSarray;
2689                                 result = kFALSE;
2690                                 continue;
2691                         }
2692                         const char* fileId = ((TObjString*) aFXSarray->At(0))->GetName();
2693                         const char* source = ((TObjString*) aFXSarray->At(1))->GetName();
2694
2695                         TString whereClause;
2696                         if (system == kDAQ || system == kDQM)
2697                         {
2698                                 whereClause = Form("where run=%d and detector=\"%s\" and fileId=\"%s\" and DAQsource=\"%s\";",
2699                                                         GetCurrentRun(), fCurrentDetector.Data(), fileId, source);
2700                         }
2701                         else if (system == kDCS)
2702                         {
2703                                 whereClause = Form("where run=%d and detector=\"%s\" and fileId=\"%s\";",
2704                                                         GetCurrentRun(), fCurrentDetector.Data(), fileId);
2705                         }
2706                         else if (system == kHLT)
2707                         {
2708                                 whereClause = Form("where run=%d and detector=\"%s\" and fileId=\"%s\" and DDLnumbers=\"%s\";",
2709                                                         GetCurrentRun(), fCurrentDetector.Data(), fileId, source);
2710                         }
2711
2712                         delete aFXSarray;
2713
2714                         TString sqlQuery = Form("update %s set time_processed=%ld %s", fConfig->GetFXSdbTable(system),
2715                                                 (ULong_t)now.GetSec(), whereClause.Data());
2716
2717                         AliDebug(2, Form("SQL query: \n%s",sqlQuery.Data()));
2718
2719                         // Query execution
2720                         TSQLResult* aResult;
2721                         aResult = dynamic_cast<TSQLResult*> (fServer[system]->Query(sqlQuery));
2722                         if (!aResult)
2723                         {
2724                                 Log(fCurrentDetector, Form("UpdateTable - %s db: can't execute SQL query <%s>",
2725                                                                 GetSystemName(system), sqlQuery.Data()));
2726                                 result = kFALSE;
2727                                 continue;
2728                         }
2729                         delete aResult;
2730                 }
2731         }
2732
2733         return result;
2734 }
2735
2736 //_______________________________________________________________________________
2737 Bool_t AliShuttle::UpdateTableSkippedCase(const char* detector)
2738 {
2739         //
2740         // Update FXS table filling time_processed field in all rows corresponding to current run and detector
2741         // if detector = "ALL" update all detectors
2742         //
2743
2744         Bool_t result = kTRUE;
2745
2746         TString detName(detector);
2747
2748         for (UInt_t system=0; system<4; system++)
2749         {
2750
2751                 // check connection, in case connect
2752                 if (!Connect(system))
2753                 {
2754                         Log(fCurrentDetector, Form("UpdateTableSkippedCase - Couldn't connect to %s FXS database", GetSystemName(system)));
2755                         result = kFALSE;
2756                         continue;
2757                 }
2758
2759                 TTimeStamp now; // now
2760
2761                 // Loop on FXS list entries
2762                 TIter iter(&fFXSlist[system]);
2763                         
2764                 TString whereClause;
2765                 if (detName == "ALL") whereClause = Form("where run=%d and time_processed IS NULL;",GetCurrentRun());
2766                 else whereClause = Form("where run=%d and detector=\"%s\" and time_processed IS NULL;",GetCurrentRun(), detector);
2767
2768                 //Log("SHUTTLE",Form(" whereClause = %s ",whereClause.Data()));
2769
2770                 TString sqlQuery = Form("update %s set time_processed=%ld %s", fConfig->GetFXSdbTable(system),
2771                                         (ULong_t)now.GetSec(), whereClause.Data());
2772
2773                 AliDebug(2, Form("SQL query: \n%s",sqlQuery.Data()));
2774
2775                 // Query execution
2776                 TSQLResult* aResult;
2777                 aResult = dynamic_cast<TSQLResult*> (fServer[system]->Query(sqlQuery));
2778                 if (!aResult)
2779                 {
2780                         Log("SHUTTLE", Form("UpdateTableSkippedCase - %s db: can't execute SQL query <%s>",
2781                                                         GetSystemName(system), sqlQuery.Data()));
2782                         result = kFALSE;
2783                         continue;
2784                 }
2785                 delete aResult;
2786                 
2787         }
2788
2789         return result;
2790 }
2791 //______________________________________________________________________________________________
2792 Bool_t AliShuttle::UpdateTableFailCase()
2793 {
2794         // Update FXS table filling time_processed field in all rows corresponding to current run and detector
2795         // this is called in case the preprocessor is declared failed for the current run, because
2796         // the fields are updated only in case of success
2797
2798         Bool_t result = kTRUE;
2799
2800         for (UInt_t system=0; system<4; system++)
2801         {
2802                 // check connection, in case connect
2803                 if (!Connect(system))
2804                 {
2805                         Log(fCurrentDetector, Form("UpdateTableFailCase - Couldn't connect to %s FXS database",
2806                                                         GetSystemName(system)));
2807                         result = kFALSE;
2808                         continue;
2809                 }
2810
2811                 TTimeStamp now; // now
2812
2813                 // Loop on FXS list entries
2814
2815                 TString whereClause = Form("where run=%d and detector=\"%s\";",
2816                                                 GetCurrentRun(), fCurrentDetector.Data());
2817
2818
2819                 TString sqlQuery = Form("update %s set time_processed=%ld %s", fConfig->GetFXSdbTable(system),
2820                                         (ULong_t)now.GetSec(), whereClause.Data());
2821
2822                 AliDebug(2, Form("SQL query: \n%s",sqlQuery.Data()));
2823
2824                 // Query execution
2825                 TSQLResult* aResult;
2826                 aResult = dynamic_cast<TSQLResult*> (fServer[system]->Query(sqlQuery));
2827                 if (!aResult)
2828                 {
2829                         Log(fCurrentDetector, Form("UpdateTableFailCase - %s db: can't execute SQL query <%s>",
2830                                                         GetSystemName(system), sqlQuery.Data()));
2831                         result = kFALSE;
2832                         continue;
2833                 }
2834                 delete aResult;
2835         }
2836
2837         return result;
2838 }
2839
2840 //______________________________________________________________________________________________
2841 Bool_t AliShuttle::UpdateShuttleLogbook(const char* detector, const char* status)
2842 {
2843         //
2844         // Update Shuttle logbook filling detector or shuttle_done column
2845         // ex. of usage: UpdateShuttleLogbook("PHOS", "DONE") or UpdateShuttleLogbook("shuttle_done")
2846         //
2847
2848         // check connection, in case connect
2849         if(!Connect(4)){
2850                 Log("SHUTTLE", "UpdateShuttleLogbook - Couldn't connect to DAQ Logbook.");
2851                 return kFALSE;
2852         }
2853
2854         TString detName(detector);
2855         TString setClause;
2856         if (detName == "shuttle_done" || detName == "shuttle_skipped")
2857         {
2858                 setClause = "set shuttle_done=1";
2859                 
2860                 if (detName == "shuttle_done")
2861                 {
2862                         if (TouchFile() != kTRUE)
2863                         {
2864                                 SendMLRunInfo("Pending");
2865                                 return kFALSE;
2866                         }
2867                         
2868                         SendMLRunInfo("Done");
2869                 }
2870                 else 
2871                         SendMLRunInfo("Skipped");
2872         } 
2873         else {
2874                 TString statusStr(status);
2875                 if(statusStr.Contains("done", TString::kIgnoreCase) ||
2876                    statusStr.Contains("failed", TString::kIgnoreCase)){
2877                         setClause = Form("set %s=\"%s\"", detector, status);
2878                 } else {
2879                         Log("SHUTTLE",
2880                                 Form("UpdateShuttleLogbook - Invalid status <%s> for detector %s",
2881                                         status, detector));
2882                         return kFALSE;
2883                 }
2884         }
2885
2886         TString whereClause = Form("where run=%d", GetCurrentRun());
2887
2888         TString sqlQuery = Form("update %s %s %s",
2889                                         fConfig->GetShuttlelbTable(), setClause.Data(), whereClause.Data());
2890
2891         AliDebug(2, Form("SQL query: \n%s",sqlQuery.Data()));
2892
2893         // Query execution
2894         TSQLResult* aResult;
2895         aResult = dynamic_cast<TSQLResult*> (fServer[4]->Query(sqlQuery));
2896         if (!aResult) {
2897                 Log("SHUTTLE", Form("UpdateShuttleLogbook - Can't execute query <%s>", sqlQuery.Data()));
2898                 return kFALSE;
2899         }
2900         delete aResult;
2901
2902         return kTRUE;
2903 }
2904
2905 //______________________________________________________________________________________________
2906 Int_t AliShuttle::GetCurrentRun() const
2907 {
2908         //
2909         // Get current run from logbook entry
2910         //
2911
2912         return fLogbookEntry ? fLogbookEntry->GetRun() : -1;
2913 }
2914
2915 //______________________________________________________________________________________________
2916 UInt_t AliShuttle::GetCurrentStartTime() const
2917 {
2918         //
2919         // get current start time
2920         //
2921
2922         return fLogbookEntry ? fLogbookEntry->GetStartTime() : 0;
2923 }
2924
2925 //______________________________________________________________________________________________
2926 UInt_t AliShuttle::GetCurrentEndTime() const
2927 {
2928         //
2929         // get current end time from logbook entry
2930         //
2931
2932         return fLogbookEntry ? fLogbookEntry->GetEndTime() : 0;
2933 }
2934 //______________________________________________________________________________________________
2935 UInt_t AliShuttle::GetCurrentYear() const
2936 {
2937         //
2938         // Get current year from logbook entry
2939         //
2940
2941         if (!fLogbookEntry) return 0;
2942         
2943         TTimeStamp startTime(GetCurrentStartTime());
2944         TString year =  Form("%d",startTime.GetDate());
2945         year = year(0,4);
2946         
2947         return year.Atoi();
2948 }
2949
2950 //______________________________________________________________________________________________
2951 const char* AliShuttle::GetLHCPeriod() const
2952 {
2953         //
2954         // Get current LHC period from logbook entry
2955         //
2956
2957         if (!fLogbookEntry) return 0;
2958                 
2959         return fLogbookEntry->GetRunParameter("LHCperiod");
2960 }
2961
2962 //______________________________________________________________________________________________
2963 void AliShuttle::Log(const char* detector, const char* message, UInt_t level)
2964 {
2965         //
2966         // Fill log string with a message
2967         //
2968         
2969         TString logRunDir = GetShuttleLogDir();
2970         if (GetCurrentRun() >=0) {
2971                 Int_t logDir_lev1 = GetCurrentRun()/10000;
2972                 logRunDir += Form("/%d/%d", logDir_lev1, GetCurrentRun());
2973         }               
2974         void* dir = gSystem->OpenDirectory(logRunDir.Data());
2975         if (dir == NULL) {
2976                 if (gSystem->mkdir(logRunDir.Data(), kTRUE)) {
2977                         AliError(Form("Can't open directory <%s>", GetShuttleLogDir()));
2978                         return;
2979                 }
2980
2981         } else {
2982                 gSystem->FreeDirectory(dir);
2983         }
2984
2985         TString toLog = Form("%s UTC (%d): %s - ", TTimeStamp(time(0)).AsString("s"), getpid(), detector);
2986         if (GetCurrentRun() >= 0) 
2987                 toLog += Form("run %d - ", GetCurrentRun());
2988         toLog += Form("%s", message);
2989
2990         AliLog::Message(level, toLog, MODULENAME(), ClassName(), FUNCTIONNAME(), __FILE__, __LINE__);
2991         
2992         // if we redirect the log output already to the file, leave here
2993         if (fOutputRedirected && strcmp(detector, "SHUTTLE") != 0)
2994                 return;
2995
2996         TString fileName = GetLogFileName(detector);
2997         
2998         gSystem->ExpandPathName(fileName);
2999
3000         ofstream logFile;
3001         logFile.open(fileName, ofstream::out | ofstream::app);
3002
3003         if (!logFile.is_open()) {
3004                 AliError(Form("Could not open file %s", fileName.Data()));
3005                 return;
3006         }
3007
3008         logFile << toLog.Data() << "\n";
3009
3010         logFile.close();
3011 }
3012
3013 //______________________________________________________________________________________________
3014 TString AliShuttle::GetLogFileName(const char* detector) const
3015 {
3016         // 
3017         // returns the name of the log file for a given sub detector
3018         //
3019         
3020         TString fileName;
3021         
3022         if (GetCurrentRun() >= 0) 
3023         {
3024                 Int_t logDir_lev1 = GetCurrentRun()/10000;
3025                 fileName.Form("%s/%d/%d/%s.log", GetShuttleLogDir(), logDir_lev1, GetCurrentRun(), 
3026                         detector);
3027         } else {
3028                 fileName.Form("%s/%s.log", GetShuttleLogDir(), detector);
3029         }
3030
3031         return fileName;
3032 }
3033
3034 //______________________________________________________________________________________________
3035 void AliShuttle::SendAlive()
3036 {
3037         // sends alive message to ML
3038         
3039         TMonaLisaText mlStatus("SHUTTLE_status", "Alive");
3040
3041         TList mlList;
3042         mlList.Add(&mlStatus);
3043
3044         fMonaLisa->SendParameters(&mlList, "__PROCESSINGINFO__");
3045 }
3046
3047 //______________________________________________________________________________________________
3048 Bool_t AliShuttle::Collect(Int_t run)
3049 {
3050         //
3051         // Collects conditions data for all UNPROCESSED run written to DAQ LogBook in case of run = -1 (default)
3052         // If a dedicated run is given this run is processed
3053         //
3054         // In operational mode, this is the Shuttle function triggered by the EOR signal.
3055         //
3056
3057         if (run == -1)
3058                 Log("SHUTTLE","Collect - Shuttle called. Collecting conditions data for unprocessed runs");
3059         else
3060                 Log("SHUTTLE", Form("Collect - Shuttle called. Collecting conditions data for run %d", run));
3061
3062         SetLastAction("Starting");
3063
3064         // create ML instance
3065         if (!fMonaLisa)
3066                 fMonaLisa = new TMonaLisaWriter(fConfig->GetMonitorHost(), fConfig->GetMonitorTable());
3067                 
3068         CountOpenRuns();
3069
3070         TString whereClause("where shuttle_done=0");
3071         if (run != -1)
3072                 whereClause += Form(" and run=%d", run);
3073
3074         TObjArray shuttleLogbookEntries;
3075         if (!QueryShuttleLogbook(whereClause, shuttleLogbookEntries))
3076         {
3077                 Log("SHUTTLE", "Collect - Can't retrieve entries from Shuttle logbook");
3078                 return kFALSE;
3079         }
3080
3081         if (shuttleLogbookEntries.GetEntries() == 0)
3082         {
3083                 if (run == -1)
3084                         Log("SHUTTLE","Collect - Found no UNPROCESSED runs in Shuttle logbook");
3085                 else
3086                         Log("SHUTTLE", Form("Collect - Run %d is already DONE "
3087                                                 "or it does not exist in Shuttle logbook", run));
3088                 return kTRUE;
3089         }
3090
3091         for (UInt_t iDet=0; iDet<NDetectors(); iDet++)
3092                 fFirstUnprocessed[iDet] = kTRUE;
3093
3094         if (run != -1)
3095         {
3096                 // query Shuttle logbook for earlier runs, check if some detectors are unprocessed,
3097                 // flag them into fFirstUnprocessed array
3098                 TString whereClauseBis(Form("where shuttle_done=0 and run < %d", run));
3099                 TObjArray tmpLogbookEntries;
3100                 if (!QueryShuttleLogbook(whereClauseBis, tmpLogbookEntries))
3101                 {
3102                         Log("SHUTTLE", "Collect - Can't retrieve entries from Shuttle logbook");
3103                         return kFALSE;
3104                 }
3105
3106                 TIter iter(&tmpLogbookEntries);
3107                 AliShuttleLogbookEntry* anEntry = 0;
3108                 while ((anEntry = dynamic_cast<AliShuttleLogbookEntry*> (iter.Next())))
3109                 {
3110                         for (UInt_t iDet=0; iDet<NDetectors(); iDet++)
3111                         {
3112                                 if (anEntry->GetDetectorStatus(iDet) == AliShuttleLogbookEntry::kUnprocessed)
3113                                 {
3114                                         AliDebug(2, Form("Run %d: setting %s as \"not first time unprocessed\"",
3115                                                         anEntry->GetRun(), GetDetName(iDet)));
3116                                         fFirstUnprocessed[iDet] = kFALSE;
3117                                 }
3118                         }
3119
3120                 }
3121
3122         }
3123
3124         if (!RetrieveConditionsData(shuttleLogbookEntries))
3125         {
3126                 Log("SHUTTLE", "Collect - Process of at least one run failed");
3127                 CountOpenRuns();
3128                 return kFALSE;
3129         }
3130
3131         Log("SHUTTLE", "Collect - Requested run(s) successfully processed");
3132         CountOpenRuns();
3133         return kTRUE;
3134 }
3135
3136 //______________________________________________________________________________________________
3137 Bool_t AliShuttle::RetrieveConditionsData(const TObjArray& dateEntries)
3138 {
3139         //
3140         // Retrieve conditions data for all runs that aren't processed yet
3141         //
3142
3143         Bool_t hasError = kFALSE;
3144
3145         TIter iter(&dateEntries);
3146         AliShuttleLogbookEntry* anEntry;
3147
3148         while ((anEntry = (AliShuttleLogbookEntry*) iter.Next())){
3149                 if (!Process(anEntry)){
3150                         hasError = kTRUE;
3151                 }
3152
3153                 // clean SHUTTLE temp directory
3154                 //TString filename = Form("%s/*.shuttle", GetShuttleTempDir());
3155                 //RemoveFile(filename.Data());
3156         }
3157
3158         return hasError == kFALSE;
3159 }
3160
3161 //______________________________________________________________________________________________
3162 ULong_t AliShuttle::GetTimeOfLastAction() const
3163 {
3164         //
3165         // Gets time of last action
3166         //
3167
3168         ULong_t tmp;
3169
3170         fMonitoringMutex->Lock();
3171
3172         tmp = fLastActionTime;
3173
3174         fMonitoringMutex->UnLock();
3175
3176         return tmp;
3177 }
3178
3179 //______________________________________________________________________________________________
3180 const TString AliShuttle::GetLastAction() const
3181 {
3182         //
3183         // returns a string description of the last action
3184         //
3185
3186         TString tmp;
3187
3188         fMonitoringMutex->Lock();
3189         
3190         tmp = fLastAction;
3191         
3192         fMonitoringMutex->UnLock();
3193
3194         return tmp;
3195 }
3196
3197 //______________________________________________________________________________________________
3198 void AliShuttle::SetLastAction(const char* action)
3199 {
3200         //
3201         // updates the monitoring variables
3202         //
3203
3204         fMonitoringMutex->Lock();
3205
3206         fLastAction = action;
3207         fLastActionTime = time(0);
3208         
3209         fMonitoringMutex->UnLock();
3210 }
3211
3212 //______________________________________________________________________________________________
3213 const char* AliShuttle::GetRunParameter(const char* param)
3214 {
3215         //
3216         // returns run parameter read from DAQ logbook
3217         //
3218
3219         if(!fLogbookEntry) {
3220                 AliError("No logbook entry!");
3221                 return 0;
3222         }
3223
3224         return fLogbookEntry->GetRunParameter(param);
3225 }
3226
3227 //______________________________________________________________________________________________
3228 AliCDBEntry* AliShuttle::GetFromOCDB(const char* detector, const AliCDBPath& path)
3229 {
3230         //
3231         // returns object from OCDB valid for current run
3232         //
3233
3234         if (fTestMode & kErrorOCDB)
3235         {
3236                 Log(detector, "GetFromOCDB - In TESTMODE - Simulating error with OCDB");
3237                 return 0;
3238         }
3239         
3240         AliCDBStorage *sto = AliCDBManager::Instance()->GetStorage(fgkMainCDB);
3241         if (!sto)
3242         {
3243                 Log(detector, "GetFromOCDB - Cannot activate main OCDB for query!");
3244                 return 0;
3245         }
3246
3247         return dynamic_cast<AliCDBEntry*> (sto->Get(path, GetCurrentRun()));
3248 }
3249
3250 //______________________________________________________________________________________________
3251 Bool_t AliShuttle::SendMail(EMailTarget target, Int_t system)
3252 {
3253         //
3254         // sends a mail to the subdetector expert in case of preprocessor error
3255         //
3256         
3257         if (fTestMode != kNone)
3258                 return kTRUE;
3259                 
3260         if (!fConfig->SendMail()) 
3261                 return kTRUE;
3262
3263         if (target == kDCSEMail || target == kFXSEMail) {
3264                 if (!fFirstProcessing)
3265                         return kTRUE;
3266         }
3267
3268         Int_t runMode = (Int_t)fConfig->GetRunMode();
3269         TString tmpStr;
3270         if (runMode == 0) tmpStr = " Nightly Test:";
3271         else tmpStr = " Data Taking:"; 
3272         void* dir = gSystem->OpenDirectory(GetShuttleLogDir());
3273         if (dir == NULL)
3274         {
3275                 if (gSystem->mkdir(GetShuttleLogDir(), kTRUE))
3276                 {
3277                         Log("SHUTTLE", Form("SendMail - Can't open directory <%s>", GetShuttleLogDir()));
3278                         return kFALSE;
3279                 }
3280
3281         } else {
3282                 gSystem->FreeDirectory(dir);
3283         }
3284
3285         // det experts in to
3286         TString to="";
3287         TIter *iterExperts = 0;
3288         if (target == kDCSEMail) {
3289                 iterExperts = new TIter(fConfig->GetAdmins(AliShuttleConfig::kAmanda));
3290         }
3291         else if (target == kFXSEMail) {
3292                 iterExperts = new TIter(fConfig->GetAdmins(system));
3293         }
3294         if (iterExperts) {
3295                 TObjString *anExpert=0;
3296                 while ((anExpert = (TObjString*) iterExperts->Next()))
3297                 {
3298                         to += Form("%s,", anExpert->GetName());
3299                 }
3300                 delete iterExperts;
3301         }
3302
3303         // add subdetector experts      
3304         iterExperts = new TIter(fConfig->GetResponsibles(fCurrentDetector));
3305         TObjString *anExpert=0;
3306         while ((anExpert = (TObjString*) iterExperts->Next()))
3307         {
3308                 to += Form("%s,", anExpert->GetName());
3309         }
3310         delete iterExperts;
3311         
3312         if (to.Length() > 0)
3313           to.Remove(to.Length()-1);
3314         AliDebug(2, Form("to: %s",to.Data()));
3315
3316         if (to.IsNull()) {
3317                 Log("SHUTTLE", Form("List of %d responsibles not set!", (Int_t) target));
3318                 return kFALSE;
3319         }
3320
3321         // SHUTTLE responsibles in cc
3322         TString cc="";
3323         TIter iterAdmins(fConfig->GetAdmins(AliShuttleConfig::kGlobal));
3324         TObjString *anAdmin=0;
3325         while ((anAdmin = (TObjString*) iterAdmins.Next()))
3326         {
3327                 cc += Form("%s,", anAdmin->GetName());
3328         }
3329         if (cc.Length() > 0)
3330           cc.Remove(cc.Length()-1);
3331         AliDebug(2, Form("cc: %s",to.Data()));
3332
3333         // mail body 
3334         TString bodyFileName;
3335         bodyFileName.Form("%s/mail.body", GetShuttleLogDir());
3336         gSystem->ExpandPathName(bodyFileName);
3337
3338         ofstream mailBody;
3339         mailBody.open(bodyFileName, ofstream::out);
3340
3341         if (!mailBody.is_open())
3342         {
3343                 Log("SHUTTLE", Form("Could not open mail body file %s", bodyFileName.Data()));
3344                 return kFALSE;
3345         }
3346
3347
3348         TString subject;
3349         TString body;
3350
3351         if (target == kDCSEMail){
3352                 subject = Form("%s CRITICAL Retrieval of data points for %s FAILED in run %d !",
3353                                 tmpStr.Data(), fCurrentDetector.Data(), GetCurrentRun());
3354                 AliDebug(2, Form("subject: %s", subject.Data()));
3355                 
3356                 body = Form("Dear DCS experts, \n\n");
3357                 body += Form("SHUTTLE couldn\'t retrieve the data points for detector %s "
3358                              "in run %d!!\n\n", fCurrentDetector.Data(), GetCurrentRun());
3359         }
3360         else if (target == kFXSEMail){
3361                 subject = Form("%s CRITICAL FXS communication for %s FAILED in run %d !",
3362                                 tmpStr.Data(), fCurrentDetector.Data(), GetCurrentRun());
3363                 AliDebug(2, Form("subject: %s", subject.Data()));
3364                 TString sys;
3365                 if (system == kDAQ) sys="DAQ";
3366                 else if (system == kDCS) sys="DCS";
3367                 else if (system == kHLT) sys="HLT";
3368                 else if (system == kDQM) sys="DQM";
3369                 else return kFALSE;
3370                 body = Form("Dear  %s FXS experts, \n\n",sys.Data());
3371                 body += Form("SHUTTLE couldn\'t retrieve data from the FXS for detector %s "
3372                              "in run %d!!\n\n", fCurrentDetector.Data(), GetCurrentRun());
3373                 body += Form("The contacted server was:\nDB: %s\nFXS:%s\n\n", fConfig->GetFXSdbHost(system), fConfig->GetFXSHost(system));
3374         }
3375         else {
3376                 subject = Form("%s %s Shuttle preprocessor FAILED in run %d (run type = %s)!",
3377                                        tmpStr.Data(), fCurrentDetector.Data(), GetCurrentRun(), GetRunType());
3378                 AliDebug(2, Form("subject: %s", subject.Data()));
3379         
3380                 body = Form("Dear %s expert(s), \n\n", fCurrentDetector.Data());
3381                 body += Form("SHUTTLE just detected that your preprocessor "
3382                              "failed processing run %d (run type = %s)!!\n\n", 
3383                              GetCurrentRun(), GetRunType());
3384         }
3385
3386         body += Form("Please check %s status on the SHUTTLE monitoring page: \n\n", 
3387                                 fCurrentDetector.Data());
3388         if (fConfig->GetRunMode() == AliShuttleConfig::kTest)
3389         {
3390                 body += Form("\thttp://pcalimonitor.cern.ch/shuttle.jsp?time=24 \n\n");
3391         } else {
3392                 body += Form("\thttp://pcalimonitor.cern.ch/shuttle.jsp?instance=PROD&time=24 \n\n");
3393         }
3394         
3395         
3396         TString logFolder = "logs";
3397         if (fConfig->GetRunMode() == AliShuttleConfig::kProd) 
3398                 logFolder += "_PROD";
3399         
3400         
3401         body += Form("Find the %s log for the current run on \n\n"
3402                 "\thttp://pcalishuttle02.cern.ch/%s/%d/%d/%s.log \n\n", 
3403                      fCurrentDetector.Data(), logFolder.Data(), GetCurrentRun()/10000,  
3404                                 GetCurrentRun(), fCurrentDetector.Data());
3405         body += Form("The last 15 lines of %s log file are following:\n\n", fCurrentDetector.Data());
3406
3407         AliDebug(2, Form("Body begin: %s", body.Data()));
3408
3409         mailBody << body.Data();
3410         mailBody.close();
3411         mailBody.open(bodyFileName, ofstream::out | ofstream::app);
3412
3413         TString logFileName = Form("%s/%d/%d/%s.log", GetShuttleLogDir(), 
3414                 GetCurrentRun()/10000, GetCurrentRun(), fCurrentDetector.Data());
3415         TString tailCommand = Form("tail -n 15 %s >> %s", logFileName.Data(), bodyFileName.Data());
3416         if (gSystem->Exec(tailCommand.Data()))
3417         {
3418                 mailBody << Form("%s log file not found ...\n\n", fCurrentDetector.Data());
3419         }
3420
3421         TString endBody = Form("------------------------------------------------------\n\n");
3422         endBody += Form("In case of problems please contact the SHUTTLE core team.\n\n");
3423         endBody += "Please do not answer this message directly, it is automatically generated.\n\n";
3424         endBody += "Greetings,\n\n \t\t\tthe SHUTTLE\n";
3425
3426         AliDebug(2, Form("Body end: %s", endBody.Data()));
3427
3428         mailBody << endBody.Data();
3429
3430         mailBody.close();
3431
3432         // send mail!
3433         TString mailCommand = Form("mail -s \"%s\" -c %s %s < %s",
3434                                                 subject.Data(),
3435                                                 cc.Data(),
3436                                                 to.Data(),
3437                                                 bodyFileName.Data());
3438         AliDebug(2, Form("mail command: %s", mailCommand.Data()));
3439
3440         Bool_t result = gSystem->Exec(mailCommand.Data());
3441
3442         return result == 0;
3443 }
3444 //______________________________________________________________________________________________
3445 const char* AliShuttle::GetRunType()
3446 {
3447         //
3448         // returns run type read from "run type" logbook
3449         //
3450
3451         if(!fLogbookEntry) {
3452                 AliError("No logbook entry!");
3453                 return 0;
3454         }
3455
3456         return fLogbookEntry->GetRunType();
3457 }
3458
3459 //______________________________________________________________________________________________
3460 Bool_t AliShuttle::GetHLTStatus()
3461 {
3462         // Return HLT status (ON=1 OFF=0)
3463         // Converts the HLT status from the mode string read in the run logbook (not just a bool)
3464
3465         if(!fLogbookEntry) {
3466                 AliError("No logbook entry!");
3467                 return 0;
3468         }
3469
3470         // TODO implement when HLTMode is inserted in run logbook
3471         TString hltMode = fLogbookEntry->GetRunParameter("HLTmode");
3472         TSubString firstChar = hltMode(0,1);
3473         AliDebug(2,Form("First char = %s ",firstChar.Data())); 
3474         if (firstChar == "A") {
3475                 return kFALSE;
3476         }
3477         else if ((firstChar == "B") || (firstChar == "C") || (firstChar == "D") || (firstChar == "E")) {
3478                 return kTRUE;
3479         }
3480         else {
3481                 Log("SHUTTLE","Unexpected HLT mode! Returning 0....");
3482                 return kFALSE;
3483         }
3484 }
3485
3486 //______________________________________________________________________________________________
3487 const char* AliShuttle::GetTriggerConfiguration()