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