3from AthenaConfiguration.ComponentAccumulator
import ComponentAccumulator, ConfigurationError
5from AthenaConfiguration.ComponentFactory
import CompFactory
6from AthenaConfiguration.AccumulatorCache
import AccumulatorCache
7from AthenaCommon.Logging
import logging
8from functools
import cache
10msg = logging.getLogger(
'IOVDbSvcCfg')
13 result = ComponentAccumulator()
14 result.addCondAlgo(CompFactory.CondInputLoader(**kwargs))
20 kwargs.setdefault(
'COOLSQLiteVetoPattern',
'/DBRelease/')
22 result = ComponentAccumulator()
23 result.addService(CompFactory.DBReplicaSvc(**kwargs))
32 kwargs.setdefault(
'OnlineMode', flags.Common.isOnline)
33 kwargs.setdefault(
'dbConnection', flags.IOVDb.DBConnection)
35 kwargs.setdefault(
'DBInstance', flags.IOVDb.DatabaseInstance)
37 if 'FRONTIER_SERVER' in os.environ.keys()
and os.environ[
'FRONTIER_SERVER'] !=
'':
38 kwargs.setdefault(
'CacheAlign', 3)
41 if flags.Common.isOnline
and flags.Trigger.Online.isPartition:
42 kwargs[
'CacheAlign'] = 0
43 kwargs[
'CacheRun'] = 0
44 kwargs[
'CacheTime'] = 0
46 kwargs.setdefault(
'GlobalTag', flags.IOVDb.GlobalTag)
47 if 'Folders' in kwargs:
48 kwargs[
'Folders'] = [
'/TagInfo<metaOnly/>'] + kwargs[
'Folders']
50 kwargs.setdefault(
'Folders', [
'/TagInfo<metaOnly/>'])
53 if flags.IOVDb.UseCREST:
54 kwargs.setdefault(
'Source',
'CREST')
57 result.addService(CompFactory.IOVDbSvc(**kwargs), primary=
True)
60 from AthenaPoolCnvSvc.PoolCommonConfig
import PoolSvcCfg
61 result.merge(PoolSvcCfg(flags, withCatalogs=
True))
62 if flags.MP.UseSharedReader
or flags.MP.UseSharedWriter:
63 from AthenaPoolCnvSvc.PoolCommonConfig
import AthenaPoolSharedIOCnvSvcCfg
64 result.merge(AthenaPoolSharedIOCnvSvcCfg(flags))
66 from AthenaPoolCnvSvc.PoolCommonConfig
import AthenaPoolCnvSvcCfg
67 result.merge(AthenaPoolCnvSvcCfg(flags))
68 result.addService(CompFactory.CondSvc())
69 result.addService(CompFactory.ProxyProviderSvc(ProviderNames=[
'IOVDbSvc']))
71 if not flags.Input.isMC:
75 from EventInfoMgt.TagInfoMgrConfig
import TagInfoMgrCfg
76 result.merge(TagInfoMgrCfg(flags))
79 from AthenaServices.MetaDataSvcConfig
import MetaDataSvcCfg
80 result.merge(MetaDataSvcCfg(flags, [
'IOVDbMetaDataTool']))
86def addFolders(flags, folderStrings, detDb=None, className=None, extensible=False, tag=None, db=None, modifiers=''):
89 if flags.IOVDb.UseCREST:
90 tagString =
'<ctag>%s</ctag>' % tag
92 tagString =
'<tag>%s</tag>' % tag
95 if isinstance(folderStrings, str):
96 return addFolderList(flags, ((folderStrings + tagString, detDb, className),), extensible, db, modifiers)
99 folderDefinitions = []
101 for folderString
in folderStrings:
102 folderDefinitions.append((folderString + tagString, detDb, className))
104 return addFolderList(flags, folderDefinitions, extensible, db, modifiers)
107def addFolderList(flags, listOfFolderInfoTuple, extensible=False, db=None, modifiers=''):
108 """Add access to the given set of folders, in the identified subdetector schema.
109 FolerInfoTuple consists of (foldername,detDB,classname)
111 If EXTENSIBLE is set, then if we access an open-ended IOV at the end of the list,
112 the end time for this range will be set to just past the current event.
113 Subsequent accesses will update this end time for subsequent events.
114 This allows the possibility of later adding a new IOV using IOVSvc::setRange."""
117 if flags.IOVDb.UseCREST:
121 flags.IOVDb.SqliteFolders,
122 flags.IOVDb.DatabaseInstance)
124 for (fs, detDb, className)
in listOfFolderInfoTuple:
127 if className
is not None:
128 loadFolders.add((className, fse))
130 if fse
in sqliteFolders:
131 msg.warning(f
'Reading folder {fs} from local storage, bypassing production database')
132 fs+=sqliteFolders[fse]
133 elif detDb
is not None and fs.find(
'<db>') == -1:
138 dbName = flags.IOVDb.DatabaseInstance
139 if detDb
in _dblist.keys():
140 fs = f
'<db>{_dblist[detDb]}/{dbName}</db> {fs}'
141 elif os.access(detDb, os.R_OK):
143 fs = f
'<db>sqlite://;schema={detDb};dbname={dbName}</db> {fs}'
144 elif detDb.startswith(
"crest_fs:"):
145 fs = f
'<db>{detDb}</db> {fs}'
147 raise ConfigurationError(f
'Error, db shorthand {detDb} not known, nor found as sqlite file')
151 fs = fs +
'<extensible/>'
161 result.getPrimary().Folders+=folders
163 result.getCondAlgo(
'CondInputLoader').Load |= loadFolders
165 if flags.IOVDb.CleanerRingSize > 0:
167 cleanerSvc = CompFactory.Athena.DelayedConditionsCleanerSvc(RingSize=flags.IOVDb.CleanerRingSize)
168 result.addService(cleanerSvc)
169 result.addService(CompFactory.Athena.ConditionsCleanerSvc(CleanerSvc=cleanerSvc))
175def addFoldersSplitOnline(flags, detDb, onlineFolders, offlineFolders, className=None, extensible=False, addMCString='_OFL', splitMC=False, tag=None, forceDb=None, modifiers=''):
176 """Add access to given folder, using either online_folder or offline_folder. For MC, add addMCString as a postfix (default is _OFL)"""
178 if flags.Common.isOnline
and not flags.Input.isMC:
179 folders = onlineFolders
180 elif splitMC
and not flags.Input.isMC:
181 folders = onlineFolders
184 detDb = detDb + addMCString
185 folders = offlineFolders
187 return addFolders(flags, folders, detDb, className, extensible, tag=tag, db=forceDb, modifiers=modifiers)
191 'INDET':
'COOLONL_INDET',
192 'INDET_ONL':
'COOLONL_INDET',
193 'PIXEL':
'COOLONL_PIXEL',
194 'PIXEL_ONL':
'COOLONL_PIXEL',
196 'SCT_ONL':
'COOLONL_SCT',
198 'TRT_ONL':
'COOLONL_TRT',
200 'LAR_ONL':
'COOLONL_LAR',
201 'TILE':
'COOLONL_TILE',
202 'TILE_ONL':
'COOLONL_TILE',
203 'MUON':
'COOLONL_MUON',
204 'MUON_ONL':
'COOLONL_MUON',
205 'MUONALIGN':
'COOLONL_MUONALIGN',
206 'MUONALIGN_ONL':
'COOLONL_MUONALIGN',
208 'MDT_ONL':
'COOLONL_MDT',
210 'RPC_ONL':
'COOLONL_RPC',
212 'TGC_ONL':
'COOLONL_TGC',
214 'CSC_ONL':
'COOLONL_CSC',
215 'TDAQ':
'COOLONL_TDAQ',
216 'TDAQ_ONL':
'COOLONL_TDAQ',
217 'GLOBAL':
'COOLONL_GLOBAL',
218 'GLOBAL_ONL':
'COOLONL_GLOBAL',
219 'TRIGGER':
'COOLONL_TRIGGER',
220 'TRIGGER_ONL':
'COOLONL_TRIGGER',
221 'CALO':
'COOLONL_CALO',
222 'CALO_ONL':
'COOLONL_CALO',
224 'FWD_ONL':
'COOLONL_FWD',
225 'INDET_OFL':
'COOLOFL_INDET',
226 'PIXEL_OFL':
'COOLOFL_PIXEL',
227 'SCT_OFL':
'COOLOFL_SCT',
228 'TRT_OFL':
'COOLOFL_TRT',
229 'LAR_OFL':
'COOLOFL_LAR',
230 'TILE_OFL':
'COOLOFL_TILE',
231 'MUON_OFL':
'COOLOFL_MUON',
232 'MUONALIGN_OFL':
'COOLOFL_MUONALIGN',
233 'MDT_OFL':
'COOLOFL_MDT',
234 'RPC_OFL':
'COOLOFL_RPC',
235 'TGC_OFL':
'COOLOFL_TGC',
236 'CSC_OFL':
'COOLOFL_CSC',
237 'TDAQ_OFL':
'COOLOFL_TDAQ',
238 'DCS_OFL':
'COOLOFL_DCS',
239 'GLOBAL_OFL':
'COOLOFL_GLOBAL',
240 'TRIGGER_OFL':
'COOLOFL_TRIGGER',
241 'CALO_OFL':
'COOLOFL_CALO',
242 'FWD_OFL':
'COOLOFL_FWD'
247 """Add xml override for the specified folder (folder-level tag, forceRunNumber, ...)"""
250 suffix = f
' <db>{db}</db>'
251 return IOVDbSvcCfg(flags, overrideTags=(f
'<prefix>{folder}</prefix> <{tagType}>{tag}</{tagType}>{suffix}',))
255 """Extract the folder name (non-XML text) from a IOVDbSvc.Folders entry"""
259 while ix < len(folderString):
260 if (folderString[ix] ==
'<' and xmlTag ==
''):
261 ix2 = folderString.find(
'>', ix)
263 xmlTag = folderString[ix + 1 : ix2].
strip()
265 elif folderString[ix:ix+2] ==
'</' and xmlTag !=
'':
266 ix2 = folderString.find(
'>', ix)
271 ix2 = folderString.find(
'<', ix)
273 ix2 = len(folderString)
275 folderName = folderName + folderString[ix : ix2]
277 return folderName.strip()
282 if sqliteInput ==
"":
return dict()
284 if isinstance(takeFolders, str):
285 takeFolders=[takeFolders,]
286 dbStr=
"sqlite://;schema="+ sqliteInput+
";dbname="+databaseInstance
287 from PyCool
import cool
288 dbSvc = cool.DatabaseSvcFactory.databaseService()
289 db = dbSvc.openDatabase(dbStr)
290 nodelist=db.listAllNodes()
291 for node
in nodelist:
292 if db.existsFolder(node):
293 if (len(takeFolders)>0
and str(node)
not in takeFolders):
continue
294 connStr=
"<db>"+dbStr+
"</db>"
296 if f.versioningMode
is not cool.FolderVersioning.SINGLE_VERSION:
299 connStr+=
"<tag>"+tags[0]+
"</tag>"
300 sqliteFolders[str(node)]=connStr
303 if len(takeFolders)>0:
304 missedFolders=
set(takeFolders)-
set(sqliteFolders.keys())
305 if len(missedFolders):
306 msg.error(
"The following folders were requested via the flag IOVSvc.sqliteFolder but not found in the sqlite file %s",(sqliteInput))
307 for f
in missedFolders:
310 msg.info(
"The following folders/tags are read from sqlite:")
311 for v
in sqliteFolders.items():
312 msg.info(
"\t"+str(v))
319 """The CREST version of getSqliteContent.
320 Signficantly more complicated because CREST has no folder (only tags)
321 If there is a global tag table defined in the local crest directly,
323 Otherwise, open the production DB and guess the tag based on the first part of
324 the folder name. Works only if the tag-naming convention is respected:
325 Folder /LAR/ElecCalib/Ramps becomes LARElecCalibRamps-suffix
328 crestDir=flags.IOVDb.SqliteInput
329 if crestDir ==
"":
return dict()
330 requestedTags=flags.IOVDb.SqliteFolders
331 localCrestFolders=dict()
333 if len(crestDir.split(
":"))==1:
334 crestDir=
"crest_fs:"+crestDir
336 missedTags=
set(requestedTags)
340 localdb = chai.Database(crestDir)
341 except Exception
as e:
342 msg.error(
"Failed to connect to crest directoy %s",crestDir)
349 localGTs=localdb.find_global_tags()
355 msg.info(
"Found exactly one global tag in local crest directory: [%s] Try to use it.",localGT)
356 elif len(localGTs)>1:
357 if flags.IOVDb.GlobalTag
in localGTs:
358 localGT=flags.IOVDb.GlobalTag
359 msg.info(
"Global tag %s also defined in local crest directory. Try to use it.",flags.IOVDb.GlobalTag)
361 msg.warning(
"More than one global tag found in crest directory [%s], none matches the global conditions tag %s",
362 crestDir,flags.IOVDb.GlobalTag)
364 gt=localdb.get_global_tag(localGT)
365 resolvedTags= gt.resolve_all_tags()
366 for gt2ft
in resolvedTags.items():
369 if len(requestedTags)>0
and lt
not in requestedTags:
continue
370 localCrestFolders[f]=
"<db>"+crestDir+
"</db><ctag>"+lt+
"</ctag>"
371 missedTags.discard(lt)
374 msg.warning(
"No (usable) global tag found in local crest directory %s. Open production db, try to guess folder-tag relation")
375 localtags=
set(localdb.find_tags())
378 proddb=chai.Database(
"crest:"+flags.IOVDb.DBConnection)
379 except Exception
as e:
380 msg.error(
"Failed to connect to crest server %s",flags.IOVDb.CrestServer)
383 gt=proddb.get_global_tag(flags.IOVDb.GlobalTag)
385 resolvedTags=gt.resolve_all_tags()
386 folderstubToFolderMap={}
387 tbl=str.maketrans(
".",
"-")
388 for gt2ft
in resolvedTags.items():
391 if ft.startswith(
"UPGRADE_"): ft=ft[8:]
392 folderstub=
"".join(f.split(
"/")).lower()
393 tagstub=ft.translate(tbl).
split(
"-")[0].lower()
394 if (tagstub != folderstub):
395 msg.warning(
"Folder-tag %s of folder %s in the production DB does not follow tag naming convention",ft, f)
397 folderstubToFolderMap[folderstub]=f
400 if len(requestedTags)>0
and lt
not in requestedTags:
continue
401 tagstub=lt.translate(tbl).
split(
"-")[0].lower()
402 if tagstub
in folderstubToFolderMap:
403 f=folderstubToFolderMap[tagstub]
404 localCrestFolders[f]=
"<db>"+crestDir+
"</db><ctag>"+lt+
"</ctag>"
405 missedTags.discard(lt)
407 msg.warning(
"Cannot guess the folder of the tag %s in the local CREST directory %s",lt,crestDir)
408 msg.warning(
"Ignoring this tag")
411 msg.info(
"The following folders/tags are read from local crest directory:")
412 for v
in localCrestFolders.items():
413 msg.info(
"\t"+str(v))
415 msg.error(
"The following local Crest tags have been explicitly requested via the flag IOVSvc.sqliteFolder but not found in the local crest directory %s",(crestDir))
416 for mt
in missedTags:
419 return localCrestFolders
430 "Block use of specified conditions DB folder so data can be read from elsewhere"
431 msg.info(
"Trying to remove folder [%s] from IOVDbSvc.Folders",folder)
432 iovdbsvc=ca.getService(
"IOVDbSvc")
433 oldLen=len(iovdbsvc.Folders)
434 iovdbsvc.Folders=[x
for x
in iovdbsvc.Folders
if x.find(folder)==-1]
435 newLen=len(iovdbsvc.Folders)
437 msg.warning(
"Folder [%s] not found in IOVDbSvc.Folder",folder)
439 elif (oldLen-newLen>1):
440 msg.warning(
"Folder string [%s] matched more than one folder, removed %i folders",folder,oldLen-newLen)
443 condInputLoader=ca.getCondAlgo(
"CondInputLoader")
444 condInputLoader.Load=
set([x
for x
in condInputLoader.Load
if x[1].
find(folder)==-1])
451 if connStr.startswith(
"http"):
452 connStr1=
"crest:"+connStr
454 connStr1=
"crest_fs:"+connStr
457 db=chai.Database(connStr1)
458 allGlobalTags=
set(db.find_global_tags())
459 except chai._chai.NotFoundError
as e:
461 msg.error(f
"Could not load data from crest URL {connStr}")
463 except chai._chai.BackendError
as e:
465 msg.error(f
"Could not load data from crest URL {connStr}")
468 if fail:
raise ConfigurationError()
470 if currGlobalTag
not in allGlobalTags:
471 from difflib
import get_close_matches
472 m1=get_close_matches(currGlobalTag,allGlobalTags,1)
473 msg.error(f
"Global tag {currGlobalTag} does not exist"+(f
". Did you mean '{m1[0]}'?" if m1
else ""))
474 raise ConfigurationError()
481if __name__ ==
'__main__':
482 from AthenaConfiguration.AllConfigFlags
import initConfigFlags
483 from AthenaConfiguration.TestDefaults
import defaultTestFiles
484 flags = initConfigFlags()
485 flags.Input.Files = defaultTestFiles.RAW_RUN2
490 with open(
'test.pkl',
'wb')
as f:
std::string find(const std::string &s)
return a remapped string
std::vector< std::string > split(const std::string &s, const std::string &t=":")
addOverride(flags, folder, tag, tagType="tag", db=None)
addFolderList(flags, listOfFolderInfoTuple, extensible=False, db=None, modifiers='')
addFolders(flags, folderStrings, detDb=None, className=None, extensible=False, tag=None, db=None, modifiers='')
checkGlobalTag(connStr, currGlobalTag)
CondInputLoaderCfg(flags, **kwargs)
addFoldersSplitOnline(flags, detDb, onlineFolders, offlineFolders, className=None, extensible=False, addMCString='_OFL', splitMC=False, tag=None, forceDb=None, modifiers='')
_extractFolder(folderString)
IOVDbSvcCfg(flags, **kwargs)
getCrestDirContent(flags)
DBReplicaSvcCfg(flags, vetoDBRelease=False, **kwargs)
getSqliteContent(sqliteInput, takeFolders, databaseInstance)