1 /**************************************************************************
2 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
4 * Author: The ALICE Off-line Project. *
5 * Contributors are mentioned in the code where appropriate. *
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 **************************************************************************/
16 /////////////////////////////////////////////////////////////////////////////////////////////////
19 // access class to a DataBase in an AliEn storage //
21 /////////////////////////////////////////////////////////////////////////////////////////////////
25 #include <TGridResult.h>
30 #include <TObjArray.h>
31 #include <TObjString.h>
36 #include "AliCDBEntry.h"
37 #include "AliCDBGrid.h"
38 #include "AliCDBManager.h"
43 //_____________________________________________________________________________
44 AliCDBGrid::AliCDBGrid(const char *gridUrl, const char *user, const char *dbFolder,
45 const char *se, const char* cacheFolder, Bool_t operateDisconnected,
46 Long64_t cacheSize, Long_t cleanupInterval) :
52 fCacheFolder(cacheFolder),
53 fOperateDisconnected(operateDisconnected),
54 fCacheSize(cacheSize),
55 fCleanupInterval(cleanupInterval)
59 // if the same Grid is alreay active, skip connection
60 if (!gGrid || fGridUrl != gGrid->GridUrl()
61 || (( fUser != "" ) && ( fUser != gGrid->GetUser() )) ) {
62 // connection to the Grid
63 AliInfo("Connection to the Grid...");
65 AliInfo(Form("gGrid = %p; fGridUrl = %s; gGrid->GridUrl() = %s",gGrid,fGridUrl.Data(), gGrid->GridUrl()));
66 AliInfo(Form("fUser = %s; gGrid->GetUser() = %s",fUser.Data(), gGrid->GetUser()));
68 TGrid::Connect(fGridUrl.Data(),fUser.Data());
72 AliError("Connection failed!");
76 TString initDir(gGrid->Pwd(0));
77 if (fDBFolder[0] != '/') {
78 fDBFolder.Prepend(initDir);
81 // check DBFolder: trying to cd to DBFolder; if it does not exist, create it
82 if(!gGrid->Cd(fDBFolder.Data(),0)){
83 AliDebug(2,Form("Creating new folder <%s> ...",fDBFolder.Data()));
84 TGridResult* res = gGrid->Command(Form("mkdir -p %s",fDBFolder.Data()));
85 TString result = res->GetKey(0,"__result__");
87 AliFatal(Form("Cannot create folder <%s> !",fDBFolder.Data()));
91 AliDebug(2,Form("Folder <%s> found",fDBFolder.Data()));
94 // removes any '/' at the end of path, then append one '/'
95 while(fDBFolder.EndsWith("/")) fDBFolder.Remove(fDBFolder.Last('/'));
99 fBaseFolder = fDBFolder;
103 // Check if local cache folder is already defined
104 TString origCache(TFile::GetCacheFileDir());
105 if(fCacheFolder.Length() > 0) {
106 if(origCache.Length() == 0) {
107 AliInfo(Form("Setting local cache to: %s", fCacheFolder.Data()));
108 } else if(fCacheFolder != origCache) {
109 AliWarning(Form("Local cache folder was already defined, changing it to: %s",
110 fCacheFolder.Data()));
113 // default settings are: operateDisconnected=kTRUE, forceCacheread = kFALSE
114 if(!TFile::SetCacheFileDir(fCacheFolder.Data(), fOperateDisconnected)) {
115 AliError(Form("Could not set cache folder %s !", fCacheFolder.Data()));
118 // reset fCacheFolder because the function may have
119 // slightly changed the folder name (e.g. '/' added)
120 fCacheFolder = TFile::GetCacheFileDir();
123 // default settings are: cacheSize=1GB, cleanupInterval = 0
124 if(!TFile::ShrinkCacheFileDir(fCacheSize, fCleanupInterval)) {
125 AliError(Form("Could not set following values "
126 "to ShrinkCacheFileDir: cacheSize = %lld, cleanupInterval = %ld !",
127 fCacheSize, fCleanupInterval));
131 // return to the initial directory
132 gGrid->Cd(initDir.Data(),0);
135 //_____________________________________________________________________________
136 AliCDBGrid::~AliCDBGrid()
139 delete gGrid; gGrid=0;
143 //_____________________________________________________________________________
144 Bool_t AliCDBGrid::FilenameToId(TString& filename, AliCDBId& id) {
145 // build AliCDBId from full path filename (fDBFolder/path/Run#x_#y_v#z_s0.root)
147 if(filename.Contains(fDBFolder)){
148 filename = filename(fDBFolder.Length(),filename.Length()-fDBFolder.Length());
151 TString idPath = filename(0,filename.Last('/'));
153 if(!id.IsValid()) return kFALSE;
155 filename=filename(idPath.Length()+1,filename.Length()-idPath.Length());
158 // valid filename: Run#firstRun_#lastRun_v#version_s0.root
159 TRegexp keyPattern("^Run[0-9]+_[0-9]+_v[0-9]+_s0.root$");
160 keyPattern.Index(filename, &mSize);
163 // TODO backward compatibility ... maybe remove later!
165 TRegexp oldKeyPattern("^Run[0-9]+_[0-9]+_v[0-9]+.root$");
166 oldKeyPattern.Index(filename, &oldmSize);
168 AliDebug(2,Form("Bad filename <%s>.", filename.Data()));
171 AliDebug(2,Form("Old filename format <%s>.", filename.Data()));
172 id.SetSubVersion(-11); // TODO trick to ensure backward compatibility
176 id.SetSubVersion(-1); // TODO trick to ensure backward compatibility
179 filename.Resize(filename.Length() - sizeof(".root") + 1);
181 TObjArray* strArray = (TObjArray*) filename.Tokenize("_");
183 TString firstRunString(((TObjString*) strArray->At(0))->GetString());
184 id.SetFirstRun(atoi(firstRunString.Data() + 3));
185 id.SetLastRun(atoi(((TObjString*) strArray->At(1))->GetString()));
187 TString verString(((TObjString*) strArray->At(2))->GetString());
188 id.SetVersion(atoi(verString.Data() + 1));
195 //_____________________________________________________________________________
196 Bool_t AliCDBGrid::IdToFilename(const AliCDBId& id, TString& filename) const {
197 // build file name from AliCDBId (path, run range, version) and fDBFolder
199 if (!id.GetAliCDBRunRange().IsValid()) {
200 AliDebug(2,Form("Invalid run range <%d, %d>.",
201 id.GetFirstRun(), id.GetLastRun()));
205 if (id.GetVersion() < 0) {
206 AliDebug(2,Form("Invalid version <%d>.", id.GetVersion()));
210 filename = Form("Run%d_%d_v%d",
215 if (id.GetSubVersion() != -11) filename += "_s0"; // TODO to ensure backward compatibility
218 filename.Prepend(fDBFolder + id.GetPath() + '/');
223 //_____________________________________________________________________________
224 void AliCDBGrid::SetRetry(Int_t nretry, Int_t totsec) {
226 // Function to set the exponential retry for putting entries in the OCDB
228 const Double_t klog2 = TMath::Log(2.);
230 fRetrySeconds = TMath::Max(TMath::Exp(TMath::Log(totsec)-nretry*klog2),1.);
234 //_____________________________________________________________________________
235 Bool_t AliCDBGrid::PrepareId(AliCDBId& id) {
236 // prepare id (version) of the object that will be stored (called by PutEntry)
238 TString initDir(gGrid->Pwd(0));
240 TString dirName(fDBFolder);
242 Bool_t dirExist=kFALSE;
246 // go to the path; if directory does not exist, create it
247 for(int i=0;i<3;i++){
248 //TString cmd("find -d ");
249 //cmd += Form("%s ",dirName);
251 //gGrid->Command(cmd.Data());
252 dirName+=Form("%s/",id.GetPathLevel(i).Data());
253 dirExist=gGrid->Cd(dirName,0);
255 AliDebug(2,Form("Creating new folder <%s> ...",dirName.Data()));
256 if(!gGrid->Mkdir(dirName,"",0)){
257 AliError(Form("Cannot create directory <%s> !",dirName.Data()));
258 gGrid->Cd(initDir.Data());
262 // if folders are new add tags to them
264 // TODO Currently disabled
265 // add short lived tag!
266 // AliInfo("Tagging level 1 folder with \"ShortLived\" tag");
267 // if(!AddTag(dirName,"ShortLived_try")){
268 // AliError(Form("Could not tag folder %s !", dirName.Data()));
269 // if(!gGrid->Rmdir(dirName.Data())){
270 // AliError(Form("Unexpected: could not remove %s directory!", dirName.Data()));
276 AliDebug(2,"Tagging level 2 folder with \"CDB\" and \"CDB_MD\" tag");
277 if(!AddTag(dirName,"CDB")){
278 AliError(Form("Could not tag folder %s !", dirName.Data()));
279 if(!gGrid->Rmdir(dirName.Data())){
280 AliError(Form("Unexpected: could not remove %s directory!", dirName.Data()));
284 if(!AddTag(dirName,"CDB_MD")){
285 AliError(Form("Could not tag folder %s !", dirName.Data()));
286 if(!gGrid->Rmdir(dirName.Data())){
287 AliError(Form("Unexpected: could not remove %s directory!", dirName.Data()));
292 // TODO Currently disabled
293 // add short lived tag!
294 // TString path=id.GetPath();
295 // if(AliCDBManager::Instance()->IsShortLived(path.Data())) {
296 // AliInfo(Form("Tagging %s as short lived", dirName.Data()));
297 // if(!TagShortLived(dirName, kTRUE)){
298 // AliError(Form("Could not tag folder %s !", dirName.Data()));
299 // if(!gGrid->Rmdir(dirName.Data())){
300 // AliError(Form("Unexpected: could not remove %s directory!", dirName.Data()));
305 // AliInfo(Form("Tagging %s as long lived", dirName.Data()));
306 // if(!TagShortLived(dirName, kFALSE)){
307 // AliError(Form("Could not tag folder %s !", dirName.Data()));
308 // if(!gGrid->Rmdir(dirName.Data())){
309 // AliError(Form("Unexpected: could not remove %s directory!", dirName.Data()));
317 gGrid->Cd(initDir,0);
320 AliCDBId anId; // the id got from filename
321 AliCDBRunRange lastRunRange(-1,-1); // highest runRange found
322 Int_t lastVersion=0; // highest version found
324 TGridResult *res = gGrid->Ls(dirName);
326 //loop on the files in the directory, look for highest version
327 for(int i=0; i < res->GetEntries(); i++){
328 filename=res->GetFileNamePath(i);
329 if (!FilenameToId(filename, anId)) continue;
330 if (anId.GetAliCDBRunRange().Overlaps(id.GetAliCDBRunRange()) && anId.GetVersion() > lastVersion) {
331 lastVersion = anId.GetVersion();
332 lastRunRange = anId.GetAliCDBRunRange();
338 // GRP entries with explicitly set version escape default incremental versioning
339 if(id.GetPath().Contains("GRP") && id.HasVersion() && lastVersion!=0)
341 AliDebug(5,Form("Entry %s won't be put in the destination OCDB", id.ToString().Data()));
345 id.SetVersion(lastVersion + 1);
348 TString lastStorage = id.GetLastStorage();
349 if(lastStorage.Contains(TString("new"), TString::kIgnoreCase) && id.GetVersion() > 1 ){
350 AliDebug(2, Form("A NEW object is being stored with version %d",
352 AliDebug(2, Form("and it will hide previously stored object with version %d!",
356 if(!lastRunRange.IsAnyRange() && !(lastRunRange.IsEqual(&id.GetAliCDBRunRange())))
357 AliWarning(Form("Run range modified w.r.t. previous version (Run%d_%d_v%d)",
358 lastRunRange.GetFirstRun(), lastRunRange.GetLastRun(), id.GetVersion()));
363 //_____________________________________________________________________________
364 AliCDBId* AliCDBGrid::GetId(const TObjArray& validFileIds, const AliCDBId& query) {
365 // look for the Id that matches query's requests (highest or exact version)
367 if(validFileIds.GetEntriesFast() < 1)
370 TIter iter(&validFileIds);
375 while((anIdPtr = dynamic_cast<AliCDBId*> (iter.Next()))){
376 if(anIdPtr->GetPath() != query.GetPath()) continue;
378 //if(!CheckVersion(query, anIdPtr, result)) return NULL;
380 if (!query.HasVersion()){ // look for highest version
381 if(result && result->GetVersion() > anIdPtr->GetVersion()) continue;
382 if(result && result->GetVersion() == anIdPtr->GetVersion()) {
383 AliError(Form("More than one object valid for run %d, version %d!",
384 query.GetFirstRun(), anIdPtr->GetVersion()));
388 } else { // look for specified version
389 if(query.GetVersion() != anIdPtr->GetVersion()) continue;
390 if(result && result->GetVersion() == anIdPtr->GetVersion()){
391 AliError(Form("More than one object valid for run %d, version %d!",
392 query.GetFirstRun(), anIdPtr->GetVersion()));
400 if (!result) return NULL;
402 return dynamic_cast<AliCDBId*> (result->Clone());
405 //_____________________________________________________________________________
406 AliCDBId* AliCDBGrid::GetEntryId(const AliCDBId& queryId) {
407 // get AliCDBId from the database
408 // User must delete returned object
412 AliCDBId selectedId(queryId);
413 if (!selectedId.HasVersion()) {
414 // if version is not specified, first check the selection criteria list
415 GetSelection(&selectedId);
418 TObjArray validFileIds;
419 validFileIds.SetOwner(1);
421 // look for file matching query requests (path, runRange, version)
422 if(selectedId.GetFirstRun() == fRun && fPathFilter.Comprises(selectedId.GetAliCDBPath()) &&
423 fVersion == selectedId.GetVersion() && !fMetaDataFilter){
424 // look into list of valid files previously loaded with AliCDBStorage::FillValidFileIds()
425 AliDebug(2, Form("List of files valid for run %d was loaded. Looking there for fileids valid for path %s!",
426 selectedId.GetFirstRun(), selectedId.GetPath().Data()));
427 dataId = GetId(fValidFileIds, selectedId);
430 // List of files valid for reqested run was not loaded. Looking directly into CDB
431 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!",
432 selectedId.GetFirstRun(), selectedId.GetVersion(), selectedId.GetPath().Data()));
435 MakeQueryFilter(selectedId.GetFirstRun(), selectedId.GetLastRun(), 0, filter);
437 TString pattern = ".root";
438 TString optionQuery = "-y -m";
439 if(selectedId.GetVersion() >= 0) {
440 pattern.Prepend(Form("_v%d_s0",selectedId.GetVersion()));
444 TString folderCopy(Form("%s%s/Run",fDBFolder.Data(),selectedId.GetPath().Data()));
446 if (optionQuery.Contains("-y")){
447 AliInfo("Only latest version will be returned");
450 AliDebug(2,Form("** fDBFolder = %s, pattern = %s, filter = %s",folderCopy.Data(), pattern.Data(), filter.Data()));
451 TGridResult *res = gGrid->Query(folderCopy, pattern, filter, optionQuery.Data());
453 AliCDBId validFileId;
454 for(int i=0; i<res->GetEntries(); i++){
455 TString filename = res->GetKey(i, "lfn");
456 if(filename == "") continue;
457 if(FilenameToId(filename, validFileId))
458 validFileIds.AddLast(validFileId.Clone());
462 dataId = GetId(validFileIds, selectedId);
468 //_____________________________________________________________________________
469 AliCDBEntry* AliCDBGrid::GetEntry(const AliCDBId& queryId) {
470 // get AliCDBEntry from the database
472 AliCDBId* dataId = GetEntryId(queryId);
474 if (!dataId) return NULL;
477 if (!IdToFilename(*dataId, filename)) {
478 AliDebug(2,Form("Bad data ID encountered! Subnormal error!"));
483 AliCDBEntry* anEntry = GetEntryFromFile(filename, dataId);
489 //_____________________________________________________________________________
490 AliCDBEntry* AliCDBGrid::GetEntryFromFile(TString& filename, AliCDBId* dataId){
491 // Get AliCBEntry object from file "filename"
493 AliDebug(2,Form("Opening file: %s",filename.Data()));
495 filename.Prepend("/alien");
497 // if option="CACHEREAD" TFile will use the local caching facility!
498 TString option="READ";
499 if(fCacheFolder != ""){
501 // Check if local cache folder was changed in the meanwhile
502 TString origCache(TFile::GetCacheFileDir());
503 if(fCacheFolder != origCache) {
504 AliWarning(Form("Local cache folder has been overwritten!! fCacheFolder = %s origCache = %s",
505 fCacheFolder.Data(), origCache.Data()));
506 TFile::SetCacheFileDir(fCacheFolder.Data(), fOperateDisconnected);
507 TFile::ShrinkCacheFileDir(fCacheSize, fCleanupInterval);
510 option.Prepend("CACHE");
513 AliDebug(2, Form("Option: %s", option.Data()));
515 TFile *file = TFile::Open(filename, option);
517 AliDebug(2,Form("Can't open file <%s>!", filename.Data()));
521 // get the only AliCDBEntry object from the file
522 // the object in the file is an AliCDBEntry entry named "AliCDBEntry"
524 AliCDBEntry* anEntry = dynamic_cast<AliCDBEntry*> (file->Get("AliCDBEntry"));
527 AliDebug(2,Form("Bad storage data: file does not contain an AliCDBEntry object!"));
532 // The object's Id is not reset during storage
533 // If object's Id runRange or version do not match with filename,
534 // it means that someone renamed file by hand. In this case a warning msg is issued.
537 AliCDBId entryId = anEntry->GetId();
538 Int_t tmpSubVersion = dataId->GetSubVersion();
539 dataId->SetSubVersion(entryId.GetSubVersion()); // otherwise filename and id may mismatch
540 if(!entryId.IsEqual(dataId)){
541 AliWarning(Form("Mismatch between file name and object's Id!"));
542 AliWarning(Form("File name: %s", dataId->ToString().Data()));
543 AliWarning(Form("Object's Id: %s", entryId.ToString().Data()));
545 dataId->SetSubVersion(tmpSubVersion);
548 anEntry->SetLastStorage("grid");
550 // Check whether entry contains a TTree. In case load the tree in memory!
551 LoadTreeFromFile(anEntry);
553 // close file, return retieved entry
554 file->Close(); delete file; file=0;
559 //_____________________________________________________________________________
560 TList* AliCDBGrid::GetEntries(const AliCDBId& queryId) {
561 // multiple request (AliCDBStorage::GetAll)
563 TList* result = new TList();
566 TObjArray validFileIds;
567 validFileIds.SetOwner(1);
569 Bool_t alreadyLoaded = kFALSE;
571 // look for file matching query requests (path, runRange)
572 if(queryId.GetFirstRun() == fRun &&
573 fPathFilter.Comprises(queryId.GetAliCDBPath()) && fVersion < 0 && !fMetaDataFilter){
574 // look into list of valid files previously loaded with AliCDBStorage::FillValidFileIds()
575 AliDebug(2,Form("List of files valid for run %d and for path %s was loaded. Looking there!",
576 queryId.GetFirstRun(), queryId.GetPath().Data()));
578 alreadyLoaded = kTRUE;
581 // List of files valid for reqested run was not loaded. Looking directly into CDB
582 AliDebug(2,Form("List of files valid for run %d and for path %s was not loaded. Looking directly into CDB!",
583 queryId.GetFirstRun(), queryId.GetPath().Data()));
586 MakeQueryFilter(queryId.GetFirstRun(), queryId.GetLastRun(), 0, filter);
588 TString path = queryId.GetPath();
590 TString pattern = "Run*.root";
591 TString optionQuery = "-y";
593 TString addFolder = "";
594 if (!path.Contains("*")){
595 if (!path.BeginsWith("/")) addFolder += "/";
599 if (path.BeginsWith("/")) path.Remove(0,1);
600 if (path.EndsWith("/")) path.Remove(path.Length()-1,1);
601 TObjArray* tokenArr = path.Tokenize("/");
602 if (tokenArr->GetEntries() != 3) {
603 AliError("Not a 3 level path! Keeping old query...");
604 pattern.Prepend(path+"/");
607 TString str0 = ((TObjString*)tokenArr->At(0))->String();
608 TString str1 = ((TObjString*)tokenArr->At(1))->String();
609 TString str2 = ((TObjString*)tokenArr->At(2))->String();
610 if (str0 != "*" && str1 != "*" && str2 == "*"){
611 // e.g. "ITS/Calib/*"
612 addFolder = "/"+str0+"/"+str1;
614 else if (str0 != "*" && str1 == "*" && str2 == "*"){
616 addFolder = "/"+str0;
618 else if (str0 == "*" && str1 == "*" && str2 == "*"){
620 // do nothing: addFolder is already an empty string;
623 // e.g. "ITS/*/RecoParam"
624 pattern.Prepend(path+"/");
627 delete tokenArr; tokenArr=0;
630 TString folderCopy(Form("%s%s",fDBFolder.Data(),addFolder.Data()));
632 AliDebug(2,Form("fDBFolder = %s, pattern = %s, filter = %s",folderCopy.Data(), pattern.Data(), filter.Data()));
634 TGridResult *res = gGrid->Query(folderCopy, pattern, filter, optionQuery.Data());
637 AliError("Grid query failed");
641 AliCDBId validFileId;
642 for(int i=0; i<res->GetEntries(); i++){
643 TString filename = res->GetKey(i, "lfn");
644 if(filename == "") continue;
645 if(FilenameToId(filename, validFileId))
646 validFileIds.AddLast(validFileId.Clone());
653 iter = new TIter(&fValidFileIds);
655 iter = new TIter(&validFileIds);
658 TObjArray selectedIds;
659 selectedIds.SetOwner(1);
661 // loop on list of valid Ids to select the right version to get.
662 // According to query and to the selection criteria list, version can be the highest or exact
666 AliCDBPath queryPath = queryId.GetAliCDBPath();
667 while((anIdPtr = dynamic_cast<AliCDBId*> (iter->Next()))){
668 AliCDBPath thisCDBPath = anIdPtr->GetAliCDBPath();
669 if(!(queryPath.Comprises(thisCDBPath)) || pathCopy.GetPath() == thisCDBPath.GetPath()) continue;
670 pathCopy = thisCDBPath;
672 // check the selection criteria list for this query
673 AliCDBId thisId(*anIdPtr);
674 thisId.SetVersion(queryId.GetVersion());
675 if(!thisId.HasVersion()) GetSelection(&thisId);
678 dataId = GetId(fValidFileIds, thisId);
680 dataId = GetId(validFileIds, thisId);
682 if(dataId) selectedIds.Add(dataId);
687 // selectedIds contains the Ids of the files matching all requests of query!
688 // All the objects are now ready to be retrieved
689 iter = new TIter(&selectedIds);
690 while((anIdPtr = dynamic_cast<AliCDBId*> (iter->Next()))){
692 if (!IdToFilename(*anIdPtr, filename)) {
693 AliDebug(2,Form("Bad data ID encountered! Subnormal error!"));
697 AliCDBEntry* anEntry = GetEntryFromFile(filename, anIdPtr);
699 if(anEntry) result->Add(anEntry);
707 //_____________________________________________________________________________
708 Bool_t AliCDBGrid::PutEntry(AliCDBEntry* entry) {
709 // put an AliCDBEntry object into the database
711 AliCDBId& id = entry->GetId();
713 // set version for the entry to be stored
714 if (!PrepareId(id)) return kFALSE;
716 // build filename from entry's id
718 if (!IdToFilename(id, filename)) {
719 AliError("Bad ID encountered! Subnormal error!");
723 TString folderToTag = Form("%s%s",
725 id.GetPath().Data());
727 TDirectory* saveDir = gDirectory;
729 TString fullFilename = Form("/alien%s", filename.Data());
730 // specify SE to filename
731 if (fSE != "default") fullFilename += Form("?se=%s",fSE.Data());
736 Printf("fNretry = %d, fRetrySeconds = %d",fNretry,fRetrySeconds);
737 for(Int_t i=0; i<=fNretry; ++i) {
738 AliDebug(2, Form("Putting the file in the OCDB: Retry n. %d",i));
739 file = TFile::Open(fullFilename,"CREATE");
740 if(!file || !file->IsWritable()){
741 AliError(Form("Can't open file <%s>!", filename.Data()));
742 if(file && !file->IsWritable()) file->Close(); delete file; file=0;
743 if(i==fNretry) return kFALSE;
744 else sleep(fRetrySeconds*nsleep);
747 AliDebug(2, " Successful!");
755 //SetTreeToFile(entry, file);
757 entry->SetVersion(id.GetVersion());
759 // write object (key name: "AliCDBEntry")
760 Bool_t result = (file->WriteTObject(entry, "AliCDBEntry") != 0);
761 if (!result) AliError(Form("Can't write entry to file <%s>!", filename.Data()));
764 if (saveDir) saveDir->cd(); else gROOT->cd();
765 file->Close(); delete file; file=0;
769 if(!TagFileId(filename, &id)){
770 AliInfo(Form("CDB tagging failed. Deleting file %s!",filename.Data()));
771 if(!gGrid->Rm(filename.Data()))
772 AliError("Can't delete file!");
776 TagFileMetaData(filename, entry->GetMetaData());
779 AliInfo(Form("CDB object stored into file %s", filename.Data()));
780 AliInfo(Form("Storage Element: %s", fSE.Data()));
783 //_____________________________________________________________________________
784 Bool_t AliCDBGrid::AddTag(TString& folderToTag, const char* tagname){
785 // add "tagname" tag (CDB or CDB_MD) to folder where object will be stored
787 Bool_t result = kTRUE;
788 AliDebug(2, Form("adding %s tag to folder %s", tagname, folderToTag.Data()));
789 TString addTag = Form("addTag %s %s", folderToTag.Data(), tagname);
790 TGridResult *gridres = gGrid->Command(addTag.Data());
791 const char* resCode = gridres->GetKey(0,"__result__"); // '1' if success
792 if(resCode[0] != '1') {
793 AliError(Form("Couldn't add %s tags to folder %s !",
794 tagname, folderToTag.Data()));
801 //_____________________________________________________________________________
802 Bool_t AliCDBGrid::TagFileId(TString& filename, const AliCDBId* id){
803 // tag stored object in CDB table using object Id's parameters
806 TString dirname(filename);
807 Int_t dirNumber = gGrid->Mkdir(dirname.Remove(dirname.Last('/')),"-d");
809 TString addTagValue1 = Form("addTagValue %s CDB ", filename.Data());
810 TString addTagValue2 = Form("first_run=%d last_run=%d version=%d ",
814 TString addTagValue3 = Form("path_level_0=\"%s\" path_level_1=\"%s\" path_level_2=\"%s\" ",
815 id->GetPathLevel(0).Data(),
816 id->GetPathLevel(1).Data(),
817 id->GetPathLevel(2).Data());
818 //TString addTagValue4 = Form("version_path=\"%s\" dir_number=%d",Form("%d_%s",id->GetVersion(),filename.Data()),dirNumber);
819 TString addTagValue4 = Form("version_path=\"%09d%s\" dir_number=%d",id->GetVersion(),filename.Data(),dirNumber);
820 TString addTagValue = Form("%s%s%s%s",
824 addTagValue4.Data());
826 Bool_t result = kFALSE;
827 AliDebug(2, Form("Tagging file. Tag command: %s", addTagValue.Data()));
828 TGridResult* res = gGrid->Command(addTagValue.Data());
829 const char* resCode = res->GetKey(0,"__result__"); // '1' if success
830 if(resCode[0] != '1') {
831 AliError(Form("Couldn't add CDB tag value to file %s !",
835 AliDebug(2, "Object successfully tagged.");
843 //_____________________________________________________________________________
844 Bool_t AliCDBGrid::TagShortLived(TString& filename, Bool_t value){
845 // tag folder with ShortLived tag
847 TString addTagValue = Form("addTagValue %s ShortLived_try value=%d", filename.Data(), value);
849 Bool_t result = kFALSE;
850 AliDebug(2, Form("Tagging file. Tag command: %s", addTagValue.Data()));
851 TGridResult* res = gGrid->Command(addTagValue.Data());
852 const char* resCode = res->GetKey(0,"__result__"); // '1' if success
853 if(resCode[0] != '1') {
854 AliError(Form("Couldn't add ShortLived tag value to file %s !", filename.Data()));
857 AliDebug(2,"Object successfully tagged.");
865 //_____________________________________________________________________________
866 Bool_t AliCDBGrid::TagFileMetaData(TString& filename, const AliCDBMetaData* md){
867 // tag stored object in CDB table using object Id's parameters
869 TString addTagValue1 = Form("addTagValue %s CDB_MD ", filename.Data());
870 TString addTagValue2 = Form("object_classname=\"%s\" responsible=\"%s\" beam_period=%d ",
871 md->GetObjectClassName(),
872 md->GetResponsible(),
873 md->GetBeamPeriod());
874 TString addTagValue3 = Form("aliroot_version=\"%s\" comment=\"%s\"",
875 md->GetAliRootVersion(),
877 TString addTagValue = Form("%s%s%s",
880 addTagValue3.Data());
882 Bool_t result = kFALSE;
883 AliDebug(2, Form("Tagging file. Tag command: %s", addTagValue.Data()));
884 TGridResult* res = gGrid->Command(addTagValue.Data());
885 const char* resCode = res->GetKey(0,"__result__"); // '1' if success
886 if(resCode[0] != '1') {
887 AliWarning(Form("Couldn't add CDB_MD tag value to file %s !",
891 AliDebug(2,"Object successfully tagged.");
897 //_____________________________________________________________________________
898 TList* AliCDBGrid::GetIdListFromFile(const char* fileName){
900 TString turl(fileName);
901 turl.Prepend("/alien" + fDBFolder);
902 turl += "?se="; turl += fSE.Data();
903 TFile *file = TFile::Open(turl);
905 AliError(Form("Can't open selection file <%s>!", turl.Data()));
909 TList *list = new TList();
917 keycycle = "AliCDBId;";
920 id = (AliCDBId*) file->Get(keycycle);
924 file->Close(); delete file; file=0;
931 //_____________________________________________________________________________
932 Bool_t AliCDBGrid::Contains(const char* path) const{
933 // check for path in storage's DBFolder
935 TString initDir(gGrid->Pwd(0));
936 TString dirName(fDBFolder);
937 dirName += path; // dirName = fDBFolder/path
938 Bool_t result=kFALSE;
939 if (gGrid->Cd(dirName,0)) result=kTRUE;
940 gGrid->Cd(initDir.Data(),0);
944 //_____________________________________________________________________________
945 void AliCDBGrid::QueryValidFiles()
947 // Query the CDB for files valid for AliCDBStorage::fRun
948 // fills list fValidFileIds with AliCDBId objects created from file name
951 MakeQueryFilter(fRun, fRun, fMetaDataFilter, filter);
953 TString path = fPathFilter.GetPath();
955 TString pattern = "Run*";
956 TString optionQuery = "-y";
958 pattern += Form("_v%d_s0", fVersion);
962 AliDebug(2,Form("pattern: %s", pattern.Data()));
964 TString addFolder = "";
965 if (!path.Contains("*")){
966 if (!path.BeginsWith("/")) addFolder += "/";
970 if (path.BeginsWith("/")) path.Remove(0,1);
971 if (path.EndsWith("/")) path.Remove(path.Length()-1,1);
972 TObjArray* tokenArr = path.Tokenize("/");
973 if (tokenArr->GetEntries() != 3) {
974 AliError("Not a 3 level path! Keeping old query...");
975 pattern.Prepend(path+"/");
978 TString str0 = ((TObjString*)tokenArr->At(0))->String();
979 TString str1 = ((TObjString*)tokenArr->At(1))->String();
980 TString str2 = ((TObjString*)tokenArr->At(2))->String();
981 if (str0 != "*" && str1 != "*" && str2 == "*"){
982 // e.g. "ITS/Calib/*"
983 addFolder = "/"+str0+"/"+str1;
985 else if (str0 != "*" && str1 == "*" && str2 == "*"){
987 addFolder = "/"+str0;
989 else if (str0 == "*" && str1 == "*" && str2 == "*"){
991 // do nothing: addFolder is already an empty string;
994 // e.g. "ITS/*/RecoParam"
995 pattern.Prepend(path+"/");
998 delete tokenArr; tokenArr=0;
1001 TString folderCopy(Form("%s%s",fDBFolder.Data(),addFolder.Data()));
1003 AliDebug(2,Form("fDBFolder = %s, pattern = %s, filter = %s",folderCopy.Data(), pattern.Data(), filter.Data()));
1005 if (optionQuery == "-y"){
1006 AliInfo("Only latest version will be returned");
1009 TGridResult *res = gGrid->Query(folderCopy, pattern, filter, optionQuery.Data());
1012 AliError("Grid query failed");
1018 while ((map = (TMap*)next())) {
1020 if ((entry = (TObjString *) ((TMap *)map)->GetValue("lfn"))) {
1021 TString& filename = entry->String();
1022 if(filename.IsNull()) continue;
1023 AliDebug(2,Form("Found valid file: %s", filename.Data()));
1024 AliCDBId *validFileId = new AliCDBId;
1025 Bool_t result = FilenameToId(filename, *validFileId);
1027 fValidFileIds.AddLast(validFileId);
1038 //_____________________________________________________________________________
1039 void AliCDBGrid::MakeQueryFilter(Int_t firstRun, Int_t lastRun,
1040 const AliCDBMetaData* md, TString& result) const
1042 // create filter for file query
1044 result = Form("CDB:first_run<=%d and CDB:last_run>=%d", firstRun, lastRun);
1046 // if(version >= 0) {
1047 // result += Form(" and CDB:version=%d", version);
1049 // if(pathFilter.GetLevel0() != "*") {
1050 // result += Form(" and CDB:path_level_0=\"%s\"", pathFilter.GetLevel0().Data());
1052 // if(pathFilter.GetLevel1() != "*") {
1053 // result += Form(" and CDB:path_level_1=\"%s\"", pathFilter.GetLevel1().Data());
1055 // if(pathFilter.GetLevel2() != "*") {
1056 // result += Form(" and CDB:path_level_2=\"%s\"", pathFilter.GetLevel2().Data());
1060 if(md->GetObjectClassName()[0] != '\0') {
1061 result += Form(" and CDB_MD:object_classname=\"%s\"", md->GetObjectClassName());
1063 if(md->GetResponsible()[0] != '\0') {
1064 result += Form(" and CDB_MD:responsible=\"%s\"", md->GetResponsible());
1066 if(md->GetBeamPeriod() != 0) {
1067 result += Form(" and CDB_MD:beam_period=%d", md->GetBeamPeriod());
1069 if(md->GetAliRootVersion()[0] != '\0') {
1070 result += Form(" and CDB_MD:aliroot_version=\"%s\"", md->GetAliRootVersion());
1072 if(md->GetComment()[0] != '\0') {
1073 result += Form(" and CDB_MD:comment=\"%s\"", md->GetComment());
1076 AliDebug(2, Form("filter: %s",result.Data()));
1080 //_____________________________________________________________________________
1081 Int_t AliCDBGrid::GetLatestVersion(const char* path, Int_t run){
1082 // get last version found in the database valid for run and path
1084 AliCDBPath aCDBPath(path);
1085 if(!aCDBPath.IsValid() || aCDBPath.IsWildcard()) {
1086 AliError(Form("Invalid path in request: %s", path));
1089 AliCDBId query(path, run, run, -1, -1);
1091 AliCDBId* dataId = 0;
1092 // look for file matching query requests (path, runRange, version)
1093 if(run == fRun && fPathFilter.Comprises(aCDBPath) && fVersion < 0){
1094 // look into list of valid files previously loaded with AliCDBStorage::FillValidFileIds()
1095 AliDebug(2, Form("List of files valid for run %d and for path %s was loaded. Looking there!",
1097 dataId = GetId(fValidFileIds, query);
1098 if (!dataId) return -1;
1099 Int_t version = dataId->GetVersion();
1104 // List of files valid for reqested run was not loaded. Looking directly into CDB
1105 AliDebug(2, Form("List of files valid for run %d and for path %s was not loaded. Looking directly into CDB!",
1108 TObjArray validFileIds;
1109 validFileIds.SetOwner(1);
1112 MakeQueryFilter(run, run, 0, filter);
1114 TString pattern = ".root";
1116 TString folderCopy(Form("%s%s/Run",fDBFolder.Data(),path));
1118 AliDebug(2,Form("** fDBFolder = %s, pattern = %s, filter = %s",folderCopy.Data(), pattern.Data(), filter.Data()));
1119 TGridResult *res = gGrid->Query(folderCopy, pattern, filter, "-y -m");
1121 AliCDBId validFileId;
1122 if (res->GetEntries()>1){
1123 AliWarning("Number of found entries >1, even if option -y was used");
1124 for(int i=0; i<res->GetEntries(); i++){
1125 TString filename = res->GetKey(i, "lfn");
1126 if(filename == "") continue;
1127 if(FilenameToId(filename, validFileId))
1128 validFileIds.AddLast(validFileId.Clone());
1130 dataId = GetId(validFileIds, query);
1131 if (!dataId) return -1;
1133 Int_t version = dataId->GetVersion();
1137 else if (res->GetEntries()==1){
1138 TString filename = res->GetKey(0, "lfn");
1139 if(filename == "") {
1140 AliError("The only entry found has filename empty");
1143 if(FilenameToId(filename, validFileId)) return validFileId.GetVersion();
1145 AliError("Impossible to get FileId from filename");
1150 AliError("No entries found");
1159 //_____________________________________________________________________________
1160 Int_t AliCDBGrid::GetLatestSubVersion(const char* /*path*/, Int_t /*run*/, Int_t /*version*/){
1161 // get last subversion found in the database valid for run and path
1162 AliError("Objects in GRID storage have no sub version!");
1167 /////////////////////////////////////////////////////////////////////////////////////////////////
1169 // AliCDBGrid factory //
1171 /////////////////////////////////////////////////////////////////////////////////////////////////
1173 ClassImp(AliCDBGridFactory)
1175 //_____________________________________________________________________________
1176 Bool_t AliCDBGridFactory::Validate(const char* gridString) {
1177 // check if the string is valid Grid URI
1179 TRegexp gridPattern("^alien://.+$");
1181 return TString(gridString).Contains(gridPattern);
1184 //_____________________________________________________________________________
1185 AliCDBParam* AliCDBGridFactory::CreateParameter(const char* gridString) {
1186 // create AliCDBGridParam class from the URI string
1188 if (!Validate(gridString)) {
1192 TString buffer(gridString);
1194 TString gridUrl = "alien://";
1196 TString dbFolder = "";
1197 TString se = "default";
1198 TString cacheFolder = "";
1199 Bool_t operateDisconnected = kTRUE;
1200 Long64_t cacheSize = (UInt_t) 1024*1024*1024; // 1GB
1201 Long_t cleanupInterval = 0;
1203 TObjArray *arr = buffer.Tokenize('?');
1205 TObjString *str = 0;
1207 while((str = (TObjString*) iter.Next())){
1208 TString entry(str->String());
1209 Int_t indeq = entry.Index('=');
1211 if(entry.BeginsWith("alien://")) { // maybe it's a gridUrl!
1215 AliError(Form("Invalid entry! %s",entry.Data()));
1220 TString key = entry(0,indeq);
1221 TString value = entry(indeq+1,entry.Length()-indeq);
1223 if(key.Contains("grid",TString::kIgnoreCase)) {
1226 else if (key.Contains("user",TString::kIgnoreCase)){
1229 else if (key.Contains("se",TString::kIgnoreCase)){
1232 else if (key.Contains("cacheF",TString::kIgnoreCase)){
1233 cacheFolder = value;
1234 if (!cacheFolder.IsNull() && !cacheFolder.EndsWith("/"))
1237 else if (key.Contains("folder",TString::kIgnoreCase)){
1240 else if (key.Contains("operateDisc",TString::kIgnoreCase)){
1241 if(value == "kTRUE") {
1242 operateDisconnected = kTRUE;
1243 } else if (value == "kFALSE") {
1244 operateDisconnected = kFALSE;
1245 } else if (value == "0" || value == "1") {
1246 operateDisconnected = (Bool_t) value.Atoi();
1248 AliError(Form("Invalid entry! %s",entry.Data()));
1252 else if (key.Contains("cacheS",TString::kIgnoreCase)){
1253 if(value.IsDigit()) {
1254 cacheSize = value.Atoi();
1256 AliError(Form("Invalid entry! %s",entry.Data()));
1260 else if (key.Contains("cleanupInt",TString::kIgnoreCase)){
1261 if(value.IsDigit()) {
1262 cleanupInterval = value.Atoi();
1264 AliError(Form("Invalid entry! %s",entry.Data()));
1269 AliError(Form("Invalid entry! %s",entry.Data()));
1275 AliDebug(2, Form("gridUrl: %s", gridUrl.Data()));
1276 AliDebug(2, Form("user: %s", user.Data()));
1277 AliDebug(2, Form("dbFolder: %s", dbFolder.Data()));
1278 AliDebug(2, Form("s.e.: %s", se.Data()));
1279 AliDebug(2, Form("local cache folder: %s", cacheFolder.Data()));
1280 AliDebug(2, Form("local cache operate disconnected: %d", operateDisconnected));
1281 AliDebug(2, Form("local cache size: %lld", cacheSize));
1282 AliDebug(2, Form("local cache cleanup interval: %ld", cleanupInterval));
1285 AliError("Base folder must be specified!");
1289 return new AliCDBGridParam(gridUrl.Data(), user.Data(),
1290 dbFolder.Data(), se.Data(), cacheFolder.Data(),
1291 operateDisconnected, cacheSize, cleanupInterval);
1294 //_____________________________________________________________________________
1295 AliCDBStorage* AliCDBGridFactory::Create(const AliCDBParam* param) {
1296 // create AliCDBGrid storage instance from parameters
1298 AliCDBGrid *grid = 0;
1299 if (AliCDBGridParam::Class() == param->IsA()) {
1301 const AliCDBGridParam* gridParam = (const AliCDBGridParam*) param;
1302 grid = new AliCDBGrid(gridParam->GridUrl().Data(),
1303 gridParam->GetUser().Data(),
1304 gridParam->GetDBFolder().Data(),
1305 gridParam->GetSE().Data(),
1306 gridParam->GetCacheFolder().Data(),
1307 gridParam->GetOperateDisconnected(),
1308 gridParam->GetCacheSize(),
1309 gridParam->GetCleanupInterval());
1313 if(!gGrid && grid) {
1314 delete grid; grid=0;
1320 /////////////////////////////////////////////////////////////////////////////////////////////////
1322 // AliCDBGrid Parameter class // //
1324 /////////////////////////////////////////////////////////////////////////////////////////////////
1326 ClassImp(AliCDBGridParam)
1328 //_____________________________________________________________________________
1329 AliCDBGridParam::AliCDBGridParam():
1336 fOperateDisconnected(),
1341 // default constructor
1345 //_____________________________________________________________________________
1346 AliCDBGridParam::AliCDBGridParam(const char* gridUrl, const char* user, const char* dbFolder,
1347 const char* se, const char* cacheFolder, Bool_t operateDisconnected,
1348 Long64_t cacheSize, Long_t cleanupInterval):
1352 fDBFolder(dbFolder),
1354 fCacheFolder(cacheFolder),
1355 fOperateDisconnected(operateDisconnected),
1356 fCacheSize(cacheSize),
1357 fCleanupInterval(cleanupInterval)
1363 TString uri = Form("%s?User=%s?DBFolder=%s?SE=%s?CacheFolder=%s"
1364 "?OperateDisconnected=%d?CacheSize=%lld?CleanupInterval=%ld",
1365 fGridUrl.Data(), fUser.Data(),
1366 fDBFolder.Data(), fSE.Data(), fCacheFolder.Data(),
1367 fOperateDisconnected, fCacheSize, fCleanupInterval);
1372 //_____________________________________________________________________________
1373 AliCDBGridParam::~AliCDBGridParam() {
1378 //_____________________________________________________________________________
1379 AliCDBParam* AliCDBGridParam::CloneParam() const {
1382 return new AliCDBGridParam(fGridUrl.Data(), fUser.Data(),
1383 fDBFolder.Data(), fSE.Data(), fCacheFolder.Data(),
1384 fOperateDisconnected, fCacheSize, fCleanupInterval);
1387 //_____________________________________________________________________________
1388 ULong_t AliCDBGridParam::Hash() const {
1389 // return Hash function
1391 return fGridUrl.Hash()+fUser.Hash()+fDBFolder.Hash()+fSE.Hash()+fCacheFolder.Hash();
1394 //_____________________________________________________________________________
1395 Bool_t AliCDBGridParam::IsEqual(const TObject* obj) const {
1396 // check if this object is equal to AliCDBParam obj
1402 if (AliCDBGridParam::Class() != obj->IsA()) {
1406 AliCDBGridParam* other = (AliCDBGridParam*) obj;
1408 if(fGridUrl != other->fGridUrl) return kFALSE;
1409 if(fUser != other->fUser) return kFALSE;
1410 if(fDBFolder != other->fDBFolder) return kFALSE;
1411 if(fSE != other->fSE) return kFALSE;
1412 if(fCacheFolder != other->fCacheFolder) return kFALSE;
1413 if(fOperateDisconnected != other->fOperateDisconnected) return kFALSE;
1414 if(fCacheSize != other->fCacheSize) return kFALSE;
1415 if(fCleanupInterval != other->fCleanupInterval) return kFALSE;