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 88 of file TriggerConfigAccessBase.py.

Constructor & Destructor Documentation

◆ __init__()

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

Definition at line 89 of file TriggerConfigAccessBase.py.

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

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 50 of file TriggerConfigAccessBase.py.

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

◆ getConnectionParameters()

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

Definition at line 116 of file TriggerConfigAccessBase.py.

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

◆ 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 207 of file TriggerConfigAccessBase.py.

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

◆ getQueryDefinition()

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

Definition at line 246 of file TriggerConfigAccessBase.py.

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

◆ getResolvedFileName()

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

Definition at line 104 of file TriggerConfigAccessBase.py.

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

◆ getSchema()

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

Definition at line 162 of file TriggerConfigAccessBase.py.

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

◆ getWriteFilename()

def python.TriggerConfigAccessBase.ConfigDBLoader.getWriteFilename (   self)

Definition at line 338 of file TriggerConfigAccessBase.py.

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

◆ load()

def python.TriggerConfigAccessBase.ConfigDBLoader.load (   self)

Definition at line 258 of file TriggerConfigAccessBase.py.

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

◆ readSchemaVersion()

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

Definition at line 181 of file TriggerConfigAccessBase.py.

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

◆ 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 96 of file TriggerConfigAccessBase.py.

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

Member Data Documentation

◆ configType

python.TriggerConfigAccessBase.ConfigLoader.configType
inherited

Definition at line 49 of file TriggerConfigAccessBase.py.

◆ dbalias

python.TriggerConfigAccessBase.ConfigDBLoader.dbalias

Definition at line 91 of file TriggerConfigAccessBase.py.

◆ dbkey

python.TriggerConfigAccessBase.ConfigDBLoader.dbkey

Definition at line 92 of file TriggerConfigAccessBase.py.

◆ query

python.TriggerConfigAccessBase.ConfigDBLoader.query

Definition at line 93 of file TriggerConfigAccessBase.py.

◆ schema

python.TriggerConfigAccessBase.ConfigDBLoader.schema

Definition at line 94 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
max
constexpr double max()
Definition: ap_fixedTest.cxx:33
mergePhysValFiles.start
start
Definition: DataQuality/DataQualityUtils/scripts/mergePhysValFiles.py:13
python.processes.powheg.ZZj_MiNNLO.ZZj_MiNNLO.__init__
def __init__(self, base_directory, **kwargs)
Constructor: all process options are set here.
Definition: ZZj_MiNNLO.py:18
python.CaloAddPedShiftConfig.type
type
Definition: CaloAddPedShiftConfig.py:42
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.CaloAddPedShiftConfig.int
int
Definition: CaloAddPedShiftConfig.py:45
python.Bindings.keys
keys
Definition: Control/AthenaPython/python/Bindings.py:801
calibdata.commit
bool commit
Definition: calibdata.py:831
python.root_pickle.load
def load(f, use_proxy=1, key=None)
Definition: root_pickle.py:430
Trk::split
@ split
Definition: LayerMaterialProperties.h:38