]> git.uio.no Git - u/mrichter/AliRoot.git/blob - STEER/AliCDBGrid.cxx
Protection against div. by 0 in the Set(xyz,p..) for tracks with momentum along X...
[u/mrichter/AliRoot.git] / STEER / AliCDBGrid.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 /////////////////////////////////////////////////////////////////////////////////////////////////
17 //                                                                                             //
18 // AliCDBGrid                                                                                  //
19 // access class to a DataBase in an AliEn storage                                              //
20 //                                                                                             //
21 /////////////////////////////////////////////////////////////////////////////////////////////////
22
23 #include <cstdlib>
24 #include <TGrid.h>
25 #include <TGridResult.h>
26 #include <TFile.h>
27 #include <TKey.h>
28 #include <TROOT.h>
29 #include <TList.h>
30 #include <TObjArray.h>
31 #include <TObjString.h>
32 #include <TRegexp.h>
33
34 #include "AliLog.h"
35 #include "AliCDBEntry.h"
36 #include "AliCDBGrid.h"
37 #include "AliCDBManager.h"
38
39
40 ClassImp(AliCDBGrid)
41
42 //_____________________________________________________________________________
43 AliCDBGrid::AliCDBGrid(const char *gridUrl, const char *user, const char *dbFolder,
44                        const char *se, const char* cacheFolder, Bool_t operateDisconnected,
45                        Long64_t cacheSize, Long_t cleanupInterval) :
46 AliCDBStorage(),
47 fGridUrl(gridUrl),
48 fUser(user),
49 fDBFolder(dbFolder),
50 fSE(se),
51 fCacheFolder(cacheFolder),
52 fOperateDisconnected(operateDisconnected),
53 fCacheSize(cacheSize),
54 fCleanupInterval(cleanupInterval)
55 {
56 // constructor //
57
58         // if the same Grid is alreay active, skip connection
59         if (!gGrid || fGridUrl != gGrid->GridUrl()
60              || (( fUser != "" ) && ( fUser != gGrid->GetUser() )) ) {
61                 // connection to the Grid
62                 AliInfo("Connection to the Grid...");
63                 if(gGrid){
64                         AliInfo(Form("gGrid = %p; fGridUrl = %s; gGrid->GridUrl() = %s",gGrid,fGridUrl.Data(), gGrid->GridUrl()));
65                         AliInfo(Form("fUser = %s; gGrid->GetUser() = %s",fUser.Data(), gGrid->GetUser()));
66                 }
67                 TGrid::Connect(fGridUrl.Data(),fUser.Data());
68         }
69
70         if(!gGrid) {
71                 AliError("Connection failed!");
72                 return;
73         }
74
75         TString initDir(gGrid->Pwd(0));
76         if (fDBFolder[0] != '/') {
77                 fDBFolder.Prepend(initDir);
78         }
79
80         // check DBFolder: trying to cd to DBFolder; if it does not exist, create it
81         if(!gGrid->Cd(fDBFolder.Data(),0)){
82                 AliDebug(2,Form("Creating new folder <%s> ...",fDBFolder.Data()));
83                 TGridResult* res = gGrid->Command(Form("mkdir -p %s",fDBFolder.Data()));
84                 TString result = res->GetKey(0,"__result__");
85                 if(result == "0"){
86                         AliFatal(Form("Cannot create folder <%s> !",fDBFolder.Data()));
87                         return;
88                 }
89         } else {
90                 AliDebug(2,Form("Folder <%s> found",fDBFolder.Data()));
91         }
92
93         // removes any '/' at the end of path, then append one '/'
94         while(fDBFolder.EndsWith("/")) fDBFolder.Remove(fDBFolder.Last('/')); 
95         fDBFolder+="/";
96
97         fType="alien";
98         fBaseFolder = fDBFolder;
99
100         // Setting the cache
101
102         // Check if local cache folder is already defined
103         TString origCache(TFile::GetCacheFileDir());
104         if(fCacheFolder.Length() > 0) {
105                 if(origCache.Length() == 0) {
106                         AliInfo(Form("Setting local cache to: %s", fCacheFolder.Data()));
107                 } else if(fCacheFolder != origCache) {
108                         AliWarning(Form("Local cache folder was already defined, changing it to: %s",
109                                         fCacheFolder.Data()));
110                 }
111
112                 // default settings are: operateDisconnected=kTRUE, forceCacheread = kFALSE
113                 if(!TFile::SetCacheFileDir(fCacheFolder.Data(), fOperateDisconnected)) {
114                         AliError(Form("Could not set cache folder %s !", fCacheFolder.Data()));
115                         fCacheFolder = "";
116                 } else {
117                         // reset fCacheFolder because the function may have
118                         // slightly changed the folder name (e.g. '/' added)
119                         fCacheFolder = TFile::GetCacheFileDir();
120                 }
121
122                 // default settings are: cacheSize=1GB, cleanupInterval = 0
123                 if(!TFile::ShrinkCacheFileDir(fCacheSize, fCleanupInterval)) {
124                         AliError(Form("Could not set following values "
125                                 "to ShrinkCacheFileDir: cacheSize = %lld, cleanupInterval = %ld !",
126                                 fCacheSize, fCleanupInterval));
127                 }
128         }
129
130         // return to the initial directory
131         gGrid->Cd(initDir.Data(),0);
132 }
133
134 //_____________________________________________________________________________
135 AliCDBGrid::~AliCDBGrid()
136 {
137 // destructor
138         delete gGrid; gGrid=0;
139
140 }
141
142 //_____________________________________________________________________________
143 Bool_t AliCDBGrid::FilenameToId(TString& filename, AliCDBId& id) {
144 // build AliCDBId from full path filename (fDBFolder/path/Run#x_#y_v#z_s0.root)
145
146         if(filename.Contains(fDBFolder)){
147                 filename = filename(fDBFolder.Length(),filename.Length()-fDBFolder.Length());
148         }
149
150         TString idPath = filename(0,filename.Last('/'));
151         id.SetPath(idPath);
152         if(!id.IsValid()) return kFALSE;
153
154         filename=filename(idPath.Length()+1,filename.Length()-idPath.Length());
155
156         Ssiz_t mSize;
157         // valid filename: Run#firstRun_#lastRun_v#version_s0.root
158         TRegexp keyPattern("^Run[0-9]+_[0-9]+_v[0-9]+_s0.root$");
159         keyPattern.Index(filename, &mSize);
160         if (!mSize) {
161
162                 // TODO backward compatibility ... maybe remove later!
163                 Ssiz_t oldmSize;
164                 TRegexp oldKeyPattern("^Run[0-9]+_[0-9]+_v[0-9]+.root$");
165                 oldKeyPattern.Index(filename, &oldmSize);
166                 if(!oldmSize) {
167                         AliDebug(2,Form("Bad filename <%s>.", filename.Data()));
168                         return kFALSE;
169                 } else {
170                         AliDebug(2,Form("Old filename format <%s>.", filename.Data()));
171                         id.SetSubVersion(-11); // TODO trick to ensure backward compatibility
172                 }
173
174         } else {
175                 id.SetSubVersion(-1); // TODO trick to ensure backward compatibility
176         }
177
178         filename.Resize(filename.Length() - sizeof(".root") + 1);
179
180         TObjArray* strArray = (TObjArray*) filename.Tokenize("_");
181
182         TString firstRunString(((TObjString*) strArray->At(0))->GetString());
183         id.SetFirstRun(atoi(firstRunString.Data() + 3));
184         id.SetLastRun(atoi(((TObjString*) strArray->At(1))->GetString()));
185
186         TString verString(((TObjString*) strArray->At(2))->GetString());
187         id.SetVersion(atoi(verString.Data() + 1));
188
189         delete strArray;
190
191         return kTRUE;
192 }
193
194 //_____________________________________________________________________________
195 Bool_t AliCDBGrid::IdToFilename(const AliCDBId& id, TString& filename) const {
196 // build file name from AliCDBId (path, run range, version) and fDBFolder
197
198         if (!id.GetAliCDBRunRange().IsValid()) {
199                 AliDebug(2,Form("Invalid run range <%d, %d>.",
200                         id.GetFirstRun(), id.GetLastRun()));
201                 return kFALSE;
202         }
203
204         if (id.GetVersion() < 0) {
205                 AliDebug(2,Form("Invalid version <%d>.", id.GetVersion()));
206                 return kFALSE;
207         }
208
209         filename = Form("Run%d_%d_v%d",
210                                 id.GetFirstRun(),
211                                 id.GetLastRun(),
212                                 id.GetVersion());
213
214         if (id.GetSubVersion() != -11) filename += "_s0"; // TODO to ensure backward compatibility
215         filename += ".root";
216
217         filename.Prepend(fDBFolder + id.GetPath() + '/');
218
219         return kTRUE;
220 }
221
222 //_____________________________________________________________________________
223 Bool_t AliCDBGrid::PrepareId(AliCDBId& id) {
224 // prepare id (version) of the object that will be stored (called by PutEntry)
225
226         TString initDir(gGrid->Pwd(0));
227
228         TString dirName(fDBFolder);
229
230         Bool_t dirExist=kFALSE;
231
232
233
234         // go to the path; if directory does not exist, create it
235         for(int i=0;i<3;i++){
236                 //TString cmd("find -d ");
237                 //cmd += Form("%s ",dirName);
238                 //cmd += 
239                 //gGrid->Command(cmd.Data());
240                 dirName+=Form("%s/",id.GetPathLevel(i).Data());
241                 dirExist=gGrid->Cd(dirName,0);
242                 if (!dirExist) {
243                         AliDebug(2,Form("Creating new folder <%s> ...",dirName.Data()));
244                         if(!gGrid->Mkdir(dirName,"",0)){
245                                 AliError(Form("Cannot create directory <%s> !",dirName.Data()));
246                                 gGrid->Cd(initDir.Data());
247                         return kFALSE;
248                         }
249
250                         // if folders are new add tags to them
251                         if(i == 1) {
252                                 // TODO Currently disabled
253                                 // add short lived tag!
254                                 // AliInfo("Tagging level 1 folder with \"ShortLived\" tag");
255                                 // if(!AddTag(dirName,"ShortLived_try")){
256                                 //      AliError(Form("Could not tag folder %s !", dirName.Data()));
257                                 //      if(!gGrid->Rmdir(dirName.Data())){
258                                 //              AliError(Form("Unexpected: could not remove %s directory!", dirName.Data()));
259                                 //      }
260                                 //      return 0;
261                                 //}
262
263                         } else if(i == 2) {
264                                 AliDebug(2,"Tagging level 2 folder with \"CDB\" and \"CDB_MD\" tag");
265                                 if(!AddTag(dirName,"CDB")){
266                                         AliError(Form("Could not tag folder %s !", dirName.Data()));
267                                         if(!gGrid->Rmdir(dirName.Data())){
268                                                 AliError(Form("Unexpected: could not remove %s directory!", dirName.Data()));
269                                         }
270                                         return 0;
271                                 }
272                                 if(!AddTag(dirName,"CDB_MD")){
273                                         AliError(Form("Could not tag folder %s !", dirName.Data()));
274                                         if(!gGrid->Rmdir(dirName.Data())){
275                                                 AliError(Form("Unexpected: could not remove %s directory!", dirName.Data()));
276                                         }
277                                         return 0;
278                                 }
279
280                                 // TODO Currently disabled
281                                 // add short lived tag!
282                                 // TString path=id.GetPath();
283                                 // if(AliCDBManager::Instance()->IsShortLived(path.Data())) {
284                                 //      AliInfo(Form("Tagging %s as short lived", dirName.Data()));
285                                 //      if(!TagShortLived(dirName, kTRUE)){
286                                 //              AliError(Form("Could not tag folder %s !", dirName.Data()));
287                                 //              if(!gGrid->Rmdir(dirName.Data())){
288                                 //                      AliError(Form("Unexpected: could not remove %s directory!", dirName.Data()));
289                                 //              }
290                                 //              return 0;
291                                 //      }
292                                 // } else {
293                                 //      AliInfo(Form("Tagging %s as long lived", dirName.Data()));
294                                 //      if(!TagShortLived(dirName, kFALSE)){
295                                 //              AliError(Form("Could not tag folder %s !", dirName.Data()));
296                                 //              if(!gGrid->Rmdir(dirName.Data())){
297                                 //                      AliError(Form("Unexpected: could not remove %s directory!", dirName.Data()));
298                                 //              }
299                                 //              return 0;
300                                 //      }
301                                 // }
302                         }
303                 }
304         }
305         gGrid->Cd(initDir,0);
306
307         TString filename;
308         AliCDBId anId; // the id got from filename
309         AliCDBRunRange lastRunRange(-1,-1); // highest runRange found
310         Int_t lastVersion=0; // highest version found
311
312         TGridResult *res = gGrid->Ls(dirName);
313
314         //loop on the files in the directory, look for highest version
315         for(int i=0; i < res->GetEntries(); i++){
316                 filename=res->GetFileNamePath(i);
317                 if (!FilenameToId(filename, anId)) continue;
318                 if (anId.GetAliCDBRunRange().Overlaps(id.GetAliCDBRunRange()) && anId.GetVersion() > lastVersion) {
319                         lastVersion = anId.GetVersion();
320                         lastRunRange = anId.GetAliCDBRunRange();
321                 }
322
323         }
324         delete res;
325
326         // GRP entries with explicitly set version escape default incremental versioning
327         if(id.GetPath().Contains("GRP") && id.HasVersion() && lastVersion!=0)
328         {
329                 AliDebug(5,Form("Entry %s won't be put in the destination OCDB", id.ToString().Data()));
330                 return kFALSE;
331         }
332
333         id.SetVersion(lastVersion + 1);
334         id.SetSubVersion(0);
335
336         TString lastStorage = id.GetLastStorage();
337         if(lastStorage.Contains(TString("new"), TString::kIgnoreCase) && id.GetVersion() > 1 ){
338                 AliDebug(2, Form("A NEW object is being stored with version %d",
339                                         id.GetVersion()));
340                 AliDebug(2, Form("and it will hide previously stored object with version %d!",
341                                         id.GetVersion()-1));
342         }
343
344         if(!lastRunRange.IsAnyRange() && !(lastRunRange.IsEqual(&id.GetAliCDBRunRange())))
345                 AliWarning(Form("Run range modified w.r.t. previous version (Run%d_%d_v%d)",
346                         lastRunRange.GetFirstRun(), lastRunRange.GetLastRun(), id.GetVersion()));
347
348         return kTRUE;
349 }
350
351 //_____________________________________________________________________________
352 AliCDBId* AliCDBGrid::GetId(const TObjArray& validFileIds, const AliCDBId& query) {
353 // look for the Id that matches query's requests (highest or exact version)
354
355         if(validFileIds.GetEntriesFast() < 1)
356                 return NULL;
357
358         TIter iter(&validFileIds);
359
360         AliCDBId *anIdPtr=0;
361         AliCDBId* result=0;
362
363         while((anIdPtr = dynamic_cast<AliCDBId*> (iter.Next()))){
364                 if(anIdPtr->GetPath() != query.GetPath()) continue;
365
366                 //if(!CheckVersion(query, anIdPtr, result)) return NULL;
367
368                 if (!query.HasVersion()){ // look for highest version
369                         if(result && result->GetVersion() > anIdPtr->GetVersion()) continue;
370                         if(result && result->GetVersion() == anIdPtr->GetVersion()) {
371                                 AliError(Form("More than one object valid for run %d, version %d!",
372                                         query.GetFirstRun(), anIdPtr->GetVersion()));
373                                 return NULL;
374                         }
375                         result = anIdPtr;
376                 } else { // look for specified version
377                         if(query.GetVersion() != anIdPtr->GetVersion()) continue;
378                         if(result && result->GetVersion() == anIdPtr->GetVersion()){
379                                 AliError(Form("More than one object valid for run %d, version %d!",
380                                         query.GetFirstRun(), anIdPtr->GetVersion()));
381                                 return NULL;
382                         }
383                         result = anIdPtr;
384                 }
385
386         }
387         
388         if (!result) return NULL;
389
390         return dynamic_cast<AliCDBId*> (result->Clone());
391 }
392
393 //_____________________________________________________________________________
394 AliCDBId* AliCDBGrid::GetEntryId(const AliCDBId& queryId) {
395 // get AliCDBId from the database
396 // User must delete returned object
397
398         AliCDBId* dataId=0;
399
400         AliCDBId selectedId(queryId);
401         if (!selectedId.HasVersion()) {
402                 // if version is not specified, first check the selection criteria list
403                 GetSelection(&selectedId);
404         }
405
406         TObjArray validFileIds;
407         validFileIds.SetOwner(1);
408
409         // look for file matching query requests (path, runRange, version)
410         if(selectedId.GetFirstRun() == fRun && fPathFilter.Comprises(selectedId.GetAliCDBPath()) &&
411                         fVersion == selectedId.GetVersion() && !fMetaDataFilter){
412                 // look into list of valid files previously loaded with AliCDBStorage::FillValidFileIds()
413                 AliDebug(2, Form("List of files valid for run %d was loaded. Looking there for fileids valid for path %s!",
414                                         selectedId.GetFirstRun(), selectedId.GetPath().Data()));
415                 dataId = GetId(fValidFileIds, selectedId);
416
417         } else {
418                 // List of files valid for reqested run was not loaded. Looking directly into CDB
419                 AliDebug(2, Form("List of files valid for run %d and version %d was not loaded. Looking directly into CDB for fileids valid for path %s!",
420                                         selectedId.GetFirstRun(), selectedId.GetVersion(), selectedId.GetPath().Data()));
421
422                 TString filter;
423                 MakeQueryFilter(selectedId.GetFirstRun(), selectedId.GetLastRun(), 0, filter);
424
425                 TString pattern = ".root";
426                 TString optionQuery = "-y -m";
427                 if(selectedId.GetVersion() >= 0) {
428                         pattern.Prepend(Form("_v%d_s0",selectedId.GetVersion()));
429                         optionQuery = "";
430                 }
431
432                 TString folderCopy(Form("%s%s/Run",fDBFolder.Data(),selectedId.GetPath().Data()));
433
434                 if (optionQuery.Contains("-y")){
435                         AliInfo("Only latest version will be returned");
436                 }
437
438                 AliDebug(2,Form("** fDBFolder = %s, pattern = %s, filter = %s",folderCopy.Data(), pattern.Data(), filter.Data()));
439                 TGridResult *res = gGrid->Query(folderCopy, pattern, filter, optionQuery.Data());
440                 if (res) {
441                         AliCDBId validFileId;
442                         for(int i=0; i<res->GetEntries(); i++){
443                                 TString filename = res->GetKey(i, "lfn");
444                                 if(filename == "") continue;
445                                 if(FilenameToId(filename, validFileId))
446                                                 validFileIds.AddLast(validFileId.Clone());
447                         }
448                         delete res;
449                 }       
450                 dataId = GetId(validFileIds, selectedId);
451         }
452
453         return dataId;
454 }
455
456 //_____________________________________________________________________________
457 AliCDBEntry* AliCDBGrid::GetEntry(const AliCDBId& queryId) {
458 // get AliCDBEntry from the database
459
460         AliCDBId* dataId = GetEntryId(queryId);
461
462         if (!dataId) return NULL;
463
464         TString filename;
465         if (!IdToFilename(*dataId, filename)) {
466                 AliDebug(2,Form("Bad data ID encountered! Subnormal error!"));
467                 delete dataId;
468                 return NULL;
469         }
470
471         AliCDBEntry* anEntry = GetEntryFromFile(filename, dataId);
472
473         delete dataId;
474         return anEntry;
475 }
476
477 //_____________________________________________________________________________
478 AliCDBEntry* AliCDBGrid::GetEntryFromFile(TString& filename, AliCDBId* dataId){
479 // Get AliCBEntry object from file "filename"
480
481         AliDebug(2,Form("Opening file: %s",filename.Data()));
482
483         filename.Prepend("/alien");
484
485         // if option="CACHEREAD" TFile will use the local caching facility!
486         TString option="READ";
487         if(fCacheFolder != ""){
488
489                 // Check if local cache folder was changed in the meanwhile
490                 TString origCache(TFile::GetCacheFileDir());
491                 if(fCacheFolder != origCache) {
492                         AliWarning(Form("Local cache folder has been overwritten!! fCacheFolder = %s origCache = %s",
493                                         fCacheFolder.Data(), origCache.Data()));
494                         TFile::SetCacheFileDir(fCacheFolder.Data(), fOperateDisconnected);
495                         TFile::ShrinkCacheFileDir(fCacheSize, fCleanupInterval);
496                 }
497
498                 option.Prepend("CACHE");
499         }
500
501         AliDebug(2, Form("Option: %s", option.Data()));
502
503         TFile *file = TFile::Open(filename, option);
504         if (!file) {
505                 AliDebug(2,Form("Can't open file <%s>!", filename.Data()));
506                 return NULL;
507         }
508
509         // get the only AliCDBEntry object from the file
510         // the object in the file is an AliCDBEntry entry named "AliCDBEntry"
511
512         AliCDBEntry* anEntry = dynamic_cast<AliCDBEntry*> (file->Get("AliCDBEntry"));
513
514         if (!anEntry) {
515                 AliDebug(2,Form("Bad storage data: file does not contain an AliCDBEntry object!"));
516                 file->Close();
517                 return NULL;
518         }
519
520         // The object's Id is not reset during storage
521         // If object's Id runRange or version do not match with filename,
522         // it means that someone renamed file by hand. In this case a warning msg is issued.
523
524         if(anEntry){
525                 AliCDBId entryId = anEntry->GetId();
526                 Int_t tmpSubVersion = dataId->GetSubVersion();
527                 dataId->SetSubVersion(entryId.GetSubVersion()); // otherwise filename and id may mismatch
528                 if(!entryId.IsEqual(dataId)){
529                         AliWarning(Form("Mismatch between file name and object's Id!"));
530                         AliWarning(Form("File name: %s", dataId->ToString().Data()));
531                         AliWarning(Form("Object's Id: %s", entryId.ToString().Data()));
532                 }
533                 dataId->SetSubVersion(tmpSubVersion);
534         }
535
536         anEntry->SetLastStorage("grid");
537
538         // Check whether entry contains a TTree. In case load the tree in memory!
539         LoadTreeFromFile(anEntry);
540
541         // close file, return retieved entry
542         file->Close(); delete file; file=0;
543
544         return anEntry;
545 }
546
547 //_____________________________________________________________________________
548 TList* AliCDBGrid::GetEntries(const AliCDBId& queryId) {
549 // multiple request (AliCDBStorage::GetAll)
550
551         TList* result = new TList();
552         result->SetOwner();
553
554         TObjArray validFileIds;
555         validFileIds.SetOwner(1);
556
557         Bool_t alreadyLoaded = kFALSE;
558
559         // look for file matching query requests (path, runRange)
560         if(queryId.GetFirstRun() == fRun &&
561                         fPathFilter.Comprises(queryId.GetAliCDBPath()) && fVersion < 0 && !fMetaDataFilter){
562                 // look into list of valid files previously loaded with AliCDBStorage::FillValidFileIds()
563                 AliDebug(2,Form("List of files valid for run %d and for path %s was loaded. Looking there!",
564                                         queryId.GetFirstRun(), queryId.GetPath().Data()));
565
566                 alreadyLoaded = kTRUE;
567
568         } else {
569                 // List of files valid for reqested run was not loaded. Looking directly into CDB
570                 AliDebug(2,Form("List of files valid for run %d and for path %s was not loaded. Looking directly into CDB!",
571                                         queryId.GetFirstRun(), queryId.GetPath().Data()));
572
573                 TString filter;
574                 MakeQueryFilter(queryId.GetFirstRun(), queryId.GetLastRun(), 0, filter);
575
576                 TString pattern = Form("%s/Run*.root", queryId.GetPath().Data());
577                 AliDebug(2,Form("pattern: %s", pattern.Data()));
578
579                 TString optionQuery("-y");
580                 if(queryId.GetVersion() >= 0) optionQuery = "";
581
582                 if (optionQuery == "-y"){
583                         AliInfo("Only latest version will be returned");
584                 }
585
586                 TGridResult *res = gGrid->Query(fDBFolder, pattern, filter, optionQuery.Data());
587
588                 AliCDBId validFileId;
589                 for(int i=0; i<res->GetEntries(); i++){
590                         TString filename = res->GetKey(i, "lfn");
591                         if(filename == "") continue;
592                         if(FilenameToId(filename, validFileId))
593                                         validFileIds.AddLast(validFileId.Clone());
594                 }
595                 delete res;
596         }
597
598         TIter *iter=0;
599         if(alreadyLoaded){
600                 iter = new TIter(&fValidFileIds);
601         } else {
602                 iter = new TIter(&validFileIds);
603         }
604
605         TObjArray selectedIds;
606         selectedIds.SetOwner(1);
607
608         // loop on list of valid Ids to select the right version to get.
609         // According to query and to the selection criteria list, version can be the highest or exact
610         AliCDBPath pathCopy;
611         AliCDBId* anIdPtr=0;
612         AliCDBId* dataId=0;
613         AliCDBPath queryPath = queryId.GetAliCDBPath();
614         while((anIdPtr = dynamic_cast<AliCDBId*> (iter->Next()))){
615                 AliCDBPath thisCDBPath = anIdPtr->GetAliCDBPath();
616                 if(!(queryPath.Comprises(thisCDBPath)) || pathCopy.GetPath() == thisCDBPath.GetPath()) continue;
617                 pathCopy = thisCDBPath;
618
619                 // check the selection criteria list for this query
620                 AliCDBId thisId(*anIdPtr);
621                 thisId.SetVersion(queryId.GetVersion());
622                 if(!thisId.HasVersion()) GetSelection(&thisId);
623
624                 if(alreadyLoaded){
625                         dataId = GetId(fValidFileIds, thisId);
626                 } else {
627                         dataId = GetId(validFileIds, thisId);
628                 }
629                 if(dataId) selectedIds.Add(dataId);
630         }
631
632         delete iter; iter=0;
633
634         // selectedIds contains the Ids of the files matching all requests of query!
635         // All the objects are now ready to be retrieved
636         iter = new TIter(&selectedIds);
637         while((anIdPtr = dynamic_cast<AliCDBId*> (iter->Next()))){
638                 TString filename;
639                 if (!IdToFilename(*anIdPtr, filename)) {
640                         AliDebug(2,Form("Bad data ID encountered! Subnormal error!"));
641                         continue;
642                 }
643
644                 AliCDBEntry* anEntry = GetEntryFromFile(filename, anIdPtr);
645
646                 if(anEntry) result->Add(anEntry);
647
648         }
649         delete iter; iter=0;
650
651         return result;
652 }
653
654 //_____________________________________________________________________________
655 Bool_t AliCDBGrid::PutEntry(AliCDBEntry* entry) {
656 // put an AliCDBEntry object into the database
657
658         AliCDBId& id = entry->GetId();
659
660         // set version for the entry to be stored
661         if (!PrepareId(id)) return kFALSE;
662
663         // build filename from entry's id
664         TString filename;
665         if (!IdToFilename(id, filename)) {
666                 AliError("Bad ID encountered! Subnormal error!");
667                 return kFALSE;
668         }
669
670         TString folderToTag = Form("%s%s",
671                                         fDBFolder.Data(),
672                                         id.GetPath().Data());
673
674         TDirectory* saveDir = gDirectory;
675
676         TString fullFilename = Form("/alien%s", filename.Data());
677         // specify SE to filename
678         if (fSE != "default") fullFilename += Form("?se=%s",fSE.Data());
679
680         // open file
681         TFile *file = TFile::Open(fullFilename,"CREATE");
682         if(!file || !file->IsWritable()){
683                 AliError(Form("Can't open file <%s>!", filename.Data()));
684                 if(file && !file->IsWritable()) file->Close(); delete file; file=0;
685                 return kFALSE;
686         }
687
688         file->cd();
689
690         //SetTreeToFile(entry, file);
691
692         entry->SetVersion(id.GetVersion());
693
694         // write object (key name: "AliCDBEntry")
695         Bool_t result = (file->WriteTObject(entry, "AliCDBEntry") != 0);
696         if (!result) AliError(Form("Can't write entry to file <%s>!", filename.Data()));
697
698
699         if (saveDir) saveDir->cd(); else gROOT->cd();
700         file->Close(); delete file; file=0;
701
702         if(result) {
703         
704                 if(!TagFileId(filename, &id)){
705                         AliInfo(Form("CDB tagging failed. Deleting file %s!",filename.Data()));
706                         if(!gGrid->Rm(filename.Data()))
707                                 AliError("Can't delete file!");
708                         return kFALSE;
709                 }
710
711                 TagFileMetaData(filename, entry->GetMetaData());
712         }
713
714         AliInfo(Form("CDB object stored into file %s", filename.Data()));
715         AliInfo(Form("Storage Element: %s", fSE.Data()));
716         return result;
717 }
718 //_____________________________________________________________________________
719 Bool_t AliCDBGrid::AddTag(TString& folderToTag, const char* tagname){
720 // add "tagname" tag (CDB or CDB_MD) to folder where object will be stored
721
722         Bool_t result = kTRUE;
723         AliDebug(2, Form("adding %s tag to folder %s", tagname, folderToTag.Data()));
724         TString addTag = Form("addTag %s %s", folderToTag.Data(), tagname);
725         TGridResult *gridres = gGrid->Command(addTag.Data());
726         const char* resCode = gridres->GetKey(0,"__result__"); // '1' if success
727         if(resCode[0] != '1') {
728                 AliError(Form("Couldn't add %s tags to folder %s !",
729                                                 tagname, folderToTag.Data()));
730                 result = kFALSE;
731         }
732         delete gridres;
733         return result;
734 }
735
736 //_____________________________________________________________________________
737 Bool_t AliCDBGrid::TagFileId(TString& filename, const AliCDBId* id){
738 // tag stored object in CDB table using object Id's parameters
739
740
741         TString dirname(filename);
742         Int_t dirNumber = gGrid->Mkdir(dirname.Remove(dirname.Last('/')),"-d");
743         
744         TString addTagValue1 = Form("addTagValue %s CDB ", filename.Data());
745         TString addTagValue2 = Form("first_run=%d last_run=%d version=%d ",
746                                         id->GetFirstRun(),
747                                         id->GetLastRun(),
748                                         id->GetVersion());
749         TString addTagValue3 = Form("path_level_0=\"%s\" path_level_1=\"%s\" path_level_2=\"%s\" ",
750                                         id->GetPathLevel(0).Data(),
751                                         id->GetPathLevel(1).Data(),
752                                         id->GetPathLevel(2).Data());
753         //TString addTagValue4 = Form("version_path=\"%s\" dir_number=%d",Form("%d_%s",id->GetVersion(),filename.Data()),dirNumber); 
754         TString addTagValue4 = Form("version_path=\"%09d%s\" dir_number=%d",id->GetVersion(),filename.Data(),dirNumber); 
755         TString addTagValue = Form("%s%s%s%s",
756                                         addTagValue1.Data(),
757                                         addTagValue2.Data(),
758                                         addTagValue3.Data(),
759                                         addTagValue4.Data());
760
761         Bool_t result = kFALSE;
762         AliDebug(2, Form("Tagging file. Tag command: %s", addTagValue.Data()));
763         TGridResult* res = gGrid->Command(addTagValue.Data());
764         const char* resCode = res->GetKey(0,"__result__"); // '1' if success
765         if(resCode[0] != '1') {
766                 AliError(Form("Couldn't add CDB tag value to file %s !",
767                                                 filename.Data()));
768                 result = kFALSE;
769         } else {
770                 AliDebug(2, "Object successfully tagged.");
771                 result = kTRUE;
772         }
773         delete res;
774         return result;
775
776 }
777
778 //_____________________________________________________________________________
779 Bool_t AliCDBGrid::TagShortLived(TString& filename, Bool_t value){
780 // tag folder with ShortLived tag
781
782         TString addTagValue = Form("addTagValue %s ShortLived_try value=%d", filename.Data(), value);
783
784         Bool_t result = kFALSE;
785         AliDebug(2, Form("Tagging file. Tag command: %s", addTagValue.Data()));
786         TGridResult* res = gGrid->Command(addTagValue.Data());
787         const char* resCode = res->GetKey(0,"__result__"); // '1' if success
788         if(resCode[0] != '1') {
789                 AliError(Form("Couldn't add ShortLived tag value to file %s !", filename.Data()));
790                 result = kFALSE;
791         } else {
792                 AliDebug(2,"Object successfully tagged.");
793                 result = kTRUE;
794         }
795         delete res;
796         return result;
797
798 }
799
800 //_____________________________________________________________________________
801 Bool_t AliCDBGrid::TagFileMetaData(TString& filename, const AliCDBMetaData* md){
802 // tag stored object in CDB table using object Id's parameters
803
804         TString addTagValue1 = Form("addTagValue %s CDB_MD ", filename.Data());
805         TString addTagValue2 = Form("object_classname=\"%s\" responsible=\"%s\" beam_period=%d ",
806                                         md->GetObjectClassName(),
807                                         md->GetResponsible(),
808                                         md->GetBeamPeriod());
809         TString addTagValue3 = Form("aliroot_version=\"%s\" comment=\"%s\"",
810                                         md->GetAliRootVersion(),
811                                         md->GetComment());
812         TString addTagValue = Form("%s%s%s",
813                                         addTagValue1.Data(),
814                                         addTagValue2.Data(),
815                                         addTagValue3.Data());
816
817         Bool_t result = kFALSE;
818         AliDebug(2, Form("Tagging file. Tag command: %s", addTagValue.Data()));
819         TGridResult* res = gGrid->Command(addTagValue.Data());
820         const char* resCode = res->GetKey(0,"__result__"); // '1' if success
821         if(resCode[0] != '1') {
822                 AliWarning(Form("Couldn't add CDB_MD tag value to file %s !",
823                                                 filename.Data()));
824                 result = kFALSE;
825         } else {
826                 AliDebug(2,"Object successfully tagged.");
827                 result = kTRUE;
828         }
829         return result;
830 }
831
832 //_____________________________________________________________________________
833 TList* AliCDBGrid::GetIdListFromFile(const char* fileName){
834
835         TString turl(fileName);
836         turl.Prepend("/alien" + fDBFolder);
837         turl += "?se="; turl += fSE.Data();
838         TFile *file = TFile::Open(turl);
839         if (!file) {
840                 AliError(Form("Can't open selection file <%s>!", turl.Data()));
841                 return NULL;
842         }
843
844         TList *list = new TList();
845         list->SetOwner();
846         int i=0;
847         TString keycycle;
848
849         AliCDBId *id;
850         while(1){
851                 i++;
852                 keycycle = "AliCDBId;";
853                 keycycle+=i;
854                 
855                 id = (AliCDBId*) file->Get(keycycle);
856                 if(!id) break;
857                 list->AddFirst(id);
858         }
859         file->Close(); delete file; file=0;
860         
861         return list;
862
863
864 }
865
866 //_____________________________________________________________________________
867 Bool_t AliCDBGrid::Contains(const char* path) const{
868 // check for path in storage's DBFolder
869
870         TString initDir(gGrid->Pwd(0));
871         TString dirName(fDBFolder);
872         dirName += path; // dirName = fDBFolder/path
873         Bool_t result=kFALSE;
874         if (gGrid->Cd(dirName,0)) result=kTRUE;
875         gGrid->Cd(initDir.Data(),0);
876         return result;
877 }
878
879 //_____________________________________________________________________________
880 void AliCDBGrid::QueryValidFiles()
881 {
882 // Query the CDB for files valid for AliCDBStorage::fRun
883 // fills list fValidFileIds with AliCDBId objects created from file name
884
885         TString filter;
886         MakeQueryFilter(fRun, fRun, fMetaDataFilter, filter);
887
888         TString path = fPathFilter.GetPath();
889
890         TString pattern = "Run*";
891         TString optionQuery = "-y";
892         if(fVersion >= 0) {
893                 pattern += Form("_v%d_s0", fVersion);
894                 optionQuery = "";
895         }
896         pattern += ".root";
897         AliDebug(2,Form("pattern: %s", pattern.Data()));
898
899         TString tempPattern = pattern;
900         TString addFolder = "";
901         if (!path.Contains("*")){
902                 if (!path.BeginsWith("/")) addFolder += "/";
903                 addFolder += path;
904         }
905         else{
906                 if (path.BeginsWith("/")) path.Remove(0,1);
907                 if (path.EndsWith("/")) path.Remove(path.Length()-1,1); 
908                 TObjArray* tokenArr = path.Tokenize("/");
909                 if (tokenArr->GetEntries() != 3) {
910                         AliError("Not a 3 level path! Keeping old query...");
911                         tempPattern = pattern.Prepend(path+"/");
912                 }
913                 else{
914                         TString str0 = ((TObjString*)tokenArr->At(0))->String();
915                         TString str1 = ((TObjString*)tokenArr->At(1))->String();
916                         TString str2 = ((TObjString*)tokenArr->At(2))->String();
917                         if (str0 != "*" && str1 != "*" && str2 == "*"){
918                                 // e.g. "ITS/Calib/*"
919                                 addFolder = "/"+str0+"/"+str1;
920                         }
921                         else if (str0 != "*" && str1 == "*" && str2 == "*"){    
922                                 // e.g. "ITS/*/*"
923                                 addFolder = "/"+str0;
924                         }
925                         else if (str0 == "*" && str1 == "*" && str2 == "*"){    
926                                 // e.g. "*/*/*"
927                                 // do nothing: addFolder is already an empty string;
928                         }
929                         else{
930                                 // e.g. "ITS/*/RecoParam"
931                                 tempPattern = pattern.Prepend(path+"/");
932                         }
933                 }
934                 delete tokenArr; tokenArr=0;
935         }
936
937         TString folderCopy(Form("%s%s",fDBFolder.Data(),addFolder.Data()));
938
939         AliDebug(2,Form("fDBFolder = %s, pattern = %s, filter = %s",folderCopy.Data(), tempPattern.Data(), filter.Data()));
940
941         if (optionQuery == "-y"){
942                 AliInfo("Only latest version will be returned");
943         } 
944
945         TGridResult *res = gGrid->Query(folderCopy, tempPattern, filter, optionQuery.Data());  
946
947         if (!res) {
948                 AliError("Grid query failed");
949                 return;
950         }
951
952         TIter next(res);
953         TMap *map;
954         while ((map = (TMap*)next())) {
955           TObjString *entry;
956           if ((entry = (TObjString *) ((TMap *)map)->GetValue("lfn"))) {
957             TString& filename = entry->String();
958             if(filename.IsNull()) continue;
959             AliDebug(2,Form("Found valid file: %s", filename.Data()));
960             AliCDBId *validFileId = new AliCDBId;
961             Bool_t result = FilenameToId(filename, *validFileId);
962             if(result) {
963               fValidFileIds.AddLast(validFileId);
964             }
965             else {
966               delete validFileId;
967             }
968           }
969         }
970         delete res;
971
972 }
973
974 //_____________________________________________________________________________
975 void AliCDBGrid::MakeQueryFilter(Int_t firstRun, Int_t lastRun,
976                                         const AliCDBMetaData* md, TString& result) const
977 {
978 // create filter for file query
979
980         result = Form("CDB:first_run<=%d and CDB:last_run>=%d", firstRun, lastRun);
981
982 //      if(version >= 0) {
983 //              result += Form(" and CDB:version=%d", version);
984 //      }
985 //      if(pathFilter.GetLevel0() != "*") {
986 //              result += Form(" and CDB:path_level_0=\"%s\"", pathFilter.GetLevel0().Data());
987 //      }
988 //      if(pathFilter.GetLevel1() != "*") {
989 //              result += Form(" and CDB:path_level_1=\"%s\"", pathFilter.GetLevel1().Data());
990 //      }
991 //      if(pathFilter.GetLevel2() != "*") {
992 //              result += Form(" and CDB:path_level_2=\"%s\"", pathFilter.GetLevel2().Data());
993 //      }
994
995         if(md){
996                 if(md->GetObjectClassName()[0] != '\0') {
997                         result += Form(" and CDB_MD:object_classname=\"%s\"", md->GetObjectClassName());
998                 }
999                 if(md->GetResponsible()[0] != '\0') {
1000                         result += Form(" and CDB_MD:responsible=\"%s\"", md->GetResponsible());
1001                 }
1002                 if(md->GetBeamPeriod() != 0) {
1003                         result += Form(" and CDB_MD:beam_period=%d", md->GetBeamPeriod());
1004                 }
1005                 if(md->GetAliRootVersion()[0] != '\0') {
1006                         result += Form(" and CDB_MD:aliroot_version=\"%s\"", md->GetAliRootVersion());
1007                 }
1008                 if(md->GetComment()[0] != '\0') {
1009                         result += Form(" and CDB_MD:comment=\"%s\"", md->GetComment());
1010                 }
1011         }
1012         AliDebug(2, Form("filter: %s",result.Data()));
1013
1014 }
1015
1016 //_____________________________________________________________________________
1017 Int_t AliCDBGrid::GetLatestVersion(const char* path, Int_t run){
1018 // get last version found in the database valid for run and path
1019
1020         AliCDBPath aCDBPath(path);
1021         if(!aCDBPath.IsValid() || aCDBPath.IsWildcard()) {
1022                 AliError(Form("Invalid path in request: %s", path));
1023                 return -1;
1024         }
1025         AliCDBId query(path, run, run, -1, -1);
1026
1027         AliCDBId* dataId = 0;
1028         // look for file matching query requests (path, runRange, version)
1029         if(run == fRun && fPathFilter.Comprises(aCDBPath) && fVersion < 0){
1030                 // look into list of valid files previously loaded with AliCDBStorage::FillValidFileIds()
1031                 AliDebug(2, Form("List of files valid for run %d and for path %s was loaded. Looking there!",
1032                                         run, path));
1033                 dataId = GetId(fValidFileIds, query);
1034                 if (!dataId) return -1;
1035                 Int_t version = dataId->GetVersion();
1036                 delete dataId;
1037                 return version;
1038
1039         }
1040         // List of files valid for reqested run was not loaded. Looking directly into CDB
1041         AliDebug(2, Form("List of files valid for run %d and for path %s was not loaded. Looking directly into CDB!",
1042                                 run, path));
1043
1044         TObjArray validFileIds;
1045         validFileIds.SetOwner(1);
1046
1047         TString filter;
1048         MakeQueryFilter(run, run, 0, filter);
1049
1050         TString pattern = Form("%s/Run*.root", path);
1051         AliDebug(2,Form("pattern: %s", pattern.Data()));
1052
1053         TGridResult *res = gGrid->Query(fDBFolder, pattern, filter, "-y");
1054         AliCDBId validFileId;
1055         if (res->GetEntries()>1){
1056                 AliWarning("Number of found entries >1, even if option -y was used");
1057                 for(int i=0; i<res->GetEntries(); i++){
1058                         TString filename = res->GetKey(i, "lfn");
1059                         if(filename == "") continue;
1060                         if(FilenameToId(filename, validFileId))
1061                                 validFileIds.AddLast(validFileId.Clone());
1062                 }
1063                 dataId = GetId(validFileIds, query);
1064                 if (!dataId) return -1;
1065                 
1066                 Int_t version = dataId->GetVersion();
1067                 delete dataId;
1068                 return version;
1069         }
1070         else if (res->GetEntries()==1){
1071                 TString filename = res->GetKey(0, "lfn");
1072                 if(filename == "") {
1073                         AliError("The only entry found has filename empty");
1074                         return -1;
1075                 }
1076                 if(FilenameToId(filename, validFileId)) return validFileId.GetVersion();
1077                 else{
1078                         AliError("Impossible to get FileId from filename");
1079                         return -1;
1080                 }
1081         }
1082         else {
1083                 AliError("No entries found");
1084                 return -1;
1085         }
1086
1087         delete res;
1088
1089
1090 }
1091
1092 //_____________________________________________________________________________
1093 Int_t AliCDBGrid::GetLatestSubVersion(const char* /*path*/, Int_t /*run*/, Int_t /*version*/){
1094 // get last subversion found in the database valid for run and path
1095         AliError("Objects in GRID storage have no sub version!");
1096         return -1;
1097 }
1098
1099
1100 /////////////////////////////////////////////////////////////////////////////////////////////////
1101 //                                                                                             //
1102 // AliCDBGrid factory                                                                          //
1103 //                                                                                             //
1104 /////////////////////////////////////////////////////////////////////////////////////////////////
1105
1106 ClassImp(AliCDBGridFactory)
1107
1108 //_____________________________________________________________________________
1109 Bool_t AliCDBGridFactory::Validate(const char* gridString) {
1110 // check if the string is valid Grid URI
1111
1112         TRegexp gridPattern("^alien://.+$");
1113
1114         return TString(gridString).Contains(gridPattern);
1115 }
1116
1117 //_____________________________________________________________________________
1118 AliCDBParam* AliCDBGridFactory::CreateParameter(const char* gridString) {
1119 // create AliCDBGridParam class from the URI string
1120
1121         if (!Validate(gridString)) {
1122                 return NULL;
1123         }
1124
1125         TString buffer(gridString);
1126
1127         TString gridUrl         = "alien://";
1128         TString user            = "";
1129         TString dbFolder        = "";
1130         TString se              = "default";
1131         TString cacheFolder     = "";
1132         Bool_t  operateDisconnected = kTRUE;
1133         Long64_t cacheSize          = (UInt_t) 1024*1024*1024; // 1GB
1134         Long_t cleanupInterval      = 0;
1135
1136         TObjArray *arr = buffer.Tokenize('?');
1137         TIter iter(arr);
1138         TObjString *str = 0;
1139
1140         while((str = (TObjString*) iter.Next())){
1141                 TString entry(str->String());
1142                 Int_t indeq = entry.Index('=');
1143                 if(indeq == -1) {
1144                         if(entry.BeginsWith("alien://")) { // maybe it's a gridUrl!
1145                                 gridUrl = entry;
1146                                 continue;
1147                         } else {
1148                                 AliError(Form("Invalid entry! %s",entry.Data()));
1149                                 continue;
1150                         }
1151                 }
1152                 
1153                 TString key = entry(0,indeq);
1154                 TString value = entry(indeq+1,entry.Length()-indeq);
1155
1156                 if(key.Contains("grid",TString::kIgnoreCase)) {
1157                         gridUrl += value;
1158                 }
1159                 else if (key.Contains("user",TString::kIgnoreCase)){
1160                         user = value;
1161                 }
1162                 else if (key.Contains("se",TString::kIgnoreCase)){
1163                         se = value;
1164                 }
1165                 else if (key.Contains("cacheF",TString::kIgnoreCase)){
1166                         cacheFolder = value;
1167                         if (!cacheFolder.IsNull() && !cacheFolder.EndsWith("/"))
1168                                 cacheFolder += "/";
1169                 }
1170                 else if (key.Contains("folder",TString::kIgnoreCase)){
1171                         dbFolder = value;
1172                 }
1173                 else if (key.Contains("operateDisc",TString::kIgnoreCase)){
1174                         if(value == "kTRUE") {
1175                                 operateDisconnected = kTRUE;
1176                         } else if (value == "kFALSE") {
1177                                 operateDisconnected = kFALSE;
1178                         } else if (value == "0" || value == "1") {
1179                                 operateDisconnected = (Bool_t) value.Atoi();
1180                         } else {
1181                                 AliError(Form("Invalid entry! %s",entry.Data()));
1182                                 return NULL;
1183                         }
1184                 }
1185                 else if (key.Contains("cacheS",TString::kIgnoreCase)){
1186                         if(value.IsDigit()) {
1187                                 cacheSize = value.Atoi();
1188                         } else {
1189                                 AliError(Form("Invalid entry! %s",entry.Data()));
1190                                 return NULL;
1191                         }
1192                 }
1193                 else if (key.Contains("cleanupInt",TString::kIgnoreCase)){
1194                         if(value.IsDigit()) {
1195                                 cleanupInterval = value.Atoi();
1196                         } else {
1197                                 AliError(Form("Invalid entry! %s",entry.Data()));
1198                                 return NULL;
1199                         }
1200                 }
1201                 else{
1202                         AliError(Form("Invalid entry! %s",entry.Data()));
1203                         return NULL;
1204                 }
1205         }
1206         delete arr; arr=0;
1207
1208         AliDebug(2, Form("gridUrl:      %s", gridUrl.Data()));
1209         AliDebug(2, Form("user: %s", user.Data()));
1210         AliDebug(2, Form("dbFolder:     %s", dbFolder.Data()));
1211         AliDebug(2, Form("s.e.: %s", se.Data()));
1212         AliDebug(2, Form("local cache folder: %s", cacheFolder.Data()));
1213         AliDebug(2, Form("local cache operate disconnected: %d", operateDisconnected));
1214         AliDebug(2, Form("local cache size: %lld", cacheSize));
1215         AliDebug(2, Form("local cache cleanup interval: %ld", cleanupInterval));
1216
1217         if(dbFolder == ""){
1218                 AliError("Base folder must be specified!");
1219                 return NULL;
1220         }
1221
1222         return new AliCDBGridParam(gridUrl.Data(), user.Data(),
1223                           dbFolder.Data(), se.Data(), cacheFolder.Data(),
1224                           operateDisconnected, cacheSize, cleanupInterval);
1225 }
1226
1227 //_____________________________________________________________________________
1228 AliCDBStorage* AliCDBGridFactory::Create(const AliCDBParam* param) {
1229 // create AliCDBGrid storage instance from parameters
1230         
1231         AliCDBGrid *grid = 0;
1232         if (AliCDBGridParam::Class() == param->IsA()) {
1233
1234                 const AliCDBGridParam* gridParam = (const AliCDBGridParam*) param;
1235                 grid = new AliCDBGrid(gridParam->GridUrl().Data(),
1236                                       gridParam->GetUser().Data(),
1237                                       gridParam->GetDBFolder().Data(),
1238                                       gridParam->GetSE().Data(),
1239                                       gridParam->GetCacheFolder().Data(),
1240                                       gridParam->GetOperateDisconnected(),
1241                                       gridParam->GetCacheSize(),
1242                                       gridParam->GetCleanupInterval());
1243
1244         }
1245
1246         if(!gGrid && grid) {
1247                 delete grid; grid=0;
1248         }
1249
1250         return grid;
1251 }
1252
1253 /////////////////////////////////////////////////////////////////////////////////////////////////
1254 //                                                                                             //
1255 // AliCDBGrid Parameter class                                                                  //                                         //
1256 //                                                                                             //
1257 /////////////////////////////////////////////////////////////////////////////////////////////////
1258
1259 ClassImp(AliCDBGridParam)
1260
1261 //_____________________________________________________________________________
1262 AliCDBGridParam::AliCDBGridParam():
1263  AliCDBParam(),
1264  fGridUrl(),
1265  fUser(),
1266  fDBFolder(),
1267  fSE(),
1268  fCacheFolder(),
1269  fOperateDisconnected(),
1270  fCacheSize(),
1271  fCleanupInterval()
1272
1273  {
1274 // default constructor
1275
1276 }
1277
1278 //_____________________________________________________________________________
1279 AliCDBGridParam::AliCDBGridParam(const char* gridUrl, const char* user, const char* dbFolder,
1280                                 const char* se, const char* cacheFolder, Bool_t operateDisconnected,
1281                                 Long64_t cacheSize, Long_t cleanupInterval):
1282  AliCDBParam(),
1283  fGridUrl(gridUrl),
1284  fUser(user),
1285  fDBFolder(dbFolder),
1286  fSE(se),
1287  fCacheFolder(cacheFolder),
1288  fOperateDisconnected(operateDisconnected),
1289  fCacheSize(cacheSize),
1290  fCleanupInterval(cleanupInterval)
1291 {
1292 // constructor
1293
1294         SetType("alien");
1295
1296         TString uri = Form("%s?User=%s?DBFolder=%s?SE=%s?CacheFolder=%s"
1297                         "?OperateDisconnected=%d?CacheSize=%lld?CleanupInterval=%ld",
1298                         fGridUrl.Data(), fUser.Data(),
1299                         fDBFolder.Data(), fSE.Data(), fCacheFolder.Data(),
1300                         fOperateDisconnected, fCacheSize, fCleanupInterval);
1301
1302         SetURI(uri.Data());
1303 }
1304
1305 //_____________________________________________________________________________
1306 AliCDBGridParam::~AliCDBGridParam() {
1307 // destructor
1308
1309 }
1310
1311 //_____________________________________________________________________________
1312 AliCDBParam* AliCDBGridParam::CloneParam() const {
1313 // clone parameter
1314
1315         return new AliCDBGridParam(fGridUrl.Data(), fUser.Data(),
1316                                         fDBFolder.Data(), fSE.Data(), fCacheFolder.Data(),
1317                                         fOperateDisconnected, fCacheSize, fCleanupInterval);
1318 }
1319
1320 //_____________________________________________________________________________
1321 ULong_t AliCDBGridParam::Hash() const {
1322 // return Hash function
1323
1324         return fGridUrl.Hash()+fUser.Hash()+fDBFolder.Hash()+fSE.Hash()+fCacheFolder.Hash();
1325 }
1326
1327 //_____________________________________________________________________________
1328 Bool_t AliCDBGridParam::IsEqual(const TObject* obj) const {
1329 // check if this object is equal to AliCDBParam obj
1330
1331         if (this == obj) {
1332                 return kTRUE;
1333         }
1334
1335         if (AliCDBGridParam::Class() != obj->IsA()) {
1336                 return kFALSE;
1337         }
1338
1339         AliCDBGridParam* other = (AliCDBGridParam*) obj;
1340
1341         if(fGridUrl != other->fGridUrl) return kFALSE;
1342         if(fUser != other->fUser) return kFALSE;
1343         if(fDBFolder != other->fDBFolder) return kFALSE;
1344         if(fSE != other->fSE) return kFALSE;
1345         if(fCacheFolder != other->fCacheFolder) return kFALSE;
1346         if(fOperateDisconnected != other->fOperateDisconnected) return kFALSE;
1347         if(fCacheSize != other->fCacheSize) return kFALSE;
1348         if(fCleanupInterval != other->fCleanupInterval) return kFALSE;
1349         return kTRUE;
1350 }
1351