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