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