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