]> git.uio.no Git - u/mrichter/AliRoot.git/blame - STEER/AliCDBGrid.cxx
Bug fix
[u/mrichter/AliRoot.git] / STEER / AliCDBGrid.cxx
CommitLineData
9e1ceb13 1/**************************************************************************
2 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
3 * *
4 * Author: The ALICE Off-line Project. *
5 * Contributors are mentioned in the code where appropriate. *
6 * *
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 **************************************************************************/
15
16/////////////////////////////////////////////////////////////////////////////////////////////////
17// //
18// AliCDBGrid //
19// access class to a DataBase in an AliEn storage //
20// //
21/////////////////////////////////////////////////////////////////////////////////////////////////
22
23
24#include <TGrid.h>
25#include <TGridResult.h>
26#include <TFile.h>
6dc56e97 27#include <TKey.h>
9e1ceb13 28#include <TROOT.h>
f430a9ce 29//#include <TSystem.h>
9e1ceb13 30#include <TObjArray.h>
31#include <TObjString.h>
32#include <TRegexp.h>
33
34#include "AliLog.h"
fdf65bb5 35#include "AliCDBEntry.h"
9e1ceb13 36#include "AliCDBGrid.h"
37
38
39ClassImp(AliCDBGrid)
40
41//_____________________________________________________________________________
b05400be 42AliCDBGrid::AliCDBGrid(const char *gridUrl, const char *user, const char *dbFolder, const char *se) :
9e1ceb13 43AliCDBStorage(),
b05400be 44fGridUrl(gridUrl),
9e1ceb13 45fUser(user),
b05400be 46fDBFolder(dbFolder),
9e1ceb13 47fSE(se)
48{
49// constructor //
50
9e1ceb13 51 // if the same Grid is alreay active, skip connection
b05400be 52 if (!gGrid || fGridUrl != gGrid->GridUrl()
024cf675 53 || (( fUser != "" ) && ( fUser != gGrid->GetUser() )) ) {
9e1ceb13 54 // connection to the Grid
62032124 55 AliInfo("Connection to the Grid...");
024cf675 56 if(gGrid){
57 AliInfo(Form("gGrid = %x; fGridUrl = %s; gGrid->GridUrl() = %s",gGrid,fGridUrl.Data(), gGrid->GridUrl()));
58 AliInfo(Form("fUser = %s; gGrid->GetUser() = %s",fUser.Data(), gGrid->GetUser()));
59 }
b05400be 60 TGrid::Connect(fGridUrl.Data(),fUser.Data());
9e1ceb13 61 }
62
63 if(!gGrid) {
64 AliError("Connection failed!");
65 return;
66 }
67
68 TString initDir(gGrid->Pwd(0));
b05400be 69 if (fDBFolder[0] != '/') {
70 fDBFolder.Prepend(initDir);
9e1ceb13 71 }
72
73 // check DBFolder: trying to cd to DBFolder; if it does not exist, create it
b05400be 74 if(!gGrid->Cd(fDBFolder.Data(),0)){
75 AliDebug(2,Form("Creating new folder <%s> ...",fDBFolder.Data()));
76 if(!gGrid->Mkdir(fDBFolder.Data(),"",0)){
77 AliError(Form("Cannot create folder <%s> !",fDBFolder.Data()));
9e1ceb13 78 }
79 } else {
b05400be 80 AliDebug(2,Form("Folder <%s> found",fDBFolder.Data()));
9e1ceb13 81 }
82
83 // removes any '/' at the end of path, then append one '/'
b05400be 84 while(fDBFolder.EndsWith("/")) fDBFolder.Remove(fDBFolder.Last('/'));
85 fDBFolder+="/";
9e1ceb13 86
62032124 87 fType="alien";
88 fBaseFolder = fDBFolder;
89
9e1ceb13 90 // return to the initial directory
91 gGrid->Cd(initDir.Data(),0);
92}
93
94//_____________________________________________________________________________
95AliCDBGrid::~AliCDBGrid()
96{
97// destructor
62032124 98 delete gGrid; gGrid=0;
9e1ceb13 99
100}
101
102//_____________________________________________________________________________
62032124 103Bool_t AliCDBGrid::FilenameToId(TString& filename, AliCDBId& id) {
4005d0b5 104// build AliCDBId from full path filename (fDBFolder/path/Run#x_#y_v#z_s0.root)
62032124 105
106 if(filename.Contains(fDBFolder)){
107 filename = filename(fDBFolder.Length(),filename.Length()-fDBFolder.Length());
108 }
109
110 TString idPath = filename(0,filename.Last('/'));
111 id.SetPath(idPath);
112 if(!id.IsValid()) return kFALSE;
113
114 filename=filename(idPath.Length()+1,filename.Length()-idPath.Length());
9e1ceb13 115
116 Ssiz_t mSize;
4005d0b5 117 // valid filename: Run#firstRun_#lastRun_v#version_s0.root
118 TRegexp keyPattern("^Run[0-9]+_[0-9]+_v[0-9]+_s0.root$");
9e1ceb13 119 keyPattern.Index(filename, &mSize);
120 if (!mSize) {
4005d0b5 121
122 // TODO backward compatibility ... maybe remove later!
123 Ssiz_t oldmSize;
124 TRegexp oldKeyPattern("^Run[0-9]+_[0-9]+_v[0-9]+.root$");
125 oldKeyPattern.Index(filename, &oldmSize);
126 if(!oldmSize) {
127 AliDebug(2,Form("Bad filename <%s>.", filename.Data()));
128 return kFALSE;
129 } else {
130 AliDebug(2,Form("Old filename format <%s>.", filename.Data()));
131 id.SetSubVersion(-11); // TODO trick to ensure backward compatibility
132 }
133
134 } else {
135 id.SetSubVersion(-1); // TODO trick to ensure backward compatibility
136 }
9e1ceb13 137
62032124 138 filename.Resize(filename.Length() - sizeof(".root") + 1);
9e1ceb13 139
62032124 140 TObjArray* strArray = (TObjArray*) filename.Tokenize("_");
9e1ceb13 141
142 TString firstRunString(((TObjString*) strArray->At(0))->GetString());
62032124 143 id.SetFirstRun(atoi(firstRunString.Data() + 3));
144 id.SetLastRun(atoi(((TObjString*) strArray->At(1))->GetString()));
145
9e1ceb13 146 TString verString(((TObjString*) strArray->At(2))->GetString());
62032124 147 id.SetVersion(atoi(verString.Data() + 1));
9e1ceb13 148
149 delete strArray;
150
151 return kTRUE;
152}
153
154//_____________________________________________________________________________
c3a7b59a 155Bool_t AliCDBGrid::IdToFilename(const AliCDBId& id, TString& filename) const {
62032124 156// build file name from AliCDBId (path, run range, version) and fDBFolder
9e1ceb13 157
62032124 158 if (!id.GetAliCDBRunRange().IsValid()) {
159 AliDebug(2,Form("Invalid run range <%d, %d>.",
160 id.GetFirstRun(), id.GetLastRun()));
9e1ceb13 161 return kFALSE;
162 }
163
62032124 164 if (id.GetVersion() < 0) {
165 AliDebug(2,Form("Invalid version <%d>.", id.GetVersion()));
9e1ceb13 166 return kFALSE;
167 }
62032124 168
4005d0b5 169 filename = Form("Run%d_%d_v%d",
62032124 170 id.GetFirstRun(),
171 id.GetLastRun(),
172 id.GetVersion());
173
4005d0b5 174 if (id.GetSubVersion() != -11) filename += "_s0"; // TODO to ensure backward compatibility
175 filename += ".root";
176
62032124 177 filename.Prepend(fDBFolder + id.GetPath() + '/');
9e1ceb13 178
179 return kTRUE;
180}
181
182//_____________________________________________________________________________
183Bool_t AliCDBGrid::PrepareId(AliCDBId& id) {
184// prepare id (version) of the object that will be stored (called by PutEntry)
185
186 TString initDir(gGrid->Pwd(0));
187 TString pathName= id.GetPath();
188
b05400be 189 TString dirName(fDBFolder);
9e1ceb13 190
191 Bool_t dirExist=kFALSE;
4005d0b5 192
9e1ceb13 193 // go to the path; if directory does not exist, create it
194 TObjArray *arrName=pathName.Tokenize("/");
195 for(int i=0;i<arrName->GetEntries();i++){
196 TString buffer((arrName->At(i))->GetName());
197 dirName+=buffer; dirName+="/";
198 dirExist=gGrid->Cd(dirName,0);
199 if (!dirExist) {
b05400be 200 AliDebug(2,Form("Creating new folder <%s> ...",dirName.Data()));
9e1ceb13 201 if(!gGrid->Mkdir(dirName,"",0)){
202 AliError(Form("Cannot create directory <%s> !",dirName.Data()));
203 gGrid->Cd(initDir.Data());
204 return kFALSE;
205 }
206 }
207 }
208 delete arrName;
209 gGrid->Cd(initDir,0);
210
62032124 211 TString filename;
212 AliCDBId anId; // the id got from filename
9e1ceb13 213 AliCDBRunRange lastRunRange(-1,-1); // highest runRange found
9e1ceb13 214 Int_t lastVersion=0; // highest version found
215
216 TGridResult *res = gGrid->Ls(dirName);
217
218 //loop on the files in the directory, look for highest version
219 for(int i=0; i < res->GetEntries(); i++){
62032124 220 filename=res->GetFileNamePath(i);
221 if (!FilenameToId(filename, anId)) continue;
222 if (anId.GetAliCDBRunRange().Overlaps(id.GetAliCDBRunRange()) && anId.GetVersion() > lastVersion) {
223 lastVersion = anId.GetVersion();
224 lastRunRange = anId.GetAliCDBRunRange();
9e1ceb13 225 }
226
227 }
4005d0b5 228 delete res;
229
9e1ceb13 230 id.SetVersion(lastVersion + 1);
4005d0b5 231 id.SetSubVersion(0);
9e1ceb13 232
233 TString lastStorage = id.GetLastStorage();
234 if(lastStorage.Contains(TString("new"), TString::kIgnoreCase) && id.GetVersion() > 1 ){
84090f85 235 AliDebug(2, Form("A NEW object is being stored with version %d",
9e1ceb13 236 id.GetVersion()));
84090f85 237 AliDebug(2, Form("and it will hide previously stored object with version %d!",
9e1ceb13 238 id.GetVersion()-1));
239 }
240
4005d0b5 241 if(!lastRunRange.IsAnyRange() && !(lastRunRange.IsEqual(&id.GetAliCDBRunRange())))
9e1ceb13 242 AliWarning(Form("Run range modified w.r.t. previous version (Run%d_%d_v%d)",
243 lastRunRange.GetFirstRun(), lastRunRange.GetLastRun(), id.GetVersion()));
4005d0b5 244
9e1ceb13 245 return kTRUE;
246}
247
248//_____________________________________________________________________________
6dc56e97 249AliCDBId* AliCDBGrid::GetId(const TObjArray& validFileIds, const AliCDBId& query) {
62032124 250// look for the Id that matches query's requests (highest or exact version)
9e1ceb13 251
6dc56e97 252 if(validFileIds.GetEntriesFast() < 1) {
62032124 253 return NULL;
6dc56e97 254 } else if (validFileIds.GetEntriesFast() == 1) {
62032124 255 return dynamic_cast<AliCDBId*> (validFileIds.At(0));
256 }
9e1ceb13 257
62032124 258 TIter iter(&validFileIds);
9e1ceb13 259
62032124 260 AliCDBId *anIdPtr=0;
261 AliCDBId* result=0;
9e1ceb13 262
62032124 263 while((anIdPtr = dynamic_cast<AliCDBId*> (iter.Next()))){
62032124 264 if(anIdPtr->GetPath() != query.GetPath()) continue;
265
266 //if(!CheckVersion(query, anIdPtr, result)) return NULL;
9e1ceb13 267
268 if (!query.HasVersion()){ // look for highest version
62032124 269 if(result && result->GetVersion() > anIdPtr->GetVersion()) continue;
270 if(result && result->GetVersion() == anIdPtr->GetVersion()) {
271 AliDebug(2,Form("More than one object valid for run %d, version %d!",
272 query.GetFirstRun(), anIdPtr->GetVersion()));
273 return NULL;
9e1ceb13 274 }
62032124 275 result = anIdPtr;
9e1ceb13 276 } else { // look for specified version
62032124 277 if(query.GetVersion() != anIdPtr->GetVersion()) continue;
278 if(result && result->GetVersion() == anIdPtr->GetVersion()){
279 AliDebug(2,Form("More than one object valid for run %d, version %d!",
280 query.GetFirstRun(), anIdPtr->GetVersion()));
281 return NULL;
9e1ceb13 282 }
62032124 283 result = anIdPtr;
9e1ceb13 284 }
62032124 285
286 }
287
288
289 return result;
290}
291
9e1ceb13 292//_____________________________________________________________________________
293AliCDBEntry* AliCDBGrid::GetEntry(const AliCDBId& queryId) {
294// get AliCDBEntry from the database
295
62032124 296 AliCDBId* dataId=0;
297
298 AliCDBId selectedId(queryId);
299 if (!selectedId.HasVersion()) {
9e1ceb13 300 // if version is not specified, first check the selection criteria list
4b5e0dce 301 GetSelection(&selectedId);
62032124 302 }
303
6dc56e97 304 TObjArray validFileIds;
62032124 305 validFileIds.SetOwner(1);
306
307 // look for file matching query requests (path, runRange, version)
308 if(selectedId.GetFirstRun() == fRun &&
c3a7b59a 309 fPathFilter.Comprises(selectedId.GetAliCDBPath()) && fVersion < 0 && !fMetaDataFilter){
62032124 310 // look into list of valid files previously loaded with AliCDBStorage::FillValidFileIds()
311 AliDebug(2, Form("List of files valid for run %d and for path %s was loaded. Looking there!",
312 selectedId.GetFirstRun(), selectedId.GetPath().Data()));
313 dataId = GetId(fValidFileIds, selectedId);
314
9e1ceb13 315 } else {
62032124 316 // List of files valid for reqested run was not loaded. Looking directly into CDB
317 AliDebug(2, Form("List of files valid for run %d and for path %s was not loaded. Looking directly into CDB!",
318 selectedId.GetFirstRun(), selectedId.GetPath().Data()));
319
320 TString filter;
6dc56e97 321 MakeQueryFilter(selectedId.GetFirstRun(), selectedId.GetLastRun(), 0, filter);
62032124 322
6dc56e97 323 TString pattern = Form("%s/Run*", selectedId.GetPath().Data());
4005d0b5 324 if(selectedId.GetVersion() >= 0) pattern += Form("_v%d*",selectedId.GetVersion());
6dc56e97 325 pattern += ".root";
326 AliDebug(2,Form("pattern: %s", pattern.Data()));
327
328 TGridResult *res = gGrid->Query(fDBFolder, pattern, filter, "");
62032124 329 AliCDBId validFileId;
330 for(int i=0; i<res->GetEntries(); i++){
331 TString filename = res->GetKey(i, "lfn");
c3a7b59a 332 if(filename == "") continue;
62032124 333 if(FilenameToId(filename, validFileId))
334 validFileIds.AddLast(validFileId.Clone());
335 }
336 delete res;
337 dataId = GetId(validFileIds, selectedId);
9e1ceb13 338 }
339
62032124 340 if (!dataId) return NULL;
9e1ceb13 341
342 TString filename;
62032124 343 if (!IdToFilename(*dataId, filename)) {
024cf675 344 AliDebug(2,Form("Bad data ID encountered! Subnormal error!"));
9e1ceb13 345 return NULL;
346 }
347
62032124 348 AliCDBEntry* anEntry = GetEntryFromFile(filename, dataId);
349
350 return anEntry;
351}
352
353//_____________________________________________________________________________
8e245d15 354AliCDBEntry* AliCDBGrid::GetEntryFromFile(TString& filename, AliCDBId* dataId){
62032124 355// Get AliCBEntry object from file "filename"
9e1ceb13 356
024cf675 357 AliDebug(2,Form("Opening file: %s",filename.Data()));
62032124 358
359 filename.Prepend("/alien");
9e1ceb13 360 TFile *file = TFile::Open(filename);
361 if (!file) {
024cf675 362 AliDebug(2,Form("Can't open file <%s>!", filename.Data()));
9e1ceb13 363 return NULL;
364 }
365
366 // get the only AliCDBEntry object from the file
367 // the object in the file is an AliCDBEntry entry named "AliCDBEntry"
368
62032124 369 AliCDBEntry* anEntry = dynamic_cast<AliCDBEntry*> (file->Get("AliCDBEntry"));
9e1ceb13 370
62032124 371 if (!anEntry) {
372 AliDebug(2,Form("Bad storage data: file does not contain an AliCDBEntry object!"));
373 file->Close();
9e1ceb13 374 return NULL;
375 }
376
9e1ceb13 377 // The object's Id is not reset during storage
378 // If object's Id runRange or version do not match with filename,
379 // it means that someone renamed file by hand. In this case a warning msg is issued.
62032124 380
381 if(anEntry){
382 AliCDBId entryId = anEntry->GetId();
4005d0b5 383 Int_t tmpSubVersion = dataId->GetSubVersion();
384 dataId->SetSubVersion(entryId.GetSubVersion()); // otherwise filename and id may mismatch
8e245d15 385 if(!entryId.IsEqual(dataId)){
b8ec52f6 386 AliWarning(Form("Mismatch between file name and object's Id!"));
387 AliWarning(Form("File name: %s", dataId->ToString().Data()));
388 AliWarning(Form("Object's Id: %s", entryId.ToString().Data()));
62032124 389 }
4005d0b5 390 dataId->SetSubVersion(tmpSubVersion);
9e1ceb13 391 }
392
62032124 393 anEntry->SetLastStorage("grid");
394
145f45a2 395 // Check whether entry contains a TTree. In case load the tree in memory!
396 LoadTreeFromFile(anEntry);
397
9e1ceb13 398 // close file, return retieved entry
399 file->Close(); delete file; file=0;
62032124 400
401 return anEntry;
9e1ceb13 402}
403
404//_____________________________________________________________________________
62032124 405TList* AliCDBGrid::GetEntries(const AliCDBId& queryId) {
9e1ceb13 406// multiple request (AliCDBStorage::GetAll)
407
62032124 408 TList* result = new TList();
409 result->SetOwner();
9e1ceb13 410
6dc56e97 411 TObjArray validFileIds;
62032124 412 validFileIds.SetOwner(1);
9e1ceb13 413
62032124 414 Bool_t alreadyLoaded = kFALSE;
9e1ceb13 415
62032124 416 // look for file matching query requests (path, runRange)
417 if(queryId.GetFirstRun() == fRun &&
c3a7b59a 418 fPathFilter.Comprises(queryId.GetAliCDBPath()) && fVersion < 0 && !fMetaDataFilter){
62032124 419 // look into list of valid files previously loaded with AliCDBStorage::FillValidFileIds()
420 AliDebug(2,Form("List of files valid for run %d and for path %s was loaded. Looking there!",
421 queryId.GetFirstRun(), queryId.GetPath().Data()));
9e1ceb13 422
62032124 423 alreadyLoaded = kTRUE;
9e1ceb13 424
62032124 425 } else {
426 // List of files valid for reqested run was not loaded. Looking directly into CDB
427 AliDebug(2,Form("List of files valid for run %d and for path %s was not loaded. Looking directly into CDB!",
428 queryId.GetFirstRun(), queryId.GetPath().Data()));
429
430 TString filter;
6dc56e97 431 MakeQueryFilter(queryId.GetFirstRun(), queryId.GetLastRun(), 0, filter);
432
433 TString pattern = Form("%s/Run*.root", queryId.GetPath().Data());
434 AliDebug(2,Form("pattern: %s", pattern.Data()));
435
436 TGridResult *res = gGrid->Query(fDBFolder, pattern, filter, "");
62032124 437
62032124 438 AliCDBId validFileId;
439 for(int i=0; i<res->GetEntries(); i++){
440 TString filename = res->GetKey(i, "lfn");
c3a7b59a 441 if(filename == "") continue;
62032124 442 if(FilenameToId(filename, validFileId))
443 validFileIds.AddLast(validFileId.Clone());
444 }
445 delete res;
9e1ceb13 446 }
447
62032124 448 TIter *iter=0;
449 if(alreadyLoaded){
450 iter = new TIter(&fValidFileIds);
451 } else {
452 iter = new TIter(&validFileIds);
453 }
9e1ceb13 454
6dc56e97 455 TObjArray selectedIds;
62032124 456 selectedIds.SetOwner(1);
457
458 // loop on list of valid Ids to select the right version to get.
459 // According to query and to the selection criteria list, version can be the highest or exact
460 AliCDBPath pathCopy;
461 AliCDBId* anIdPtr=0;
462 AliCDBId* dataId=0;
463 AliCDBPath queryPath = queryId.GetAliCDBPath();
464 while((anIdPtr = dynamic_cast<AliCDBId*> (iter->Next()))){
465 AliCDBPath thisCDBPath = anIdPtr->GetAliCDBPath();
466 if(!(queryPath.Comprises(thisCDBPath)) || pathCopy.GetPath() == thisCDBPath.GetPath()) continue;
467 pathCopy = thisCDBPath;
468
469 // check the selection criteria list for this query
470 AliCDBId thisId(*anIdPtr);
471 thisId.SetVersion(queryId.GetVersion());
472 if(!thisId.HasVersion()) GetSelection(&thisId);
473
474 if(alreadyLoaded){
475 dataId = GetId(fValidFileIds, thisId);
476 } else {
477 dataId = GetId(validFileIds, thisId);
9e1ceb13 478 }
62032124 479 if(dataId) selectedIds.Add(dataId->Clone());
9e1ceb13 480 }
9e1ceb13 481
62032124 482 delete iter; iter=0;
9e1ceb13 483
62032124 484 // selectedIds contains the Ids of the files matching all requests of query!
485 // All the objects are now ready to be retrieved
486 iter = new TIter(&selectedIds);
487 while((anIdPtr = dynamic_cast<AliCDBId*> (iter->Next()))){
488 TString filename;
489 if (!IdToFilename(*anIdPtr, filename)) {
490 AliDebug(2,Form("Bad data ID encountered! Subnormal error!"));
491 continue;
492 }
9e1ceb13 493
62032124 494 AliCDBEntry* anEntry = GetEntryFromFile(filename, anIdPtr);
9e1ceb13 495
62032124 496 if(anEntry) result->Add(anEntry);
9e1ceb13 497
62032124 498 }
499 delete iter; iter=0;
500
501 return result;
9e1ceb13 502}
503
504//_____________________________________________________________________________
505Bool_t AliCDBGrid::PutEntry(AliCDBEntry* entry) {
506// put an AliCDBEntry object into the database
62032124 507
9e1ceb13 508 AliCDBId& id = entry->GetId();
509
510 // set version for the entry to be stored
62032124 511 if (!PrepareId(id)) return kFALSE;
9e1ceb13 512
513 // build filename from entry's id
514 TString filename;
62032124 515 if (!IdToFilename(id, filename)) {
9e1ceb13 516 AliError("Bad ID encountered! Subnormal error!");
517 return kFALSE;
62032124 518 }
519
520 TString folderToTag = Form("%s%s",
521 fDBFolder.Data(),
522 id.GetPath().Data());
523
524 // add CDB and CDB_MD tag to folder
525 // TODO how to check that folder has already tags?
c3a7b59a 526 AddTag(folderToTag,"CDB");
527 AddTag(folderToTag,"CDB_MD");
9e1ceb13 528
9e1ceb13 529 TDirectory* saveDir = gDirectory;
530
fb33abde 531 TString fullFilename = Form("/alien%s", filename.Data());
62032124 532 // specify SE to filename
fb33abde 533 if (fSE != "default") fullFilename += Form("?se=%s",fSE.Data());
62032124 534
9e1ceb13 535 // open file
145f45a2 536 TFile *file = TFile::Open(fullFilename,"CREATE");
537 if(!file || !file->IsWritable()){
538 AliError(Form("Can't open file <%s>!", filename.Data()));
539 if(file && !file->IsWritable()) file->Close(); delete file; file=0;
540 return kFALSE;
541 }
62032124 542
543 file->cd();
9e1ceb13 544
ed343d5e 545 //SetTreeToFile(entry, file);
145f45a2 546
9e1ceb13 547 entry->SetVersion(id.GetVersion());
548
549 // write object (key name: "AliCDBEntry")
145f45a2 550 Bool_t result = (file->WriteTObject(entry, "AliCDBEntry") != 0);
62032124 551 if (!result) AliError(Form("Can't write entry to file <%s>!", filename.Data()));
9e1ceb13 552
553
554 if (saveDir) saveDir->cd(); else gROOT->cd();
555 file->Close(); delete file; file=0;
c3a7b59a 556
9e1ceb13 557 if(result) {
62032124 558 AliInfo(Form("CDB object stored into file %s", filename.Data()));
fb33abde 559 AliInfo(Form("using S.E.: %s", fSE.Data()));
62032124 560
c3a7b59a 561 if(!TagFileId(filename, &id)){
562 AliInfo(Form("CDB tagging failed. Deleting file %s!",filename.Data()));
563 if(!gGrid->Rm(filename.Data()))
564 AliError("Can't delete file!");
565 return kFALSE;
566 }
567
568 TagFileMetaData(filename, entry->GetMetaData());
9e1ceb13 569 }
62032124 570
571 return result;
572}
573//_____________________________________________________________________________
574Bool_t AliCDBGrid::AddTag(TString& folderToTag, const char* tagname){
575// add "tagname" tag (CDB or CDB_MD) to folder where object will be stored
576
577 Bool_t result = kTRUE;
578 AliDebug(2, Form("adding %s tag to folder %s", tagname, folderToTag.Data()));
579 TString addTag = Form("addTag %s %s", folderToTag.Data(), tagname);
580 TGridResult *gridres = gGrid->Command(addTag.Data());
581 const char* resCode = gridres->GetKey(0,"__result__"); // '1' if success
582 if(resCode[0] != '1') {
583 AliError(Form("Couldn't add %s tags to folder %s !",
584 tagname, folderToTag.Data()));
585 result = kFALSE;
586 }
587 delete gridres;
9e1ceb13 588 return result;
589}
590
62032124 591//_____________________________________________________________________________
c3a7b59a 592Bool_t AliCDBGrid::TagFileId(TString& filename, const AliCDBId* id){
62032124 593// tag stored object in CDB table using object Id's parameters
594
f430a9ce 595 TString addTagValue1 = Form("addTagValue %s CDB ", filename.Data());
596 TString addTagValue2 = Form("first_run=%d last_run=%d version=%d ",
62032124 597 id->GetFirstRun(),
598 id->GetLastRun(),
599 id->GetVersion());
f430a9ce 600 TString addTagValue3 = Form("path_level_0=\"%s\" path_level_1=\"%s\" path_level_2=\"%s\"",
62032124 601 id->GetLevel0().Data(),
602 id->GetLevel1().Data(),
603 id->GetLevel2().Data());
604 TString addTagValue = Form("%s%s%s",
f430a9ce 605 addTagValue1.Data(),
606 addTagValue2.Data(),
607 addTagValue3.Data());
62032124 608
c3a7b59a 609 Bool_t result = kFALSE;
62032124 610 AliDebug(2, Form("Tagging file. Tag command: %s", addTagValue.Data()));
611 TGridResult* res = gGrid->Command(addTagValue.Data());
612 const char* resCode = res->GetKey(0,"__result__"); // '1' if success
613 if(resCode[0] != '1') {
c3a7b59a 614 AliError(Form("Couldn't add CDB tag value to file %s !",
62032124 615 filename.Data()));
c3a7b59a 616 result = kFALSE;
62032124 617 } else {
618 AliInfo("Object successfully tagged.");
c3a7b59a 619 result = kTRUE;
62032124 620 }
621 delete res;
c3a7b59a 622 return result;
62032124 623
624}
625
626//_____________________________________________________________________________
c3a7b59a 627Bool_t AliCDBGrid::TagFileMetaData(TString& filename, const AliCDBMetaData* md){
62032124 628// tag stored object in CDB table using object Id's parameters
629
f430a9ce 630 TString addTagValue1 = Form("addTagValue %s CDB_MD ", filename.Data());
631 TString addTagValue2 = Form("object_classname=\"%s\" responsible=\"%s\" beam_period=%d ",
62032124 632 md->GetObjectClassName(),
633 md->GetResponsible(),
634 md->GetBeamPeriod());
f430a9ce 635 TString addTagValue3 = Form("aliroot_version=\"%s\" comment=\"%s\"",
62032124 636 md->GetAliRootVersion(),
637 md->GetComment());
638 TString addTagValue = Form("%s%s%s",
f430a9ce 639 addTagValue1.Data(),
640 addTagValue2.Data(),
641 addTagValue3.Data());
62032124 642
c3a7b59a 643 Bool_t result = kFALSE;
62032124 644 AliDebug(2, Form("Tagging file. Tag command: %s", addTagValue.Data()));
645 TGridResult* res = gGrid->Command(addTagValue.Data());
646 const char* resCode = res->GetKey(0,"__result__"); // '1' if success
647 if(resCode[0] != '1') {
648 AliWarning(Form("Couldn't add CDB_MD tag value to file %s !",
649 filename.Data()));
c3a7b59a 650 result = kFALSE;
62032124 651 } else {
652 AliInfo("Object successfully tagged.");
c3a7b59a 653 result = kTRUE;
62032124 654 }
c3a7b59a 655 return result;
62032124 656}
657
b05400be 658//_____________________________________________________________________________
659TList* AliCDBGrid::GetIdListFromFile(const char* fileName){
6dc56e97 660
b05400be 661 TString turl(fileName);
662 turl.Prepend("/alien" + fDBFolder);
62032124 663 turl += "?se="; turl += fSE.Data();
b05400be 664 TFile *file = TFile::Open(turl);
665 if (!file) {
666 AliError(Form("Can't open selection file <%s>!", turl.Data()));
667 return NULL;
668 }
669
670 TList *list = new TList();
671 list->SetOwner();
672 int i=0;
673 TString keycycle;
62032124 674
b05400be 675 AliCDBId *id;
676 while(1){
677 i++;
678 keycycle = "AliCDBId;";
679 keycycle+=i;
680
681 id = (AliCDBId*) file->Get(keycycle);
682 if(!id) break;
683 list->AddFirst(id);
684 }
685 file->Close(); delete file; file=0;
686
687 return list;
688
689
690}
691
692//_____________________________________________________________________________
693Bool_t AliCDBGrid::Contains(const char* path) const{
694// check for path in storage's DBFolder
695
696 TString initDir(gGrid->Pwd(0));
697 TString dirName(fDBFolder);
698 dirName += path; // dirName = fDBFolder/path
699 Bool_t result=kFALSE;
700 if (gGrid->Cd(dirName,0)) result=kTRUE;
701 gGrid->Cd(initDir.Data(),0);
702 return result;
703}
704
62032124 705//_____________________________________________________________________________
706void AliCDBGrid::QueryValidFiles()
707{
708// Query the CDB for files valid for AliCDBStorage::fRun
709// fills list fValidFileIds with AliCDBId objects created from file name
710
711 TString filter;
6dc56e97 712 MakeQueryFilter(fRun, fRun, fMetaDataFilter, filter);
713
714 TString pattern = Form("%s/Run*", fPathFilter.GetPath().Data());
4005d0b5 715 if(fVersion >= 0) pattern += Form("_v%d*", fVersion);
6dc56e97 716 pattern += ".root";
717 AliDebug(2,Form("pattern: %s", pattern.Data()));
718
719 TGridResult *res = gGrid->Query(fDBFolder, pattern, filter, "");
62032124 720
62032124 721 AliCDBId validFileId;
722 for(int i=0; i<res->GetEntries(); i++){
723 TString filename = res->GetKey(i, "lfn");
c3a7b59a 724 if(filename == "") continue;
62032124 725 AliDebug(2,Form("Found valid file: %s", filename.Data()));
726 Bool_t result = FilenameToId(filename, validFileId);
727 if(result) {
728 fValidFileIds.AddLast(validFileId.Clone());
729 }
730 }
731 delete res;
732
733}
734
735//_____________________________________________________________________________
c3a7b59a 736void AliCDBGrid::MakeQueryFilter(Int_t firstRun, Int_t lastRun,
62032124 737 const AliCDBMetaData* md, TString& result) const
738{
739// create filter for file query
740
c3a7b59a 741 result = Form("CDB:first_run<=%d and CDB:last_run>=%d", firstRun, lastRun);
62032124 742
6dc56e97 743// if(version >= 0) {
744// result += Form(" and CDB:version=%d", version);
745// }
746// if(pathFilter.GetLevel0() != "*") {
747// result += Form(" and CDB:path_level_0=\"%s\"", pathFilter.GetLevel0().Data());
748// }
749// if(pathFilter.GetLevel1() != "*") {
750// result += Form(" and CDB:path_level_1=\"%s\"", pathFilter.GetLevel1().Data());
751// }
752// if(pathFilter.GetLevel2() != "*") {
753// result += Form(" and CDB:path_level_2=\"%s\"", pathFilter.GetLevel2().Data());
754// }
62032124 755
756 if(md){
757 if(md->GetObjectClassName()[0] != '\0') {
758 result += Form(" and CDB_MD:object_classname=\"%s\"", md->GetObjectClassName());
759 }
760 if(md->GetResponsible()[0] != '\0') {
761 result += Form(" and CDB_MD:responsible=\"%s\"", md->GetResponsible());
762 }
763 if(md->GetBeamPeriod() != 0) {
764 result += Form(" and CDB_MD:beam_period=%d", md->GetBeamPeriod());
765 }
766 if(md->GetAliRootVersion()[0] != '\0') {
767 result += Form(" and CDB_MD:aliroot_version=\"%s\"", md->GetAliRootVersion());
768 }
769 if(md->GetComment()[0] != '\0') {
770 result += Form(" and CDB_MD:comment=\"%s\"", md->GetComment());
771 }
772 }
773 AliDebug(2, Form("filter: %s",result.Data()));
774
775}
776
c3a7b59a 777//_____________________________________________________________________________
778Int_t AliCDBGrid::GetLatestVersion(const char* path, Int_t run){
779// get last version found in the database valid for run and path
780
6dc56e97 781 TObjArray validFileIds;
c3a7b59a 782 validFileIds.SetOwner(1);
783
784 AliCDBPath aCDBPath(path);
785 if(!aCDBPath.IsValid() || aCDBPath.IsWildcard()) {
786 AliError(Form("Invalid path in request: %s", path));
787 return -1;
788 }
789 AliCDBId query(path, run, run, -1, -1);
790 AliCDBId* dataId = 0;
791
792 // look for file matching query requests (path, runRange, version)
6dc56e97 793 if(run == fRun && fPathFilter.Comprises(aCDBPath) && fVersion < 0){
c3a7b59a 794 // look into list of valid files previously loaded with AliCDBStorage::FillValidFileIds()
795 AliDebug(2, Form("List of files valid for run %d and for path %s was loaded. Looking there!",
796 run, path));
797 dataId = GetId(fValidFileIds, query);
798 if (!dataId) return -1;
799 return dataId->GetVersion();
800
801 }
802 // List of files valid for reqested run was not loaded. Looking directly into CDB
803 AliDebug(2, Form("List of files valid for run %d and for path %s was not loaded. Looking directly into CDB!",
804 run, path));
805
806 TString filter;
6dc56e97 807 MakeQueryFilter(run, run, 0, filter);
808
809 TString pattern = Form("%s/Run*.root", path);
810 AliDebug(2,Form("pattern: %s", pattern.Data()));
c3a7b59a 811
6dc56e97 812 TGridResult *res = gGrid->Query(fDBFolder, pattern, filter, "");
c3a7b59a 813 AliCDBId validFileId;
814 for(int i=0; i<res->GetEntries(); i++){
815 TString filename = res->GetKey(i, "lfn");
816 if(filename == "") continue;
817 if(FilenameToId(filename, validFileId))
818 validFileIds.AddLast(validFileId.Clone());
819 }
820 delete res;
821
822 dataId = GetId(validFileIds, query);
823 if (!dataId) return -1;
824
825 return dataId->GetVersion();
826
827}
828
829//_____________________________________________________________________________
830Int_t AliCDBGrid::GetLatestSubVersion(const char* /*path*/, Int_t /*run*/, Int_t /*version*/){
831// get last subversion found in the database valid for run and path
832 AliError("Objects in GRID storage have no sub version!");
833 return -1;
834}
835
836
9e1ceb13 837/////////////////////////////////////////////////////////////////////////////////////////////////
838// //
839// AliCDBGrid factory //
840// //
841/////////////////////////////////////////////////////////////////////////////////////////////////
842
843ClassImp(AliCDBGridFactory)
844
845//_____________________________________________________________________________
846Bool_t AliCDBGridFactory::Validate(const char* gridString) {
847// check if the string is valid Grid URI
848
849 // pattern: alien://hostName:Port;user;dbPath;SE
850 // example of a valid pattern:
851 // "alien://aliendb4.cern.ch:9000;colla;DBTest;ALICE::CERN::Server"
b05400be 852// TRegexp gridPattern("^alien://.+:[0-9]+;[a-zA-Z0-9_-.]+;.+;.+$");
853 TRegexp gridPattern("^alien://.+$");
9e1ceb13 854
855 return TString(gridString).Contains(gridPattern);
856}
857
858//_____________________________________________________________________________
859AliCDBParam* AliCDBGridFactory::CreateParameter(const char* gridString) {
860// create AliCDBGridParam class from the URI string
861
862 if (!Validate(gridString)) {
863 return NULL;
864 }
b05400be 865 //TString buffer(gridString + sizeof("alien://") - 1);
866 TString buffer(gridString);
c3a7b59a 867
868 TString gridUrl = "alien://";
b05400be 869 TString user = "";
870 TString dbFolder = "DBGrid";
fb33abde 871 TString se = "default";
b05400be 872
873 TObjArray *arr = buffer.Tokenize('?');
874 TIter iter(arr);
62032124 875 TObjString *str = 0;
9e1ceb13 876
b05400be 877 while((str = (TObjString*) iter.Next())){
878 TString entry(str->String());
879 Int_t indeq = entry.Index('=');
880 if(indeq == -1) {
881 if(entry.BeginsWith("alien://")) { // maybe it's a gridUrl!
882 gridUrl = entry;
883 continue;
884 } else {
885 AliError(Form("Invalid entry! %s",entry.Data()));
886 continue;
887 }
888 }
889
890 TString key = entry(0,indeq);
891 TString value = entry(indeq+1,entry.Length()-indeq);
892
893 if(key.Contains("grid",TString::kIgnoreCase)) {
894 gridUrl += value;
895 }
896 else if (key.Contains("user",TString::kIgnoreCase)){
897 user = value;
898 }
899 else if (key.Contains("folder",TString::kIgnoreCase)){
900 dbFolder = value;
901 }
902 else if (key.Contains("se",TString::kIgnoreCase)){
903 se = value;
904 }
905 else{
906 AliError(Form("Invalid entry! %s",entry.Data()));
907 }
908 }
909 delete arr; arr=0;
910
0f678e35 911 AliDebug(2, Form("gridUrl: %s",gridUrl.Data()));
912 AliDebug(2, Form("user: %s",user.Data()));
913 AliDebug(2, Form("dbFolder: %s",dbFolder.Data()));
914 AliDebug(2, Form("s.e.: %s",se.Data()));
9e1ceb13 915
62032124 916 return new AliCDBGridParam(gridUrl.Data(), user.Data(), dbFolder.Data(), se.Data());
9e1ceb13 917}
918
919//_____________________________________________________________________________
920AliCDBStorage* AliCDBGridFactory::Create(const AliCDBParam* param) {
921// create AliCDBGrid storage instance from parameters
922
62032124 923 AliCDBGrid *grid = 0;
9e1ceb13 924 if (AliCDBGridParam::Class() == param->IsA()) {
62032124 925
9e1ceb13 926 const AliCDBGridParam* gridParam = (const AliCDBGridParam*) param;
62032124 927 grid = new AliCDBGrid(gridParam->GridUrl().Data(),
928 gridParam->GetUser().Data(),
929 gridParam->GetDBFolder().Data(),
930 gridParam->GetSE().Data());
9e1ceb13 931
9e1ceb13 932 }
933
c3a7b59a 934 if(!gGrid && grid) {
935 delete grid; grid=0;
936 }
937
62032124 938 return grid;
9e1ceb13 939}
940
941/////////////////////////////////////////////////////////////////////////////////////////////////
942// //
943// AliCDBGrid Parameter class // //
944// //
945/////////////////////////////////////////////////////////////////////////////////////////////////
946
947ClassImp(AliCDBGridParam)
948
949//_____________________________________________________________________________
62032124 950AliCDBGridParam::AliCDBGridParam():
951 AliCDBParam(),
952 fGridUrl(),
953 fUser(),
954 fDBFolder(),
955 fSE()
956 {
9e1ceb13 957// default constructor
958
959}
960
961//_____________________________________________________________________________
b05400be 962AliCDBGridParam::AliCDBGridParam(const char* gridUrl,
62032124 963 const char* user,
b05400be 964 const char* dbFolder,
9e1ceb13 965 const char* se):
62032124 966 AliCDBParam(),
b05400be 967 fGridUrl(gridUrl),
9e1ceb13 968 fUser(user),
b05400be 969 fDBFolder(dbFolder),
9e1ceb13 970 fSE(se)
971{
972// constructor
973
974 SetType("alien");
975
62032124 976 TString uri = Form("%s?User=%s?DBFolder=%s?SE=%s",
977 fGridUrl.Data(), fUser.Data(),
978 fDBFolder.Data(), fSE.Data());
979
980 SetURI(uri.Data());
9e1ceb13 981}
982
983//_____________________________________________________________________________
984AliCDBGridParam::~AliCDBGridParam() {
985// destructor
986
987}
988
989//_____________________________________________________________________________
990AliCDBParam* AliCDBGridParam::CloneParam() const {
991// clone parameter
992
62032124 993 return new AliCDBGridParam(fGridUrl.Data(), fUser.Data(),
994 fDBFolder.Data(), fSE.Data());
9e1ceb13 995}
996
997//_____________________________________________________________________________
998ULong_t AliCDBGridParam::Hash() const {
999// return Hash function
1000
b05400be 1001 return fGridUrl.Hash()+fUser.Hash()+fDBFolder.Hash()+fSE.Hash();
9e1ceb13 1002}
1003
1004//_____________________________________________________________________________
1005Bool_t AliCDBGridParam::IsEqual(const TObject* obj) const {
1006// check if this object is equal to AliCDBParam obj
1007
1008 if (this == obj) {
1009 return kTRUE;
1010 }
1011
1012 if (AliCDBGridParam::Class() != obj->IsA()) {
1013 return kFALSE;
1014 }
1015
1016 AliCDBGridParam* other = (AliCDBGridParam*) obj;
1017
b05400be 1018 if(fGridUrl != other->fGridUrl) return kFALSE;
9e1ceb13 1019 if(fUser != other->fUser) return kFALSE;
b05400be 1020 if(fDBFolder != other->fDBFolder) return kFALSE;
9e1ceb13 1021 if(fSE != other->fSE) return kFALSE;
1022 return kTRUE;
1023}
1024