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 TGridResult* res = gGrid->Command(Form("mkdir -p %s",fDBFolder.Data()));
84 TString result = res->GetKey(0,"__result__");
86 AliFatal(Form("Cannot create folder <%s> !",fDBFolder.Data()));
90 AliDebug(2,Form("Folder <%s> found",fDBFolder.Data()));
93 // removes any '/' at the end of path, then append one '/'
94 while(fDBFolder.EndsWith("/")) fDBFolder.Remove(fDBFolder.Last('/'));
98 fBaseFolder = fDBFolder;
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()));
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()));
117 // reset fCacheFolder because the function may have
118 // slightly changed the folder name (e.g. '/' added)
119 fCacheFolder = TFile::GetCacheFileDir();
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 = %d, cleanupInterval = %d !",
126 fCacheSize, fCleanupInterval));
130 // return to the initial directory
131 gGrid->Cd(initDir.Data(),0);
134 //_____________________________________________________________________________
135 AliCDBGrid::~AliCDBGrid()
138 delete gGrid; gGrid=0;
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)
146 if(filename.Contains(fDBFolder)){
147 filename = filename(fDBFolder.Length(),filename.Length()-fDBFolder.Length());
150 TString idPath = filename(0,filename.Last('/'));
152 if(!id.IsValid()) return kFALSE;
154 filename=filename(idPath.Length()+1,filename.Length()-idPath.Length());
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);
162 // TODO backward compatibility ... maybe remove later!
164 TRegexp oldKeyPattern("^Run[0-9]+_[0-9]+_v[0-9]+.root$");
165 oldKeyPattern.Index(filename, &oldmSize);
167 AliDebug(2,Form("Bad filename <%s>.", filename.Data()));
170 AliDebug(2,Form("Old filename format <%s>.", filename.Data()));
171 id.SetSubVersion(-11); // TODO trick to ensure backward compatibility
175 id.SetSubVersion(-1); // TODO trick to ensure backward compatibility
178 filename.Resize(filename.Length() - sizeof(".root") + 1);
180 TObjArray* strArray = (TObjArray*) filename.Tokenize("_");
182 TString firstRunString(((TObjString*) strArray->At(0))->GetString());
183 id.SetFirstRun(atoi(firstRunString.Data() + 3));
184 id.SetLastRun(atoi(((TObjString*) strArray->At(1))->GetString()));
186 TString verString(((TObjString*) strArray->At(2))->GetString());
187 id.SetVersion(atoi(verString.Data() + 1));
194 //_____________________________________________________________________________
195 Bool_t AliCDBGrid::IdToFilename(const AliCDBId& id, TString& filename) const {
196 // build file name from AliCDBId (path, run range, version) and fDBFolder
198 if (!id.GetAliCDBRunRange().IsValid()) {
199 AliDebug(2,Form("Invalid run range <%d, %d>.",
200 id.GetFirstRun(), id.GetLastRun()));
204 if (id.GetVersion() < 0) {
205 AliDebug(2,Form("Invalid version <%d>.", id.GetVersion()));
209 filename = Form("Run%d_%d_v%d",
214 if (id.GetSubVersion() != -11) filename += "_s0"; // TODO to ensure backward compatibility
217 filename.Prepend(fDBFolder + id.GetPath() + '/');
222 //_____________________________________________________________________________
223 Bool_t AliCDBGrid::PrepareId(AliCDBId& id) {
224 // prepare id (version) of the object that will be stored (called by PutEntry)
226 TString initDir(gGrid->Pwd(0));
228 TString dirName(fDBFolder);
230 Bool_t dirExist=kFALSE;
234 // go to the path; if directory does not exist, create it
235 for(int i=0;i<3;i++){
236 dirName+=Form("%s/",id.GetPathLevel(i).Data());
237 dirExist=gGrid->Cd(dirName,0);
239 AliDebug(2,Form("Creating new folder <%s> ...",dirName.Data()));
240 if(!gGrid->Mkdir(dirName,"",0)){
241 AliError(Form("Cannot create directory <%s> !",dirName.Data()));
242 gGrid->Cd(initDir.Data());
246 // if folders are new add tags to them
248 // TODO Currently disabled
249 // add short lived tag!
250 // AliInfo("Tagging level 1 folder with \"ShortLived\" tag");
251 // if(!AddTag(dirName,"ShortLived_try")){
252 // AliError(Form("Could not tag folder %s !", dirName.Data()));
253 // if(!gGrid->Rmdir(dirName.Data())){
254 // AliError(Form("Unexpected: could not remove %s directory!", dirName.Data()));
260 AliDebug(2,"Tagging level 2 folder with \"CDB\" and \"CDB_MD\" tag");
261 if(!AddTag(dirName,"CDB")){
262 AliError(Form("Could not tag folder %s !", dirName.Data()));
263 if(!gGrid->Rmdir(dirName.Data())){
264 AliError(Form("Unexpected: could not remove %s directory!", dirName.Data()));
268 if(!AddTag(dirName,"CDB_MD")){
269 AliError(Form("Could not tag folder %s !", dirName.Data()));
270 if(!gGrid->Rmdir(dirName.Data())){
271 AliError(Form("Unexpected: could not remove %s directory!", dirName.Data()));
276 // TODO Currently disabled
277 // add short lived tag!
278 // TString path=id.GetPath();
279 // if(AliCDBManager::Instance()->IsShortLived(path.Data())) {
280 // AliInfo(Form("Tagging %s as short lived", dirName.Data()));
281 // if(!TagShortLived(dirName, kTRUE)){
282 // AliError(Form("Could not tag folder %s !", dirName.Data()));
283 // if(!gGrid->Rmdir(dirName.Data())){
284 // AliError(Form("Unexpected: could not remove %s directory!", dirName.Data()));
289 // AliInfo(Form("Tagging %s as long lived", dirName.Data()));
290 // if(!TagShortLived(dirName, kFALSE)){
291 // AliError(Form("Could not tag folder %s !", dirName.Data()));
292 // if(!gGrid->Rmdir(dirName.Data())){
293 // AliError(Form("Unexpected: could not remove %s directory!", dirName.Data()));
301 gGrid->Cd(initDir,0);
304 AliCDBId anId; // the id got from filename
305 AliCDBRunRange lastRunRange(-1,-1); // highest runRange found
306 Int_t lastVersion=0; // highest version found
308 TGridResult *res = gGrid->Ls(dirName);
310 //loop on the files in the directory, look for highest version
311 for(int i=0; i < res->GetEntries(); i++){
312 filename=res->GetFileNamePath(i);
313 if (!FilenameToId(filename, anId)) continue;
314 if (anId.GetAliCDBRunRange().Overlaps(id.GetAliCDBRunRange()) && anId.GetVersion() > lastVersion) {
315 lastVersion = anId.GetVersion();
316 lastRunRange = anId.GetAliCDBRunRange();
322 // GRP entries with explicitly set version escape default incremental versioning
323 if(id.GetPath().Contains("GRP") && id.HasVersion() && lastVersion!=0)
325 AliDebug(5,Form("Entry %s won't be put in the destination OCDB", id.ToString().Data()));
329 id.SetVersion(lastVersion + 1);
332 TString lastStorage = id.GetLastStorage();
333 if(lastStorage.Contains(TString("new"), TString::kIgnoreCase) && id.GetVersion() > 1 ){
334 AliDebug(2, Form("A NEW object is being stored with version %d",
336 AliDebug(2, Form("and it will hide previously stored object with version %d!",
340 if(!lastRunRange.IsAnyRange() && !(lastRunRange.IsEqual(&id.GetAliCDBRunRange())))
341 AliWarning(Form("Run range modified w.r.t. previous version (Run%d_%d_v%d)",
342 lastRunRange.GetFirstRun(), lastRunRange.GetLastRun(), id.GetVersion()));
347 //_____________________________________________________________________________
348 AliCDBId* AliCDBGrid::GetId(const TObjArray& validFileIds, const AliCDBId& query) {
349 // look for the Id that matches query's requests (highest or exact version)
351 if(validFileIds.GetEntriesFast() < 1)
354 TIter iter(&validFileIds);
359 while((anIdPtr = dynamic_cast<AliCDBId*> (iter.Next()))){
360 if(anIdPtr->GetPath() != query.GetPath()) continue;
362 //if(!CheckVersion(query, anIdPtr, result)) return NULL;
364 if (!query.HasVersion()){ // look for highest version
365 if(result && result->GetVersion() > anIdPtr->GetVersion()) continue;
366 if(result && result->GetVersion() == anIdPtr->GetVersion()) {
367 AliError(Form("More than one object valid for run %d, version %d!",
368 query.GetFirstRun(), anIdPtr->GetVersion()));
372 } else { // look for specified version
373 if(query.GetVersion() != anIdPtr->GetVersion()) continue;
374 if(result && result->GetVersion() == anIdPtr->GetVersion()){
375 AliError(Form("More than one object valid for run %d, version %d!",
376 query.GetFirstRun(), anIdPtr->GetVersion()));
384 if (!result) return NULL;
386 return dynamic_cast<AliCDBId*> (result->Clone());
389 //_____________________________________________________________________________
390 AliCDBId* AliCDBGrid::GetEntryId(const AliCDBId& queryId) {
391 // get AliCDBId from the database
392 // User must delete returned object
396 AliCDBId selectedId(queryId);
397 if (!selectedId.HasVersion()) {
398 // if version is not specified, first check the selection criteria list
399 GetSelection(&selectedId);
402 TObjArray validFileIds;
403 validFileIds.SetOwner(1);
405 // look for file matching query requests (path, runRange, version)
406 if(selectedId.GetFirstRun() == fRun &&
407 fPathFilter.Comprises(selectedId.GetAliCDBPath()) && fVersion < 0 && !fMetaDataFilter){
408 // look into list of valid files previously loaded with AliCDBStorage::FillValidFileIds()
409 AliDebug(2, Form("List of files valid for run %d was loaded. Looking there for fileids valid for path %s!",
410 selectedId.GetFirstRun(), selectedId.GetPath().Data()));
411 dataId = GetId(fValidFileIds, selectedId);
414 // List of files valid for reqested run was not loaded. Looking directly into CDB
415 AliDebug(2, Form("List of files valid for run %d was not loaded. Looking directly into CDB for fileids valid for path %s!",
416 selectedId.GetFirstRun(), selectedId.GetPath().Data()));
419 MakeQueryFilter(selectedId.GetFirstRun(), selectedId.GetLastRun(), 0, filter);
421 TString pattern = Form("%s/Run*", selectedId.GetPath().Data());
422 if(selectedId.GetVersion() >= 0) pattern += Form("_v%d*",selectedId.GetVersion());
424 AliDebug(2,Form("pattern: %s", pattern.Data()));
426 TGridResult *res = gGrid->Query(fDBFolder, pattern, filter, "");
428 AliCDBId validFileId;
429 for(int i=0; i<res->GetEntries(); i++){
430 TString filename = res->GetKey(i, "lfn");
431 if(filename == "") continue;
432 if(FilenameToId(filename, validFileId))
433 validFileIds.AddLast(validFileId.Clone());
437 dataId = GetId(validFileIds, selectedId);
443 //_____________________________________________________________________________
444 AliCDBEntry* AliCDBGrid::GetEntry(const AliCDBId& queryId) {
445 // get AliCDBEntry from the database
447 AliCDBId* dataId = GetEntryId(queryId);
449 if (!dataId) return NULL;
452 if (!IdToFilename(*dataId, filename)) {
453 AliDebug(2,Form("Bad data ID encountered! Subnormal error!"));
458 AliCDBEntry* anEntry = GetEntryFromFile(filename, dataId);
464 //_____________________________________________________________________________
465 AliCDBEntry* AliCDBGrid::GetEntryFromFile(TString& filename, AliCDBId* dataId){
466 // Get AliCBEntry object from file "filename"
468 AliDebug(2,Form("Opening file: %s",filename.Data()));
470 filename.Prepend("/alien");
472 // if option="CACHEREAD" TFile will use the local caching facility!
473 TString option="READ";
474 if(fCacheFolder != ""){
476 // Check if local cache folder was changed in the meanwhile
477 TString origCache(TFile::GetCacheFileDir());
478 if(fCacheFolder != origCache) {
479 AliWarning(Form("Local cache folder has been overwritten!! fCacheFolder = %s origCache = %s",
480 fCacheFolder.Data(), origCache.Data()));
481 TFile::SetCacheFileDir(fCacheFolder.Data(), fOperateDisconnected);
482 TFile::ShrinkCacheFileDir(fCacheSize, fCleanupInterval);
485 option.Prepend("CACHE");
488 AliDebug(2, Form("Option: %s", option.Data()));
490 TFile *file = TFile::Open(filename, option);
492 AliDebug(2,Form("Can't open file <%s>!", filename.Data()));
496 // get the only AliCDBEntry object from the file
497 // the object in the file is an AliCDBEntry entry named "AliCDBEntry"
499 AliCDBEntry* anEntry = dynamic_cast<AliCDBEntry*> (file->Get("AliCDBEntry"));
502 AliDebug(2,Form("Bad storage data: file does not contain an AliCDBEntry object!"));
507 // The object's Id is not reset during storage
508 // If object's Id runRange or version do not match with filename,
509 // it means that someone renamed file by hand. In this case a warning msg is issued.
512 AliCDBId entryId = anEntry->GetId();
513 Int_t tmpSubVersion = dataId->GetSubVersion();
514 dataId->SetSubVersion(entryId.GetSubVersion()); // otherwise filename and id may mismatch
515 if(!entryId.IsEqual(dataId)){
516 AliWarning(Form("Mismatch between file name and object's Id!"));
517 AliWarning(Form("File name: %s", dataId->ToString().Data()));
518 AliWarning(Form("Object's Id: %s", entryId.ToString().Data()));
520 dataId->SetSubVersion(tmpSubVersion);
523 anEntry->SetLastStorage("grid");
525 // Check whether entry contains a TTree. In case load the tree in memory!
526 LoadTreeFromFile(anEntry);
528 // close file, return retieved entry
529 file->Close(); delete file; file=0;
534 //_____________________________________________________________________________
535 TList* AliCDBGrid::GetEntries(const AliCDBId& queryId) {
536 // multiple request (AliCDBStorage::GetAll)
538 TList* result = new TList();
541 TObjArray validFileIds;
542 validFileIds.SetOwner(1);
544 Bool_t alreadyLoaded = kFALSE;
546 // look for file matching query requests (path, runRange)
547 if(queryId.GetFirstRun() == fRun &&
548 fPathFilter.Comprises(queryId.GetAliCDBPath()) && fVersion < 0 && !fMetaDataFilter){
549 // look into list of valid files previously loaded with AliCDBStorage::FillValidFileIds()
550 AliDebug(2,Form("List of files valid for run %d and for path %s was loaded. Looking there!",
551 queryId.GetFirstRun(), queryId.GetPath().Data()));
553 alreadyLoaded = kTRUE;
556 // List of files valid for reqested run was not loaded. Looking directly into CDB
557 AliDebug(2,Form("List of files valid for run %d and for path %s was not loaded. Looking directly into CDB!",
558 queryId.GetFirstRun(), queryId.GetPath().Data()));
561 MakeQueryFilter(queryId.GetFirstRun(), queryId.GetLastRun(), 0, filter);
563 TString pattern = Form("%s/Run*.root", queryId.GetPath().Data());
564 AliDebug(2,Form("pattern: %s", pattern.Data()));
566 TGridResult *res = gGrid->Query(fDBFolder, pattern, filter, "");
568 AliCDBId validFileId;
569 for(int i=0; i<res->GetEntries(); i++){
570 TString filename = res->GetKey(i, "lfn");
571 if(filename == "") continue;
572 if(FilenameToId(filename, validFileId))
573 validFileIds.AddLast(validFileId.Clone());
580 iter = new TIter(&fValidFileIds);
582 iter = new TIter(&validFileIds);
585 TObjArray selectedIds;
586 selectedIds.SetOwner(1);
588 // loop on list of valid Ids to select the right version to get.
589 // According to query and to the selection criteria list, version can be the highest or exact
593 AliCDBPath queryPath = queryId.GetAliCDBPath();
594 while((anIdPtr = dynamic_cast<AliCDBId*> (iter->Next()))){
595 AliCDBPath thisCDBPath = anIdPtr->GetAliCDBPath();
596 if(!(queryPath.Comprises(thisCDBPath)) || pathCopy.GetPath() == thisCDBPath.GetPath()) continue;
597 pathCopy = thisCDBPath;
599 // check the selection criteria list for this query
600 AliCDBId thisId(*anIdPtr);
601 thisId.SetVersion(queryId.GetVersion());
602 if(!thisId.HasVersion()) GetSelection(&thisId);
605 dataId = GetId(fValidFileIds, thisId);
607 dataId = GetId(validFileIds, thisId);
609 if(dataId) selectedIds.Add(dataId);
614 // selectedIds contains the Ids of the files matching all requests of query!
615 // All the objects are now ready to be retrieved
616 iter = new TIter(&selectedIds);
617 while((anIdPtr = dynamic_cast<AliCDBId*> (iter->Next()))){
619 if (!IdToFilename(*anIdPtr, filename)) {
620 AliDebug(2,Form("Bad data ID encountered! Subnormal error!"));
624 AliCDBEntry* anEntry = GetEntryFromFile(filename, anIdPtr);
626 if(anEntry) result->Add(anEntry);
634 //_____________________________________________________________________________
635 Bool_t AliCDBGrid::PutEntry(AliCDBEntry* entry) {
636 // put an AliCDBEntry object into the database
638 AliCDBId& id = entry->GetId();
640 // set version for the entry to be stored
641 if (!PrepareId(id)) return kFALSE;
643 // build filename from entry's id
645 if (!IdToFilename(id, filename)) {
646 AliError("Bad ID encountered! Subnormal error!");
650 TString folderToTag = Form("%s%s",
652 id.GetPath().Data());
654 TDirectory* saveDir = gDirectory;
656 TString fullFilename = Form("/alien%s", filename.Data());
657 // specify SE to filename
658 if (fSE != "default") fullFilename += Form("?se=%s",fSE.Data());
661 TFile *file = TFile::Open(fullFilename,"CREATE");
662 if(!file || !file->IsWritable()){
663 AliError(Form("Can't open file <%s>!", filename.Data()));
664 if(file && !file->IsWritable()) file->Close(); delete file; file=0;
670 //SetTreeToFile(entry, file);
672 entry->SetVersion(id.GetVersion());
674 // write object (key name: "AliCDBEntry")
675 Bool_t result = (file->WriteTObject(entry, "AliCDBEntry") != 0);
676 if (!result) AliError(Form("Can't write entry to file <%s>!", filename.Data()));
679 if (saveDir) saveDir->cd(); else gROOT->cd();
680 file->Close(); delete file; file=0;
684 if(!TagFileId(filename, &id)){
685 AliInfo(Form("CDB tagging failed. Deleting file %s!",filename.Data()));
686 if(!gGrid->Rm(filename.Data()))
687 AliError("Can't delete file!");
691 TagFileMetaData(filename, entry->GetMetaData());
694 AliInfo(Form("CDB object stored into file %s", filename.Data()));
695 AliInfo(Form("Storage Element: %s", fSE.Data()));
698 //_____________________________________________________________________________
699 Bool_t AliCDBGrid::AddTag(TString& folderToTag, const char* tagname){
700 // add "tagname" tag (CDB or CDB_MD) to folder where object will be stored
702 Bool_t result = kTRUE;
703 AliDebug(2, Form("adding %s tag to folder %s", tagname, folderToTag.Data()));
704 TString addTag = Form("addTag %s %s", folderToTag.Data(), tagname);
705 TGridResult *gridres = gGrid->Command(addTag.Data());
706 const char* resCode = gridres->GetKey(0,"__result__"); // '1' if success
707 if(resCode[0] != '1') {
708 AliError(Form("Couldn't add %s tags to folder %s !",
709 tagname, folderToTag.Data()));
716 //_____________________________________________________________________________
717 Bool_t AliCDBGrid::TagFileId(TString& filename, const AliCDBId* id){
718 // tag stored object in CDB table using object Id's parameters
720 TString addTagValue1 = Form("addTagValue %s CDB ", filename.Data());
721 TString addTagValue2 = Form("first_run=%d last_run=%d version=%d ",
725 TString addTagValue3 = Form("path_level_0=\"%s\" path_level_1=\"%s\" path_level_2=\"%s\"",
726 id->GetPathLevel(0).Data(),
727 id->GetPathLevel(1).Data(),
728 id->GetPathLevel(2).Data());
729 TString addTagValue = Form("%s%s%s",
732 addTagValue3.Data());
734 Bool_t result = kFALSE;
735 AliDebug(2, Form("Tagging file. Tag command: %s", addTagValue.Data()));
736 TGridResult* res = gGrid->Command(addTagValue.Data());
737 const char* resCode = res->GetKey(0,"__result__"); // '1' if success
738 if(resCode[0] != '1') {
739 AliError(Form("Couldn't add CDB tag value to file %s !",
743 AliDebug(2, "Object successfully tagged.");
751 //_____________________________________________________________________________
752 Bool_t AliCDBGrid::TagShortLived(TString& filename, Bool_t value){
753 // tag folder with ShortLived tag
755 TString addTagValue = Form("addTagValue %s ShortLived_try value=%d", filename.Data(), value);
757 Bool_t result = kFALSE;
758 AliDebug(2, Form("Tagging file. Tag command: %s", addTagValue.Data()));
759 TGridResult* res = gGrid->Command(addTagValue.Data());
760 const char* resCode = res->GetKey(0,"__result__"); // '1' if success
761 if(resCode[0] != '1') {
762 AliError(Form("Couldn't add ShortLived tag value to file %s !", filename.Data()));
765 AliDebug(2,"Object successfully tagged.");
773 //_____________________________________________________________________________
774 Bool_t AliCDBGrid::TagFileMetaData(TString& filename, const AliCDBMetaData* md){
775 // tag stored object in CDB table using object Id's parameters
777 TString addTagValue1 = Form("addTagValue %s CDB_MD ", filename.Data());
778 TString addTagValue2 = Form("object_classname=\"%s\" responsible=\"%s\" beam_period=%d ",
779 md->GetObjectClassName(),
780 md->GetResponsible(),
781 md->GetBeamPeriod());
782 TString addTagValue3 = Form("aliroot_version=\"%s\" comment=\"%s\"",
783 md->GetAliRootVersion(),
785 TString addTagValue = Form("%s%s%s",
788 addTagValue3.Data());
790 Bool_t result = kFALSE;
791 AliDebug(2, Form("Tagging file. Tag command: %s", addTagValue.Data()));
792 TGridResult* res = gGrid->Command(addTagValue.Data());
793 const char* resCode = res->GetKey(0,"__result__"); // '1' if success
794 if(resCode[0] != '1') {
795 AliWarning(Form("Couldn't add CDB_MD tag value to file %s !",
799 AliDebug(2,"Object successfully tagged.");
805 //_____________________________________________________________________________
806 TList* AliCDBGrid::GetIdListFromFile(const char* fileName){
808 TString turl(fileName);
809 turl.Prepend("/alien" + fDBFolder);
810 turl += "?se="; turl += fSE.Data();
811 TFile *file = TFile::Open(turl);
813 AliError(Form("Can't open selection file <%s>!", turl.Data()));
817 TList *list = new TList();
825 keycycle = "AliCDBId;";
828 id = (AliCDBId*) file->Get(keycycle);
832 file->Close(); delete file; file=0;
839 //_____________________________________________________________________________
840 Bool_t AliCDBGrid::Contains(const char* path) const{
841 // check for path in storage's DBFolder
843 TString initDir(gGrid->Pwd(0));
844 TString dirName(fDBFolder);
845 dirName += path; // dirName = fDBFolder/path
846 Bool_t result=kFALSE;
847 if (gGrid->Cd(dirName,0)) result=kTRUE;
848 gGrid->Cd(initDir.Data(),0);
852 //_____________________________________________________________________________
853 void AliCDBGrid::QueryValidFiles()
855 // Query the CDB for files valid for AliCDBStorage::fRun
856 // fills list fValidFileIds with AliCDBId objects created from file name
859 MakeQueryFilter(fRun, fRun, fMetaDataFilter, filter);
861 TString pattern = Form("%s/Run*", fPathFilter.GetPath().Data());
862 if(fVersion >= 0) pattern += Form("_v%d*", fVersion);
864 AliDebug(2,Form("pattern: %s", pattern.Data()));
866 TGridResult *res = gGrid->Query(fDBFolder, pattern, filter, "");
869 AliError("Grid query failed");
873 AliCDBId validFileId;
874 for(int i=0; i<res->GetEntries(); i++){
875 TString filename = res->GetKey(i, "lfn");
876 if(filename == "") continue;
877 AliDebug(2,Form("Found valid file: %s", filename.Data()));
878 Bool_t result = FilenameToId(filename, validFileId);
880 fValidFileIds.AddLast(validFileId.Clone());
887 //_____________________________________________________________________________
888 void AliCDBGrid::MakeQueryFilter(Int_t firstRun, Int_t lastRun,
889 const AliCDBMetaData* md, TString& result) const
891 // create filter for file query
893 result = Form("CDB:first_run<=%d and CDB:last_run>=%d", firstRun, lastRun);
895 // if(version >= 0) {
896 // result += Form(" and CDB:version=%d", version);
898 // if(pathFilter.GetLevel0() != "*") {
899 // result += Form(" and CDB:path_level_0=\"%s\"", pathFilter.GetLevel0().Data());
901 // if(pathFilter.GetLevel1() != "*") {
902 // result += Form(" and CDB:path_level_1=\"%s\"", pathFilter.GetLevel1().Data());
904 // if(pathFilter.GetLevel2() != "*") {
905 // result += Form(" and CDB:path_level_2=\"%s\"", pathFilter.GetLevel2().Data());
909 if(md->GetObjectClassName()[0] != '\0') {
910 result += Form(" and CDB_MD:object_classname=\"%s\"", md->GetObjectClassName());
912 if(md->GetResponsible()[0] != '\0') {
913 result += Form(" and CDB_MD:responsible=\"%s\"", md->GetResponsible());
915 if(md->GetBeamPeriod() != 0) {
916 result += Form(" and CDB_MD:beam_period=%d", md->GetBeamPeriod());
918 if(md->GetAliRootVersion()[0] != '\0') {
919 result += Form(" and CDB_MD:aliroot_version=\"%s\"", md->GetAliRootVersion());
921 if(md->GetComment()[0] != '\0') {
922 result += Form(" and CDB_MD:comment=\"%s\"", md->GetComment());
925 AliDebug(2, Form("filter: %s",result.Data()));
929 //_____________________________________________________________________________
930 Int_t AliCDBGrid::GetLatestVersion(const char* path, Int_t run){
931 // get last version found in the database valid for run and path
933 AliCDBPath aCDBPath(path);
934 if(!aCDBPath.IsValid() || aCDBPath.IsWildcard()) {
935 AliError(Form("Invalid path in request: %s", path));
938 AliCDBId query(path, run, run, -1, -1);
939 AliCDBId* dataId = 0;
941 // look for file matching query requests (path, runRange, version)
942 if(run == fRun && fPathFilter.Comprises(aCDBPath) && fVersion < 0){
943 // look into list of valid files previously loaded with AliCDBStorage::FillValidFileIds()
944 AliDebug(2, Form("List of files valid for run %d and for path %s was loaded. Looking there!",
946 dataId = GetId(fValidFileIds, query);
947 if (!dataId) return -1;
948 Int_t version = dataId->GetVersion();
953 // List of files valid for reqested run was not loaded. Looking directly into CDB
954 AliDebug(2, Form("List of files valid for run %d and for path %s was not loaded. Looking directly into CDB!",
957 TObjArray validFileIds;
958 validFileIds.SetOwner(1);
961 MakeQueryFilter(run, run, 0, filter);
963 TString pattern = Form("%s/Run*.root", path);
964 AliDebug(2,Form("pattern: %s", pattern.Data()));
966 TGridResult *res = gGrid->Query(fDBFolder, pattern, filter, "");
967 AliCDBId validFileId;
968 for(int i=0; i<res->GetEntries(); i++){
969 TString filename = res->GetKey(i, "lfn");
970 if(filename == "") continue;
971 if(FilenameToId(filename, validFileId))
972 validFileIds.AddLast(validFileId.Clone());
976 dataId = GetId(validFileIds, query);
977 if (!dataId) return -1;
979 Int_t version = dataId->GetVersion();
985 //_____________________________________________________________________________
986 Int_t AliCDBGrid::GetLatestSubVersion(const char* /*path*/, Int_t /*run*/, Int_t /*version*/){
987 // get last subversion found in the database valid for run and path
988 AliError("Objects in GRID storage have no sub version!");
993 /////////////////////////////////////////////////////////////////////////////////////////////////
995 // AliCDBGrid factory //
997 /////////////////////////////////////////////////////////////////////////////////////////////////
999 ClassImp(AliCDBGridFactory)
1001 //_____________________________________________________________________________
1002 Bool_t AliCDBGridFactory::Validate(const char* gridString) {
1003 // check if the string is valid Grid URI
1005 TRegexp gridPattern("^alien://.+$");
1007 return TString(gridString).Contains(gridPattern);
1010 //_____________________________________________________________________________
1011 AliCDBParam* AliCDBGridFactory::CreateParameter(const char* gridString) {
1012 // create AliCDBGridParam class from the URI string
1014 if (!Validate(gridString)) {
1018 TString buffer(gridString);
1020 TString gridUrl = "alien://";
1022 TString dbFolder = "";
1023 TString se = "default";
1024 TString cacheFolder = "";
1025 Bool_t operateDisconnected = kTRUE;
1026 Long64_t cacheSize = (UInt_t) 1024*1024*1024; // 1GB
1027 Long_t cleanupInterval = 0;
1029 TObjArray *arr = buffer.Tokenize('?');
1031 TObjString *str = 0;
1033 while((str = (TObjString*) iter.Next())){
1034 TString entry(str->String());
1035 Int_t indeq = entry.Index('=');
1037 if(entry.BeginsWith("alien://")) { // maybe it's a gridUrl!
1041 AliError(Form("Invalid entry! %s",entry.Data()));
1046 TString key = entry(0,indeq);
1047 TString value = entry(indeq+1,entry.Length()-indeq);
1049 if(key.Contains("grid",TString::kIgnoreCase)) {
1052 else if (key.Contains("user",TString::kIgnoreCase)){
1055 else if (key.Contains("se",TString::kIgnoreCase)){
1058 else if (key.Contains("cacheF",TString::kIgnoreCase)){
1059 cacheFolder = value;
1060 if (!cacheFolder.EndsWith("/"))
1063 else if (key.Contains("folder",TString::kIgnoreCase)){
1066 else if (key.Contains("operateDisc",TString::kIgnoreCase)){
1067 if(value == "kTRUE") {
1068 operateDisconnected = kTRUE;
1069 } else if (value == "kFALSE") {
1070 operateDisconnected = kFALSE;
1071 } else if (value == "0" || value == "1") {
1072 operateDisconnected = (Bool_t) value.Atoi();
1074 AliError(Form("Invalid entry! %s",entry.Data()));
1078 else if (key.Contains("cacheS",TString::kIgnoreCase)){
1079 if(value.IsDigit()) {
1080 cacheSize = value.Atoi();
1082 AliError(Form("Invalid entry! %s",entry.Data()));
1086 else if (key.Contains("cleanupInt",TString::kIgnoreCase)){
1087 if(value.IsDigit()) {
1088 cleanupInterval = value.Atoi();
1090 AliError(Form("Invalid entry! %s",entry.Data()));
1095 AliError(Form("Invalid entry! %s",entry.Data()));
1101 AliDebug(2, Form("gridUrl: %s", gridUrl.Data()));
1102 AliDebug(2, Form("user: %s", user.Data()));
1103 AliDebug(2, Form("dbFolder: %s", dbFolder.Data()));
1104 AliDebug(2, Form("s.e.: %s", se.Data()));
1105 AliDebug(2, Form("local cache folder: %s", cacheFolder.Data()));
1106 AliDebug(2, Form("local cache operate disconnected: %d", operateDisconnected));
1107 AliDebug(2, Form("local cache size: %d", cacheSize));
1108 AliDebug(2, Form("local cache cleanup interval: %d", cleanupInterval));
1111 AliError("Base folder must be specified!");
1115 return new AliCDBGridParam(gridUrl.Data(), user.Data(),
1116 dbFolder.Data(), se.Data(), cacheFolder.Data(),
1117 operateDisconnected, cacheSize, cleanupInterval);
1120 //_____________________________________________________________________________
1121 AliCDBStorage* AliCDBGridFactory::Create(const AliCDBParam* param) {
1122 // create AliCDBGrid storage instance from parameters
1124 AliCDBGrid *grid = 0;
1125 if (AliCDBGridParam::Class() == param->IsA()) {
1127 const AliCDBGridParam* gridParam = (const AliCDBGridParam*) param;
1128 grid = new AliCDBGrid(gridParam->GridUrl().Data(),
1129 gridParam->GetUser().Data(),
1130 gridParam->GetDBFolder().Data(),
1131 gridParam->GetSE().Data(),
1132 gridParam->GetCacheFolder().Data(),
1133 gridParam->GetOperateDisconnected(),
1134 gridParam->GetCacheSize(),
1135 gridParam->GetCleanupInterval());
1139 if(!gGrid && grid) {
1140 delete grid; grid=0;
1146 /////////////////////////////////////////////////////////////////////////////////////////////////
1148 // AliCDBGrid Parameter class // //
1150 /////////////////////////////////////////////////////////////////////////////////////////////////
1152 ClassImp(AliCDBGridParam)
1154 //_____________________________________________________________________________
1155 AliCDBGridParam::AliCDBGridParam():
1162 fOperateDisconnected(),
1167 // default constructor
1171 //_____________________________________________________________________________
1172 AliCDBGridParam::AliCDBGridParam(const char* gridUrl, const char* user, const char* dbFolder,
1173 const char* se, const char* cacheFolder, Bool_t operateDisconnected,
1174 Long64_t cacheSize, Long_t cleanupInterval):
1178 fDBFolder(dbFolder),
1180 fCacheFolder(cacheFolder),
1181 fOperateDisconnected(operateDisconnected),
1182 fCacheSize(cacheSize),
1183 fCleanupInterval(cleanupInterval)
1189 TString uri = Form("%s?User=%s?DBFolder=%s?SE=%s?CacheFolder=%s"
1190 "?OperateDisconnected=%d?CacheSize=%d?CleanupInterval=%d",
1191 fGridUrl.Data(), fUser.Data(),
1192 fDBFolder.Data(), fSE.Data(), fCacheFolder.Data(),
1193 fOperateDisconnected, fCacheSize, fCleanupInterval);
1198 //_____________________________________________________________________________
1199 AliCDBGridParam::~AliCDBGridParam() {
1204 //_____________________________________________________________________________
1205 AliCDBParam* AliCDBGridParam::CloneParam() const {
1208 return new AliCDBGridParam(fGridUrl.Data(), fUser.Data(),
1209 fDBFolder.Data(), fSE.Data(), fCacheFolder.Data(),
1210 fOperateDisconnected, fCacheSize, fCleanupInterval);
1213 //_____________________________________________________________________________
1214 ULong_t AliCDBGridParam::Hash() const {
1215 // return Hash function
1217 return fGridUrl.Hash()+fUser.Hash()+fDBFolder.Hash()+fSE.Hash()+fCacheFolder.Hash();
1220 //_____________________________________________________________________________
1221 Bool_t AliCDBGridParam::IsEqual(const TObject* obj) const {
1222 // check if this object is equal to AliCDBParam obj
1228 if (AliCDBGridParam::Class() != obj->IsA()) {
1232 AliCDBGridParam* other = (AliCDBGridParam*) obj;
1234 if(fGridUrl != other->fGridUrl) return kFALSE;
1235 if(fUser != other->fUser) return kFALSE;
1236 if(fDBFolder != other->fDBFolder) return kFALSE;
1237 if(fSE != other->fSE) return kFALSE;
1238 if(fCacheFolder != other->fCacheFolder) return kFALSE;
1239 if(fOperateDisconnected != other->fOperateDisconnected) return kFALSE;
1240 if(fCacheSize != other->fCacheSize) return kFALSE;
1241 if(fCleanupInterval != other->fCleanupInterval) return kFALSE;