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>
35 #include "AliCDBEntry.h"
36 #include "AliCDBGrid.h"
37 #include "AliCDBManager.h"
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) :
51 fCacheFolder(cacheFolder),
52 fOperateDisconnected(operateDisconnected),
53 fCacheSize(cacheSize),
54 fCleanupInterval(cleanupInterval)
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...");
64 AliInfo(Form("gGrid = %x; fGridUrl = %s; gGrid->GridUrl() = %s",gGrid,fGridUrl.Data(), gGrid->GridUrl()));
65 AliInfo(Form("fUser = %s; gGrid->GetUser() = %s",fUser.Data(), gGrid->GetUser()));
67 TGrid::Connect(fGridUrl.Data(),fUser.Data());
71 AliError("Connection failed!");
75 TString initDir(gGrid->Pwd(0));
76 if (fDBFolder[0] != '/') {
77 fDBFolder.Prepend(initDir);
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 if(!gGrid->Mkdir(fDBFolder.Data(),"",0)){
84 AliError(Form("Cannot create folder <%s> !",fDBFolder.Data()));
87 AliDebug(2,Form("Folder <%s> found",fDBFolder.Data()));
90 // removes any '/' at the end of path, then append one '/'
91 while(fDBFolder.EndsWith("/")) fDBFolder.Remove(fDBFolder.Last('/'));
95 fBaseFolder = fDBFolder;
99 // Check if local cache folder is already defined
100 TString origCache(TFile::GetCacheFileDir());
101 if(fCacheFolder.Length() > 0) {
102 if(origCache.Length() == 0) {
103 AliInfo(Form("Setting local cache to: %s", fCacheFolder.Data()));
104 } else if(fCacheFolder != origCache) {
105 AliWarning(Form("Local cache folder was already defined, changing it to: %s",
106 fCacheFolder.Data()));
109 // default settings are: operateDisconnected=kTRUE, forceCacheread = kFALSE
110 if(!TFile::SetCacheFileDir(fCacheFolder.Data(), fOperateDisconnected)) {
111 AliError(Form("Could not set cache folder %s !", fCacheFolder.Data()));
114 // reset fCacheFolder because the function may have
115 // slightly changed the folder name (e.g. '/' added)
116 fCacheFolder = TFile::GetCacheFileDir();
119 // default settings are: cacheSize=1GB, cleanupInterval = 0
120 if(!TFile::ShrinkCacheFileDir(fCacheSize, fCleanupInterval)) {
121 AliError(Form("Could not set following values "
122 "to ShrinkCacheFileDir: cacheSize = %d, cleanupInterval = %d !",
123 fCacheSize, fCleanupInterval));
127 // return to the initial directory
128 gGrid->Cd(initDir.Data(),0);
131 //_____________________________________________________________________________
132 AliCDBGrid::~AliCDBGrid()
135 delete gGrid; gGrid=0;
139 //_____________________________________________________________________________
140 Bool_t AliCDBGrid::FilenameToId(TString& filename, AliCDBId& id) {
141 // build AliCDBId from full path filename (fDBFolder/path/Run#x_#y_v#z_s0.root)
143 if(filename.Contains(fDBFolder)){
144 filename = filename(fDBFolder.Length(),filename.Length()-fDBFolder.Length());
147 TString idPath = filename(0,filename.Last('/'));
149 if(!id.IsValid()) return kFALSE;
151 filename=filename(idPath.Length()+1,filename.Length()-idPath.Length());
154 // valid filename: Run#firstRun_#lastRun_v#version_s0.root
155 TRegexp keyPattern("^Run[0-9]+_[0-9]+_v[0-9]+_s0.root$");
156 keyPattern.Index(filename, &mSize);
159 // TODO backward compatibility ... maybe remove later!
161 TRegexp oldKeyPattern("^Run[0-9]+_[0-9]+_v[0-9]+.root$");
162 oldKeyPattern.Index(filename, &oldmSize);
164 AliDebug(2,Form("Bad filename <%s>.", filename.Data()));
167 AliDebug(2,Form("Old filename format <%s>.", filename.Data()));
168 id.SetSubVersion(-11); // TODO trick to ensure backward compatibility
172 id.SetSubVersion(-1); // TODO trick to ensure backward compatibility
175 filename.Resize(filename.Length() - sizeof(".root") + 1);
177 TObjArray* strArray = (TObjArray*) filename.Tokenize("_");
179 TString firstRunString(((TObjString*) strArray->At(0))->GetString());
180 id.SetFirstRun(atoi(firstRunString.Data() + 3));
181 id.SetLastRun(atoi(((TObjString*) strArray->At(1))->GetString()));
183 TString verString(((TObjString*) strArray->At(2))->GetString());
184 id.SetVersion(atoi(verString.Data() + 1));
191 //_____________________________________________________________________________
192 Bool_t AliCDBGrid::IdToFilename(const AliCDBId& id, TString& filename) const {
193 // build file name from AliCDBId (path, run range, version) and fDBFolder
195 if (!id.GetAliCDBRunRange().IsValid()) {
196 AliDebug(2,Form("Invalid run range <%d, %d>.",
197 id.GetFirstRun(), id.GetLastRun()));
201 if (id.GetVersion() < 0) {
202 AliDebug(2,Form("Invalid version <%d>.", id.GetVersion()));
206 filename = Form("Run%d_%d_v%d",
211 if (id.GetSubVersion() != -11) filename += "_s0"; // TODO to ensure backward compatibility
214 filename.Prepend(fDBFolder + id.GetPath() + '/');
219 //_____________________________________________________________________________
220 Bool_t AliCDBGrid::PrepareId(AliCDBId& id) {
221 // prepare id (version) of the object that will be stored (called by PutEntry)
223 TString initDir(gGrid->Pwd(0));
225 TString dirName(fDBFolder);
227 Bool_t dirExist=kFALSE;
231 // go to the path; if directory does not exist, create it
232 for(int i=0;i<3;i++){
233 dirName+=Form("%s/",id.GetPathLevel(i).Data());
234 dirExist=gGrid->Cd(dirName,0);
236 AliDebug(2,Form("Creating new folder <%s> ...",dirName.Data()));
237 if(!gGrid->Mkdir(dirName,"",0)){
238 AliError(Form("Cannot create directory <%s> !",dirName.Data()));
239 gGrid->Cd(initDir.Data());
243 // if folders are new add tags to them
245 // TODO Currently disabled
246 // add short lived tag!
247 // AliInfo("Tagging level 1 folder with \"ShortLived\" tag");
248 // if(!AddTag(dirName,"ShortLived_try")){
249 // AliError(Form("Could not tag folder %s !", dirName.Data()));
250 // if(!gGrid->Rmdir(dirName.Data())){
251 // AliError(Form("Unexpected: could not remove %s directory!", dirName.Data()));
257 AliDebug(2,"Tagging level 2 folder with \"CDB\" and \"CDB_MD\" tag");
258 if(!AddTag(dirName,"CDB")){
259 AliError(Form("Could not tag folder %s !", dirName.Data()));
260 if(!gGrid->Rmdir(dirName.Data())){
261 AliError(Form("Unexpected: could not remove %s directory!", dirName.Data()));
265 if(!AddTag(dirName,"CDB_MD")){
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()));
273 // TODO Currently disabled
274 // add short lived tag!
275 // TString path=id.GetPath();
276 // if(AliCDBManager::Instance()->IsShortLived(path.Data())) {
277 // AliInfo(Form("Tagging %s as short lived", dirName.Data()));
278 // if(!TagShortLived(dirName, kTRUE)){
279 // AliError(Form("Could not tag folder %s !", dirName.Data()));
280 // if(!gGrid->Rmdir(dirName.Data())){
281 // AliError(Form("Unexpected: could not remove %s directory!", dirName.Data()));
286 // AliInfo(Form("Tagging %s as long lived", dirName.Data()));
287 // if(!TagShortLived(dirName, kFALSE)){
288 // AliError(Form("Could not tag folder %s !", dirName.Data()));
289 // if(!gGrid->Rmdir(dirName.Data())){
290 // AliError(Form("Unexpected: could not remove %s directory!", dirName.Data()));
298 gGrid->Cd(initDir,0);
301 AliCDBId anId; // the id got from filename
302 AliCDBRunRange lastRunRange(-1,-1); // highest runRange found
303 Int_t lastVersion=0; // highest version found
305 TGridResult *res = gGrid->Ls(dirName);
307 //loop on the files in the directory, look for highest version
308 for(int i=0; i < res->GetEntries(); i++){
309 filename=res->GetFileNamePath(i);
310 if (!FilenameToId(filename, anId)) continue;
311 if (anId.GetAliCDBRunRange().Overlaps(id.GetAliCDBRunRange()) && anId.GetVersion() > lastVersion) {
312 lastVersion = anId.GetVersion();
313 lastRunRange = anId.GetAliCDBRunRange();
319 id.SetVersion(lastVersion + 1);
322 TString lastStorage = id.GetLastStorage();
323 if(lastStorage.Contains(TString("new"), TString::kIgnoreCase) && id.GetVersion() > 1 ){
324 AliDebug(2, Form("A NEW object is being stored with version %d",
326 AliDebug(2, Form("and it will hide previously stored object with version %d!",
330 if(!lastRunRange.IsAnyRange() && !(lastRunRange.IsEqual(&id.GetAliCDBRunRange())))
331 AliWarning(Form("Run range modified w.r.t. previous version (Run%d_%d_v%d)",
332 lastRunRange.GetFirstRun(), lastRunRange.GetLastRun(), id.GetVersion()));
337 //_____________________________________________________________________________
338 AliCDBId* AliCDBGrid::GetId(const TObjArray& validFileIds, const AliCDBId& query) {
339 // look for the Id that matches query's requests (highest or exact version)
341 if(validFileIds.GetEntriesFast() < 1) {
343 } else if (validFileIds.GetEntriesFast() == 1) {
344 return dynamic_cast<AliCDBId*> (validFileIds.At(0)->Clone());
347 TIter iter(&validFileIds);
352 while((anIdPtr = dynamic_cast<AliCDBId*> (iter.Next()))){
353 if(anIdPtr->GetPath() != query.GetPath()) continue;
355 //if(!CheckVersion(query, anIdPtr, result)) return NULL;
357 if (!query.HasVersion()){ // look for highest version
358 if(result && result->GetVersion() > anIdPtr->GetVersion()) continue;
359 if(result && result->GetVersion() == anIdPtr->GetVersion()) {
360 AliError(Form("More than one object valid for run %d, version %d!",
361 query.GetFirstRun(), anIdPtr->GetVersion()));
365 } else { // look for specified version
366 if(query.GetVersion() != anIdPtr->GetVersion()) continue;
367 if(result && result->GetVersion() == anIdPtr->GetVersion()){
368 AliError(Form("More than one object valid for run %d, version %d!",
369 query.GetFirstRun(), anIdPtr->GetVersion()));
377 if (!result) return NULL;
379 return dynamic_cast<AliCDBId*> (result->Clone());
382 //_____________________________________________________________________________
383 AliCDBId* AliCDBGrid::GetEntryId(const AliCDBId& queryId) {
384 // get AliCDBId from the database
385 // User must delete returned object
389 AliCDBId selectedId(queryId);
390 if (!selectedId.HasVersion()) {
391 // if version is not specified, first check the selection criteria list
392 GetSelection(&selectedId);
395 TObjArray validFileIds;
396 validFileIds.SetOwner(1);
398 // look for file matching query requests (path, runRange, version)
399 if(selectedId.GetFirstRun() == fRun &&
400 fPathFilter.Comprises(selectedId.GetAliCDBPath()) && fVersion < 0 && !fMetaDataFilter){
401 // look into list of valid files previously loaded with AliCDBStorage::FillValidFileIds()
402 AliDebug(2, Form("List of files valid for run %d and for path %s was loaded. Looking there!",
403 selectedId.GetFirstRun(), selectedId.GetPath().Data()));
404 dataId = GetId(fValidFileIds, selectedId);
407 // List of files valid for reqested run was not loaded. Looking directly into CDB
408 AliDebug(2, Form("List of files valid for run %d and for path %s was not loaded. Looking directly into CDB!",
409 selectedId.GetFirstRun(), selectedId.GetPath().Data()));
412 MakeQueryFilter(selectedId.GetFirstRun(), selectedId.GetLastRun(), 0, filter);
414 TString pattern = Form("%s/Run*", selectedId.GetPath().Data());
415 if(selectedId.GetVersion() >= 0) pattern += Form("_v%d*",selectedId.GetVersion());
417 AliDebug(2,Form("pattern: %s", pattern.Data()));
419 TGridResult *res = gGrid->Query(fDBFolder, pattern, filter, "");
420 AliCDBId validFileId;
421 for(int i=0; i<res->GetEntries(); i++){
422 TString filename = res->GetKey(i, "lfn");
423 if(filename == "") continue;
424 if(FilenameToId(filename, validFileId))
425 validFileIds.AddLast(validFileId.Clone());
428 dataId = GetId(validFileIds, selectedId);
434 //_____________________________________________________________________________
435 AliCDBEntry* AliCDBGrid::GetEntry(const AliCDBId& queryId) {
436 // get AliCDBEntry from the database
438 AliCDBId* dataId = GetEntryId(queryId);
440 if (!dataId) return NULL;
443 if (!IdToFilename(*dataId, filename)) {
444 AliDebug(2,Form("Bad data ID encountered! Subnormal error!"));
449 AliCDBEntry* anEntry = GetEntryFromFile(filename, dataId);
455 //_____________________________________________________________________________
456 AliCDBEntry* AliCDBGrid::GetEntryFromFile(TString& filename, AliCDBId* dataId){
457 // Get AliCBEntry object from file "filename"
459 AliDebug(2,Form("Opening file: %s",filename.Data()));
461 filename.Prepend("/alien");
463 // if option="CACHEREAD" TFile will use the local caching facility!
464 TString option="READ";
465 if(fCacheFolder != ""){
467 // Check if local cache folder was changed in the meanwhile
468 TString origCache(TFile::GetCacheFileDir());
469 if(fCacheFolder != origCache) {
470 AliWarning(Form("Local cache folder has been overwritten!! fCacheFolder = %s origCache = %s",
471 fCacheFolder.Data(), origCache.Data()));
472 TFile::SetCacheFileDir(fCacheFolder.Data(), fOperateDisconnected);
473 TFile::ShrinkCacheFileDir(fCacheSize, fCleanupInterval);
476 option.Prepend("CACHE");
479 AliDebug(2, Form("Option: %s", option.Data()));
481 TFile *file = TFile::Open(filename, option);
483 AliDebug(2,Form("Can't open file <%s>!", filename.Data()));
487 // get the only AliCDBEntry object from the file
488 // the object in the file is an AliCDBEntry entry named "AliCDBEntry"
490 AliCDBEntry* anEntry = dynamic_cast<AliCDBEntry*> (file->Get("AliCDBEntry"));
493 AliDebug(2,Form("Bad storage data: file does not contain an AliCDBEntry object!"));
498 // The object's Id is not reset during storage
499 // If object's Id runRange or version do not match with filename,
500 // it means that someone renamed file by hand. In this case a warning msg is issued.
503 AliCDBId entryId = anEntry->GetId();
504 Int_t tmpSubVersion = dataId->GetSubVersion();
505 dataId->SetSubVersion(entryId.GetSubVersion()); // otherwise filename and id may mismatch
506 if(!entryId.IsEqual(dataId)){
507 AliWarning(Form("Mismatch between file name and object's Id!"));
508 AliWarning(Form("File name: %s", dataId->ToString().Data()));
509 AliWarning(Form("Object's Id: %s", entryId.ToString().Data()));
511 dataId->SetSubVersion(tmpSubVersion);
514 anEntry->SetLastStorage("grid");
516 // Check whether entry contains a TTree. In case load the tree in memory!
517 LoadTreeFromFile(anEntry);
519 // close file, return retieved entry
520 file->Close(); delete file; file=0;
525 //_____________________________________________________________________________
526 TList* AliCDBGrid::GetEntries(const AliCDBId& queryId) {
527 // multiple request (AliCDBStorage::GetAll)
529 TList* result = new TList();
532 TObjArray validFileIds;
533 validFileIds.SetOwner(1);
535 Bool_t alreadyLoaded = kFALSE;
537 // look for file matching query requests (path, runRange)
538 if(queryId.GetFirstRun() == fRun &&
539 fPathFilter.Comprises(queryId.GetAliCDBPath()) && fVersion < 0 && !fMetaDataFilter){
540 // look into list of valid files previously loaded with AliCDBStorage::FillValidFileIds()
541 AliDebug(2,Form("List of files valid for run %d and for path %s was loaded. Looking there!",
542 queryId.GetFirstRun(), queryId.GetPath().Data()));
544 alreadyLoaded = kTRUE;
547 // List of files valid for reqested run was not loaded. Looking directly into CDB
548 AliDebug(2,Form("List of files valid for run %d and for path %s was not loaded. Looking directly into CDB!",
549 queryId.GetFirstRun(), queryId.GetPath().Data()));
552 MakeQueryFilter(queryId.GetFirstRun(), queryId.GetLastRun(), 0, filter);
554 TString pattern = Form("%s/Run*.root", queryId.GetPath().Data());
555 AliDebug(2,Form("pattern: %s", pattern.Data()));
557 TGridResult *res = gGrid->Query(fDBFolder, pattern, filter, "");
559 AliCDBId validFileId;
560 for(int i=0; i<res->GetEntries(); i++){
561 TString filename = res->GetKey(i, "lfn");
562 if(filename == "") continue;
563 if(FilenameToId(filename, validFileId))
564 validFileIds.AddLast(validFileId.Clone());
571 iter = new TIter(&fValidFileIds);
573 iter = new TIter(&validFileIds);
576 TObjArray selectedIds;
577 selectedIds.SetOwner(1);
579 // loop on list of valid Ids to select the right version to get.
580 // According to query and to the selection criteria list, version can be the highest or exact
584 AliCDBPath queryPath = queryId.GetAliCDBPath();
585 while((anIdPtr = dynamic_cast<AliCDBId*> (iter->Next()))){
586 AliCDBPath thisCDBPath = anIdPtr->GetAliCDBPath();
587 if(!(queryPath.Comprises(thisCDBPath)) || pathCopy.GetPath() == thisCDBPath.GetPath()) continue;
588 pathCopy = thisCDBPath;
590 // check the selection criteria list for this query
591 AliCDBId thisId(*anIdPtr);
592 thisId.SetVersion(queryId.GetVersion());
593 if(!thisId.HasVersion()) GetSelection(&thisId);
596 dataId = GetId(fValidFileIds, thisId);
598 dataId = GetId(validFileIds, thisId);
600 if(dataId) selectedIds.Add(dataId);
605 // selectedIds contains the Ids of the files matching all requests of query!
606 // All the objects are now ready to be retrieved
607 iter = new TIter(&selectedIds);
608 while((anIdPtr = dynamic_cast<AliCDBId*> (iter->Next()))){
610 if (!IdToFilename(*anIdPtr, filename)) {
611 AliDebug(2,Form("Bad data ID encountered! Subnormal error!"));
615 AliCDBEntry* anEntry = GetEntryFromFile(filename, anIdPtr);
617 if(anEntry) result->Add(anEntry);
625 //_____________________________________________________________________________
626 Bool_t AliCDBGrid::PutEntry(AliCDBEntry* entry) {
627 // put an AliCDBEntry object into the database
629 AliCDBId& id = entry->GetId();
631 // set version for the entry to be stored
632 if (!PrepareId(id)) return kFALSE;
634 // build filename from entry's id
636 if (!IdToFilename(id, filename)) {
637 AliError("Bad ID encountered! Subnormal error!");
641 TString folderToTag = Form("%s%s",
643 id.GetPath().Data());
645 TDirectory* saveDir = gDirectory;
647 TString fullFilename = Form("/alien%s", filename.Data());
648 // specify SE to filename
649 if (fSE != "default") fullFilename += Form("?se=%s",fSE.Data());
652 TFile *file = TFile::Open(fullFilename,"CREATE");
653 if(!file || !file->IsWritable()){
654 AliError(Form("Can't open file <%s>!", filename.Data()));
655 if(file && !file->IsWritable()) file->Close(); delete file; file=0;
661 //SetTreeToFile(entry, file);
663 entry->SetVersion(id.GetVersion());
665 // write object (key name: "AliCDBEntry")
666 Bool_t result = (file->WriteTObject(entry, "AliCDBEntry") != 0);
667 if (!result) AliError(Form("Can't write entry to file <%s>!", filename.Data()));
670 if (saveDir) saveDir->cd(); else gROOT->cd();
671 file->Close(); delete file; file=0;
675 if(!TagFileId(filename, &id)){
676 AliInfo(Form("CDB tagging failed. Deleting file %s!",filename.Data()));
677 if(!gGrid->Rm(filename.Data()))
678 AliError("Can't delete file!");
682 TagFileMetaData(filename, entry->GetMetaData());
685 AliInfo(Form("CDB object stored into file %s", filename.Data()));
686 AliInfo(Form("Storage Element: %s", fSE.Data()));
689 //_____________________________________________________________________________
690 Bool_t AliCDBGrid::AddTag(TString& folderToTag, const char* tagname){
691 // add "tagname" tag (CDB or CDB_MD) to folder where object will be stored
693 Bool_t result = kTRUE;
694 AliDebug(2, Form("adding %s tag to folder %s", tagname, folderToTag.Data()));
695 TString addTag = Form("addTag %s %s", folderToTag.Data(), tagname);
696 TGridResult *gridres = gGrid->Command(addTag.Data());
697 const char* resCode = gridres->GetKey(0,"__result__"); // '1' if success
698 if(resCode[0] != '1') {
699 AliError(Form("Couldn't add %s tags to folder %s !",
700 tagname, folderToTag.Data()));
707 //_____________________________________________________________________________
708 Bool_t AliCDBGrid::TagFileId(TString& filename, const AliCDBId* id){
709 // tag stored object in CDB table using object Id's parameters
711 TString addTagValue1 = Form("addTagValue %s CDB ", filename.Data());
712 TString addTagValue2 = Form("first_run=%d last_run=%d version=%d ",
716 TString addTagValue3 = Form("path_level_0=\"%s\" path_level_1=\"%s\" path_level_2=\"%s\"",
717 id->GetPathLevel(0).Data(),
718 id->GetPathLevel(1).Data(),
719 id->GetPathLevel(2).Data());
720 TString addTagValue = Form("%s%s%s",
723 addTagValue3.Data());
725 Bool_t result = kFALSE;
726 AliDebug(2, Form("Tagging file. Tag command: %s", addTagValue.Data()));
727 TGridResult* res = gGrid->Command(addTagValue.Data());
728 const char* resCode = res->GetKey(0,"__result__"); // '1' if success
729 if(resCode[0] != '1') {
730 AliError(Form("Couldn't add CDB tag value to file %s !",
734 AliDebug(2, "Object successfully tagged.");
742 //_____________________________________________________________________________
743 Bool_t AliCDBGrid::TagShortLived(TString& filename, Bool_t value){
744 // tag folder with ShortLived tag
746 TString addTagValue = Form("addTagValue %s ShortLived_try value=%d", filename.Data(), value);
748 Bool_t result = kFALSE;
749 AliDebug(2, Form("Tagging file. Tag command: %s", addTagValue.Data()));
750 TGridResult* res = gGrid->Command(addTagValue.Data());
751 const char* resCode = res->GetKey(0,"__result__"); // '1' if success
752 if(resCode[0] != '1') {
753 AliError(Form("Couldn't add ShortLived tag value to file %s !", filename.Data()));
756 AliDebug(2,"Object successfully tagged.");
764 //_____________________________________________________________________________
765 Bool_t AliCDBGrid::TagFileMetaData(TString& filename, const AliCDBMetaData* md){
766 // tag stored object in CDB table using object Id's parameters
768 TString addTagValue1 = Form("addTagValue %s CDB_MD ", filename.Data());
769 TString addTagValue2 = Form("object_classname=\"%s\" responsible=\"%s\" beam_period=%d ",
770 md->GetObjectClassName(),
771 md->GetResponsible(),
772 md->GetBeamPeriod());
773 TString addTagValue3 = Form("aliroot_version=\"%s\" comment=\"%s\"",
774 md->GetAliRootVersion(),
776 TString addTagValue = Form("%s%s%s",
779 addTagValue3.Data());
781 Bool_t result = kFALSE;
782 AliDebug(2, Form("Tagging file. Tag command: %s", addTagValue.Data()));
783 TGridResult* res = gGrid->Command(addTagValue.Data());
784 const char* resCode = res->GetKey(0,"__result__"); // '1' if success
785 if(resCode[0] != '1') {
786 AliWarning(Form("Couldn't add CDB_MD tag value to file %s !",
790 AliDebug(2,"Object successfully tagged.");
796 //_____________________________________________________________________________
797 TList* AliCDBGrid::GetIdListFromFile(const char* fileName){
799 TString turl(fileName);
800 turl.Prepend("/alien" + fDBFolder);
801 turl += "?se="; turl += fSE.Data();
802 TFile *file = TFile::Open(turl);
804 AliError(Form("Can't open selection file <%s>!", turl.Data()));
808 TList *list = new TList();
816 keycycle = "AliCDBId;";
819 id = (AliCDBId*) file->Get(keycycle);
823 file->Close(); delete file; file=0;
830 //_____________________________________________________________________________
831 Bool_t AliCDBGrid::Contains(const char* path) const{
832 // check for path in storage's DBFolder
834 TString initDir(gGrid->Pwd(0));
835 TString dirName(fDBFolder);
836 dirName += path; // dirName = fDBFolder/path
837 Bool_t result=kFALSE;
838 if (gGrid->Cd(dirName,0)) result=kTRUE;
839 gGrid->Cd(initDir.Data(),0);
843 //_____________________________________________________________________________
844 void AliCDBGrid::QueryValidFiles()
846 // Query the CDB for files valid for AliCDBStorage::fRun
847 // fills list fValidFileIds with AliCDBId objects created from file name
850 MakeQueryFilter(fRun, fRun, fMetaDataFilter, filter);
852 TString pattern = Form("%s/Run*", fPathFilter.GetPath().Data());
853 if(fVersion >= 0) pattern += Form("_v%d*", fVersion);
855 AliDebug(2,Form("pattern: %s", pattern.Data()));
857 TGridResult *res = gGrid->Query(fDBFolder, pattern, filter, "");
859 AliCDBId validFileId;
860 for(int i=0; i<res->GetEntries(); i++){
861 TString filename = res->GetKey(i, "lfn");
862 if(filename == "") continue;
863 AliDebug(2,Form("Found valid file: %s", filename.Data()));
864 Bool_t result = FilenameToId(filename, validFileId);
866 fValidFileIds.AddLast(validFileId.Clone());
873 //_____________________________________________________________________________
874 void AliCDBGrid::MakeQueryFilter(Int_t firstRun, Int_t lastRun,
875 const AliCDBMetaData* md, TString& result) const
877 // create filter for file query
879 result = Form("CDB:first_run<=%d and CDB:last_run>=%d", firstRun, lastRun);
881 // if(version >= 0) {
882 // result += Form(" and CDB:version=%d", version);
884 // if(pathFilter.GetLevel0() != "*") {
885 // result += Form(" and CDB:path_level_0=\"%s\"", pathFilter.GetLevel0().Data());
887 // if(pathFilter.GetLevel1() != "*") {
888 // result += Form(" and CDB:path_level_1=\"%s\"", pathFilter.GetLevel1().Data());
890 // if(pathFilter.GetLevel2() != "*") {
891 // result += Form(" and CDB:path_level_2=\"%s\"", pathFilter.GetLevel2().Data());
895 if(md->GetObjectClassName()[0] != '\0') {
896 result += Form(" and CDB_MD:object_classname=\"%s\"", md->GetObjectClassName());
898 if(md->GetResponsible()[0] != '\0') {
899 result += Form(" and CDB_MD:responsible=\"%s\"", md->GetResponsible());
901 if(md->GetBeamPeriod() != 0) {
902 result += Form(" and CDB_MD:beam_period=%d", md->GetBeamPeriod());
904 if(md->GetAliRootVersion()[0] != '\0') {
905 result += Form(" and CDB_MD:aliroot_version=\"%s\"", md->GetAliRootVersion());
907 if(md->GetComment()[0] != '\0') {
908 result += Form(" and CDB_MD:comment=\"%s\"", md->GetComment());
911 AliDebug(2, Form("filter: %s",result.Data()));
915 //_____________________________________________________________________________
916 Int_t AliCDBGrid::GetLatestVersion(const char* path, Int_t run){
917 // get last version found in the database valid for run and path
919 AliCDBPath aCDBPath(path);
920 if(!aCDBPath.IsValid() || aCDBPath.IsWildcard()) {
921 AliError(Form("Invalid path in request: %s", path));
924 AliCDBId query(path, run, run, -1, -1);
925 AliCDBId* dataId = 0;
927 // look for file matching query requests (path, runRange, version)
928 if(run == fRun && fPathFilter.Comprises(aCDBPath) && fVersion < 0){
929 // look into list of valid files previously loaded with AliCDBStorage::FillValidFileIds()
930 AliDebug(2, Form("List of files valid for run %d and for path %s was loaded. Looking there!",
932 dataId = GetId(fValidFileIds, query);
933 if (!dataId) return -1;
934 Int_t version = dataId->GetVersion();
939 // List of files valid for reqested run was not loaded. Looking directly into CDB
940 AliDebug(2, Form("List of files valid for run %d and for path %s was not loaded. Looking directly into CDB!",
943 TObjArray validFileIds;
944 validFileIds.SetOwner(1);
947 MakeQueryFilter(run, run, 0, filter);
949 TString pattern = Form("%s/Run*.root", path);
950 AliDebug(2,Form("pattern: %s", pattern.Data()));
952 TGridResult *res = gGrid->Query(fDBFolder, pattern, filter, "");
953 AliCDBId validFileId;
954 for(int i=0; i<res->GetEntries(); i++){
955 TString filename = res->GetKey(i, "lfn");
956 if(filename == "") continue;
957 if(FilenameToId(filename, validFileId))
958 validFileIds.AddLast(validFileId.Clone());
962 dataId = GetId(validFileIds, query);
963 if (!dataId) return -1;
965 Int_t version = dataId->GetVersion();
971 //_____________________________________________________________________________
972 Int_t AliCDBGrid::GetLatestSubVersion(const char* /*path*/, Int_t /*run*/, Int_t /*version*/){
973 // get last subversion found in the database valid for run and path
974 AliError("Objects in GRID storage have no sub version!");
979 /////////////////////////////////////////////////////////////////////////////////////////////////
981 // AliCDBGrid factory //
983 /////////////////////////////////////////////////////////////////////////////////////////////////
985 ClassImp(AliCDBGridFactory)
987 //_____________________________________________________________________________
988 Bool_t AliCDBGridFactory::Validate(const char* gridString) {
989 // check if the string is valid Grid URI
991 TRegexp gridPattern("^alien://.+$");
993 return TString(gridString).Contains(gridPattern);
996 //_____________________________________________________________________________
997 AliCDBParam* AliCDBGridFactory::CreateParameter(const char* gridString) {
998 // create AliCDBGridParam class from the URI string
1000 if (!Validate(gridString)) {
1004 TString buffer(gridString);
1006 TString gridUrl = "alien://";
1008 TString dbFolder = "";
1009 TString se = "default";
1010 TString cacheFolder = "";
1011 Bool_t operateDisconnected = kTRUE;
1012 Long64_t cacheSize = (UInt_t) 1024*1024*1024; // 1GB
1013 Long_t cleanupInterval = 0;
1015 TObjArray *arr = buffer.Tokenize('?');
1017 TObjString *str = 0;
1019 while((str = (TObjString*) iter.Next())){
1020 TString entry(str->String());
1021 Int_t indeq = entry.Index('=');
1023 if(entry.BeginsWith("alien://")) { // maybe it's a gridUrl!
1027 AliError(Form("Invalid entry! %s",entry.Data()));
1032 TString key = entry(0,indeq);
1033 TString value = entry(indeq+1,entry.Length()-indeq);
1035 if(key.Contains("grid",TString::kIgnoreCase)) {
1038 else if (key.Contains("user",TString::kIgnoreCase)){
1041 else if (key.Contains("folder",TString::kIgnoreCase)){
1044 else if (key.Contains("se",TString::kIgnoreCase)){
1047 else if (key.Contains("cacheFold",TString::kIgnoreCase)){
1048 cacheFolder = value;
1049 if (!cacheFolder.EndsWith("/"))
1052 else if (key.Contains("operateDisc",TString::kIgnoreCase)){
1053 if(value == "kTRUE") {
1054 operateDisconnected = kTRUE;
1055 } else if (value == "kFALSE") {
1056 operateDisconnected = kFALSE;
1057 } else if (value == "0" || value == "1") {
1058 operateDisconnected = (Bool_t) value.Atoi();
1060 AliError(Form("Invalid entry! %s",entry.Data()));
1064 else if (key.Contains("cacheSiz",TString::kIgnoreCase)){
1065 if(value.IsDigit()) {
1066 cacheSize = value.Atoi();
1068 AliError(Form("Invalid entry! %s",entry.Data()));
1072 else if (key.Contains("cleanupInt",TString::kIgnoreCase)){
1073 if(value.IsDigit()) {
1074 cleanupInterval = value.Atoi();
1076 AliError(Form("Invalid entry! %s",entry.Data()));
1081 AliError(Form("Invalid entry! %s",entry.Data()));
1087 AliDebug(2, Form("gridUrl: %s", gridUrl.Data()));
1088 AliDebug(2, Form("user: %s", user.Data()));
1089 AliDebug(2, Form("dbFolder: %s", dbFolder.Data()));
1090 AliDebug(2, Form("s.e.: %s", se.Data()));
1091 AliDebug(2, Form("local cache folder: %s", cacheFolder.Data()));
1092 AliDebug(2, Form("local cache operate disconnected: %d", operateDisconnected));
1093 AliDebug(2, Form("local cache size: %d", cacheSize));
1094 AliDebug(2, Form("local cache cleanup interval: %d", cleanupInterval));
1097 AliError("Base folder must be specified!");
1101 return new AliCDBGridParam(gridUrl.Data(), user.Data(),
1102 dbFolder.Data(), se.Data(), cacheFolder.Data(),
1103 operateDisconnected, cacheSize, cleanupInterval);
1106 //_____________________________________________________________________________
1107 AliCDBStorage* AliCDBGridFactory::Create(const AliCDBParam* param) {
1108 // create AliCDBGrid storage instance from parameters
1110 AliCDBGrid *grid = 0;
1111 if (AliCDBGridParam::Class() == param->IsA()) {
1113 const AliCDBGridParam* gridParam = (const AliCDBGridParam*) param;
1114 grid = new AliCDBGrid(gridParam->GridUrl().Data(),
1115 gridParam->GetUser().Data(),
1116 gridParam->GetDBFolder().Data(),
1117 gridParam->GetSE().Data(),
1118 gridParam->GetCacheFolder().Data(),
1119 gridParam->GetOperateDisconnected(),
1120 gridParam->GetCacheSize(),
1121 gridParam->GetCleanupInterval());
1125 if(!gGrid && grid) {
1126 delete grid; grid=0;
1132 /////////////////////////////////////////////////////////////////////////////////////////////////
1134 // AliCDBGrid Parameter class // //
1136 /////////////////////////////////////////////////////////////////////////////////////////////////
1138 ClassImp(AliCDBGridParam)
1140 //_____________________________________________________________________________
1141 AliCDBGridParam::AliCDBGridParam():
1148 fOperateDisconnected(),
1153 // default constructor
1157 //_____________________________________________________________________________
1158 AliCDBGridParam::AliCDBGridParam(const char* gridUrl, const char* user, const char* dbFolder,
1159 const char* se, const char* cacheFolder, Bool_t operateDisconnected,
1160 Long64_t cacheSize, Long_t cleanupInterval):
1164 fDBFolder(dbFolder),
1166 fCacheFolder(cacheFolder),
1167 fOperateDisconnected(operateDisconnected),
1168 fCacheSize(cacheSize),
1169 fCleanupInterval(cleanupInterval)
1175 TString uri = Form("%s?User=%s?DBFolder=%s?SE=%s?CacheFolder=%s"
1176 "?OperateDisconnected=%d?CacheSize=%d?CleanupInterval=%d",
1177 fGridUrl.Data(), fUser.Data(),
1178 fDBFolder.Data(), fSE.Data(), fCacheFolder.Data(),
1179 fOperateDisconnected, fCacheSize, fCleanupInterval);
1184 //_____________________________________________________________________________
1185 AliCDBGridParam::~AliCDBGridParam() {
1190 //_____________________________________________________________________________
1191 AliCDBParam* AliCDBGridParam::CloneParam() const {
1194 return new AliCDBGridParam(fGridUrl.Data(), fUser.Data(),
1195 fDBFolder.Data(), fSE.Data(), fCacheFolder.Data(),
1196 fOperateDisconnected, fCacheSize, fCleanupInterval);
1199 //_____________________________________________________________________________
1200 ULong_t AliCDBGridParam::Hash() const {
1201 // return Hash function
1203 return fGridUrl.Hash()+fUser.Hash()+fDBFolder.Hash()+fSE.Hash()+fCacheFolder.Hash();
1206 //_____________________________________________________________________________
1207 Bool_t AliCDBGridParam::IsEqual(const TObject* obj) const {
1208 // check if this object is equal to AliCDBParam obj
1214 if (AliCDBGridParam::Class() != obj->IsA()) {
1218 AliCDBGridParam* other = (AliCDBGridParam*) obj;
1220 if(fGridUrl != other->fGridUrl) return kFALSE;
1221 if(fUser != other->fUser) return kFALSE;
1222 if(fDBFolder != other->fDBFolder) return kFALSE;
1223 if(fSE != other->fSE) return kFALSE;
1224 if(fCacheFolder != other->fCacheFolder) return kFALSE;
1225 if(fOperateDisconnected != other->fOperateDisconnected) return kFALSE;
1226 if(fCacheSize != other->fCacheSize) return kFALSE;
1227 if(fCleanupInterval != other->fCleanupInterval) return kFALSE;