]> git.uio.no Git - u/mrichter/AliRoot.git/blob - STEER/CDB/AliCDBManager.cxx
Adding protection for not-yet-opened snapshot file
[u/mrichter/AliRoot.git] / STEER / CDB / 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 <stdlib.h>
22
23 #include "AliCDBManager.h"
24 #include "AliCDBStorage.h"
25 #include "AliLog.h"
26 #include "AliCDBDump.h"
27 #include "AliCDBLocal.h"
28 #include "AliCDBGrid.h"
29 #include "AliCDBEntry.h"
30 #include "AliCDBHandler.h"
31
32 #include <TObjString.h>
33 #include <TSAXParser.h>
34 #include <TFile.h>
35 #include <TKey.h>
36 #include <TUUID.h>
37 #include <TGrid.h>
38
39 ClassImp(AliCDBParam)
40
41 ClassImp(AliCDBManager)
42
43 //TODO OCDB and Reference folder should not be fully hardcoded but built from run number (or year/LHC period)
44 TString AliCDBManager::fgkCondUri("alien://folder=/alice/cern.ch/user/a/aliprod/testCDB/CDB?user=aliprod");
45 TString AliCDBManager::fgkRefUri("alien://folder=/alice/cern.ch/user/a/aliprod/testCDB/Reference?user=aliprod");
46 TString AliCDBManager::fgkMCIdealStorage("alien://folder=/alice/simulation/2008/v4-15-Release/Ideal");
47 TString AliCDBManager::fgkMCFullStorage("alien://folder=/alice/simulation/2008/v4-15-Release/Full");
48 TString AliCDBManager::fgkMCResidualStorage("alien://folder=/alice/simulation/2008/v4-15-Release/Residual");
49 TString AliCDBManager::fgkOCDBFolderXMLfile("alien:///alice/data/OCDBFoldervsRunRange.xml");
50 AliCDBManager* AliCDBManager::fgInstance = 0x0;
51
52 //_____________________________________________________________________________
53 AliCDBManager* AliCDBManager::Instance(TMap *entryCache, Int_t run)
54 {
55 // returns AliCDBManager instance (singleton)
56
57         if (!fgInstance) {
58                 fgInstance = new AliCDBManager();
59                 if (!entryCache)
60                   fgInstance->Init();
61                 else
62                   fgInstance->InitFromCache(entryCache,run);
63         }
64
65         return fgInstance;
66 }
67
68 //_____________________________________________________________________________
69 void AliCDBManager::Init() {
70 // factory registering
71
72         RegisterFactory(new AliCDBDumpFactory());
73         RegisterFactory(new AliCDBLocalFactory()); 
74         // AliCDBGridFactory is registered only if AliEn libraries are enabled in Root
75         if(!gSystem->Exec("root-config --has-alien 2>/dev/null |grep yes 2>&1 > /dev/null")){ // returns 0 if yes
76                 AliInfo("AliEn classes enabled in Root. AliCDBGrid factory registered.");
77                 RegisterFactory(new AliCDBGridFactory());
78                 fCondParam = CreateParameter(fgkCondUri);
79                 fRefParam = CreateParameter(fgkRefUri);
80         }
81
82         InitShortLived();
83 }
84
85 //_____________________________________________________________________________
86 void AliCDBManager::InitFromCache(TMap *entryCache, Int_t run) {
87 // initialize manager from existing cache
88 // used on the slaves in case of parallel reconstruction
89   SetRun(run);
90
91   TIter iter(entryCache->GetTable());
92   TPair* pair = 0;
93
94   while((pair = dynamic_cast<TPair*> (iter.Next()))){
95     fEntryCache.Add(pair->Key(),pair->Value());
96   }
97   // fEntry is the new owner of the cache
98   fEntryCache.SetOwnerKeyValue(kTRUE,kTRUE);
99   entryCache->SetOwnerKeyValue(kFALSE,kFALSE);
100   AliInfo(Form("%d cache entries have been loaded",fEntryCache.GetEntries()));
101 }
102
103 //_____________________________________________________________________________
104 void  AliCDBManager::DumpToSnapshotFile(const char* snapshotFileName, Bool_t singleKeys){
105 // 
106 // dump the entries map and the ids list to
107 // the output file
108
109     // open the file
110     TFile *f = TFile::Open(snapshotFileName,"RECREATE");
111     if (!f || f->IsZombie()){
112         AliError(Form("Cannot open file %s",snapshotFileName));
113         return;
114     }
115
116     AliInfo(Form("Dumping entriesMap (entries'cache) with %d entries!\n", fEntryCache.GetEntries())); 
117     AliInfo(Form("Dumping entriesList with %d entries!\n", fIds->GetEntries()));
118
119     f->cd();                                                                                           
120
121     if(singleKeys){
122         f->WriteObject(&fEntryCache,"CDBentriesMap");
123         f->WriteObject(fIds,"CDBidsList");
124     }else{
125         // We write the entries one by one named by their calibration path
126         /*
127         fEntryCache.Write("CDBentriesMap");
128         fIds->Write("CDBidsList");
129         */
130         TIter iter(fEntryCache.GetTable());
131         TPair* pair = 0;
132         while((pair = dynamic_cast<TPair*> (iter.Next()))){
133             TObjString *os = dynamic_cast<TObjString*>(pair->Key());
134             if (!os) continue;
135             TString path = os->GetString();
136             AliCDBEntry *entry = dynamic_cast<AliCDBEntry*>(pair->Value());
137             if (!entry) continue;
138             path.ReplaceAll("/","*");
139             entry->Write(path.Data());
140         }
141     }
142     f->Close();
143     delete f;
144
145     exit(0);
146 }
147
148 //_____________________________________________________________________________
149 Bool_t AliCDBManager::InitFromSnapshot(const char* snapshotFileName, Bool_t overwrite){
150 // initialize manager from a CDB snapshot, that is add the entries
151 // to the entries map and the ids to the ids list taking them from
152 // the map and the list found in the input file
153
154 // if the manager is locked it cannot initialize from a snapshot
155     if(fLock) {
156         AliError("Being locked I cannot initialize from the snapshot!");
157         return kFALSE;
158     }   
159
160     // open the file
161     TString snapshotFile(snapshotFileName);
162     if(snapshotFile.BeginsWith("alien://")){
163         if(!gGrid) {
164             TGrid::Connect("alien://","");
165             if(!gGrid) {
166                 AliError("Connection to alien failed!");
167                 return kFALSE;
168             }
169         }
170     }
171
172     TFile *f = TFile::Open(snapshotFileName);
173     if (!f || f->IsZombie()){
174         AliError(Form("Cannot open file %s",snapshotFileName));
175         return kFALSE;
176     }
177
178     // retrieve entries' map from snapshot file
179     TMap *entriesMap = 0;
180     TIter next(f->GetListOfKeys());
181     TKey *key;
182     while ((key = (TKey*)next())) {
183         if (strcmp(key->GetClassName(),"TMap") != 0) continue;
184         entriesMap = (TMap*)key->ReadObj();
185         break;
186     }
187     if (!entriesMap || entriesMap->GetEntries()==0){
188         AliError("Cannot get valid map of CDB entries from snapshot file");
189         return kFALSE;
190     }
191
192     // retrieve ids' list from snapshot file
193     TList *idsList = 0;
194     TIter nextKey(f->GetListOfKeys());
195     TKey *keyN;
196     while ((keyN = (TKey*)nextKey())) {
197         if (strcmp(keyN->GetClassName(),"TList") != 0) continue;
198         idsList = (TList*)keyN->ReadObj();
199         break;
200     }
201     if (!idsList || idsList->GetEntries()==0){
202         AliError("Cannot get valid list of CDB entries from snapshot file");
203         return kFALSE;
204     }
205
206     // Add each (entry,id) from the snapshot to the memory: entry to the cache, id to the list of ids.
207     // If "overwrite" is false: add the entry to the cache and its id to the list of ids
208     // only if neither of them is already there.
209     // If "overwrite" is true: write the snapshot entry,id in any case. If something
210     // was already there for that calibration type, remove it and issue a warning
211     TIter iterObj(entriesMap->GetTable());
212     TPair* pair = 0;
213     Int_t nAdded=0;
214     while((pair = dynamic_cast<TPair*> (iterObj.Next()))){
215         TObjString* os = (TObjString*) pair->Key();
216         TString path = os->GetString();
217         TIter iterId(idsList);
218         AliCDBId* id=0;
219         AliCDBId* correspondingId=0;
220         while((id = dynamic_cast<AliCDBId*> (iterId.Next()))){
221             TString idpath(id->GetPath());
222             if(idpath==path){
223                 correspondingId=id;
224                 break;
225             }
226         }
227         if(!correspondingId){
228             AliError(Form("id for \"%s\" not found in the snapshot (while entry was). This entry is skipped!",path.Data()));
229             break;
230         }
231         Bool_t cached = fEntryCache.Contains(path.Data());
232         Bool_t registeredId = kFALSE;
233         TIter iter(fIds);
234         AliCDBId *idT = 0;
235         while((idT = dynamic_cast<AliCDBId*> (iter.Next()))){
236             if(idT->GetPath()==path){
237                 registeredId = kTRUE;
238                 break;
239             }
240         }
241
242         if(overwrite){
243             if(cached || registeredId){
244                 AliWarning(Form("An entry was already cached for \"%s\". Removing it before caching from snapshot",path.Data()));
245                 UnloadFromCache(path.Data());
246             }
247             fEntryCache.Add(pair->Key(),pair->Value());
248             fIds->Add(id);
249             nAdded++;
250         }else{
251             if(cached || registeredId){
252                 AliWarning(Form("An entry was already cached for \"%s\". Not adding this object from snapshot",path.Data()));
253             }else{
254                 fEntryCache.Add(pair->Key(),pair->Value());
255                 fIds->Add(id);
256                 nAdded++;
257             }
258         }
259     }
260
261     // fEntry is the new owner of the cache
262     fEntryCache.SetOwnerKeyValue(kTRUE,kTRUE);
263     entriesMap->SetOwnerKeyValue(kFALSE,kFALSE);
264     fIds->SetOwner(kTRUE);
265     idsList->SetOwner(kFALSE);
266     AliInfo(Form("%d new (entry,id) cached. Total number %d",nAdded,fEntryCache.GetEntries()));
267
268     f->Close();
269     delete f;
270
271     return kTRUE;
272 }
273
274 //_____________________________________________________________________________
275 void AliCDBManager::Destroy() {
276 // delete ALCDBManager instance and active storages
277
278         if (fgInstance) {
279                 //fgInstance->Delete();
280                 delete fgInstance;
281                 fgInstance = 0x0;
282         }
283 }
284
285 //_____________________________________________________________________________
286 AliCDBManager::AliCDBManager():
287   TObject(),
288   fFactories(),
289   fActiveStorages(),
290   fSpecificStorages(),
291   fEntryCache(),
292   fIds(0),
293   fStorageMap(0),
294   fShortLived(0),
295   fDefaultStorage(NULL),
296   fDrainStorage(NULL),
297   fCondParam(0),
298   fRefParam(0),
299   fRun(-1),
300   fCache(kTRUE),
301   fLock(kFALSE),
302   fSnapshotMode(kFALSE),
303   fSnapshotFile(0),
304   fRaw(kFALSE),
305   fStartRunLHCPeriod(-1),
306   fEndRunLHCPeriod(-1),
307   fLHCPeriod(""),
308   fKey(0)
309 {
310 // default constuctor
311         fFactories.SetOwner(1);
312         fActiveStorages.SetOwner(1);
313         fSpecificStorages.SetOwner(1);
314         fEntryCache.SetName("CDBEntryCache");
315         fEntryCache.SetOwnerKeyValue(kTRUE,kTRUE);
316
317         fStorageMap = new TMap();
318         fStorageMap->SetOwner(1);
319         fIds = new TList();
320         fIds->SetOwner(1);
321 }
322
323 //_____________________________________________________________________________
324 AliCDBManager::~AliCDBManager() {
325 // destructor
326         ClearCache();
327         DestroyActiveStorages();
328         fFactories.Delete();
329         fDrainStorage = 0x0;
330         fDefaultStorage = 0x0;
331         delete fStorageMap; fStorageMap = 0;
332         delete fIds; fIds = 0;
333         delete fCondParam;
334         delete fRefParam;
335         delete fShortLived; fShortLived = 0x0;
336         //fSnapshotCache = 0;
337         //fSnapshotIdsList = 0;
338         if(fSnapshotMode){
339             fSnapshotFile->Close();
340             fSnapshotFile = 0;
341         }
342 }
343
344 //_____________________________________________________________________________
345 void AliCDBManager::PutActiveStorage(AliCDBParam* param, AliCDBStorage* storage){
346 // put a storage object into the list of active storages
347
348         fActiveStorages.Add(param, storage);
349         AliDebug(1, Form("Active storages: %d", fActiveStorages.GetEntries()));
350 }
351
352 //_____________________________________________________________________________
353 void AliCDBManager::RegisterFactory(AliCDBStorageFactory* factory) {
354 // add a storage factory to the list of registerd factories
355  
356         if (!fFactories.Contains(factory)) {
357                 fFactories.Add(factory);
358         }
359 }
360
361 //_____________________________________________________________________________
362 Bool_t AliCDBManager::HasStorage(const char* dbString) const {
363 // check if dbString is a URI valid for one of the registered factories
364
365         TIter iter(&fFactories);
366
367         AliCDBStorageFactory* factory=0;
368         while ((factory = (AliCDBStorageFactory*) iter.Next())) {
369
370                 if (factory->Validate(dbString)) {
371                         return kTRUE;
372                 }
373         }
374
375         return kFALSE;
376 }
377
378 //_____________________________________________________________________________
379 AliCDBParam* AliCDBManager::CreateParameter(const char* dbString) const {
380 // create AliCDBParam object from URI string
381
382         TIter iter(&fFactories);
383
384         AliCDBStorageFactory* factory=0;
385         while ((factory = (AliCDBStorageFactory*) iter.Next())) {
386                 AliCDBParam* param = factory->CreateParameter(dbString);
387                 if(param) return param;
388         }
389
390         return NULL;
391 }
392
393 //_____________________________________________________________________________
394 AliCDBStorage* AliCDBManager::GetStorage(const char* dbString) {
395 // get storage object from URI string
396                 
397         AliCDBParam* param = CreateParameter(dbString);
398         if (!param) {
399                 AliError(Form("Failed to activate requested storage! Check URI: %s", dbString));
400                 return NULL;
401         }
402
403         AliCDBStorage* aStorage = GetStorage(param);
404
405         delete param;
406         return aStorage;
407 }
408
409 //_____________________________________________________________________________
410 AliCDBStorage* AliCDBManager::GetStorage(const AliCDBParam* param) {
411 // get storage object from AliCDBParam object
412         
413         // if the list of active storages already contains
414         // the requested storage, return it
415         AliCDBStorage* aStorage = GetActiveStorage(param);
416         if (aStorage) {
417                 return aStorage;
418         }
419
420         // if lock is ON, cannot activate more storages!
421         if(fLock) {
422                 if (fDefaultStorage) {
423                         AliFatal("Lock is ON, and default storage is already set: "
424                                 "cannot reset it or activate more storages!");
425                 }
426         }       
427         
428         TIter iter(&fFactories);
429
430         AliCDBStorageFactory* factory=0;
431
432         // loop on the list of registered factories
433         while ((factory = (AliCDBStorageFactory*) iter.Next())) {
434
435                 // each factory tries to create its storage from the parameter
436                 aStorage = factory->Create(param);
437                 if (aStorage) {
438                         PutActiveStorage(param->CloneParam(), aStorage);
439                         aStorage->SetURI(param->GetURI());
440                         if(fRun >= 0) {
441                                 if(aStorage->GetType() == "alien"){
442                                         aStorage->QueryCDB(fRun);
443                                 } else {
444                                         AliDebug(2,
445                                                 "Skipping query for valid files, it is used only in grid...");
446                                 }
447                         }
448                         return aStorage;
449                 }
450         }
451
452         AliError(Form("Failed to activate requested storage! Check URI: %s", param->GetURI().Data()));
453
454         return NULL;
455 }
456
457 //_____________________________________________________________________________
458 AliCDBStorage* AliCDBManager::GetActiveStorage(const AliCDBParam* param) {
459 // get a storage object from the list of active storages
460
461         return dynamic_cast<AliCDBStorage*> (fActiveStorages.GetValue(param));
462 }
463
464 //_____________________________________________________________________________
465 TList* AliCDBManager::GetActiveStorages() {
466 // return list of active storages
467 // user has responsibility to delete returned object
468
469         TList* result = new TList();
470
471         TIter iter(fActiveStorages.GetTable());
472         TPair* aPair=0;
473         while ((aPair = (TPair*) iter.Next())) {
474                 result->Add(aPair->Value());
475         }
476
477         return result;
478 }
479
480 //_____________________________________________________________________________
481 void AliCDBManager::SetDrain(const char* dbString) {
482 // set drain storage from URI string
483
484         fDrainStorage = GetStorage(dbString);   
485 }
486
487 //_____________________________________________________________________________
488 void AliCDBManager::SetDrain(const AliCDBParam* param) {
489 // set drain storage from AliCDBParam
490
491         fDrainStorage = GetStorage(param);
492 }
493
494 //_____________________________________________________________________________
495 void AliCDBManager::SetDrain(AliCDBStorage* storage) {
496 // set drain storage from another active storage
497         
498         fDrainStorage = storage;
499 }
500
501 //_____________________________________________________________________________
502 Bool_t AliCDBManager::Drain(AliCDBEntry *entry) {
503 // drain retrieved object to drain storage
504
505         AliDebug(2, "Draining into drain storage...");
506         return fDrainStorage->Put(entry);
507 }
508
509 //____________________________________________________________________________
510 void AliCDBManager::SetDefaultStorage(const char* dbString) {
511 // sets default storage from URI string
512         
513         // checking whether we are in the raw case
514         TString dbStringTemp(dbString);
515         if (dbStringTemp == "raw://")
516         {
517                 fRaw = kTRUE;
518                 AliInfo("Setting the run-number will set the corresponding OCDB for raw data reconstruction.");
519                 AliInfo("Connecting to the grid...");
520                 if(!gGrid) {
521                         TGrid::Connect("alien://","");
522                         if(!gGrid) {
523                                 AliError("Connection to alien failed!");
524                                 return;
525                         }
526                 }
527                 return;
528         }
529
530         AliCDBStorage* bckStorage = fDefaultStorage;
531         
532         fDefaultStorage = GetStorage(dbString);
533         
534         if(!fDefaultStorage) return;
535         
536         if(bckStorage && (fDefaultStorage != bckStorage)){
537                 AliWarning("Existing default storage replaced: clearing cache!");
538                 ClearCache();
539         }
540         
541         if (fStorageMap->Contains("default")) {
542                 delete fStorageMap->Remove(((TPair*)fStorageMap->FindObject("default"))->Key());
543         }
544         fStorageMap->Add(new TObjString("default"), new TObjString(fDefaultStorage->GetURI()));
545 }
546 //_____________________________________________________________________________
547 void AliCDBManager::SetDefaultStorage(const AliCDBParam* param) {
548 // set default storage from AliCDBParam object
549         
550         AliCDBStorage* bckStorage = fDefaultStorage;
551
552         fDefaultStorage = GetStorage(param);
553
554         if(!fDefaultStorage) return;
555
556         if(bckStorage && (fDefaultStorage != bckStorage)){
557                 AliWarning("Existing default storage replaced: clearing cache!");
558                 ClearCache();
559         }
560
561         if (fStorageMap->Contains("default")) {
562                 delete fStorageMap->Remove(((TPair*)fStorageMap->FindObject("default"))->Key());
563         }
564         fStorageMap->Add(new TObjString("default"), new TObjString(fDefaultStorage->GetURI()));
565 }
566
567 //_____________________________________________________________________________
568 void AliCDBManager::SetDefaultStorage(AliCDBStorage* storage) {
569 // set default storage from another active storage
570         
571         // if lock is ON, cannot activate more storages!
572         if(fLock) {
573                 if (fDefaultStorage) {
574                         AliFatal("Lock is ON, and default storage is already set: "
575                                 "cannot reset it or activate more storages!");
576                 }
577         }       
578         
579         if (!storage) {
580                 UnsetDefaultStorage();
581                 return;
582         }
583         
584         AliCDBStorage* bckStorage = fDefaultStorage;
585
586         fDefaultStorage = storage;
587
588         if(bckStorage && (fDefaultStorage != bckStorage)){
589                 AliWarning("Existing default storage replaced: clearing cache!");
590                 ClearCache();
591         }
592
593         if (fStorageMap->Contains("default")) {
594                 delete fStorageMap->Remove(((TPair*)fStorageMap->FindObject("default"))->Key());
595         }
596         fStorageMap->Add(new TObjString("default"), new TObjString(fDefaultStorage->GetURI()));
597 }
598
599 //_____________________________________________________________________________
600 void AliCDBManager::SetDefaultStorage(const char* mcString, const char* simType) {
601 // sets default storage for MC data
602 // mcString MUST be "MC", 
603 // simType can be "Ideal","Residual","Full"
604         
605         TString strmcString(mcString);
606         TString strsimType(simType);
607         TString dbString; 
608         if (strmcString != "MC"){
609                 AliFatal("Method requires first string to be MC!");
610         }
611         else {
612                 if (strsimType == "Ideal"){
613                         dbString = fgkMCIdealStorage;
614                 }
615                 else if (strsimType == "Full"){
616                         dbString = fgkMCFullStorage;
617                 }
618                 else if (strsimType == "Residual"){
619                         dbString = fgkMCResidualStorage;
620                 }
621                 else {
622                         AliFatal("Error in setting the storage for MC data, second argument MUST be either \"Ideal\" or \"Full\" or \"Residual\".");
623                 }
624
625                 SetDefaultStorage(dbString.Data());
626                 fStartRunLHCPeriod=0;
627                 fEndRunLHCPeriod=AliCDBRunRange::Infinity();
628                 if(!fDefaultStorage) AliFatal(Form("%s storage not there! Please check!",dbString.Data()));
629         }
630 }
631 //_____________________________________________________________________________
632 void AliCDBManager::SetDefaultStorageFromRun(Int_t run) {
633 // set default storage from the run number - to be used only with raw data      
634
635         // if lock is ON, cannot activate more storages!
636         if(fLock) {
637                 if (fDefaultStorage) {
638                         AliFatal("Lock is ON, and default storage is already set: "
639                                 "cannot activate default storage from run number");
640                 }
641         }       
642
643         // retrieve XML file from alien
644         if(!gGrid) {
645             TGrid::Connect("alien://","");
646             if(!gGrid) {
647                 AliError("Connection to alien failed!");
648                 return;
649             }
650         }
651         TUUID uuid;
652         TString rndname = "/tmp/";
653         rndname += "OCDBFolderXML.";
654         rndname += uuid.AsString();
655         rndname += ".xml";
656         AliDebug(2, Form("file to be copied = %s", fgkOCDBFolderXMLfile.Data()));
657         if (!TFile::Cp(fgkOCDBFolderXMLfile.Data(), rndname.Data())) {
658                 AliFatal(Form("Cannot make a local copy of OCDBFolder xml file in %s",rndname.Data()));
659         }
660         AliCDBHandler* saxcdb = new AliCDBHandler();
661         saxcdb->SetRun(run);
662         TSAXParser *saxParser = new TSAXParser();
663         saxParser->ConnectToHandler("AliCDBHandler", saxcdb);  
664         saxParser->ParseFile(rndname.Data()); 
665         AliInfo(Form(" LHC folder = %s", saxcdb->GetOCDBFolder().Data()));
666         AliInfo(Form(" LHC period start run = %d", saxcdb->GetStartRunRange()));
667         AliInfo(Form(" LHC period end run = %d", saxcdb->GetEndRunRange()));
668         fLHCPeriod = saxcdb->GetOCDBFolder();
669         fStartRunLHCPeriod = saxcdb->GetStartRunRange();
670         fEndRunLHCPeriod = saxcdb->GetEndRunRange();
671
672         SetDefaultStorage(fLHCPeriod.Data());
673         if(!fDefaultStorage) AliFatal(Form("%s storage not there! Please check!",fLHCPeriod.Data()));
674
675 }
676
677 //_____________________________________________________________________________
678 void AliCDBManager::UnsetDefaultStorage() {
679 // Unset default storage
680         
681         // if lock is ON, action is forbidden!
682         if(fLock) {
683                 if (fDefaultStorage) {
684                         AliFatal("Lock is ON: cannot unset default storage!");
685                 }
686         }
687         
688         if (fDefaultStorage) {
689                 AliWarning("Clearing cache!");
690                 ClearCache();
691         }
692
693         fRun = fStartRunLHCPeriod = fEndRunLHCPeriod = -1;
694         fRaw = kFALSE;
695         
696         fDefaultStorage = 0x0;
697 }
698
699 //_____________________________________________________________________________
700 void AliCDBManager::SetSpecificStorage(const char* calibType, const char* dbString) {
701 // sets storage specific for detector or calibration type (works with AliCDBManager::Get(...))
702
703         AliCDBParam *aPar = CreateParameter(dbString);
704         if(!aPar) return;
705         SetSpecificStorage(calibType, aPar);
706         delete aPar;
707 }
708
709 //_____________________________________________________________________________
710 void AliCDBManager::SetSpecificStorage(const char* calibType, const AliCDBParam* param) {
711 // sets storage specific for detector or calibration type (works with AliCDBManager::Get(...))
712 // Default storage should be defined prior to any specific storages, e.g.:
713 // AliCDBManager::instance()->SetDefaultStorage("alien://");
714 // AliCDBManager::instance()->SetSpecificStorage("TPC/*","local://DB_TPC");
715 // AliCDBManager::instance()->SetSpecificStorage("*/Align/*","local://DB_TPCAlign");
716 // calibType must be a valid CDB path! (3 level folder structure)
717
718
719         if(!fDefaultStorage && !fRaw) {
720                 AliError("Please activate a default storage first!");
721                 return;
722         }
723
724
725         AliCDBPath aPath(calibType);
726         if(!aPath.IsValid()){
727                 AliError(Form("Not a valid path: %s", calibType));
728                 return;
729         }
730
731         TObjString *objCalibType = new TObjString(aPath.GetPath());
732         if(fSpecificStorages.Contains(objCalibType)){
733                 AliWarning(Form("Storage \"%s\" already activated! It will be replaced by the new one",
734                                         calibType));
735                 AliCDBParam *checkPar = dynamic_cast<AliCDBParam*> (fSpecificStorages.GetValue(calibType));
736                 if(checkPar) delete checkPar;
737                 delete fSpecificStorages.Remove(objCalibType);
738         }
739         AliCDBStorage *aStorage = GetStorage(param);
740         if(!aStorage) return;
741
742         fSpecificStorages.Add(objCalibType, param->CloneParam());
743
744         if(fStorageMap->Contains(objCalibType)){
745                 delete fStorageMap->Remove(objCalibType);
746         }
747         fStorageMap->Add(objCalibType->Clone(), new TObjString(param->GetURI()));
748
749 }
750
751 //_____________________________________________________________________________
752 AliCDBStorage* AliCDBManager::GetSpecificStorage(const char* calibType) {
753 // get storage specific for detector or calibration type 
754
755         AliCDBPath calibPath(calibType);
756         if(!calibPath.IsValid()) return NULL;
757
758         AliCDBParam *checkPar = (AliCDBParam*) fSpecificStorages.GetValue(calibPath.GetPath());
759         if(!checkPar){
760                 AliError(Form("%s storage not found!", calibType));
761                 return NULL;
762         } else {
763                 return GetStorage(checkPar);
764         }
765
766 }
767
768 //_____________________________________________________________________________
769 AliCDBParam* AliCDBManager::SelectSpecificStorage(const TString& path) {
770 // select storage valid for path from the list of specific storages
771
772         AliCDBPath aPath(path);
773         if(!aPath.IsValid()) return NULL;
774
775         TIter iter(&fSpecificStorages);
776         TObjString *aCalibType=0;
777         AliCDBPath tmpPath("null/null/null");
778         AliCDBParam* aPar=0;
779         while((aCalibType = (TObjString*) iter.Next())){
780                 AliCDBPath calibTypePath(aCalibType->GetName());
781                 if(calibTypePath.Comprises(aPath)) {
782                         if(calibTypePath.Comprises(tmpPath)) continue;
783                         aPar = (AliCDBParam*) fSpecificStorages.GetValue(aCalibType);
784                         tmpPath.SetPath(calibTypePath.GetPath());
785                 }
786         }
787         return aPar;
788 }
789
790 //_____________________________________________________________________________
791 AliCDBEntry* AliCDBManager::Get(const AliCDBPath& path, Int_t runNumber,
792         Int_t version, Int_t subVersion) {
793 // get an AliCDBEntry object from the database
794
795         if(runNumber < 0){
796                 // RunNumber is not specified. Try with fRun
797                 if (fRun < 0){
798                         AliError("Run number neither specified in query nor set in AliCDBManager! Use AliCDBManager::SetRun.");
799                         return NULL;
800                 }
801                 runNumber = fRun;
802         }
803
804         return Get(AliCDBId(path, runNumber, runNumber, version, subVersion));
805 }
806
807 //_____________________________________________________________________________
808 AliCDBEntry* AliCDBManager::Get(const AliCDBPath& path,
809         const AliCDBRunRange& runRange, Int_t version,
810         Int_t subVersion) {
811 // get an AliCDBEntry object from the database!
812
813         return Get(AliCDBId(path, runRange, version, subVersion));
814 }
815
816 //_____________________________________________________________________________
817 AliCDBEntry* AliCDBManager::Get(const AliCDBId& query, Bool_t forceCaching) {
818 // get an AliCDBEntry object from the database
819         
820         // check if query's path and runRange are valid
821         // query is invalid also if version is not specified and subversion is!
822         if (!query.IsValid()) {
823                 AliError(Form("Invalid query: %s", query.ToString().Data()));
824                 return NULL;
825         }
826         
827         // query is not specified if path contains wildcard or run range= [-1,-1]
828         if (!query.IsSpecified()) {
829                 AliError(Form("Unspecified query: %s",
830                                 query.ToString().Data()));
831                 return NULL;
832         }
833
834         if(fLock && !(fRun >= query.GetFirstRun() && fRun <= query.GetLastRun())) 
835                 AliFatal("Lock is ON: cannot use different run number than the internal one!");
836         
837         if(fCache && !(fRun >= query.GetFirstRun() && fRun <= query.GetLastRun())) 
838                 AliWarning("Run number explicitly set in query: CDB cache temporarily disabled!");
839
840         AliCDBEntry *entry=0;
841
842         // first look into map of cached objects
843         if(fCache && query.GetFirstRun() == fRun)
844                 entry = (AliCDBEntry*) fEntryCache.GetValue(query.GetPath());
845         if(entry) {
846                 AliDebug(2, Form("Object %s retrieved from cache !!",query.GetPath().Data()));
847                 return entry;
848         }
849
850         // if snapshot flag is set, try getting from the snapshot
851         // but in the case a specific storage is specified for this path
852         AliCDBParam *aPar=SelectSpecificStorage(query.GetPath());
853         if(!aPar){
854             if(fSnapshotMode && query.GetFirstRun() == fRun)
855             {
856                 entry = GetEntryFromSnapshot(query.GetPath());
857                 if(entry) {
858                     AliInfo(Form("Object \"%s\" retrieved from the snapshot.",query.GetPath().Data()));
859                     if(query.GetFirstRun() == fRun) // no need to check fCache, fSnapshotMode not possible otherwise
860                         CacheEntry(query.GetPath(), entry);
861
862                     if(!fIds->Contains(&entry->GetId()))
863                         fIds->Add(entry->GetId().Clone());
864
865                     return entry;
866                 }
867             }
868         }
869
870         // Entry is not in cache (and, in case we are in snapshot mode, not in the snapshot either)
871         // => retrieve it from the storage and cache it!!
872         if(!fDefaultStorage) {
873                 AliError("No storage set!");
874                 return NULL;
875         }
876
877         AliCDBStorage *aStorage=0;
878         if(aPar) {
879                 aStorage=GetStorage(aPar);
880                 TString str = aPar->GetURI();
881                 AliDebug(2,Form("Looking into storage: %s",str.Data()));
882         } else {
883                 aStorage=GetDefaultStorage();
884                 AliDebug(2,"Looking into default storage");
885         }
886
887         entry = aStorage->Get(query);
888
889         if(entry && fCache && (query.GetFirstRun()==fRun || forceCaching)){
890                 CacheEntry(query.GetPath(), entry);
891         }
892
893         if(entry && !fIds->Contains(&entry->GetId())){
894                 fIds->Add(entry->GetId().Clone());
895         }
896
897
898         return entry;
899
900 }
901
902 //_____________________________________________________________________________
903 AliCDBEntry* AliCDBManager::GetEntryFromSnapshot(const char* path) {
904     // get the entry from the open snapshot file
905
906     TString sPath(path);
907     sPath.ReplaceAll("/","*");
908     if(!fSnapshotFile){
909         AliError("No snapshot file is open!");
910         return 0;
911     }
912     AliCDBEntry *entry = dynamic_cast<AliCDBEntry*>(fSnapshotFile->Get(sPath.Data()));
913     if(!entry){
914         AliDebug(2,Form("Cannot get a CDB entry for \"%s\" from snapshot file",path));
915         return 0;
916     }
917
918     return entry;
919 }
920
921 //_____________________________________________________________________________
922 Bool_t AliCDBManager::SetSnapshotMode(const char* snapshotFileName) {
923 // set the manager in snapshot mode
924     
925     if(!fCache){
926         AliError("Cannot set the CDB manage in snapshot mode if the cache is not active!");
927         return kFALSE;
928     }
929
930     //open snapshot file
931     TString snapshotFile(snapshotFileName);
932     if(snapshotFile.BeginsWith("alien://")){
933         if(!gGrid) {
934             TGrid::Connect("alien://","");
935             if(!gGrid) {
936                 AliError("Connection to alien failed!");
937                 return kFALSE;
938             }
939         }
940     }
941
942     fSnapshotFile = TFile::Open(snapshotFileName);
943     if (!fSnapshotFile || fSnapshotFile->IsZombie()){
944         AliError(Form("Cannot open file %s",snapshotFileName));
945         return kFALSE;
946     }
947
948     AliInfo("The CDB manager is set in snapshot mode!");
949     fSnapshotMode = kTRUE;
950     return kTRUE;
951
952 }
953
954 //_____________________________________________________________________________
955 const char* AliCDBManager::GetURI(const char* path) {
956 // return the URI of the storage where to look for path
957
958         if(!IsDefaultStorageSet()) return 0;
959         
960         AliCDBParam *aPar=SelectSpecificStorage(path);
961
962         if(aPar) {
963                 return aPar->GetURI().Data();
964
965         } else {
966                 return GetDefaultStorage()->GetURI().Data();
967         }
968         
969         return 0;
970 }
971
972 //_____________________________________________________________________________
973 Int_t AliCDBManager::GetStartRunLHCPeriod(){
974     // get the first run of validity
975     // for the current period
976     // if set
977     if(fStartRunLHCPeriod==-1)
978         AliWarning("Run-range not yet set for the current LHC period.");
979     return fStartRunLHCPeriod;
980 }
981
982 //_____________________________________________________________________________
983 Int_t AliCDBManager::GetEndRunLHCPeriod(){
984     // get the last run of validity
985     // for the current period
986     // if set
987     if(fEndRunLHCPeriod==-1)
988         AliWarning("Run-range not yet set for the current LHC period.");
989     return fEndRunLHCPeriod;
990 }
991
992 //_____________________________________________________________________________
993 TString AliCDBManager::GetLHCPeriod(){
994     // get the current LHC period string
995     //
996     if(fLHCPeriod.IsWhitespace() || fLHCPeriod.IsNull())
997         AliWarning("LHC period (OCDB folder) not yet set");
998     return fLHCPeriod;
999 }
1000
1001 //_____________________________________________________________________________
1002 AliCDBId* AliCDBManager::GetId(const AliCDBPath& path, Int_t runNumber,
1003         Int_t version, Int_t subVersion) {
1004 // get the AliCDBId of the valid object from the database (does not retrieve the object)
1005 // User must delete returned object!
1006
1007         if(runNumber < 0){
1008                 // RunNumber is not specified. Try with fRun
1009                 if (fRun < 0){
1010                         AliError("Run number neither specified in query nor set in AliCDBManager! Use AliCDBManager::SetRun.");
1011                         return NULL;
1012                 }
1013                 runNumber = fRun;
1014         }
1015
1016         return GetId(AliCDBId(path, runNumber, runNumber, version, subVersion));
1017 }
1018
1019 //_____________________________________________________________________________
1020 AliCDBId* AliCDBManager::GetId(const AliCDBPath& path,
1021         const AliCDBRunRange& runRange, Int_t version,
1022         Int_t subVersion) {
1023 // get the AliCDBId of the valid object from the database (does not retrieve the object)
1024 // User must delete returned object!
1025
1026         return GetId(AliCDBId(path, runRange, version, subVersion));
1027 }
1028
1029 //_____________________________________________________________________________
1030 AliCDBId* AliCDBManager::GetId(const AliCDBId& query) {
1031 // get the AliCDBId of the valid object from the database (does not retrieve the object)
1032 // User must delete returned object!
1033
1034         if(!fDefaultStorage) {
1035                 AliError("No storage set!");
1036                 return NULL;
1037         }
1038
1039         // check if query's path and runRange are valid
1040         // query is invalid also if version is not specified and subversion is!
1041         if (!query.IsValid()) {
1042                 AliError(Form("Invalid query: %s", query.ToString().Data()));
1043                 return NULL;
1044         }
1045         
1046         // query is not specified if path contains wildcard or run range= [-1,-1]
1047         if (!query.IsSpecified()) {
1048                 AliError(Form("Unspecified query: %s",
1049                                 query.ToString().Data()));
1050                 return NULL;
1051         }
1052
1053         if(fCache && query.GetFirstRun() != fRun)
1054                 AliWarning("Run number explicitly set in query: CDB cache temporarily disabled!");
1055
1056         AliCDBEntry* entry = 0;
1057
1058         // first look into map of cached objects
1059         if(fCache && query.GetFirstRun() == fRun)
1060                 entry = (AliCDBEntry*) fEntryCache.GetValue(query.GetPath());
1061
1062         if(entry) {
1063                 AliDebug(2, Form("Object %s retrieved from cache !!",query.GetPath().Data()));
1064                 return dynamic_cast<AliCDBId*> (entry->GetId().Clone());
1065         }
1066
1067         // Entry is not in cache -> retrieve it from CDB and cache it!!
1068         AliCDBStorage *aStorage=0;
1069         AliCDBParam *aPar=SelectSpecificStorage(query.GetPath());
1070
1071         if(aPar) {
1072                 aStorage=GetStorage(aPar);
1073                 TString str = aPar->GetURI();
1074                 AliDebug(2,Form("Looking into storage: %s",str.Data()));
1075                 
1076         } else {
1077                 aStorage=GetDefaultStorage();
1078                 AliDebug(2,"Looking into default storage");
1079         }
1080
1081         return aStorage->GetId(query);
1082
1083 }
1084
1085 //_____________________________________________________________________________
1086 TList* AliCDBManager::GetAll(const AliCDBPath& path, Int_t runNumber,
1087         Int_t version, Int_t subVersion) {
1088 // get multiple AliCDBEntry objects from the database
1089
1090         if(runNumber < 0){
1091                 // RunNumber is not specified. Try with fRun
1092                 if (fRun < 0){
1093                         AliError("Run number neither specified in query nor set in AliCDBManager! Use AliCDBManager::SetRun.");
1094                         return NULL;
1095                 }
1096                 runNumber = fRun;
1097         }
1098
1099         return GetAll(AliCDBId(path, runNumber, runNumber, version,     
1100                         subVersion));
1101 }
1102
1103 //_____________________________________________________________________________
1104 TList* AliCDBManager::GetAll(const AliCDBPath& path,
1105         const AliCDBRunRange& runRange, Int_t version, Int_t subVersion) {
1106 // get multiple AliCDBEntry objects from the database
1107
1108         return GetAll(AliCDBId(path, runRange, version, subVersion));
1109 }
1110
1111 //_____________________________________________________________________________
1112 TList* AliCDBManager::GetAll(const AliCDBId& query) {
1113 // get multiple AliCDBEntry objects from the database
1114 // Warning: this method works correctly only for queries of the type "Detector/*"
1115 //              and not for more specific queries e.g. "Detector/Calib/*" !
1116 // Warning #2: Entries are cached, but GetAll will keep on retrieving objects from OCDB!
1117 //              To get an object from cache use Get() function
1118
1119         if(!fDefaultStorage) {
1120                 AliError("No storage set!");
1121                 return NULL;
1122         }
1123
1124         if (!query.IsValid()) {
1125                 AliError(Form("Invalid query: %s", query.ToString().Data()));
1126                 return NULL;
1127         }
1128
1129         if((fSpecificStorages.GetEntries()>0) && query.GetPath().BeginsWith('*')){
1130                 // if specific storages are active a query with "*" is ambiguous
1131                 AliError("Query too generic in this context!");
1132                 return NULL;
1133         }
1134
1135         if (query.IsAnyRange()) {
1136                 AliError(Form("Unspecified run or runrange: %s",
1137                                 query.ToString().Data()));
1138                 return NULL;
1139         }
1140
1141         if(fLock && query.GetFirstRun() != fRun)
1142                 AliFatal("Lock is ON: cannot use different run number than the internal one!");
1143         
1144         AliCDBParam *aPar=SelectSpecificStorage(query.GetPath());
1145
1146         AliCDBStorage *aStorage;
1147         if(aPar) {
1148                 aStorage=GetStorage(aPar);
1149                 AliDebug(2,Form("Looking into storage: %s", aPar->GetURI().Data()));
1150
1151         } else {
1152                 aStorage=GetDefaultStorage();
1153                 AliDebug(2,"Looking into default storage");
1154         }
1155
1156         TList *result = 0;
1157         if(aStorage) result = aStorage->GetAll(query);
1158         if(!result) return 0;
1159
1160        // loop on result to check whether entries should be re-queried with specific storages
1161         if(fSpecificStorages.GetEntries()>0 && ! (fSpecificStorages.GetEntries() == 1 && aPar)) {
1162                 AliInfo("Now look into all other specific storages...");
1163
1164                 TIter iter(result);
1165                 AliCDBEntry* chkEntry=0;
1166
1167                 while((chkEntry = dynamic_cast<AliCDBEntry*> (iter.Next()))){
1168                         AliCDBId& chkId = chkEntry->GetId();
1169                         AliDebug(2, Form("Checking id %s ", chkId.GetPath().Data()));
1170                         AliCDBParam *chkPar=SelectSpecificStorage(chkId.GetPath());
1171                         if (!chkPar || aPar == chkPar) continue;
1172                         AliCDBStorage *chkStorage = GetStorage(chkPar);
1173                         AliDebug(2, Form("Found specific storage! %s", chkPar->GetURI().Data()));
1174
1175                         AliCDBEntry *newEntry=0;
1176                         chkId.SetRunRange(query.GetFirstRun(), query.GetLastRun());
1177                         chkId.SetVersion(query.GetVersion());
1178                         chkId.SetSubVersion(query.GetSubVersion());
1179
1180                         if(chkStorage) newEntry = chkStorage->Get(chkId);
1181                         if(!newEntry) continue;
1182
1183                         // object is found in specific storage: replace entry in the result list!
1184                         chkEntry->SetOwner(1);
1185                         delete result->Remove(chkEntry);
1186                         result->AddFirst(newEntry);
1187                 }
1188
1189                 Int_t nEntries = result->GetEntries();
1190                 AliInfo("After look into other specific storages, result list is:");
1191                 for(int i=0; i<nEntries;i++){
1192                         AliCDBEntry *entry = (AliCDBEntry*) result->At(i);
1193                         AliInfo(Form("%s",entry->GetId().ToString().Data()));
1194                 }
1195         }
1196
1197         // caching entries
1198         TIter iter(result);
1199         AliCDBEntry* entry=0;
1200         while((entry = dynamic_cast<AliCDBEntry*> (iter.Next()))){
1201
1202                 if(!fIds->Contains(&entry->GetId())){
1203                         fIds->Add(entry->GetId().Clone());
1204                 }
1205                 if(fCache && (query.GetFirstRun() == fRun)){
1206                         CacheEntry(entry->GetId().GetPath(), entry);
1207                 }
1208         }
1209
1210
1211         return result;
1212 }
1213
1214 //_____________________________________________________________________________
1215 Bool_t AliCDBManager::Put(TObject* object, const AliCDBId& id, AliCDBMetaData* metaData, const char* mirrors, const DataType type){
1216 // store an AliCDBEntry object into the database
1217
1218         if (object==0x0) {
1219                 AliError("Null Entry! No storage will be done!");
1220                 return kFALSE;
1221         } 
1222
1223         AliCDBEntry anEntry(object, id, metaData);
1224         return Put(&anEntry, mirrors, type);
1225
1226 }
1227
1228
1229 //_____________________________________________________________________________
1230 Bool_t AliCDBManager::Put(AliCDBEntry* entry, const char* mirrors, DataType type){
1231 // store an AliCDBEntry object into the database
1232
1233         if(type == kPrivate && !fDefaultStorage) {
1234                 AliError("No storage set!");
1235                 return kFALSE;
1236         }
1237
1238         if (!entry){
1239                 AliError("No entry!");
1240                 return kFALSE;
1241         }
1242
1243         if (entry->GetObject()==0x0){
1244                 AliError("No valid object in CDB entry!");
1245                 return kFALSE;
1246         }
1247
1248         if (!entry->GetId().IsValid()) {
1249                 AliError(Form("Invalid entry ID: %s", 
1250                         entry->GetId().ToString().Data()));
1251                 return kFALSE;
1252         }       
1253
1254         if (!entry->GetId().IsSpecified()) {
1255                 AliError(Form("Unspecified entry ID: %s", 
1256                         entry->GetId().ToString().Data()));
1257                 return kFALSE;
1258         }
1259
1260         AliCDBId id = entry->GetId();
1261         AliCDBParam *aPar = SelectSpecificStorage(id.GetPath());
1262
1263         AliCDBStorage *aStorage=0;
1264         
1265         if(aPar) {
1266                 aStorage=GetStorage(aPar);
1267         } else {
1268                 switch(type){
1269                         case kCondition:
1270                                 aStorage = GetStorage(fCondParam);
1271                                 break;
1272                         case kReference:
1273                                 aStorage = GetStorage(fRefParam);
1274                                 break;
1275                         case kPrivate:
1276                                 aStorage = GetDefaultStorage();
1277                                 break;
1278                 }
1279         }
1280
1281         AliDebug(2,Form("Storing object into storage: %s", aStorage->GetURI().Data()));
1282
1283         TString strMirrors(mirrors);
1284         Bool_t result = "kFALSE";
1285         if(!strMirrors.IsNull() && !strMirrors.IsWhitespace())
1286             result = aStorage->Put(entry, mirrors, type);
1287         else
1288             result = aStorage->Put(entry, "", type);
1289
1290         if(fRun >= 0) QueryCDB();
1291
1292         return result;
1293
1294
1295 }
1296
1297 //_____________________________________________________________________________
1298 void AliCDBManager::SetMirrorSEs(const char* mirrors)
1299 {
1300 // set mirror Storage Elements for the default storage, if it is of type "alien"
1301     if(fDefaultStorage->GetType() != "alien"){
1302         AliInfo("The default storage is not of type \"alien\". Settings for Storage Elements are not taken into account!");
1303         return;
1304     }
1305     fDefaultStorage->SetMirrorSEs(mirrors);
1306 }
1307
1308 //_____________________________________________________________________________
1309 const char* AliCDBManager::GetMirrorSEs() const {
1310 // get mirror Storage Elements for the default storage, if it is of type "alien"
1311     if(fDefaultStorage->GetType() != "alien"){
1312         AliInfo("The default storage is not of type \"alien\". Settings for Storage Elements are not taken into account!");
1313         return "";
1314     }
1315     return fDefaultStorage->GetMirrorSEs();
1316 }
1317
1318 //_____________________________________________________________________________
1319 void AliCDBManager::CacheEntry(const char* path, AliCDBEntry* entry)
1320 {
1321 // cache AliCDBEntry. Cache is valid until run number is changed.
1322
1323         AliCDBEntry *chkEntry = dynamic_cast<AliCDBEntry*> (fEntryCache.GetValue(path));
1324
1325         if(chkEntry) {
1326                 AliDebug(2, Form("Object %s already in cache !!", path));
1327                 return;
1328         } else {
1329                 AliDebug(2,Form("Caching entry %s", path));
1330         }
1331
1332         fEntryCache.Add(new TObjString(path), entry);
1333         AliDebug(2,Form("Cache entries: %d", fEntryCache.GetEntries()));
1334
1335 }
1336
1337 //_____________________________________________________________________________
1338 void AliCDBManager::Print(Option_t* /*option*/) const
1339 {
1340 // Print list of active storages and their URIs
1341
1342         TString output=Form("Run number = %d; ",fRun);
1343         output += "Cache is ";
1344         if(!fCache) output += "NOT ";
1345         output += Form("ACTIVE; Number of active storages: %d\n",fActiveStorages.GetEntries());
1346
1347         if(fDefaultStorage) {
1348                 output += Form("\t*** Default Storage URI: \"%s\"\n",fDefaultStorage->GetURI().Data());
1349 //              AliInfo(output.Data());
1350         }
1351         if(fSpecificStorages.GetEntries()>0) {
1352                 TIter iter(fSpecificStorages.GetTable());
1353                 TPair *aPair=0;
1354                 Int_t i=1;
1355                 while((aPair = (TPair*) iter.Next())){
1356                         output += Form("\t*** Specific storage %d: Path \"%s\" -> URI \"%s\"\n",
1357                                 i++, ((TObjString*) aPair->Key())->GetName(),
1358                                 ((AliCDBParam*) aPair->Value())->GetURI().Data());
1359                 }
1360         }
1361         if(fDrainStorage) {
1362                 output += Form("*** Drain Storage URI: %s\n",fDrainStorage->GetURI().Data());
1363         }
1364         AliInfo(output.Data());
1365 }
1366
1367 //_____________________________________________________________________________
1368 void AliCDBManager::SetRun(Int_t run)
1369 {
1370 // Sets current run number.
1371 // When the run number changes the caching is cleared.
1372         
1373         if(fRun == run)
1374                 return;
1375   
1376         if(fLock && fRun >= 0) {
1377                 AliFatal("Lock is ON, cannot reset run number!");
1378         }       
1379                 
1380         fRun = run;
1381         if(fRaw){
1382                 // here the LHCPeriod xml file is parsed; the string containing the correct period is returned; the default storage is set
1383                 if (fStartRunLHCPeriod <= run && fEndRunLHCPeriod >= run){
1384                         AliInfo("LHCPeriod alien folder for current run already in memory");
1385                 }else{
1386                         SetDefaultStorageFromRun(run);
1387                         if(fEntryCache.GetEntries()!=0) ClearCache();
1388                         return;
1389                 }
1390         }
1391         ClearCache();
1392         QueryCDB();
1393 }
1394
1395 //_____________________________________________________________________________
1396 void AliCDBManager::ClearCache(){
1397 // clear AliCDBEntry cache
1398
1399         AliDebug(2, Form("Cache entries to be deleted: %d",fEntryCache.GetEntries()));
1400         
1401         /*
1402         // To clean entries one by one
1403         TIter iter(fEntryCache.GetTable());
1404         TPair* pair=0;
1405         while((pair= dynamic_cast<TPair*> (iter.Next()))){
1406         
1407                 TObjString* key = dynamic_cast<TObjString*> (pair->Key());
1408                 AliCDBEntry* entry = dynamic_cast<AliCDBEntry*> (pair->Value());
1409                 AliDebug(2, Form("Deleting entry: %s", key->GetName()));
1410                 if (entry) delete entry;
1411                 delete fEntryCache.Remove(key);
1412         }
1413         */
1414         fEntryCache.DeleteAll();
1415         AliDebug(2, Form("After deleting - Cache entries: %d",fEntryCache.GetEntries()));
1416 }
1417
1418 //_____________________________________________________________________________
1419 void AliCDBManager::UnloadFromCache(const char* path){
1420 // unload cached object
1421 // that is remove the entry from the cache and the id from the list of ids
1422 //
1423         if(!fActiveStorages.GetEntries()) {
1424                 AliDebug(2, Form("No active storages. Object \"%s\" is not unloaded from cache", path));
1425                 return;
1426         }
1427
1428         AliCDBPath queryPath(path);
1429         if(!queryPath.IsValid()) return;
1430
1431         if(!queryPath.IsWildcard()) { // path is not wildcard, get it directly from the cache and unload it!
1432                 if(fEntryCache.Contains(path)){
1433                         AliDebug(2, Form("Unloading object \"%s\" from cache and from list of ids", path));
1434                         TObjString pathStr(path);
1435                         delete fEntryCache.Remove(&pathStr);
1436                         // we do not remove from the list of Id's (it's not very coherent but we leave the
1437                         // id for the benefit of the userinfo)
1438                         /*
1439                         TIter iter(fIds);
1440                         AliCDBId *id = 0;
1441                         while((id = dynamic_cast<AliCDBId*> (iter.Next()))){
1442                             if(queryPath.Comprises(id->GetPath()))
1443                                 delete fIds->Remove(id);
1444                         }*/
1445                 } else {
1446                   AliError(Form("Cache does not contain object \"%s\"!", path));
1447                 }
1448                 AliDebug(2, Form("Cache entries: %d",fEntryCache.GetEntries()));
1449                 return;
1450         }
1451
1452         // path is wildcard: loop on the cache and unload all comprised objects!
1453         TIter iter(fEntryCache.GetTable());
1454         TPair* pair = 0;
1455         Int_t removed=0;
1456
1457         while((pair = dynamic_cast<TPair*> (iter.Next()))){
1458                 AliCDBPath entryPath = pair->Key()->GetName();
1459                 if(queryPath.Comprises(entryPath)) {
1460                         AliDebug(2, Form("Unloading object \"%s\" from cache and from list of ids", entryPath.GetPath().Data()));
1461                         TObjString pathStr(entryPath.GetPath());
1462                         delete fEntryCache.Remove(&pathStr);
1463                         removed++;
1464
1465                         // we do not remove from the list of Id's (it's not very coherent but we leave the
1466                         // id for the benefit of the userinfo)
1467                         /*
1468                         TIter iterids(fIds);
1469                         AliCDBId *anId = 0;
1470                         while((anId = dynamic_cast<AliCDBId*> (iterids.Next()))){
1471                             AliCDBPath aPath = anId->GetPath();
1472                             TString aPathStr = aPath.GetPath();
1473                             if(queryPath.Comprises(aPath)) {
1474                                 delete fIds->Remove(anId);
1475                             }
1476                         }*/
1477                 }
1478         }
1479         AliDebug(2,Form("Cache entries and ids removed: %d   Remaining: %d",removed,fEntryCache.GetEntries()));
1480 }
1481
1482 //_____________________________________________________________________________
1483 void AliCDBManager::DestroyActiveStorages() {
1484 // delete list of active storages
1485
1486         fActiveStorages.DeleteAll();
1487         fSpecificStorages.DeleteAll();
1488 }
1489
1490 //_____________________________________________________________________________
1491 void AliCDBManager::DestroyActiveStorage(AliCDBStorage* /*storage*/) {
1492 // destroys active storage
1493
1494 /*
1495         TIter iter(fActiveStorages.GetTable());
1496         TPair* aPair;
1497         while ((aPair = (TPair*) iter.Next())) {
1498                 if(storage == (AliCDBStorage*) aPair->Value())
1499                         delete fActiveStorages.Remove(aPair->Key());
1500                         storage->Delete(); storage=0x0;
1501         }
1502 */
1503
1504 }
1505
1506 //_____________________________________________________________________________
1507 void AliCDBManager::QueryCDB() {
1508 // query default and specific storages for files valid for fRun. Every storage loads the Ids into its list.
1509
1510         if (fRun < 0){
1511                 AliError("Run number not yet set! Use AliCDBManager::SetRun.");
1512         return;
1513         }
1514         if (!fDefaultStorage){
1515                 AliError("Default storage is not set! Use AliCDBManager::SetDefaultStorage");
1516         return;
1517         }
1518         if(fDefaultStorage->GetType() == "alien"){
1519                 fDefaultStorage->QueryCDB(fRun);
1520         } else {
1521                 AliDebug(2,"Skipping query for valid files, it used only in grid...");
1522         }
1523
1524         TIter iter(&fSpecificStorages);
1525         TObjString *aCalibType=0;
1526         AliCDBParam* aPar=0;
1527         while((aCalibType = dynamic_cast<TObjString*> (iter.Next()))){
1528                 aPar = (AliCDBParam*) fSpecificStorages.GetValue(aCalibType);
1529                 if(aPar) {
1530                         AliDebug(2,Form("Querying specific storage %s",aCalibType->GetName()));
1531                         AliCDBStorage *aStorage = GetStorage(aPar);
1532                         if(aStorage->GetType() == "alien"){
1533                                 aStorage->QueryCDB(fRun,aCalibType->GetName());
1534                         } else {
1535                                 AliDebug(2,
1536                                         "Skipping query for valid files, it is used only in grid...");
1537                         }
1538                 }
1539         }
1540 }
1541
1542 //______________________________________________________________________________________________
1543 const char* AliCDBManager::GetDataTypeName(DataType type)
1544 {
1545   // returns the name (string) of the data type
1546
1547       switch (type){
1548             case kCondition: return "Conditions";
1549             case kReference: return "Reference";
1550             case kPrivate: return "Private";
1551      }
1552      return 0;
1553
1554 }
1555
1556 //______________________________________________________________________________________________
1557 void AliCDBManager::InitShortLived()
1558 {
1559   // Init the list of short-lived objects
1560   // currently disabled
1561
1562         fShortLived=0x0;
1563
1564 //      fShortLived = new TList();
1565 //      fShortLived->SetOwner(1);
1566 //
1567 //      fShortLived->Add(new TObjString("EMCAL/Calib/Data"));
1568 // 
1569 //      fShortLived->Add(new TObjString("HMPID/Calib/Nmean"));
1570 //      fShortLived->Add(new TObjString("HMPID/Calib/Qthre"));
1571 // 
1572 //      fShortLived->Add(new TObjString("ITS/Calib/CalibSPD"));
1573 // 
1574 //      fShortLived->Add(new TObjString("MUON/Calib/Gains"));
1575 //      fShortLived->Add(new TObjString("MUON/Calib/HV"));
1576 //      fShortLived->Add(new TObjString("MUON/Calib/Pedestals"));
1577 // 
1578 //      fShortLived->Add(new TObjString("PHOS/Calib/CpvGainPedestals"));
1579 //      fShortLived->Add(new TObjString("PHOS/Calib/EmcGainPedestals"));
1580 // 
1581 //      fShortLived->Add(new TObjString("PMD/Calib/Data"));
1582 // 
1583 //      fShortLived->Add(new TObjString("TRD/Calib/ChamberGainFactor"));
1584 //      fShortLived->Add(new TObjString("TRD/Calib/LocalGainFactor"));
1585 //      fShortLived->Add(new TObjString("TRD/Calib/ChamberT0"));
1586 //      fShortLived->Add(new TObjString("TRD/Calib/LocalT0"));
1587 //      fShortLived->Add(new TObjString("TRD/Calib/ChamberVdrift"));
1588 //      fShortLived->Add(new TObjString("TRD/Calib/LocalVdrift"));
1589 // 
1590 //      fShortLived->Add(new TObjString("ZDC/Calib/Data"));
1591
1592 }
1593
1594 //______________________________________________________________________________________________
1595 Bool_t AliCDBManager::IsShortLived(const char* path)
1596 {
1597   // returns the name (string) of the data type
1598
1599         if(!fShortLived) return kFALSE;
1600
1601         AliCDBPath aPath(path);
1602         if(!aPath.IsValid()){
1603                 AliError(Form("Not a valid path: %s", path));
1604                 return kFALSE;
1605         }
1606
1607         return fShortLived->Contains(path);
1608
1609 }
1610
1611 //______________________________________________________________________________________________
1612 ULong_t AliCDBManager::SetLock(Bool_t lock, ULong_t key){
1613   // To lock/unlock user must provide the key. A new key is provided after
1614   // each successful lock. User should always backup the returned key and
1615   // use it on next access.
1616   if (fLock == lock) return 0;  // nothing to be done
1617   if (lock) {
1618     // User wants to lock - check his identity
1619     if (fKey) {
1620       // Lock has a user - check his key
1621       if (fKey != key) {
1622         AliFatal("Wrong key provided to lock CDB. Please remove CDB lock access from your code !");
1623         return 0;
1624       }  
1625     }  
1626     // Provide new key 
1627     fKey = gSystem->Now();
1628     fLock = kTRUE;
1629     return fKey;
1630   }
1631   // User wants to unlock - check the provided key
1632   if (key != fKey) {
1633     AliFatal("Lock is ON: wrong key provided");
1634     return 0;
1635   }  
1636   fLock = kFALSE;
1637   return key;  
1638 }
1639
1640 ///////////////////////////////////////////////////////////
1641 // AliCDBManager Parameter class                         //
1642 // interface to specific AliCDBParameter class           //
1643 // (AliCDBGridParam, AliCDBLocalParam, AliCDBDumpParam)  //
1644 ///////////////////////////////////////////////////////////
1645
1646 AliCDBParam::AliCDBParam():
1647   fType(),
1648   fURI()
1649 {
1650 // constructor
1651
1652 }
1653
1654 //_____________________________________________________________________________
1655 AliCDBParam::~AliCDBParam() {
1656 // destructor
1657
1658 }
1659