]> git.uio.no Git - u/mrichter/AliRoot.git/blame - SHUTTLE/AliShuttle.cxx
Changes to remove compilation warnings
[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 - "
95d4aaef 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 - "
95d4aaef 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
c98417a1 2102 if (fileSize.Length()>0)
2103 {
2104 // compare filesize of local file with the one stored in the FXS DB
95d4aaef 2105 Long_t id,size,flags,mtime;
2106 Int_t sizeComp = gSystem->GetPathInfo(localFileName.Data(),&id,&size,&flags,&mtime);
c98417a1 2107
95d4aaef 2108 if ( sizeComp != 0 || size != fileSize.Atoi())
c98417a1 2109 {
2110 Log(detector, Form("GetFileName - size of file %s does not match with local copy!",
2111 filePath.Data()));
2112 result = kFALSE;
2113 continue;
2114 }
2115
2116 } else {
2117 Log(fCurrentDetector, Form("GetFile - size of file %s not set in %s database, skipping comparison",
2118 filePath.Data(), GetSystemName(system)));
2119 }
2120
d386d623 2121 if (fileChecksum.Length()>0)
4b95672b 2122 {
2123 // compare md5sum of local file with the one stored in the FXS DB
95d4aaef 2124 if(fileChecksum.Contains(' ')) fileChecksum.Resize(fileChecksum.First(' '));
d524ade6 2125 Int_t md5Comp = gSystem->Exec(Form("md5sum %s |grep %s 2>&1 > /dev/null",
2126 localFileName.Data(), fileChecksum.Data()));
9e080f92 2127
4b95672b 2128 if (md5Comp != 0)
2129 {
2130 Log(detector, Form("GetFileName - md5sum of file %s does not match with local copy!",
2131 filePath.Data()));
2132 result = kFALSE;
2133 continue;
2134 }
d386d623 2135 } else {
2136 Log(fCurrentDetector, Form("GetFile - md5sum of file %s not set in %s database, skipping comparison",
2137 filePath.Data(), GetSystemName(system)));
9d733021 2138 }
4b95672b 2139 if (result) break;
9e080f92 2140 }
2141
4b95672b 2142 if(!result) return 0;
2143
9d733021 2144 fFXSCalled[system]=kTRUE;
2145 TObjString *fileParams = new TObjString(Form("%s#!?!#%s", id, sourceName.Data()));
2146 fFXSlist[system].Add(fileParams);
9e080f92 2147
675f64cd 2148 static TString staticLocalFileName;
2149 staticLocalFileName.Form("%s", localFileName.Data());
2150
c88ad5db 2151 Log(fCurrentDetector, Form("GetFile - Retrieved file with id %s and "
2152 "source %s from %s to %s", id, source,
d524ade6 2153 GetSystemName(system), localFileName.Data()));
675f64cd 2154
d524ade6 2155 return staticLocalFileName.Data();
2bb7b766 2156}
2157
2158//______________________________________________________________________________________________
9d733021 2159Bool_t AliShuttle::RetrieveFile(UInt_t system, const char* fxsFileName, const char* localFileName)
9e080f92 2160{
9827400b 2161 //
2162 // Copies file from FXS to local Shuttle machine
2163 //
2bb7b766 2164
9e080f92 2165 // check temp directory: trying to cd to temp; if it does not exist, create it
d524ade6 2166 AliDebug(2, Form("Copy file %s from %s FXS into %s",
2167 GetSystemName(system), fxsFileName, localFileName));
2168
2169 TString tmpDir(localFileName);
2170
2171 tmpDir = tmpDir(0,tmpDir.Last('/'));
9e080f92 2172
d524ade6 2173 Int_t noDir = gSystem->GetPathInfo(tmpDir.Data(), 0, (Long64_t*) 0, 0, 0);
2174 if (noDir) // temp dir does not exists!
2175 {
2176 if (gSystem->mkdir(tmpDir.Data(), 1))
2177 {
2178 Log(fCurrentDetector.Data(), "RetrieveFile - could not make temp directory!!");
9e080f92 2179 return kFALSE;
2180 }
9e080f92 2181 }
2182
9d733021 2183 TString baseFXSFolder;
2184 if (system == kDAQ)
2185 {
2186 baseFXSFolder = "FES/";
2187 }
2188 else if (system == kDCS)
2189 {
2190 baseFXSFolder = "";
2191 }
2192 else if (system == kHLT)
2193 {
42fde080 2194 baseFXSFolder = "/opt/FXS/";
9d733021 2195 }
2196
2197
d524ade6 2198 TString command = Form("scp -oPort=%d -2 %s@%s:%s%s %s",
9d733021 2199 fConfig->GetFXSPort(system),
2200 fConfig->GetFXSUser(system),
2201 fConfig->GetFXSHost(system),
2202 baseFXSFolder.Data(),
2203 fxsFileName,
9e080f92 2204 localFileName);
2205
2206 AliDebug(2, Form("%s",command.Data()));
2207
4b95672b 2208 Bool_t result = (gSystem->Exec(command.Data()) == 0);
9e080f92 2209
4b95672b 2210 return result;
9e080f92 2211}
2212
2213//______________________________________________________________________________________________
9d733021 2214TList* AliShuttle::GetFileSources(Int_t system, const char* detector, const char* id)
2215{
9827400b 2216 //
2217 // Get sources producing the condition file Id from file exchange servers
4a33bdd9 2218 // if id is NULL all sources are returned (distinct)
9827400b 2219 //
1bcd28db 2220
8884d71e 2221 if (id)
2222 {
2223 Log(detector, Form("GetFileSources - Querying %s FXS for files with id %s produced by %s", GetSystemName(system), id, detector));
2224 } else {
2225 Log(detector, Form("GetFileSources - Querying %s FXS for files produced by %s", GetSystemName(system), detector));
2226 }
9827400b 2227
2228 // check if test mode should simulate a FXS error
2229 if (fTestMode & kErrorFXSSources)
2230 {
2231 Log(detector, Form("GetFileSources - In TESTMODE - Simulating error while connecting to %s FXS", GetSystemName(system)));
2232 return 0;
2233 }
2234
9d733021 2235 if (system == kDCS)
2236 {
c88ad5db 2237 Log(detector, "GetFileSources - WARNING: DCS system has only one source of data!");
6297b37d 2238 TList *list = new TList();
2239 list->SetOwner(1);
2240 list->Add(new TObjString(" "));
2241 return list;
9d733021 2242 }
9e080f92 2243
2244 // check connection, in case connect
9d733021 2245 if (!Connect(system))
2246 {
4a33bdd9 2247 Log(detector, Form("GetFileSources - Couldn't connect to %s FXS database", GetSystemName(system)));
9d733021 2248 return NULL;
9e080f92 2249 }
2250
9d733021 2251 TString sourceName = 0;
2252 if (system == kDAQ)
2253 {
2254 sourceName = "DAQsource";
2255 } else if (system == kHLT)
2256 {
2257 sourceName = "DDLnumbers";
2258 }
2259
4a33bdd9 2260 TString sqlQueryStart = Form("select distinct %s from %s where", sourceName.Data(), fConfig->GetFXSdbTable(system));
2261 TString whereClause = Form("run=%d and detector=\"%s\"",
2262 GetCurrentRun(), detector);
2263 if (id)
2264 whereClause += Form(" and fileId=\"%s\"", id);
9e080f92 2265 TString sqlQuery = Form("%s %s", sqlQueryStart.Data(), whereClause.Data());
2266
2267 AliDebug(2, Form("SQL query: \n%s",sqlQuery.Data()));
2268
2269 // Query execution
2270 TSQLResult* aResult;
9d733021 2271 aResult = fServer[system]->Query(sqlQuery);
9e080f92 2272 if (!aResult) {
9d733021 2273 Log(detector, Form("GetFileSources - Can't execute SQL query to %s database for id: %s",
2274 GetSystemName(system), id));
9e080f92 2275 return 0;
2276 }
2277
86aa42c3 2278 TList *list = new TList();
2279 list->SetOwner(1);
2280
9d733021 2281 if (aResult->GetRowCount() == 0)
2282 {
9e080f92 2283 Log(detector,
9d733021 2284 Form("GetFileSources - No entry in %s FXS table for id: %s", GetSystemName(system), id));
9e080f92 2285 delete aResult;
86aa42c3 2286 return list;
9e080f92 2287 }
2288
1bcd28db 2289 Log(detector, Form("GetFileSources - Found %d sources", aResult->GetRowCount()));
9e080f92 2290
1bcd28db 2291 TSQLRow* aRow;
9d733021 2292 while ((aRow = aResult->Next()))
2293 {
9e080f92 2294
9d733021 2295 TString source(aRow->GetField(0), aRow->GetFieldLength(0));
2296 AliDebug(2, Form("%s = %s", sourceName.Data(), source.Data()));
2297 list->Add(new TObjString(source));
9e080f92 2298 delete aRow;
2299 }
9d733021 2300
9e080f92 2301 delete aResult;
2302
2303 return list;
2bb7b766 2304}
2305
4a33bdd9 2306//______________________________________________________________________________________________
2307TList* AliShuttle::GetFileIDs(Int_t system, const char* detector, const char* source)
2308{
2309 //
2310 // Get all ids of condition files produced by a given source from file exchange servers
2311 //
2312
1bcd28db 2313 Log(detector, Form("GetFileIDs - Retrieving ids with source %s with %s", source, GetSystemName(system)));
2314
4a33bdd9 2315 // check if test mode should simulate a FXS error
2316 if (fTestMode & kErrorFXSSources)
2317 {
2318 Log(detector, Form("GetFileIDs - In TESTMODE - Simulating error while connecting to %s FXS", GetSystemName(system)));
2319 return 0;
2320 }
2321
2322 // check connection, in case connect
2323 if (!Connect(system))
2324 {
2325 Log(detector, Form("GetFileIDs - Couldn't connect to %s FXS database", GetSystemName(system)));
2326 return NULL;
2327 }
2328
2329 TString sourceName = 0;
2330 if (system == kDAQ)
2331 {
2332 sourceName = "DAQsource";
2333 } else if (system == kHLT)
2334 {
2335 sourceName = "DDLnumbers";
2336 }
2337
2338 TString sqlQueryStart = Form("select fileId from %s where", fConfig->GetFXSdbTable(system));
2339 TString whereClause = Form("run=%d and detector=\"%s\"",
2340 GetCurrentRun(), detector);
2341 if (sourceName.Length() > 0 && source)
2342 whereClause += Form(" and %s=\"%s\"", sourceName.Data(), source);
2343 TString sqlQuery = Form("%s %s", sqlQueryStart.Data(), whereClause.Data());
2344
2345 AliDebug(2, Form("SQL query: \n%s",sqlQuery.Data()));
2346
2347 // Query execution
2348 TSQLResult* aResult;
2349 aResult = fServer[system]->Query(sqlQuery);
2350 if (!aResult) {
2351 Log(detector, Form("GetFileIDs - Can't execute SQL query to %s database for source: %s",
2352 GetSystemName(system), source));
2353 return 0;
2354 }
2355
2356 TList *list = new TList();
2357 list->SetOwner(1);
2358
2359 if (aResult->GetRowCount() == 0)
2360 {
2361 Log(detector,
2362 Form("GetFileIDs - No entry in %s FXS table for source: %s", GetSystemName(system), source));
2363 delete aResult;
2364 return list;
2365 }
2366
1bcd28db 2367 Log(detector, Form("GetFileIDs - Found %d ids", aResult->GetRowCount()));
2368
4a33bdd9 2369 TSQLRow* aRow;
2370
2371 while ((aRow = aResult->Next()))
2372 {
2373
2374 TString id(aRow->GetField(0), aRow->GetFieldLength(0));
2375 AliDebug(2, Form("fileId = %s", id.Data()));
2376 list->Add(new TObjString(id));
2377 delete aRow;
2378 }
2379
2380 delete aResult;
2381
2382 return list;
2383}
2384
2bb7b766 2385//______________________________________________________________________________________________
9d733021 2386Bool_t AliShuttle::Connect(Int_t system)
2bb7b766 2387{
9827400b 2388 // Connect to MySQL Server of the system's FXS MySQL databases
2389 // DAQ Logbook, Shuttle Logbook and DAQ FXS db are on the same host
2390 //
57f50b3c 2391
9d733021 2392 // check connection: if already connected return
2393 if(fServer[system] && fServer[system]->IsConnected()) return kTRUE;
57f50b3c 2394
9d733021 2395 TString dbHost, dbUser, dbPass, dbName;
57f50b3c 2396
9d733021 2397 if (system < 3) // FXS db servers
2398 {
2399 dbHost = Form("mysql://%s:%d", fConfig->GetFXSdbHost(system), fConfig->GetFXSdbPort(system));
2400 dbUser = fConfig->GetFXSdbUser(system);
2401 dbPass = fConfig->GetFXSdbPass(system);
2402 dbName = fConfig->GetFXSdbName(system);
2403 } else { // Run & Shuttle logbook servers
2404 // TODO Will the Shuttle logbook server be the same as the Run logbook server ???
2405 dbHost = Form("mysql://%s:%d", fConfig->GetDAQlbHost(), fConfig->GetDAQlbPort());
2406 dbUser = fConfig->GetDAQlbUser();
2407 dbPass = fConfig->GetDAQlbPass();
2408 dbName = fConfig->GetDAQlbDB();
2409 }
57f50b3c 2410
9d733021 2411 fServer[system] = TSQLServer::Connect(dbHost.Data(), dbUser.Data(), dbPass.Data());
2412 if (!fServer[system] || !fServer[system]->IsConnected()) {
2413 if(system < 3)
2414 {
2415 AliError(Form("Can't establish connection to FXS database for %s",
2416 AliShuttleInterface::GetSystemName(system)));
2417 } else {
2418 AliError("Can't establish connection to Run logbook.");
57f50b3c 2419 }
9d733021 2420 if(fServer[system]) delete fServer[system];
2421 return kFALSE;
2bb7b766 2422 }
57f50b3c 2423
9d733021 2424 // Get tables
2425 TSQLResult* aResult=0;
2426 switch(system){
2427 case kDAQ:
2428 aResult = fServer[kDAQ]->GetTables(dbName.Data());
2429 break;
2430 case kDCS:
2431 aResult = fServer[kDCS]->GetTables(dbName.Data());
2432 break;
2433 case kHLT:
2434 aResult = fServer[kHLT]->GetTables(dbName.Data());
2435 break;
2436 default:
2437 aResult = fServer[3]->GetTables(dbName.Data());
2438 break;
2439 }
2440
2441 delete aResult;
2bb7b766 2442 return kTRUE;
2443}
57f50b3c 2444
9e080f92 2445//______________________________________________________________________________________________
9d733021 2446Bool_t AliShuttle::UpdateTable()
9e080f92 2447{
9827400b 2448 //
2449 // Update FXS table filling time_processed field in all rows corresponding to current run and detector
2450 //
9e080f92 2451
9d733021 2452 Bool_t result = kTRUE;
9e080f92 2453
9d733021 2454 for (UInt_t system=0; system<3; system++)
2455 {
2456 if(!fFXSCalled[system]) continue;
9e080f92 2457
9d733021 2458 // check connection, in case connect
2459 if (!Connect(system))
2460 {
2461 Log(fCurrentDetector, Form("UpdateTable - Couldn't connect to %s FXS database", GetSystemName(system)));
2462 result = kFALSE;
2463 continue;
9e080f92 2464 }
9e080f92 2465
9d733021 2466 TTimeStamp now; // now
2467
2468 // Loop on FXS list entries
2469 TIter iter(&fFXSlist[system]);
2470 TObjString *aFXSentry=0;
2471 while ((aFXSentry = dynamic_cast<TObjString*> (iter.Next())))
2472 {
2473 TString aFXSentrystr = aFXSentry->String();
2474 TObjArray *aFXSarray = aFXSentrystr.Tokenize("#!?!#");
2475 if (!aFXSarray || aFXSarray->GetEntries() != 2 )
2476 {
2477 Log(fCurrentDetector, Form("UpdateTable - error updating %s FXS entry. Check string: <%s>",
2478 GetSystemName(system), aFXSentrystr.Data()));
2479 if(aFXSarray) delete aFXSarray;
2480 result = kFALSE;
2481 continue;
2482 }
2483 const char* fileId = ((TObjString*) aFXSarray->At(0))->GetName();
2484 const char* source = ((TObjString*) aFXSarray->At(1))->GetName();
2485
2486 TString whereClause;
2487 if (system == kDAQ)
2488 {
2489 whereClause = Form("where run=%d and detector=\"%s\" and fileId=\"%s\" and DAQsource=\"%s\";",
2490 GetCurrentRun(), fCurrentDetector.Data(), fileId, source);
2491 }
2492 else if (system == kDCS)
2493 {
2494 whereClause = Form("where run=%d and detector=\"%s\" and fileId=\"%s\";",
2495 GetCurrentRun(), fCurrentDetector.Data(), fileId);
2496 }
2497 else if (system == kHLT)
2498 {
2499 whereClause = Form("where run=%d and detector=\"%s\" and fileId=\"%s\" and DDLnumbers=\"%s\";",
2500 GetCurrentRun(), fCurrentDetector.Data(), fileId, source);
2501 }
2502
2503 delete aFXSarray;
9e080f92 2504
9d733021 2505 TString sqlQuery = Form("update %s set time_processed=%d %s", fConfig->GetFXSdbTable(system),
2506 now.GetSec(), whereClause.Data());
9e080f92 2507
9d733021 2508 AliDebug(2, Form("SQL query: \n%s",sqlQuery.Data()));
9e080f92 2509
9d733021 2510 // Query execution
2511 TSQLResult* aResult;
2512 aResult = dynamic_cast<TSQLResult*> (fServer[system]->Query(sqlQuery));
2513 if (!aResult)
2514 {
2515 Log(fCurrentDetector, Form("UpdateTable - %s db: can't execute SQL query <%s>",
2516 GetSystemName(system), sqlQuery.Data()));
2517 result = kFALSE;
2518 continue;
2519 }
2520 delete aResult;
9e080f92 2521 }
9e080f92 2522 }
2523
9d733021 2524 return result;
9e080f92 2525}
57f50b3c 2526
3301427a 2527//______________________________________________________________________________________________
2528Bool_t AliShuttle::UpdateTableFailCase()
2529{
9827400b 2530 // Update FXS table filling time_processed field in all rows corresponding to current run and detector
2531 // this is called in case the preprocessor is declared failed for the current run, because
2532 // the fields are updated only in case of success
3301427a 2533
2534 Bool_t result = kTRUE;
2535
2536 for (UInt_t system=0; system<3; system++)
2537 {
2538 // check connection, in case connect
2539 if (!Connect(system))
2540 {
2541 Log(fCurrentDetector, Form("UpdateTableFailCase - Couldn't connect to %s FXS database",
2542 GetSystemName(system)));
2543 result = kFALSE;
2544 continue;
2545 }
2546
2547 TTimeStamp now; // now
2548
2549 // Loop on FXS list entries
2550
2551 TString whereClause = Form("where run=%d and detector=\"%s\";",
2552 GetCurrentRun(), fCurrentDetector.Data());
2553
2554
2555 TString sqlQuery = Form("update %s set time_processed=%d %s", fConfig->GetFXSdbTable(system),
2556 now.GetSec(), whereClause.Data());
2557
2558 AliDebug(2, Form("SQL query: \n%s",sqlQuery.Data()));
2559
2560 // Query execution
2561 TSQLResult* aResult;
2562 aResult = dynamic_cast<TSQLResult*> (fServer[system]->Query(sqlQuery));
2563 if (!aResult)
2564 {
2565 Log(fCurrentDetector, Form("UpdateTableFailCase - %s db: can't execute SQL query <%s>",
2566 GetSystemName(system), sqlQuery.Data()));
2567 result = kFALSE;
2568 continue;
2569 }
2570 delete aResult;
2571 }
2572
2573 return result;
2574}
2575
2bb7b766 2576//______________________________________________________________________________________________
2577Bool_t AliShuttle::UpdateShuttleLogbook(const char* detector, const char* status)
2578{
e7f62f16 2579 //
2580 // Update Shuttle logbook filling detector or shuttle_done column
2581 // ex. of usage: UpdateShuttleLogbook("PHOS", "DONE") or UpdateShuttleLogbook("shuttle_done")
2582 //
57f50b3c 2583
2bb7b766 2584 // check connection, in case connect
be48e3ea 2585 if(!Connect(3)){
2bb7b766 2586 Log("SHUTTLE", "UpdateShuttleLogbook - Couldn't connect to DAQ Logbook.");
2587 return kFALSE;
57f50b3c 2588 }
2589
2bb7b766 2590 TString detName(detector);
2591 TString setClause;
ee6f7523 2592 if (detName == "shuttle_done" || detName == "shuttle_ignored")
e7f62f16 2593 {
2bb7b766 2594 setClause = "set shuttle_done=1";
e7f62f16 2595
ee6f7523 2596 if (detName == "shuttle_done")
b0e53b15 2597 {
2598 // Send the information to ML
2599 TMonaLisaText mlStatus("SHUTTLE_status", "Done");
e7f62f16 2600
b0e53b15 2601 TList mlList;
2602 mlList.Add(&mlStatus);
2603
ee6f7523 2604 TString mlID;
2605 mlID.Form("%d", GetCurrentRun());
2606 fMonaLisa->SendParameters(&mlList, mlID);
b0e53b15 2607 }
2bb7b766 2608 } else {
2bb7b766 2609 TString statusStr(status);
2610 if(statusStr.Contains("done", TString::kIgnoreCase) ||
2611 statusStr.Contains("failed", TString::kIgnoreCase)){
eba76848 2612 setClause = Form("set %s=\"%s\"", detector, status);
2bb7b766 2613 } else {
2614 Log("SHUTTLE",
2615 Form("UpdateShuttleLogbook - Invalid status <%s> for detector %s",
2616 status, detector));
2617 return kFALSE;
2618 }
2619 }
57f50b3c 2620
2bb7b766 2621 TString whereClause = Form("where run=%d", GetCurrentRun());
2622
441b0e9c 2623 TString sqlQuery = Form("update %s %s %s",
2624 fConfig->GetShuttlelbTable(), setClause.Data(), whereClause.Data());
57f50b3c 2625
2bb7b766 2626 AliDebug(2, Form("SQL query: \n%s",sqlQuery.Data()));
2627
2628 // Query execution
2629 TSQLResult* aResult;
be48e3ea 2630 aResult = dynamic_cast<TSQLResult*> (fServer[3]->Query(sqlQuery));
2bb7b766 2631 if (!aResult) {
2632 Log("SHUTTLE", Form("UpdateShuttleLogbook - Can't execute query <%s>", sqlQuery.Data()));
2633 return kFALSE;
57f50b3c 2634 }
2bb7b766 2635 delete aResult;
57f50b3c 2636
2637 return kTRUE;
2638}
2639
2640//______________________________________________________________________________________________
2bb7b766 2641Int_t AliShuttle::GetCurrentRun() const
2642{
9827400b 2643 //
2644 // Get current run from logbook entry
2645 //
57f50b3c 2646
2bb7b766 2647 return fLogbookEntry ? fLogbookEntry->GetRun() : -1;
57f50b3c 2648}
2649
2650//______________________________________________________________________________________________
2bb7b766 2651UInt_t AliShuttle::GetCurrentStartTime() const
2652{
9827400b 2653 //
2654 // get current start time
2655 //
57f50b3c 2656
2bb7b766 2657 return fLogbookEntry ? fLogbookEntry->GetStartTime() : 0;
57f50b3c 2658}
2659
2660//______________________________________________________________________________________________
2bb7b766 2661UInt_t AliShuttle::GetCurrentEndTime() const
2662{
9827400b 2663 //
2664 // get current end time from logbook entry
2665 //
57f50b3c 2666
2bb7b766 2667 return fLogbookEntry ? fLogbookEntry->GetEndTime() : 0;
57f50b3c 2668}
2669
675f64cd 2670//______________________________________________________________________________________________
2671UInt_t AliShuttle::GetCurrentYear() const
2672{
2673 //
2674 // Get current year from logbook entry
2675 //
2676
2677 if (!fLogbookEntry) return 0;
2678
2679 TTimeStamp startTime(GetCurrentStartTime());
2680 TString year = Form("%d",startTime.GetDate());
2681 year = year(0,4);
2682
2683 return year.Atoi();
2684}
2685
2686//______________________________________________________________________________________________
2687const char* AliShuttle::GetLHCPeriod() const
2688{
2689 //
2690 // Get current LHC period from logbook entry
2691 //
2692
2693 if (!fLogbookEntry) return 0;
2694
2695 return fLogbookEntry->GetRunParameter("LHCperiod");
2696}
2697
b948db8d 2698//______________________________________________________________________________________________
2699void AliShuttle::Log(const char* detector, const char* message)
2700{
9827400b 2701 //
2702 // Fill log string with a message
2703 //
b948db8d 2704
7d4cf768 2705 TString logRunDir = GetShuttleLogDir();
2706 if (GetCurrentRun() >=0)
2707 logRunDir += Form("/%d", GetCurrentRun());
2708
2709 void* dir = gSystem->OpenDirectory(logRunDir.Data());
84090f85 2710 if (dir == NULL) {
7d4cf768 2711 if (gSystem->mkdir(logRunDir.Data(), kTRUE)) {
36c99a6a 2712 AliError(Form("Can't open directory <%s>", GetShuttleLogDir()));
84090f85 2713 return;
2714 }
b948db8d 2715
84090f85 2716 } else {
2717 gSystem->FreeDirectory(dir);
2718 }
b948db8d 2719
cb343cfd 2720 TString toLog = Form("%s (%d): %s - ", TTimeStamp(time(0)).AsString("s"), getpid(), detector);
e7f62f16 2721 if (GetCurrentRun() >= 0)
2722 toLog += Form("run %d - ", GetCurrentRun());
2bb7b766 2723 toLog += Form("%s", message);
2724
84090f85 2725 AliInfo(toLog.Data());
ffa29e93 2726
2727 // if we redirect the log output already to the file, leave here
2728 if (fOutputRedirected && strcmp(detector, "SHUTTLE") != 0)
2729 return;
b948db8d 2730
ffa29e93 2731 TString fileName = GetLogFileName(detector);
e7f62f16 2732
84090f85 2733 gSystem->ExpandPathName(fileName);
2734
2735 ofstream logFile;
2736 logFile.open(fileName, ofstream::out | ofstream::app);
2737
2738 if (!logFile.is_open()) {
2739 AliError(Form("Could not open file %s", fileName.Data()));
2740 return;
2741 }
7bfb2090 2742
84090f85 2743 logFile << toLog.Data() << "\n";
b948db8d 2744
84090f85 2745 logFile.close();
b948db8d 2746}
2bb7b766 2747
ffa29e93 2748//______________________________________________________________________________________________
2749TString AliShuttle::GetLogFileName(const char* detector) const
2750{
2751 //
2752 // returns the name of the log file for a given sub detector
2753 //
2754
2755 TString fileName;
2756
2757 if (GetCurrentRun() >= 0)
7d4cf768 2758 {
2759 fileName.Form("%s/%d/%s_%d.log", GetShuttleLogDir(), GetCurrentRun(),
2760 detector, GetCurrentRun());
2761 } else {
ffa29e93 2762 fileName.Form("%s/%s.log", GetShuttleLogDir(), detector);
7d4cf768 2763 }
ffa29e93 2764
2765 return fileName;
2766}
2767
ee6f7523 2768//______________________________________________________________________________________________
2769void AliShuttle::SendAlive()
2770{
2771 // sends alive message to ML
2772
2773 TMonaLisaText mlStatus("SHUTTLE_status", "Alive");
2774
2775 TList mlList;
2776 mlList.Add(&mlStatus);
2777
2778 fMonaLisa->SendParameters(&mlList, "__PROCESSINGINFO__");
2779}
2780
2bb7b766 2781//______________________________________________________________________________________________
2782Bool_t AliShuttle::Collect(Int_t run)
2783{
9827400b 2784 //
2785 // Collects conditions data for all UNPROCESSED run written to DAQ LogBook in case of run = -1 (default)
2786 // If a dedicated run is given this run is processed
2787 //
2788 // In operational mode, this is the Shuttle function triggered by the EOR signal.
2789 //
2bb7b766 2790
eba76848 2791 if (run == -1)
2792 Log("SHUTTLE","Collect - Shuttle called. Collecting conditions data for unprocessed runs");
2793 else
2794 Log("SHUTTLE", Form("Collect - Shuttle called. Collecting conditions data for run %d", run));
cb343cfd 2795
2796 SetLastAction("Starting");
2bb7b766 2797
ee6f7523 2798 // create ML instance
2799 if (!fMonaLisa)
2800 fMonaLisa = new TMonaLisaWriter(fConfig->GetMonitorHost(), fConfig->GetMonitorTable());
2801
ee6f7523 2802 SendAlive();
fbc112e3 2803 CountOpenRuns();
ee6f7523 2804
2bb7b766 2805 TString whereClause("where shuttle_done=0");
eba76848 2806 if (run != -1)
2807 whereClause += Form(" and run=%d", run);
2bb7b766 2808
2809 TObjArray shuttleLogbookEntries;
be48e3ea 2810 if (!QueryShuttleLogbook(whereClause, shuttleLogbookEntries))
2811 {
cb343cfd 2812 Log("SHUTTLE", "Collect - Can't retrieve entries from Shuttle logbook");
2bb7b766 2813 return kFALSE;
2814 }
2815
9e080f92 2816 if (shuttleLogbookEntries.GetEntries() == 0)
2817 {
2818 if (run == -1)
2819 Log("SHUTTLE","Collect - Found no UNPROCESSED runs in Shuttle logbook");
2820 else
2821 Log("SHUTTLE", Form("Collect - Run %d is already DONE "
2822 "or it does not exist in Shuttle logbook", run));
2823 return kTRUE;
2824 }
2825
be48e3ea 2826 for (UInt_t iDet=0; iDet<NDetectors(); iDet++)
2827 fFirstUnprocessed[iDet] = kTRUE;
2828
fc5a4708 2829 if (run != -1)
be48e3ea 2830 {
2831 // query Shuttle logbook for earlier runs, check if some detectors are unprocessed,
2832 // flag them into fFirstUnprocessed array
2833 TString whereClause(Form("where shuttle_done=0 and run < %d", run));
2834 TObjArray tmpLogbookEntries;
2835 if (!QueryShuttleLogbook(whereClause, tmpLogbookEntries))
2836 {
2837 Log("SHUTTLE", "Collect - Can't retrieve entries from Shuttle logbook");
2838 return kFALSE;
2839 }
2840
2841 TIter iter(&tmpLogbookEntries);
2842 AliShuttleLogbookEntry* anEntry = 0;
2843 while ((anEntry = dynamic_cast<AliShuttleLogbookEntry*> (iter.Next())))
2844 {
2845 for (UInt_t iDet=0; iDet<NDetectors(); iDet++)
2846 {
2847 if (anEntry->GetDetectorStatus(iDet) == AliShuttleLogbookEntry::kUnprocessed)
2848 {
2849 AliDebug(2, Form("Run %d: setting %s as \"not first time unprocessed\"",
2850 anEntry->GetRun(), GetDetName(iDet)));
2851 fFirstUnprocessed[iDet] = kFALSE;
2852 }
2853 }
2854
2855 }
2856
2857 }
2858
2859 if (!RetrieveConditionsData(shuttleLogbookEntries))
2860 {
cb343cfd 2861 Log("SHUTTLE", "Collect - Process of at least one run failed");
a3ca69fe 2862 CountOpenRuns();
2bb7b766 2863 return kFALSE;
2864 }
2865
36c99a6a 2866 Log("SHUTTLE", "Collect - Requested run(s) successfully processed");
a3ca69fe 2867 CountOpenRuns();
eba76848 2868 return kTRUE;
2bb7b766 2869}
2870
2bb7b766 2871//______________________________________________________________________________________________
2872Bool_t AliShuttle::RetrieveConditionsData(const TObjArray& dateEntries)
2873{
9827400b 2874 //
2875 // Retrieve conditions data for all runs that aren't processed yet
2876 //
2bb7b766 2877
2878 Bool_t hasError = kFALSE;
2879
2880 TIter iter(&dateEntries);
2881 AliShuttleLogbookEntry* anEntry;
2882
2883 while ((anEntry = (AliShuttleLogbookEntry*) iter.Next())){
2884 if (!Process(anEntry)){
2885 hasError = kTRUE;
2886 }
4b95672b 2887
2888 // clean SHUTTLE temp directory
d524ade6 2889 //TString filename = Form("%s/*.shuttle", GetShuttleTempDir());
2890 //RemoveFile(filename.Data());
2bb7b766 2891 }
2892
2893 return hasError == kFALSE;
2894}
cb343cfd 2895
2896//______________________________________________________________________________________________
2897ULong_t AliShuttle::GetTimeOfLastAction() const
2898{
9827400b 2899 //
2900 // Gets time of last action
2901 //
2902
cb343cfd 2903 ULong_t tmp;
36c99a6a 2904
cb343cfd 2905 fMonitoringMutex->Lock();
be48e3ea 2906
cb343cfd 2907 tmp = fLastActionTime;
36c99a6a 2908
cb343cfd 2909 fMonitoringMutex->UnLock();
36c99a6a 2910
cb343cfd 2911 return tmp;
2912}
2913
2914//______________________________________________________________________________________________
2915const TString AliShuttle::GetLastAction() const
2916{
9827400b 2917 //
cb343cfd 2918 // returns a string description of the last action
9827400b 2919 //
cb343cfd 2920
2921 TString tmp;
36c99a6a 2922
cb343cfd 2923 fMonitoringMutex->Lock();
2924
2925 tmp = fLastAction;
2926
2927 fMonitoringMutex->UnLock();
2928
36c99a6a 2929 return tmp;
cb343cfd 2930}
2931
2932//______________________________________________________________________________________________
2933void AliShuttle::SetLastAction(const char* action)
2934{
9827400b 2935 //
cb343cfd 2936 // updates the monitoring variables
9827400b 2937 //
36c99a6a 2938
cb343cfd 2939 fMonitoringMutex->Lock();
36c99a6a 2940
cb343cfd 2941 fLastAction = action;
2942 fLastActionTime = time(0);
2943
2944 fMonitoringMutex->UnLock();
2945}
eba76848 2946
2947//______________________________________________________________________________________________
2948const char* AliShuttle::GetRunParameter(const char* param)
2949{
9827400b 2950 //
2951 // returns run parameter read from DAQ logbook
2952 //
eba76848 2953
2954 if(!fLogbookEntry) {
2955 AliError("No logbook entry!");
2956 return 0;
2957 }
2958
2959 return fLogbookEntry->GetRunParameter(param);
2960}
57c1a579 2961
d386d623 2962//______________________________________________________________________________________________
9827400b 2963AliCDBEntry* AliShuttle::GetFromOCDB(const char* detector, const AliCDBPath& path)
d386d623 2964{
9827400b 2965 //
2966 // returns object from OCDB valid for current run
2967 //
d386d623 2968
9827400b 2969 if (fTestMode & kErrorOCDB)
2970 {
2971 Log(detector, "GetFromOCDB - In TESTMODE - Simulating error with OCDB");
2972 return 0;
2973 }
2974
d386d623 2975 AliCDBStorage *sto = AliCDBManager::Instance()->GetStorage(fgkMainCDB);
2976 if (!sto)
2977 {
9827400b 2978 Log(detector, "GetFromOCDB - Cannot activate main OCDB for query!");
d386d623 2979 return 0;
2980 }
2981
2982 return dynamic_cast<AliCDBEntry*> (sto->Get(path, GetCurrentRun()));
2983}
2984
57c1a579 2985//______________________________________________________________________________________________
2986Bool_t AliShuttle::SendMail()
2987{
9827400b 2988 //
2989 // sends a mail to the subdetector expert in case of preprocessor error
2990 //
2991
2992 if (fTestMode != kNone)
2993 return kTRUE;
fb40ead4 2994
2995 if (!fConfig->SendMail()) return kTRUE;
57c1a579 2996
57c1a579 2997 TString to="";
2998 TIter iterExperts(fConfig->GetResponsibles(fCurrentDetector));
2999 TObjString *anExpert=0;
3000 while ((anExpert = (TObjString*) iterExperts.Next()))
3001 {
3002 to += Form("%s,", anExpert->GetName());
3003 }
4508ab8b 3004 if (to.Length() > 0)
3005 to.Remove(to.Length()-1);
909732f7 3006 AliDebug(2, Form("to: %s",to.Data()));
57c1a579 3007
86aa42c3 3008 if (to.IsNull()) {
fb40ead4 3009 Log("SHUTTLE", "List of detector responsibles not set!");
36c99a6a 3010 return kFALSE;
3011 }
3012
fbc112e3 3013 void* dir = gSystem->OpenDirectory(GetShuttleLogDir());
3014 if (dir == NULL)
3015 {
3016 if (gSystem->mkdir(GetShuttleLogDir(), kTRUE))
3017 {
3018 Log("SHUTTLE", Form("SendMail - Can't open directory <%s>", GetShuttleLogDir()));
3019 return kFALSE;
3020 }
3021
3022 } else {
3023 gSystem->FreeDirectory(dir);
3024 }
3025
4508ab8b 3026 TString bodyFileName;
3027 bodyFileName.Form("%s/mail.body", GetShuttleLogDir());
3028 gSystem->ExpandPathName(bodyFileName);
3029
3030 ofstream mailBody;
3031 mailBody.open(bodyFileName, ofstream::out);
3032
3033 if (!mailBody.is_open())
3034 {
3035 Log("SHUTTLE", Form("Could not open mail body file %s", bodyFileName.Data()));
3036 return kFALSE;
3037 }
3038
fb40ead4 3039 TString cc="";
3040 TIter iterAdmins(fConfig->GetAdmins(AliShuttleConfig::kGlobal));
3041 TObjString *anAdmin=0;
3042 while ((anAdmin = (TObjString*) iterAdmins.Next()))
3043 {
3044 cc += Form("%s,", anAdmin->GetName());
3045 }
3046 if (cc.Length() > 0)
c19963db 3047 cc.Remove(cc.Length()-1);
fb40ead4 3048 AliDebug(2, Form("cc: %s",to.Data()));
57c1a579 3049
6a1146c4 3050 TString subject = Form("%s Shuttle preprocessor FAILED in run %d (run type = %s)!",
3051 fCurrentDetector.Data(), GetCurrentRun(), GetRunType());
909732f7 3052 AliDebug(2, Form("subject: %s", subject.Data()));
57c1a579 3053
3054 TString body = Form("Dear %s expert(s), \n\n", fCurrentDetector.Data());
3055 body += Form("SHUTTLE just detected that your preprocessor "
6a1146c4 3056 "failed processing run %d (run type = %s)!!\n\n",
3057 GetCurrentRun(), GetRunType());
7d4cf768 3058 body += Form("Please check %s status on the SHUTTLE monitoring page: \n\n",
3059 fCurrentDetector.Data());
b0e53b15 3060 if (fConfig->GetRunMode() == AliShuttleConfig::kTest)
3061 {
3062 body += Form("\thttp://pcalimonitor.cern.ch:8889/shuttle.jsp?time=168 \n\n");
3063 } else {
4508ab8b 3064 body += Form("\thttp://pcalimonitor.cern.ch/shuttle.jsp?instance=PROD&time=168 \n\n");
b0e53b15 3065 }
3066
7d4cf768 3067
3068 TString logFolder = "logs";
3069 if (fConfig->GetRunMode() == AliShuttleConfig::kProd)
3070 logFolder += "_PROD";
3071
3072
546242fb 3073 body += Form("Find the %s log for the current run on \n\n"
7d4cf768 3074 "\thttp://pcalishuttle01.cern.ch:8880/%s/%d/%s_%d.log \n\n",
3075 fCurrentDetector.Data(), logFolder.Data(), GetCurrentRun(),
3076 fCurrentDetector.Data(), GetCurrentRun());
3077 body += Form("The last 10 lines of %s log file are following:\n\n", fCurrentDetector.Data());
57c1a579 3078
909732f7 3079 AliDebug(2, Form("Body begin: %s", body.Data()));
57c1a579 3080
3081 mailBody << body.Data();
3082 mailBody.close();
3083 mailBody.open(bodyFileName, ofstream::out | ofstream::app);
3084
7d4cf768 3085 TString logFileName = Form("%s/%d/%s_%d.log", GetShuttleLogDir(),
3086 GetCurrentRun(), fCurrentDetector.Data(), GetCurrentRun());
57c1a579 3087 TString tailCommand = Form("tail -n 10 %s >> %s", logFileName.Data(), bodyFileName.Data());
3088 if (gSystem->Exec(tailCommand.Data()))
3089 {
3090 mailBody << Form("%s log file not found ...\n\n", fCurrentDetector.Data());
3091 }
3092
3093 TString endBody = Form("------------------------------------------------------\n\n");
675f64cd 3094 endBody += Form("In case of problems please contact the SHUTTLE core team.\n\n");
3095 endBody += "Please do not answer this message directly, it is automatically generated.\n\n";
3096 endBody += "Greetings,\n\n \t\t\tthe SHUTTLE\n";
3097
3098 AliDebug(2, Form("Body end: %s", endBody.Data()));
3099
3100 mailBody << endBody.Data();
3101
3102 mailBody.close();
3103
3104 // send mail!
3105 TString mailCommand = Form("mail -s \"%s\" -c %s %s < %s",
3106 subject.Data(),
3107 cc.Data(),
3108 to.Data(),
3109 bodyFileName.Data());
3110 AliDebug(2, Form("mail command: %s", mailCommand.Data()));
3111
3112 Bool_t result = gSystem->Exec(mailCommand.Data());
3113
3114 return result == 0;
3115}
3116
3117//______________________________________________________________________________________________
3118Bool_t AliShuttle::SendMailToDCS()
3119{
3120 //
fb40ead4 3121 // sends a mail to the DCS Amanda experts in case of DCS data point retrieval error
675f64cd 3122 //
3123
3124 if (fTestMode != kNone)
3125 return kTRUE;
3126
fb40ead4 3127 if (!fConfig->SendMail()) return kTRUE;
3128
675f64cd 3129 void* dir = gSystem->OpenDirectory(GetShuttleLogDir());
3130 if (dir == NULL)
3131 {
3132 if (gSystem->mkdir(GetShuttleLogDir(), kTRUE))
3133 {
3134 Log("SHUTTLE", Form("SendMailToDCS - Can't open directory <%s>", GetShuttleLogDir()));
3135 return kFALSE;
3136 }
3137
3138 } else {
3139 gSystem->FreeDirectory(dir);
3140 }
3141
3142 TString bodyFileName;
3143 bodyFileName.Form("%s/mail.body", GetShuttleLogDir());
3144 gSystem->ExpandPathName(bodyFileName);
3145
3146 ofstream mailBody;
3147 mailBody.open(bodyFileName, ofstream::out);
3148
3149 if (!mailBody.is_open())
3150 {
3151 Log("SHUTTLE", Form("SendMailToDCS - Could not open mail body file %s", bodyFileName.Data()));
3152 return kFALSE;
3153 }
3154
fb40ead4 3155 TString to="";
3156 TIter iterExperts(fConfig->GetAdmins(AliShuttleConfig::kAmanda));
3157 TObjString *anExpert=0;
3158 while ((anExpert = (TObjString*) iterExperts.Next()))
3159 {
3160 to += Form("%s,", anExpert->GetName());
3161 }
3162 if (to.Length() > 0)
3163 to.Remove(to.Length()-1);
675f64cd 3164 AliDebug(2, Form("to: %s",to.Data()));
3165
3166 if (to.IsNull()) {
fb40ead4 3167 Log("SHUTTLE", "List of Amanda server administrators not set!");
675f64cd 3168 return kFALSE;
3169 }
3170
fb40ead4 3171 TString cc="";
3172 TIter iterAdmins(fConfig->GetAdmins(AliShuttleConfig::kGlobal));
3173 TObjString *anAdmin=0;
3174 while ((anAdmin = (TObjString*) iterAdmins.Next()))
3175 {
3176 cc += Form("%s,", anAdmin->GetName());
3177 }
3178 if (cc.Length() > 0)
c19963db 3179 cc.Remove(cc.Length()-1);
fb40ead4 3180 AliDebug(2, Form("cc: %s",to.Data()));
675f64cd 3181
3182 TString subject = Form("Retrieval of data points for %s FAILED in run %d !",
3183 fCurrentDetector.Data(), GetCurrentRun());
3184 AliDebug(2, Form("subject: %s", subject.Data()));
3185
3186 TString body = Form("Dear DCS experts, \n\n");
3187 body += Form("SHUTTLE couldn\'t retrieve the data points for detector %s "
3188 "in run %d!!\n\n", fCurrentDetector.Data(), GetCurrentRun());
7d4cf768 3189 body += Form("Please check %s status on the SHUTTLE monitoring page: \n\n",
3190 fCurrentDetector.Data());
b0e53b15 3191 if (fConfig->GetRunMode() == AliShuttleConfig::kTest)
3192 {
3193 body += Form("\thttp://pcalimonitor.cern.ch:8889/shuttle.jsp?time=168 \n\n");
3194 } else {
3195 body += Form("\thttp://pcalimonitor.cern.ch/shuttle.jsp?instance=PROD?time=168 \n\n");
3196 }
7d4cf768 3197
3198 TString logFolder = "logs";
3199 if (fConfig->GetRunMode() == AliShuttleConfig::kProd)
3200 logFolder += "_PROD";
3201
3202
675f64cd 3203 body += Form("Find the %s log for the current run on \n\n"
7d4cf768 3204 "\thttp://pcalishuttle01.cern.ch:8880/%s/%d/%s_%d.log \n\n",
3205 fCurrentDetector.Data(), logFolder.Data(), GetCurrentRun(),
3206 fCurrentDetector.Data(), GetCurrentRun());
3207 body += Form("The last 10 lines of %s log file are following:\n\n", fCurrentDetector.Data());
675f64cd 3208
3209 AliDebug(2, Form("Body begin: %s", body.Data()));
3210
3211 mailBody << body.Data();
3212 mailBody.close();
3213 mailBody.open(bodyFileName, ofstream::out | ofstream::app);
3214
7d4cf768 3215 TString logFileName = Form("%s/%d/%s_%d.log", GetShuttleLogDir(), GetCurrentRun(),
3216 fCurrentDetector.Data(), GetCurrentRun());
675f64cd 3217 TString tailCommand = Form("tail -n 10 %s >> %s", logFileName.Data(), bodyFileName.Data());
3218 if (gSystem->Exec(tailCommand.Data()))
3219 {
3220 mailBody << Form("%s log file not found ...\n\n", fCurrentDetector.Data());
3221 }
3222
3223 TString endBody = Form("------------------------------------------------------\n\n");
36c99a6a 3224 endBody += Form("In case of problems please contact the SHUTTLE core team.\n\n");
3225 endBody += "Please do not answer this message directly, it is automatically generated.\n\n";
546242fb 3226 endBody += "Greetings,\n\n \t\t\tthe SHUTTLE\n";
57c1a579 3227
909732f7 3228 AliDebug(2, Form("Body end: %s", endBody.Data()));
57c1a579 3229
3230 mailBody << endBody.Data();
3231
3232 mailBody.close();
3233
3234 // send mail!
3235 TString mailCommand = Form("mail -s \"%s\" -c %s %s < %s",
3236 subject.Data(),
3237 cc.Data(),
3238 to.Data(),
3239 bodyFileName.Data());
909732f7 3240 AliDebug(2, Form("mail command: %s", mailCommand.Data()));
57c1a579 3241
3242 Bool_t result = gSystem->Exec(mailCommand.Data());
3243
3244 return result == 0;
3245}
d386d623 3246
441b0e9c 3247//______________________________________________________________________________________________
9827400b 3248const char* AliShuttle::GetRunType()
441b0e9c 3249{
9827400b 3250 //
3251 // returns run type read from "run type" logbook
3252 //
441b0e9c 3253
3254 if(!fLogbookEntry) {
3255 AliError("No logbook entry!");
3256 return 0;
3257 }
3258
9827400b 3259 return fLogbookEntry->GetRunType();
441b0e9c 3260}
3261
4859271b 3262//______________________________________________________________________________________________
3263Bool_t AliShuttle::GetHLTStatus()
3264{
3265 // Return HLT status (ON=1 OFF=0)
3266 // Converts the HLT status from the status string read in the run logbook (not just a bool)
3267
3268 if(!fLogbookEntry) {
3269 AliError("No logbook entry!");
3270 return 0;
3271 }
3272
3273 // TODO implement when HLTStatus is inserted in run logbook
3274 //TString hltStatus = fLogbookEntry->GetRunParameter("HLTStatus");
3275 //if(hltStatus == "OFF") {return kFALSE};
3276
3277 return kTRUE;
3278}
3279
d386d623 3280//______________________________________________________________________________________________
3281void AliShuttle::SetShuttleTempDir(const char* tmpDir)
3282{
9827400b 3283 //
3284 // sets Shuttle temp directory
3285 //
d386d623 3286
3287 fgkShuttleTempDir = gSystem->ExpandPathName(tmpDir);
3288}
3289
3290//______________________________________________________________________________________________
3291void AliShuttle::SetShuttleLogDir(const char* logDir)
3292{
9827400b 3293 //
3294 // sets Shuttle log directory
3295 //
d386d623 3296
3297 fgkShuttleLogDir = gSystem->ExpandPathName(logDir);
3298}