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