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