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