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 AliDebug(2,Form("1. Grid Url = %s",fGridUrl.Data()));
68 if (fGridUrl == "raw://") fGridUrl = "alien://";
69 AliDebug(2,Form("2. Grid Url = %s (should be different from previous in cas eof raw)", fGridUrl.Data()));
70 TGrid::Connect(fGridUrl.Data(),fUser.Data());
74 AliError("Connection failed!");
78 TString initDir(gGrid->Pwd(0));
79 if (fDBFolder[0] != '/') {
80 fDBFolder.Prepend(initDir);
83 // check DBFolder: trying to cd to DBFolder; if it does not exist, create it
84 if(!gGrid->Cd(fDBFolder.Data(),0)){
85 AliDebug(2,Form("Creating new folder <%s> ...",fDBFolder.Data()));
86 TGridResult* res = gGrid->Command(Form("mkdir -p %s",fDBFolder.Data()));
87 TString result = res->GetKey(0,"__result__");
89 AliFatal(Form("Cannot create folder <%s> !",fDBFolder.Data()));
93 AliDebug(2,Form("Folder <%s> found",fDBFolder.Data()));
96 // removes any '/' at the end of path, then append one '/'
97 while(fDBFolder.EndsWith("/")) fDBFolder.Remove(fDBFolder.Last('/'));
101 fBaseFolder = fDBFolder;
105 // Check if local cache folder is already defined
106 TString origCache(TFile::GetCacheFileDir());
107 if(fCacheFolder.Length() > 0) {
108 if(origCache.Length() == 0) {
109 AliInfo(Form("Setting local cache to: %s", fCacheFolder.Data()));
110 } else if(fCacheFolder != origCache) {
111 AliWarning(Form("Local cache folder was already defined, changing it to: %s",
112 fCacheFolder.Data()));
115 // default settings are: operateDisconnected=kTRUE, forceCacheread = kFALSE
116 if(!TFile::SetCacheFileDir(fCacheFolder.Data(), fOperateDisconnected)) {
117 AliError(Form("Could not set cache folder %s !", fCacheFolder.Data()));
120 // reset fCacheFolder because the function may have
121 // slightly changed the folder name (e.g. '/' added)
122 fCacheFolder = TFile::GetCacheFileDir();
125 // default settings are: cacheSize=1GB, cleanupInterval = 0
126 if(!TFile::ShrinkCacheFileDir(fCacheSize, fCleanupInterval)) {
127 AliError(Form("Could not set following values "
128 "to ShrinkCacheFileDir: cacheSize = %d, cleanupInterval = %d !",
129 fCacheSize, fCleanupInterval));
133 // return to the initial directory
134 gGrid->Cd(initDir.Data(),0);
137 //_____________________________________________________________________________
138 AliCDBGrid::~AliCDBGrid()
141 delete gGrid; gGrid=0;
145 //_____________________________________________________________________________
146 Bool_t AliCDBGrid::FilenameToId(TString& filename, AliCDBId& id) {
147 // build AliCDBId from full path filename (fDBFolder/path/Run#x_#y_v#z_s0.root)
149 if(filename.Contains(fDBFolder)){
150 filename = filename(fDBFolder.Length(),filename.Length()-fDBFolder.Length());
153 TString idPath = filename(0,filename.Last('/'));
155 if(!id.IsValid()) return kFALSE;
157 filename=filename(idPath.Length()+1,filename.Length()-idPath.Length());
160 // valid filename: Run#firstRun_#lastRun_v#version_s0.root
161 TRegexp keyPattern("^Run[0-9]+_[0-9]+_v[0-9]+_s0.root$");
162 keyPattern.Index(filename, &mSize);
165 // TODO backward compatibility ... maybe remove later!
167 TRegexp oldKeyPattern("^Run[0-9]+_[0-9]+_v[0-9]+.root$");
168 oldKeyPattern.Index(filename, &oldmSize);
170 AliDebug(2,Form("Bad filename <%s>.", filename.Data()));
173 AliDebug(2,Form("Old filename format <%s>.", filename.Data()));
174 id.SetSubVersion(-11); // TODO trick to ensure backward compatibility
178 id.SetSubVersion(-1); // TODO trick to ensure backward compatibility
181 filename.Resize(filename.Length() - sizeof(".root") + 1);
183 TObjArray* strArray = (TObjArray*) filename.Tokenize("_");
185 TString firstRunString(((TObjString*) strArray->At(0))->GetString());
186 id.SetFirstRun(atoi(firstRunString.Data() + 3));
187 id.SetLastRun(atoi(((TObjString*) strArray->At(1))->GetString()));
189 TString verString(((TObjString*) strArray->At(2))->GetString());
190 id.SetVersion(atoi(verString.Data() + 1));
197 //_____________________________________________________________________________
198 Bool_t AliCDBGrid::IdToFilename(const AliCDBId& id, TString& filename) const {
199 // build file name from AliCDBId (path, run range, version) and fDBFolder
201 if (!id.GetAliCDBRunRange().IsValid()) {
202 AliDebug(2,Form("Invalid run range <%d, %d>.",
203 id.GetFirstRun(), id.GetLastRun()));
207 if (id.GetVersion() < 0) {
208 AliDebug(2,Form("Invalid version <%d>.", id.GetVersion()));
212 filename = Form("Run%d_%d_v%d",
217 if (id.GetSubVersion() != -11) filename += "_s0"; // TODO to ensure backward compatibility
220 filename.Prepend(fDBFolder + id.GetPath() + '/');
225 //_____________________________________________________________________________
226 Bool_t AliCDBGrid::PrepareId(AliCDBId& id) {
227 // prepare id (version) of the object that will be stored (called by PutEntry)
229 TString initDir(gGrid->Pwd(0));
231 TString dirName(fDBFolder);
233 Bool_t dirExist=kFALSE;
237 // go to the path; if directory does not exist, create it
238 for(int i=0;i<3;i++){
239 dirName+=Form("%s/",id.GetPathLevel(i).Data());
240 dirExist=gGrid->Cd(dirName,0);
242 AliDebug(2,Form("Creating new folder <%s> ...",dirName.Data()));
243 if(!gGrid->Mkdir(dirName,"",0)){
244 AliError(Form("Cannot create directory <%s> !",dirName.Data()));
245 gGrid->Cd(initDir.Data());
249 // if folders are new add tags to them
251 // TODO Currently disabled
252 // add short lived tag!
253 // AliInfo("Tagging level 1 folder with \"ShortLived\" tag");
254 // if(!AddTag(dirName,"ShortLived_try")){
255 // AliError(Form("Could not tag folder %s !", dirName.Data()));
256 // if(!gGrid->Rmdir(dirName.Data())){
257 // AliError(Form("Unexpected: could not remove %s directory!", dirName.Data()));
263 AliDebug(2,"Tagging level 2 folder with \"CDB\" and \"CDB_MD\" tag");
264 if(!AddTag(dirName,"CDB")){
265 AliError(Form("Could not tag folder %s !", dirName.Data()));
266 if(!gGrid->Rmdir(dirName.Data())){
267 AliError(Form("Unexpected: could not remove %s directory!", dirName.Data()));
271 if(!AddTag(dirName,"CDB_MD")){
272 AliError(Form("Could not tag folder %s !", dirName.Data()));
273 if(!gGrid->Rmdir(dirName.Data())){
274 AliError(Form("Unexpected: could not remove %s directory!", dirName.Data()));
279 // TODO Currently disabled
280 // add short lived tag!
281 // TString path=id.GetPath();
282 // if(AliCDBManager::Instance()->IsShortLived(path.Data())) {
283 // AliInfo(Form("Tagging %s as short lived", dirName.Data()));
284 // if(!TagShortLived(dirName, kTRUE)){
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 // AliInfo(Form("Tagging %s as long lived", dirName.Data()));
293 // if(!TagShortLived(dirName, kFALSE)){
294 // AliError(Form("Could not tag folder %s !", dirName.Data()));
295 // if(!gGrid->Rmdir(dirName.Data())){
296 // AliError(Form("Unexpected: could not remove %s directory!", dirName.Data()));
304 gGrid->Cd(initDir,0);
307 AliCDBId anId; // the id got from filename
308 AliCDBRunRange lastRunRange(-1,-1); // highest runRange found
309 Int_t lastVersion=0; // highest version found
311 TGridResult *res = gGrid->Ls(dirName);
313 //loop on the files in the directory, look for highest version
314 for(int i=0; i < res->GetEntries(); i++){
315 filename=res->GetFileNamePath(i);
316 if (!FilenameToId(filename, anId)) continue;
317 if (anId.GetAliCDBRunRange().Overlaps(id.GetAliCDBRunRange()) && anId.GetVersion() > lastVersion) {
318 lastVersion = anId.GetVersion();
319 lastRunRange = anId.GetAliCDBRunRange();
325 // GRP entries with explicitly set version escape default incremental versioning
326 if(id.GetPath().Contains("GRP") && id.HasVersion() && lastVersion!=0)
328 AliDebug(5,Form("Entry %s won't be put in the destination OCDB", id.ToString().Data()));
332 id.SetVersion(lastVersion + 1);
335 TString lastStorage = id.GetLastStorage();
336 if(lastStorage.Contains(TString("new"), TString::kIgnoreCase) && id.GetVersion() > 1 ){
337 AliDebug(2, Form("A NEW object is being stored with version %d",
339 AliDebug(2, Form("and it will hide previously stored object with version %d!",
343 if(!lastRunRange.IsAnyRange() && !(lastRunRange.IsEqual(&id.GetAliCDBRunRange())))
344 AliWarning(Form("Run range modified w.r.t. previous version (Run%d_%d_v%d)",
345 lastRunRange.GetFirstRun(), lastRunRange.GetLastRun(), id.GetVersion()));
350 //_____________________________________________________________________________
351 AliCDBId* AliCDBGrid::GetId(const TObjArray& validFileIds, const AliCDBId& query) {
352 // look for the Id that matches query's requests (highest or exact version)
354 if(validFileIds.GetEntriesFast() < 1) {
356 } else if (validFileIds.GetEntriesFast() == 1) {
357 return dynamic_cast<AliCDBId*> (validFileIds.At(0)->Clone());
360 TIter iter(&validFileIds);
365 while((anIdPtr = dynamic_cast<AliCDBId*> (iter.Next()))){
366 if(anIdPtr->GetPath() != query.GetPath()) continue;
368 //if(!CheckVersion(query, anIdPtr, result)) return NULL;
370 if (!query.HasVersion()){ // look for highest version
371 if(result && result->GetVersion() > anIdPtr->GetVersion()) continue;
372 if(result && result->GetVersion() == anIdPtr->GetVersion()) {
373 AliError(Form("More than one object valid for run %d, version %d!",
374 query.GetFirstRun(), anIdPtr->GetVersion()));
378 } else { // look for specified version
379 if(query.GetVersion() != anIdPtr->GetVersion()) continue;
380 if(result && result->GetVersion() == anIdPtr->GetVersion()){
381 AliError(Form("More than one object valid for run %d, version %d!",
382 query.GetFirstRun(), anIdPtr->GetVersion()));
390 if (!result) return NULL;
392 return dynamic_cast<AliCDBId*> (result->Clone());
395 //_____________________________________________________________________________
396 AliCDBId* AliCDBGrid::GetEntryId(const AliCDBId& queryId) {
397 // get AliCDBId from the database
398 // User must delete returned object
402 AliCDBId selectedId(queryId);
403 if (!selectedId.HasVersion()) {
404 // if version is not specified, first check the selection criteria list
405 GetSelection(&selectedId);
408 TObjArray validFileIds;
409 validFileIds.SetOwner(1);
411 // look for file matching query requests (path, runRange, version)
412 if(selectedId.GetFirstRun() == fRun &&
413 fPathFilter.Comprises(selectedId.GetAliCDBPath()) && fVersion < 0 && !fMetaDataFilter){
414 // look into list of valid files previously loaded with AliCDBStorage::FillValidFileIds()
415 AliDebug(2, Form("List of files valid for run %d and for path %s was loaded. Looking there!",
416 selectedId.GetFirstRun(), selectedId.GetPath().Data()));
417 dataId = GetId(fValidFileIds, selectedId);
420 // List of files valid for reqested run was not loaded. Looking directly into CDB
421 AliDebug(2, Form("List of files valid for run %d and for path %s was not loaded. Looking directly into CDB!",
422 selectedId.GetFirstRun(), selectedId.GetPath().Data()));
425 MakeQueryFilter(selectedId.GetFirstRun(), selectedId.GetLastRun(), 0, filter);
427 TString pattern = Form("%s/Run*", selectedId.GetPath().Data());
428 if(selectedId.GetVersion() >= 0) pattern += Form("_v%d*",selectedId.GetVersion());
430 AliDebug(2,Form("pattern: %s", pattern.Data()));
432 TGridResult *res = gGrid->Query(fDBFolder, pattern, filter, "");
434 AliCDBId validFileId;
435 for(int i=0; i<res->GetEntries(); i++){
436 TString filename = res->GetKey(i, "lfn");
437 if(filename == "") continue;
438 if(FilenameToId(filename, validFileId))
439 validFileIds.AddLast(validFileId.Clone());
443 dataId = GetId(validFileIds, selectedId);
449 //_____________________________________________________________________________
450 AliCDBEntry* AliCDBGrid::GetEntry(const AliCDBId& queryId) {
451 // get AliCDBEntry from the database
453 AliCDBId* dataId = GetEntryId(queryId);
455 if (!dataId) return NULL;
458 if (!IdToFilename(*dataId, filename)) {
459 AliDebug(2,Form("Bad data ID encountered! Subnormal error!"));
464 AliCDBEntry* anEntry = GetEntryFromFile(filename, dataId);
470 //_____________________________________________________________________________
471 AliCDBEntry* AliCDBGrid::GetEntryFromFile(TString& filename, AliCDBId* dataId){
472 // Get AliCBEntry object from file "filename"
474 AliDebug(2,Form("Opening file: %s",filename.Data()));
476 filename.Prepend("/alien");
478 // if option="CACHEREAD" TFile will use the local caching facility!
479 TString option="READ";
480 if(fCacheFolder != ""){
482 // Check if local cache folder was changed in the meanwhile
483 TString origCache(TFile::GetCacheFileDir());
484 if(fCacheFolder != origCache) {
485 AliWarning(Form("Local cache folder has been overwritten!! fCacheFolder = %s origCache = %s",
486 fCacheFolder.Data(), origCache.Data()));
487 TFile::SetCacheFileDir(fCacheFolder.Data(), fOperateDisconnected);
488 TFile::ShrinkCacheFileDir(fCacheSize, fCleanupInterval);
491 option.Prepend("CACHE");
494 AliDebug(2, Form("Option: %s", option.Data()));
496 TFile *file = TFile::Open(filename, option);
498 AliDebug(2,Form("Can't open file <%s>!", filename.Data()));
502 // get the only AliCDBEntry object from the file
503 // the object in the file is an AliCDBEntry entry named "AliCDBEntry"
505 AliCDBEntry* anEntry = dynamic_cast<AliCDBEntry*> (file->Get("AliCDBEntry"));
508 AliDebug(2,Form("Bad storage data: file does not contain an AliCDBEntry object!"));
513 // The object's Id is not reset during storage
514 // If object's Id runRange or version do not match with filename,
515 // it means that someone renamed file by hand. In this case a warning msg is issued.
518 AliCDBId entryId = anEntry->GetId();
519 Int_t tmpSubVersion = dataId->GetSubVersion();
520 dataId->SetSubVersion(entryId.GetSubVersion()); // otherwise filename and id may mismatch
521 if(!entryId.IsEqual(dataId)){
522 AliWarning(Form("Mismatch between file name and object's Id!"));
523 AliWarning(Form("File name: %s", dataId->ToString().Data()));
524 AliWarning(Form("Object's Id: %s", entryId.ToString().Data()));
526 dataId->SetSubVersion(tmpSubVersion);
529 anEntry->SetLastStorage("grid");
531 // Check whether entry contains a TTree. In case load the tree in memory!
532 LoadTreeFromFile(anEntry);
534 // close file, return retieved entry
535 file->Close(); delete file; file=0;
540 //_____________________________________________________________________________
541 TList* AliCDBGrid::GetEntries(const AliCDBId& queryId) {
542 // multiple request (AliCDBStorage::GetAll)
544 TList* result = new TList();
547 TObjArray validFileIds;
548 validFileIds.SetOwner(1);
550 Bool_t alreadyLoaded = kFALSE;
552 // look for file matching query requests (path, runRange)
553 if(queryId.GetFirstRun() == fRun &&
554 fPathFilter.Comprises(queryId.GetAliCDBPath()) && fVersion < 0 && !fMetaDataFilter){
555 // look into list of valid files previously loaded with AliCDBStorage::FillValidFileIds()
556 AliDebug(2,Form("List of files valid for run %d and for path %s was loaded. Looking there!",
557 queryId.GetFirstRun(), queryId.GetPath().Data()));
559 alreadyLoaded = kTRUE;
562 // List of files valid for reqested run was not loaded. Looking directly into CDB
563 AliDebug(2,Form("List of files valid for run %d and for path %s was not loaded. Looking directly into CDB!",
564 queryId.GetFirstRun(), queryId.GetPath().Data()));
567 MakeQueryFilter(queryId.GetFirstRun(), queryId.GetLastRun(), 0, filter);
569 TString pattern = Form("%s/Run*.root", queryId.GetPath().Data());
570 AliDebug(2,Form("pattern: %s", pattern.Data()));
572 TGridResult *res = gGrid->Query(fDBFolder, pattern, filter, "");
574 AliCDBId validFileId;
575 for(int i=0; i<res->GetEntries(); i++){
576 TString filename = res->GetKey(i, "lfn");
577 if(filename == "") continue;
578 if(FilenameToId(filename, validFileId))
579 validFileIds.AddLast(validFileId.Clone());
586 iter = new TIter(&fValidFileIds);
588 iter = new TIter(&validFileIds);
591 TObjArray selectedIds;
592 selectedIds.SetOwner(1);
594 // loop on list of valid Ids to select the right version to get.
595 // According to query and to the selection criteria list, version can be the highest or exact
599 AliCDBPath queryPath = queryId.GetAliCDBPath();
600 while((anIdPtr = dynamic_cast<AliCDBId*> (iter->Next()))){
601 AliCDBPath thisCDBPath = anIdPtr->GetAliCDBPath();
602 if(!(queryPath.Comprises(thisCDBPath)) || pathCopy.GetPath() == thisCDBPath.GetPath()) continue;
603 pathCopy = thisCDBPath;
605 // check the selection criteria list for this query
606 AliCDBId thisId(*anIdPtr);
607 thisId.SetVersion(queryId.GetVersion());
608 if(!thisId.HasVersion()) GetSelection(&thisId);
611 dataId = GetId(fValidFileIds, thisId);
613 dataId = GetId(validFileIds, thisId);
615 if(dataId) selectedIds.Add(dataId);
620 // selectedIds contains the Ids of the files matching all requests of query!
621 // All the objects are now ready to be retrieved
622 iter = new TIter(&selectedIds);
623 while((anIdPtr = dynamic_cast<AliCDBId*> (iter->Next()))){
625 if (!IdToFilename(*anIdPtr, filename)) {
626 AliDebug(2,Form("Bad data ID encountered! Subnormal error!"));
630 AliCDBEntry* anEntry = GetEntryFromFile(filename, anIdPtr);
632 if(anEntry) result->Add(anEntry);
640 //_____________________________________________________________________________
641 Bool_t AliCDBGrid::PutEntry(AliCDBEntry* entry) {
642 // put an AliCDBEntry object into the database
644 AliCDBId& id = entry->GetId();
646 // set version for the entry to be stored
647 if (!PrepareId(id)) return kFALSE;
649 // build filename from entry's id
651 if (!IdToFilename(id, filename)) {
652 AliError("Bad ID encountered! Subnormal error!");
656 TString folderToTag = Form("%s%s",
658 id.GetPath().Data());
660 TDirectory* saveDir = gDirectory;
662 TString fullFilename = Form("/alien%s", filename.Data());
663 // specify SE to filename
664 if (fSE != "default") fullFilename += Form("?se=%s",fSE.Data());
667 TFile *file = TFile::Open(fullFilename,"CREATE");
668 if(!file || !file->IsWritable()){
669 AliError(Form("Can't open file <%s>!", filename.Data()));
670 if(file && !file->IsWritable()) file->Close(); delete file; file=0;
676 //SetTreeToFile(entry, file);
678 entry->SetVersion(id.GetVersion());
680 // write object (key name: "AliCDBEntry")
681 Bool_t result = (file->WriteTObject(entry, "AliCDBEntry") != 0);
682 if (!result) AliError(Form("Can't write entry to file <%s>!", filename.Data()));
685 if (saveDir) saveDir->cd(); else gROOT->cd();
686 file->Close(); delete file; file=0;
690 if(!TagFileId(filename, &id)){
691 AliInfo(Form("CDB tagging failed. Deleting file %s!",filename.Data()));
692 if(!gGrid->Rm(filename.Data()))
693 AliError("Can't delete file!");
697 TagFileMetaData(filename, entry->GetMetaData());
700 AliInfo(Form("CDB object stored into file %s", filename.Data()));
701 AliInfo(Form("Storage Element: %s", fSE.Data()));
704 //_____________________________________________________________________________
705 Bool_t AliCDBGrid::AddTag(TString& folderToTag, const char* tagname){
706 // add "tagname" tag (CDB or CDB_MD) to folder where object will be stored
708 Bool_t result = kTRUE;
709 AliDebug(2, Form("adding %s tag to folder %s", tagname, folderToTag.Data()));
710 TString addTag = Form("addTag %s %s", folderToTag.Data(), tagname);
711 TGridResult *gridres = gGrid->Command(addTag.Data());
712 const char* resCode = gridres->GetKey(0,"__result__"); // '1' if success
713 if(resCode[0] != '1') {
714 AliError(Form("Couldn't add %s tags to folder %s !",
715 tagname, folderToTag.Data()));
722 //_____________________________________________________________________________
723 Bool_t AliCDBGrid::TagFileId(TString& filename, const AliCDBId* id){
724 // tag stored object in CDB table using object Id's parameters
726 TString addTagValue1 = Form("addTagValue %s CDB ", filename.Data());
727 TString addTagValue2 = Form("first_run=%d last_run=%d version=%d ",
731 TString addTagValue3 = Form("path_level_0=\"%s\" path_level_1=\"%s\" path_level_2=\"%s\"",
732 id->GetPathLevel(0).Data(),
733 id->GetPathLevel(1).Data(),
734 id->GetPathLevel(2).Data());
735 TString addTagValue = Form("%s%s%s",
738 addTagValue3.Data());
740 Bool_t result = kFALSE;
741 AliDebug(2, Form("Tagging file. Tag command: %s", addTagValue.Data()));
742 TGridResult* res = gGrid->Command(addTagValue.Data());
743 const char* resCode = res->GetKey(0,"__result__"); // '1' if success
744 if(resCode[0] != '1') {
745 AliError(Form("Couldn't add CDB tag value to file %s !",
749 AliDebug(2, "Object successfully tagged.");
757 //_____________________________________________________________________________
758 Bool_t AliCDBGrid::TagShortLived(TString& filename, Bool_t value){
759 // tag folder with ShortLived tag
761 TString addTagValue = Form("addTagValue %s ShortLived_try value=%d", filename.Data(), value);
763 Bool_t result = kFALSE;
764 AliDebug(2, Form("Tagging file. Tag command: %s", addTagValue.Data()));
765 TGridResult* res = gGrid->Command(addTagValue.Data());
766 const char* resCode = res->GetKey(0,"__result__"); // '1' if success
767 if(resCode[0] != '1') {
768 AliError(Form("Couldn't add ShortLived tag value to file %s !", filename.Data()));
771 AliDebug(2,"Object successfully tagged.");
779 //_____________________________________________________________________________
780 Bool_t AliCDBGrid::TagFileMetaData(TString& filename, const AliCDBMetaData* md){
781 // tag stored object in CDB table using object Id's parameters
783 TString addTagValue1 = Form("addTagValue %s CDB_MD ", filename.Data());
784 TString addTagValue2 = Form("object_classname=\"%s\" responsible=\"%s\" beam_period=%d ",
785 md->GetObjectClassName(),
786 md->GetResponsible(),
787 md->GetBeamPeriod());
788 TString addTagValue3 = Form("aliroot_version=\"%s\" comment=\"%s\"",
789 md->GetAliRootVersion(),
791 TString addTagValue = Form("%s%s%s",
794 addTagValue3.Data());
796 Bool_t result = kFALSE;
797 AliDebug(2, Form("Tagging file. Tag command: %s", addTagValue.Data()));
798 TGridResult* res = gGrid->Command(addTagValue.Data());
799 const char* resCode = res->GetKey(0,"__result__"); // '1' if success
800 if(resCode[0] != '1') {
801 AliWarning(Form("Couldn't add CDB_MD tag value to file %s !",
805 AliDebug(2,"Object successfully tagged.");
811 //_____________________________________________________________________________
812 TList* AliCDBGrid::GetIdListFromFile(const char* fileName){
814 TString turl(fileName);
815 turl.Prepend("/alien" + fDBFolder);
816 turl += "?se="; turl += fSE.Data();
817 TFile *file = TFile::Open(turl);
819 AliError(Form("Can't open selection file <%s>!", turl.Data()));
823 TList *list = new TList();
831 keycycle = "AliCDBId;";
834 id = (AliCDBId*) file->Get(keycycle);
838 file->Close(); delete file; file=0;
845 //_____________________________________________________________________________
846 Bool_t AliCDBGrid::Contains(const char* path) const{
847 // check for path in storage's DBFolder
849 TString initDir(gGrid->Pwd(0));
850 TString dirName(fDBFolder);
851 dirName += path; // dirName = fDBFolder/path
852 Bool_t result=kFALSE;
853 if (gGrid->Cd(dirName,0)) result=kTRUE;
854 gGrid->Cd(initDir.Data(),0);
858 //_____________________________________________________________________________
859 void AliCDBGrid::QueryValidFiles()
861 // Query the CDB for files valid for AliCDBStorage::fRun
862 // fills list fValidFileIds with AliCDBId objects created from file name
865 MakeQueryFilter(fRun, fRun, fMetaDataFilter, filter);
867 TString pattern = Form("%s/Run*", fPathFilter.GetPath().Data());
868 if(fVersion >= 0) pattern += Form("_v%d*", fVersion);
870 AliDebug(2,Form("pattern: %s", pattern.Data()));
872 TGridResult *res = gGrid->Query(fDBFolder, pattern, filter, "");
875 AliError("Grid query failed");
879 AliCDBId validFileId;
880 for(int i=0; i<res->GetEntries(); i++){
881 TString filename = res->GetKey(i, "lfn");
882 if(filename == "") continue;
883 AliDebug(2,Form("Found valid file: %s", filename.Data()));
884 Bool_t result = FilenameToId(filename, validFileId);
886 fValidFileIds.AddLast(validFileId.Clone());
893 //_____________________________________________________________________________
894 void AliCDBGrid::MakeQueryFilter(Int_t firstRun, Int_t lastRun,
895 const AliCDBMetaData* md, TString& result) const
897 // create filter for file query
899 result = Form("CDB:first_run<=%d and CDB:last_run>=%d", firstRun, lastRun);
901 // if(version >= 0) {
902 // result += Form(" and CDB:version=%d", version);
904 // if(pathFilter.GetLevel0() != "*") {
905 // result += Form(" and CDB:path_level_0=\"%s\"", pathFilter.GetLevel0().Data());
907 // if(pathFilter.GetLevel1() != "*") {
908 // result += Form(" and CDB:path_level_1=\"%s\"", pathFilter.GetLevel1().Data());
910 // if(pathFilter.GetLevel2() != "*") {
911 // result += Form(" and CDB:path_level_2=\"%s\"", pathFilter.GetLevel2().Data());
915 if(md->GetObjectClassName()[0] != '\0') {
916 result += Form(" and CDB_MD:object_classname=\"%s\"", md->GetObjectClassName());
918 if(md->GetResponsible()[0] != '\0') {
919 result += Form(" and CDB_MD:responsible=\"%s\"", md->GetResponsible());
921 if(md->GetBeamPeriod() != 0) {
922 result += Form(" and CDB_MD:beam_period=%d", md->GetBeamPeriod());
924 if(md->GetAliRootVersion()[0] != '\0') {
925 result += Form(" and CDB_MD:aliroot_version=\"%s\"", md->GetAliRootVersion());
927 if(md->GetComment()[0] != '\0') {
928 result += Form(" and CDB_MD:comment=\"%s\"", md->GetComment());
931 AliDebug(2, Form("filter: %s",result.Data()));
935 //_____________________________________________________________________________
936 Int_t AliCDBGrid::GetLatestVersion(const char* path, Int_t run){
937 // get last version found in the database valid for run and path
939 AliCDBPath aCDBPath(path);
940 if(!aCDBPath.IsValid() || aCDBPath.IsWildcard()) {
941 AliError(Form("Invalid path in request: %s", path));
944 AliCDBId query(path, run, run, -1, -1);
945 AliCDBId* dataId = 0;
947 // look for file matching query requests (path, runRange, version)
948 if(run == fRun && fPathFilter.Comprises(aCDBPath) && fVersion < 0){
949 // look into list of valid files previously loaded with AliCDBStorage::FillValidFileIds()
950 AliDebug(2, Form("List of files valid for run %d and for path %s was loaded. Looking there!",
952 dataId = GetId(fValidFileIds, query);
953 if (!dataId) return -1;
954 Int_t version = dataId->GetVersion();
959 // List of files valid for reqested run was not loaded. Looking directly into CDB
960 AliDebug(2, Form("List of files valid for run %d and for path %s was not loaded. Looking directly into CDB!",
963 TObjArray validFileIds;
964 validFileIds.SetOwner(1);
967 MakeQueryFilter(run, run, 0, filter);
969 TString pattern = Form("%s/Run*.root", path);
970 AliDebug(2,Form("pattern: %s", pattern.Data()));
972 TGridResult *res = gGrid->Query(fDBFolder, pattern, filter, "");
973 AliCDBId validFileId;
974 for(int i=0; i<res->GetEntries(); i++){
975 TString filename = res->GetKey(i, "lfn");
976 if(filename == "") continue;
977 if(FilenameToId(filename, validFileId))
978 validFileIds.AddLast(validFileId.Clone());
982 dataId = GetId(validFileIds, query);
983 if (!dataId) return -1;
985 Int_t version = dataId->GetVersion();
991 //_____________________________________________________________________________
992 Int_t AliCDBGrid::GetLatestSubVersion(const char* /*path*/, Int_t /*run*/, Int_t /*version*/){
993 // get last subversion found in the database valid for run and path
994 AliError("Objects in GRID storage have no sub version!");
999 /////////////////////////////////////////////////////////////////////////////////////////////////
1001 // AliCDBGrid factory //
1003 /////////////////////////////////////////////////////////////////////////////////////////////////
1005 ClassImp(AliCDBGridFactory)
1007 //_____________________________________________________________________________
1008 Bool_t AliCDBGridFactory::Validate(const char* gridString) {
1009 // check if the string is valid Grid URI
1011 TRegexp gridPattern("^alien://.+$");
1012 TRegexp gridRawPattern("^raw://.+$");
1014 return (TString(gridString).Contains(gridPattern)||TString(gridString).Contains(gridRawPattern));
1017 //_____________________________________________________________________________
1018 AliCDBParam* AliCDBGridFactory::CreateParameter(const char* gridString) {
1019 // create AliCDBGridParam class from the URI string
1021 if (!Validate(gridString)) {
1025 TString buffer(gridString);
1026 Bool_t rawFlag = kFALSE; // flag to say whether we are in the "raw://" case
1028 TString gridUrl = "alien://";
1030 TString dbFolder = "";
1031 TString se = "default";
1032 TString cacheFolder = "";
1033 Bool_t operateDisconnected = kTRUE;
1034 Long64_t cacheSize = (UInt_t) 1024*1024*1024; // 1GB
1035 Long_t cleanupInterval = 0;
1037 TObjArray *arr = buffer.Tokenize('?');
1039 TObjString *str = 0;
1041 while((str = (TObjString*) iter.Next())){
1042 TString entry(str->String());
1043 Int_t indeq = entry.Index('=');
1045 if(entry.BeginsWith("alien://")) { // maybe it's a gridUrl!
1048 } else if(entry.BeginsWith("raw://")) { // maybe it's a gridRawUrl!
1053 AliError(Form("Invalid entry! %s",entry.Data()));
1058 TString key = entry(0,indeq);
1059 TString value = entry(indeq+1,entry.Length()-indeq);
1061 if(key.Contains("grid",TString::kIgnoreCase)) {
1064 else if (key.Contains("user",TString::kIgnoreCase)){
1067 else if (key.Contains("se",TString::kIgnoreCase)){
1070 else if (key.Contains("cacheF",TString::kIgnoreCase)){
1071 cacheFolder = value;
1072 if (!cacheFolder.EndsWith("/"))
1075 else if (key.Contains("folder",TString::kIgnoreCase)){
1078 else if (key.Contains("operateDisc",TString::kIgnoreCase)){
1079 if(value == "kTRUE") {
1080 operateDisconnected = kTRUE;
1081 } else if (value == "kFALSE") {
1082 operateDisconnected = kFALSE;
1083 } else if (value == "0" || value == "1") {
1084 operateDisconnected = (Bool_t) value.Atoi();
1086 AliError(Form("Invalid entry! %s",entry.Data()));
1090 else if (key.Contains("cacheS",TString::kIgnoreCase)){
1091 if(value.IsDigit()) {
1092 cacheSize = value.Atoi();
1094 AliError(Form("Invalid entry! %s",entry.Data()));
1098 else if (key.Contains("cleanupInt",TString::kIgnoreCase)){
1099 if(value.IsDigit()) {
1100 cleanupInterval = value.Atoi();
1102 AliError(Form("Invalid entry! %s",entry.Data()));
1107 AliError(Form("Invalid entry! %s",entry.Data()));
1113 AliDebug(2, Form("gridUrl: %s", gridUrl.Data()));
1114 AliDebug(2, Form("user: %s", user.Data()));
1115 AliDebug(2, Form("dbFolder: %s", dbFolder.Data()));
1116 AliDebug(2, Form("s.e.: %s", se.Data()));
1117 AliDebug(2, Form("local cache folder: %s", cacheFolder.Data()));
1118 AliDebug(2, Form("local cache operate disconnected: %d", operateDisconnected));
1119 AliDebug(2, Form("local cache size: %d", cacheSize));
1120 AliDebug(2, Form("local cache cleanup interval: %d", cleanupInterval));
1122 if(dbFolder == "" && !rawFlag){
1123 AliError("Base folder must be specified!");
1127 return new AliCDBGridParam(gridUrl.Data(), user.Data(),
1128 dbFolder.Data(), se.Data(), cacheFolder.Data(),
1129 operateDisconnected, cacheSize, cleanupInterval);
1132 //_____________________________________________________________________________
1133 AliCDBStorage* AliCDBGridFactory::Create(const AliCDBParam* param) {
1134 // create AliCDBGrid storage instance from parameters
1136 AliCDBGrid *grid = 0;
1137 if (AliCDBGridParam::Class() == param->IsA()) {
1139 const AliCDBGridParam* gridParam = (const AliCDBGridParam*) param;
1140 grid = new AliCDBGrid(gridParam->GridUrl().Data(),
1141 gridParam->GetUser().Data(),
1142 gridParam->GetDBFolder().Data(),
1143 gridParam->GetSE().Data(),
1144 gridParam->GetCacheFolder().Data(),
1145 gridParam->GetOperateDisconnected(),
1146 gridParam->GetCacheSize(),
1147 gridParam->GetCleanupInterval());
1151 if(!gGrid && grid) {
1152 delete grid; grid=0;
1158 /////////////////////////////////////////////////////////////////////////////////////////////////
1160 // AliCDBGrid Parameter class // //
1162 /////////////////////////////////////////////////////////////////////////////////////////////////
1164 ClassImp(AliCDBGridParam)
1166 //_____________________________________________________________________________
1167 AliCDBGridParam::AliCDBGridParam():
1174 fOperateDisconnected(),
1179 // default constructor
1183 //_____________________________________________________________________________
1184 AliCDBGridParam::AliCDBGridParam(const char* gridUrl, const char* user, const char* dbFolder,
1185 const char* se, const char* cacheFolder, Bool_t operateDisconnected,
1186 Long64_t cacheSize, Long_t cleanupInterval):
1190 fDBFolder(dbFolder),
1192 fCacheFolder(cacheFolder),
1193 fOperateDisconnected(operateDisconnected),
1194 fCacheSize(cacheSize),
1195 fCleanupInterval(cleanupInterval)
1201 TString uri = Form("%s?User=%s?DBFolder=%s?SE=%s?CacheFolder=%s"
1202 "?OperateDisconnected=%d?CacheSize=%d?CleanupInterval=%d",
1203 fGridUrl.Data(), fUser.Data(),
1204 fDBFolder.Data(), fSE.Data(), fCacheFolder.Data(),
1205 fOperateDisconnected, fCacheSize, fCleanupInterval);
1207 AliDebug(2,Form("uri = %s", uri.Data()));
1211 //_____________________________________________________________________________
1212 AliCDBGridParam::~AliCDBGridParam() {
1217 //_____________________________________________________________________________
1218 AliCDBParam* AliCDBGridParam::CloneParam() const {
1221 return new AliCDBGridParam(fGridUrl.Data(), fUser.Data(),
1222 fDBFolder.Data(), fSE.Data(), fCacheFolder.Data(),
1223 fOperateDisconnected, fCacheSize, fCleanupInterval);
1226 //_____________________________________________________________________________
1227 ULong_t AliCDBGridParam::Hash() const {
1228 // return Hash function
1230 return fGridUrl.Hash()+fUser.Hash()+fDBFolder.Hash()+fSE.Hash()+fCacheFolder.Hash();
1233 //_____________________________________________________________________________
1234 Bool_t AliCDBGridParam::IsEqual(const TObject* obj) const {
1235 // check if this object is equal to AliCDBParam obj
1241 if (AliCDBGridParam::Class() != obj->IsA()) {
1245 AliCDBGridParam* other = (AliCDBGridParam*) obj;
1247 if(fGridUrl != other->fGridUrl) return kFALSE;
1248 if(fUser != other->fUser) return kFALSE;
1249 if(fDBFolder != other->fDBFolder) return kFALSE;
1250 if(fSE != other->fSE) return kFALSE;
1251 if(fCacheFolder != other->fCacheFolder) return kFALSE;
1252 if(fOperateDisconnected != other->fOperateDisconnected) return kFALSE;
1253 if(fCacheSize != other->fCacheSize) return kFALSE;
1254 if(fCleanupInterval != other->fCleanupInterval) return kFALSE;