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