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