1 /**************************************************************************
2 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
4 * Author: The ALICE Off-line Project. *
5 * Contributors are mentioned in the code where appropriate. *
7 * Permission to use, copy, modify and distribute this software and its *
8 * documentation strictly for non-commercial purposes is hereby granted *
9 * without fee, provided that the above copyright notice appears in all *
10 * copies and that both the copyright notice and this permission notice *
11 * appear in the supporting documentation. The authors make no claims *
12 * about the suitability of this software for any purpose. It is *
13 * provided "as is" without express or implied warranty. *
14 **************************************************************************/
16 /////////////////////////////////////////////////////////////////////////////////////////////////
19 // access class to a DataBase in an AliEn storage //
21 /////////////////////////////////////////////////////////////////////////////////////////////////
25 #include <TGridResult.h>
30 #include <TObjArray.h>
31 #include <TObjString.h>
36 #include "AliCDBEntry.h"
37 #include "AliCDBGrid.h"
38 #include "AliCDBManager.h"
43 //_____________________________________________________________________________
44 AliCDBGrid::AliCDBGrid(const char *gridUrl, const char *user, const char *dbFolder,
45 const char *se, const char* cacheFolder, Bool_t operateDisconnected,
46 Long64_t cacheSize, Long_t cleanupInterval) :
53 fCacheFolder(cacheFolder),
54 fOperateDisconnected(operateDisconnected),
55 fCacheSize(cacheSize),
56 fCleanupInterval(cleanupInterval)
60 // if the same Grid is alreay active, skip connection
61 if (!gGrid || fGridUrl != gGrid->GridUrl()
62 || (( fUser != "" ) && ( fUser != gGrid->GetUser() )) ) {
63 // connection to the Grid
64 AliInfo("Connection to the Grid...");
66 AliInfo(Form("gGrid = %p; fGridUrl = %s; gGrid->GridUrl() = %s",gGrid,fGridUrl.Data(), gGrid->GridUrl()));
67 AliInfo(Form("fUser = %s; gGrid->GetUser() = %s",fUser.Data(), gGrid->GetUser()));
69 TGrid::Connect(fGridUrl.Data(),fUser.Data());
73 AliError("Connection failed!");
77 TString initDir(gGrid->Pwd(0));
78 if (fDBFolder[0] != '/') {
79 fDBFolder.Prepend(initDir);
82 // check DBFolder: trying to cd to DBFolder; if it does not exist, create it
83 if(!gGrid->Cd(fDBFolder.Data(),0)){
84 AliDebug(2,Form("Creating new folder <%s> ...",fDBFolder.Data()));
85 TGridResult* res = gGrid->Command(Form("mkdir -p %s",fDBFolder.Data()));
86 TString result = res->GetKey(0,"__result__");
88 AliFatal(Form("Cannot create folder <%s> !",fDBFolder.Data()));
92 AliDebug(2,Form("Folder <%s> found",fDBFolder.Data()));
95 // removes any '/' at the end of path, then append one '/'
96 while(fDBFolder.EndsWith("/")) fDBFolder.Remove(fDBFolder.Last('/'));
100 fBaseFolder = fDBFolder;
104 // Check if local cache folder is already defined
105 TString origCache(TFile::GetCacheFileDir());
106 if(fCacheFolder.Length() > 0) {
107 if(origCache.Length() == 0) {
108 AliInfo(Form("Setting local cache to: %s", fCacheFolder.Data()));
109 } else if(fCacheFolder != origCache) {
110 AliWarning(Form("Local cache folder was already defined, changing it to: %s",
111 fCacheFolder.Data()));
114 // default settings are: operateDisconnected=kTRUE, forceCacheread = kFALSE
115 if(!TFile::SetCacheFileDir(fCacheFolder.Data(), fOperateDisconnected)) {
116 AliError(Form("Could not set cache folder %s !", fCacheFolder.Data()));
119 // reset fCacheFolder because the function may have
120 // slightly changed the folder name (e.g. '/' added)
121 fCacheFolder = TFile::GetCacheFileDir();
124 // default settings are: cacheSize=1GB, cleanupInterval = 0
125 if(!TFile::ShrinkCacheFileDir(fCacheSize, fCleanupInterval)) {
126 AliError(Form("Could not set following values "
127 "to ShrinkCacheFileDir: cacheSize = %lld, cleanupInterval = %ld !",
128 fCacheSize, fCleanupInterval));
132 // return to the initial directory
133 gGrid->Cd(initDir.Data(),0);
135 fNretry = 3; // default
136 fInitRetrySeconds = 5; // default
139 //_____________________________________________________________________________
140 AliCDBGrid::~AliCDBGrid() {
142 delete gGrid; gGrid=0;
146 //_____________________________________________________________________________
147 Bool_t AliCDBGrid::FilenameToId(TString& filename, AliCDBId& id) {
148 // build AliCDBId from full path filename (fDBFolder/path/Run#x_#y_v#z_s0.root)
150 if(filename.Contains(fDBFolder)){
151 filename = filename(fDBFolder.Length(),filename.Length()-fDBFolder.Length());
154 TString idPath = filename(0,filename.Last('/'));
156 if(!id.IsValid()) return kFALSE;
158 filename=filename(idPath.Length()+1,filename.Length()-idPath.Length());
161 // valid filename: Run#firstRun_#lastRun_v#version_s0.root
162 TRegexp keyPattern("^Run[0-9]+_[0-9]+_v[0-9]+_s0.root$");
163 keyPattern.Index(filename, &mSize);
166 // TODO backward compatibility ... maybe remove later!
168 TRegexp oldKeyPattern("^Run[0-9]+_[0-9]+_v[0-9]+.root$");
169 oldKeyPattern.Index(filename, &oldmSize);
171 AliDebug(2,Form("Bad filename <%s>.", filename.Data()));
174 AliDebug(2,Form("Old filename format <%s>.", filename.Data()));
175 id.SetSubVersion(-11); // TODO trick to ensure backward compatibility
179 id.SetSubVersion(-1); // TODO trick to ensure backward compatibility
182 filename.Resize(filename.Length() - sizeof(".root") + 1);
184 TObjArray* strArray = (TObjArray*) filename.Tokenize("_");
186 TString firstRunString(((TObjString*) strArray->At(0))->GetString());
187 id.SetFirstRun(atoi(firstRunString.Data() + 3));
188 id.SetLastRun(atoi(((TObjString*) strArray->At(1))->GetString()));
190 TString verString(((TObjString*) strArray->At(2))->GetString());
191 id.SetVersion(atoi(verString.Data() + 1));
198 //_____________________________________________________________________________
199 Bool_t AliCDBGrid::IdToFilename(const AliCDBId& id, TString& filename) const {
200 // build file name from AliCDBId (path, run range, version) and fDBFolder
202 if (!id.GetAliCDBRunRange().IsValid()) {
203 AliDebug(2,Form("Invalid run range <%d, %d>.",
204 id.GetFirstRun(), id.GetLastRun()));
208 if (id.GetVersion() < 0) {
209 AliDebug(2,Form("Invalid version <%d>.", id.GetVersion()));
213 filename = Form("Run%d_%d_v%d",
218 if (id.GetSubVersion() != -11) filename += "_s0"; // TODO to ensure backward compatibility
221 filename.Prepend(fDBFolder + id.GetPath() + '/');
226 //_____________________________________________________________________________
227 void AliCDBGrid::SetRetry(Int_t nretry, Int_t initsec) {
229 // Function to set the exponential retry for putting entries in the OCDB
231 AliWarning("WARNING!!! You are changing the exponential retry times and delay: this function should be used by experts!");
233 fInitRetrySeconds = initsec;
234 AliDebug(2,Form("fNretry = %d, fInitRetrySeconds = %d", fNretry, fInitRetrySeconds));
238 //_____________________________________________________________________________
239 Bool_t AliCDBGrid::PrepareId(AliCDBId& id) {
240 // prepare id (version) of the object that will be stored (called by PutEntry)
242 TString initDir(gGrid->Pwd(0));
244 TString dirName(fDBFolder);
246 Bool_t dirExist=kFALSE;
250 // go to the path; if directory does not exist, create it
251 for(int i=0;i<3;i++){
252 //TString cmd("find -d ");
253 //cmd += Form("%s ",dirName);
255 //gGrid->Command(cmd.Data());
256 dirName+=Form("%s/",id.GetPathLevel(i).Data());
257 dirExist=gGrid->Cd(dirName,0);
259 AliDebug(2,Form("Creating new folder <%s> ...",dirName.Data()));
260 if(!gGrid->Mkdir(dirName,"",0)){
261 AliError(Form("Cannot create directory <%s> !",dirName.Data()));
262 gGrid->Cd(initDir.Data());
266 // if folders are new add tags to them
268 // TODO Currently disabled
269 // add short lived tag!
270 // AliInfo("Tagging level 1 folder with \"ShortLived\" tag");
271 // if(!AddTag(dirName,"ShortLived_try")){
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()));
280 AliDebug(2,"Tagging level 2 folder with \"CDB\" and \"CDB_MD\" tag");
281 if(!AddTag(dirName,"CDB")){
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()));
288 if(!AddTag(dirName,"CDB_MD")){
289 AliError(Form("Could not tag folder %s !", dirName.Data()));
290 if(!gGrid->Rmdir(dirName.Data())){
291 AliError(Form("Unexpected: could not remove %s directory!", dirName.Data()));
296 // TODO Currently disabled
297 // add short lived tag!
298 // TString path=id.GetPath();
299 // if(AliCDBManager::Instance()->IsShortLived(path.Data())) {
300 // AliInfo(Form("Tagging %s as short lived", dirName.Data()));
301 // if(!TagShortLived(dirName, kTRUE)){
302 // AliError(Form("Could not tag folder %s !", dirName.Data()));
303 // if(!gGrid->Rmdir(dirName.Data())){
304 // AliError(Form("Unexpected: could not remove %s directory!", dirName.Data()));
309 // AliInfo(Form("Tagging %s as long lived", dirName.Data()));
310 // if(!TagShortLived(dirName, kFALSE)){
311 // AliError(Form("Could not tag folder %s !", dirName.Data()));
312 // if(!gGrid->Rmdir(dirName.Data())){
313 // AliError(Form("Unexpected: could not remove %s directory!", dirName.Data()));
321 gGrid->Cd(initDir,0);
324 AliCDBId anId; // the id got from filename
325 AliCDBRunRange lastRunRange(-1,-1); // highest runRange found
326 Int_t lastVersion=0; // highest version found
328 TGridResult *res = gGrid->Ls(dirName);
330 //loop on the files in the directory, look for highest version
331 for(int i=0; i < res->GetEntries(); i++){
332 filename=res->GetFileNamePath(i);
333 if (!FilenameToId(filename, anId)) continue;
334 if (anId.GetAliCDBRunRange().Overlaps(id.GetAliCDBRunRange()) && anId.GetVersion() > lastVersion) {
335 lastVersion = anId.GetVersion();
336 lastRunRange = anId.GetAliCDBRunRange();
342 // GRP entries with explicitly set version escape default incremental versioning
343 if(id.GetPath().Contains("GRP") && id.HasVersion() && lastVersion!=0)
345 AliDebug(5,Form("Entry %s won't be put in the destination OCDB", id.ToString().Data()));
349 id.SetVersion(lastVersion + 1);
352 TString lastStorage = id.GetLastStorage();
353 if(lastStorage.Contains(TString("new"), TString::kIgnoreCase) && id.GetVersion() > 1 ){
354 AliDebug(2, Form("A NEW object is being stored with version %d",
356 AliDebug(2, Form("and it will hide previously stored object with version %d!",
360 if(!lastRunRange.IsAnyRange() && !(lastRunRange.IsEqual(&id.GetAliCDBRunRange())))
361 AliWarning(Form("Run range modified w.r.t. previous version (Run%d_%d_v%d)",
362 lastRunRange.GetFirstRun(), lastRunRange.GetLastRun(), id.GetVersion()));
367 //_____________________________________________________________________________
368 AliCDBId* AliCDBGrid::GetId(const TObjArray& validFileIds, const AliCDBId& query) {
369 // look for the Id that matches query's requests (highest or exact version)
371 if(validFileIds.GetEntriesFast() < 1)
374 TIter iter(&validFileIds);
379 while((anIdPtr = dynamic_cast<AliCDBId*> (iter.Next()))){
380 if(anIdPtr->GetPath() != query.GetPath()) continue;
382 //if(!CheckVersion(query, anIdPtr, result)) return NULL;
384 if (!query.HasVersion()){ // look for highest version
385 if(result && result->GetVersion() > anIdPtr->GetVersion()) continue;
386 if(result && result->GetVersion() == anIdPtr->GetVersion()) {
387 AliError(Form("More than one object valid for run %d, version %d!",
388 query.GetFirstRun(), anIdPtr->GetVersion()));
392 } else { // look for specified version
393 if(query.GetVersion() != anIdPtr->GetVersion()) continue;
394 if(result && result->GetVersion() == anIdPtr->GetVersion()){
395 AliError(Form("More than one object valid for run %d, version %d!",
396 query.GetFirstRun(), anIdPtr->GetVersion()));
404 if (!result) return NULL;
406 return dynamic_cast<AliCDBId*> (result->Clone());
409 //_____________________________________________________________________________
410 AliCDBId* AliCDBGrid::GetEntryId(const AliCDBId& queryId) {
411 // get AliCDBId from the database
412 // User must delete returned object
416 AliCDBId selectedId(queryId);
417 if (!selectedId.HasVersion()) {
418 // if version is not specified, first check the selection criteria list
419 GetSelection(&selectedId);
422 TObjArray validFileIds;
423 validFileIds.SetOwner(1);
425 // look for file matching query requests (path, runRange, version)
426 if(selectedId.GetFirstRun() == fRun && fPathFilter.Comprises(selectedId.GetAliCDBPath()) &&
427 fVersion == selectedId.GetVersion() && !fMetaDataFilter){
428 // look into list of valid files previously loaded with AliCDBStorage::FillValidFileIds()
429 AliDebug(2, Form("List of files valid for run %d was loaded. Looking there for fileids valid for path %s!",
430 selectedId.GetFirstRun(), selectedId.GetPath().Data()));
431 dataId = GetId(fValidFileIds, selectedId);
434 // List of files valid for reqested run was not loaded. Looking directly into CDB
435 AliDebug(2, Form("List of files valid for run %d and version %d was not loaded. Looking directly into CDB for fileids valid for path %s!",
436 selectedId.GetFirstRun(), selectedId.GetVersion(), selectedId.GetPath().Data()));
439 MakeQueryFilter(selectedId.GetFirstRun(), selectedId.GetLastRun(), 0, filter);
441 TString pattern = ".root";
442 TString optionQuery = "-y -m";
443 if(selectedId.GetVersion() >= 0) {
444 pattern.Prepend(Form("_v%d_s0",selectedId.GetVersion()));
448 TString folderCopy(Form("%s%s/Run",fDBFolder.Data(),selectedId.GetPath().Data()));
450 if (optionQuery.Contains("-y")){
451 AliInfo("Only latest version will be returned");
454 AliDebug(2,Form("** fDBFolder = %s, pattern = %s, filter = %s",folderCopy.Data(), pattern.Data(), filter.Data()));
455 TGridResult *res = gGrid->Query(folderCopy, pattern, filter, optionQuery.Data());
457 AliCDBId validFileId;
458 for(int i=0; i<res->GetEntries(); i++){
459 TString filename = res->GetKey(i, "lfn");
460 if(filename == "") continue;
461 if(FilenameToId(filename, validFileId))
462 validFileIds.AddLast(validFileId.Clone());
466 return 0; // this should be only in case of file catalogue glitch
469 dataId = GetId(validFileIds, selectedId);
475 //_____________________________________________________________________________
476 AliCDBEntry* AliCDBGrid::GetEntry(const AliCDBId& queryId) {
477 // get AliCDBEntry from the database
479 AliCDBId* dataId = GetEntryId(queryId);
482 AliFatal(TString::Format("No valid CDB object found! request was: %s", queryId.ToString().Data()));
487 if (!IdToFilename(*dataId, filename)) {
488 AliDebug(2,Form("Bad data ID encountered! Subnormal error!"));
490 AliFatal(TString::Format("No valid CDB object found! request was: %s", queryId.ToString().Data()));
493 AliCDBEntry* anEntry = GetEntryFromFile(filename, dataId);
497 AliFatal(TString::Format("No valid CDB object found! request was: %s", queryId.ToString().Data()));
502 //_____________________________________________________________________________
503 AliCDBEntry* AliCDBGrid::GetEntryFromFile(TString& filename, AliCDBId* dataId){
504 // Get AliCBEntry object from file "filename"
506 AliDebug(2,Form("Opening file: %s",filename.Data()));
508 filename.Prepend("/alien");
510 // if option="CACHEREAD" TFile will use the local caching facility!
511 TString option="READ";
512 if(fCacheFolder != ""){
514 // Check if local cache folder was changed in the meanwhile
515 TString origCache(TFile::GetCacheFileDir());
516 if(fCacheFolder != origCache) {
517 AliWarning(Form("Local cache folder has been overwritten!! fCacheFolder = %s origCache = %s",
518 fCacheFolder.Data(), origCache.Data()));
519 TFile::SetCacheFileDir(fCacheFolder.Data(), fOperateDisconnected);
520 TFile::ShrinkCacheFileDir(fCacheSize, fCleanupInterval);
523 option.Prepend("CACHE");
526 AliDebug(2, Form("Option: %s", option.Data()));
528 TFile *file = TFile::Open(filename, option);
530 AliDebug(2,Form("Can't open file <%s>!", filename.Data()));
534 // get the only AliCDBEntry object from the file
535 // the object in the file is an AliCDBEntry entry named "AliCDBEntry"
537 AliCDBEntry* anEntry = dynamic_cast<AliCDBEntry*> (file->Get("AliCDBEntry"));
540 AliDebug(2,Form("Bad storage data: file does not contain an AliCDBEntry object!"));
545 // The object's Id is not reset during storage
546 // If object's Id runRange or version do not match with filename,
547 // it means that someone renamed file by hand. In this case a warning msg is issued.
550 AliCDBId entryId = anEntry->GetId();
551 Int_t tmpSubVersion = dataId->GetSubVersion();
552 dataId->SetSubVersion(entryId.GetSubVersion()); // otherwise filename and id may mismatch
553 if(!entryId.IsEqual(dataId)){
554 AliWarning(Form("Mismatch between file name and object's Id!"));
555 AliWarning(Form("File name: %s", dataId->ToString().Data()));
556 AliWarning(Form("Object's Id: %s", entryId.ToString().Data()));
558 dataId->SetSubVersion(tmpSubVersion);
561 anEntry->SetLastStorage("grid");
563 // Check whether entry contains a TTree. In case load the tree in memory!
564 LoadTreeFromFile(anEntry);
566 // close file, return retieved entry
567 file->Close(); delete file; file=0;
572 //_____________________________________________________________________________
573 TList* AliCDBGrid::GetEntries(const AliCDBId& queryId) {
574 // multiple request (AliCDBStorage::GetAll)
576 TList* result = new TList();
579 TObjArray validFileIds;
580 validFileIds.SetOwner(1);
582 Bool_t alreadyLoaded = kFALSE;
584 // look for file matching query requests (path, runRange)
585 if(queryId.GetFirstRun() == fRun &&
586 fPathFilter.Comprises(queryId.GetAliCDBPath()) && fVersion < 0 && !fMetaDataFilter){
587 // look into list of valid files previously loaded with AliCDBStorage::FillValidFileIds()
588 AliDebug(2,Form("List of files valid for run %d and for path %s was loaded. Looking there!",
589 queryId.GetFirstRun(), queryId.GetPath().Data()));
591 alreadyLoaded = kTRUE;
594 // List of files valid for reqested run was not loaded. Looking directly into CDB
595 AliDebug(2,Form("List of files valid for run %d and for path %s was not loaded. Looking directly into CDB!",
596 queryId.GetFirstRun(), queryId.GetPath().Data()));
599 MakeQueryFilter(queryId.GetFirstRun(), queryId.GetLastRun(), 0, filter);
601 TString path = queryId.GetPath();
603 TString pattern = "Run*.root";
604 TString optionQuery = "-y";
606 TString addFolder = "";
607 if (!path.Contains("*")){
608 if (!path.BeginsWith("/")) addFolder += "/";
612 if (path.BeginsWith("/")) path.Remove(0,1);
613 if (path.EndsWith("/")) path.Remove(path.Length()-1,1);
614 TObjArray* tokenArr = path.Tokenize("/");
615 if (tokenArr->GetEntries() != 3) {
616 AliError("Not a 3 level path! Keeping old query...");
617 pattern.Prepend(path+"/");
620 TString str0 = ((TObjString*)tokenArr->At(0))->String();
621 TString str1 = ((TObjString*)tokenArr->At(1))->String();
622 TString str2 = ((TObjString*)tokenArr->At(2))->String();
623 if (str0 != "*" && str1 != "*" && str2 == "*"){
624 // e.g. "ITS/Calib/*"
625 addFolder = "/"+str0+"/"+str1;
627 else if (str0 != "*" && str1 == "*" && str2 == "*"){
629 addFolder = "/"+str0;
631 else if (str0 == "*" && str1 == "*" && str2 == "*"){
633 // do nothing: addFolder is already an empty string;
636 // e.g. "ITS/*/RecoParam"
637 pattern.Prepend(path+"/");
640 delete tokenArr; tokenArr=0;
643 TString folderCopy(Form("%s%s",fDBFolder.Data(),addFolder.Data()));
645 AliDebug(2,Form("fDBFolder = %s, pattern = %s, filter = %s",folderCopy.Data(), pattern.Data(), filter.Data()));
647 TGridResult *res = gGrid->Query(folderCopy, pattern, filter, optionQuery.Data());
650 AliError("Grid query failed");
654 AliCDBId validFileId;
655 for(int i=0; i<res->GetEntries(); i++){
656 TString filename = res->GetKey(i, "lfn");
657 if(filename == "") continue;
658 if(FilenameToId(filename, validFileId))
659 validFileIds.AddLast(validFileId.Clone());
666 iter = new TIter(&fValidFileIds);
668 iter = new TIter(&validFileIds);
671 TObjArray selectedIds;
672 selectedIds.SetOwner(1);
674 // loop on list of valid Ids to select the right version to get.
675 // According to query and to the selection criteria list, version can be the highest or exact
679 AliCDBPath queryPath = queryId.GetAliCDBPath();
680 while((anIdPtr = dynamic_cast<AliCDBId*> (iter->Next()))){
681 AliCDBPath thisCDBPath = anIdPtr->GetAliCDBPath();
682 if(!(queryPath.Comprises(thisCDBPath)) || pathCopy.GetPath() == thisCDBPath.GetPath()) continue;
683 pathCopy = thisCDBPath;
685 // check the selection criteria list for this query
686 AliCDBId thisId(*anIdPtr);
687 thisId.SetVersion(queryId.GetVersion());
688 if(!thisId.HasVersion()) GetSelection(&thisId);
691 dataId = GetId(fValidFileIds, thisId);
693 dataId = GetId(validFileIds, thisId);
695 if(dataId) selectedIds.Add(dataId);
700 // selectedIds contains the Ids of the files matching all requests of query!
701 // All the objects are now ready to be retrieved
702 iter = new TIter(&selectedIds);
703 while((anIdPtr = dynamic_cast<AliCDBId*> (iter->Next()))){
705 if (!IdToFilename(*anIdPtr, filename)) {
706 AliDebug(2,Form("Bad data ID encountered! Subnormal error!"));
710 AliCDBEntry* anEntry = GetEntryFromFile(filename, anIdPtr);
712 if(anEntry) result->Add(anEntry);
720 //_____________________________________________________________________________
721 Bool_t AliCDBGrid::PutEntry(AliCDBEntry* entry, const char* mirrors) {
722 // put an AliCDBEntry object into the database
724 AliCDBId& id = entry->GetId();
726 // set version for the entry to be stored
727 if (!PrepareId(id)) return kFALSE;
729 // build filename from entry's id
731 if (!IdToFilename(id, filename)) {
732 AliError("Bad ID encountered! Subnormal error!");
736 TString folderToTag = Form("%s%s",
738 id.GetPath().Data());
740 TDirectory* saveDir = gDirectory;
742 TString fullFilename = Form("/alien%s", filename.Data());
743 TString seMirrors(mirrors);
744 if(seMirrors.IsNull() || seMirrors.IsWhitespace()) seMirrors=GetMirrorSEs();
745 // specify SE to filename
746 // if a list of SEs was passed to this method or set via SetMirrorSEs, set the first as SE for opening the file.
747 // The other SEs will be used in cascade in case of failure in opening the file.
748 // The remaining SEs will be used to create replicas.
749 TObjArray *arraySEs = seMirrors.Tokenize(',');
750 Int_t nSEs = arraySEs->GetEntries();
751 Int_t remainingSEs = 1;
753 if (fSE != "default") fullFilename += Form("?se=%s",fSE.Data());
760 AliDebug(2, Form("fNretry = %d, fInitRetrySeconds = %d",fNretry,fInitRetrySeconds));
761 TString targetSE("");
763 Bool_t result = kFALSE;
764 Bool_t reOpenResult = kFALSE;
765 Int_t reOpenAttempts=0;
766 while( !reOpenResult && reOpenAttempts<2){ //loop to check the file after closing it, to catch the unlikely but possible case when the file
767 // is cleaned up by alien just before closing as a consequence of a network disconnection while writing
769 while( !file && remainingSEs>0){
771 TObjString *target = (TObjString*) arraySEs->At(nSEs-remainingSEs);
772 targetSE=target->String();
773 if ( !(targetSE.BeginsWith("ALICE::") && targetSE.CountChar(':')==4) ) {
774 AliError(Form("\"%s\" is an invalid storage element identifier.",targetSE.Data()));
777 if(fullFilename.Contains('?')) fullFilename.Remove(fullFilename.Last('?'));
778 fullFilename += Form("?se=%s",targetSE.Data());
780 Int_t remainingAttempts=fNretry;
781 Int_t nsleep = fInitRetrySeconds; // number of seconds between attempts. We let it increase exponentially
782 AliDebug(2, Form("Uploading file into SE #%d: %s",nSEs-remainingSEs+1,targetSE.Data()));
783 while(remainingAttempts > 0) {
784 AliDebug(2, Form("Uploading file into OCDB at %s - Attempt #%d",targetSE.Data(),fNretry-remainingAttempts+1));
786 file = TFile::Open(fullFilename,"CREATE");
787 if(!file || !file->IsWritable()){
788 if(file) file->Close(); delete file; file=0; // file is not writable
789 TString message(TString::Format("Attempt %d failed.",fNretry-remainingAttempts));
790 if(remainingAttempts>0) {
791 message += " Sleeping for "; message += nsleep; message += " seconds";
793 if(remainingSEs>0) message += " Trying to upload at next SE";
795 AliDebug(2, message.Data());
796 if(remainingAttempts>0) sleep(nsleep);
800 nsleep*=fInitRetrySeconds;
805 AliError(Form("All %d attempts have failed on all %d SEs. Returning...",fNretry,nSEs));
811 //SetTreeToFile(entry, file);
812 entry->SetVersion(id.GetVersion());
814 // write object (key name: "AliCDBEntry")
815 result = (file->WriteTObject(entry, "AliCDBEntry") != 0);
816 if (!result) AliError(Form("Can't write entry to file <%s>!", filename.Data()));
821 AliDebug(2, Form("Reopening file %s for checking its correctness",fullFilename.Data()));
822 TFile* ffile = TFile::Open(fullFilename.Data(),"READ");
824 reOpenResult = kFALSE;
825 AliInfo(Form("The file %s was closed successfully but cannot be reopened. Trying now to regenerate it (regeneration attempt number %d)",
826 fullFilename.Data(),++reOpenAttempts));
828 AliDebug(2, Form("Removing file %s", filename.Data()));
829 if(!gGrid->Rm(filename.Data()))
830 AliError("Can't delete file!");
833 reOpenResult = kTRUE;
836 delete ffile; ffile=0;
840 if (saveDir) saveDir->cd(); else gROOT->cd();
843 if(result && reOpenResult) {
845 if(!TagFileId(filename, &id)){
846 AliInfo(Form("CDB tagging failed. Deleting file %s!",filename.Data()));
847 if(!gGrid->Rm(filename.Data()))
848 AliError("Can't delete file!");
852 TagFileMetaData(filename, entry->GetMetaData());
854 AliError("The file could not be opend or the object could not be written");
855 if(!gGrid->Rm(filename.Data()))
856 AliError("Can't delete file!");
860 AliInfo(Form("CDB object stored into file %s", filename.Data()));
862 AliInfo(Form("Storage Element: %s", fSE.Data()));
864 AliInfo(Form("Storage Element: %s", targetSE.Data()));
866 //In case of other SEs specified by the user, mirror the file to the remaining SEs
867 for(Int_t i=0; i<nSEs; i++){
868 if(i==nSEs-remainingSEs-1) continue; // skip mirroring to the SE where the file was saved
869 TString mirrorCmd("mirror ");
870 mirrorCmd += filename;
872 TObjString *target = (TObjString*) arraySEs->At(i);
873 TString mirrorSE(target->String());
874 mirrorCmd += mirrorSE;
875 AliDebug(5,Form("mirror command: \"%s\"",mirrorCmd.Data()));
876 AliInfo(Form("Mirroring to storage element: %s", mirrorSE.Data()));
877 gGrid->Command(mirrorCmd.Data());
879 arraySEs->Delete(); arraySEs=0;
884 //_____________________________________________________________________________
885 Bool_t AliCDBGrid::AddTag(TString& folderToTag, const char* tagname){
886 // add "tagname" tag (CDB or CDB_MD) to folder where object will be stored
888 Bool_t result = kTRUE;
889 AliDebug(2, Form("adding %s tag to folder %s", tagname, folderToTag.Data()));
890 TString addTag = Form("addTag %s %s", folderToTag.Data(), tagname);
891 TGridResult *gridres = gGrid->Command(addTag.Data());
892 const char* resCode = gridres->GetKey(0,"__result__"); // '1' if success
893 if(resCode[0] != '1') {
894 AliError(Form("Couldn't add %s tags to folder %s !",
895 tagname, folderToTag.Data()));
902 //_____________________________________________________________________________
903 Bool_t AliCDBGrid::TagFileId(TString& filename, const AliCDBId* id){
904 // tag stored object in CDB table using object Id's parameters
907 TString dirname(filename);
908 Int_t dirNumber = gGrid->Mkdir(dirname.Remove(dirname.Last('/')),"-d");
910 TString addTagValue1 = Form("addTagValue %s CDB ", filename.Data());
911 TString addTagValue2 = Form("first_run=%d last_run=%d version=%d ",
915 TString addTagValue3 = Form("path_level_0=\"%s\" path_level_1=\"%s\" path_level_2=\"%s\" ",
916 id->GetPathLevel(0).Data(),
917 id->GetPathLevel(1).Data(),
918 id->GetPathLevel(2).Data());
919 //TString addTagValue4 = Form("version_path=\"%s\" dir_number=%d",Form("%d_%s",id->GetVersion(),filename.Data()),dirNumber);
920 TString addTagValue4 = Form("version_path=\"%09d%s\" dir_number=%d",id->GetVersion(),filename.Data(),dirNumber);
921 TString addTagValue = Form("%s%s%s%s",
925 addTagValue4.Data());
927 Bool_t result = kFALSE;
928 AliDebug(2, Form("Tagging file. Tag command: %s", addTagValue.Data()));
929 TGridResult* res = gGrid->Command(addTagValue.Data());
930 const char* resCode = res->GetKey(0,"__result__"); // '1' if success
931 if(resCode[0] != '1') {
932 AliError(Form("Couldn't add CDB tag value to file %s !",
936 AliDebug(2, "Object successfully tagged.");
944 //_____________________________________________________________________________
945 Bool_t AliCDBGrid::TagShortLived(TString& filename, Bool_t value){
946 // tag folder with ShortLived tag
948 TString addTagValue = Form("addTagValue %s ShortLived_try value=%d", filename.Data(), value);
950 Bool_t result = kFALSE;
951 AliDebug(2, Form("Tagging file. Tag command: %s", addTagValue.Data()));
952 TGridResult* res = gGrid->Command(addTagValue.Data());
953 const char* resCode = res->GetKey(0,"__result__"); // '1' if success
954 if(resCode[0] != '1') {
955 AliError(Form("Couldn't add ShortLived tag value to file %s !", filename.Data()));
958 AliDebug(2,"Object successfully tagged.");
966 //_____________________________________________________________________________
967 Bool_t AliCDBGrid::TagFileMetaData(TString& filename, const AliCDBMetaData* md){
968 // tag stored object in CDB table using object Id's parameters
970 TString addTagValue1 = Form("addTagValue %s CDB_MD ", filename.Data());
971 TString addTagValue2 = Form("object_classname=\"%s\" responsible=\"%s\" beam_period=%d ",
972 md->GetObjectClassName(),
973 md->GetResponsible(),
974 md->GetBeamPeriod());
975 TString addTagValue3 = Form("aliroot_version=\"%s\" comment=\"%s\"",
976 md->GetAliRootVersion(),
978 TString addTagValue = Form("%s%s%s",
981 addTagValue3.Data());
983 Bool_t result = kFALSE;
984 AliDebug(2, Form("Tagging file. Tag command: %s", addTagValue.Data()));
985 TGridResult* res = gGrid->Command(addTagValue.Data());
986 const char* resCode = res->GetKey(0,"__result__"); // '1' if success
987 if(resCode[0] != '1') {
988 AliWarning(Form("Couldn't add CDB_MD tag value to file %s !",
992 AliDebug(2,"Object successfully tagged.");
998 //_____________________________________________________________________________
999 TList* AliCDBGrid::GetIdListFromFile(const char* fileName){
1001 TString turl(fileName);
1002 turl.Prepend("/alien" + fDBFolder);
1003 turl += "?se="; turl += fSE.Data();
1004 TFile *file = TFile::Open(turl);
1006 AliError(Form("Can't open selection file <%s>!", turl.Data()));
1010 TList *list = new TList();
1018 keycycle = "AliCDBId;";
1021 id = (AliCDBId*) file->Get(keycycle);
1025 file->Close(); delete file; file=0;
1032 //_____________________________________________________________________________
1033 Bool_t AliCDBGrid::Contains(const char* path) const{
1034 // check for path in storage's DBFolder
1036 TString initDir(gGrid->Pwd(0));
1037 TString dirName(fDBFolder);
1038 dirName += path; // dirName = fDBFolder/path
1039 Bool_t result=kFALSE;
1040 if (gGrid->Cd(dirName,0)) result=kTRUE;
1041 gGrid->Cd(initDir.Data(),0);
1045 //_____________________________________________________________________________
1046 void AliCDBGrid::QueryValidFiles()
1048 // Query the CDB for files valid for AliCDBStorage::fRun
1049 // Fills list fValidFileIds with AliCDBId objects extracted from CDB files
1050 // selected from AliEn metadata.
1051 // If fVersion was not set, fValidFileIds is filled with highest versions.
1054 MakeQueryFilter(fRun, fRun, fMetaDataFilter, filter);
1056 TString path = fPathFilter.GetPath();
1058 TString pattern = "Run*";
1059 TString optionQuery = "-y";
1061 pattern += Form("_v%d_s0", fVersion);
1065 AliDebug(2,Form("pattern: %s", pattern.Data()));
1067 TString addFolder = "";
1068 if (!path.Contains("*")){
1069 if (!path.BeginsWith("/")) addFolder += "/";
1073 if (path.BeginsWith("/")) path.Remove(0,1);
1074 if (path.EndsWith("/")) path.Remove(path.Length()-1,1);
1075 TObjArray* tokenArr = path.Tokenize("/");
1076 if (tokenArr->GetEntries() != 3) {
1077 AliError("Not a 3 level path! Keeping old query...");
1078 pattern.Prepend(path+"/");
1081 TString str0 = ((TObjString*)tokenArr->At(0))->String();
1082 TString str1 = ((TObjString*)tokenArr->At(1))->String();
1083 TString str2 = ((TObjString*)tokenArr->At(2))->String();
1084 if (str0 != "*" && str1 != "*" && str2 == "*"){
1085 // e.g. "ITS/Calib/*"
1086 addFolder = "/"+str0+"/"+str1;
1088 else if (str0 != "*" && str1 == "*" && str2 == "*"){
1090 addFolder = "/"+str0;
1092 else if (str0 == "*" && str1 == "*" && str2 == "*"){
1094 // do nothing: addFolder is already an empty string;
1097 // e.g. "ITS/*/RecoParam"
1098 pattern.Prepend(path+"/");
1101 delete tokenArr; tokenArr=0;
1104 TString folderCopy(Form("%s%s",fDBFolder.Data(),addFolder.Data()));
1106 AliDebug(2,Form("fDBFolder = %s, pattern = %s, filter = %s",folderCopy.Data(), pattern.Data(), filter.Data()));
1108 if (optionQuery == "-y"){
1109 AliInfo("Only latest version will be returned");
1112 TGridResult *res = gGrid->Query(folderCopy, pattern, filter, optionQuery.Data());
1115 AliError("Grid query failed");
1121 while ((map = (TMap*)next())) {
1123 if ((entry = (TObjString *) ((TMap *)map)->GetValue("lfn"))) {
1124 TString& filename = entry->String();
1125 if(filename.IsNull()) continue;
1126 AliDebug(2,Form("Found valid file: %s", filename.Data()));
1127 AliCDBId *validFileId = new AliCDBId;
1128 Bool_t result = FilenameToId(filename, *validFileId);
1130 fValidFileIds.AddLast(validFileId);
1141 //_____________________________________________________________________________
1142 void AliCDBGrid::MakeQueryFilter(Int_t firstRun, Int_t lastRun,
1143 const AliCDBMetaData* md, TString& result) const
1145 // create filter for file query
1147 result = Form("CDB:first_run<=%d and CDB:last_run>=%d", firstRun, lastRun);
1149 // if(version >= 0) {
1150 // result += Form(" and CDB:version=%d", version);
1152 // if(pathFilter.GetLevel0() != "*") {
1153 // result += Form(" and CDB:path_level_0=\"%s\"", pathFilter.GetLevel0().Data());
1155 // if(pathFilter.GetLevel1() != "*") {
1156 // result += Form(" and CDB:path_level_1=\"%s\"", pathFilter.GetLevel1().Data());
1158 // if(pathFilter.GetLevel2() != "*") {
1159 // result += Form(" and CDB:path_level_2=\"%s\"", pathFilter.GetLevel2().Data());
1163 if(md->GetObjectClassName()[0] != '\0') {
1164 result += Form(" and CDB_MD:object_classname=\"%s\"", md->GetObjectClassName());
1166 if(md->GetResponsible()[0] != '\0') {
1167 result += Form(" and CDB_MD:responsible=\"%s\"", md->GetResponsible());
1169 if(md->GetBeamPeriod() != 0) {
1170 result += Form(" and CDB_MD:beam_period=%d", md->GetBeamPeriod());
1172 if(md->GetAliRootVersion()[0] != '\0') {
1173 result += Form(" and CDB_MD:aliroot_version=\"%s\"", md->GetAliRootVersion());
1175 if(md->GetComment()[0] != '\0') {
1176 result += Form(" and CDB_MD:comment=\"%s\"", md->GetComment());
1179 AliDebug(2, Form("filter: %s",result.Data()));
1184 /////////////////////////////////////////////////////////////////////////////////////////////////
1186 // AliCDBGrid factory //
1188 /////////////////////////////////////////////////////////////////////////////////////////////////
1190 ClassImp(AliCDBGridFactory)
1192 //_____________________________________________________________________________
1193 Bool_t AliCDBGridFactory::Validate(const char* gridString) {
1194 // check if the string is valid Grid URI
1196 TRegexp gridPattern("^alien://.+$");
1198 return TString(gridString).Contains(gridPattern);
1201 //_____________________________________________________________________________
1202 AliCDBParam* AliCDBGridFactory::CreateParameter(const char* gridString) {
1203 // create AliCDBGridParam class from the URI string
1205 if (!Validate(gridString)) {
1209 TString buffer(gridString);
1211 TString gridUrl = "alien://";
1213 TString dbFolder = "";
1214 TString se = "default";
1215 TString cacheFolder = "";
1216 Bool_t operateDisconnected = kTRUE;
1217 Long64_t cacheSize = (UInt_t) 1024*1024*1024; // 1GB
1218 Long_t cleanupInterval = 0;
1220 TObjArray *arr = buffer.Tokenize('?');
1222 TObjString *str = 0;
1224 while((str = (TObjString*) iter.Next())){
1225 TString entry(str->String());
1226 Int_t indeq = entry.Index('=');
1228 if(entry.BeginsWith("alien://")) { // maybe it's a gridUrl!
1232 AliError(Form("Invalid entry! %s",entry.Data()));
1237 TString key = entry(0,indeq);
1238 TString value = entry(indeq+1,entry.Length()-indeq);
1240 if(key.Contains("grid",TString::kIgnoreCase)) {
1243 else if (key.Contains("user",TString::kIgnoreCase)){
1246 else if (key.Contains("se",TString::kIgnoreCase)){
1249 else if (key.Contains("cacheF",TString::kIgnoreCase)){
1250 cacheFolder = value;
1251 if (!cacheFolder.IsNull() && !cacheFolder.EndsWith("/"))
1254 else if (key.Contains("folder",TString::kIgnoreCase)){
1257 else if (key.Contains("operateDisc",TString::kIgnoreCase)){
1258 if(value == "kTRUE") {
1259 operateDisconnected = kTRUE;
1260 } else if (value == "kFALSE") {
1261 operateDisconnected = kFALSE;
1262 } else if (value == "0" || value == "1") {
1263 operateDisconnected = (Bool_t) value.Atoi();
1265 AliError(Form("Invalid entry! %s",entry.Data()));
1269 else if (key.Contains("cacheS",TString::kIgnoreCase)){
1270 if(value.IsDigit()) {
1271 cacheSize = value.Atoi();
1273 AliError(Form("Invalid entry! %s",entry.Data()));
1277 else if (key.Contains("cleanupInt",TString::kIgnoreCase)){
1278 if(value.IsDigit()) {
1279 cleanupInterval = value.Atoi();
1281 AliError(Form("Invalid entry! %s",entry.Data()));
1286 AliError(Form("Invalid entry! %s",entry.Data()));
1292 AliDebug(2, Form("gridUrl: %s", gridUrl.Data()));
1293 AliDebug(2, Form("user: %s", user.Data()));
1294 AliDebug(2, Form("dbFolder: %s", dbFolder.Data()));
1295 AliDebug(2, Form("s.e.: %s", se.Data()));
1296 AliDebug(2, Form("local cache folder: %s", cacheFolder.Data()));
1297 AliDebug(2, Form("local cache operate disconnected: %d", operateDisconnected));
1298 AliDebug(2, Form("local cache size: %lld", cacheSize));
1299 AliDebug(2, Form("local cache cleanup interval: %ld", cleanupInterval));
1302 AliError("Base folder must be specified!");
1306 return new AliCDBGridParam(gridUrl.Data(), user.Data(),
1307 dbFolder.Data(), se.Data(), cacheFolder.Data(),
1308 operateDisconnected, cacheSize, cleanupInterval);
1311 //_____________________________________________________________________________
1312 AliCDBStorage* AliCDBGridFactory::Create(const AliCDBParam* param) {
1313 // create AliCDBGrid storage instance from parameters
1315 AliCDBGrid *grid = 0;
1316 if (AliCDBGridParam::Class() == param->IsA()) {
1318 const AliCDBGridParam* gridParam = (const AliCDBGridParam*) param;
1319 grid = new AliCDBGrid(gridParam->GridUrl().Data(),
1320 gridParam->GetUser().Data(),
1321 gridParam->GetDBFolder().Data(),
1322 gridParam->GetSE().Data(),
1323 gridParam->GetCacheFolder().Data(),
1324 gridParam->GetOperateDisconnected(),
1325 gridParam->GetCacheSize(),
1326 gridParam->GetCleanupInterval());
1330 if(!gGrid && grid) {
1331 delete grid; grid=0;
1337 /////////////////////////////////////////////////////////////////////////////////////////////////
1339 // AliCDBGrid Parameter class // //
1341 /////////////////////////////////////////////////////////////////////////////////////////////////
1343 ClassImp(AliCDBGridParam)
1345 //_____________________________________________________________________________
1346 AliCDBGridParam::AliCDBGridParam():
1353 fOperateDisconnected(),
1358 // default constructor
1362 //_____________________________________________________________________________
1363 AliCDBGridParam::AliCDBGridParam(const char* gridUrl, const char* user, const char* dbFolder,
1364 const char* se, const char* cacheFolder, Bool_t operateDisconnected,
1365 Long64_t cacheSize, Long_t cleanupInterval):
1369 fDBFolder(dbFolder),
1371 fCacheFolder(cacheFolder),
1372 fOperateDisconnected(operateDisconnected),
1373 fCacheSize(cacheSize),
1374 fCleanupInterval(cleanupInterval)
1380 TString uri = Form("%s?User=%s?DBFolder=%s?SE=%s?CacheFolder=%s"
1381 "?OperateDisconnected=%d?CacheSize=%lld?CleanupInterval=%ld",
1382 fGridUrl.Data(), fUser.Data(),
1383 fDBFolder.Data(), fSE.Data(), fCacheFolder.Data(),
1384 fOperateDisconnected, fCacheSize, fCleanupInterval);
1389 //_____________________________________________________________________________
1390 AliCDBGridParam::~AliCDBGridParam() {
1395 //_____________________________________________________________________________
1396 AliCDBParam* AliCDBGridParam::CloneParam() const {
1399 return new AliCDBGridParam(fGridUrl.Data(), fUser.Data(),
1400 fDBFolder.Data(), fSE.Data(), fCacheFolder.Data(),
1401 fOperateDisconnected, fCacheSize, fCleanupInterval);
1404 //_____________________________________________________________________________
1405 ULong_t AliCDBGridParam::Hash() const {
1406 // return Hash function
1408 return fGridUrl.Hash()+fUser.Hash()+fDBFolder.Hash()+fSE.Hash()+fCacheFolder.Hash();
1411 //_____________________________________________________________________________
1412 Bool_t AliCDBGridParam::IsEqual(const TObject* obj) const {
1413 // check if this object is equal to AliCDBParam obj
1419 if (AliCDBGridParam::Class() != obj->IsA()) {
1423 AliCDBGridParam* other = (AliCDBGridParam*) obj;
1425 if(fGridUrl != other->fGridUrl) return kFALSE;
1426 if(fUser != other->fUser) return kFALSE;
1427 if(fDBFolder != other->fDBFolder) return kFALSE;
1428 if(fSE != other->fSE) return kFALSE;
1429 if(fCacheFolder != other->fCacheFolder) return kFALSE;
1430 if(fOperateDisconnected != other->fOperateDisconnected) return kFALSE;
1431 if(fCacheSize != other->fCacheSize) return kFALSE;
1432 if(fCleanupInterval != other->fCleanupInterval) return kFALSE;