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