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