AliShuttle can set mirror SEs for OCDB uploads via static method
[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         fStatusEntry = AliCDBManager::Instance()->GetStorage(GetLocalCDB())
955                 ->Get(Form("/SHUTTLE/%s/%d", fCurrentDetector.Data(), path1), GetCurrentRun());
956
957         if (!fStatusEntry) return 0;
958         fStatusEntry->SetOwner(1);
959
960         AliShuttleStatus* status = dynamic_cast<AliShuttleStatus*> (fStatusEntry->GetObject());
961         if (!status) {
962                 AliError("Invalid object stored to CDB!");
963                 return 0;
964         }
965
966         return status;
967 }
968
969 //______________________________________________________________________________________________
970 Bool_t AliShuttle::WriteShuttleStatus(AliShuttleStatus* status)
971 {
972         //
973         // writes the status for one subdetector
974         //
975
976         if (fStatusEntry){
977                 delete fStatusEntry;
978                 fStatusEntry = 0;
979         }
980
981         Int_t run = GetCurrentRun();
982         Int_t path1 = run/10000;
983         TString path1_string = Form("%d",path1);
984
985         AliCDBId id(AliCDBPath("SHUTTLE", fCurrentDetector, path1_string), run, run);
986
987         fStatusEntry = new AliCDBEntry(status, id, new AliCDBMetaData);
988         fStatusEntry->SetOwner(1);
989
990         Int_t logLevel = AliLog::GetGlobalLogLevel();
991         AliLog::SetGlobalLogLevel(AliLog::kError);
992
993         UInt_t result = AliCDBManager::Instance()->GetStorage(fgkLocalCDB)->Put(fStatusEntry);
994
995         AliLog::SetGlobalLogLevel((AliLog::EType_t)logLevel);
996
997         if (!result) {
998                 Log("SHUTTLE", Form("WriteShuttleStatus - Failed for %s, run %d",
999                                                 fCurrentDetector.Data(), run));
1000                 return kFALSE;
1001         }
1002         
1003         SendMLDetInfo();
1004
1005         return kTRUE;
1006 }
1007
1008 //______________________________________________________________________________________________
1009 void AliShuttle::UpdateShuttleStatus(AliShuttleStatus::Status newStatus, Bool_t increaseCount)
1010 {
1011         //
1012         // changes the AliShuttleStatus for the given detector and run to the given status
1013         //
1014
1015         if (!fStatusEntry){
1016                 AliError("UNEXPECTED: fStatusEntry empty");
1017                 return;
1018         }
1019
1020         AliShuttleStatus* status = dynamic_cast<AliShuttleStatus*> (fStatusEntry->GetObject());
1021
1022         if (!status){
1023                 Log("SHUTTLE", "UpdateShuttleStatus - UNEXPECTED: status could not be read from current CDB entry");
1024                 return;
1025         }
1026
1027         TString actionStr = Form("UpdateShuttleStatus - %s: Changing state from %s to %s",
1028                                 fCurrentDetector.Data(),
1029                                 status->GetStatusName(),
1030                                 status->GetStatusName(newStatus));
1031         Log("SHUTTLE", actionStr);
1032         SetLastAction(actionStr);
1033
1034         status->SetStatus(newStatus);
1035         if (increaseCount) status->IncreaseCount();
1036
1037         Int_t logLevel = AliLog::GetGlobalLogLevel();
1038         AliLog::SetGlobalLogLevel(AliLog::kError);
1039
1040         AliCDBManager::Instance()->GetStorage(fgkLocalCDB)->Put(fStatusEntry);
1041
1042         AliLog::SetGlobalLogLevel((AliLog::EType_t)logLevel);
1043
1044         SendMLDetInfo();
1045 }
1046
1047 //______________________________________________________________________________________________
1048 void AliShuttle::SendMLDetInfo()
1049 {
1050         //
1051         // sends ML information about the current status of the current detector being processed
1052         //
1053         
1054         AliShuttleStatus* status = dynamic_cast<AliShuttleStatus*> (fStatusEntry->GetObject());
1055         
1056         if (!status){
1057                 Log("SHUTTLE", "SendMLDetInfo - UNEXPECTED: status could not be read from current CDB entry");
1058                 return;
1059         }
1060         
1061         TMonaLisaText  mlStatus(Form("%s_status", fCurrentDetector.Data()), status->GetStatusName());
1062         TMonaLisaValue mlRetryCount(Form("%s_count", fCurrentDetector.Data()), status->GetCount());
1063
1064         TList mlList;
1065         mlList.Add(&mlStatus);
1066         mlList.Add(&mlRetryCount);
1067
1068         TString mlID;
1069         mlID.Form("%d", GetCurrentRun());
1070         fMonaLisa->SendParameters(&mlList, mlID);
1071 }
1072
1073 //______________________________________________________________________________________________
1074 Bool_t AliShuttle::ContinueProcessing()
1075 {
1076         // this function reads the AliShuttleStatus information from CDB and
1077         // checks if the processing should be continued
1078         // if yes it returns kTRUE and updates the AliShuttleStatus with nextStatus
1079
1080         if (!fConfig->HostProcessDetector(fCurrentDetector))
1081                 return kFALSE;
1082
1083         AliPreprocessor* aPreprocessor =
1084                 dynamic_cast<AliPreprocessor*> (fPreprocessorMap.GetValue(fCurrentDetector));
1085         if (!aPreprocessor)
1086         {
1087                 Log("SHUTTLE", Form("ContinueProcessing - %s: no preprocessor registered", fCurrentDetector.Data()));
1088                 return kFALSE;
1089         }
1090
1091         AliShuttleLogbookEntry::Status entryStatus =
1092                 fLogbookEntry->GetDetectorStatus(fCurrentDetector);
1093
1094         if (entryStatus != AliShuttleLogbookEntry::kUnprocessed) {
1095                 Log("SHUTTLE", Form("ContinueProcessing - %s is %s",
1096                                 fCurrentDetector.Data(),
1097                                 fLogbookEntry->GetDetectorStatusName(entryStatus)));
1098                 return kFALSE;
1099         }
1100
1101         // if we get here, according to Shuttle logbook subdetector is in UNPROCESSED state
1102
1103         // check if current run is first unprocessed run for current detector
1104         if (fConfig->StrictRunOrder(fCurrentDetector) &&
1105                 !fFirstUnprocessed[GetDetPos(fCurrentDetector)])
1106         {
1107                 if (fTestMode == kNone)
1108                 {
1109                         Log("SHUTTLE", Form("ContinueProcessing - %s requires strict run ordering"
1110                                             " but this is not the first unprocessed run!",fCurrentDetector.Data()));
1111                         return kFALSE;
1112                 }
1113                 else
1114                 {
1115                         Log("SHUTTLE", Form("ContinueProcessing - In TESTMODE - "
1116                                         "Although %s requires strict run ordering "
1117                                         "and this is not the first unprocessed run, "
1118                                             "the SHUTTLE continues",fCurrentDetector.Data()));
1119                 }
1120         }
1121
1122         // Is the subdetector processed first time for this run?
1123         fFirstProcessing = kFALSE;
1124
1125         AliShuttleStatus* status = ReadShuttleStatus();
1126         if (!status) {
1127                 // first time
1128                 Log("SHUTTLE", Form("ContinueProcessing - %s: Processing first time",
1129                                 fCurrentDetector.Data()));
1130                 status = new AliShuttleStatus(AliShuttleStatus::kStarted);
1131                 fFirstProcessing = kTRUE;
1132                 return WriteShuttleStatus(status);
1133         }
1134
1135         // The following case shouldn't happen if Shuttle Logbook was correctly updated.
1136         // If it happens it may mean Logbook updating failed... let's do it now!
1137         if (status->GetStatus() == AliShuttleStatus::kDone ||
1138             status->GetStatus() == AliShuttleStatus::kFailed ||
1139             status->GetStatus() == AliShuttleStatus::kSkipped) {
1140                 Log("SHUTTLE", Form("ContinueProcessing - %s is already %s. Updating Shuttle Logbook",
1141                                         fCurrentDetector.Data(),
1142                                         status->GetStatusName(status->GetStatus())));
1143                 
1144                 if (status->GetStatus() == AliShuttleStatus::kSkipped)
1145                 {
1146                         UpdateShuttleLogbook(fCurrentDetector.Data(), "DONE");
1147                 }
1148                 else
1149                         UpdateShuttleLogbook(fCurrentDetector.Data(), status->GetStatusName(status->GetStatus()));
1150                         
1151                 return kFALSE;
1152         }
1153
1154         if (status->GetStatus() == AliShuttleStatus::kStoreStarted || status->GetStatus() == AliShuttleStatus::kStoreDelayed ||status->GetStatus() == AliShuttleStatus::kStoreError) {
1155                 Log("SHUTTLE",
1156                         Form("ContinueProcessing - %s: Grid storage of one or more "
1157                                 "objects failed. Trying again now",
1158                                 fCurrentDetector.Data()));
1159                 StoreOCDB();
1160                 return kFALSE;
1161         }
1162
1163         // if we get here, there is a restart
1164         Bool_t cont = kFALSE;
1165
1166         // abort conditions
1167         if (status->GetCount() >= fConfig->GetMaxRetries()) {
1168                 Log("SHUTTLE", Form("ContinueProcessing - %s failed %d times in status %s - "
1169                                 "Updating Shuttle Logbook", fCurrentDetector.Data(),
1170                                 status->GetCount(), status->GetStatusName()));
1171                 UpdateShuttleLogbook(fCurrentDetector.Data(), "FAILED");
1172                 UpdateShuttleStatus(AliShuttleStatus::kFailed);
1173
1174                 // there may still be objects in local OCDB and reference storage
1175                 // and FXS databases may be not updated: do it now!
1176                 
1177                 // TODO Currently disabled, we want to keep files in case of failure!
1178                 // CleanLocalStorage(fgkLocalCDB);
1179                 // CleanLocalStorage(fgkLocalRefStorage);
1180                 // UpdateTableFailCase();
1181                 
1182                 // Send mail to detector expert!
1183                 Log("SHUTTLE", Form("ContinueProcessing - Sending mail to %s expert...", 
1184                                     fCurrentDetector.Data()));
1185                 // det experts in to
1186                 TString to="";
1187                 TIter *iterExperts = 0;
1188                 iterExperts = new TIter(fConfig->GetResponsibles(fCurrentDetector));
1189                 TObjString *anExpert=0;
1190                 while ((anExpert = (TObjString*) iterExperts->Next()))
1191                         {
1192                                 to += Form("%s, \n", anExpert->GetName());
1193                         }
1194                 delete iterExperts;
1195                 
1196                 if (to.Length() > 0)
1197                         to.Remove(to.Length()-3);
1198                 AliDebug(2, Form("to: %s",to.Data()));
1199
1200                 if (to.IsNull()) {
1201                         Log("SHUTTLE", Form("List of %s responsibles not set!", fCurrentDetector.Data()));
1202                         return kFALSE;
1203                 }
1204
1205                 Log(fCurrentDetector.Data(), Form("ContinueProcessing - Sending mail to %s expert(s):", 
1206                                     fCurrentDetector.Data()));
1207                 Log(fCurrentDetector.Data(), Form("\n%s", to.Data()));
1208                 if (!SendMail(kPPEMail))
1209                         Log("SHUTTLE", Form("ContinueProcessing - Could not send mail to %s expert",
1210                                             fCurrentDetector.Data()));
1211
1212         } else {
1213                 Log("SHUTTLE", Form("ContinueProcessing - %s: restarting. "
1214                                 "Aborted before with %s. Retry number %d.", fCurrentDetector.Data(),
1215                                 status->GetStatusName(), status->GetCount()));
1216                 Bool_t increaseCount = kTRUE;
1217                 if (status->GetStatus() == AliShuttleStatus::kDCSError || 
1218                     status->GetStatus() == AliShuttleStatus::kDCSStarted ||
1219                     status->GetStatus() == AliShuttleStatus::kFXSError ||
1220                     status->GetStatus() == AliShuttleStatus::kOCDBError)
1221                                 increaseCount = kFALSE;
1222                                 
1223                 UpdateShuttleStatus(AliShuttleStatus::kStarted, increaseCount);
1224                 cont = kTRUE;
1225         }
1226
1227         return cont;
1228 }
1229
1230 //______________________________________________________________________________________________
1231 void AliShuttle::SendMLRunInfo(const char* status)
1232 {
1233         // 
1234         // Send information about this run to ML
1235         
1236         TMonaLisaText  mlStatus("SHUTTLE_status", status);
1237         TString runType(fLogbookEntry->GetRunType());
1238         if (strlen(fLogbookEntry->GetRunParameter("log")) > 0){
1239
1240                 runType += "(";
1241                 runType += fLogbookEntry->GetRunParameter("log");
1242                 runType += ")";
1243         }
1244         if (fLogbookEntry->GetDATestMode()){
1245                 runType += " (DATest)";
1246         }
1247         TMonaLisaText  mlRunType("SHUTTLE_runtype", runType);
1248
1249         TList mlList;
1250         mlList.Add(&mlStatus);
1251         mlList.Add(&mlRunType);
1252
1253         TString mlID;
1254         mlID.Form("%d", GetCurrentRun());
1255         fMonaLisa->SendParameters(&mlList, mlID);       
1256 }
1257
1258 //______________________________________________________________________________________________
1259 Int_t AliShuttle::GetMem(Int_t pid)
1260 {
1261         // invokes ps to get the memory consumption of the process <pid>
1262         // returns -1 in case of error
1263         
1264         TString checkStr;
1265         checkStr.Form("ps -o vsize --pid %d | tail -n 1", pid);
1266         FILE* pipe = gSystem->OpenPipe(checkStr, "r");
1267         if (!pipe)
1268         {
1269                 Log("SHUTTLE", Form("Process - Error: "
1270                         "Could not open pipe to %s", checkStr.Data()));
1271                 return -1;
1272         }
1273                 
1274         char buffer[100];
1275         if (!fgets(buffer, 100, pipe))
1276         {
1277                 Log("SHUTTLE", "Process - Error: ps did not return anything");
1278                 gSystem->ClosePipe(pipe);
1279                 return -1;
1280         }
1281         gSystem->ClosePipe(pipe);
1282         
1283         //Log("SHUTTLE", Form("ps returned %s", buffer));
1284         
1285         Int_t mem = 0;
1286         if ((sscanf(buffer, "%d\n", &mem) != 1) || !mem)
1287         {
1288                 Log("SHUTTLE", "Process - Error: Could not parse output of ps");
1289                 return -1;
1290         }
1291         
1292         return mem;
1293 }
1294
1295 //______________________________________________________________________________________________
1296 Bool_t AliShuttle::Process(AliShuttleLogbookEntry* entry)
1297 {
1298         //
1299         // Makes data retrieval for all detectors in the configuration.
1300         // entry: Shuttle logbook entry, contains run paramenters and status of detectors
1301         // (Unprocessed, Inactive, Failed or Done).
1302         // Returns kFALSE in case of error occured and kTRUE otherwise
1303         //
1304
1305         if (!entry) return kFALSE;
1306
1307         fLogbookEntry = entry;
1308
1309         Log("SHUTTLE", Form("\t\t\t^*^*^*^*^*^*^*^*^*^*^*^* run %d: START ^*^*^*^*^*^*^*^*^*^*^*^*",
1310                                         GetCurrentRun()));
1311
1312         CountOpenRuns();
1313         
1314         // Send the information to ML
1315         SendMLRunInfo("Processing");
1316
1317         if (fLogbookEntry->IsDone())
1318         {
1319                 Log("SHUTTLE","Process - Shuttle is already DONE. Updating logbook");
1320                 UpdateShuttleLogbook("shuttle_done");
1321                 fLogbookEntry = 0;
1322                 return kTRUE;
1323         }
1324
1325         // read test mode if flag is set
1326         if (fReadTestMode)
1327         {
1328                 fTestMode = kNone;
1329                 TString logEntry(entry->GetRunParameter("log"));
1330                 //printf("log entry = %s\n", logEntry.Data());
1331                 TString searchStr("Testmode: ");
1332                 Int_t pos = logEntry.Index(searchStr.Data());
1333                 //printf("%d\n", pos);
1334                 if (pos >= 0)
1335                 {
1336                         TSubString subStr = logEntry(pos + searchStr.Length(), logEntry.Length());
1337                         //printf("%s\n", subStr.String().Data());
1338                         TString newStr(subStr.Data());
1339                         TObjArray* token = newStr.Tokenize(' ');
1340                         if (token)
1341                         {
1342                                 //token->Print();
1343                                 TObjString* tmpStr = dynamic_cast<TObjString*> (token->First());
1344                                 if (tmpStr)
1345                                 {
1346                                         Int_t testMode = tmpStr->String().Atoi();
1347                                         if (testMode > 0)
1348                                         {
1349                                                 Log("SHUTTLE", Form("Process - Enabling test mode %d", testMode));
1350                                                 SetTestMode((TestMode) testMode);
1351                                         }
1352                                 }
1353                                 delete token;          
1354                         }
1355                 }
1356         }
1357                 
1358         fLogbookEntry->Print("all");
1359
1360         // Initialization
1361         Bool_t hasError = kFALSE;
1362
1363         // Set the CDB and Reference folders according to the year
1364
1365         // build cdb paths (repeat each time, run might be a DATest run)
1366         if (!fLogbookEntry->GetDATestMode()){
1367                 fgkMainCDB.Form("alien://folder=%s%d/OCDB?user=alidaq?cacheFold=/tmp/OCDBCache", 
1368                                 fConfig->GetAlienPath(), GetCurrentYear());
1369                 
1370                 fgkMainRefStorage.Form("alien://folder=%s%d/Reference?user=alidaq?cacheFold=/tmp/OCDBCache", 
1371                                        fConfig->GetAlienPath(), GetCurrentYear());
1372         }
1373         else {
1374                 fgkMainCDB.Form("alien://folder=%s%d/DATest/OCDB?user=alidaq?cacheFold=/tmp/OCDBCache",
1375                                 fConfig->GetAlienPath(), GetCurrentYear());
1376                 
1377                 fgkMainRefStorage.Form("alien://folder=%s%d/DATest/Reference?user=alidaq?cacheFold=/tmp/OCDBCache",
1378                                        fConfig->GetAlienPath(), GetCurrentYear());
1379         }
1380
1381         AliDebug(2,Form("Main CDB storage = %s",fgkMainCDB.Data()));
1382         AliDebug(2,Form("Main Reference storage = %s",fgkMainRefStorage.Data()));
1383
1384         // Loop on detectors in the configuration
1385         TIter iter(fConfig->GetDetectors());
1386         TObjString* aDetector = 0;
1387
1388         Bool_t first = kTRUE;
1389
1390         while ((aDetector = (TObjString*) iter.Next()))
1391         {
1392                 fCurrentDetector = aDetector->String();
1393
1394                 if (ContinueProcessing() == kFALSE) 
1395                         continue;
1396                 
1397                 if (first)
1398                 {
1399                   // only read QueryCDB when needed and only once
1400                   AliCDBStorage *mainCDBSto = AliCDBManager::Instance()->GetStorage(fgkMainCDB);
1401                   if(mainCDBSto) mainCDBSto->QueryCDB(GetCurrentRun());
1402                   AliCDBStorage *mainRefSto = AliCDBManager::Instance()->GetStorage(fgkMainRefStorage);
1403                   if(mainRefSto) mainRefSto->QueryCDB(GetCurrentRun());
1404                   first = kFALSE;
1405                 }
1406
1407                 Log("SHUTTLE", Form("\t\t\t****** run %d - %s: START  ******",
1408                                                 GetCurrentRun(), aDetector->GetName()));
1409
1410                 for(Int_t iSys=0;iSys<4;iSys++) fFXSCalled[iSys]=kFALSE;
1411                 
1412                 Int_t initialMem = GetMem(getpid());
1413                 Log("SHUTTLE", Form("Memory consumption before forking is %d", initialMem));
1414
1415                 Log(fCurrentDetector.Data(), "Process - Starting processing");
1416
1417                 Int_t pid = fork();
1418
1419                 if (pid < 0)
1420                 {
1421                         Log("SHUTTLE", "Process - ERROR: Forking failed");
1422                 }
1423                 else if (pid > 0)
1424                 {
1425                         // parent
1426                         Log("SHUTTLE", Form("Process - In parent process of %d - %s: Starting monitoring",
1427                                                         GetCurrentRun(), aDetector->GetName()));
1428
1429                         Long_t begin = time(0);
1430
1431                         int status; // to be used with waitpid, on purpose an int (not Int_t)!
1432                         while (waitpid(pid, &status, WNOHANG) == 0)
1433                         {
1434                                 Long_t expiredTime = time(0) - begin;
1435
1436                                 if (expiredTime > fConfig->GetPPTimeOut())
1437                                 {
1438                                         TString logMsg;
1439                                         AliShuttleStatus *currentStatus = ReadShuttleStatus();
1440                                         AliShuttleStatus::Status newStatus = AliShuttleStatus::kInvalid;
1441                                         
1442                                         if (currentStatus->GetStatus() == AliShuttleStatus::kDCSStarted)
1443                                         {
1444                                                 // in case the pp goes in TimeOut while retrieving the DCS DPs
1445                                                 // set status to kDCSError
1446                                                 
1447                                                 logMsg.Form("Process - Process of %s timed out while retrieving the DCS DataPoints. Run time: %ld seconds. Killing... and setting status to DCSError.",
1448                                                                 fCurrentDetector.Data(), expiredTime);
1449                                                 newStatus = AliShuttleStatus::kDCSError;
1450                                         }
1451                                         else if (currentStatus->GetStatus() <= AliShuttleStatus::kPPDone)
1452                                         {
1453                                                 // in case pp not yet done set status to kPPTimeOut
1454                                         
1455                                                 logMsg.Form("Process - Process of %s timed out. Run time: %ld seconds. Killing...",
1456                                                                 fCurrentDetector.Data(), expiredTime);
1457                                                 newStatus = AliShuttleStatus::kPPTimeOut;
1458                                         }
1459                                         else if (currentStatus->GetStatus() == AliShuttleStatus::kStoreStarted)
1460                                         {
1461                                                 // in case the pp goes in TimeOut while storing the objects in the OCDB
1462                                                 // set status to kStoreError
1463                                                 
1464                                                 logMsg.Form("Process - Process of %s timed out while storing the OCDB object. Run time: %ld seconds. Killing... and setting status to StoreError.",
1465                                                                 fCurrentDetector.Data(), expiredTime);
1466                                                 newStatus = AliShuttleStatus::kStoreError;
1467                                         }
1468                                         else 
1469                                         {
1470                                                 // in other cases don't change the status
1471                                                 
1472                                                 logMsg.Form("Process - Process of %s timed out in status = %s. Run time: %ld seconds. Killing... without changing the status",
1473                                                                 fCurrentDetector.Data(), currentStatus->GetStatusName(), expiredTime);
1474                                         }
1475                                 
1476                                         Log("SHUTTLE", logMsg);
1477                                         Log(fCurrentDetector, logMsg);
1478
1479                                         kill(pid, 9);
1480
1481                                         if (newStatus != AliShuttleStatus::kInvalid)
1482                                                 UpdateShuttleStatus(newStatus);
1483                                         hasError = kTRUE;
1484
1485                                         gSystem->Sleep(1000);
1486                                 }
1487                                 else
1488                                 {
1489                                         gSystem->Sleep(1000);
1490                                         
1491                                         Int_t mem = GetMem(pid);
1492
1493                                         if (mem < 0)
1494                                                 continue;
1495                                                 
1496                                         mem -= initialMem;
1497                                         if (mem < 0)
1498                                                 mem = 0;
1499                                         
1500                                         if (expiredTime % 60 == 0)
1501                                         {
1502                                                 Log("SHUTTLE", Form("Process - %s: Checking process. "
1503                                                         "Run time: %ld seconds - Memory consumption: %d KB",
1504                                                         fCurrentDetector.Data(), expiredTime, mem));
1505                                                 SendAlive();
1506                                         }
1507                                         
1508                                         if (mem > fConfig->GetPPMaxMem())
1509                                         {
1510                                                 TString tmp;
1511                                                 tmp.Form("Process - Process exceeds maximum allowed memory "
1512                                                         "(%d KB > %d KB). Killing...",
1513                                                         mem, fConfig->GetPPMaxMem());
1514                                                 Log("SHUTTLE", tmp);
1515                                                 Log(fCurrentDetector, tmp);
1516         
1517                                                 kill(pid, 9);
1518         
1519                                                 UpdateShuttleStatus(AliShuttleStatus::kPPOutOfMemory);
1520                                                 hasError = kTRUE;
1521         
1522                                                 gSystem->Sleep(1000);
1523                                         }
1524                                 }
1525                         }
1526
1527                         Log("SHUTTLE", Form("Process - In parent process of %d - %s: Client has terminated.",
1528                                                                 GetCurrentRun(), aDetector->GetName()));
1529
1530                         if (WIFEXITED(status))
1531                         {
1532                                 Int_t returnCode = WEXITSTATUS(status);
1533
1534                                 Log("SHUTTLE", Form("Process - %s: the return code is %d", fCurrentDetector.Data(),
1535                                                                                 returnCode));
1536
1537                                 if (returnCode == 0) hasError = kTRUE;
1538                         }
1539                 }
1540                 else if (pid == 0)
1541                 {
1542                         // child
1543                         Log("SHUTTLE", Form("Process - In child process of %d - %s", GetCurrentRun(),
1544                                 aDetector->GetName()));
1545
1546                         Log("SHUTTLE", Form("Process - Redirecting output to %s log",fCurrentDetector.Data()));
1547
1548                         if ((freopen(GetLogFileName(fCurrentDetector), "a", stdout)) == 0)
1549                         {
1550                                 Log("SHUTTLE", "Process - Could not freopen stdout");
1551                         }
1552                         else
1553                         {
1554                                 fOutputRedirected = kTRUE;
1555                                 if ((dup2(fileno(stdout), fileno(stderr))) < 0)
1556                                         Log("SHUTTLE", "Process - Could not redirect stderr");
1557                                 
1558                         }
1559
1560                         Log("SHUTTLE", "Executing TGrid::Connect");
1561                         TGrid::Connect("alien://");
1562                         
1563                         TString wd = gSystem->WorkingDirectory();
1564                         Int_t dir_lev1 = GetCurrentRun()/10000;
1565                         TString tmpDir = Form("%s/%d/%d/%s_process", GetShuttleTempDir(), 
1566                                 dir_lev1, GetCurrentRun(), fCurrentDetector.Data());
1567                         
1568                         Int_t result = gSystem->GetPathInfo(tmpDir.Data(), 0, (Long64_t*) 0, 0, 0);
1569                         if (!result) // temp dir already exists!
1570                         {
1571                                 Log(fCurrentDetector.Data(), 
1572                                         Form("Process - %s dir already exists! Removing...", tmpDir.Data()));
1573                                 gSystem->Exec(Form("rm -rf %s",tmpDir.Data()));         
1574                         } 
1575                         
1576                         if (gSystem->mkdir(tmpDir.Data(), 1))
1577                         {
1578                                 Log(fCurrentDetector.Data(), "Process - could not make temp directory!!");
1579                                 gSystem->Exit(1);
1580                         }
1581                         
1582                         if (!gSystem->ChangeDirectory(tmpDir.Data())) 
1583                         {
1584                                 Log(fCurrentDetector.Data(), "Process - could not change directory!!");
1585                                 gSystem->Exit(1);                       
1586                         }
1587                         
1588                         Int_t success = ProcessCurrentDetector();
1589
1590                         gSystem->ChangeDirectory(wd.Data());
1591                                                 
1592                         if (success == 1) // Preprocessor finished successfully!
1593                         { 
1594                                 // remove temporary folder or DCS map
1595                                 if (!fConfig->KeepTempFolder())
1596                                 {
1597                                         gSystem->Exec(Form("rm -rf %s",tmpDir.Data()));
1598                                 } else if (!fConfig->KeepDCSMap())
1599                                 {
1600                                         gSystem->Exec(Form("rm -f %s/DCSMap.root",tmpDir.Data()));
1601                                 }
1602                                 
1603                                 // Update time_processed field in FXS DB
1604                                 if (UpdateTable() == kFALSE)
1605                                         Log("SHUTTLE", Form("Process - %s: Could not update FXS databases!", 
1606                                                         fCurrentDetector.Data()));
1607
1608                                 // Transfer the data from local storage to main storage (Grid)
1609                                 if (StoreOCDB() == kFALSE)
1610                                         success = kFALSE;
1611                         } 
1612                         else if (success == 0)
1613                         {
1614                                 Log("SHUTTLE", 
1615                                         Form("\t\t\t****** run %d - %s: ERROR ******",
1616                                                 GetCurrentRun(), aDetector->GetName()));
1617                         }
1618
1619                         for (UInt_t iSys=0; iSys<4; iSys++)
1620                         {
1621                                 if (fFXSCalled[iSys]) fFXSlist[iSys].Clear();
1622                         }
1623
1624                         Log("SHUTTLE", Form("Process - Client process of %d - %s is exiting now with %d.",
1625                                                         GetCurrentRun(), aDetector->GetName(), success));
1626
1627                         // the client exits here
1628                         gSystem->Exit(success);
1629
1630                         AliError("We should never get here!!!");
1631                 }
1632         }
1633
1634         Log("SHUTTLE", Form("\t\t\t^*^*^*^*^*^*^*^*^*^*^*^* run %d: FINISH ^*^*^*^*^*^*^*^*^*^*^*^*",
1635                                                         GetCurrentRun()));
1636
1637         //check if shuttle is done for this run, if so update logbook
1638         TObjArray checkEntryArray;
1639         checkEntryArray.SetOwner(1);
1640         TString whereClause = Form("where run=%d", GetCurrentRun());
1641         if (!QueryShuttleLogbook(whereClause.Data(), checkEntryArray) || 
1642                         checkEntryArray.GetEntries() == 0) {
1643                 Log("SHUTTLE", Form("Process - Warning: Cannot check status of run %d on Shuttle logbook!",
1644                                                 GetCurrentRun()));
1645                 return hasError == kFALSE;
1646         }
1647
1648         AliShuttleLogbookEntry* checkEntry = dynamic_cast<AliShuttleLogbookEntry*>
1649                                                 (checkEntryArray.At(0));
1650
1651         if (checkEntry)
1652         {
1653                 if (checkEntry->IsDone())
1654                 {
1655                         Log("SHUTTLE","Process - Shuttle is DONE. Updating logbook");
1656                         UpdateShuttleLogbook("shuttle_done");
1657                 }
1658                 else
1659                 {
1660                         for (UInt_t iDet=0; iDet<NDetectors(); iDet++)
1661                         {
1662                                 if (checkEntry->GetDetectorStatus(iDet) == AliShuttleLogbookEntry::kUnprocessed)
1663                                 {
1664                                         AliDebug(2, Form("Run %d: setting %s as \"not first time unprocessed\"",
1665                                                         checkEntry->GetRun(), GetDetName(iDet)));
1666                                         fFirstUnprocessed[iDet] = kFALSE;
1667                                 }
1668                         }
1669                         SendMLRunInfo("Pending");
1670                 }
1671         }
1672
1673         fLogbookEntry = 0;
1674
1675         return hasError == kFALSE;
1676 }
1677
1678 //______________________________________________________________________________________________
1679 Int_t AliShuttle::ProcessCurrentDetector()
1680 {
1681         //
1682         // Makes data retrieval just for a specific detector (fCurrentDetector).
1683         // Threre should be a configuration for this detector.
1684
1685         Log("SHUTTLE", Form("ProcessCurrentDetector - Retrieving values for %s, run %d", 
1686                                                 fCurrentDetector.Data(), GetCurrentRun()));
1687
1688         TString wd = gSystem->WorkingDirectory();
1689         
1690         if (!CleanReferenceStorage(fCurrentDetector.Data()))
1691                 return 0;
1692         
1693         gSystem->ChangeDirectory(wd.Data());
1694         
1695         // call preprocessor
1696         AliPreprocessor* aPreprocessor =
1697                 dynamic_cast<AliPreprocessor*> (fPreprocessorMap.GetValue(fCurrentDetector));
1698
1699         // check if the preprocessor wants to process this run type
1700         if (aPreprocessor->ProcessRunType() == kFALSE)
1701         {
1702                 UpdateShuttleStatus(AliShuttleStatus::kSkipped);
1703                 UpdateShuttleLogbook(fCurrentDetector, "DONE");
1704                 if (!UpdateTableSkippedCase(fCurrentDetector.Data()))
1705                 {
1706                         AliError(Form("Could not update FXS tables for run %d !", GetCurrentRun()));
1707                 }
1708                 Log(fCurrentDetector, Form("ProcessCurrentDetector - %s preprocessor is not interested in this run type", fCurrentDetector.Data()));
1709         
1710                 return 2;
1711         }
1712         
1713         // checking if OCDB is reachable
1714         AliCDBEntry* testEntry = GetFromOCDB("SHUTTLE","GRP/CTP/DummyConfig");
1715         if (!testEntry){
1716                 // OCDB is not accessible, going in OCDBError for current detector
1717                 AliError("OCDB Test entry not accessible");
1718                 UpdateShuttleStatus(AliShuttleStatus::kOCDBError);
1719                 return 0;
1720         }
1721
1722         TMap* dcsMap = new TMap();
1723         
1724         aPreprocessor->Initialize(GetCurrentRun(), GetCurrentStartTime(), GetCurrentEndTime());
1725
1726         Bool_t processDCS = aPreprocessor->ProcessDCS();
1727
1728         if (!processDCS)
1729         {
1730                 Log(fCurrentDetector, "ProcessCurrentDetector -"
1731                         " The preprocessor requested to skip the retrieval of DCS values");
1732         }
1733         else if (fTestMode & kSkipDCS)
1734         {
1735                 Log(fCurrentDetector, "ProcessCurrentDetector - In TESTMODE: Skipping DCS processing");
1736         } 
1737         else if (fTestMode & kErrorDCS)
1738         {
1739                 Log(fCurrentDetector, "ProcessCurrentDetector - In TESTMODE: Simulating DCS error");
1740                 UpdateShuttleStatus(AliShuttleStatus::kDCSStarted);
1741                 UpdateShuttleStatus(AliShuttleStatus::kDCSError);
1742                 delete dcsMap;
1743                 return 0;
1744         } else {
1745
1746                 UpdateShuttleStatus(AliShuttleStatus::kDCSStarted);
1747
1748                 // Query DCS archive
1749                 Int_t nServers = fConfig->GetNServers(fCurrentDetector);
1750                 
1751                 for (int iServ=0; iServ<nServers; iServ++)
1752                 {
1753                 
1754                         TString host(fConfig->GetDCSHost(fCurrentDetector, iServ));
1755                         Int_t port = fConfig->GetDCSPort(fCurrentDetector, iServ);
1756                         Int_t multiSplit = fConfig->GetMultiSplit(fCurrentDetector, iServ);
1757
1758                         Log(fCurrentDetector, Form("ProcessCurrentDetector -"
1759                                         " Querying DCS Amanda server %s:%d (%d of %d)", 
1760                                         host.Data(), port, iServ+1, nServers));
1761                         
1762                         TMap* aliasMap = 0;
1763                         TMap* dpMap = 0;
1764
1765                         if (fConfig->GetDCSAliases(fCurrentDetector, iServ)->GetEntries() > 0)
1766                         {
1767                                 Log(fCurrentDetector, Form("Querying %d DCS aliases", fConfig->GetDCSAliases(fCurrentDetector, iServ)->GetEntries()));
1768                                 aliasMap = GetValueSet(host, port, 
1769                                                 fConfig->GetDCSAliases(fCurrentDetector, iServ), 
1770                                                 kAlias, multiSplit);
1771                                 if (!aliasMap)
1772                                 {
1773                                         Log(fCurrentDetector, 
1774                                                 Form("ProcessCurrentDetector -"
1775                                                         " Error retrieving DCS aliases from server %s."
1776                                                         " Sending mail to DCS experts!", host.Data()));
1777                                         UpdateShuttleStatus(AliShuttleStatus::kDCSError);
1778                                         
1779                                         if (!SendMail(kDCSEMail))
1780                                                 Log("SHUTTLE", Form("ProcessCurrentDetector - "
1781                                                                     "Could not send mail to DCS experts!"));
1782
1783                                         delete dcsMap;
1784                                         return 0;
1785                                 }
1786                         }
1787                         
1788                         if (fConfig->GetDCSDataPoints(fCurrentDetector, iServ)->GetEntries() > 0)
1789                         {
1790                                 Log(fCurrentDetector, Form("Querying %d DCS data points", fConfig->GetDCSDataPoints(fCurrentDetector, iServ)->GetEntries()));
1791                                 dpMap = GetValueSet(host, port, 
1792                                                 fConfig->GetDCSDataPoints(fCurrentDetector, iServ), 
1793                                                 kDP, multiSplit);
1794                                 if (!dpMap)
1795                                 {
1796                                         Log(fCurrentDetector, 
1797                                                 Form("ProcessCurrentDetector -"
1798                                                         " Error retrieving DCS data points from server %s."
1799                                                         " Sending mail to DCS experts!", host.Data()));
1800                                         UpdateShuttleStatus(AliShuttleStatus::kDCSError);
1801                                         
1802                                         if (!SendMail(kDCSEMail))
1803                                                 Log("SHUTTLE", Form("ProcessCurrentDetector - "
1804                                                                     "Could not send mail to DCS experts!"));
1805                                         
1806                                         if (aliasMap) delete aliasMap;
1807                                         delete dcsMap;
1808                                         return 0;
1809                                 }                               
1810                         }
1811                         
1812                         // merge aliasMap and dpMap into dcsMap
1813                         if(aliasMap) {
1814                                 TIter iter(aliasMap);
1815                                 TObjString* key = 0;
1816                                 while ((key = (TObjString*) iter.Next()))
1817                                         dcsMap->Add(key, aliasMap->GetValue(key->String()));
1818                                 
1819                                 aliasMap->SetOwner(kFALSE);
1820                                 delete aliasMap;
1821                         }       
1822                         
1823                         if(dpMap) {
1824                                 TIter iter(dpMap);
1825                                 TObjString* key = 0;
1826                                 while ((key = (TObjString*) iter.Next()))
1827                                         dcsMap->Add(key, dpMap->GetValue(key->String()));
1828                                 
1829                                 dpMap->SetOwner(kFALSE);
1830                                 delete dpMap;
1831                         }
1832                 }
1833         }
1834         
1835         // save map into file, to help debugging in case of preprocessor error
1836         TFile* f = TFile::Open("DCSMap.root","recreate");
1837         f->cd();
1838         dcsMap->Write("DCSMap", TObject::kSingleKey);
1839         f->Close();
1840         delete f;
1841         
1842         // DCS Archive DB processing successful. Call Preprocessor!
1843         UpdateShuttleStatus(AliShuttleStatus::kPPStarted);
1844
1845         fFXSError = -1; // this variable is kTRUE after ::Process if an FXS error occured
1846         
1847         UInt_t returnValue = aPreprocessor->Process(dcsMap);
1848         
1849         if (fFXSError!=-1) {
1850                 UpdateShuttleStatus(AliShuttleStatus::kFXSError);
1851                 SendMail(kFXSEMail, fFXSError);
1852                 dcsMap->DeleteAll();
1853                 delete dcsMap;
1854                 return 0;
1855         }
1856
1857         if (returnValue > 0) // Preprocessor error!
1858         {
1859                 Log(fCurrentDetector, Form("ProcessCurrentDetector - "
1860                                 "Preprocessor failed. Process returned %d.", returnValue));
1861                 UpdateShuttleStatus(AliShuttleStatus::kPPError);
1862                 dcsMap->DeleteAll();
1863                 delete dcsMap;
1864                 return 0;
1865         }
1866         
1867         // preprocessor ok!
1868         UpdateShuttleStatus(AliShuttleStatus::kPPDone);
1869         Log(fCurrentDetector, Form("ProcessCurrentDetector - %s preprocessor returned success",
1870                                 fCurrentDetector.Data()));
1871
1872         dcsMap->DeleteAll();
1873         delete dcsMap;
1874
1875         return 1;
1876 }
1877
1878 //______________________________________________________________________________________________
1879 void AliShuttle::CountOpenRuns()
1880 {
1881         // Query DAQ's Shuttle logbook and sends the number of open runs to ML
1882         
1883         SendAlive();
1884         
1885         // check connection, in case connect
1886         if (!Connect(4)) 
1887                 return;
1888
1889         TString sqlQuery;
1890         sqlQuery = Form("select count(*) from %s where shuttle_done=0", fConfig->GetShuttlelbTable());
1891         
1892         TSQLResult* aResult = fServer[4]->Query(sqlQuery);
1893         if (!aResult) {
1894                 AliError(Form("Can't execute query <%s>!", sqlQuery.Data()));
1895                 return;
1896         }
1897
1898         AliDebug(2,Form("Query = %s", sqlQuery.Data()));
1899         
1900         if (aResult->GetRowCount() == 0) {
1901                 AliError(Form("No result for query %s received", sqlQuery.Data()));
1902                 return;
1903         }
1904
1905         if (aResult->GetFieldCount() != 1) {
1906                 AliError(Form("Invalid field count for query %s received", sqlQuery.Data()));
1907                 return;
1908         }
1909
1910         TSQLRow* aRow = aResult->Next();
1911         if (!aRow) {
1912                 AliError(Form("Could not receive result of query %s", sqlQuery.Data()));
1913                 return;
1914         }
1915         
1916         TString result(aRow->GetField(0), aRow->GetFieldLength(0));
1917         Int_t count = result.Atoi();
1918         
1919         Log("SHUTTLE", Form("%d unprocessed runs", count));
1920         
1921         delete aRow;
1922         delete aResult;
1923
1924         TMonaLisaValue mlStatus("SHUTTLE_openruns", count);
1925
1926         TList mlList;
1927         mlList.Add(&mlStatus);
1928
1929         fMonaLisa->SendParameters(&mlList, "__PROCESSINGINFO__");
1930 }
1931
1932 //______________________________________________________________________________________________
1933 Bool_t AliShuttle::QueryShuttleLogbook(const char* whereClause,
1934                 TObjArray& entries)
1935 {
1936         // Query DAQ's Shuttle logbook and fills detector status object.
1937         // Call QueryRunParameters to query DAQ logbook for run parameters.
1938         //
1939
1940         entries.SetOwner(1);
1941
1942         // check connection, in case connect
1943         if (!Connect(4)) return kFALSE;
1944
1945         TString sqlQuery;
1946         sqlQuery = Form("select * from %s %s order by run", fConfig->GetShuttlelbTable(), whereClause);
1947
1948         TSQLResult* aResult = fServer[4]->Query(sqlQuery);
1949         if (!aResult) {
1950                 AliError(Form("Can't execute query <%s>!", sqlQuery.Data()));
1951                 return kFALSE;
1952         }
1953
1954         AliDebug(2,Form("Query = %s", sqlQuery.Data()));
1955
1956         if(aResult->GetRowCount() == 0) {
1957                 Log("SHUTTLE", "No entries in Shuttle Logbook match request");
1958                 delete aResult;
1959                 return kTRUE;
1960         }
1961
1962         // TODO Check field count!
1963         const UInt_t nCols = 26;
1964         if (aResult->GetFieldCount() != (Int_t) nCols) {
1965                 Log("SHUTTLE", "Invalid SQL result field number!");
1966                 delete aResult;
1967                 return kFALSE;
1968         }
1969
1970         TSQLRow* aRow;
1971         while ((aRow = aResult->Next())) {
1972                 TString runString(aRow->GetField(0), aRow->GetFieldLength(0));
1973                 Int_t run = runString.Atoi();
1974
1975                 AliShuttleLogbookEntry *entry = QueryRunParameters(run);
1976                 if (!entry)
1977                         continue;
1978
1979                 // DA test mode flag
1980                 TString daTestModeString(aRow->GetField(2), aRow->GetFieldLength(2)); // field 2 = DA test mode flag 
1981                 Bool_t daTestMode = (Bool_t)daTestModeString.Atoi();
1982                 entry->SetDATestMode(daTestMode);
1983
1984                 // loop on detectors
1985                 for(UInt_t ii = 0; ii < nCols; ii++)
1986                         entry->SetDetectorStatus(aResult->GetFieldName(ii), aRow->GetField(ii));
1987
1988                 entries.AddLast(entry);
1989                 delete aRow;
1990         }
1991
1992         delete aResult;
1993         return kTRUE;
1994 }
1995
1996 //______________________________________________________________________________________________
1997 AliShuttleLogbookEntry* AliShuttle::QueryRunParameters(Int_t run)
1998 {
1999         //
2000         // Retrieve run parameters written in the DAQ logbook and sets them into AliShuttleLogbookEntry object
2001         //
2002
2003         // check connection, in case connect
2004         if (!Connect(4))
2005                 return 0;
2006
2007         TString sqlQuery;
2008         sqlQuery.Form("select * from %s where run=%d", fConfig->GetDAQlbTable(), run);
2009
2010         TSQLResult* aResult = fServer[4]->Query(sqlQuery);
2011         if (!aResult) {
2012                 Log("SHUTTLE", Form("Can't execute query <%s>!", sqlQuery.Data()));
2013                 return 0;
2014         }
2015
2016         if (aResult->GetRowCount() == 0) {
2017                 Log("SHUTTLE", Form("QueryRunParameters - No entry in DAQ Logbook for run %d. Skipping", run));
2018                 delete aResult;
2019                 return 0;
2020         }
2021
2022         if (aResult->GetRowCount() > 1) {
2023                 Log("SHUTTLE", Form("QueryRunParameters - UNEXPECTED: "
2024                                 "more than one entry in DAQ Logbook for run %d!", run));
2025                 delete aResult;
2026                 return 0;
2027         }
2028
2029         TSQLRow* aRow = aResult->Next();
2030         if (!aRow)
2031         {
2032                 Log("SHUTTLE", Form("QueryRunParameters - Could not retrieve row for run %d. Skipping", run));
2033                 delete aResult;
2034                 return 0;
2035         }
2036
2037         AliShuttleLogbookEntry* entry = new AliShuttleLogbookEntry(run);
2038
2039         for (Int_t ii = 0; ii < aResult->GetFieldCount(); ii++)
2040                 entry->SetRunParameter(aResult->GetFieldName(ii), aRow->GetField(ii));
2041
2042         delete aRow;
2043         delete aResult;
2044         
2045         UInt_t startTime = entry->GetStartTime();
2046         UInt_t endTime = entry->GetEndTime();
2047         Bool_t ecsSuccess = entry->GetECSSuccess();
2048         TString runType = entry->GetRunType();
2049         TString tmpdaqstartTime = entry->GetRunParameter("DAQ_time_start");
2050         TString recordingFlagString = entry->GetRunParameter("GDCmStreamRecording");
2051         UInt_t recordingFlag = recordingFlagString.Atoi();
2052         UInt_t daqstartTime = tmpdaqstartTime.Atoi();
2053         
2054         UInt_t now = time(0);
2055         Int_t dcsDelay = fConfig->GetDCSDelay()+fConfig->GetDCSQueryOffset();
2056
2057         Bool_t skip = kFALSE;
2058                                 
2059         // runs are processed if
2060         //   a) runType is PHYSICS and ecsSuccess is set
2061         //   b) runType is not PHYSICS and (ecsSuccess is set or DAQ_time_start is non-0)
2062         // effectively this means that all runs are processed that started properly (ecsSucess behaviour is different for PHYSICS and non-PHYSICS runs (check with ECS!)
2063         if (startTime != 0 && endTime != 0) {
2064                 if (endTime > startTime) { 
2065                         if (endTime >= now - dcsDelay) {
2066                                 Log("SHUTTLE", Form("Skipping run %d for now, because DCS buffer time is not yet expired", run));
2067                         } else {
2068                                 if ((runType == "PHYSICS" || runType == "STANDALONE") && recordingFlag == 0){
2069                                         Log("SHUTTLE", Form("QueryRunParameters - Run type for run %d is %s but the recording is OFF - Skipping!", run, runType.Data()));
2070                                         skip = kTRUE;
2071                                 } 
2072                                 else {
2073                                         if (runType == "PHYSICS") {
2074                                                 if (ecsSuccess) {
2075                                                         return entry;
2076                                                 } else {
2077                                                         Log("SHUTTLE", Form("QueryRunParameters - Run type for run %d is PHYSICS but ECS success flag not set (Reason = %s) - Skipping!", run, entry->GetRunParameter("eor_reason")));
2078                                                         skip = kTRUE;
2079                                                 } 
2080                                         } else {
2081                                                 if (ecsSuccess || daqstartTime > 0) {
2082                                                         if (ecsSuccess == kFALSE)
2083                                                                 Log("SHUTTLE", Form("Processing run %d although in status ECS failure (Reason: %s), since run type != PHYSICS and DAQ_time_start != 0", run, entry->GetRunParameter("eor_reason")));
2084                                                         return entry;
2085                                                 } else {
2086                                                         Log("SHUTTLE", Form("QueryRunParameters - Run type for run %d is %s, ECS success flag was not set (Reason = %s) and DAQ_time_start was NULL - Skipping!", run, runType.Data(), entry->GetRunParameter("eor_reason")));
2087                                                         skip = kTRUE;
2088                                                 }
2089                                         }
2090                                 }
2091                         }
2092                 } else {
2093                         Log("SHUTTLE", Form("QueryRunParameters - Invalid parameters for run %d: startTime equal to endTime: %d %d - Skipping!", run, startTime, endTime));
2094                         skip = kTRUE;
2095                 }
2096         } else {
2097           Log("SHUTTLE", Form("QueryRunParameters - Invalid parameters for Run %d: "
2098                               "startTime = %d, endTime = %d. Skipping (Shuttle won't be marked as DONE)!",
2099                               run, startTime, endTime));
2100         }
2101         
2102         if (skip)
2103         {
2104                 Log("SHUTTLE", Form("Marking SHUTTLE skipped for run %d", run));
2105                 fLogbookEntry = entry;
2106                 if (!UpdateShuttleLogbook("shuttle_skipped"))
2107                 {
2108                         AliError(Form("Could not update logbook for run %d !", run));
2109                 }
2110                 if (!UpdateTableSkippedCase("ALL"))
2111                 {
2112                         AliError(Form("Could not update FXS tables for run %d !", run));
2113                 }
2114                 fLogbookEntry = 0;
2115         }
2116                         
2117         delete entry;
2118         return 0;
2119 }
2120
2121 //______________________________________________________________________________________________
2122 TMap* AliShuttle::GetValueSet(const char* host, Int_t port, const TSeqCollection* entries,
2123                               DCSType type, Int_t multiSplit)
2124 {
2125         // Retrieve all "entry" data points from the DCS server
2126         // host, port: TSocket connection parameters
2127         // entries: list of name of the alias or data point
2128         // type: kAlias or kDP
2129         // returns TMap of values, 0 when failure
2130         
2131         AliDCSClient client(host, port, fTimeout, fRetries, multiSplit);
2132
2133         TMap* result = 0;
2134         if (type == kAlias)
2135         {
2136                 //result = client.GetAliasValues(entries, GetCurrentStartTime()-offset, 
2137                 //      GetCurrentEndTime()+offset);
2138                 result = client.GetAliasValues(entries, GetStartTimeDCSQuery(), 
2139                         GetEndTimeDCSQuery());
2140         } 
2141         else if (type == kDP)
2142         {
2143                 //result = client.GetDPValues(entries, GetCurrentStartTime()-offset, 
2144                 //      GetCurrentEndTime()+offset);
2145                 result = client.GetDPValues(entries, GetStartTimeDCSQuery(), 
2146                         GetEndTimeDCSQuery());
2147         }
2148
2149         if (result == 0)
2150         {
2151                 Log(fCurrentDetector.Data(), Form("GetValueSet - Can't get entries! Reason: %s",
2152                         client.GetErrorString(client.GetResultErrorCode())));
2153                 if (client.GetResultErrorCode() == AliDCSClient::fgkServerError)        
2154                         Log(fCurrentDetector.Data(), Form("GetValueSet - Server error code: %s",
2155                                 client.GetServerError().Data()));
2156
2157                 return 0;
2158         }
2159                 
2160         return result;
2161 }
2162
2163 //______________________________________________________________________________________________
2164 const char* AliShuttle::GetFile(Int_t system, const char* detector,
2165                 const char* id, const char* source)
2166 {
2167         // Get calibration file from file exchange servers
2168         // First queris the FXS database for the file name, using the run, detector, id and source info
2169         // then calls RetrieveFile(filename) for actual copy to local disk
2170         // run: current run being processed (given by Logbook entry fLogbookEntry)
2171         // detector: the Preprocessor name
2172         // id: provided as a parameter by the Preprocessor
2173         // source: provided by the Preprocessor through GetFileSources function
2174
2175         // check if test mode should simulate a FXS error
2176         if (fTestMode & kErrorFXSFiles)
2177         {
2178                 Log(detector, Form("GetFile - In TESTMODE - Simulating error while connecting to %s FXS", GetSystemName(system)));
2179                 return 0;
2180         }
2181         
2182         // check connection, in case connect
2183         if (!Connect(system))
2184         {
2185                 Log(detector, Form("GetFile - Couldn't connect to %s FXS database", GetSystemName(system)));
2186                 fFXSError = system;
2187                 return 0;
2188         }
2189
2190         // Query preparation
2191         TString sourceName(source);
2192         Int_t nFields = 3;
2193         TString sqlQueryStart = Form("select filePath,size,fileChecksum from %s where",
2194                                                                 fConfig->GetFXSdbTable(system));
2195         TString whereClause = Form("run=%d and detector=\"%s\" and fileId=\"%s\"",
2196                                                                 GetCurrentRun(), detector, id);
2197
2198         if (system == kDAQ || system == kDQM)
2199         {
2200                 whereClause += Form(" and DAQsource=\"%s\"", source);
2201         }
2202         else if (system == kDCS)
2203         {
2204                 sourceName="none";
2205         }
2206         else if (system == kHLT)
2207         {
2208                 whereClause += Form(" and DDLnumbers=\"%s\"", source);
2209         }
2210
2211         TString sqlQuery = Form("%s %s", sqlQueryStart.Data(), whereClause.Data());
2212
2213         AliDebug(2, Form("SQL query: \n%s",sqlQuery.Data()));
2214
2215         // Query execution
2216         TSQLResult* aResult = 0;
2217         aResult = dynamic_cast<TSQLResult*> (fServer[system]->Query(sqlQuery));
2218         if (!aResult) {
2219                 Log(detector, Form("GetFile - Can't execute SQL query to %s database for: id = %s, source = %s",
2220                                 GetSystemName(system), id, sourceName.Data()));
2221                 fFXSError = system;
2222                 return 0;
2223         }
2224
2225         if (aResult->GetRowCount() == 0)
2226         {
2227                 Log(detector,
2228                         Form("GetFile - No entry in %s FXS db for: id = %s, source = %s",
2229                                 GetSystemName(system), id, sourceName.Data()));
2230                 delete aResult;
2231                 return 0;
2232         }
2233
2234         if (aResult->GetRowCount() > 1) {
2235                 Log(detector,
2236                         Form("GetFile - More than one entry in %s FXS db for: id = %s, source = %s",
2237                                 GetSystemName(system), id, sourceName.Data()));
2238                 fFXSError = system;
2239                 delete aResult;
2240                 return 0;
2241         }
2242
2243         if (aResult->GetFieldCount() != nFields) {
2244                 Log(detector,
2245                         Form("GetFileName - Wrong field count in %s FXS db for: id = %s, source = %s",
2246                                 GetSystemName(system), id, sourceName.Data()));
2247                 fFXSError = system;
2248                 delete aResult;
2249                 return 0;
2250         }
2251
2252         TSQLRow* aRow = dynamic_cast<TSQLRow*> (aResult->Next());
2253
2254         if (!aRow){
2255                 Log(detector, Form("GetFile - Empty set result in %s FXS db from query: id = %s, source = %s",
2256                                 GetSystemName(system), id, sourceName.Data()));
2257                 fFXSError = system;
2258                 delete aResult;
2259                 return 0;
2260         }
2261
2262         TString filePath(aRow->GetField(0), aRow->GetFieldLength(0));
2263         TString fileSize(aRow->GetField(1), aRow->GetFieldLength(1));
2264         TString fileChecksum(aRow->GetField(2), aRow->GetFieldLength(2));
2265
2266         delete aResult;
2267         delete aRow;
2268
2269         AliDebug(2, Form("filePath = %s; size = %s, fileChecksum = %s",
2270                                 filePath.Data(), fileSize.Data(), fileChecksum.Data()));
2271
2272         // retrieved file is renamed to make it unique
2273         Int_t dir_lev1 = GetCurrentRun()/10000;
2274         TString localFileName = Form("%s/%d/%d/%s_process/%s_%s_%d_%s_%s.shuttle",
2275                                      GetShuttleTempDir(), dir_lev1, GetCurrentRun(), detector,
2276                                         GetSystemName(system), detector, GetCurrentRun(), 
2277                                         id, sourceName.Data());
2278         Log("SHUTTLE",Form("file from FXS = %s",localFileName.Data())); 
2279
2280
2281         // file retrieval from FXS
2282         UInt_t nRetries = 0;
2283         UInt_t maxRetries = 3;
2284         Bool_t result = kFALSE;
2285
2286         // copy!! if successful TSystem::Exec returns 0
2287         while (nRetries++ < maxRetries) {
2288                 AliDebug(2, Form("Trying to copy file. Retry # %d", nRetries));
2289                 result = RetrieveFile(system, filePath.Data(), localFileName.Data());
2290                 if (!result)
2291                 {
2292                         Log(detector, Form("GetFile - Copy of file %s from %s FXS failed",
2293                                         filePath.Data(), GetSystemName(system)));
2294                         continue;
2295                 } 
2296
2297                 if (fileSize.Length()>0)
2298                 {
2299                         // compare filesize of local file with the one stored in the FXS DB
2300                         Long_t size = -1;
2301                         Int_t sizeComp = gSystem->GetPathInfo(localFileName.Data(), 0, &size, 0, 0);
2302
2303                         if (sizeComp != 0 || size != fileSize.Atoi())
2304                         {
2305                                 Log(detector, Form("GetFile - size of file %s does not match with local copy!",
2306                                                         filePath.Data()));
2307                                 result = kFALSE;
2308                                 continue;
2309                         }
2310
2311                 } else {
2312                         Log(fCurrentDetector, Form("GetFile - size of file %s not set in %s database, skipping comparison",
2313                                                 filePath.Data(), GetSystemName(system)));
2314                 }
2315
2316                 if (fileChecksum.Length()>0)
2317                 {
2318                         // compare md5sum of local file with the one stored in the FXS DB
2319                         if(fileChecksum.Contains(' ')) fileChecksum.Resize(fileChecksum.First(' '));
2320                         Int_t md5Comp = gSystem->Exec(Form("md5sum %s |grep %s > /dev/null 2> /dev/null",
2321                                                 localFileName.Data(), fileChecksum.Data()));
2322
2323                         if (md5Comp != 0)
2324                         {
2325                                 Log(detector, Form("GetFile - md5sum of file %s does not match with local copy!",
2326                                                         filePath.Data()));
2327                                 result = kFALSE;
2328                                 continue;
2329                         }
2330                 } else {
2331                         Log(fCurrentDetector, Form("GetFile - md5sum of file %s not set in %s database, skipping comparison",
2332                                                         filePath.Data(), GetSystemName(system)));
2333                 }
2334                 if (result) break;
2335         }
2336
2337         if (!result) 
2338         {
2339                 fFXSError = system;
2340                 return 0;
2341         }
2342
2343         fFXSCalled[system]=kTRUE;
2344         TObjString *fileParams = new TObjString(Form("%s#!?!#%s", id, sourceName.Data()));
2345         fFXSlist[system].Add(fileParams);
2346
2347         static TString staticLocalFileName;
2348         staticLocalFileName.Form("%s", localFileName.Data());
2349         
2350         Log(fCurrentDetector, Form("GetFile - Retrieved file with id %s and "
2351                         "source %s from %s to %s", id, source, 
2352                         GetSystemName(system), localFileName.Data()));
2353                         
2354         return staticLocalFileName.Data();
2355 }
2356
2357 //______________________________________________________________________________________________
2358 Bool_t AliShuttle::RetrieveFile(UInt_t system, const char* fxsFileName, const char* localFileName)
2359 {
2360         //
2361         // Copies file from FXS to local Shuttle machine
2362         //
2363
2364         // check temp directory: trying to cd to temp; if it does not exist, create it
2365         AliDebug(2, Form("Copy file %s from %s FXS into %s",
2366                         GetSystemName(system), fxsFileName, localFileName));
2367                         
2368         TString tmpDir(localFileName);
2369         
2370         tmpDir = tmpDir(0,tmpDir.Last('/'));
2371
2372         Int_t noDir = gSystem->GetPathInfo(tmpDir.Data(), 0, (Long64_t*) 0, 0, 0);
2373         if (noDir) // temp dir does not exists!
2374         {
2375                 if (gSystem->mkdir(tmpDir.Data(), 1))
2376                 {
2377                         Log(fCurrentDetector.Data(), "RetrieveFile - could not make temp directory!!");
2378                         return kFALSE;
2379                 }
2380         }
2381
2382         TString command = Form("scp -oPort=%d -2 %s@%s:%s/%s %s",
2383                 fConfig->GetFXSPort(system),
2384                 fConfig->GetFXSUser(system),
2385                 fConfig->GetFXSHost(system),
2386                 fConfig->GetFXSBaseFolder(system),
2387                 fxsFileName,
2388                 localFileName);
2389
2390         AliDebug(2, Form("%s",command.Data()));
2391
2392         Bool_t result = (gSystem->Exec(command.Data()) == 0);
2393
2394         return result;
2395 }
2396
2397 //______________________________________________________________________________________________
2398 TList* AliShuttle::GetFileSources(Int_t system, const char* detector, const char* id)
2399 {
2400         //
2401         // Get sources producing the condition file Id from file exchange servers
2402         // if id is NULL all sources are returned (distinct)
2403         //
2404
2405         if (id)
2406         {
2407                 Log(detector, Form("GetFileSources - Querying %s FXS for files with id %s produced by %s", GetSystemName(system), id, detector));
2408         } else {
2409                 Log(detector, Form("GetFileSources - Querying %s FXS for files produced by %s", GetSystemName(system), detector));
2410         }
2411         
2412         // check if test mode should simulate a FXS error
2413         if (fTestMode & kErrorFXSSources)
2414         {
2415                 Log(detector, Form("GetFileSources - In TESTMODE - Simulating error while connecting to %s FXS", GetSystemName(system)));
2416                 return 0;
2417         }
2418
2419         if (system == kDCS)
2420         {
2421                 Log(detector, "GetFileSources - WARNING: DCS system has only one source of data!");
2422                 TList *list = new TList();
2423                 list->SetOwner(1);
2424                 list->Add(new TObjString(" "));
2425                 return list;
2426         }
2427
2428         // check connection, in case connect
2429         if (!Connect(system))
2430         {
2431                 Log(detector, Form("GetFileSources - Couldn't connect to %s FXS database", GetSystemName(system)));
2432                 fFXSError = system;
2433                 return NULL;
2434         }
2435
2436         TString sourceName = "";
2437         if (system == kDAQ || system == kDQM)
2438         {
2439                 sourceName = "DAQsource";
2440         } else if (system == kHLT)
2441         {
2442                 sourceName = "DDLnumbers";
2443         }
2444
2445         TString sqlQueryStart = Form("select distinct %s from %s where", sourceName.Data(), fConfig->GetFXSdbTable(system));
2446         TString whereClause = Form("run=%d and detector=\"%s\"",
2447                                 GetCurrentRun(), detector);
2448         if (id)
2449                 whereClause += Form(" and fileId=\"%s\"", id);
2450         TString sqlQuery = Form("%s %s", sqlQueryStart.Data(), whereClause.Data());
2451
2452         AliDebug(2, Form("SQL query: \n%s",sqlQuery.Data()));
2453
2454         // Query execution
2455         TSQLResult* aResult;
2456         aResult = fServer[system]->Query(sqlQuery);
2457         if (!aResult) {
2458                 Log(detector, Form("GetFileSources - Can't execute SQL query to %s database for id: %s",
2459                                 GetSystemName(system), id));
2460                 fFXSError = system;
2461                 return 0;
2462         }
2463
2464         TList *list = new TList();
2465         list->SetOwner(1);
2466         
2467         if (aResult->GetRowCount() == 0)
2468         {
2469                 Log(detector,
2470                         Form("GetFileSources - No entry in %s FXS table for id: %s", GetSystemName(system), id));
2471                 delete aResult;
2472                 return list;
2473         }
2474
2475         Log(detector, Form("GetFileSources - Found %d sources", aResult->GetRowCount()));
2476
2477         TSQLRow* aRow;
2478         while ((aRow = aResult->Next()))
2479         {
2480
2481                 TString source(aRow->GetField(0), aRow->GetFieldLength(0));
2482                 AliDebug(2, Form("%s = %s", sourceName.Data(), source.Data()));
2483                 list->Add(new TObjString(source));
2484                 delete aRow;
2485         }
2486
2487         delete aResult;
2488
2489         return list;
2490 }
2491
2492 //______________________________________________________________________________________________
2493 TList* AliShuttle::GetFileIDs(Int_t system, const char* detector, const char* source)
2494 {
2495         //
2496         // Get all ids of condition files produced by a given source from file exchange servers
2497         //
2498         
2499         Log(detector, Form("GetFileIDs - Retrieving ids with source %s with %s", source, GetSystemName(system)));
2500
2501         // check if test mode should simulate a FXS error
2502         if (fTestMode & kErrorFXSSources)
2503         {
2504                 Log(detector, Form("GetFileIDs - In TESTMODE - Simulating error while connecting to %s FXS", GetSystemName(system)));
2505                 return 0;
2506         }
2507
2508         // check connection, in case connect
2509         if (!Connect(system))
2510         {
2511                 Log(detector, Form("GetFileIDs - Couldn't connect to %s FXS database", GetSystemName(system)));
2512                 return NULL;
2513         }
2514
2515         TString sourceName = "";
2516         if (system == kDAQ)
2517         {
2518                 sourceName = "DAQsource";
2519         } else if (system == kHLT)
2520         {
2521                 sourceName = "DDLnumbers";
2522         }
2523
2524         TString sqlQueryStart = Form("select fileId from %s where", fConfig->GetFXSdbTable(system));
2525         TString whereClause = Form("run=%d and detector=\"%s\"",
2526                                 GetCurrentRun(), detector);
2527         if (sourceName.Length() > 0 && source)
2528                 whereClause += Form(" and %s=\"%s\"", sourceName.Data(), source);
2529         TString sqlQuery = Form("%s %s", sqlQueryStart.Data(), whereClause.Data());
2530
2531         AliDebug(2, Form("SQL query: \n%s",sqlQuery.Data()));
2532
2533         // Query execution
2534         TSQLResult* aResult;
2535         aResult = fServer[system]->Query(sqlQuery);
2536         if (!aResult) {
2537                 Log(detector, Form("GetFileIDs - Can't execute SQL query to %s database for source: %s",
2538                                 GetSystemName(system), source));
2539                 return 0;
2540         }
2541
2542         TList *list = new TList();
2543         list->SetOwner(1);
2544         
2545         if (aResult->GetRowCount() == 0)
2546         {
2547                 Log(detector,
2548                         Form("GetFileIDs - No entry in %s FXS table for source: %s", GetSystemName(system), source));
2549                 delete aResult;
2550                 return list;
2551         }
2552
2553         Log(detector, Form("GetFileIDs - Found %d ids", aResult->GetRowCount()));
2554
2555         TSQLRow* aRow;
2556
2557         while ((aRow = aResult->Next()))
2558         {
2559
2560                 TString id(aRow->GetField(0), aRow->GetFieldLength(0));
2561                 AliDebug(2, Form("fileId = %s", id.Data()));
2562                 list->Add(new TObjString(id));
2563                 delete aRow;
2564         }
2565
2566         delete aResult;
2567
2568         return list;
2569 }
2570
2571 //______________________________________________________________________________________________
2572 Bool_t AliShuttle::Connect(Int_t system)
2573 {
2574         // Connect to MySQL Server of the system's FXS MySQL databases
2575         // DAQ Logbook, Shuttle Logbook and DAQ FXS db are on the same host
2576         //
2577
2578         // check connection: if already connected return
2579
2580         if(fServer[system] && fServer[system]->IsConnected()) {
2581                 // ping the server              
2582                 if (fServer[system]->PingVerify()==kTRUE){ // connection is still alive
2583                         return kTRUE;
2584                 }               
2585                 else{
2586                         AliWarning(Form("Connection got lost to FXS database for %s. Closing and reconnecting.",
2587                                         AliShuttleInterface::GetSystemName(system)));
2588                         fServer[system]->Close();
2589                         delete fServer[system];
2590                         fServer[system] = 0x0;
2591                 }
2592         }
2593
2594         TString dbHost, dbUser, dbPass, dbName;
2595
2596         if (system < 4) // FXS db servers
2597         {
2598                 dbHost = Form("mysql://%s:%d", fConfig->GetFXSdbHost(system), fConfig->GetFXSdbPort(system));
2599                 dbUser = fConfig->GetFXSdbUser(system);
2600                 dbPass = fConfig->GetFXSdbPass(system);
2601                 dbName =   fConfig->GetFXSdbName(system);
2602         } else { // Run & Shuttle logbook servers
2603         // TODO Will the Shuttle logbook server be the same as the Run logbook server ???
2604                 dbHost = Form("mysql://%s:%d", fConfig->GetDAQlbHost(), fConfig->GetDAQlbPort());
2605                 dbUser = fConfig->GetDAQlbUser();
2606                 dbPass = fConfig->GetDAQlbPass();
2607                 dbName =   fConfig->GetDAQlbDB();
2608         }
2609
2610         fServer[system] = TSQLServer::Connect(dbHost.Data(), dbUser.Data(), dbPass.Data());
2611                 if (!fServer[system] || !fServer[system]->IsConnected()) {
2612                 if(system < 4)
2613                 {
2614                 AliError(Form("Can't establish connection to FXS database for %s",
2615                                         AliShuttleInterface::GetSystemName(system)));
2616                 } else {
2617                 AliError("Can't establish connection to Run logbook.");
2618                 }
2619                 if(fServer[system]) delete fServer[system];
2620                 return kFALSE;
2621         }
2622
2623         // Get tables
2624         TSQLResult* aResult=0;
2625         switch(system){
2626                 case kDAQ:
2627                         aResult = fServer[kDAQ]->GetTables(dbName.Data());
2628                         break;
2629                 case kDCS:
2630                         aResult = fServer[kDCS]->GetTables(dbName.Data());
2631                         break;
2632                 case kHLT:
2633                         aResult = fServer[kHLT]->GetTables(dbName.Data());
2634                         break;
2635                 case kDQM:
2636                         aResult = fServer[kDQM]->GetTables(dbName.Data());
2637                         break;
2638                 default:
2639                         aResult = fServer[4]->GetTables(dbName.Data());
2640                         break;
2641         }
2642
2643         delete aResult;
2644         return kTRUE;
2645 }
2646
2647 //______________________________________________________________________________________________
2648 Bool_t AliShuttle::UpdateTable()
2649 {
2650         //
2651         // Update FXS table filling time_processed field in all rows corresponding to current run and detector
2652         //
2653
2654         Bool_t result = kTRUE;
2655
2656         for (UInt_t system=0; system<4; system++)
2657         {
2658                 if(!fFXSCalled[system]) continue;
2659
2660                 // check connection, in case connect
2661                 if (!Connect(system))
2662                 {
2663                         Log(fCurrentDetector, Form("UpdateTable - Couldn't connect to %s FXS database", GetSystemName(system)));
2664                         result = kFALSE;
2665                         continue;
2666                 }
2667
2668                 TTimeStamp now; // now
2669
2670                 // Loop on FXS list entries
2671                 TIter iter(&fFXSlist[system]);
2672                 TObjString *aFXSentry=0;
2673                 while ((aFXSentry = dynamic_cast<TObjString*> (iter.Next())))
2674                 {
2675                         TString aFXSentrystr = aFXSentry->String();
2676                         TObjArray *aFXSarray = aFXSentrystr.Tokenize("#!?!#");
2677                         if (!aFXSarray || aFXSarray->GetEntries() != 2 )
2678                         {
2679                                 Log(fCurrentDetector, Form("UpdateTable - error updating %s FXS entry. Check string: <%s>",
2680                                         GetSystemName(system), aFXSentrystr.Data()));
2681                                 if(aFXSarray) delete aFXSarray;
2682                                 result = kFALSE;
2683                                 continue;
2684                         }
2685                         const char* fileId = ((TObjString*) aFXSarray->At(0))->GetName();
2686                         const char* source = ((TObjString*) aFXSarray->At(1))->GetName();
2687
2688                         TString whereClause;
2689                         if (system == kDAQ || system == kDQM)
2690                         {
2691                                 whereClause = Form("where run=%d and detector=\"%s\" and fileId=\"%s\" and DAQsource=\"%s\";",
2692                                                         GetCurrentRun(), fCurrentDetector.Data(), fileId, source);
2693                         }
2694                         else if (system == kDCS)
2695                         {
2696                                 whereClause = Form("where run=%d and detector=\"%s\" and fileId=\"%s\";",
2697                                                         GetCurrentRun(), fCurrentDetector.Data(), fileId);
2698                         }
2699                         else if (system == kHLT)
2700                         {
2701                                 whereClause = Form("where run=%d and detector=\"%s\" and fileId=\"%s\" and DDLnumbers=\"%s\";",
2702                                                         GetCurrentRun(), fCurrentDetector.Data(), fileId, source);
2703                         }
2704
2705                         delete aFXSarray;
2706
2707                         TString sqlQuery = Form("update %s set time_processed=%ld %s", fConfig->GetFXSdbTable(system),
2708                                                 (ULong_t)now.GetSec(), whereClause.Data());
2709
2710                         AliDebug(2, Form("SQL query: \n%s",sqlQuery.Data()));
2711
2712                         // Query execution
2713                         TSQLResult* aResult;
2714                         aResult = dynamic_cast<TSQLResult*> (fServer[system]->Query(sqlQuery));
2715                         if (!aResult)
2716                         {
2717                                 Log(fCurrentDetector, Form("UpdateTable - %s db: can't execute SQL query <%s>",
2718                                                                 GetSystemName(system), sqlQuery.Data()));
2719                                 result = kFALSE;
2720                                 continue;
2721                         }
2722                         delete aResult;
2723                 }
2724         }
2725
2726         return result;
2727 }
2728
2729 //_______________________________________________________________________________
2730 Bool_t AliShuttle::UpdateTableSkippedCase(const char* detector)
2731 {
2732         //
2733         // Update FXS table filling time_processed field in all rows corresponding to current run and detector
2734         // if detector = "ALL" update all detectors
2735         //
2736
2737         Bool_t result = kTRUE;
2738
2739         TString detName(detector);
2740
2741         for (UInt_t system=0; system<4; system++)
2742         {
2743
2744                 // check connection, in case connect
2745                 if (!Connect(system))
2746                 {
2747                         Log(fCurrentDetector, Form("UpdateTableSkippedCase - Couldn't connect to %s FXS database", GetSystemName(system)));
2748                         result = kFALSE;
2749                         continue;
2750                 }
2751
2752                 TTimeStamp now; // now
2753
2754                 // Loop on FXS list entries
2755                 TIter iter(&fFXSlist[system]);
2756                         
2757                 TString whereClause;
2758                 if (detName == "ALL") whereClause = Form("where run=%d and time_processed IS NULL;",GetCurrentRun());
2759                 else whereClause = Form("where run=%d and detector=\"%s\" and time_processed IS NULL;",GetCurrentRun(), detector);
2760
2761                 //Log("SHUTTLE",Form(" whereClause = %s ",whereClause.Data()));
2762
2763                 TString sqlQuery = Form("update %s set time_processed=%ld %s", fConfig->GetFXSdbTable(system),
2764                                         (ULong_t)now.GetSec(), whereClause.Data());
2765
2766                 AliDebug(2, Form("SQL query: \n%s",sqlQuery.Data()));
2767
2768                 // Query execution
2769                 TSQLResult* aResult;
2770                 aResult = dynamic_cast<TSQLResult*> (fServer[system]->Query(sqlQuery));
2771                 if (!aResult)
2772                 {
2773                         Log("SHUTTLE", Form("UpdateTableSkippedCase - %s db: can't execute SQL query <%s>",
2774                                                         GetSystemName(system), sqlQuery.Data()));
2775                         result = kFALSE;
2776                         continue;
2777                 }
2778                 delete aResult;
2779                 
2780         }
2781
2782         return result;
2783 }
2784 //______________________________________________________________________________________________
2785 Bool_t AliShuttle::UpdateTableFailCase()
2786 {
2787         // Update FXS table filling time_processed field in all rows corresponding to current run and detector
2788         // this is called in case the preprocessor is declared failed for the current run, because
2789         // the fields are updated only in case of success
2790
2791         Bool_t result = kTRUE;
2792
2793         for (UInt_t system=0; system<4; system++)
2794         {
2795                 // check connection, in case connect
2796                 if (!Connect(system))
2797                 {
2798                         Log(fCurrentDetector, Form("UpdateTableFailCase - Couldn't connect to %s FXS database",
2799                                                         GetSystemName(system)));
2800                         result = kFALSE;
2801                         continue;
2802                 }
2803
2804                 TTimeStamp now; // now
2805
2806                 // Loop on FXS list entries
2807
2808                 TString whereClause = Form("where run=%d and detector=\"%s\";",
2809                                                 GetCurrentRun(), fCurrentDetector.Data());
2810
2811
2812                 TString sqlQuery = Form("update %s set time_processed=%ld %s", fConfig->GetFXSdbTable(system),
2813                                         (ULong_t)now.GetSec(), whereClause.Data());
2814
2815                 AliDebug(2, Form("SQL query: \n%s",sqlQuery.Data()));
2816
2817                 // Query execution
2818                 TSQLResult* aResult;
2819                 aResult = dynamic_cast<TSQLResult*> (fServer[system]->Query(sqlQuery));
2820                 if (!aResult)
2821                 {
2822                         Log(fCurrentDetector, Form("UpdateTableFailCase - %s db: can't execute SQL query <%s>",
2823                                                         GetSystemName(system), sqlQuery.Data()));
2824                         result = kFALSE;
2825                         continue;
2826                 }
2827                 delete aResult;
2828         }
2829
2830         return result;
2831 }
2832
2833 //______________________________________________________________________________________________
2834 Bool_t AliShuttle::UpdateShuttleLogbook(const char* detector, const char* status)
2835 {
2836         //
2837         // Update Shuttle logbook filling detector or shuttle_done column
2838         // ex. of usage: UpdateShuttleLogbook("PHOS", "DONE") or UpdateShuttleLogbook("shuttle_done")
2839         //
2840
2841         // check connection, in case connect
2842         if(!Connect(4)){
2843                 Log("SHUTTLE", "UpdateShuttleLogbook - Couldn't connect to DAQ Logbook.");
2844                 return kFALSE;
2845         }
2846
2847         TString detName(detector);
2848         TString setClause;
2849         if (detName == "shuttle_done" || detName == "shuttle_skipped")
2850         {
2851                 setClause = "set shuttle_done=1";
2852                 
2853                 if (detName == "shuttle_done")
2854                 {
2855                         if (TouchFile() != kTRUE)
2856                         {
2857                                 SendMLRunInfo("Pending");
2858                                 return kFALSE;
2859                         }
2860                         
2861                         SendMLRunInfo("Done");
2862                 }
2863                 else 
2864                         SendMLRunInfo("Skipped");
2865         } 
2866         else {
2867                 TString statusStr(status);
2868                 if(statusStr.Contains("done", TString::kIgnoreCase) ||
2869                    statusStr.Contains("failed", TString::kIgnoreCase)){
2870                         setClause = Form("set %s=\"%s\"", detector, status);
2871                 } else {
2872                         Log("SHUTTLE",
2873                                 Form("UpdateShuttleLogbook - Invalid status <%s> for detector %s",
2874                                         status, detector));
2875                         return kFALSE;
2876                 }
2877         }
2878
2879         TString whereClause = Form("where run=%d", GetCurrentRun());
2880
2881         TString sqlQuery = Form("update %s %s %s",
2882                                         fConfig->GetShuttlelbTable(), setClause.Data(), whereClause.Data());
2883
2884         AliDebug(2, Form("SQL query: \n%s",sqlQuery.Data()));
2885
2886         // Query execution
2887         TSQLResult* aResult;
2888         aResult = dynamic_cast<TSQLResult*> (fServer[4]->Query(sqlQuery));
2889         if (!aResult) {
2890                 Log("SHUTTLE", Form("UpdateShuttleLogbook - Can't execute query <%s>", sqlQuery.Data()));
2891                 return kFALSE;
2892         }
2893         delete aResult;
2894
2895         return kTRUE;
2896 }
2897
2898 //______________________________________________________________________________________________
2899 Int_t AliShuttle::GetCurrentRun() const
2900 {
2901         //
2902         // Get current run from logbook entry
2903         //
2904
2905         return fLogbookEntry ? fLogbookEntry->GetRun() : -1;
2906 }
2907
2908 //______________________________________________________________________________________________
2909 UInt_t AliShuttle::GetCurrentStartTime() const
2910 {
2911         //
2912         // get current start time
2913         //
2914
2915         return fLogbookEntry ? fLogbookEntry->GetStartTime() : 0;
2916 }
2917
2918 //______________________________________________________________________________________________
2919 UInt_t AliShuttle::GetCurrentEndTime() const
2920 {
2921         //
2922         // get current end time from logbook entry
2923         //
2924
2925         return fLogbookEntry ? fLogbookEntry->GetEndTime() : 0;
2926 }
2927 //______________________________________________________________________________________________
2928 UInt_t AliShuttle::GetCurrentYear() const
2929 {
2930         //
2931         // Get current year from logbook entry
2932         //
2933
2934         if (!fLogbookEntry) return 0;
2935         
2936         TTimeStamp startTime(GetCurrentStartTime());
2937         TString year =  Form("%d",startTime.GetDate());
2938         year = year(0,4);
2939         
2940         return year.Atoi();
2941 }
2942
2943 //______________________________________________________________________________________________
2944 const char* AliShuttle::GetLHCPeriod() const
2945 {
2946         //
2947         // Get current LHC period from logbook entry
2948         //
2949
2950         if (!fLogbookEntry) return 0;
2951                 
2952         return fLogbookEntry->GetRunParameter("LHCperiod");
2953 }
2954
2955 //______________________________________________________________________________________________
2956 void AliShuttle::Log(const char* detector, const char* message, UInt_t level)
2957 {
2958         //
2959         // Fill log string with a message
2960         //
2961         
2962         TString logRunDir = GetShuttleLogDir();
2963         if (GetCurrentRun() >=0) {
2964                 Int_t logDir_lev1 = GetCurrentRun()/10000;
2965                 logRunDir += Form("/%d/%d", logDir_lev1, GetCurrentRun());
2966         }               
2967         void* dir = gSystem->OpenDirectory(logRunDir.Data());
2968         if (dir == NULL) {
2969                 if (gSystem->mkdir(logRunDir.Data(), kTRUE)) {
2970                         AliError(Form("Can't open directory <%s>", GetShuttleLogDir()));
2971                         return;
2972                 }
2973
2974         } else {
2975                 gSystem->FreeDirectory(dir);
2976         }
2977
2978         TString toLog = Form("%s UTC (%d): %s - ", TTimeStamp(time(0)).AsString("s"), getpid(), detector);
2979         if (GetCurrentRun() >= 0) 
2980                 toLog += Form("run %d - ", GetCurrentRun());
2981         toLog += Form("%s", message);
2982
2983         AliLog::Message(level, toLog, MODULENAME(), ClassName(), FUNCTIONNAME(), __FILE__, __LINE__);
2984         
2985         // if we redirect the log output already to the file, leave here
2986         if (fOutputRedirected && strcmp(detector, "SHUTTLE") != 0)
2987                 return;
2988
2989         TString fileName = GetLogFileName(detector);
2990         
2991         gSystem->ExpandPathName(fileName);
2992
2993         ofstream logFile;
2994         logFile.open(fileName, ofstream::out | ofstream::app);
2995
2996         if (!logFile.is_open()) {
2997                 AliError(Form("Could not open file %s", fileName.Data()));
2998                 return;
2999         }
3000
3001         logFile << toLog.Data() << "\n";
3002
3003         logFile.close();
3004 }
3005
3006 //______________________________________________________________________________________________
3007 TString AliShuttle::GetLogFileName(const char* detector) const
3008 {
3009         // 
3010         // returns the name of the log file for a given sub detector
3011         //
3012         
3013         TString fileName;
3014         
3015         if (GetCurrentRun() >= 0) 
3016         {
3017                 Int_t logDir_lev1 = GetCurrentRun()/10000;
3018                 fileName.Form("%s/%d/%d/%s.log", GetShuttleLogDir(), logDir_lev1, GetCurrentRun(), 
3019                         detector);
3020         } else {
3021                 fileName.Form("%s/%s.log", GetShuttleLogDir(), detector);
3022         }
3023
3024         return fileName;
3025 }
3026
3027 //______________________________________________________________________________________________
3028 void AliShuttle::SendAlive()
3029 {
3030         // sends alive message to ML
3031         
3032         TMonaLisaText mlStatus("SHUTTLE_status", "Alive");
3033
3034         TList mlList;
3035         mlList.Add(&mlStatus);
3036
3037         fMonaLisa->SendParameters(&mlList, "__PROCESSINGINFO__");
3038 }
3039
3040 //______________________________________________________________________________________________
3041 Bool_t AliShuttle::Collect(Int_t run)
3042 {
3043         //
3044         // Collects conditions data for all UNPROCESSED run written to DAQ LogBook in case of run = -1 (default)
3045         // If a dedicated run is given this run is processed
3046         //
3047         // In operational mode, this is the Shuttle function triggered by the EOR signal.
3048         //
3049
3050         if (run == -1)
3051                 Log("SHUTTLE","Collect - Shuttle called. Collecting conditions data for unprocessed runs");
3052         else
3053                 Log("SHUTTLE", Form("Collect - Shuttle called. Collecting conditions data for run %d", run));
3054
3055         SetLastAction("Starting");
3056
3057         // create ML instance
3058         if (!fMonaLisa)
3059                 fMonaLisa = new TMonaLisaWriter(fConfig->GetMonitorHost(), fConfig->GetMonitorTable());
3060                 
3061         CountOpenRuns();
3062
3063         TString whereClause("where shuttle_done=0");
3064         if (run != -1)
3065                 whereClause += Form(" and run=%d", run);
3066
3067         TObjArray shuttleLogbookEntries;
3068         if (!QueryShuttleLogbook(whereClause, shuttleLogbookEntries))
3069         {
3070                 Log("SHUTTLE", "Collect - Can't retrieve entries from Shuttle logbook");
3071                 return kFALSE;
3072         }
3073
3074         if (shuttleLogbookEntries.GetEntries() == 0)
3075         {
3076                 if (run == -1)
3077                         Log("SHUTTLE","Collect - Found no UNPROCESSED runs in Shuttle logbook");
3078                 else
3079                         Log("SHUTTLE", Form("Collect - Run %d is already DONE "
3080                                                 "or it does not exist in Shuttle logbook", run));
3081                 return kTRUE;
3082         }
3083
3084         for (UInt_t iDet=0; iDet<NDetectors(); iDet++)
3085                 fFirstUnprocessed[iDet] = kTRUE;
3086
3087         if (run != -1)
3088         {
3089                 // query Shuttle logbook for earlier runs, check if some detectors are unprocessed,
3090                 // flag them into fFirstUnprocessed array
3091                 TString whereClauseBis(Form("where shuttle_done=0 and run < %d", run));
3092                 TObjArray tmpLogbookEntries;
3093                 if (!QueryShuttleLogbook(whereClauseBis, tmpLogbookEntries))
3094                 {
3095                         Log("SHUTTLE", "Collect - Can't retrieve entries from Shuttle logbook");
3096                         return kFALSE;
3097                 }
3098
3099                 TIter iter(&tmpLogbookEntries);
3100                 AliShuttleLogbookEntry* anEntry = 0;
3101                 while ((anEntry = dynamic_cast<AliShuttleLogbookEntry*> (iter.Next())))
3102                 {
3103                         for (UInt_t iDet=0; iDet<NDetectors(); iDet++)
3104                         {
3105                                 if (anEntry->GetDetectorStatus(iDet) == AliShuttleLogbookEntry::kUnprocessed)
3106                                 {
3107                                         AliDebug(2, Form("Run %d: setting %s as \"not first time unprocessed\"",
3108                                                         anEntry->GetRun(), GetDetName(iDet)));
3109                                         fFirstUnprocessed[iDet] = kFALSE;
3110                                 }
3111                         }
3112
3113                 }
3114
3115         }
3116
3117         if (!RetrieveConditionsData(shuttleLogbookEntries))
3118         {
3119                 Log("SHUTTLE", "Collect - Process of at least one run failed");
3120                 CountOpenRuns();
3121                 return kFALSE;
3122         }
3123
3124         Log("SHUTTLE", "Collect - Requested run(s) successfully processed");
3125         CountOpenRuns();
3126         return kTRUE;
3127 }
3128
3129 //______________________________________________________________________________________________
3130 Bool_t AliShuttle::RetrieveConditionsData(const TObjArray& dateEntries)
3131 {
3132         //
3133         // Retrieve conditions data for all runs that aren't processed yet
3134         //
3135
3136         Bool_t hasError = kFALSE;
3137
3138         TIter iter(&dateEntries);
3139         AliShuttleLogbookEntry* anEntry;
3140
3141         while ((anEntry = (AliShuttleLogbookEntry*) iter.Next())){
3142                 if (!Process(anEntry)){
3143                         hasError = kTRUE;
3144                 }
3145
3146                 // clean SHUTTLE temp directory
3147                 //TString filename = Form("%s/*.shuttle", GetShuttleTempDir());
3148                 //RemoveFile(filename.Data());
3149         }
3150
3151         return hasError == kFALSE;
3152 }
3153
3154 //______________________________________________________________________________________________
3155 ULong_t AliShuttle::GetTimeOfLastAction() const
3156 {
3157         //
3158         // Gets time of last action
3159         //
3160
3161         ULong_t tmp;
3162
3163         fMonitoringMutex->Lock();
3164
3165         tmp = fLastActionTime;
3166
3167         fMonitoringMutex->UnLock();
3168
3169         return tmp;
3170 }
3171
3172 //______________________________________________________________________________________________
3173 const TString AliShuttle::GetLastAction() const
3174 {
3175         //
3176         // returns a string description of the last action
3177         //
3178
3179         TString tmp;
3180
3181         fMonitoringMutex->Lock();
3182         
3183         tmp = fLastAction;
3184         
3185         fMonitoringMutex->UnLock();
3186
3187         return tmp;
3188 }
3189
3190 //______________________________________________________________________________________________
3191 void AliShuttle::SetLastAction(const char* action)
3192 {
3193         //
3194         // updates the monitoring variables
3195         //
3196
3197         fMonitoringMutex->Lock();
3198
3199         fLastAction = action;
3200         fLastActionTime = time(0);
3201         
3202         fMonitoringMutex->UnLock();
3203 }
3204
3205 //______________________________________________________________________________________________
3206 const char* AliShuttle::GetRunParameter(const char* param)
3207 {
3208         //
3209         // returns run parameter read from DAQ logbook
3210         //
3211
3212         if(!fLogbookEntry) {
3213                 AliError("No logbook entry!");
3214                 return 0;
3215         }
3216
3217         return fLogbookEntry->GetRunParameter(param);
3218 }
3219
3220 //______________________________________________________________________________________________
3221 AliCDBEntry* AliShuttle::GetFromOCDB(const char* detector, const AliCDBPath& path)
3222 {
3223         //
3224         // returns object from OCDB valid for current run
3225         //
3226
3227         if (fTestMode & kErrorOCDB)
3228         {
3229                 Log(detector, "GetFromOCDB - In TESTMODE - Simulating error with OCDB");
3230                 return 0;
3231         }
3232         
3233         AliCDBStorage *sto = AliCDBManager::Instance()->GetStorage(fgkMainCDB);
3234         if (!sto)
3235         {
3236                 Log(detector, "GetFromOCDB - Cannot activate main OCDB for query!");
3237                 return 0;
3238         }
3239
3240         return dynamic_cast<AliCDBEntry*> (sto->Get(path, GetCurrentRun()));
3241 }
3242
3243 //______________________________________________________________________________________________
3244 Bool_t AliShuttle::SendMail(EMailTarget target, Int_t system)
3245 {
3246         //
3247         // sends a mail to the subdetector expert in case of preprocessor error
3248         //
3249         
3250         if (fTestMode != kNone)
3251                 return kTRUE;
3252                 
3253         if (!fConfig->SendMail()) 
3254                 return kTRUE;
3255
3256         if (target == kDCSEMail || target == kFXSEMail) {
3257                 if (!fFirstProcessing)
3258                         return kTRUE;
3259         }
3260
3261         Int_t runMode = (Int_t)fConfig->GetRunMode();
3262         TString tmpStr;
3263         if (runMode == 0) tmpStr = " Nightly Test:";
3264         else tmpStr = " Data Taking:"; 
3265         void* dir = gSystem->OpenDirectory(GetShuttleLogDir());
3266         if (dir == NULL)
3267         {
3268                 if (gSystem->mkdir(GetShuttleLogDir(), kTRUE))
3269                 {
3270                         Log("SHUTTLE", Form("SendMail - Can't open directory <%s>", GetShuttleLogDir()));
3271                         return kFALSE;
3272                 }
3273
3274         } else {
3275                 gSystem->FreeDirectory(dir);
3276         }
3277
3278         // det experts in to
3279         TString to="";
3280         TIter *iterExperts = 0;
3281         if (target == kDCSEMail) {
3282                 iterExperts = new TIter(fConfig->GetAdmins(AliShuttleConfig::kAmanda));
3283         }
3284         else if (target == kFXSEMail) {
3285                 iterExperts = new TIter(fConfig->GetAdmins(system));
3286         }
3287         if (iterExperts) {
3288                 TObjString *anExpert=0;
3289                 while ((anExpert = (TObjString*) iterExperts->Next()))
3290                 {
3291                         to += Form("%s,", anExpert->GetName());
3292                 }
3293                 delete iterExperts;
3294         }
3295
3296         // add subdetector experts      
3297         iterExperts = new TIter(fConfig->GetResponsibles(fCurrentDetector));
3298         TObjString *anExpert=0;
3299         while ((anExpert = (TObjString*) iterExperts->Next()))
3300         {
3301                 to += Form("%s,", anExpert->GetName());
3302         }
3303         delete iterExperts;
3304         
3305         if (to.Length() > 0)
3306           to.Remove(to.Length()-1);
3307         AliDebug(2, Form("to: %s",to.Data()));
3308
3309         if (to.IsNull()) {
3310                 Log("SHUTTLE", Form("List of %d responsibles not set!", (Int_t) target));
3311                 return kFALSE;
3312         }
3313
3314         // SHUTTLE responsibles in cc
3315         TString cc="";
3316         TIter iterAdmins(fConfig->GetAdmins(AliShuttleConfig::kGlobal));
3317         TObjString *anAdmin=0;
3318         while ((anAdmin = (TObjString*) iterAdmins.Next()))
3319         {
3320                 cc += Form("%s,", anAdmin->GetName());
3321         }
3322         if (cc.Length() > 0)
3323           cc.Remove(cc.Length()-1);
3324         AliDebug(2, Form("cc: %s",to.Data()));
3325
3326         // mail body 
3327         TString bodyFileName;
3328         bodyFileName.Form("%s/mail.body", GetShuttleLogDir());
3329         gSystem->ExpandPathName(bodyFileName);
3330
3331         ofstream mailBody;
3332         mailBody.open(bodyFileName, ofstream::out);
3333
3334         if (!mailBody.is_open())
3335         {
3336                 Log("SHUTTLE", Form("Could not open mail body file %s", bodyFileName.Data()));
3337                 return kFALSE;
3338         }
3339
3340
3341         TString subject;
3342         TString body;
3343
3344         if (target == kDCSEMail){
3345                 subject = Form("%s CRITICAL Retrieval of data points for %s FAILED in run %d !",
3346                                 tmpStr.Data(), fCurrentDetector.Data(), GetCurrentRun());
3347                 AliDebug(2, Form("subject: %s", subject.Data()));
3348                 
3349                 body = Form("Dear DCS experts, \n\n");
3350                 body += Form("SHUTTLE couldn\'t retrieve the data points for detector %s "
3351                              "in run %d!!\n\n", fCurrentDetector.Data(), GetCurrentRun());
3352         }
3353         else if (target == kFXSEMail){
3354                 subject = Form("%s CRITICAL FXS communication for %s FAILED in run %d !",
3355                                 tmpStr.Data(), fCurrentDetector.Data(), GetCurrentRun());
3356                 AliDebug(2, Form("subject: %s", subject.Data()));
3357                 TString sys;
3358                 if (system == kDAQ) sys="DAQ";
3359                 else if (system == kDCS) sys="DCS";
3360                 else if (system == kHLT) sys="HLT";
3361                 else if (system == kDQM) sys="DQM";
3362                 else return kFALSE;
3363                 body = Form("Dear  %s FXS experts, \n\n",sys.Data());
3364                 body += Form("SHUTTLE couldn\'t retrieve data from the FXS for detector %s "
3365                              "in run %d!!\n\n", fCurrentDetector.Data(), GetCurrentRun());
3366                 body += Form("The contacted server was:\nDB: %s\nFXS:%s\n\n", fConfig->GetFXSdbHost(system), fConfig->GetFXSHost(system));
3367         }
3368         else {
3369                 subject = Form("%s %s Shuttle preprocessor FAILED in run %d (run type = %s)!",
3370                                        tmpStr.Data(), fCurrentDetector.Data(), GetCurrentRun(), GetRunType());
3371                 AliDebug(2, Form("subject: %s", subject.Data()));
3372         
3373                 body = Form("Dear %s expert(s), \n\n", fCurrentDetector.Data());
3374                 body += Form("SHUTTLE just detected that your preprocessor "
3375                              "failed processing run %d (run type = %s)!!\n\n", 
3376                              GetCurrentRun(), GetRunType());
3377         }
3378
3379         body += Form("Please check %s status on the SHUTTLE monitoring page: \n\n", 
3380                                 fCurrentDetector.Data());
3381         if (fConfig->GetRunMode() == AliShuttleConfig::kTest)
3382         {
3383                 body += Form("\thttp://pcalimonitor.cern.ch/shuttle.jsp?time=24 \n\n");
3384         } else {
3385                 body += Form("\thttp://pcalimonitor.cern.ch/shuttle.jsp?instance=PROD&time=24 \n\n");
3386         }
3387         
3388         
3389         TString logFolder = "logs";
3390         if (fConfig->GetRunMode() == AliShuttleConfig::kProd) 
3391                 logFolder += "_PROD";
3392         
3393         
3394         body += Form("Find the %s log for the current run on \n\n"
3395                 "\thttp://pcalishuttle02.cern.ch/%s/%d/%d/%s.log \n\n", 
3396                      fCurrentDetector.Data(), logFolder.Data(), GetCurrentRun()/10000,  
3397                                 GetCurrentRun(), fCurrentDetector.Data());
3398         body += Form("The last 15 lines of %s log file are following:\n\n", fCurrentDetector.Data());
3399
3400         AliDebug(2, Form("Body begin: %s", body.Data()));
3401
3402         mailBody << body.Data();
3403         mailBody.close();
3404         mailBody.open(bodyFileName, ofstream::out | ofstream::app);
3405
3406         TString logFileName = Form("%s/%d/%d/%s.log", GetShuttleLogDir(), 
3407                 GetCurrentRun()/10000, GetCurrentRun(), fCurrentDetector.Data());
3408         TString tailCommand = Form("tail -n 15 %s >> %s", logFileName.Data(), bodyFileName.Data());
3409         if (gSystem->Exec(tailCommand.Data()))
3410         {
3411                 mailBody << Form("%s log file not found ...\n\n", fCurrentDetector.Data());
3412         }
3413
3414         TString endBody = Form("------------------------------------------------------\n\n");
3415         endBody += Form("In case of problems please contact the SHUTTLE core team.\n\n");
3416         endBody += "Please do not answer this message directly, it is automatically generated.\n\n";
3417         endBody += "Greetings,\n\n \t\t\tthe SHUTTLE\n";
3418
3419         AliDebug(2, Form("Body end: %s", endBody.Data()));
3420
3421         mailBody << endBody.Data();
3422
3423         mailBody.close();
3424
3425         // send mail!
3426         TString mailCommand = Form("mail -s \"%s\" -c %s %s < %s",
3427                                                 subject.Data(),
3428                                                 cc.Data(),
3429                                                 to.Data(),
3430                                                 bodyFileName.Data());
3431         AliDebug(2, Form("mail command: %s", mailCommand.Data()));
3432
3433         Bool_t result = gSystem->Exec(mailCommand.Data());
3434
3435         return result == 0;
3436 }
3437 //______________________________________________________________________________________________
3438 const char* AliShuttle::GetRunType()
3439 {
3440         //
3441         // returns run type read from "run type" logbook
3442         //
3443
3444         if(!fLogbookEntry) {
3445                 AliError("No logbook entry!");
3446                 return 0;
3447         }
3448
3449         return fLogbookEntry->GetRunType();
3450 }
3451
3452 //______________________________________________________________________________________________
3453 Bool_t AliShuttle::GetHLTStatus()
3454 {
3455         // Return HLT status (ON=1 OFF=0)
3456         // Converts the HLT status from the mode string read in the run logbook (not just a bool)
3457
3458         if(!fLogbookEntry) {
3459                 AliError("No logbook entry!");
3460                 return 0;
3461         }
3462
3463         // TODO implement when HLTMode is inserted in run logbook
3464         TString hltMode = fLogbookEntry->GetRunParameter("HLTmode");
3465         TSubString firstChar = hltMode(0,1);
3466         AliDebug(2,Form("First char = %s ",firstChar.Data())); 
3467         if (firstChar == "A") {
3468                 return kFALSE;
3469         }
3470         else if ((firstChar == "B") || (firstChar == "C") || (firstChar == "D") || (firstChar == "E")) {
3471                 return kTRUE;
3472         }
3473         else {