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