ATLAS Offline Software
Public Member Functions | Static Public Member Functions | Public Attributes | List of all members
python.TriggerConfigAccessBase.ConfigDBLoader Class Reference
Inheritance diagram for python.TriggerConfigAccessBase.ConfigDBLoader:
Collaboration diagram for python.TriggerConfigAccessBase.ConfigDBLoader:

Public Member Functions

def __init__ (self, configType, dbalias, dbkey)
 
def setQuery (self, query)
 
def getQueryDefinition (self, schemaVersion)
 
def load (self)
 
def getWriteFilename (self)
 
def confirmConfigType (self, config)
 

Static Public Member Functions

def getResolvedFileName (filename, pathenv="")
 
def getConnectionParameters (dbalias)
 
def getSchema (connStr)
 
def readSchemaVersion (qdict, session)
 
def getCoralQuery (session, queryStr, qdict=None)
 

Public Attributes

 dbalias
 
 dbkey
 
 query
 
 schema
 
 configType
 

Detailed Description

Definition at line 89 of file TriggerConfigAccessBase.py.

Constructor & Destructor Documentation

◆ __init__()

def python.TriggerConfigAccessBase.ConfigDBLoader.__init__ (   self,
  configType,
  dbalias,
  dbkey 
)

Definition at line 90 of file TriggerConfigAccessBase.py.

90  def __init__(self, configType, dbalias, dbkey):
91  super().__init__(configType)
92  self.dbalias = dbalias
93  self.dbkey = dbkey
94  self.query = None
95  self.schema = None
96 

Member Function Documentation

◆ confirmConfigType()

def python.TriggerConfigAccessBase.ConfigLoader.confirmConfigType (   self,
  config 
)
inherited
checks that the in-file specification of the configuration type matches the expected type

Definition at line 51 of file TriggerConfigAccessBase.py.

51  def confirmConfigType(self,config):
52  """
53  checks that the in-file specification of the configuration type matches the expected type
54  """
55  if config['filetype'] != self.configType:
56  raise RuntimeError("Can not load file with filetype '%s' when expecting '%s'" % (config['filetype'], self.configType.filetype))
57 

◆ getConnectionParameters()

def python.TriggerConfigAccessBase.ConfigDBLoader.getConnectionParameters (   dbalias)
static

Definition at line 117 of file TriggerConfigAccessBase.py.

117  def getConnectionParameters(dbalias):
118  dblookupFile = ConfigDBLoader.getResolvedFileName("dblookup.xml", "CORAL_DBLOOKUP_PATH")
119  dbp = ET.parse(dblookupFile)
120  listOfServices = None
121  for logSvc in dbp.iter("logicalservice"):
122  if logSvc.attrib["name"] != dbalias:
123  continue
124  listOfServices = [ serv.attrib["name"] for serv in logSvc.iter("service") ]
125  if len(listOfServices) == 0:
126  raise RuntimeError("DB %s has no services listed in %s" % (dbalias, dblookupFile))
127  break
128  if listOfServices is None:
129  raise RuntimeError("DB %s not available in %s" % (dbalias, dblookupFile))
130 
131  if "FRONTIER_SERVER" not in os.environ:
132  # remove all frontier connnections in the list if the environment FRONTIER_SERVER variable does not exist
133  # this speeds up the resolution of the connection specification (dbalias)
134  listOfServices = [svc for svc in listOfServices if not svc.startswith("frontier:")]
135 
136  # now get the account and pw for oracle connections
137  credentials = odict().fromkeys(listOfServices)
138 
139  for svc in filter(lambda s : s.startswith("frontier:"), listOfServices):
140  credentials[svc] = dict()
141  credentials[svc]["user"] = svc
142  credentials[svc]["password"] = ""
143 
144  try:
145  authFile = ConfigDBLoader.getResolvedFileName("authentication.xml", "CORAL_AUTH_PATH")
146  except Exception as e:
147  log.warning("File authentication.xml is not available! Oracle connection cannot be established. Exception message is: %s",e)
148  else:
149  for svc in filter(lambda s : s.startswith("oracle:"), listOfServices):
150  ap = ET.parse(authFile)
151  count = 0
152  for con in filter( lambda c: c.attrib["name"]==svc, ap.iter("connection")):
153  credentials[svc] = dict([(par.attrib["name"],par.attrib["value"]) for par in con])
154  count += 1
155  if count==0:
156  raise RuntimeError("No credentials found for connection %s from service %s for db %s" % (con,svc,dbalias))
157  if count>1:
158  raise RuntimeError("More than 1 connection found in %s for service %s" % (authFile, svc))
159 
160  return credentials
161 

◆ getCoralQuery()

def python.TriggerConfigAccessBase.ConfigDBLoader.getCoralQuery (   session,
  queryStr,
  qdict = None 
)
static
Parse output, tables and condition from the query string into coral query object

Definition at line 208 of file TriggerConfigAccessBase.py.

208  def getCoralQuery(session, queryStr, qdict = None):
209  ''' Parse output, tables and condition from the query string into coral query object'''
210  query = session.nominalSchema().newQuery()
211 
212  if qdict is not None:
213  queryStr = queryStr.format(**qdict)
214 
215  # bind vars
216  bindVars = coral.AttributeList()
217  bindVarsInQuery = re.findall(r":(\w*)", queryStr)
218  if len(bindVarsInQuery) > 0 and qdict is None:
219  log.error("Query has bound-variable syntax but no value dictionary is provided. Query: %s", queryStr)
220  for k in bindVarsInQuery:
221  bindVars.extend(k, "int")
222  bindVars[k].setData(qdict[k])
223 
224  output = queryStr.split("SELECT")[1].split("FROM")[0]
225  for field in output.split(','):
226  query.addToOutputList(field)
227 
228  log.debug("Conversion for Coral of query: %s", queryStr)
229 
230  for table in queryStr.split("FROM")[1].split("WHERE")[0].split(","):
231  tableSplit = list(filter(None, table.split(" ")))
232  # Schema name is stripped from TableList in Coral query
233  query.addToTableList(tableSplit[0].split(".")[1], tableSplit[1])
234 
235  if "WHERE" in queryStr:
236  cond = queryStr.split("WHERE")[1]
237  m = re.match("(.*)(?i: ORDER *BY )(.*)", cond) # check for "order by" clause
238  if m:
239  where, order = m.groups()
240  query.setCondition(where, bindVars)
241  query.addToOrderList(order)
242  else:
243  query.setCondition(cond, bindVars)
244 
245  return query
246 

◆ getQueryDefinition()

def python.TriggerConfigAccessBase.ConfigDBLoader.getQueryDefinition (   self,
  schemaVersion 
)
Choose query based on schema version, based on TrigConf::TrigDBLoader::getQueryDefinition 

Definition at line 247 of file TriggerConfigAccessBase.py.

247  def getQueryDefinition(self, schemaVersion):
248  '''Choose query based on schema version, based on TrigConf::TrigDBLoader::getQueryDefinition '''
249  maxDefVersion = 0
250  for vkey in self.query.keys():
251  if vkey>maxDefVersion and vkey<=schemaVersion:
252  maxDefVersion = vkey
253 
254  if maxDefVersion == 0:
255  raise RuntimeError("No query available for schema version {0}".format(schemaVersion))
256 
257  return self.query[maxDefVersion]
258 

◆ getResolvedFileName()

def python.TriggerConfigAccessBase.ConfigDBLoader.getResolvedFileName (   filename,
  pathenv = "" 
)
static
looks for file, first absolute, then by resolving envvar pathenv

Definition at line 105 of file TriggerConfigAccessBase.py.

105  def getResolvedFileName(filename, pathenv=""):
106  """ looks for file, first absolute, then by resolving envvar pathenv"""
107  if os.access(filename,os.R_OK):
108  return filename
109  pathlist = os.getenv(pathenv,'').split(os.pathsep)
110  for path in pathlist:
111  f = os.path.join( path, filename )
112  if os.access( f, os.R_OK ):
113  return f
114  raise RuntimeError("Can't read file %s, neither locally nor in %s" % (filename, pathenv) )
115 

◆ getSchema()

def python.TriggerConfigAccessBase.ConfigDBLoader.getSchema (   connStr)
static
Read schema from connection string 

Definition at line 163 of file TriggerConfigAccessBase.py.

163  def getSchema(connStr):
164  ''' Read schema from connection string '''
165  if connStr.startswith("oracle:"):
166  [_, schema] = connStr.split("/")[-2:]
167  return schema
168 
169  if connStr.startswith("frontier:"):
170  import re
171  pattern = r"frontier://ATLF/\‍(\‍)/(.*)"
172  m = re.match(pattern, connStr)
173  if not m:
174  raise RuntimeError("connection string '%s' doesn't match the pattern '%s'?" % (connStr, pattern))
175  (schema, ) = m.groups()
176  return schema
177 
178  if connStr.startswith("sqlite_file:"):
179  raise NotImplementedError("Python-loading of trigger configuration from sqlite has not yet been implemented")
180 

◆ getWriteFilename()

def python.TriggerConfigAccessBase.ConfigDBLoader.getWriteFilename (   self)

Definition at line 339 of file TriggerConfigAccessBase.py.

339  def getWriteFilename(self):
340  return "{basename}_{schema}_{dbkey}.json".format(basename = self.configType.basename, schema = self.schema, dbkey = self.dbkey)
341 

◆ load()

def python.TriggerConfigAccessBase.ConfigDBLoader.load (   self)

Definition at line 259 of file TriggerConfigAccessBase.py.

259  def load(self):
260  credentials: dict[str,Any] = ConfigDBLoader.getConnectionParameters(self.dbalias)
261 
262  if not credentials:
263  log.error("No TriggerDB connections found for %s", self.dbalias)
264  raise RuntimeError(f"No TriggerDB connections found for {self.dbalias}")
265 
266  svc = coral.ConnectionService()
267  svcconfig = svc.configuration()
268  svcconfig.disablePoolAutomaticCleanUp()
269  svcconfig.setConnectionTimeOut(0)
270 
271  failureMode = 0
272  for credential in credentials:
273  log.debug("Trying credentials %s",credential)
274 
275  try:
276  session = svc.connect(credential, coral.access_ReadOnly)
277  except Exception as e:
278  log.warning("Failed to establish connection: %s",e)
279  failureMode = max(1, failureMode)
280  continue
281 
282  # Check that the FRONTIER_SERVER is set properly, if not reduce the retrial period and time out values
283  if 'FRONTIER_SERVER' in os.environ and os.environ['FRONTIER_SERVER']:
284  svcconfig.setConnectionRetrialPeriod(300)
285  svcconfig.setConnectionRetrialTimeOut(3600)
286  else:
287  svcconfig.setConnectionRetrialPeriod(1)
288  svcconfig.setConnectionRetrialTimeOut(1)
289 
290  try:
291  session.transaction().start(True) # readOnly
292  self.schema = ConfigDBLoader.getSchema(credential)
293  qdict = { "schema" : self.schema, "dbkey" : self.dbkey }
294 
295  # Choose query based on schema
296  schemaVersion = ConfigDBLoader.readSchemaVersion(qdict, session)
297  qstr = self.getQueryDefinition(schemaVersion)
298  # execute coral query
299  query = ConfigDBLoader.getCoralQuery(session, qstr, qdict)
300  cursor = query.execute()
301 
302  except Exception as e:
303  log.warning(f"DB query on {credential} failed to execute.")
304  log.warning("Exception message: %r", e)
305  failureMode = max(2, failureMode)
306  continue # to next source
307 
308  # Read query result
309  if not cursor.next():
310  # empty result
311  log.warning(f"DB query on {credential} returned empty result, likely due to non-existing key {self.dbkey}")
312  failureMode = 3
313  continue # to next source
314 
315  configblob = cursor.currentRow()[0].data()
316  if type(configblob) is not str:
317  configblob = configblob.readline()
318  config = json.loads(configblob, object_pairs_hook = odict)
319  session.transaction().commit()
320 
321  self.confirmConfigType(config)
322  return config
323 
324  if failureMode == 1:
325  log.error("TriggerDB query: could not connect to any source for %s", self.configType.basename)
326  log.error("Considered sources: %s", ", ".join(credentials))
327  raise RuntimeError("TriggerDB query: could not connect to any source", self.configType.basename)
328  if failureMode == 2:
329  log.error("Query failed due to wrong definition for %s", self.configType.basename)
330  log.error("DB query was: %s", qstr.format(**qdict))
331  raise RuntimeError("Query failed due to wrong definition", self.configType.basename)
332  elif failureMode == 3:
333  log.error("DB key %s does not exist for %s", self.dbkey, self.configType.basename)
334  raise KeyError("DB key does not exist", self.dbkey, self.configType.basename)
335  else:
336  raise RuntimeError("Query failed for unknown reason")
337 

◆ readSchemaVersion()

def python.TriggerConfigAccessBase.ConfigDBLoader.readSchemaVersion (   qdict,
  session 
)
static
Read schema version form database, based on TrigConf::TrigDBLoader::schemaVersion 

Definition at line 182 of file TriggerConfigAccessBase.py.

182  def readSchemaVersion(qdict, session):
183  ''' Read schema version form database, based on TrigConf::TrigDBLoader::schemaVersion '''
184  try:
185  q = "SELECT TS_TAG FROM {schema}.TRIGGER_SCHEMA TS"
186  query = ConfigDBLoader.getCoralQuery(session, q.format(**qdict))
187  cursor = query.execute()
188  cursor.next()
189 
190  versionTag = cursor.currentRow()[0].data()
191 
192  versionTagPrefix = "Trigger-Run3-Schema-v"
193  if not versionTag.startswith(versionTagPrefix):
194  raise RuntimeError( "Tag format error: Trigger schema version tag %s does not start with %s", versionTag, versionTagPrefix)
195 
196  vstr = versionTag[len(versionTagPrefix)]
197 
198  if not vstr.isdigit():
199  raise RuntimeError( "Invalid argument when interpreting the version part %s of schema tag %s is %s", vstr, versionTag, type(vstr))
200 
201  log.debug("Found schema version %s", vstr)
202  return int(vstr)
203 
204  except Exception as e:
205  log.warning("Failed to read schema version: %r", e)
206 

◆ setQuery()

def python.TriggerConfigAccessBase.ConfigDBLoader.setQuery (   self,
  query 
)
query template is a dictionary of queries, identified by schema version, 
similar to TrigConf::TrigDBMenuLoader::m_hltQueries and TrigConf::TrigDBMenuLoader::m_l1Queries

Definition at line 97 of file TriggerConfigAccessBase.py.

97  def setQuery(self, query):
98  """
99  query template is a dictionary of queries, identified by schema version,
100  similar to TrigConf::TrigDBMenuLoader::m_hltQueries and TrigConf::TrigDBMenuLoader::m_l1Queries
101  """
102  self.query = query
103 

Member Data Documentation

◆ configType

python.TriggerConfigAccessBase.ConfigLoader.configType
inherited

Definition at line 50 of file TriggerConfigAccessBase.py.

◆ dbalias

python.TriggerConfigAccessBase.ConfigDBLoader.dbalias

Definition at line 92 of file TriggerConfigAccessBase.py.

◆ dbkey

python.TriggerConfigAccessBase.ConfigDBLoader.dbkey

Definition at line 93 of file TriggerConfigAccessBase.py.

◆ query

python.TriggerConfigAccessBase.ConfigDBLoader.query

Definition at line 94 of file TriggerConfigAccessBase.py.

◆ schema

python.TriggerConfigAccessBase.ConfigDBLoader.schema

Definition at line 95 of file TriggerConfigAccessBase.py.


The documentation for this class was generated from the following file:
data
char data[hepevt_bytes_allocation_ATLAS]
Definition: HepEvt.cxx:11
vtune_athena.format
format
Definition: vtune_athena.py:14
CaloCellPos2Ntuple.int
int
Definition: CaloCellPos2Ntuple.py:24
max
constexpr double max()
Definition: ap_fixedTest.cxx:33
mergePhysValFiles.start
start
Definition: DataQuality/DataQualityUtils/scripts/mergePhysValFiles.py:14
covarianceTool.filter
filter
Definition: covarianceTool.py:514
histSizes.list
def list(name, path='/')
Definition: histSizes.py:38
TCS::join
std::string join(const std::vector< std::string > &v, const char c=',')
Definition: Trigger/TrigT1/L1Topo/L1TopoCommon/Root/StringUtils.cxx:10
python.processes.powheg.ZZ.ZZ.__init__
def __init__(self, base_directory, **kwargs)
Constructor: all process options are set here.
Definition: ZZ.py:18
python.CaloScaleNoiseConfig.type
type
Definition: CaloScaleNoiseConfig.py:78
python.Bindings.keys
keys
Definition: Control/AthenaPython/python/Bindings.py:798
calibdata.commit
bool commit
Definition: calibdata.py:832
python.root_pickle.load
def load(f, use_proxy=1, key=None)
Definition: root_pickle.py:476
Trk::split
@ split
Definition: LayerMaterialProperties.h:38