]> git.uio.no Git - u/mrichter/AliRoot.git/blame - SHUTTLE/AliShuttle.cxx
histogram initialization forgot in previous commit
[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;
10a5a932 954 fStatusEntry = AliCDBManager::Instance()->GetStorage(GetLocalCDB())
3ebbf3c4 955 ->Get(Form("/SHUTTLE/%s/%d", fCurrentDetector.Data(), path1), GetCurrentRun());
5164a766 956
2bb7b766 957 if (!fStatusEntry) return 0;
958 fStatusEntry->SetOwner(1);
5164a766 959
2bb7b766 960 AliShuttleStatus* status = dynamic_cast<AliShuttleStatus*> (fStatusEntry->GetObject());
961 if (!status) {
962 AliError("Invalid object stored to CDB!");
963 return 0;
964 }
5164a766 965
2bb7b766 966 return status;
5164a766 967}
968
969//______________________________________________________________________________________________
7bfb2090 970Bool_t AliShuttle::WriteShuttleStatus(AliShuttleStatus* status)
5164a766 971{
9827400b 972 //
973 // writes the status for one subdetector
974 //
2bb7b766 975
976 if (fStatusEntry){
977 delete fStatusEntry;
978 fStatusEntry = 0;
979 }
5164a766 980
2bb7b766 981 Int_t run = GetCurrentRun();
3ebbf3c4 982 Int_t path1 = run/10000;
983 TString path1_string = Form("%d",path1);
5164a766 984
3ebbf3c4 985 AliCDBId id(AliCDBPath("SHUTTLE", fCurrentDetector, path1_string), run, run);
5164a766 986
2bb7b766 987 fStatusEntry = new AliCDBEntry(status, id, new AliCDBMetaData);
988 fStatusEntry->SetOwner(1);
5164a766 989
924fb6e9 990 Int_t logLevel = AliLog::GetGlobalLogLevel();
991 AliLog::SetGlobalLogLevel(AliLog::kError);
992
2bb7b766 993 UInt_t result = AliCDBManager::Instance()->GetStorage(fgkLocalCDB)->Put(fStatusEntry);
7bfb2090 994
924fb6e9 995 AliLog::SetGlobalLogLevel((AliLog::EType_t)logLevel);
996
997 if (!result) {
3301427a 998 Log("SHUTTLE", Form("WriteShuttleStatus - Failed for %s, run %d",
999 fCurrentDetector.Data(), run));
2bb7b766 1000 return kFALSE;
1001 }
e7f62f16 1002
8e828d39 1003 SendMLDetInfo();
7bfb2090 1004
2bb7b766 1005 return kTRUE;
5164a766 1006}
1007
1008//______________________________________________________________________________________________
1009void AliShuttle::UpdateShuttleStatus(AliShuttleStatus::Status newStatus, Bool_t increaseCount)
1010{
9827400b 1011 //
1012 // changes the AliShuttleStatus for the given detector and run to the given status
1013 //
5164a766 1014
2bb7b766 1015 if (!fStatusEntry){
1016 AliError("UNEXPECTED: fStatusEntry empty");
1017 return;
1018 }
5164a766 1019
2bb7b766 1020 AliShuttleStatus* status = dynamic_cast<AliShuttleStatus*> (fStatusEntry->GetObject());
5164a766 1021
2bb7b766 1022 if (!status){
c88ad5db 1023 Log("SHUTTLE", "UpdateShuttleStatus - UNEXPECTED: status could not be read from current CDB entry");
2bb7b766 1024 return;
1025 }
5164a766 1026
2c15234c 1027 TString actionStr = Form("UpdateShuttleStatus - %s: Changing state from %s to %s",
eba76848 1028 fCurrentDetector.Data(),
36c99a6a 1029 status->GetStatusName(),
eba76848 1030 status->GetStatusName(newStatus));
cb343cfd 1031 Log("SHUTTLE", actionStr);
1032 SetLastAction(actionStr);
5164a766 1033
2bb7b766 1034 status->SetStatus(newStatus);
1035 if (increaseCount) status->IncreaseCount();
5164a766 1036
924fb6e9 1037 Int_t logLevel = AliLog::GetGlobalLogLevel();
1038 AliLog::SetGlobalLogLevel(AliLog::kError);
1039
2bb7b766 1040 AliCDBManager::Instance()->GetStorage(fgkLocalCDB)->Put(fStatusEntry);
e7f62f16 1041
924fb6e9 1042 AliLog::SetGlobalLogLevel((AliLog::EType_t)logLevel);
1043
8e828d39 1044 SendMLDetInfo();
5164a766 1045}
e7f62f16 1046
1047//______________________________________________________________________________________________
8e828d39 1048void AliShuttle::SendMLDetInfo()
e7f62f16 1049{
1050 //
1051 // sends ML information about the current status of the current detector being processed
1052 //
1053
1054 AliShuttleStatus* status = dynamic_cast<AliShuttleStatus*> (fStatusEntry->GetObject());
1055
1056 if (!status){
8e828d39 1057 Log("SHUTTLE", "SendMLDetInfo - UNEXPECTED: status could not be read from current CDB entry");
e7f62f16 1058 return;
1059 }
1060
1061 TMonaLisaText mlStatus(Form("%s_status", fCurrentDetector.Data()), status->GetStatusName());
1062 TMonaLisaValue mlRetryCount(Form("%s_count", fCurrentDetector.Data()), status->GetCount());
1063
1064 TList mlList;
1065 mlList.Add(&mlStatus);
1066 mlList.Add(&mlRetryCount);
1067
ee6f7523 1068 TString mlID;
1069 mlID.Form("%d", GetCurrentRun());
1070 fMonaLisa->SendParameters(&mlList, mlID);
e7f62f16 1071}
1072
5164a766 1073//______________________________________________________________________________________________
1074Bool_t AliShuttle::ContinueProcessing()
1075{
9827400b 1076 // this function reads the AliShuttleStatus information from CDB and
1077 // checks if the processing should be continued
1078 // if yes it returns kTRUE and updates the AliShuttleStatus with nextStatus
2bb7b766 1079
926cbc0e 1080 if (!fConfig->HostProcessDetector(fCurrentDetector))
1081 return kFALSE;
57c1a579 1082
1083 AliPreprocessor* aPreprocessor =
1084 dynamic_cast<AliPreprocessor*> (fPreprocessorMap.GetValue(fCurrentDetector));
1085 if (!aPreprocessor)
1086 {
e55e9b46 1087 Log("SHUTTLE", Form("ContinueProcessing - %s: no preprocessor registered", fCurrentDetector.Data()));
1088 return kFALSE;
57c1a579 1089 }
1090
2bb7b766 1091 AliShuttleLogbookEntry::Status entryStatus =
eba76848 1092 fLogbookEntry->GetDetectorStatus(fCurrentDetector);
2bb7b766 1093
5e993b6f 1094 if (entryStatus != AliShuttleLogbookEntry::kUnprocessed) {
c88ad5db 1095 Log("SHUTTLE", Form("ContinueProcessing - %s is %s",
2bb7b766 1096 fCurrentDetector.Data(),
1097 fLogbookEntry->GetDetectorStatusName(entryStatus)));
1098 return kFALSE;
1099 }
1100
1101 // if we get here, according to Shuttle logbook subdetector is in UNPROCESSED state
be48e3ea 1102
1103 // check if current run is first unprocessed run for current detector
1104 if (fConfig->StrictRunOrder(fCurrentDetector) &&
1105 !fFirstUnprocessed[GetDetPos(fCurrentDetector)])
1106 {
86aa42c3 1107 if (fTestMode == kNone)
1108 {
c88ad5db 1109 Log("SHUTTLE", Form("ContinueProcessing - %s requires strict run ordering"
0a0b087a 1110 " but this is not the first unprocessed run!",fCurrentDetector.Data()));
86aa42c3 1111 return kFALSE;
1112 }
1113 else
1114 {
c88ad5db 1115 Log("SHUTTLE", Form("ContinueProcessing - In TESTMODE - "
1116 "Although %s requires strict run ordering "
1117 "and this is not the first unprocessed run, "
0a0b087a 1118 "the SHUTTLE continues",fCurrentDetector.Data()));
86aa42c3 1119 }
be48e3ea 1120 }
1121
926cbc0e 1122 // Is the subdetector processed first time for this run?
1123 fFirstProcessing = kFALSE;
1124
2bb7b766 1125 AliShuttleStatus* status = ReadShuttleStatus();
1126 if (!status) {
1127 // first time
1128 Log("SHUTTLE", Form("ContinueProcessing - %s: Processing first time",
1129 fCurrentDetector.Data()));
1130 status = new AliShuttleStatus(AliShuttleStatus::kStarted);
926cbc0e 1131 fFirstProcessing = kTRUE;
2bb7b766 1132 return WriteShuttleStatus(status);
1133 }
1134
ffa25f20 1135 // The following case shouldn't happen if Shuttle Logbook was correctly updated.
2bb7b766 1136 // If it happens it may mean Logbook updating failed... let's do it now!
1137 if (status->GetStatus() == AliShuttleStatus::kDone ||
ffa25f20 1138 status->GetStatus() == AliShuttleStatus::kFailed ||
1139 status->GetStatus() == AliShuttleStatus::kSkipped) {
2bb7b766 1140 Log("SHUTTLE", Form("ContinueProcessing - %s is already %s. Updating Shuttle Logbook",
1141 fCurrentDetector.Data(),
1142 status->GetStatusName(status->GetStatus())));
ffa25f20 1143
1144 if (status->GetStatus() == AliShuttleStatus::kSkipped)
1145 {
1146 UpdateShuttleLogbook(fCurrentDetector.Data(), "DONE");
1147 }
1148 else
1149 UpdateShuttleLogbook(fCurrentDetector.Data(), status->GetStatusName(status->GetStatus()));
1150
2bb7b766 1151 return kFALSE;
1152 }
1153
5e993b6f 1154 if (status->GetStatus() == AliShuttleStatus::kStoreStarted || status->GetStatus() == AliShuttleStatus::kStoreDelayed ||status->GetStatus() == AliShuttleStatus::kStoreError) {
2bb7b766 1155 Log("SHUTTLE",
c88ad5db 1156 Form("ContinueProcessing - %s: Grid storage of one or more "
1157 "objects failed. Trying again now",
2bb7b766 1158 fCurrentDetector.Data()));
5e993b6f 1159 StoreOCDB();
2bb7b766 1160 return kFALSE;
1161 }
1162
1163 // if we get here, there is a restart
57c1a579 1164 Bool_t cont = kFALSE;
2bb7b766 1165
1166 // abort conditions
cb343cfd 1167 if (status->GetCount() >= fConfig->GetMaxRetries()) {
57c1a579 1168 Log("SHUTTLE", Form("ContinueProcessing - %s failed %d times in status %s - "
1169 "Updating Shuttle Logbook", fCurrentDetector.Data(),
2bb7b766 1170 status->GetCount(), status->GetStatusName()));
1171 UpdateShuttleLogbook(fCurrentDetector.Data(), "FAILED");
e7f62f16 1172 UpdateShuttleStatus(AliShuttleStatus::kFailed);
3301427a 1173
1174 // there may still be objects in local OCDB and reference storage
1175 // and FXS databases may be not updated: do it now!
9827400b 1176
1177 // TODO Currently disabled, we want to keep files in case of failure!
1178 // CleanLocalStorage(fgkLocalCDB);
1179 // CleanLocalStorage(fgkLocalRefStorage);
1180 // UpdateTableFailCase();
1181
1182 // Send mail to detector expert!
c88ad5db 1183 Log("SHUTTLE", Form("ContinueProcessing - Sending mail to %s expert...",
926cbc0e 1184 fCurrentDetector.Data()));
fe6a3257 1185 // det experts in to
1186 TString to="";
1187 TIter *iterExperts = 0;
1188 iterExperts = new TIter(fConfig->GetResponsibles(fCurrentDetector));
1189 TObjString *anExpert=0;
1190 while ((anExpert = (TObjString*) iterExperts->Next()))
1191 {
1192 to += Form("%s, \n", anExpert->GetName());
1193 }
1194 delete iterExperts;
1195
1196 if (to.Length() > 0)
1197 to.Remove(to.Length()-3);
1198 AliDebug(2, Form("to: %s",to.Data()));
1199
1200 if (to.IsNull()) {
1201 Log("SHUTTLE", Form("List of %s responsibles not set!", fCurrentDetector.Data()));
1202 return kFALSE;
1203 }
1204
1205 Log(fCurrentDetector.Data(), Form("ContinueProcessing - Sending mail to %s expert(s):",
1206 fCurrentDetector.Data()));
1207 Log(fCurrentDetector.Data(), Form("\n%s", to.Data()));
339adafa 1208 if (!SendMail(kPPEMail))
9827400b 1209 Log("SHUTTLE", Form("ContinueProcessing - Could not send mail to %s expert",
926cbc0e 1210 fCurrentDetector.Data()));
3301427a 1211
57c1a579 1212 } else {
1213 Log("SHUTTLE", Form("ContinueProcessing - %s: restarting. "
1214 "Aborted before with %s. Retry number %d.", fCurrentDetector.Data(),
1215 status->GetStatusName(), status->GetCount()));
9827400b 1216 Bool_t increaseCount = kTRUE;
c88ad5db 1217 if (status->GetStatus() == AliShuttleStatus::kDCSError ||
8da81210 1218 status->GetStatus() == AliShuttleStatus::kDCSStarted ||
5ca8f352 1219 status->GetStatus() == AliShuttleStatus::kFXSError ||
1220 status->GetStatus() == AliShuttleStatus::kOCDBError)
c88ad5db 1221 increaseCount = kFALSE;
675f64cd 1222
9827400b 1223 UpdateShuttleStatus(AliShuttleStatus::kStarted, increaseCount);
57c1a579 1224 cont = kTRUE;
2bb7b766 1225 }
1226
57c1a579 1227 return cont;
5164a766 1228}
1229
8e828d39 1230//______________________________________________________________________________________________
1231void AliShuttle::SendMLRunInfo(const char* status)
1232{
1233 //
1234 // Send information about this run to ML
1235
1236 TMonaLisaText mlStatus("SHUTTLE_status", status);
1237 TString runType(fLogbookEntry->GetRunType());
1238 if (strlen(fLogbookEntry->GetRunParameter("log")) > 0){
1239
1240 runType += "(";
1241 runType += fLogbookEntry->GetRunParameter("log");
1242 runType += ")";
1243 }
728290a4 1244 if (fLogbookEntry->GetDATestMode()){
1245 runType += " (DATest)";
1246 }
8e828d39 1247 TMonaLisaText mlRunType("SHUTTLE_runtype", runType);
1248
1249 TList mlList;
1250 mlList.Add(&mlStatus);
1251 mlList.Add(&mlRunType);
1252
1253 TString mlID;
1254 mlID.Form("%d", GetCurrentRun());
1255 fMonaLisa->SendParameters(&mlList, mlID);
1256}
1257
ef83773f 1258//______________________________________________________________________________________________
1259Int_t AliShuttle::GetMem(Int_t pid)
1260{
1261 // invokes ps to get the memory consumption of the process <pid>
1262 // returns -1 in case of error
1263
1264 TString checkStr;
1265 checkStr.Form("ps -o vsize --pid %d | tail -n 1", pid);
1266 FILE* pipe = gSystem->OpenPipe(checkStr, "r");
1267 if (!pipe)
1268 {
1269 Log("SHUTTLE", Form("Process - Error: "
1270 "Could not open pipe to %s", checkStr.Data()));
1271 return -1;
1272 }
1273
1274 char buffer[100];
1275 if (!fgets(buffer, 100, pipe))
1276 {
1277 Log("SHUTTLE", "Process - Error: ps did not return anything");
1278 gSystem->ClosePipe(pipe);
1279 return -1;
1280 }
1281 gSystem->ClosePipe(pipe);
1282
1283 //Log("SHUTTLE", Form("ps returned %s", buffer));
1284
1285 Int_t mem = 0;
1286 if ((sscanf(buffer, "%d\n", &mem) != 1) || !mem)
1287 {
1288 Log("SHUTTLE", "Process - Error: Could not parse output of ps");
1289 return -1;
1290 }
1291
1292 return mem;
1293}
1294
5164a766 1295//______________________________________________________________________________________________
2bb7b766 1296Bool_t AliShuttle::Process(AliShuttleLogbookEntry* entry)
58bc3020 1297{
73abe331 1298 //
b948db8d 1299 // Makes data retrieval for all detectors in the configuration.
2bb7b766 1300 // entry: Shuttle logbook entry, contains run paramenters and status of detectors
1301 // (Unprocessed, Inactive, Failed or Done).
d477ad88 1302 // Returns kFALSE in case of error occured and kTRUE otherwise
73abe331 1303 //
1304
9827400b 1305 if (!entry) return kFALSE;
2bb7b766 1306
1307 fLogbookEntry = entry;
1308
c88ad5db 1309 Log("SHUTTLE", Form("\t\t\t^*^*^*^*^*^*^*^*^*^*^*^* run %d: START ^*^*^*^*^*^*^*^*^*^*^*^*",
9827400b 1310 GetCurrentRun()));
2bb7b766 1311
339adafa 1312 CountOpenRuns();
1313
8e828d39 1314 // Send the information to ML
1315 SendMLRunInfo("Processing");
3301427a 1316
9827400b 1317 if (fLogbookEntry->IsDone())
1318 {
1319 Log("SHUTTLE","Process - Shuttle is already DONE. Updating logbook");
1320 UpdateShuttleLogbook("shuttle_done");
1321 fLogbookEntry = 0;
1322 return kTRUE;
1323 }
1324
1325 // read test mode if flag is set
1326 if (fReadTestMode)
1327 {
3d8bc902 1328 fTestMode = kNone;
9827400b 1329 TString logEntry(entry->GetRunParameter("log"));
1330 //printf("log entry = %s\n", logEntry.Data());
1331 TString searchStr("Testmode: ");
1332 Int_t pos = logEntry.Index(searchStr.Data());
1333 //printf("%d\n", pos);
1334 if (pos >= 0)
1335 {
1336 TSubString subStr = logEntry(pos + searchStr.Length(), logEntry.Length());
1337 //printf("%s\n", subStr.String().Data());
1338 TString newStr(subStr.Data());
1339 TObjArray* token = newStr.Tokenize(' ');
1340 if (token)
1341 {
1342 //token->Print();
1343 TObjString* tmpStr = dynamic_cast<TObjString*> (token->First());
1344 if (tmpStr)
1345 {
1346 Int_t testMode = tmpStr->String().Atoi();
1347 if (testMode > 0)
1348 {
c88ad5db 1349 Log("SHUTTLE", Form("Process - Enabling test mode %d", testMode));
9827400b 1350 SetTestMode((TestMode) testMode);
1351 }
1352 }
1353 delete token;
1354 }
1355 }
1356 }
c88ad5db 1357
eba76848 1358 fLogbookEntry->Print("all");
57f50b3c 1359
1360 // Initialization
d477ad88 1361 Bool_t hasError = kFALSE;
5164a766 1362
728290a4 1363 // Set the CDB and Reference folders according to the year
1364
1365 // build cdb paths (repeat each time, run might be a DATest run)
1366 if (!fLogbookEntry->GetDATestMode()){
1367 fgkMainCDB.Form("alien://folder=%s%d/OCDB?user=alidaq?cacheFold=/tmp/OCDBCache",
1368 fConfig->GetAlienPath(), GetCurrentYear());
1369
1370 fgkMainRefStorage.Form("alien://folder=%s%d/Reference?user=alidaq?cacheFold=/tmp/OCDBCache",
1371 fConfig->GetAlienPath(), GetCurrentYear());
1372 }
1373 else {
1374 fgkMainCDB.Form("alien://folder=%s%d/DATest/OCDB?user=alidaq?cacheFold=/tmp/OCDBCache",
1375 fConfig->GetAlienPath(), GetCurrentYear());
1376
1377 fgkMainRefStorage.Form("alien://folder=%s%d/DATest/Reference?user=alidaq?cacheFold=/tmp/OCDBCache",
1378 fConfig->GetAlienPath(), GetCurrentYear());
1379 }
1380
1381 AliDebug(2,Form("Main CDB storage = %s",fgkMainCDB.Data()));
1382 AliDebug(2,Form("Main Reference storage = %s",fgkMainRefStorage.Data()));
1383
57f50b3c 1384 // Loop on detectors in the configuration
b948db8d 1385 TIter iter(fConfig->GetDetectors());
2bb7b766 1386 TObjString* aDetector = 0;
b948db8d 1387
4508ab8b 1388 Bool_t first = kTRUE;
1389
be48e3ea 1390 while ((aDetector = (TObjString*) iter.Next()))
1391 {
7bfb2090 1392 fCurrentDetector = aDetector->String();
5164a766 1393
5e993b6f 1394 if (ContinueProcessing() == kFALSE)
1395 continue;
4508ab8b 1396
1397 if (first)
1398 {
1399 // only read QueryCDB when needed and only once
1400 AliCDBStorage *mainCDBSto = AliCDBManager::Instance()->GetStorage(fgkMainCDB);
1401 if(mainCDBSto) mainCDBSto->QueryCDB(GetCurrentRun());
1402 AliCDBStorage *mainRefSto = AliCDBManager::Instance()->GetStorage(fgkMainRefStorage);
1403 if(mainRefSto) mainRefSto->QueryCDB(GetCurrentRun());
1404 first = kFALSE;
1405 }
9e080f92 1406
c88ad5db 1407 Log("SHUTTLE", Form("\t\t\t****** run %d - %s: START ******",
2bb7b766 1408 GetCurrentRun(), aDetector->GetName()));
1409
6e25f828 1410 for(Int_t iSys=0;iSys<4;iSys++) fFXSCalled[iSys]=kFALSE;
ef83773f 1411
1412 Int_t initialMem = GetMem(getpid());
1413 Log("SHUTTLE", Form("Memory consumption before forking is %d", initialMem));
9d733021 1414
c88ad5db 1415 Log(fCurrentDetector.Data(), "Process - Starting processing");
85a80aa9 1416
be48e3ea 1417 Int_t pid = fork();
1418
1419 if (pid < 0)
1420 {
c88ad5db 1421 Log("SHUTTLE", "Process - ERROR: Forking failed");
be48e3ea 1422 }
1423 else if (pid > 0)
1424 {
1425 // parent
c88ad5db 1426 Log("SHUTTLE", Form("Process - In parent process of %d - %s: Starting monitoring",
be48e3ea 1427 GetCurrentRun(), aDetector->GetName()));
1428
1429 Long_t begin = time(0);
1430
1431 int status; // to be used with waitpid, on purpose an int (not Int_t)!
1432 while (waitpid(pid, &status, WNOHANG) == 0)
1433 {
1434 Long_t expiredTime = time(0) - begin;
1435
1436 if (expiredTime > fConfig->GetPPTimeOut())
1437 {
56d3e9e4 1438 TString logMsg;
1439 AliShuttleStatus *currentStatus = ReadShuttleStatus();
1440 AliShuttleStatus::Status newStatus = AliShuttleStatus::kInvalid;
1441
838d9827 1442 if (currentStatus->GetStatus() == AliShuttleStatus::kDCSStarted)
1443 {
1444 // in case the pp goes in TimeOut while retrieving the DCS DPs
1445 // set status to kDCSError
1446
0a0b087a 1447 logMsg.Form("Process - Process of %s timed out while retrieving the DCS DataPoints. Run time: %ld seconds. Killing... and setting status to DCSError.",
838d9827 1448 fCurrentDetector.Data(), expiredTime);
1449 newStatus = AliShuttleStatus::kDCSError;
1450 }
1451 else if (currentStatus->GetStatus() <= AliShuttleStatus::kPPDone)
56d3e9e4 1452 {
1453 // in case pp not yet done set status to kPPTimeOut
1454
0a0b087a 1455 logMsg.Form("Process - Process of %s timed out. Run time: %ld seconds. Killing...",
56d3e9e4 1456 fCurrentDetector.Data(), expiredTime);
1457 newStatus = AliShuttleStatus::kPPTimeOut;
1458 }
1459 else if (currentStatus->GetStatus() == AliShuttleStatus::kStoreStarted)
1460 {
1461 // in case the pp goes in TimeOut while storing the objects in the OCDB
1462 // set status to kStoreError
1463
0a0b087a 1464 logMsg.Form("Process - Process of %s timed out while storing the OCDB object. Run time: %ld seconds. Killing... and setting status to StoreError.",
56d3e9e4 1465 fCurrentDetector.Data(), expiredTime);
1466 newStatus = AliShuttleStatus::kStoreError;
1467 }
1468 else
1469 {
1470 // in other cases don't change the status
1471
0a0b087a 1472 logMsg.Form("Process - Process of %s timed out in status = %s. Run time: %ld seconds. Killing... without changing the status",
56d3e9e4 1473 fCurrentDetector.Data(), currentStatus->GetStatusName(), expiredTime);
1474 }
1475
1476 Log("SHUTTLE", logMsg);
1477 Log(fCurrentDetector, logMsg);
be48e3ea 1478
1479 kill(pid, 9);
1480
56d3e9e4 1481 if (newStatus != AliShuttleStatus::kInvalid)
1482 UpdateShuttleStatus(newStatus);
be48e3ea 1483 hasError = kTRUE;
1484
1485 gSystem->Sleep(1000);
1486 }
1487 else
1488 {
be48e3ea 1489 gSystem->Sleep(1000);
9827400b 1490
ef83773f 1491 Int_t mem = GetMem(pid);
1492
1493 if (mem < 0)
9827400b 1494 continue;
9827400b 1495
ef83773f 1496 mem -= initialMem;
1497 if (mem < 0)
1498 mem = 0;
9827400b 1499
1500 if (expiredTime % 60 == 0)
ee6f7523 1501 {
c88ad5db 1502 Log("SHUTTLE", Form("Process - %s: Checking process. "
0a0b087a 1503 "Run time: %ld seconds - Memory consumption: %d KB",
c88ad5db 1504 fCurrentDetector.Data(), expiredTime, mem));
ee6f7523 1505 SendAlive();
1506 }
9827400b 1507
1508 if (mem > fConfig->GetPPMaxMem())
1509 {
1510 TString tmp;
c88ad5db 1511 tmp.Form("Process - Process exceeds maximum allowed memory "
1512 "(%d KB > %d KB). Killing...",
9827400b 1513 mem, fConfig->GetPPMaxMem());
1514 Log("SHUTTLE", tmp);
1515 Log(fCurrentDetector, tmp);
1516
1517 kill(pid, 9);
1518
1519 UpdateShuttleStatus(AliShuttleStatus::kPPOutOfMemory);
1520 hasError = kTRUE;
1521
1522 gSystem->Sleep(1000);
1523 }
be48e3ea 1524 }
1525 }
1526
c88ad5db 1527 Log("SHUTTLE", Form("Process - In parent process of %d - %s: Client has terminated.",
be48e3ea 1528 GetCurrentRun(), aDetector->GetName()));
1529
1530 if (WIFEXITED(status))
1531 {
1532 Int_t returnCode = WEXITSTATUS(status);
1533
c88ad5db 1534 Log("SHUTTLE", Form("Process - %s: the return code is %d", fCurrentDetector.Data(),
3301427a 1535 returnCode));
be48e3ea 1536
9827400b 1537 if (returnCode == 0) hasError = kTRUE;
be48e3ea 1538 }
1539 }
1540 else if (pid == 0)
1541 {
26b1866e 1542 // child
1543 Log("SHUTTLE", Form("Process - In child process of %d - %s", GetCurrentRun(),
c88ad5db 1544 aDetector->GetName()));
be48e3ea 1545
c88ad5db 1546 Log("SHUTTLE", Form("Process - Redirecting output to %s log",fCurrentDetector.Data()));
ffa29e93 1547
546242fb 1548 if ((freopen(GetLogFileName(fCurrentDetector), "a", stdout)) == 0)
ffa29e93 1549 {
c88ad5db 1550 Log("SHUTTLE", "Process - Could not freopen stdout");
ffa29e93 1551 }
1552 else
1553 {
1554 fOutputRedirected = kTRUE;
1555 if ((dup2(fileno(stdout), fileno(stderr))) < 0)
c88ad5db 1556 Log("SHUTTLE", "Process - Could not redirect stderr");
ffa29e93 1557
1558 }
51c3744e 1559
1560 Log("SHUTTLE", "Executing TGrid::Connect");
1561 TGrid::Connect("alien://");
ffa29e93 1562
5bac2bde 1563 TString wd = gSystem->WorkingDirectory();
3ebbf3c4 1564 Int_t dir_lev1 = GetCurrentRun()/10000;
1565 TString tmpDir = Form("%s/%d/%d/%s_process", GetShuttleTempDir(),
1566 dir_lev1, GetCurrentRun(), fCurrentDetector.Data());
5bac2bde 1567
d524ade6 1568 Int_t result = gSystem->GetPathInfo(tmpDir.Data(), 0, (Long64_t*) 0, 0, 0);
1569 if (!result) // temp dir already exists!
1570 {
1571 Log(fCurrentDetector.Data(),
1572 Form("Process - %s dir already exists! Removing...", tmpDir.Data()));
1573 gSystem->Exec(Form("rm -rf %s",tmpDir.Data()));
675f64cd 1574 }
1575
1576 if (gSystem->mkdir(tmpDir.Data(), 1))
1577 {
1578 Log(fCurrentDetector.Data(), "Process - could not make temp directory!!");
1579 gSystem->Exit(1);
d524ade6 1580 }
1581
1582 if (!gSystem->ChangeDirectory(tmpDir.Data()))
1583 {
1584 Log(fCurrentDetector.Data(), "Process - could not change directory!!");
1585 gSystem->Exit(1);
1586 }
5bac2bde 1587
ffa25f20 1588 Int_t success = ProcessCurrentDetector();
26b1866e 1589
5bac2bde 1590 gSystem->ChangeDirectory(wd.Data());
b1d18693 1591
ffa25f20 1592 if (success == 1) // Preprocessor finished successfully!
9827400b 1593 {
fb40ead4 1594 // remove temporary folder or DCS map
1595 if (!fConfig->KeepTempFolder())
1596 {
1597 gSystem->Exec(Form("rm -rf %s",tmpDir.Data()));
1598 } else if (!fConfig->KeepDCSMap())
1599 {
1600 gSystem->Exec(Form("rm -f %s/DCSMap.root",tmpDir.Data()));
1601 }
b1d18693 1602
3301427a 1603 // Update time_processed field in FXS DB
1604 if (UpdateTable() == kFALSE)
5bac2bde 1605 Log("SHUTTLE", Form("Process - %s: Could not update FXS databases!",
1606 fCurrentDetector.Data()));
3301427a 1607
1608 // Transfer the data from local storage to main storage (Grid)
3301427a 1609 if (StoreOCDB() == kFALSE)
9827400b 1610 success = kFALSE;
5e993b6f 1611 }
ffa25f20 1612 else if (success == 0)
c88ad5db 1613 {
1614 Log("SHUTTLE",
5ca8f352 1615 Form("\t\t\t****** run %d - %s: ERROR ******",
c88ad5db 1616 GetCurrentRun(), aDetector->GetName()));
be48e3ea 1617 }
1618
6e25f828 1619 for (UInt_t iSys=0; iSys<4; iSys++)
4b95672b 1620 {
1621 if (fFXSCalled[iSys]) fFXSlist[iSys].Clear();
1622 }
1623
c88ad5db 1624 Log("SHUTTLE", Form("Process - Client process of %d - %s is exiting now with %d.",
9827400b 1625 GetCurrentRun(), aDetector->GetName(), success));
be48e3ea 1626
1627 // the client exits here
9827400b 1628 gSystem->Exit(success);
be48e3ea 1629
1630 AliError("We should never get here!!!");
1631 }
7bfb2090 1632 }
5164a766 1633
c88ad5db 1634 Log("SHUTTLE", Form("\t\t\t^*^*^*^*^*^*^*^*^*^*^*^* run %d: FINISH ^*^*^*^*^*^*^*^*^*^*^*^*",
2bb7b766 1635 GetCurrentRun()));
1636
1637 //check if shuttle is done for this run, if so update logbook
1638 TObjArray checkEntryArray;
1639 checkEntryArray.SetOwner(1);
9e080f92 1640 TString whereClause = Form("where run=%d", GetCurrentRun());
b0e53b15 1641 if (!QueryShuttleLogbook(whereClause.Data(), checkEntryArray) ||
1642 checkEntryArray.GetEntries() == 0) {
9e080f92 1643 Log("SHUTTLE", Form("Process - Warning: Cannot check status of run %d on Shuttle logbook!",
1644 GetCurrentRun()));
1645 return hasError == kFALSE;
1646 }
b948db8d 1647
9e080f92 1648 AliShuttleLogbookEntry* checkEntry = dynamic_cast<AliShuttleLogbookEntry*>
1649 (checkEntryArray.At(0));
2bb7b766 1650
9e080f92 1651 if (checkEntry)
1652 {
1653 if (checkEntry->IsDone())
be48e3ea 1654 {
9e080f92 1655 Log("SHUTTLE","Process - Shuttle is DONE. Updating logbook");
1656 UpdateShuttleLogbook("shuttle_done");
1657 }
1658 else
1659 {
1660 for (UInt_t iDet=0; iDet<NDetectors(); iDet++)
be48e3ea 1661 {
9e080f92 1662 if (checkEntry->GetDetectorStatus(iDet) == AliShuttleLogbookEntry::kUnprocessed)
be48e3ea 1663 {
9e080f92 1664 AliDebug(2, Form("Run %d: setting %s as \"not first time unprocessed\"",
1665 checkEntry->GetRun(), GetDetName(iDet)));
1666 fFirstUnprocessed[iDet] = kFALSE;
be48e3ea 1667 }
1668 }
8e828d39 1669 SendMLRunInfo("Pending");
2bb7b766 1670 }
1671 }
1672
1673 fLogbookEntry = 0;
85a80aa9 1674
a7160fe9 1675 return hasError == kFALSE;
73abe331 1676}
1677
b948db8d 1678//______________________________________________________________________________________________
ffa25f20 1679Int_t AliShuttle::ProcessCurrentDetector()
73abe331 1680{
1681 //
2bb7b766 1682 // Makes data retrieval just for a specific detector (fCurrentDetector).
73abe331 1683 // Threre should be a configuration for this detector.
73abe331 1684
1d172743 1685 Log("SHUTTLE", Form("ProcessCurrentDetector - Retrieving values for %s, run %d",
1686 fCurrentDetector.Data(), GetCurrentRun()));
73abe331 1687
d524ade6 1688 TString wd = gSystem->WorkingDirectory();
1689
2d9019b4 1690 if (!CleanReferenceStorage(fCurrentDetector.Data()))
ffa25f20 1691 return 0;
d524ade6 1692
1693 gSystem->ChangeDirectory(wd.Data());
1694
3301427a 1695 // call preprocessor
1696 AliPreprocessor* aPreprocessor =
1697 dynamic_cast<AliPreprocessor*> (fPreprocessorMap.GetValue(fCurrentDetector));
1698
8579c6fb 1699 // check if the preprocessor wants to process this run type
1700 if (aPreprocessor->ProcessRunType() == kFALSE)
ffa25f20 1701 {
1702 UpdateShuttleStatus(AliShuttleStatus::kSkipped);
1703 UpdateShuttleLogbook(fCurrentDetector, "DONE");
bd23d48b 1704 if (!UpdateTableSkippedCase(fCurrentDetector.Data()))
1705 {
1706 AliError(Form("Could not update FXS tables for run %d !", GetCurrentRun()));
1707 }
ffa25f20 1708 Log(fCurrentDetector, Form("ProcessCurrentDetector - %s preprocessor is not interested in this run type", fCurrentDetector.Data()));
1709
1710 return 2;
1711 }
1712
5ca8f352 1713 // checking if OCDB is reachable
1714 AliCDBEntry* testEntry = GetFromOCDB("SHUTTLE","GRP/CTP/DummyConfig");
1715 if (!testEntry){
1716 // OCDB is not accessible, going in OCDBError for current detector
1717 AliError("OCDB Test entry not accessible");
1718 UpdateShuttleStatus(AliShuttleStatus::kOCDBError);
1719 return 0;
1720 }
1721
ffa25f20 1722 TMap* dcsMap = new TMap();
1723
3301427a 1724 aPreprocessor->Initialize(GetCurrentRun(), GetCurrentStartTime(), GetCurrentEndTime());
1725
1726 Bool_t processDCS = aPreprocessor->ProcessDCS();
d477ad88 1727
651fdaab 1728 if (!processDCS)
1729 {
1d172743 1730 Log(fCurrentDetector, "ProcessCurrentDetector -"
1731 " The preprocessor requested to skip the retrieval of DCS values");
651fdaab 1732 }
8b739301 1733 else if (fTestMode & kSkipDCS)
2c15234c 1734 {
1d172743 1735 Log(fCurrentDetector, "ProcessCurrentDetector - In TESTMODE: Skipping DCS processing");
9827400b 1736 }
1737 else if (fTestMode & kErrorDCS)
1738 {
1d172743 1739 Log(fCurrentDetector, "ProcessCurrentDetector - In TESTMODE: Simulating DCS error");
3d8bc902 1740 UpdateShuttleStatus(AliShuttleStatus::kDCSStarted);
9827400b 1741 UpdateShuttleStatus(AliShuttleStatus::kDCSError);
1d172743 1742 delete dcsMap;
ffa25f20 1743 return 0;
2c15234c 1744 } else {
3301427a 1745
1746 UpdateShuttleStatus(AliShuttleStatus::kDCSStarted);
1747
1d172743 1748 // Query DCS archive
1749 Int_t nServers = fConfig->GetNServers(fCurrentDetector);
a038aa70 1750
1d172743 1751 for (int iServ=0; iServ<nServers; iServ++)
2c15234c 1752 {
1d172743 1753
1754 TString host(fConfig->GetDCSHost(fCurrentDetector, iServ));
1755 Int_t port = fConfig->GetDCSPort(fCurrentDetector, iServ);
542b6cc8 1756 Int_t multiSplit = fConfig->GetMultiSplit(fCurrentDetector, iServ);
1757
1790d4b7 1758 Log(fCurrentDetector, Form("ProcessCurrentDetector -"
1759 " Querying DCS Amanda server %s:%d (%d of %d)",
1760 host.Data(), port, iServ+1, nServers));
1d172743 1761
1762 TMap* aliasMap = 0;
1763 TMap* dpMap = 0;
26b1866e 1764
1d172743 1765 if (fConfig->GetDCSAliases(fCurrentDetector, iServ)->GetEntries() > 0)
2c15234c 1766 {
5ed060b1 1767 Log(fCurrentDetector, Form("Querying %d DCS aliases", fConfig->GetDCSAliases(fCurrentDetector, iServ)->GetEntries()));
1d172743 1768 aliasMap = GetValueSet(host, port,
542b6cc8 1769 fConfig->GetDCSAliases(fCurrentDetector, iServ),
1770 kAlias, multiSplit);
1d172743 1771 if (!aliasMap)
1772 {
1773 Log(fCurrentDetector,
1774 Form("ProcessCurrentDetector -"
675f64cd 1775 " Error retrieving DCS aliases from server %s."
1776 " Sending mail to DCS experts!", host.Data()));
1d172743 1777 UpdateShuttleStatus(AliShuttleStatus::kDCSError);
675f64cd 1778
339adafa 1779 if (!SendMail(kDCSEMail))
fb40ead4 1780 Log("SHUTTLE", Form("ProcessCurrentDetector - "
95d4aaef 1781 "Could not send mail to DCS experts!"));
675f64cd 1782
a038aa70 1783 delete dcsMap;
ffa25f20 1784 return 0;
1d172743 1785 }
2c15234c 1786 }
a038aa70 1787
1d172743 1788 if (fConfig->GetDCSDataPoints(fCurrentDetector, iServ)->GetEntries() > 0)
a038aa70 1789 {
5ed060b1 1790 Log(fCurrentDetector, Form("Querying %d DCS data points", fConfig->GetDCSDataPoints(fCurrentDetector, iServ)->GetEntries()));
1d172743 1791 dpMap = GetValueSet(host, port,
542b6cc8 1792 fConfig->GetDCSDataPoints(fCurrentDetector, iServ),
1793 kDP, multiSplit);
1d172743 1794 if (!dpMap)
1795 {
1796 Log(fCurrentDetector,
1797 Form("ProcessCurrentDetector -"
675f64cd 1798 " Error retrieving DCS data points from server %s."
1799 " Sending mail to DCS experts!", host.Data()));
1d172743 1800 UpdateShuttleStatus(AliShuttleStatus::kDCSError);
675f64cd 1801
339adafa 1802 if (!SendMail(kDCSEMail))
fb40ead4 1803 Log("SHUTTLE", Form("ProcessCurrentDetector - "
95d4aaef 1804 "Could not send mail to DCS experts!"));
675f64cd 1805
1d172743 1806 if (aliasMap) delete aliasMap;
1807 delete dcsMap;
ffa25f20 1808 return 0;
1d172743 1809 }
a038aa70 1810 }
1d172743 1811
1812 // merge aliasMap and dpMap into dcsMap
1813 if(aliasMap) {
1814 TIter iter(aliasMap);
a038aa70 1815 TObjString* key = 0;
1816 while ((key = (TObjString*) iter.Next()))
1d172743 1817 dcsMap->Add(key, aliasMap->GetValue(key->String()));
1818
1819 aliasMap->SetOwner(kFALSE);
1820 delete aliasMap;
1821 }
1822
1823 if(dpMap) {
1824 TIter iter(dpMap);
1825 TObjString* key = 0;
1826 while ((key = (TObjString*) iter.Next()))
1827 dcsMap->Add(key, dpMap->GetValue(key->String()));
1828
1829 dpMap->SetOwner(kFALSE);
1830 delete dpMap;
a038aa70 1831 }
73abe331 1832 }
1833 }
dc25836b 1834
b1d18693 1835 // save map into file, to help debugging in case of preprocessor error
fbc112e3 1836 TFile* f = TFile::Open("DCSMap.root","recreate");
b1d18693 1837 f->cd();
1838 dcsMap->Write("DCSMap", TObject::kSingleKey);
1839 f->Close();
fbc112e3 1840 delete f;
b1d18693 1841
2bb7b766 1842 // DCS Archive DB processing successful. Call Preprocessor!
85a80aa9 1843 UpdateShuttleStatus(AliShuttleStatus::kPPStarted);
a7160fe9 1844
339adafa 1845 fFXSError = -1; // this variable is kTRUE after ::Process if an FXS error occured
8da81210 1846
a038aa70 1847 UInt_t returnValue = aPreprocessor->Process(dcsMap);
8da81210 1848
339adafa 1849 if (fFXSError!=-1) {
8da81210 1850 UpdateShuttleStatus(AliShuttleStatus::kFXSError);
339adafa 1851 SendMail(kFXSEMail, fFXSError);
8da81210 1852 dcsMap->DeleteAll();
1853 delete dcsMap;
ffa25f20 1854 return 0;
8da81210 1855 }
b948db8d 1856
3301427a 1857 if (returnValue > 0) // Preprocessor error!
1858 {
c88ad5db 1859 Log(fCurrentDetector, Form("ProcessCurrentDetector - "
1860 "Preprocessor failed. Process returned %d.", returnValue));
cb343cfd 1861 UpdateShuttleStatus(AliShuttleStatus::kPPError);
a038aa70 1862 dcsMap->DeleteAll();
1863 delete dcsMap;
ffa25f20 1864 return 0;
9827400b 1865 }
1866
1867 // preprocessor ok!
1868 UpdateShuttleStatus(AliShuttleStatus::kPPDone);
1869 Log(fCurrentDetector, Form("ProcessCurrentDetector - %s preprocessor returned success",
1870 fCurrentDetector.Data()));
b948db8d 1871
a038aa70 1872 dcsMap->DeleteAll();
1873 delete dcsMap;
b948db8d 1874
ffa25f20 1875 return 1;
2bb7b766 1876}
1877
fbc112e3 1878//______________________________________________________________________________________________
1879void AliShuttle::CountOpenRuns()
1880{
1881 // Query DAQ's Shuttle logbook and sends the number of open runs to ML
1882
982278d6 1883 SendAlive();
1884
fbc112e3 1885 // check connection, in case connect
efec19bd 1886 if (!Connect(4))
fbc112e3 1887 return;
1888
1889 TString sqlQuery;
1890 sqlQuery = Form("select count(*) from %s where shuttle_done=0", fConfig->GetShuttlelbTable());
1891
efec19bd 1892 TSQLResult* aResult = fServer[4]->Query(sqlQuery);
fbc112e3 1893 if (!aResult) {
1894 AliError(Form("Can't execute query <%s>!", sqlQuery.Data()));
1895 return;
1896 }
1897
1898 AliDebug(2,Form("Query = %s", sqlQuery.Data()));
1899
1900 if (aResult->GetRowCount() == 0) {
1901 AliError(Form("No result for query %s received", sqlQuery.Data()));
1902 return;
1903 }
1904
1905 if (aResult->GetFieldCount() != 1) {
1906 AliError(Form("Invalid field count for query %s received", sqlQuery.Data()));
1907 return;
1908 }
1909
1910 TSQLRow* aRow = aResult->Next();
1911 if (!aRow) {
1912 AliError(Form("Could not receive result of query %s", sqlQuery.Data()));
1913 return;
1914 }
1915
1916 TString result(aRow->GetField(0), aRow->GetFieldLength(0));
1917 Int_t count = result.Atoi();
1918
1919 Log("SHUTTLE", Form("%d unprocessed runs", count));
1920
1921 delete aRow;
1922 delete aResult;
1923
1924 TMonaLisaValue mlStatus("SHUTTLE_openruns", count);
1925
1926 TList mlList;
1927 mlList.Add(&mlStatus);
1928
1929 fMonaLisa->SendParameters(&mlList, "__PROCESSINGINFO__");
1930}
1931
2bb7b766 1932//______________________________________________________________________________________________
1933Bool_t AliShuttle::QueryShuttleLogbook(const char* whereClause,
1934 TObjArray& entries)
1935{
9827400b 1936 // Query DAQ's Shuttle logbook and fills detector status object.
1937 // Call QueryRunParameters to query DAQ logbook for run parameters.
1938 //
2bb7b766 1939
fc5a4708 1940 entries.SetOwner(1);
1941
2bb7b766 1942 // check connection, in case connect
efec19bd 1943 if (!Connect(4)) return kFALSE;
2bb7b766 1944
1945 TString sqlQuery;
441b0e9c 1946 sqlQuery = Form("select * from %s %s order by run", fConfig->GetShuttlelbTable(), whereClause);
2bb7b766 1947
efec19bd 1948 TSQLResult* aResult = fServer[4]->Query(sqlQuery);
2bb7b766 1949 if (!aResult) {
1950 AliError(Form("Can't execute query <%s>!", sqlQuery.Data()));
1951 return kFALSE;
1952 }
1953
fc5a4708 1954 AliDebug(2,Form("Query = %s", sqlQuery.Data()));
1955
2bb7b766 1956 if(aResult->GetRowCount() == 0) {
c88ad5db 1957 Log("SHUTTLE", "No entries in Shuttle Logbook match request");
9827400b 1958 delete aResult;
1959 return kTRUE;
2bb7b766 1960 }
1961
1962 // TODO Check field count!
5b23e2da 1963 const UInt_t nCols = 26;
2bb7b766 1964 if (aResult->GetFieldCount() != (Int_t) nCols) {
c88ad5db 1965 Log("SHUTTLE", "Invalid SQL result field number!");
2bb7b766 1966 delete aResult;
1967 return kFALSE;
1968 }
1969
2bb7b766 1970 TSQLRow* aRow;
1971 while ((aRow = aResult->Next())) {
1972 TString runString(aRow->GetField(0), aRow->GetFieldLength(0));
1973 Int_t run = runString.Atoi();
1974
eba76848 1975 AliShuttleLogbookEntry *entry = QueryRunParameters(run);
1976 if (!entry)
1977 continue;
2bb7b766 1978
728290a4 1979 // DA test mode flag
1980 TString daTestModeString(aRow->GetField(2), aRow->GetFieldLength(2)); // field 2 = DA test mode flag
1981 Bool_t daTestMode = (Bool_t)daTestModeString.Atoi();
1982 entry->SetDATestMode(daTestMode);
1983
2bb7b766 1984 // loop on detectors
eba76848 1985 for(UInt_t ii = 0; ii < nCols; ii++)
1986 entry->SetDetectorStatus(aResult->GetFieldName(ii), aRow->GetField(ii));
2bb7b766 1987
eba76848 1988 entries.AddLast(entry);
2bb7b766 1989 delete aRow;
1990 }
1991
2bb7b766 1992 delete aResult;
1993 return kTRUE;
1994}
1995
1996//______________________________________________________________________________________________
eba76848 1997AliShuttleLogbookEntry* AliShuttle::QueryRunParameters(Int_t run)
2bb7b766 1998{
eba76848 1999 //
2000 // Retrieve run parameters written in the DAQ logbook and sets them into AliShuttleLogbookEntry object
2001 //
2bb7b766 2002
2003 // check connection, in case connect
efec19bd 2004 if (!Connect(4))
eba76848 2005 return 0;
2bb7b766 2006
2007 TString sqlQuery;
2c15234c 2008 sqlQuery.Form("select * from %s where run=%d", fConfig->GetDAQlbTable(), run);
2bb7b766 2009
efec19bd 2010 TSQLResult* aResult = fServer[4]->Query(sqlQuery);
2bb7b766 2011 if (!aResult) {
c88ad5db 2012 Log("SHUTTLE", Form("Can't execute query <%s>!", sqlQuery.Data()));
eba76848 2013 return 0;
2bb7b766 2014 }
2015
eba76848 2016 if (aResult->GetRowCount() == 0) {
2bb7b766 2017 Log("SHUTTLE", Form("QueryRunParameters - No entry in DAQ Logbook for run %d. Skipping", run));
2018 delete aResult;
eba76848 2019 return 0;
2bb7b766 2020 }
2021
eba76848 2022 if (aResult->GetRowCount() > 1) {
c88ad5db 2023 Log("SHUTTLE", Form("QueryRunParameters - UNEXPECTED: "
2024 "more than one entry in DAQ Logbook for run %d!", run));
2bb7b766 2025 delete aResult;
eba76848 2026 return 0;
2bb7b766 2027 }
2028
eba76848 2029 TSQLRow* aRow = aResult->Next();
2030 if (!aRow)
2031 {
c88ad5db 2032 Log("SHUTTLE", Form("QueryRunParameters - Could not retrieve row for run %d. Skipping", run));
eba76848 2033 delete aResult;
2034 return 0;
2035 }
2bb7b766 2036
eba76848 2037 AliShuttleLogbookEntry* entry = new AliShuttleLogbookEntry(run);
2bb7b766 2038
eba76848 2039 for (Int_t ii = 0; ii < aResult->GetFieldCount(); ii++)
2040 entry->SetRunParameter(aResult->GetFieldName(ii), aRow->GetField(ii));
2bb7b766 2041
c9db68c7 2042 delete aRow;
2043 delete aResult;
2044
eba76848 2045 UInt_t startTime = entry->GetStartTime();
2046 UInt_t endTime = entry->GetEndTime();
89bcf3b4 2047 Bool_t ecsSuccess = entry->GetECSSuccess();
1415d3f9 2048 TString runType = entry->GetRunType();
2049 TString tmpdaqstartTime = entry->GetRunParameter("DAQ_time_start");
f38b266c 2050 TString recordingFlagString = entry->GetRunParameter("GDCmStreamRecording");
2051 UInt_t recordingFlag = recordingFlagString.Atoi();
1415d3f9 2052 UInt_t daqstartTime = tmpdaqstartTime.Atoi();
c9db68c7 2053
af93e5d7 2054 UInt_t now = time(0);
2eb98462 2055 Int_t dcsDelay = fConfig->GetDCSDelay()+fConfig->GetDCSQueryOffset();
8e828d39 2056
2057 Bool_t skip = kFALSE;
2058
1415d3f9 2059 // runs are processed if
2060 // a) runType is PHYSICS and ecsSuccess is set
2061 // b) runType is not PHYSICS and (ecsSuccess is set or DAQ_time_start is non-0)
2062 // 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 2063 if (startTime != 0 && endTime != 0) {
2064 if (endTime > startTime) {
2065 if (endTime >= now - dcsDelay) {
2066 Log("SHUTTLE", Form("Skipping run %d for now, because DCS buffer time is not yet expired", run));
2067 } else {
f38b266c 2068 if ((runType == "PHYSICS" || runType == "STANDALONE") && recordingFlag == 0){
2069 Log("SHUTTLE", Form("QueryRunParameters - Run type for run %d is %s but the recording is OFF - Skipping!", run, runType.Data()));
2070 skip = kTRUE;
2071 }
2072 else {
2073 if (runType == "PHYSICS") {
2074 if (ecsSuccess) {
2075 return entry;
2076 } else {
2077 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")));
2078 skip = kTRUE;
2079 }
1bbcc21b 2080 } else {
f38b266c 2081 if (ecsSuccess || daqstartTime > 0) {
2082 if (ecsSuccess == kFALSE)
2083 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")));
2084 return entry;
2085 } else {
2086 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")));
2087 skip = kTRUE;
2088 }
1bbcc21b 2089 }
2090 }
2091 }
2092 } else {
2093 Log("SHUTTLE", Form("QueryRunParameters - Invalid parameters for run %d: startTime equal to endTime: %d %d - Skipping!", run, startTime, endTime));
2094 skip = kTRUE;
2095 }
1415d3f9 2096 } else {
2097 Log("SHUTTLE", Form("QueryRunParameters - Invalid parameters for Run %d: "
2098 "startTime = %d, endTime = %d. Skipping (Shuttle won't be marked as DONE)!",
2099 run, startTime, endTime));
89bcf3b4 2100 }
8e828d39 2101
2102 if (skip)
2103 {
2104 Log("SHUTTLE", Form("Marking SHUTTLE skipped for run %d", run));
2105 fLogbookEntry = entry;
2106 if (!UpdateShuttleLogbook("shuttle_skipped"))
2107 {
2108 AliError(Form("Could not update logbook for run %d !", run));
2109 }
bd23d48b 2110 if (!UpdateTableSkippedCase("ALL"))
2111 {
2112 AliError(Form("Could not update FXS tables for run %d !", run));
2113 }
8e828d39 2114 fLogbookEntry = 0;
2115 }
c9db68c7 2116
2117 delete entry;
2118 return 0;
2bb7b766 2119}
2120
a038aa70 2121//______________________________________________________________________________________________
2122TMap* AliShuttle::GetValueSet(const char* host, Int_t port, const TSeqCollection* entries,
542b6cc8 2123 DCSType type, Int_t multiSplit)
a038aa70 2124{
2125 // Retrieve all "entry" data points from the DCS server
2126 // host, port: TSocket connection parameters
2127 // entries: list of name of the alias or data point
2128 // type: kAlias or kDP
2129 // returns TMap of values, 0 when failure
542b6cc8 2130
2131 AliDCSClient client(host, port, fTimeout, fRetries, multiSplit);
b41b252a 2132
a038aa70 2133 TMap* result = 0;
b41b252a 2134 if (type == kAlias)
a038aa70 2135 {
5f3fe74e 2136 //result = client.GetAliasValues(entries, GetCurrentStartTime()-offset,
2137 // GetCurrentEndTime()+offset);
eff647d5 2138 result = client.GetAliasValues(entries, GetStartTimeDCSQuery(),
2139 GetEndTimeDCSQuery());
b41b252a 2140 }
2141 else if (type == kDP)
2142 {
5f3fe74e 2143 //result = client.GetDPValues(entries, GetCurrentStartTime()-offset,
2144 // GetCurrentEndTime()+offset);
eff647d5 2145 result = client.GetDPValues(entries, GetStartTimeDCSQuery(),
2146 GetEndTimeDCSQuery());
b41b252a 2147 }
a038aa70 2148
b41b252a 2149 if (result == 0)
2150 {
2151 Log(fCurrentDetector.Data(), Form("GetValueSet - Can't get entries! Reason: %s",
1790d4b7 2152 client.GetErrorString(client.GetResultErrorCode())));
2153 if (client.GetResultErrorCode() == AliDCSClient::fgkServerError)
2154 Log(fCurrentDetector.Data(), Form("GetValueSet - Server error code: %s",
2155 client.GetServerError().Data()));
a038aa70 2156
b41b252a 2157 return 0;
a038aa70 2158 }
b41b252a 2159
a038aa70 2160 return result;
2161}
b41b252a 2162
b948db8d 2163//______________________________________________________________________________________________
57f50b3c 2164const char* AliShuttle::GetFile(Int_t system, const char* detector,
2165 const char* id, const char* source)
b948db8d 2166{
9827400b 2167 // Get calibration file from file exchange servers
2168 // First queris the FXS database for the file name, using the run, detector, id and source info
2169 // then calls RetrieveFile(filename) for actual copy to local disk
2170 // run: current run being processed (given by Logbook entry fLogbookEntry)
2171 // detector: the Preprocessor name
2172 // id: provided as a parameter by the Preprocessor
2173 // source: provided by the Preprocessor through GetFileSources function
2174
2175 // check if test mode should simulate a FXS error
2176 if (fTestMode & kErrorFXSFiles)
2177 {
2178 Log(detector, Form("GetFile - In TESTMODE - Simulating error while connecting to %s FXS", GetSystemName(system)));
2179 return 0;
2180 }
2181
57f50b3c 2182 // check connection, in case connect
9d733021 2183 if (!Connect(system))
eba76848 2184 {
9d733021 2185 Log(detector, Form("GetFile - Couldn't connect to %s FXS database", GetSystemName(system)));
339adafa 2186 fFXSError = system;
57f50b3c 2187 return 0;
2188 }
2189
2190 // Query preparation
9d733021 2191 TString sourceName(source);
d386d623 2192 Int_t nFields = 3;
2193 TString sqlQueryStart = Form("select filePath,size,fileChecksum from %s where",
2194 fConfig->GetFXSdbTable(system));
2195 TString whereClause = Form("run=%d and detector=\"%s\" and fileId=\"%s\"",
2196 GetCurrentRun(), detector, id);
2197
efec19bd 2198 if (system == kDAQ || system == kDQM)
9d733021 2199 {
d386d623 2200 whereClause += Form(" and DAQsource=\"%s\"", source);
57f50b3c 2201 }
9d733021 2202 else if (system == kDCS)
eba76848 2203 {
9d733021 2204 sourceName="none";
57f50b3c 2205 }
9d733021 2206 else if (system == kHLT)
9e080f92 2207 {
d386d623 2208 whereClause += Form(" and DDLnumbers=\"%s\"", source);
9e080f92 2209 }
2210
9e080f92 2211 TString sqlQuery = Form("%s %s", sqlQueryStart.Data(), whereClause.Data());
2212
2213 AliDebug(2, Form("SQL query: \n%s",sqlQuery.Data()));
2214
2215 // Query execution
2216 TSQLResult* aResult = 0;
9d733021 2217 aResult = dynamic_cast<TSQLResult*> (fServer[system]->Query(sqlQuery));
9e080f92 2218 if (!aResult) {
8da81210 2219 Log(detector, Form("GetFile - Can't execute SQL query to %s database for: id = %s, source = %s",
9d733021 2220 GetSystemName(system), id, sourceName.Data()));
339adafa 2221 fFXSError = system;
9e080f92 2222 return 0;
2223 }
2224
8da81210 2225 if (aResult->GetRowCount() == 0)
9e080f92 2226 {
2227 Log(detector,
8da81210 2228 Form("GetFile - No entry in %s FXS db for: id = %s, source = %s",
9d733021 2229 GetSystemName(system), id, sourceName.Data()));
9e080f92 2230 delete aResult;
2231 return 0;
2232 }
2bb7b766 2233
9e080f92 2234 if (aResult->GetRowCount() > 1) {
2235 Log(detector,
8da81210 2236 Form("GetFile - More than one entry in %s FXS db for: id = %s, source = %s",
9d733021 2237 GetSystemName(system), id, sourceName.Data()));
339adafa 2238 fFXSError = system;
9e080f92 2239 delete aResult;
2240 return 0;
2241 }
2242
9d733021 2243 if (aResult->GetFieldCount() != nFields) {
9e080f92 2244 Log(detector,
9d733021 2245 Form("GetFileName - Wrong field count in %s FXS db for: id = %s, source = %s",
2246 GetSystemName(system), id, sourceName.Data()));
339adafa 2247 fFXSError = system;
9e080f92 2248 delete aResult;
2249 return 0;
2250 }
2251
2252 TSQLRow* aRow = dynamic_cast<TSQLRow*> (aResult->Next());
2253
2254 if (!aRow){
8da81210 2255 Log(detector, Form("GetFile - Empty set result in %s FXS db from query: id = %s, source = %s",
9d733021 2256 GetSystemName(system), id, sourceName.Data()));
339adafa 2257 fFXSError = system;
9e080f92 2258 delete aResult;
2259 return 0;
2260 }
2261
2262 TString filePath(aRow->GetField(0), aRow->GetFieldLength(0));
2263 TString fileSize(aRow->GetField(1), aRow->GetFieldLength(1));
d386d623 2264 TString fileChecksum(aRow->GetField(2), aRow->GetFieldLength(2));
9e080f92 2265
2266 delete aResult;
2267 delete aRow;
2268
d386d623 2269 AliDebug(2, Form("filePath = %s; size = %s, fileChecksum = %s",
2270 filePath.Data(), fileSize.Data(), fileChecksum.Data()));
9e080f92 2271
9e080f92 2272 // retrieved file is renamed to make it unique
3ebbf3c4 2273 Int_t dir_lev1 = GetCurrentRun()/10000;
2274 TString localFileName = Form("%s/%d/%d/%s_process/%s_%s_%d_%s_%s.shuttle",
2275 GetShuttleTempDir(), dir_lev1, GetCurrentRun(), detector,
d524ade6 2276 GetSystemName(system), detector, GetCurrentRun(),
2277 id, sourceName.Data());
3ebbf3c4 2278 Log("SHUTTLE",Form("file from FXS = %s",localFileName.Data()));
9d733021 2279
9e080f92 2280
9d733021 2281 // file retrieval from FXS
4b95672b 2282 UInt_t nRetries = 0;
2283 UInt_t maxRetries = 3;
2284 Bool_t result = kFALSE;
2285
2286 // copy!! if successful TSystem::Exec returns 0
8da81210 2287 while (nRetries++ < maxRetries) {
4b95672b 2288 AliDebug(2, Form("Trying to copy file. Retry # %d", nRetries));
2289 result = RetrieveFile(system, filePath.Data(), localFileName.Data());
8da81210 2290 if (!result)
4b95672b 2291 {
8da81210 2292 Log(detector, Form("GetFile - Copy of file %s from %s FXS failed",
9d733021 2293 filePath.Data(), GetSystemName(system)));
4b95672b 2294 continue;
4f0749a8 2295 }
9e080f92 2296
c98417a1 2297 if (fileSize.Length()>0)
2298 {
2299 // compare filesize of local file with the one stored in the FXS DB
926cbc0e 2300 Long_t size = -1;
2301 Int_t sizeComp = gSystem->GetPathInfo(localFileName.Data(), 0, &size, 0, 0);
c98417a1 2302
926cbc0e 2303 if (sizeComp != 0 || size != fileSize.Atoi())
c98417a1 2304 {
8da81210 2305 Log(detector, Form("GetFile - size of file %s does not match with local copy!",
c98417a1 2306 filePath.Data()));
2307 result = kFALSE;
2308 continue;
2309 }
2310
2311 } else {
2312 Log(fCurrentDetector, Form("GetFile - size of file %s not set in %s database, skipping comparison",
2313 filePath.Data(), GetSystemName(system)));
2314 }
2315
d386d623 2316 if (fileChecksum.Length()>0)
4b95672b 2317 {
2318 // compare md5sum of local file with the one stored in the FXS DB
95d4aaef 2319 if(fileChecksum.Contains(' ')) fileChecksum.Resize(fileChecksum.First(' '));
339adafa 2320 Int_t md5Comp = gSystem->Exec(Form("md5sum %s |grep %s > /dev/null 2> /dev/null",
d524ade6 2321 localFileName.Data(), fileChecksum.Data()));
9e080f92 2322
4b95672b 2323 if (md5Comp != 0)
2324 {
8da81210 2325 Log(detector, Form("GetFile - md5sum of file %s does not match with local copy!",
4b95672b 2326 filePath.Data()));
2327 result = kFALSE;
2328 continue;
2329 }
d386d623 2330 } else {
2331 Log(fCurrentDetector, Form("GetFile - md5sum of file %s not set in %s database, skipping comparison",
2332 filePath.Data(), GetSystemName(system)));
9d733021 2333 }
4b95672b 2334 if (result) break;
9e080f92 2335 }
2336
8da81210 2337 if (!result)
2338 {
339adafa 2339 fFXSError = system;
8da81210 2340 return 0;
2341 }
4b95672b 2342
9d733021 2343 fFXSCalled[system]=kTRUE;
2344 TObjString *fileParams = new TObjString(Form("%s#!?!#%s", id, sourceName.Data()));
2345 fFXSlist[system].Add(fileParams);
9e080f92 2346
675f64cd 2347 static TString staticLocalFileName;
2348 staticLocalFileName.Form("%s", localFileName.Data());
2349
c88ad5db 2350 Log(fCurrentDetector, Form("GetFile - Retrieved file with id %s and "
2351 "source %s from %s to %s", id, source,
d524ade6 2352 GetSystemName(system), localFileName.Data()));
675f64cd 2353
d524ade6 2354 return staticLocalFileName.Data();
2bb7b766 2355}
2356
2357//______________________________________________________________________________________________
9d733021 2358Bool_t AliShuttle::RetrieveFile(UInt_t system, const char* fxsFileName, const char* localFileName)
9e080f92 2359{
9827400b 2360 //
2361 // Copies file from FXS to local Shuttle machine
2362 //
2bb7b766 2363
9e080f92 2364 // check temp directory: trying to cd to temp; if it does not exist, create it
d524ade6 2365 AliDebug(2, Form("Copy file %s from %s FXS into %s",
2366 GetSystemName(system), fxsFileName, localFileName));
2367
2368 TString tmpDir(localFileName);
2369
2370 tmpDir = tmpDir(0,tmpDir.Last('/'));
9e080f92 2371
d524ade6 2372 Int_t noDir = gSystem->GetPathInfo(tmpDir.Data(), 0, (Long64_t*) 0, 0, 0);
2373 if (noDir) // temp dir does not exists!
2374 {
2375 if (gSystem->mkdir(tmpDir.Data(), 1))
2376 {
2377 Log(fCurrentDetector.Data(), "RetrieveFile - could not make temp directory!!");
9e080f92 2378 return kFALSE;
2379 }
9e080f92 2380 }
2381
339adafa 2382 TString command = Form("scp -oPort=%d -2 %s@%s:%s/%s %s",
9d733021 2383 fConfig->GetFXSPort(system),
2384 fConfig->GetFXSUser(system),
2385 fConfig->GetFXSHost(system),
339adafa 2386 fConfig->GetFXSBaseFolder(system),
9d733021 2387 fxsFileName,
9e080f92 2388 localFileName);
2389
2390 AliDebug(2, Form("%s",command.Data()));
2391
4b95672b 2392 Bool_t result = (gSystem->Exec(command.Data()) == 0);
9e080f92 2393
4b95672b 2394 return result;
9e080f92 2395}
2396
2397//______________________________________________________________________________________________
9d733021 2398TList* AliShuttle::GetFileSources(Int_t system, const char* detector, const char* id)
2399{
9827400b 2400 //
2401 // Get sources producing the condition file Id from file exchange servers
4a33bdd9 2402 // if id is NULL all sources are returned (distinct)
9827400b 2403 //
1bcd28db 2404
8884d71e 2405 if (id)
2406 {
2407 Log(detector, Form("GetFileSources - Querying %s FXS for files with id %s produced by %s", GetSystemName(system), id, detector));
2408 } else {
2409 Log(detector, Form("GetFileSources - Querying %s FXS for files produced by %s", GetSystemName(system), detector));
2410 }
9827400b 2411
2412 // check if test mode should simulate a FXS error
2413 if (fTestMode & kErrorFXSSources)
2414 {
2415 Log(detector, Form("GetFileSources - In TESTMODE - Simulating error while connecting to %s FXS", GetSystemName(system)));
2416 return 0;
2417 }
2418
9d733021 2419 if (system == kDCS)
2420 {
c88ad5db 2421 Log(detector, "GetFileSources - WARNING: DCS system has only one source of data!");
6297b37d 2422 TList *list = new TList();
2423 list->SetOwner(1);
2424 list->Add(new TObjString(" "));
2425 return list;
9d733021 2426 }
9e080f92 2427
2428 // check connection, in case connect
9d733021 2429 if (!Connect(system))
2430 {
4a33bdd9 2431 Log(detector, Form("GetFileSources - Couldn't connect to %s FXS database", GetSystemName(system)));
339adafa 2432 fFXSError = system;
9d733021 2433 return NULL;
9e080f92 2434 }
2435
b827f957 2436 TString sourceName = "";
efec19bd 2437 if (system == kDAQ || system == kDQM)
9d733021 2438 {
2439 sourceName = "DAQsource";
2440 } else if (system == kHLT)
2441 {
2442 sourceName = "DDLnumbers";
2443 }
2444
4a33bdd9 2445 TString sqlQueryStart = Form("select distinct %s from %s where", sourceName.Data(), fConfig->GetFXSdbTable(system));
2446 TString whereClause = Form("run=%d and detector=\"%s\"",
2447 GetCurrentRun(), detector);
2448 if (id)
2449 whereClause += Form(" and fileId=\"%s\"", id);
9e080f92 2450 TString sqlQuery = Form("%s %s", sqlQueryStart.Data(), whereClause.Data());
2451
2452 AliDebug(2, Form("SQL query: \n%s",sqlQuery.Data()));
2453
2454 // Query execution
2455 TSQLResult* aResult;
9d733021 2456 aResult = fServer[system]->Query(sqlQuery);
9e080f92 2457 if (!aResult) {
9d733021 2458 Log(detector, Form("GetFileSources - Can't execute SQL query to %s database for id: %s",
2459 GetSystemName(system), id));
339adafa 2460 fFXSError = system;
9e080f92 2461 return 0;
2462 }
2463
86aa42c3 2464 TList *list = new TList();
2465 list->SetOwner(1);
2466
9d733021 2467 if (aResult->GetRowCount() == 0)
2468 {
9e080f92 2469 Log(detector,
9d733021 2470 Form("GetFileSources - No entry in %s FXS table for id: %s", GetSystemName(system), id));
9e080f92 2471 delete aResult;
86aa42c3 2472 return list;
9e080f92 2473 }
2474
1bcd28db 2475 Log(detector, Form("GetFileSources - Found %d sources", aResult->GetRowCount()));
9e080f92 2476
1bcd28db 2477 TSQLRow* aRow;
9d733021 2478 while ((aRow = aResult->Next()))
2479 {
9e080f92 2480
9d733021 2481 TString source(aRow->GetField(0), aRow->GetFieldLength(0));
2482 AliDebug(2, Form("%s = %s", sourceName.Data(), source.Data()));
2483 list->Add(new TObjString(source));
9e080f92 2484 delete aRow;
2485 }
9d733021 2486
9e080f92 2487 delete aResult;
2488
2489 return list;
2bb7b766 2490}
2491
4a33bdd9 2492//______________________________________________________________________________________________
2493TList* AliShuttle::GetFileIDs(Int_t system, const char* detector, const char* source)
2494{
2495 //
2496 // Get all ids of condition files produced by a given source from file exchange servers
2497 //
2498
1bcd28db 2499 Log(detector, Form("GetFileIDs - Retrieving ids with source %s with %s", source, GetSystemName(system)));
2500
4a33bdd9 2501 // check if test mode should simulate a FXS error
2502 if (fTestMode & kErrorFXSSources)
2503 {
2504 Log(detector, Form("GetFileIDs - In TESTMODE - Simulating error while connecting to %s FXS", GetSystemName(system)));
2505 return 0;
2506 }
2507
2508 // check connection, in case connect
2509 if (!Connect(system))
2510 {
2511 Log(detector, Form("GetFileIDs - Couldn't connect to %s FXS database", GetSystemName(system)));
2512 return NULL;
2513 }
2514
b827f957 2515 TString sourceName = "";
4a33bdd9 2516 if (system == kDAQ)
2517 {
2518 sourceName = "DAQsource";
2519 } else if (system == kHLT)
2520 {
2521 sourceName = "DDLnumbers";
2522 }
2523
2524 TString sqlQueryStart = Form("select fileId from %s where", fConfig->GetFXSdbTable(system));
2525 TString whereClause = Form("run=%d and detector=\"%s\"",
2526 GetCurrentRun(), detector);
2527 if (sourceName.Length() > 0 && source)
2528 whereClause += Form(" and %s=\"%s\"", sourceName.Data(), source);
2529 TString sqlQuery = Form("%s %s", sqlQueryStart.Data(), whereClause.Data());
2530
2531 AliDebug(2, Form("SQL query: \n%s",sqlQuery.Data()));
2532
2533 // Query execution
2534 TSQLResult* aResult;
2535 aResult = fServer[system]->Query(sqlQuery);
2536 if (!aResult) {
2537 Log(detector, Form("GetFileIDs - Can't execute SQL query to %s database for source: %s",
2538 GetSystemName(system), source));
2539 return 0;
2540 }
2541
2542 TList *list = new TList();
2543 list->SetOwner(1);
2544
2545 if (aResult->GetRowCount() == 0)
2546 {
2547 Log(detector,
2548 Form("GetFileIDs - No entry in %s FXS table for source: %s", GetSystemName(system), source));
2549 delete aResult;
2550 return list;
2551 }
2552
1bcd28db 2553 Log(detector, Form("GetFileIDs - Found %d ids", aResult->GetRowCount()));
2554
4a33bdd9 2555 TSQLRow* aRow;
2556
2557 while ((aRow = aResult->Next()))
2558 {
2559
2560 TString id(aRow->GetField(0), aRow->GetFieldLength(0));
2561 AliDebug(2, Form("fileId = %s", id.Data()));
2562 list->Add(new TObjString(id));
2563 delete aRow;
2564 }
2565
2566 delete aResult;
2567
2568 return list;
2569}
2570
2bb7b766 2571//______________________________________________________________________________________________
9d733021 2572Bool_t AliShuttle::Connect(Int_t system)
2bb7b766 2573{
9827400b 2574 // Connect to MySQL Server of the system's FXS MySQL databases
2575 // DAQ Logbook, Shuttle Logbook and DAQ FXS db are on the same host
2576 //
57f50b3c 2577
9d733021 2578 // check connection: if already connected return
dd84c76d 2579
3a4ddf0e 2580 if(fServer[system] && fServer[system]->IsConnected()) {
dd84c76d 2581 // ping the server
2582 if (fServer[system]->PingVerify()==kTRUE){ // connection is still alive
2583 return kTRUE;
2584 }
2585 else{
2586 AliWarning(Form("Connection got lost to FXS database for %s. Closing and reconnecting.",
2587 AliShuttleInterface::GetSystemName(system)));
2588 fServer[system]->Close();
2589 delete fServer[system];
2590 fServer[system] = 0x0;
2591 }
3a4ddf0e 2592 }
57f50b3c 2593
9d733021 2594 TString dbHost, dbUser, dbPass, dbName;
57f50b3c 2595
efec19bd 2596 if (system < 4) // FXS db servers
9d733021 2597 {
2598 dbHost = Form("mysql://%s:%d", fConfig->GetFXSdbHost(system), fConfig->GetFXSdbPort(system));
2599 dbUser = fConfig->GetFXSdbUser(system);
2600 dbPass = fConfig->GetFXSdbPass(system);
2601 dbName = fConfig->GetFXSdbName(system);
2602 } else { // Run & Shuttle logbook servers
2603 // TODO Will the Shuttle logbook server be the same as the Run logbook server ???
2604 dbHost = Form("mysql://%s:%d", fConfig->GetDAQlbHost(), fConfig->GetDAQlbPort());
2605 dbUser = fConfig->GetDAQlbUser();
2606 dbPass = fConfig->GetDAQlbPass();
2607 dbName = fConfig->GetDAQlbDB();
2608 }
57f50b3c 2609
9d733021 2610 fServer[system] = TSQLServer::Connect(dbHost.Data(), dbUser.Data(), dbPass.Data());
efec19bd 2611 if (!fServer[system] || !fServer[system]->IsConnected()) {
2612 if(system < 4)
9d733021 2613 {
2614 AliError(Form("Can't establish connection to FXS database for %s",
2615 AliShuttleInterface::GetSystemName(system)));
2616 } else {
2617 AliError("Can't establish connection to Run logbook.");
57f50b3c 2618 }
9d733021 2619 if(fServer[system]) delete fServer[system];
2620 return kFALSE;
2bb7b766 2621 }
57f50b3c 2622
9d733021 2623 // Get tables
2624 TSQLResult* aResult=0;
2625 switch(system){
2626 case kDAQ:
2627 aResult = fServer[kDAQ]->GetTables(dbName.Data());
2628 break;
2629 case kDCS:
2630 aResult = fServer[kDCS]->GetTables(dbName.Data());
2631 break;
2632 case kHLT:
2633 aResult = fServer[kHLT]->GetTables(dbName.Data());
2634 break;
efec19bd 2635 case kDQM:
2636 aResult = fServer[kDQM]->GetTables(dbName.Data());
2637 break;
9d733021 2638 default:
efec19bd 2639 aResult = fServer[4]->GetTables(dbName.Data());
9d733021 2640 break;
2641 }
2642
2643 delete aResult;
2bb7b766 2644 return kTRUE;
2645}
57f50b3c 2646
9e080f92 2647//______________________________________________________________________________________________
9d733021 2648Bool_t AliShuttle::UpdateTable()
9e080f92 2649{
9827400b 2650 //
2651 // Update FXS table filling time_processed field in all rows corresponding to current run and detector
2652 //
9e080f92 2653
9d733021 2654 Bool_t result = kTRUE;
9e080f92 2655
6e25f828 2656 for (UInt_t system=0; system<4; system++)
9d733021 2657 {
2658 if(!fFXSCalled[system]) continue;
9e080f92 2659
9d733021 2660 // check connection, in case connect
2661 if (!Connect(system))
2662 {
2663 Log(fCurrentDetector, Form("UpdateTable - Couldn't connect to %s FXS database", GetSystemName(system)));
2664 result = kFALSE;
2665 continue;
9e080f92 2666 }
9e080f92 2667
9d733021 2668 TTimeStamp now; // now
2669
2670 // Loop on FXS list entries
2671 TIter iter(&fFXSlist[system]);
2672 TObjString *aFXSentry=0;
2673 while ((aFXSentry = dynamic_cast<TObjString*> (iter.Next())))
2674 {
2675 TString aFXSentrystr = aFXSentry->String();
2676 TObjArray *aFXSarray = aFXSentrystr.Tokenize("#!?!#");
2677 if (!aFXSarray || aFXSarray->GetEntries() != 2 )
2678 {
2679 Log(fCurrentDetector, Form("UpdateTable - error updating %s FXS entry. Check string: <%s>",
2680 GetSystemName(system), aFXSentrystr.Data()));
2681 if(aFXSarray) delete aFXSarray;
2682 result = kFALSE;
2683 continue;
2684 }
2685 const char* fileId = ((TObjString*) aFXSarray->At(0))->GetName();
2686 const char* source = ((TObjString*) aFXSarray->At(1))->GetName();
2687
2688 TString whereClause;
efec19bd 2689 if (system == kDAQ || system == kDQM)
9d733021 2690 {
2691 whereClause = Form("where run=%d and detector=\"%s\" and fileId=\"%s\" and DAQsource=\"%s\";",
2692 GetCurrentRun(), fCurrentDetector.Data(), fileId, source);
2693 }
2694 else if (system == kDCS)
2695 {
2696 whereClause = Form("where run=%d and detector=\"%s\" and fileId=\"%s\";",
2697 GetCurrentRun(), fCurrentDetector.Data(), fileId);
2698 }
2699 else if (system == kHLT)
2700 {
2701 whereClause = Form("where run=%d and detector=\"%s\" and fileId=\"%s\" and DDLnumbers=\"%s\";",
2702 GetCurrentRun(), fCurrentDetector.Data(), fileId, source);
2703 }
2704
2705 delete aFXSarray;
9e080f92 2706
0a0b087a 2707 TString sqlQuery = Form("update %s set time_processed=%ld %s", fConfig->GetFXSdbTable(system),
2708 (ULong_t)now.GetSec(), whereClause.Data());
9e080f92 2709
9d733021 2710 AliDebug(2, Form("SQL query: \n%s",sqlQuery.Data()));
9e080f92 2711
9d733021 2712 // Query execution
2713 TSQLResult* aResult;
2714 aResult = dynamic_cast<TSQLResult*> (fServer[system]->Query(sqlQuery));
2715 if (!aResult)
2716 {
2717 Log(fCurrentDetector, Form("UpdateTable - %s db: can't execute SQL query <%s>",
2718 GetSystemName(system), sqlQuery.Data()));
2719 result = kFALSE;
2720 continue;
2721 }
2722 delete aResult;
9e080f92 2723 }
9e080f92 2724 }
2725
9d733021 2726 return result;
9e080f92 2727}
57f50b3c 2728
bd23d48b 2729//_______________________________________________________________________________
2730Bool_t AliShuttle::UpdateTableSkippedCase(const char* detector)
2731{
2732 //
2733 // Update FXS table filling time_processed field in all rows corresponding to current run and detector
2734 // if detector = "ALL" update all detectors
2735 //
2736
2737 Bool_t result = kTRUE;
2738
7a782903 2739 TString detName(detector);
2740
6e25f828 2741 for (UInt_t system=0; system<4; system++)
bd23d48b 2742 {
2743
2744 // check connection, in case connect
2745 if (!Connect(system))
2746 {
2747 Log(fCurrentDetector, Form("UpdateTableSkippedCase - Couldn't connect to %s FXS database", GetSystemName(system)));
2748 result = kFALSE;
2749 continue;
2750 }
2751
2752 TTimeStamp now; // now
2753
2754 // Loop on FXS list entries
2755 TIter iter(&fFXSlist[system]);
2756
2757 TString whereClause;
7a782903 2758 if (detName == "ALL") whereClause = Form("where run=%d and time_processed IS NULL;",GetCurrentRun());
bd23d48b 2759 else whereClause = Form("where run=%d and detector=\"%s\" and time_processed IS NULL;",GetCurrentRun(), detector);
2760
4be2f262 2761 //Log("SHUTTLE",Form(" whereClause = %s ",whereClause.Data()));
bd23d48b 2762
0a0b087a 2763 TString sqlQuery = Form("update %s set time_processed=%ld %s", fConfig->GetFXSdbTable(system),
2764 (ULong_t)now.GetSec(), whereClause.Data());
bd23d48b 2765
2766 AliDebug(2, Form("SQL query: \n%s",sqlQuery.Data()));
2767
2768 // Query execution
2769 TSQLResult* aResult;
2770 aResult = dynamic_cast<TSQLResult*> (fServer[system]->Query(sqlQuery));
2771 if (!aResult)
2772 {
2773 Log("SHUTTLE", Form("UpdateTableSkippedCase - %s db: can't execute SQL query <%s>",
2774 GetSystemName(system), sqlQuery.Data()));
2775 result = kFALSE;
2776 continue;
2777 }
2778 delete aResult;
2779
2780 }
2781
2782 return result;
2783}
3301427a 2784//______________________________________________________________________________________________
2785Bool_t AliShuttle::UpdateTableFailCase()
2786{
9827400b 2787 // Update FXS table filling time_processed field in all rows corresponding to current run and detector
2788 // this is called in case the preprocessor is declared failed for the current run, because
2789 // the fields are updated only in case of success
3301427a 2790
2791 Bool_t result = kTRUE;
2792
6e25f828 2793 for (UInt_t system=0; system<4; system++)
3301427a 2794 {
2795 // check connection, in case connect
2796 if (!Connect(system))
2797 {
2798 Log(fCurrentDetector, Form("UpdateTableFailCase - Couldn't connect to %s FXS database",
2799 GetSystemName(system)));
2800 result = kFALSE;
2801 continue;
2802 }
2803
2804 TTimeStamp now; // now
2805
2806 // Loop on FXS list entries
2807
2808 TString whereClause = Form("where run=%d and detector=\"%s\";",
2809 GetCurrentRun(), fCurrentDetector.Data());
2810
2811
0a0b087a 2812 TString sqlQuery = Form("update %s set time_processed=%ld %s", fConfig->GetFXSdbTable(system),
2813 (ULong_t)now.GetSec(), whereClause.Data());
3301427a 2814
2815 AliDebug(2, Form("SQL query: \n%s",sqlQuery.Data()));
2816
2817 // Query execution
2818 TSQLResult* aResult;
2819 aResult = dynamic_cast<TSQLResult*> (fServer[system]->Query(sqlQuery));
2820 if (!aResult)
2821 {
2822 Log(fCurrentDetector, Form("UpdateTableFailCase - %s db: can't execute SQL query <%s>",
2823 GetSystemName(system), sqlQuery.Data()));
2824 result = kFALSE;
2825 continue;
2826 }
2827 delete aResult;
2828 }
2829
2830 return result;
2831}
2832
2bb7b766 2833//______________________________________________________________________________________________
2834Bool_t AliShuttle::UpdateShuttleLogbook(const char* detector, const char* status)
2835{
e7f62f16 2836 //
2837 // Update Shuttle logbook filling detector or shuttle_done column
2838 // ex. of usage: UpdateShuttleLogbook("PHOS", "DONE") or UpdateShuttleLogbook("shuttle_done")
2839 //
57f50b3c 2840
2bb7b766 2841 // check connection, in case connect
efec19bd 2842 if(!Connect(4)){
2bb7b766 2843 Log("SHUTTLE", "UpdateShuttleLogbook - Couldn't connect to DAQ Logbook.");
2844 return kFALSE;
57f50b3c 2845 }
2846
2bb7b766 2847 TString detName(detector);
2848 TString setClause;
8e828d39 2849 if (detName == "shuttle_done" || detName == "shuttle_skipped")
e7f62f16 2850 {
2bb7b766 2851 setClause = "set shuttle_done=1";
8e828d39 2852
ee6f7523 2853 if (detName == "shuttle_done")
b0e53b15 2854 {
8e828d39 2855 if (TouchFile() != kTRUE)
2156c755 2856 {
2857 SendMLRunInfo("Pending");
503ff24f 2858 return kFALSE;
2156c755 2859 }
8e828d39 2860
2861 SendMLRunInfo("Done");
b0e53b15 2862 }
8e828d39 2863 else
2864 SendMLRunInfo("Skipped");
2865 }
2866 else {
2bb7b766 2867 TString statusStr(status);
2868 if(statusStr.Contains("done", TString::kIgnoreCase) ||
2869 statusStr.Contains("failed", TString::kIgnoreCase)){
eba76848 2870 setClause = Form("set %s=\"%s\"", detector, status);
2bb7b766 2871 } else {
2872 Log("SHUTTLE",
2873 Form("UpdateShuttleLogbook - Invalid status <%s> for detector %s",
2874 status, detector));
2875 return kFALSE;
2876 }
2877 }
57f50b3c 2878
2bb7b766 2879 TString whereClause = Form("where run=%d", GetCurrentRun());
2880
441b0e9c 2881 TString sqlQuery = Form("update %s %s %s",
2882 fConfig->GetShuttlelbTable(), setClause.Data(), whereClause.Data());
57f50b3c 2883
2bb7b766 2884 AliDebug(2, Form("SQL query: \n%s",sqlQuery.Data()));
2885
2886 // Query execution
2887 TSQLResult* aResult;
efec19bd 2888 aResult = dynamic_cast<TSQLResult*> (fServer[4]->Query(sqlQuery));
2bb7b766 2889 if (!aResult) {
2890 Log("SHUTTLE", Form("UpdateShuttleLogbook - Can't execute query <%s>", sqlQuery.Data()));
2891 return kFALSE;
57f50b3c 2892 }
2bb7b766 2893 delete aResult;
57f50b3c 2894
2895 return kTRUE;
2896}
2897
2898//______________________________________________________________________________________________
2bb7b766 2899Int_t AliShuttle::GetCurrentRun() const
2900{
9827400b 2901 //
2902 // Get current run from logbook entry
2903 //
57f50b3c 2904
2bb7b766 2905 return fLogbookEntry ? fLogbookEntry->GetRun() : -1;
57f50b3c 2906}
2907
2908//______________________________________________________________________________________________
2bb7b766 2909UInt_t AliShuttle::GetCurrentStartTime() const
2910{
9827400b 2911 //
2912 // get current start time
2913 //
57f50b3c 2914
2bb7b766 2915 return fLogbookEntry ? fLogbookEntry->GetStartTime() : 0;
57f50b3c 2916}
2917
2918//______________________________________________________________________________________________
2bb7b766 2919UInt_t AliShuttle::GetCurrentEndTime() const
2920{
9827400b 2921 //
2922 // get current end time from logbook entry
2923 //
57f50b3c 2924
2bb7b766 2925 return fLogbookEntry ? fLogbookEntry->GetEndTime() : 0;
57f50b3c 2926}
675f64cd 2927//______________________________________________________________________________________________
2928UInt_t AliShuttle::GetCurrentYear() const
2929{
2930 //
2931 // Get current year from logbook entry
2932 //
2933
2934 if (!fLogbookEntry) return 0;
2935
2936 TTimeStamp startTime(GetCurrentStartTime());
2937 TString year = Form("%d",startTime.GetDate());
2938 year = year(0,4);
2939
2940 return year.Atoi();
2941}
2942
2943//______________________________________________________________________________________________
2944const char* AliShuttle::GetLHCPeriod() const
2945{
2946 //
2947 // Get current LHC period from logbook entry
2948 //
2949
2950 if (!fLogbookEntry) return 0;
2951
2952 return fLogbookEntry->GetRunParameter("LHCperiod");
2953}
2954
b948db8d 2955//______________________________________________________________________________________________
6a150f83 2956void AliShuttle::Log(const char* detector, const char* message, UInt_t level)
b948db8d 2957{
9827400b 2958 //
2959 // Fill log string with a message
2960 //
7d4cf768 2961
3ebbf3c4 2962 TString logRunDir = GetShuttleLogDir();
2963 if (GetCurrentRun() >=0) {
2964 Int_t logDir_lev1 = GetCurrentRun()/10000;
2965 logRunDir += Form("/%d/%d", logDir_lev1, GetCurrentRun());
2966 }
7d4cf768 2967 void* dir = gSystem->OpenDirectory(logRunDir.Data());
84090f85 2968 if (dir == NULL) {
7d4cf768 2969 if (gSystem->mkdir(logRunDir.Data(), kTRUE)) {
36c99a6a 2970 AliError(Form("Can't open directory <%s>", GetShuttleLogDir()));
84090f85 2971 return;
2972 }
b948db8d 2973
84090f85 2974 } else {
2975 gSystem->FreeDirectory(dir);
2976 }
b948db8d 2977
0b025a52 2978 TString toLog = Form("%s UTC (%d): %s - ", TTimeStamp(time(0)).AsString("s"), getpid(), detector);
e7f62f16 2979 if (GetCurrentRun() >= 0)
2980 toLog += Form("run %d - ", GetCurrentRun());
2bb7b766 2981 toLog += Form("%s", message);
2982
6a150f83 2983 AliLog::Message(level, toLog, MODULENAME(), ClassName(), FUNCTIONNAME(), __FILE__, __LINE__);
ffa29e93 2984
2985 // if we redirect the log output already to the file, leave here
2986 if (fOutputRedirected && strcmp(detector, "SHUTTLE") != 0)
2987 return;
b948db8d 2988
ffa29e93 2989 TString fileName = GetLogFileName(detector);
e7f62f16 2990
84090f85 2991 gSystem->ExpandPathName(fileName);
2992
2993 ofstream logFile;
2994 logFile.open(fileName, ofstream::out | ofstream::app);
2995
2996 if (!logFile.is_open()) {
2997 AliError(Form("Could not open file %s", fileName.Data()));
2998 return;
2999 }
7bfb2090 3000
84090f85 3001 logFile << toLog.Data() << "\n";
b948db8d 3002
84090f85 3003 logFile.close();
b948db8d 3004}
2bb7b766 3005
ffa29e93 3006//______________________________________________________________________________________________
3007TString AliShuttle::GetLogFileName(const char* detector) const
3008{
3009 //
3010 // returns the name of the log file for a given sub detector
3011 //
3012
3013 TString fileName;
3014
3015 if (GetCurrentRun() >= 0)
7d4cf768 3016 {
3ebbf3c4 3017 Int_t logDir_lev1 = GetCurrentRun()/10000;
3018 fileName.Form("%s/%d/%d/%s.log", GetShuttleLogDir(), logDir_lev1, GetCurrentRun(),
3019 detector);
7d4cf768 3020 } else {
ffa29e93 3021 fileName.Form("%s/%s.log", GetShuttleLogDir(), detector);
7d4cf768 3022 }
ffa29e93 3023
3024 return fileName;
3025}
3026
ee6f7523 3027//______________________________________________________________________________________________
3028void AliShuttle::SendAlive()
3029{
3030 // sends alive message to ML
3031
3032 TMonaLisaText mlStatus("SHUTTLE_status", "Alive");
3033
3034 TList mlList;
3035 mlList.Add(&mlStatus);
3036
3037 fMonaLisa->SendParameters(&mlList, "__PROCESSINGINFO__");
3038}
3039
2bb7b766 3040//______________________________________________________________________________________________
3041Bool_t AliShuttle::Collect(Int_t run)
3042{
9827400b 3043 //
3044 // Collects conditions data for all UNPROCESSED run written to DAQ LogBook in case of run = -1 (default)
3045 // If a dedicated run is given this run is processed
3046 //
3047 // In operational mode, this is the Shuttle function triggered by the EOR signal.
3048 //
2bb7b766 3049
eba76848 3050 if (run == -1)
3051 Log("SHUTTLE","Collect - Shuttle called. Collecting conditions data for unprocessed runs");
3052 else
3053 Log("SHUTTLE", Form("Collect - Shuttle called. Collecting conditions data for run %d", run));
cb343cfd 3054
3055 SetLastAction("Starting");
2bb7b766 3056
ee6f7523 3057 // create ML instance
3058 if (!fMonaLisa)
3059 fMonaLisa = new TMonaLisaWriter(fConfig->GetMonitorHost(), fConfig->GetMonitorTable());
3060
fbc112e3 3061 CountOpenRuns();
ee6f7523 3062
2bb7b766 3063 TString whereClause("where shuttle_done=0");
eba76848 3064 if (run != -1)
3065 whereClause += Form(" and run=%d", run);
2bb7b766 3066
3067 TObjArray shuttleLogbookEntries;
be48e3ea 3068 if (!QueryShuttleLogbook(whereClause, shuttleLogbookEntries))
3069 {
cb343cfd 3070 Log("SHUTTLE", "Collect - Can't retrieve entries from Shuttle logbook");
2bb7b766 3071 return kFALSE;
3072 }
3073
9e080f92 3074 if (shuttleLogbookEntries.GetEntries() == 0)
3075 {
3076 if (run == -1)
3077 Log("SHUTTLE","Collect - Found no UNPROCESSED runs in Shuttle logbook");
3078 else
3079 Log("SHUTTLE", Form("Collect - Run %d is already DONE "
3080 "or it does not exist in Shuttle logbook", run));
3081 return kTRUE;
3082 }
3083
be48e3ea 3084 for (UInt_t iDet=0; iDet<NDetectors(); iDet++)
3085 fFirstUnprocessed[iDet] = kTRUE;
3086
fc5a4708 3087 if (run != -1)
be48e3ea 3088 {
3089 // query Shuttle logbook for earlier runs, check if some detectors are unprocessed,
3090 // flag them into fFirstUnprocessed array
e3ae8d33 3091 TString whereClauseBis(Form("where shuttle_done=0 and run < %d", run));
be48e3ea 3092 TObjArray tmpLogbookEntries;
e3ae8d33 3093 if (!QueryShuttleLogbook(whereClauseBis, tmpLogbookEntries))
be48e3ea 3094 {
3095 Log("SHUTTLE", "Collect - Can't retrieve entries from Shuttle logbook");
3096 return kFALSE;
3097 }
3098
3099 TIter iter(&tmpLogbookEntries);
3100 AliShuttleLogbookEntry* anEntry = 0;
3101 while ((anEntry = dynamic_cast<AliShuttleLogbookEntry*> (iter.Next())))
3102 {
3103 for (UInt_t iDet=0; iDet<NDetectors(); iDet++)
3104 {
3105 if (anEntry->GetDetectorStatus(iDet) == AliShuttleLogbookEntry::kUnprocessed)
3106 {
3107 AliDebug(2, Form("Run %d: setting %s as \"not first time unprocessed\"",
3108 anEntry->GetRun(), GetDetName(iDet)));
3109 fFirstUnprocessed[iDet] = kFALSE;
3110 }
3111 }
3112
3113 }
3114
3115 }
3116
3117 if (!RetrieveConditionsData(shuttleLogbookEntries))
3118 {
cb343cfd 3119 Log("SHUTTLE", "Collect - Process of at least one run failed");
a3ca69fe 3120 CountOpenRuns();
2bb7b766 3121 return kFALSE;
3122 }
3123
36c99a6a 3124 Log("SHUTTLE", "Collect - Requested run(s) successfully processed");
a3ca69fe 3125 CountOpenRuns();
eba76848 3126 return kTRUE;
2bb7b766 3127}
3128
2bb7b766 3129//______________________________________________________________________________________________
3130Bool_t AliShuttle::RetrieveConditionsData(const TObjArray& dateEntries)
3131{
9827400b 3132 //
3133 // Retrieve conditions data for all runs that aren't processed yet
3134 //
2bb7b766 3135
3136 Bool_t hasError = kFALSE;
3137
3138 TIter iter(&dateEntries);
3139 AliShuttleLogbookEntry* anEntry;
3140
3141 while ((anEntry = (AliShuttleLogbookEntry*) iter.Next())){
3142 if (!Process(anEntry)){
3143 hasError = kTRUE;
3144 }
4b95672b 3145
3146 // clean SHUTTLE temp directory
d524ade6 3147 //TString filename = Form("%s/*.shuttle", GetShuttleTempDir());
3148 //RemoveFile(filename.Data());
2bb7b766 3149 }
3150
3151 return hasError == kFALSE;
3152}
cb343cfd 3153
3154//______________________________________________________________________________________________
3155ULong_t AliShuttle::GetTimeOfLastAction() const
3156{
9827400b 3157 //
3158 // Gets time of last action
3159 //
3160
cb343cfd 3161 ULong_t tmp;
36c99a6a 3162
cb343cfd 3163 fMonitoringMutex->Lock();
be48e3ea 3164
cb343cfd 3165 tmp = fLastActionTime;
36c99a6a 3166
cb343cfd 3167 fMonitoringMutex->UnLock();
36c99a6a 3168
cb343cfd 3169 return tmp;
3170}
3171
3172//______________________________________________________________________________________________
3173const TString AliShuttle::GetLastAction() const
3174{
9827400b 3175 //
cb343cfd 3176 // returns a string description of the last action
9827400b 3177 //
cb343cfd 3178
3179 TString tmp;
36c99a6a 3180
cb343cfd 3181 fMonitoringMutex->Lock();
3182
3183 tmp = fLastAction;
3184
3185 fMonitoringMutex->UnLock();
3186
36c99a6a 3187 return tmp;
cb343cfd 3188}
3189
3190//______________________________________________________________________________________________
3191void AliShuttle::SetLastAction(const char* action)
3192{
9827400b 3193 //
cb343cfd 3194 // updates the monitoring variables
9827400b 3195 //
36c99a6a 3196
cb343cfd 3197 fMonitoringMutex->Lock();
36c99a6a 3198
cb343cfd 3199 fLastAction = action;
3200 fLastActionTime = time(0);
3201
3202 fMonitoringMutex->UnLock();
3203}
eba76848 3204
3205//______________________________________________________________________________________________
3206const char* AliShuttle::GetRunParameter(const char* param)
3207{
9827400b 3208 //
3209 // returns run parameter read from DAQ logbook
3210 //
eba76848 3211
3212 if(!fLogbookEntry) {
3213 AliError("No logbook entry!");
3214 return 0;
3215 }
3216
3217 return fLogbookEntry->GetRunParameter(param);
3218}
57c1a579 3219
d386d623 3220//______________________________________________________________________________________________
9827400b 3221AliCDBEntry* AliShuttle::GetFromOCDB(const char* detector, const AliCDBPath& path)
d386d623 3222{
9827400b 3223 //
3224 // returns object from OCDB valid for current run
3225 //
d386d623 3226
9827400b 3227 if (fTestMode & kErrorOCDB)
3228 {
3229 Log(detector, "GetFromOCDB - In TESTMODE - Simulating error with OCDB");
3230 return 0;
3231 }
3232
d386d623 3233 AliCDBStorage *sto = AliCDBManager::Instance()->GetStorage(fgkMainCDB);
3234 if (!sto)
3235 {
9827400b 3236 Log(detector, "GetFromOCDB - Cannot activate main OCDB for query!");
d386d623 3237 return 0;
3238 }
3239
3240 return dynamic_cast<AliCDBEntry*> (sto->Get(path, GetCurrentRun()));
3241}
3242
57c1a579 3243//______________________________________________________________________________________________
339adafa 3244Bool_t AliShuttle::SendMail(EMailTarget target, Int_t system)
57c1a579 3245{
9827400b 3246 //
3247 // sends a mail to the subdetector expert in case of preprocessor error
3248 //
3249
3250 if (fTestMode != kNone)
3251 return kTRUE;
fb40ead4 3252
926cbc0e 3253 if (!fConfig->SendMail())
3254 return kTRUE;
57c1a579 3255
339adafa 3256 if (target == kDCSEMail || target == kFXSEMail) {
3257 if (!fFirstProcessing)
3a4ddf0e 3258 return kTRUE;
36c99a6a 3259 }
3260
7bdfe1fa 3261 Int_t runMode = (Int_t)fConfig->GetRunMode();
3262 TString tmpStr;
3263 if (runMode == 0) tmpStr = " Nightly Test:";
3264 else tmpStr = " Data Taking:";
fbc112e3 3265 void* dir = gSystem->OpenDirectory(GetShuttleLogDir());
3266 if (dir == NULL)
3267 {
3268 if (gSystem->mkdir(GetShuttleLogDir(), kTRUE))
3269 {
3270 Log("SHUTTLE", Form("SendMail - Can't open directory <%s>", GetShuttleLogDir()));
3271 return kFALSE;
3272 }
3273
3274 } else {
3275 gSystem->FreeDirectory(dir);
3276 }
3277
339adafa 3278 // det experts in to
3279 TString to="";
3835a613 3280 TIter *iterExperts = 0;
339adafa 3281 if (target == kDCSEMail) {
3282 iterExperts = new TIter(fConfig->GetAdmins(AliShuttleConfig::kAmanda));
3283 }
3284 else if (target == kFXSEMail) {
3285 iterExperts = new TIter(fConfig->GetAdmins(system));
3286 }
3835a613 3287 if (iterExperts) {
3288 TObjString *anExpert=0;
3289 while ((anExpert = (TObjString*) iterExperts->Next()))
3290 {
3291 to += Form("%s,", anExpert->GetName());
3292 }
3293 delete iterExperts;
339adafa 3294 }
3835a613 3295
3296 // add subdetector experts
3297 iterExperts = new TIter(fConfig->GetResponsibles(fCurrentDetector));
339adafa 3298 TObjString *anExpert=0;
3299 while ((anExpert = (TObjString*) iterExperts->Next()))
4508ab8b 3300 {
339adafa 3301 to += Form("%s,", anExpert->GetName());
3302 }
3303 delete iterExperts;
3835a613 3304
339adafa 3305 if (to.Length() > 0)
3306 to.Remove(to.Length()-1);
3307 AliDebug(2, Form("to: %s",to.Data()));
4508ab8b 3308
339adafa 3309 if (to.IsNull()) {
3310 Log("SHUTTLE", Form("List of %d responsibles not set!", (Int_t) target));
3311 return kFALSE;
3312 }
3313
3314 // SHUTTLE responsibles in cc
fb40ead4 3315 TString cc="";
3316 TIter iterAdmins(fConfig->GetAdmins(AliShuttleConfig::kGlobal));
3317 TObjString *anAdmin=0;
3318 while ((anAdmin = (TObjString*) iterAdmins.Next()))
3319 {
3320 cc += Form("%s,", anAdmin->GetName());
3321 }
3322 if (cc.Length() > 0)
c19963db 3323 cc.Remove(cc.Length()-1);
fb40ead4 3324 AliDebug(2, Form("cc: %s",to.Data()));
57c1a579 3325
339adafa 3326 // mail body
675f64cd 3327 TString bodyFileName;
3328 bodyFileName.Form("%s/mail.body", GetShuttleLogDir());
3329 gSystem->ExpandPathName(bodyFileName);
3330
3331 ofstream mailBody;
3332 mailBody.open(bodyFileName, ofstream::out);
3333
3334 if (!mailBody.is_open())
3335 {
339adafa 3336 Log("SHUTTLE", Form("Could not open mail body file %s", bodyFileName.Data()));
675f64cd 3337 return kFALSE;
3338 }
3339
675f64cd 3340
339adafa 3341 TString subject;
3342 TString body;
675f64cd 3343
339adafa 3344 if (target == kDCSEMail){
af93e5d7 3345 subject = Form("%s CRITICAL Retrieval of data points for %s FAILED in run %d !",
7bdfe1fa 3346 tmpStr.Data(), fCurrentDetector.Data(), GetCurrentRun());
339adafa 3347 AliDebug(2, Form("subject: %s", subject.Data()));
3348
3349 body = Form("Dear DCS experts, \n\n");
3350 body += Form("SHUTTLE couldn\'t retrieve the data points for detector %s "
3351 "in run %d!!\n\n", fCurrentDetector.Data(), GetCurrentRun());
fb40ead4 3352 }
339adafa 3353 else if (target == kFXSEMail){
af93e5d7 3354 subject = Form("%s CRITICAL FXS communication for %s FAILED in run %d !",
7bdfe1fa 3355 tmpStr.Data(), fCurrentDetector.Data(), GetCurrentRun());
339adafa 3356 AliDebug(2, Form("subject: %s", subject.Data()));
3357 TString sys;
3358 if (system == kDAQ) sys="DAQ";
3359 else if (system == kDCS) sys="DCS";
3360 else if (system == kHLT) sys="HLT";
3d2b6cdd 3361 else if (system == kDQM) sys="DQM";
339adafa 3362 else return kFALSE;
9c0e2d64 3363 body = Form("Dear %s FXS experts, \n\n",sys.Data());
339adafa 3364 body += Form("SHUTTLE couldn\'t retrieve data from the FXS for detector %s "
9c0e2d64 3365 "in run %d!!\n\n", fCurrentDetector.Data(), GetCurrentRun());
8662f0a8 3366 body += Form("The contacted server was:\nDB: %s\nFXS:%s\n\n", fConfig->GetFXSdbHost(system), fConfig->GetFXSHost(system));
339adafa 3367 }
3368 else {
7bdfe1fa 3369 subject = Form("%s %s Shuttle preprocessor FAILED in run %d (run type = %s)!",
3370 tmpStr.Data(), fCurrentDetector.Data(), GetCurrentRun(), GetRunType());
339adafa 3371 AliDebug(2, Form("subject: %s", subject.Data()));
3372
3373 body = Form("Dear %s expert(s), \n\n", fCurrentDetector.Data());
3374 body += Form("SHUTTLE just detected that your preprocessor "
3375 "failed processing run %d (run type = %s)!!\n\n",
3376 GetCurrentRun(), GetRunType());
3377 }
675f64cd 3378
7d4cf768 3379 body += Form("Please check %s status on the SHUTTLE monitoring page: \n\n",
3380 fCurrentDetector.Data());
b0e53b15 3381 if (fConfig->GetRunMode() == AliShuttleConfig::kTest)
3382 {
8e828d39 3383 body += Form("\thttp://pcalimonitor.cern.ch/shuttle.jsp?time=24 \n\n");
b0e53b15 3384 } else {
8e828d39 3385 body += Form("\thttp://pcalimonitor.cern.ch/shuttle.jsp?instance=PROD&time=24 \n\n");
b0e53b15 3386 }
339adafa 3387
3388
7d4cf768 3389 TString logFolder = "logs";
3390 if (fConfig->GetRunMode() == AliShuttleConfig::kProd)
3391 logFolder += "_PROD";
3392
3393
675f64cd 3394 body += Form("Find the %s log for the current run on \n\n"
29fb87f4 3395 "\thttp://pcalishuttle02.cern.ch/%s/%d/%d/%s.log \n\n",
3ebbf3c4 3396 fCurrentDetector.Data(), logFolder.Data(), GetCurrentRun()/10000,
3397 GetCurrentRun(), fCurrentDetector.Data());
fe6a3257 3398 body += Form("The last 15 lines of %s log file are following:\n\n", fCurrentDetector.Data());
675f64cd 3399
3400 AliDebug(2, Form("Body begin: %s", body.Data()));
3401
3402 mailBody << body.Data();
3403 mailBody.close();
3404 mailBody.open(bodyFileName, ofstream::out | ofstream::app);
3405
3ebbf3c4 3406 TString logFileName = Form("%s/%d/%d/%s.log", GetShuttleLogDir(),
3407 GetCurrentRun()/10000, GetCurrentRun(), fCurrentDetector.Data());
fe6a3257 3408 TString tailCommand = Form("tail -n 15 %s >> %s", logFileName.Data(), bodyFileName.Data());
675f64cd 3409 if (gSystem->Exec(tailCommand.Data()))
3410 {
3411 mailBody << Form("%s log file not found ...\n\n", fCurrentDetector.Data());
3412 }
3413
3414 TString endBody = Form("------------------------------------------------------\n\n");
36c99a6a 3415 endBody += Form("In case of problems please contact the SHUTTLE core team.\n\n");
3416 endBody += "Please do not answer this message directly, it is automatically generated.\n\n";
546242fb 3417 endBody += "Greetings,\n\n \t\t\tthe SHUTTLE\n";
57c1a579 3418
909732f7 3419 AliDebug(2, Form("Body end: %s", endBody.Data()));
57c1a579 3420
3421 mailBody << endBody.Data();
3422
3423 mailBody.close();
3424
3425 // send mail!
3426 TString mailCommand = Form("mail -s \"%s\" -c %s %s < %s",
3427 subject.Data(),
3428 cc.Data(),
3429 to.Data(),
3430 bodyFileName.Data());
909732f7 3431 AliDebug(2, Form("mail command: %s", mailCommand.Data()));
57c1a579 3432
3433 Bool_t result = gSystem->Exec(mailCommand.Data());
3434
3435 return result == 0;
3436}
441b0e9c 3437//______________________________________________________________________________________________
9827400b 3438const char* AliShuttle::GetRunType()
441b0e9c 3439{
9827400b 3440 //
3441 // returns run type read from "run type" logbook
3442 //
441b0e9c 3443
3444 if(!fLogbookEntry) {
3445 AliError("No logbook entry!");
3446 return 0;
3447 }
3448
9827400b 3449 return fLogbookEntry->GetRunType();
441b0e9c 3450}
3451
4859271b 3452//______________________________________________________________________________________________
3453Bool_t AliShuttle::GetHLTStatus()
3454{
3455 // Return HLT status (ON=1 OFF=0)
af76b20d 3456 // Converts the HLT status from the mode string read in the run logbook (not just a bool)
4859271b 3457
3458 if(!fLogbookEntry) {
3459 AliError("No logbook entry!");
3460 return 0;
3461 }
3462
af76b20d 3463 // TODO implement when HLTMode is inserted in run logbook
b4ebc2d5 3464 TString hltMode = fLogbookEntry->GetRunParameter("HLTmode");
af76b20d 3465 TSubString firstChar = hltMode(0,1);
3466 AliDebug(2,Form("First char = %s ",firstChar.Data()));
3467 if (firstChar == "A") {
3468 return kFALSE;
3469 }
3470 else if ((firstChar == "B") || (firstChar == "C") || (firstChar == "D") || (firstChar == "E")) {
3471 return kTRUE;
3472 }
3473 else {
3474 Log("SHUTTLE","Unexpected HLT mode! Returning 0....");
3475 return kFALSE;
3476 }
4859271b 3477}
ca8ea066 3478
3479//______________________________________________________________________________________________
3480const char* AliShuttle::GetTriggerConfiguration()
3481{
3482 // Receives the trigger configuration from the DAQ logbook for the current run
3483
3484 // check connection, if needed reconnect
efec19bd 3485 if (!Connect(4))
ca8ea066 3486 return 0;
3487
3488 TString sqlQuery;
3489 sqlQuery.Form("SELECT configFile FROM logbook_trigger_config WHERE run = %d", GetCurrentRun());
efec19bd 3490 TSQLResult* result = fServer[4]->Query(sqlQuery);
ca8ea066 3491 if (!result)
3492 {
3493 Log("SHUTTLE", Form("ERROR: Can't execute query <%s>!", sqlQuery.Data()));
3494 return 0;
3495 }
3496
3497 if (result->GetRowCount() == 0)
3498 {
ff0191c7 3499 Log("SHUTTLE", "WARNING: Trigger configuration not found in logbook_trigger_config");
ca8ea066 3500 delete result;
3501 return 0;
3502 }
3503
3504 TSQLRow* row = result->Next();
3505 if (!row)
3506 {
3507 Log("SHUTTLE", "ERROR: Could not receive logbook_trigger_config data");
3508 delete result;
3509 return 0;
3510 }
3511
3512 // static, so that pointer remains valid when it is returned to the calling class
3513 static TString triggerConfig(row->GetField(0));
3514
3515 delete row;
3516 row = 0;
3517
3518 delete result;
3519 result = 0;
3520
3521 Log("SHUTTLE", Form("Found trigger configuration: %s", triggerConfig.Data()));
3522
3523 return triggerConfig;
3524}
3525
2c5f9d06 3526//______________________________________________________________________________________________
3527const char* AliShuttle::GetCTPTimeParams()
3528{
3529 // Receives the CTP time parameters from the DAQ logbook for the current run
3530
3531 // check connection, if needed reconnect
efec19bd 3532 if (!Connect(4))
2c5f9d06 3533 return 0;
3534
3535 TString sqlQuery;
3536 sqlQuery.Form("SELECT alignmentFile FROM logbook_trigger_config WHERE run = %d", GetCurrentRun());
efec19bd 3537 TSQLResult* result = fServer[4]->Query(sqlQuery);
2c5f9d06 3538 if (!result)
3539 {
3540 Log("SHUTTLE", Form("ERROR: Can't execute query <%s>!", sqlQuery.Data()));
3541 return 0;
3542 }
3543
3544 if (result->GetRowCount() == 0)
3545 {
ff0191c7 3546 Log("SHUTTLE", "WARNING: CTP time params not found in logbook_trigger_config");
2c5f9d06 3547 delete result;
3548 return 0;
3549 }
3550
3551 TSQLRow* row = result->Next();
3552 if (!row)
3553 {
3554 Log("SHUTTLE", "ERROR: Could not receive logbook_trigger_config data");
3555 delete result;
3556 return 0;
3557 }
3558
3559 // static, so that pointer remains valid when it is returned to the calling class
3560 static TString triggerTimeParams(row->GetField(0));
3561
3562 delete row;
3563 row = 0;
3564
3565 delete result;
3566 result = 0;
3567
a191c286 3568 Log("SHUTTLE", Form("Found trigger time parameters: %s", triggerTimeParams.Data()));
2c5f9d06 3569
3570 return triggerTimeParams;
3571}
3572
d386d623 3573//______________________________________________________________________________________________
b48d2542 3574const char* AliShuttle::GetTriggerDetectorMask()
3575{
3576 // Receives the trigger detector mask from DAQ logbook
3577
3578 // check connection, if needed reconnect
efec19bd 3579 if (!Connect(4))
b48d2542 3580 return 0;
3581
3582 TString sqlQuery;
3583 sqlQuery.Form("SELECT BIN(BIT_OR(inputDetectorMask)) from logbook_trigger_clusters WHERE run = %d;", GetCurrentRun());
efec19bd 3584 TSQLResult* result = fServer[4]->Query(sqlQuery);
b48d2542 3585 if (!result)
3586 {
3587 Log("SHUTTLE", Form("ERROR: Can't execute query <%s>!", sqlQuery.Data()));
3588 return 0;
3589 }
3590
3591 if (result->GetRowCount() == 0)
3592 {
3593 Log("SHUTTLE", "ERROR: Trigger Detector Mask not found in logbook_trigger_clusters");
3594 delete result;
3595 return 0;
3596 }
3597
3598 TSQLRow* row = result->Next();
3599 if (!row)
3600 {
3601 Log("SHUTTLE", "ERROR: Could not receive logbook_trigger_clusters data");
3602 delete result;
3603 return 0;
3604 }
3605
3606 // static, so that pointer remains valid when it is returned to the calling class
3607 static TString triggerDetectorMask(row->GetField(0));
3608
3609 delete row;
3610 row = 0;
3611
3612 delete result;
3613 result = 0;
3614
2e7d9963 3615 Log("SHUTTLE", Form("Found Trigger Detector Mask: %s", triggerDetectorMask.Data()));
b48d2542 3616
3617 return triggerDetectorMask;
3618}
3619
3620//______________________________________________________________________________________________
d386d623 3621void AliShuttle::SetShuttleTempDir(const char* tmpDir)
3622{
9827400b 3623 //
3624 // sets Shuttle temp directory
3625 //
d386d623 3626
3627 fgkShuttleTempDir = gSystem->ExpandPathName(tmpDir);
3628}
3629
3630//______________________________________________________________________________________________
3631void AliShuttle::SetShuttleLogDir(const char* logDir)
3632{
9827400b 3633 //
3634 // sets Shuttle log directory
3635 //
d386d623 3636
3637 fgkShuttleLogDir = gSystem->ExpandPathName(logDir);
3638}
503ff24f 3639//______________________________________________________________________________________________
3640Bool_t AliShuttle::TouchFile()
3641{
3642 //
3643 // touching a file on the grid if run has been DONE
3644 //
3645
3646 if (!gGrid)
3647 {
3648 Log("SHUTTLE",Form("No TGrid connection estabilished!"));
3649 Log("SHUTTLE",Form("Could not touch file for run %i",GetCurrentRun()));
3650 return kFALSE;
3651 }
3652
b8cf5e0f 3653 TString dir;
728290a4 3654 dir.Form("%s%d/SHUTTLE_DONE", fConfig->GetAlienPath(), GetCurrentYear());
b8cf5e0f 3655 // checking whether directory for touch command exists
3656 TString commandLs;
3657 commandLs.Form("ls %s",dir.Data());
3658 TGridResult *resultLs = dynamic_cast<TGridResult*>(gGrid->Command(commandLs));
3659 if (!resultLs){
3660 Log("SHUTTLE",Form("No result for %s command, returning without touching",commandLs.Data()));
3661 return kFALSE;
3662 }
3663 TMap *mapLs = dynamic_cast<TMap*>(resultLs->At(0));
3664 if (!mapLs){
3665 Log("SHUTTLE",Form("No map for %s command, returning without touching",commandLs.Data()));
97d38a5a 3666 delete resultLs;
3667 resultLs = 0x0;
b8cf5e0f 3668 return kFALSE;
3669 }
3670 TObjString *valueLsPath = dynamic_cast<TObjString*>(mapLs->GetValue("path"));
eff13ba0 3671 if (!valueLsPath || (valueLsPath->GetString()).CompareTo(dir)!=1){
b8cf5e0f 3672 Log("SHUTTLE",Form("No directory %s found, creating it",dir.Data()));
3673
3674 // creating the directory
3675
3676 Bool_t boolMkdir = gGrid->Mkdir(dir.Data());
3677 if (!boolMkdir) {
3678 Log("SHUTTLE",Form("Impossible to create dir %s in alien catalogue for run %i!",dir.Data(),GetCurrentRun()));
97d38a5a 3679 delete resultLs;
3680 resultLs = 0x0;
b8cf5e0f 3681 return kFALSE;
3682 }
3683 Log("SHUTTLE",Form("Directory %s successfully created in alien catalogue for run %i",dir.Data(),GetCurrentRun()));
3684 }
3685 else {
3686 Log("SHUTTLE",Form("Directory %s correctly found for run %i",dir.Data(),GetCurrentRun()));
3687 }
3688
97d38a5a 3689 delete resultLs;
3690 resultLs = 0x0;
3691
503ff24f 3692 TString command;
b8cf5e0f 3693 command.Form("touch %s/%i", dir.Data(), GetCurrentRun());
e660ff60 3694 Log("SHUTTLE", Form("Creating entry in file catalog: %s", command.Data()));
503ff24f 3695 TGridResult *resultTouch = dynamic_cast<TGridResult*>(gGrid->Command(command));
b8cf5e0f 3696 if (!resultTouch){
3697 Log("SHUTTLE",Form("No result for touching command, returning without touching for run %i",GetCurrentRun()));
3698 return kFALSE;
503ff24f 3699 }
b8cf5e0f 3700 TMap *mapTouch = dynamic_cast<TMap*>(resultTouch->At(0));
3701 if (!mapTouch){
3702 Log("SHUTTLE",Form("No map for touching command, returning without touching for run %i",GetCurrentRun()));
97d38a5a 3703 delete resultTouch;
3704 resultTouch = 0x0;
b8cf5e0f 3705 return kFALSE;
3706 }
3707 TObjString *valueTouch = dynamic_cast<TObjString*>(mapTouch->GetValue("__result__"));
3708 if (!valueTouch){
3709 Log("SHUTTLE",Form("No value for \"__result__\" key set in the map for touching command, returning without touching for run %i",GetCurrentRun()));
97d38a5a 3710 delete resultTouch;
3711 resultTouch = 0x0;
b8cf5e0f 3712 return kFALSE;
503ff24f 3713 }
b8cf5e0f 3714 if (valueTouch->GetString()!="1"){
3715 Log("SHUTTLE",Form("Failing the touching command, returning without touching for run %i",GetCurrentRun()));
97d38a5a 3716 delete resultTouch;
3717 resultTouch = 0x0;
b8cf5e0f 3718 return kFALSE;
3719 }
97d38a5a 3720 delete resultTouch;
3721 resultTouch = 0x0;
98400bd9 3722 Log("SHUTTLE", "Sucessfully touched the file");
b8cf5e0f 3723 return kTRUE;
503ff24f 3724}
2eb98462 3725//______________________________________________________________________________________________
f100adeb 3726UInt_t AliShuttle::GetStartTimeDCSQuery()
2eb98462 3727{
3728 // Return Start Time for the DCS query
3729 //
3730 // The call is delegated to AliShuttleInterface
3731
3d24ad5a 3732 return GetCurrentStartTime()-fConfig->GetDCSQueryOffset();
2eb98462 3733}
3734//______________________________________________________________________________________________
f100adeb 3735UInt_t AliShuttle::GetEndTimeDCSQuery()
2eb98462 3736{
3737 // Return End Time for the DCS query
3738 //
3739 // The call is delegated to AliShuttleInterface
3740
3741 return GetCurrentEndTime()+fConfig->GetDCSQueryOffset();
3742}
1f0f7c2e 3743//______________________________________________________________________________________________
3744void AliShuttle::SendMLFromDet(const char* value)
3745{
3746 //
3747 // Sending an information coming from the current detector to ML
3748 //
3749
3750 TMonaLisaText mlText(Form("%s_RunCondition", fCurrentDetector.Data()), value);
3751
3752 TList mlList;
3753 mlList.Add(&mlText);
3754
3755 TString mlID;
3756 mlID.Form("%d", GetCurrentRun());
3757 fMonaLisa->SendParameters(&mlList, mlID);
3758
3759 return;
3760}
6ecb073a 3761//______________________________________________________________________________________________
3762TString* AliShuttle::GetLTUConfig(const char* det)
3763{
3764 //
3765 // Getting ltuFineDelay1, ltuFineDelay2, ltuBCDelay for detector det from logbook_detectors table in logbook
3766 //
3767
efec19bd 3768 if (!Connect(4))
6ecb073a 3769 return 0;
3770
3771 TString sqlQuery;
3772 sqlQuery.Form("select LTUFineDelay1, LTUFineDelay2, LTUBCDelayAdd from logbook_detectors WHERE run_number = %d and detector = \"%s\";", GetCurrentRun(),det);
3773
efec19bd 3774 TSQLResult* result = fServer[4]->Query(sqlQuery);
6ecb073a 3775 if (!result){
3776 Log("SHUTTLE","ERROR: No result found for the LTU configuration query");
3777 return 0x0;
3778 }
3779 if (result->GetRowCount() == 0){
3780 Log("SHUTTLE",Form("ERROR: LTU configuration not found in logbook_detectors for detector %s, returning null pointer",det));
3781 delete result;
3782 return 0x0;
3783 }
3784 if (result->GetFieldCount() != 3){
3785 Log("SHUTTLE",Form("ERROR: not all the required fields are there for the LTU configuration for detector %s (only %d found), returning a null pointer",det, result->GetFieldCount()));
3786 delete result;
3787 return 0x0;
3788 }
3789 TSQLRow* row = result->Next();
3790 if (!row){
3791 Printf("ERROR: Could not receive logbook_detectors data, returning null pointer");
3792 delete result;
3793 return 0x0;
3794 }
3795 TString* ltuConfigString = new TString[3];
3796
3797 ltuConfigString[0] = row->GetField(0);
3798 ltuConfigString[1] = row->GetField(1);
3799 ltuConfigString[2] = row->GetField(2);
503ff24f 3800
6ecb073a 3801 return ltuConfigString;
3802
3803}