]> git.uio.no Git - u/mrichter/AliRoot.git/blob - STEER/AliCDBManager.cxx
Propagation of MC lables from hits up to AOD.(Philippe P.)
[u/mrichter/AliRoot.git] / STEER / AliCDBManager.cxx
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 //-------------------------------------------------------------------------
16 //   Implementation of AliCDBManager and AliCDBParam classe
17 //   Author: Alberto Colla 
18 //   e-mail: Alberto.Colla@cern.ch
19 //-------------------------------------------------------------------------
20
21 #include "AliCDBManager.h"
22 #include "AliCDBStorage.h"
23 #include "AliLog.h"
24 #include "AliCDBDump.h"
25 #include "AliCDBLocal.h"
26 #include "AliCDBGrid.h"
27 #include "AliCDBEntry.h"
28 #include "AliCDBMetaData.h"
29 #include "AliCDBHandler.h"
30
31 #include <TObjString.h>
32 #include <TSystem.h>
33 #include <TSAXParser.h>
34 #include <TFile.h>
35 #include <TUUID.h>
36
37 ClassImp(AliCDBParam)
38
39 ClassImp(AliCDBManager)
40
41 //TODO OCDB and Reference folder should not be fully hardcoded but built from run number (or year/LHC period)
42 TString AliCDBManager::fgkCondUri("alien://folder=/alice/cern.ch/user/a/aliprod/testCDB/CDB?user=aliprod");
43 TString AliCDBManager::fgkRefUri("alien://folder=/alice/cern.ch/user/a/aliprod/testCDB/Reference?user=aliprod");
44 TString AliCDBManager::fgkMCIdealStorage("alien://folder=/alice/simulation/2008/v4-15-Release/Ideal");
45 TString AliCDBManager::fgkMCFullStorage("alien://folder=/alice/simulation/2008/v4-15-Release/Full");
46 TString AliCDBManager::fgkMCResidualStorage("alien://folder=/alice/simulation/2008/v4-15-Release/Residual");
47 TString AliCDBManager::fgkOCDBFolderXMLfile("alien:///alice/data/OCDBFoldervsRunRange.xml");
48 AliCDBManager* AliCDBManager::fgInstance = 0x0;
49
50 //_____________________________________________________________________________
51 AliCDBManager* AliCDBManager::Instance(TMap *entryCache, Int_t run)
52 {
53 // returns AliCDBManager instance (singleton)
54
55         if (!fgInstance) {
56                 fgInstance = new AliCDBManager();
57                 if (!entryCache)
58                   fgInstance->Init();
59                 else
60                   fgInstance->InitFromCache(entryCache,run);
61         }
62
63         return fgInstance;
64 }
65
66 //_____________________________________________________________________________
67 void AliCDBManager::Init() {
68 // factory registering
69
70         RegisterFactory(new AliCDBDumpFactory());
71         RegisterFactory(new AliCDBLocalFactory()); 
72         // AliCDBGridFactory is registered only if AliEn libraries are enabled in Root
73         if(!gSystem->Exec("root-config --has-alien |grep yes 2>&1 > /dev/null")){ // returns 0 if yes
74                 AliInfo("AliEn classes enabled in Root. AliCDBGrid factory registered.");
75                 RegisterFactory(new AliCDBGridFactory());
76                 fCondParam = CreateParameter(fgkCondUri);
77                 fRefParam = CreateParameter(fgkRefUri);
78         }
79
80         InitShortLived();
81 }
82
83 //_____________________________________________________________________________
84 void AliCDBManager::InitFromCache(TMap *entryCache, Int_t run) {
85 // initialize manager from existing cache
86 // used on the slaves in case of parallel reconstruction
87   SetRun(run);
88
89   TIter iter(entryCache->GetTable());
90   TPair* pair = 0;
91
92   while((pair = dynamic_cast<TPair*> (iter.Next()))){
93     fEntryCache.Add(pair->Key(),pair->Value());
94   }
95   // fEntry is the new owner of the cache
96   fEntryCache.SetOwnerKeyValue(kTRUE,kTRUE);
97   AliInfo(Form("%d cache entries have been loaded",fEntryCache.GetEntries()));
98 }
99
100 //_____________________________________________________________________________
101 void AliCDBManager::Destroy() {
102 // delete ALCDBManager instance and active storages
103
104         if (fgInstance) {
105                 //fgInstance->Delete();
106                 delete fgInstance;
107                 fgInstance = 0x0;
108         }
109 }
110
111 //_____________________________________________________________________________
112 AliCDBManager::AliCDBManager():
113   TObject(),
114   fFactories(),
115   fActiveStorages(),
116   fSpecificStorages(),
117   fEntryCache(),
118   fIds(0),
119   fStorageMap(0),
120   fShortLived(0),
121   fDefaultStorage(NULL),
122   fDrainStorage(NULL),
123   fCondParam(0),
124   fRefParam(0),
125   fRun(-1),
126   fCache(kTRUE),
127   fLock(kFALSE),
128   fRaw(kFALSE),
129   fStartRunLHCPeriod(-1),
130   fEndRunLHCPeriod(-1),
131   fLHCPeriod("")
132 {
133 // default constuctor
134         fFactories.SetOwner(1);
135         fActiveStorages.SetOwner(1);
136         fSpecificStorages.SetOwner(1);
137         fEntryCache.SetName("CDBEntryCache");
138         fEntryCache.SetOwner(1);
139
140         fStorageMap = new TMap();
141         fStorageMap->SetOwner(1);
142         fIds = new TList();
143         fIds->SetOwner(1);
144 }
145
146 //_____________________________________________________________________________
147 AliCDBManager::~AliCDBManager() {
148 // destructor
149         ClearCache();
150         DestroyActiveStorages();
151         fFactories.Delete();
152         fDrainStorage = 0x0;
153         fDefaultStorage = 0x0;
154         delete fStorageMap; fStorageMap = 0;
155         delete fIds; fIds = 0;
156         delete fCondParam;
157         delete fRefParam;
158         delete fShortLived; fShortLived = 0x0;
159 }
160
161 //_____________________________________________________________________________
162 void AliCDBManager::PutActiveStorage(AliCDBParam* param, AliCDBStorage* storage){
163 // put a storage object into the list of active storages
164
165         fActiveStorages.Add(param, storage);
166         AliDebug(1, Form("Active storages: %d", fActiveStorages.GetEntries()));
167 }
168
169 //_____________________________________________________________________________
170 void AliCDBManager::RegisterFactory(AliCDBStorageFactory* factory) {
171 // add a storage factory to the list of registerd factories
172  
173         if (!fFactories.Contains(factory)) {
174                 fFactories.Add(factory);
175         }
176 }
177
178 //_____________________________________________________________________________
179 Bool_t AliCDBManager::HasStorage(const char* dbString) const {
180 // check if dbString is a URI valid for one of the registered factories
181
182         TIter iter(&fFactories);
183
184         AliCDBStorageFactory* factory=0;
185         while ((factory = (AliCDBStorageFactory*) iter.Next())) {
186
187                 if (factory->Validate(dbString)) {
188                         return kTRUE;
189                 }
190         }
191
192         return kFALSE;
193 }
194
195 //_____________________________________________________________________________
196 AliCDBParam* AliCDBManager::CreateParameter(const char* dbString) const {
197 // create AliCDBParam object from URI string
198
199         TIter iter(&fFactories);
200
201         AliCDBStorageFactory* factory=0;
202         while ((factory = (AliCDBStorageFactory*) iter.Next())) {
203                 AliCDBParam* param = factory->CreateParameter(dbString);
204                 if(param) return param;
205         }
206
207         return NULL;
208 }
209
210 //_____________________________________________________________________________
211 AliCDBStorage* AliCDBManager::GetStorage(const char* dbString) {
212 // get storage object from URI string
213                 
214         AliCDBParam* param = CreateParameter(dbString);
215         if (!param) {
216                 AliError(Form("Failed to activate requested storage! Check URI: %s", dbString));
217                 return NULL;
218         }
219
220         AliCDBStorage* aStorage = GetStorage(param);
221
222         delete param;
223         return aStorage;
224 }
225
226 //_____________________________________________________________________________
227 AliCDBStorage* AliCDBManager::GetStorage(const AliCDBParam* param) {
228 // get storage object from AliCDBParam object
229         
230         // if the list of active storages already contains
231         // the requested storage, return it
232         AliCDBStorage* aStorage = GetActiveStorage(param);
233         if (aStorage) {
234                 return aStorage;
235         }
236
237         // if lock is ON, cannot activate more storages!
238         if(fLock) {
239                 if (fDefaultStorage) {
240                         AliFatal("Lock is ON, and default storage is already set: "
241                                 "cannot reset it or activate more storages!");
242                 }
243         }       
244         
245         TIter iter(&fFactories);
246
247         AliCDBStorageFactory* factory=0;
248
249         // loop on the list of registered factories
250         while ((factory = (AliCDBStorageFactory*) iter.Next())) {
251
252                 // each factory tries to create its storage from the parameter
253                 aStorage = factory->Create(param);
254                 if (aStorage) {
255                         PutActiveStorage(param->CloneParam(), aStorage);
256                         aStorage->SetURI(param->GetURI());
257                         if(fRun >= 0) {
258                                 if(aStorage->GetType() == "alien"){
259                                         aStorage->QueryCDB(fRun);
260                                 } else {
261                                         AliDebug(2,
262                                                 "Skipping query for valid files, it is used only in grid...");
263                                 }
264                         }
265                         return aStorage;
266                 }
267         }
268
269         AliError(Form("Failed to activate requested storage! Check URI: %s", param->GetURI().Data()));
270
271         return NULL;
272 }
273
274 //_____________________________________________________________________________
275 AliCDBStorage* AliCDBManager::GetActiveStorage(const AliCDBParam* param) {
276 // get a storage object from the list of active storages
277
278         return dynamic_cast<AliCDBStorage*> (fActiveStorages.GetValue(param));
279 }
280
281 //_____________________________________________________________________________
282 TList* AliCDBManager::GetActiveStorages() {
283 // return list of active storages
284 // user has responsibility to delete returned object
285
286         TList* result = new TList();
287
288         TIter iter(fActiveStorages.GetTable());
289         TPair* aPair=0;
290         while ((aPair = (TPair*) iter.Next())) {
291                 result->Add(aPair->Value());
292         }
293
294         return result;
295 }
296
297 //_____________________________________________________________________________
298 void AliCDBManager::SetDrain(const char* dbString) {
299 // set drain storage from URI string
300
301         fDrainStorage = GetStorage(dbString);   
302 }
303
304 //_____________________________________________________________________________
305 void AliCDBManager::SetDrain(const AliCDBParam* param) {
306 // set drain storage from AliCDBParam
307
308         fDrainStorage = GetStorage(param);
309 }
310
311 //_____________________________________________________________________________
312 void AliCDBManager::SetDrain(AliCDBStorage* storage) {
313 // set drain storage from another active storage
314         
315         fDrainStorage = storage;
316 }
317
318 //_____________________________________________________________________________
319 Bool_t AliCDBManager::Drain(AliCDBEntry *entry) {
320 // drain retrieved object to drain storage
321
322         AliDebug(2, "Draining into drain storage...");
323         return fDrainStorage->Put(entry);
324 }
325
326 //____________________________________________________________________________
327 void AliCDBManager::SetDefaultStorage(const char* dbString) {
328 // sets default storage from URI string
329         
330         AliInfo(Form("Setting Default storage to: %s",dbString));
331
332         // checking whether we are in the raw case
333         TString dbStringTemp(dbString);
334         if (dbStringTemp == "raw://") fRaw = kTRUE;
335
336         AliCDBStorage* bckStorage = fDefaultStorage;
337         
338         fDefaultStorage = GetStorage(dbString);
339         
340         if(!fDefaultStorage) return;
341         
342         if(bckStorage && (fDefaultStorage != bckStorage)){
343                 AliWarning("Existing default storage replaced: clearing cache!");
344                 ClearCache();
345         }
346         
347         if (fStorageMap->Contains("default")) {
348                 delete fStorageMap->Remove(fStorageMap->GetValue("default"));
349         }
350         fStorageMap->Add(new TObjString("default"), new TObjString(fDefaultStorage->GetURI()));
351 }
352 //_____________________________________________________________________________
353 void AliCDBManager::SetDefaultStorage(const AliCDBParam* param) {
354 // set default storage from AliCDBParam object
355         
356         AliCDBStorage* bckStorage = fDefaultStorage;
357
358         fDefaultStorage = GetStorage(param);
359
360         if(!fDefaultStorage) return;
361
362         if(bckStorage && (fDefaultStorage != bckStorage)){
363                 AliWarning("Existing default storage replaced: clearing cache!");
364                 ClearCache();
365         }
366
367         if (fStorageMap->Contains("default")) {
368                 delete fStorageMap->Remove(fStorageMap->GetValue("default"));
369         }
370         fStorageMap->Add(new TObjString("default"), new TObjString(fDefaultStorage->GetURI()));
371 }
372
373 //_____________________________________________________________________________
374 void AliCDBManager::SetDefaultStorage(AliCDBStorage* storage) {
375 // set default storage from another active storage
376         
377         // if lock is ON, cannot activate more storages!
378         if(fLock) {
379                 if (fDefaultStorage) {
380                         AliFatal("Lock is ON, and default storage is already set: "
381                                 "cannot reset it or activate more storages!");
382                 }
383         }       
384         
385         if (!storage) {
386                 UnsetDefaultStorage();
387                 return;
388         }
389         
390         AliCDBStorage* bckStorage = fDefaultStorage;
391
392         fDefaultStorage = storage;
393
394         if(bckStorage && (fDefaultStorage != bckStorage)){
395                 AliWarning("Existing default storage replaced: clearing cache!");
396                 ClearCache();
397         }
398
399         if (fStorageMap->Contains("default")) {
400                 delete fStorageMap->Remove(fStorageMap->GetValue("default"));
401         }
402         fStorageMap->Add(new TObjString("default"), new TObjString(fDefaultStorage->GetURI()));
403 }
404
405 //_____________________________________________________________________________
406 void AliCDBManager::SetDefaultStorage(const char* mcString, const char* simType) {
407 // sets default storage for MC data
408 // mcString MUST be "MC", 
409 // simType can be "Ideal","Residual","Full"
410         
411         TString strmcString(mcString);
412         TString strsimType(simType);
413         TString dbString; 
414         if (strmcString != "MC"){
415                 AliFatal("Method requires first string to be MC!");
416         }
417         else {
418                 if (strsimType == "Ideal"){
419                         dbString = fgkMCIdealStorage;
420                 }
421                 else if (strsimType == "Full"){
422                         dbString = fgkMCFullStorage;
423                 }
424                 else if (strsimType == "Residual"){
425                         dbString = fgkMCResidualStorage;
426                 }
427                 else {
428                         AliFatal("Error in setting the storage for MC data, second argument MUST be either \"Ideal\" or \"Full\" or \"Residual\".");
429                 }
430
431                 SetDefaultStorage(dbString.Data());
432                 if(!fDefaultStorage) AliFatal(Form("%s storage not there! Please check!",fLHCPeriod.Data()));
433         }
434 }
435 //_____________________________________________________________________________
436 void AliCDBManager::SetDefaultStorageFromRun(Int_t run) {
437 // set default storage from the run number - to be used only with raw data      
438
439         // if lock is ON, cannot activate more storages!
440         if(fLock) {
441                 if (fDefaultStorage) {
442                         AliFatal("Lock is ON, and default storage is already set: "
443                                 "cannot activate default storage from run number");
444                 }
445         }       
446
447         // retrieve XML file from alien
448         TUUID uuid;
449         TString rndname = "/tmp/";
450         rndname += "OCDBFolderXML.";
451         rndname += uuid.AsString();
452         rndname += ".xml";
453         AliDebug(2, Form("file to be copied = %s", fgkOCDBFolderXMLfile.Data()));
454         if (!TFile::Cp(fgkOCDBFolderXMLfile.Data(), rndname.Data())) {
455                 AliFatal(Form("Cannot make a local copy of OCDBFolder xml file in %s",rndname.Data()));
456         }
457         AliCDBHandler* saxcdb = new AliCDBHandler();
458         saxcdb->SetRun(run);
459         TSAXParser *saxParser = new TSAXParser();
460         saxParser->ConnectToHandler("AliCDBHandler", saxcdb);  
461         saxParser->ParseFile(rndname.Data()); 
462         AliInfo(Form(" LHC folder = %s", saxcdb->GetOCDBFolder().Data()));
463         AliInfo(Form(" LHC period start run = %d", saxcdb->GetStartRunRange()));
464         AliInfo(Form(" LHC period end run = %d", saxcdb->GetEndRunRange()));
465         fLHCPeriod = saxcdb->GetOCDBFolder();
466         fStartRunLHCPeriod = saxcdb->GetStartRunRange();
467         fEndRunLHCPeriod = saxcdb->GetEndRunRange();
468
469         SetDefaultStorage(fLHCPeriod.Data());
470         if(!fDefaultStorage) AliFatal(Form("%s storage not there! Please check!",fLHCPeriod.Data()));
471
472 }
473
474 //_____________________________________________________________________________
475 void AliCDBManager::UnsetDefaultStorage() {
476 // Unset default storage
477         
478         // if lock is ON, action is forbidden!
479         if(fLock) {
480                 if (fDefaultStorage) {
481                         AliFatal("Lock is ON: cannot unset default storage!");
482                 }
483         }
484         
485         if (fDefaultStorage) {
486                 AliWarning("Clearing cache!");
487                 ClearCache();
488         }
489         
490         fDefaultStorage = 0x0;
491 }
492
493 //_____________________________________________________________________________
494 void AliCDBManager::SetSpecificStorage(const char* calibType, const char* dbString) {
495 // sets storage specific for detector or calibration type (works with AliCDBManager::Get(...))
496
497         AliCDBParam *aPar = CreateParameter(dbString);
498         if(!aPar) return;
499         SetSpecificStorage(calibType, aPar);
500         delete aPar;
501 }
502
503 //_____________________________________________________________________________
504 void AliCDBManager::SetSpecificStorage(const char* calibType, AliCDBParam* param) {
505 // sets storage specific for detector or calibration type (works with AliCDBManager::Get(...))
506 // Default storage should be defined prior to any specific storages, e.g.:
507 // AliCDBManager::instance()->SetDefaultStorage("alien://");
508 // AliCDBManager::instance()->SetSpecificStorage("TPC/*","local://DB_TPC");
509 // AliCDBManager::instance()->SetSpecificStorage("*/Align/*","local://DB_TPCAlign");
510 // calibType must be a valid CDB path! (3 level folder structure)
511
512
513         if(!fDefaultStorage) {
514                 AliError("Please activate a default storage first!");
515                 return;
516         }
517
518
519         AliCDBPath aPath(calibType);
520         if(!aPath.IsValid()){
521                 AliError(Form("Not a valid path: %s", calibType));
522                 return;
523         }
524
525         TObjString *objCalibType = new TObjString(aPath.GetPath());
526         if(fSpecificStorages.Contains(objCalibType)){
527                 AliWarning(Form("Storage \"%s\" already activated! It will be replaced by the new one",
528                                         calibType));
529                 AliCDBParam *checkPar = dynamic_cast<AliCDBParam*> (fSpecificStorages.GetValue(calibType));
530                 if(checkPar) delete checkPar;
531                 delete fSpecificStorages.Remove(objCalibType);
532         }
533         AliCDBStorage *aStorage = GetStorage(param);
534         if(!aStorage) return;
535
536         fSpecificStorages.Add(objCalibType, param->CloneParam());
537
538         if(fStorageMap->Contains(objCalibType)){
539                 delete fStorageMap->Remove(objCalibType);
540         }
541         fStorageMap->Add(objCalibType->Clone(), new TObjString(param->GetURI()));
542
543 }
544
545 //_____________________________________________________________________________
546 AliCDBStorage* AliCDBManager::GetSpecificStorage(const char* calibType) {
547 // get storage specific for detector or calibration type 
548
549         AliCDBPath calibPath(calibType);
550         if(!calibPath.IsValid()) return NULL;
551
552         AliCDBParam *checkPar = (AliCDBParam*) fSpecificStorages.GetValue(calibPath.GetPath());
553         if(!checkPar){
554                 AliError(Form("%s storage not found!", calibType));
555                 return NULL;
556         } else {
557                 return GetStorage(checkPar);
558         }
559
560 }
561
562 //_____________________________________________________________________________
563 AliCDBParam* AliCDBManager::SelectSpecificStorage(const TString& path) {
564 // select storage valid for path from the list of specific storages
565
566         AliCDBPath aPath(path);
567         if(!aPath.IsValid()) return NULL;
568
569         TIter iter(&fSpecificStorages);
570         TObjString *aCalibType=0;
571         AliCDBPath tmpPath("null/null/null");
572         AliCDBParam* aPar=0;
573         while((aCalibType = (TObjString*) iter.Next())){
574                 AliCDBPath calibTypePath(aCalibType->GetName());
575                 if(calibTypePath.Comprises(aPath)) {
576                         if(calibTypePath.Comprises(tmpPath)) continue;
577                         aPar = (AliCDBParam*) fSpecificStorages.GetValue(aCalibType);
578                         tmpPath.SetPath(calibTypePath.GetPath());
579                 }
580         }
581         return aPar;
582 }
583
584 //_____________________________________________________________________________
585 AliCDBEntry* AliCDBManager::Get(const AliCDBPath& path, Int_t runNumber,
586         Int_t version, Int_t subVersion) {
587 // get an AliCDBEntry object from the database
588
589         if(runNumber < 0){
590                 // RunNumber is not specified. Try with fRun
591                 if (fRun < 0){
592                         AliError("Run number neither specified in query nor set in AliCDBManager! Use AliCDBManager::SetRun.");
593                         return NULL;
594                 }
595                 runNumber = fRun;
596         }
597
598         return Get(AliCDBId(path, runNumber, runNumber, version, subVersion));
599 }
600
601 //_____________________________________________________________________________
602 AliCDBEntry* AliCDBManager::Get(const AliCDBPath& path,
603         const AliCDBRunRange& runRange, Int_t version,
604         Int_t subVersion) {
605 // get an AliCDBEntry object from the database!
606
607         return Get(AliCDBId(path, runRange, version, subVersion));
608 }
609
610 //_____________________________________________________________________________
611 AliCDBEntry* AliCDBManager::Get(const AliCDBId& query) {
612 // get an AliCDBEntry object from the database
613         
614         // check if query's path and runRange are valid
615         // query is invalid also if version is not specified and subversion is!
616         if (!query.IsValid()) {
617                 AliError(Form("Invalid query: %s", query.ToString().Data()));
618                 return NULL;
619         }
620         
621         // query is not specified if path contains wildcard or run range= [-1,-1]
622         if (!query.IsSpecified()) {
623                 AliError(Form("Unspecified query: %s",
624                                 query.ToString().Data()));
625                 return NULL;
626         }
627
628         if(fLock && query.GetFirstRun() != fRun)
629                 AliFatal("Lock is ON: cannot use different run number than the internal one!");
630         
631         if(fCache && query.GetFirstRun() != fRun)
632                 AliWarning("Run number explicitly set in query: CDB cache temporarily disabled!");
633
634         AliCDBEntry *entry=0;
635
636         // first look into map of cached objects
637         if(fCache && query.GetFirstRun() == fRun)
638                 entry = (AliCDBEntry*) fEntryCache.GetValue(query.GetPath());
639
640         if(entry) {
641                 AliDebug(2, Form("Object %s retrieved from cache !!",query.GetPath().Data()));
642                 return entry;
643         }
644
645         if(!fDefaultStorage) {
646                 AliError("No storage set!");
647                 return NULL;
648         }
649         // Entry is not in cache -> retrieve it from CDB and cache it!!
650         AliCDBStorage *aStorage=0;
651         AliCDBParam *aPar=SelectSpecificStorage(query.GetPath());
652 //      Bool_t usedDefStorage=kTRUE;
653
654         if(aPar) {
655                 aStorage=GetStorage(aPar);
656                 TString str = aPar->GetURI();
657                 AliDebug(2,Form("Looking into storage: %s",str.Data()));
658 //              usedDefStorage=kFALSE;
659
660         } else {
661                 aStorage=GetDefaultStorage();
662                 AliDebug(2,"Looking into default storage");
663         }
664
665         entry = aStorage->Get(query);
666
667         if(entry && fCache && (query.GetFirstRun() == fRun)){
668                 CacheEntry(query.GetPath(), entry);
669         }
670
671         if(entry && !fIds->Contains(&entry->GetId())){
672                 fIds->Add(entry->GetId().Clone());
673         }
674
675
676         return entry;
677
678 }
679
680 //_____________________________________________________________________________
681 const char* AliCDBManager::GetURI(const char* path) {
682 // return the URI of the storage where to look for path
683
684         if(!IsDefaultStorageSet()) return 0;
685         
686         AliCDBParam *aPar=SelectSpecificStorage(path);
687
688         if(aPar) {
689                 return aPar->GetURI().Data();
690
691         } else {
692                 return GetDefaultStorage()->GetURI().Data();
693         }
694         
695         return 0;
696 }
697
698 //_____________________________________________________________________________
699 AliCDBId* AliCDBManager::GetId(const AliCDBPath& path, Int_t runNumber,
700         Int_t version, Int_t subVersion) {
701 // get the AliCDBId of the valid object from the database (does not retrieve the object)
702 // User must delete returned object!
703
704         if(runNumber < 0){
705                 // RunNumber is not specified. Try with fRun
706                 if (fRun < 0){
707                         AliError("Run number neither specified in query nor set in AliCDBManager! Use AliCDBManager::SetRun.");
708                         return NULL;
709                 }
710                 runNumber = fRun;
711         }
712
713         return GetId(AliCDBId(path, runNumber, runNumber, version, subVersion));
714 }
715
716 //_____________________________________________________________________________
717 AliCDBId* AliCDBManager::GetId(const AliCDBPath& path,
718         const AliCDBRunRange& runRange, Int_t version,
719         Int_t subVersion) {
720 // get the AliCDBId of the valid object from the database (does not retrieve the object)
721 // User must delete returned object!
722
723         return GetId(AliCDBId(path, runRange, version, subVersion));
724 }
725
726 //_____________________________________________________________________________
727 AliCDBId* AliCDBManager::GetId(const AliCDBId& query) {
728 // get the AliCDBId of the valid object from the database (does not retrieve the object)
729 // User must delete returned object!
730
731         if(!fDefaultStorage) {
732                 AliError("No storage set!");
733                 return NULL;
734         }
735
736         // check if query's path and runRange are valid
737         // query is invalid also if version is not specified and subversion is!
738         if (!query.IsValid()) {
739                 AliError(Form("Invalid query: %s", query.ToString().Data()));
740                 return NULL;
741         }
742         
743         // query is not specified if path contains wildcard or run range= [-1,-1]
744         if (!query.IsSpecified()) {
745                 AliError(Form("Unspecified query: %s",
746                                 query.ToString().Data()));
747                 return NULL;
748         }
749
750         if(fCache && query.GetFirstRun() != fRun)
751                 AliWarning("Run number explicitly set in query: CDB cache temporarily disabled!");
752
753         AliCDBEntry* entry = 0;
754
755         // first look into map of cached objects
756         if(fCache && query.GetFirstRun() == fRun)
757                 entry = (AliCDBEntry*) fEntryCache.GetValue(query.GetPath());
758
759         if(entry) {
760                 AliDebug(2, Form("Object %s retrieved from cache !!",query.GetPath().Data()));
761                 return dynamic_cast<AliCDBId*> (entry->GetId().Clone());
762         }
763
764         // Entry is not in cache -> retrieve it from CDB and cache it!!
765         AliCDBStorage *aStorage=0;
766         AliCDBParam *aPar=SelectSpecificStorage(query.GetPath());
767
768         if(aPar) {
769                 aStorage=GetStorage(aPar);
770                 TString str = aPar->GetURI();
771                 AliDebug(2,Form("Looking into storage: %s",str.Data()));
772                 
773         } else {
774                 aStorage=GetDefaultStorage();
775                 AliDebug(2,"Looking into default storage");
776         }
777
778         return aStorage->GetId(query);
779
780 }
781
782 //_____________________________________________________________________________
783 TList* AliCDBManager::GetAll(const AliCDBPath& path, Int_t runNumber,
784         Int_t version, Int_t subVersion) {
785 // get multiple AliCDBEntry objects from the database
786
787         if(runNumber < 0){
788                 // RunNumber is not specified. Try with fRun
789                 if (fRun < 0){
790                         AliError("Run number neither specified in query nor set in AliCDBManager! Use AliCDBManager::SetRun.");
791                         return NULL;
792                 }
793                 runNumber = fRun;
794         }
795
796         return GetAll(AliCDBId(path, runNumber, runNumber, version,     
797                         subVersion));
798 }
799
800 //_____________________________________________________________________________
801 TList* AliCDBManager::GetAll(const AliCDBPath& path,
802         const AliCDBRunRange& runRange, Int_t version, Int_t subVersion) {
803 // get multiple AliCDBEntry objects from the database
804
805         return GetAll(AliCDBId(path, runRange, version, subVersion));
806 }
807
808 //_____________________________________________________________________________
809 TList* AliCDBManager::GetAll(const AliCDBId& query) {
810 // get multiple AliCDBEntry objects from the database
811 // Warning: this method works correctly only for queries of the type "Detector/*"
812 //              and not for more specific queries e.g. "Detector/Calib/*" !
813 // Warning #2: Entries are cached, but GetAll will keep on retrieving objects from OCDB!
814 //              To get an object from cache use Get() function
815
816         if(!fDefaultStorage) {
817                 AliError("No storage set!");
818                 return NULL;
819         }
820
821         if (!query.IsValid()) {
822                 AliError(Form("Invalid query: %s", query.ToString().Data()));
823                 return NULL;
824         }
825
826         if((fSpecificStorages.GetEntries()>0) && query.GetPath().BeginsWith('*')){
827                 // if specific storages are active a query with "*" is ambiguous
828                 AliError("Query too generic in this context!");
829                 return NULL;
830         }
831
832         if (query.IsAnyRange()) {
833                 AliError(Form("Unspecified run or runrange: %s",
834                                 query.ToString().Data()));
835                 return NULL;
836         }
837
838         if(fLock && query.GetFirstRun() != fRun)
839                 AliFatal("Lock is ON: cannot use different run number than the internal one!");
840         
841         AliCDBParam *aPar=SelectSpecificStorage(query.GetPath());
842
843         AliCDBStorage *aStorage;
844         if(aPar) {
845                 aStorage=GetStorage(aPar);
846                 AliDebug(2,Form("Looking into storage: %s", aPar->GetURI().Data()));
847
848         } else {
849                 aStorage=GetDefaultStorage();
850                 AliDebug(2,"Looking into default storage");
851         }
852
853         TList *result = 0;
854         if(aStorage) result = aStorage->GetAll(query);
855         if(!result) return 0;
856
857        // loop on result to check whether entries should be re-queried with specific storages
858         if(fSpecificStorages.GetEntries()>0 && ! (fSpecificStorages.GetEntries() == 1 && aPar)) {
859                 AliInfo("Now look into all other specific storages...");
860
861                 TIter iter(result);
862                 AliCDBEntry* chkEntry=0;
863
864                 while((chkEntry = dynamic_cast<AliCDBEntry*> (iter.Next()))){
865                         AliCDBId& chkId = chkEntry->GetId();
866                         AliDebug(2, Form("Checking id %s ", chkId.GetPath().Data()));
867                         AliCDBParam *chkPar=SelectSpecificStorage(chkId.GetPath());
868                         if (!chkPar || aPar == chkPar) continue;
869                         AliCDBStorage *chkStorage = GetStorage(chkPar);
870                         AliDebug(2, Form("Found specific storage! %s", chkPar->GetURI().Data()));
871
872                         AliCDBEntry *newEntry=0;
873                         chkId.SetRunRange(query.GetFirstRun(), query.GetLastRun());
874                         chkId.SetVersion(query.GetVersion());
875                         chkId.SetSubVersion(query.GetSubVersion());
876
877                         if(chkStorage) newEntry = chkStorage->Get(chkId);
878                         if(!newEntry) continue;
879
880                         // object is found in specific storage: replace entry in the result list!
881                         chkEntry->SetOwner(1);
882                         delete result->Remove(chkEntry);
883                         result->AddFirst(newEntry);
884                 }
885
886                 Int_t nEntries = result->GetEntries();
887                 AliInfo("After look into other specific storages, result list is:");
888                 for(int i=0; i<nEntries;i++){
889                         AliCDBEntry *entry = (AliCDBEntry*) result->At(i);
890                         AliInfo(Form("%s",entry->GetId().ToString().Data()));
891                 }
892         }
893
894         // caching entries
895         TIter iter(result);
896         AliCDBEntry* entry=0;
897         while((entry = dynamic_cast<AliCDBEntry*> (iter.Next()))){
898
899                 if(!fIds->Contains(&entry->GetId())){
900                         fIds->Add(entry->GetId().Clone());
901                 }
902                 if(fCache && (query.GetFirstRun() == fRun)){
903                         CacheEntry(entry->GetId().GetPath(), entry);
904                 }
905         }
906
907
908         return result;
909 }
910
911 //_____________________________________________________________________________
912 Bool_t AliCDBManager::Put(TObject* object, AliCDBId& id,  AliCDBMetaData* metaData, DataType type){
913 // store an AliCDBEntry object into the database
914
915         if (object==0x0) {
916                 AliError("Null Entry! No storage will be done!");
917                 return kFALSE;
918         } 
919
920         AliCDBEntry anEntry(object, id, metaData);
921         return Put(&anEntry, type);
922
923 }
924
925
926 //_____________________________________________________________________________
927 Bool_t AliCDBManager::Put(AliCDBEntry* entry, DataType type){
928 // store an AliCDBEntry object into the database
929
930         if(type == kPrivate && !fDefaultStorage) {
931                 AliError("No storage set!");
932                 return kFALSE;
933         }
934
935         if (entry->GetObject()==0x0){
936                 AliError("No valid object in CDB entry!");
937                 return kFALSE;
938         }
939
940         if (!entry){
941                 AliError("No entry!");
942                 return kFALSE;
943         }
944
945         if (!entry->GetId().IsValid()) {
946                 AliError(Form("Invalid entry ID: %s", 
947                         entry->GetId().ToString().Data()));
948                 return kFALSE;
949         }       
950
951         if (!entry->GetId().IsSpecified()) {
952                 AliError(Form("Unspecified entry ID: %s", 
953                         entry->GetId().ToString().Data()));
954                 return kFALSE;
955         }
956
957         AliCDBId id = entry->GetId();
958         AliCDBParam *aPar = SelectSpecificStorage(id.GetPath());
959
960         AliCDBStorage *aStorage=0;
961         
962         if(aPar) {
963                 aStorage=GetStorage(aPar);
964         } else {
965                 switch(type){
966                         case kCondition:
967                                 aStorage = GetStorage(fCondParam);
968                                 break;
969                         case kReference:
970                                 aStorage = GetStorage(fRefParam);
971                                 break;
972                         case kPrivate:
973                                 aStorage = GetDefaultStorage();
974                                 break;
975                 }
976         }
977
978         AliDebug(2,Form("Storing object into storage: %s", aStorage->GetURI().Data()));
979
980         Bool_t result = aStorage->Put(entry, type);
981
982         if(fRun >= 0) QueryCDB();
983
984         return result;
985
986
987 }
988
989 //_____________________________________________________________________________
990 void AliCDBManager::CacheEntry(const char* path, AliCDBEntry* entry)
991 {
992 // cache AliCDBEntry. Cache is valid until run number is changed.
993
994         AliCDBEntry *chkEntry = dynamic_cast<AliCDBEntry*> (fEntryCache.GetValue(path));
995
996         if(chkEntry) {
997                 AliDebug(2, Form("Object %s already in cache !!", path));
998                 return;
999         } else {
1000                 AliDebug(2,Form("Caching entry %s", path));
1001         }
1002
1003         fEntryCache.Add(new TObjString(path), entry);
1004         AliDebug(2,Form("Cache entries: %d", fEntryCache.GetEntries()));
1005
1006 }
1007
1008 //_____________________________________________________________________________
1009 void AliCDBManager::Print(Option_t* /*option*/) const
1010 {
1011 // Print list of active storages and their URIs
1012
1013         TString output=Form("Run number = %d; ",fRun);
1014         output += "Cache is ";
1015         if(!fCache) output += "NOT ";
1016         output += Form("ACTIVE; Number of active storages: %d\n",fActiveStorages.GetEntries());
1017
1018         if(fDefaultStorage) {
1019                 output += Form("\t*** Default Storage URI: \"%s\"\n",fDefaultStorage->GetURI().Data());
1020 //              AliInfo(output.Data());
1021         }
1022         if(fSpecificStorages.GetEntries()>0) {
1023                 TIter iter(fSpecificStorages.GetTable());
1024                 TPair *aPair=0;
1025                 Int_t i=1;
1026                 while((aPair = (TPair*) iter.Next())){
1027                         output += Form("\t*** Specific storage %d: Path \"%s\" -> URI \"%s\"\n",
1028                                 i++, ((TObjString*) aPair->Key())->GetName(),
1029                                 ((AliCDBParam*) aPair->Value())->GetURI().Data());
1030                 }
1031         }
1032         if(fDrainStorage) {
1033                 output += Form("*** Drain Storage URI: %s\n",fDrainStorage->GetURI().Data());
1034         }
1035         AliInfo(output.Data());
1036 }
1037
1038 //_____________________________________________________________________________
1039 void AliCDBManager::SetRun(Int_t run)
1040 {
1041 // Sets current run number.
1042 // When the run number changes the caching is cleared.
1043         
1044         if (fRun == run)
1045                 return;
1046   
1047         if(fLock && fRun >= 0) {
1048                 AliFatal("Lock is ON, cannot reset run number!");
1049         }       
1050                 
1051         fRun = run;
1052         if (fRaw){
1053                 // here the LHCPeriod xml file is parsed; the string containing the correct period is returned; the default storage is set
1054                 if (fStartRunLHCPeriod <= run && fEndRunLHCPeriod >= run){
1055                         AliInfo("LHCPeriod alien folder for current run already in memory");
1056                 }
1057                 else {
1058                         SetDefaultStorageFromRun(run);
1059                 }
1060         }
1061         ClearCache();
1062         QueryCDB();
1063 }
1064
1065 //_____________________________________________________________________________
1066 void AliCDBManager::ClearCache(){
1067 // clear AliCDBEntry cache
1068
1069         AliDebug(2, Form("Cache entries to be deleted: %d",fEntryCache.GetEntries()));
1070         
1071         /*
1072         // To clean entries one by one
1073         TIter iter(fEntryCache.GetTable());
1074         TPair* pair=0;
1075         while((pair= dynamic_cast<TPair*> (iter.Next()))){
1076         
1077                 TObjString* key = dynamic_cast<TObjString*> (pair->Key());
1078                 AliCDBEntry* entry = dynamic_cast<AliCDBEntry*> (pair->Value());
1079                 AliDebug(2, Form("Deleting entry: %s", key->GetName()));
1080                 if (entry) delete entry;
1081                 delete fEntryCache.Remove(key);
1082         }
1083         */
1084         fEntryCache.DeleteAll();
1085         AliDebug(2, Form("After deleting - Cache entries: %d",fEntryCache.GetEntries()));
1086 }
1087
1088 //_____________________________________________________________________________
1089 void AliCDBManager::UnloadFromCache(const char* path){
1090 // unload cached object
1091
1092         AliCDBPath queryPath(path);
1093         if(!queryPath.IsValid()) return;
1094
1095         if(!queryPath.IsWildcard()) { // path is not wildcard, get it directly from the cache and unload it!
1096                 if(fEntryCache.Contains(path)){
1097                         AliInfo(Form("Unloading object \"%s\" from cache", path));
1098                         TObjString pathStr(path);
1099                         AliCDBEntry *entry = dynamic_cast<AliCDBEntry*> (fEntryCache.GetValue(&pathStr));
1100                         if(entry) delete entry;
1101                         delete fEntryCache.Remove(&pathStr);
1102                 } else {
1103                         AliError(Form("Cache does not contain object \"%s\"!", path))
1104                 }
1105                 AliDebug(2,Form("Cache entries: %d",fEntryCache.GetEntries()));
1106                 return;
1107         }
1108
1109         // path is wildcard: loop on the cache and unload all comprised objects!
1110         TIter iter(fEntryCache.GetTable());
1111         TPair* pair = 0;
1112
1113         while((pair = dynamic_cast<TPair*> (iter.Next()))){
1114                 AliCDBPath entryPath = pair->Key()->GetName();
1115                 if(queryPath.Comprises(entryPath)) {
1116                         AliInfo(Form("Unloading object \"%s\" from cache", entryPath.GetPath().Data()));
1117                         TObjString pathStr(entryPath.GetPath().Data());
1118                         AliCDBEntry *entry = dynamic_cast<AliCDBEntry*> (fEntryCache.GetValue(&pathStr));
1119                         if(entry) delete entry;
1120                         delete fEntryCache.Remove(&pathStr);
1121                 }
1122         }
1123         AliDebug(2,Form("Cache entries: %d",fEntryCache.GetEntries()));
1124 }
1125
1126 //_____________________________________________________________________________
1127 void AliCDBManager::DestroyActiveStorages() {
1128 // delete list of active storages
1129
1130         fActiveStorages.DeleteAll();
1131         fSpecificStorages.DeleteAll();
1132 }
1133
1134 //_____________________________________________________________________________
1135 void AliCDBManager::DestroyActiveStorage(AliCDBStorage* /*storage*/) {
1136 // destroys active storage
1137
1138 /*
1139         TIter iter(fActiveStorages.GetTable());
1140         TPair* aPair;
1141         while ((aPair = (TPair*) iter.Next())) {
1142                 if(storage == (AliCDBStorage*) aPair->Value())
1143                         delete fActiveStorages.Remove(aPair->Key());
1144                         storage->Delete(); storage=0x0;
1145         }
1146 */
1147
1148 }
1149
1150 //_____________________________________________________________________________
1151 void AliCDBManager::QueryCDB() {
1152 // query default and specific storages for files valid for fRun. Every storage loads the Ids into its list.
1153
1154         if (fRun < 0){
1155                 AliError("Run number not yet set! Use AliCDBManager::SetRun.");
1156         return;
1157         }
1158         if (!fDefaultStorage){
1159                 AliError("Default storage is not set! Use AliCDBManager::SetDefaultStorage");
1160         return;
1161         }
1162         if(fDefaultStorage->GetType() == "alien"){
1163                 fDefaultStorage->QueryCDB(fRun);
1164         } else {
1165                 AliDebug(2,"Skipping query for valid files, it used only in grid...");
1166         }
1167
1168         TIter iter(&fSpecificStorages);
1169         TObjString *aCalibType=0;
1170         AliCDBParam* aPar=0;
1171         while((aCalibType = dynamic_cast<TObjString*> (iter.Next()))){
1172                 aPar = (AliCDBParam*) fSpecificStorages.GetValue(aCalibType);
1173                 if(aPar) {
1174                         AliDebug(2,Form("Querying specific storage %s",aCalibType->GetName()));
1175                         AliCDBStorage *aStorage = GetStorage(aPar);
1176                         if(aStorage->GetType() == "alien"){
1177                                 aStorage->QueryCDB(fRun,aCalibType->GetName());
1178                         } else {
1179                                 AliDebug(2,
1180                                         "Skipping query for valid files, it is used only in grid...");
1181                         }
1182                 }
1183         }
1184 }
1185
1186 //______________________________________________________________________________________________
1187 const char* AliCDBManager::GetDataTypeName(DataType type)
1188 {
1189   // returns the name (string) of the data type
1190
1191       switch (type){
1192             case kCondition: return "Conditions";
1193             case kReference: return "Reference";
1194             case kPrivate: return "Private";
1195      }
1196      return 0;
1197
1198 }
1199
1200 //______________________________________________________________________________________________
1201 void AliCDBManager::InitShortLived()
1202 {
1203   // Init the list of short-lived objects
1204   // currently disabled
1205
1206         fShortLived=0x0;
1207
1208 //      fShortLived = new TList();
1209 //      fShortLived->SetOwner(1);
1210 //
1211 //      fShortLived->Add(new TObjString("EMCAL/Calib/Data"));
1212 // 
1213 //      fShortLived->Add(new TObjString("HMPID/Calib/Nmean"));
1214 //      fShortLived->Add(new TObjString("HMPID/Calib/Qthre"));
1215 // 
1216 //      fShortLived->Add(new TObjString("ITS/Calib/CalibSPD"));
1217 // 
1218 //      fShortLived->Add(new TObjString("MUON/Calib/Gains"));
1219 //      fShortLived->Add(new TObjString("MUON/Calib/HV"));
1220 //      fShortLived->Add(new TObjString("MUON/Calib/Pedestals"));
1221 // 
1222 //      fShortLived->Add(new TObjString("PHOS/Calib/CpvGainPedestals"));
1223 //      fShortLived->Add(new TObjString("PHOS/Calib/EmcGainPedestals"));
1224 // 
1225 //      fShortLived->Add(new TObjString("PMD/Calib/Data"));
1226 // 
1227 //      fShortLived->Add(new TObjString("TRD/Calib/ChamberGainFactor"));
1228 //      fShortLived->Add(new TObjString("TRD/Calib/LocalGainFactor"));
1229 //      fShortLived->Add(new TObjString("TRD/Calib/ChamberT0"));
1230 //      fShortLived->Add(new TObjString("TRD/Calib/LocalT0"));
1231 //      fShortLived->Add(new TObjString("TRD/Calib/ChamberVdrift"));
1232 //      fShortLived->Add(new TObjString("TRD/Calib/LocalVdrift"));
1233 // 
1234 //      fShortLived->Add(new TObjString("ZDC/Calib/Data"));
1235
1236 }
1237
1238 //______________________________________________________________________________________________
1239 Bool_t AliCDBManager::IsShortLived(const char* path)
1240 {
1241   // returns the name (string) of the data type
1242
1243         if(!fShortLived) return kFALSE;
1244
1245         AliCDBPath aPath(path);
1246         if(!aPath.IsValid()){
1247                 AliError(Form("Not a valid path: %s", path));
1248                 return kFALSE;
1249         }
1250
1251         return fShortLived->Contains(path);
1252
1253 }
1254
1255 //______________________________________________________________________________________________
1256 void AliCDBManager::SetLock(Bool_t lock){
1257
1258         if(fLock == kTRUE && lock == kFALSE) {
1259                 AliFatal("Lock is ON: cannot reset it!");
1260         }
1261         
1262         fLock=lock;
1263 }
1264
1265 ///////////////////////////////////////////////////////////
1266 // AliCDBManager Parameter class                         //
1267 // interface to specific AliCDBParameter class           //
1268 // (AliCDBGridParam, AliCDBLocalParam, AliCDBDumpParam)  //
1269 ///////////////////////////////////////////////////////////
1270
1271 AliCDBParam::AliCDBParam():
1272   fType(),
1273   fURI()
1274 {
1275 // constructor
1276
1277 }
1278
1279 //_____________________________________________________________________________
1280 AliCDBParam::~AliCDBParam() {
1281 // destructor
1282
1283 }
1284