ATLAS Offline Software
Classes | Functions
python.AtlCoolLib Namespace Reference

Classes

class  coolTool
 
class  RangeList
 
class  TimeStampToRLB
 

Functions

def transConn (conn)
 
def forceOpen (conn)
 
def readOpen (conn)
 
def ensureFolder (db, folder, spec, desc, version=cool.FolderVersioning.SINGLE_VERSION)
 
def athenaDesc (runLumi, datatype)
 
def timeVal (val)
 
def timeString (iovkey)
 
def indirectOpen (coolstr, readOnly=True, debug=False)
 
def replicaList ()
 
def pathResolver (leaf, retFile=True)
 
def getHostname ()
 
def tests ()
 

Function Documentation

◆ athenaDesc()

def python.AtlCoolLib.athenaDesc (   runLumi,
  datatype 
)
Return the correct folder description string for Athena IOVDbSVc access
runLumi=True or False for timestamp
datatype= { AthenaAttributeList | CondAttrListCollection }

Definition at line 81 of file AtlCoolLib.py.

81 def athenaDesc(runLumi,datatype):
82  """
83  Return the correct folder description string for Athena IOVDbSVc access
84  runLumi=True or False for timestamp
85  datatype= { AthenaAttributeList | CondAttrListCollection }
86  """
87  if (runLumi):
88  desc='<timeStamp>run-lumi</timeStamp>'
89  else:
90  desc='<timeStamp>time</timeStamp>'
91  stype=71
92  clid=0
93  tname=''
94  if (datatype=='CondAttrListCollection'):
95  clid=1238547719
96  tname='CondAttrListCollection'
97  elif (datatype=='AthenaAttributeList'):
98  clid=40774348
99  tname='AthenaAttributeList'
100  elif (datatype=='CondAttrListVec'):
101  clid=55403898
102  tname='CondAttrListVec'
103 
104  desc+='<addrHeader><address_header service_type=\"'+str(stype)+'\" clid=\"'+str(clid)+'\" /></addrHeader><typeName>'+tname+'</typeName>'
105  return desc
106 

◆ ensureFolder()

def python.AtlCoolLib.ensureFolder (   db,
  folder,
  spec,
  desc,
  version = cool.FolderVersioning.SINGLE_VERSION 
)
Ensure folder exists, creating it if needed with given spec
Return COOL folder object

Definition at line 63 of file AtlCoolLib.py.

63 def ensureFolder(db,folder,spec,desc,version=cool.FolderVersioning.SINGLE_VERSION):
64  """
65  Ensure folder exists, creating it if needed with given spec
66  Return COOL folder object
67  """
68  if (not db.existsFolder(folder)):
69  print ('Attempting to create',folder,'with description',desc)
70  try:
71  # Deprecated/dropped: db.createFolder(folder,spec,desc,version,True)
72  folderSpec = cool.FolderSpecification(version,spec)
73  db.createFolder(folder,folderSpec,desc,True)
74  print ('Folder created')
75  except Exception as e:
76  print (e)
77  print ('Could not create folder',folder)
78  return None
79  return db.getFolder(folder)
80 

◆ forceOpen()

def python.AtlCoolLib.forceOpen (   conn)
Open COOL database with given connection, or force open if not possible
Return COOL database object, or None if cannot be opened
Database is opened in update mode

Definition at line 28 of file AtlCoolLib.py.

28 def forceOpen(conn):
29  """
30  Open COOL database with given connection, or force open if not possible
31  Return COOL database object, or None if cannot be opened
32  Database is opened in update mode
33  """
34  dbSvc=cool.DatabaseSvcFactory.databaseService()
35  conn2=transConn(conn)
36  try:
37  db=dbSvc.openDatabase(conn2,False)
38  except Exception as e:
39  print (e)
40  print ('Could not connect to',conn,'try to create it')
41  try:
42  db=dbSvc.createDatabase(conn2)
43  except Exception as e:
44  print (e)
45  print ('Could not create the database - give up')
46  return None
47  return db
48 

◆ getHostname()

def python.AtlCoolLib.getHostname ( )

Definition at line 235 of file AtlCoolLib.py.

235 def getHostname():
236  "Get the hostname including domain name if possible"
237  if ('ATLAS_CONDDB' in os.environ):
238  name=os.environ['ATLAS_CONDDB']
239  else:
240  try:
241  name=os.environ['HOSTNAME']
242  except Exception:
243  # try socket lib (for Mac) as HOSTNAME does not contain os.environ
244  import socket
245  try:
246  name=socket.getfqdn()
247  except Exception:
248  name='unknown'
249  # check name has a . (and doesn't end with .local, as macs default to),
250  # otherwise try command hostname --fqdn
251  if (name.find('.')>=0 and name[-6:]!=".local"):
252  return name
253  else:
254  if (name[-6:]==".local"):
255  print ("WARNING. Hostname is ",name, " which does not define a domain. Consider setting $ATLAS_CONDDB to avoid this")
256  return "unknown"
257 
258  import subprocess
259  try:
260  name=subprocess.check_output('hostname --fqdn').decode('utf-8')
261  except Exception:
262  name='unknown'
263 
264  #Calling hostname wrong will fill 'name' with error message
265  if (name.find('illegal')>-1 or name.find('unrecognized')>-1):
266  print ("WARNING. hostname --fqdn returned the following:",name)
267  print ("Consider setting $ATLAS_CONDDB to avoid this.")
268  return "unknown"
269  return name
270 
271 
272 # test code

◆ indirectOpen()

def python.AtlCoolLib.indirectOpen (   coolstr,
  readOnly = True,
  debug = False 
)
Obtain a connection to the database coolstr (e.g.
   COOLONL_INDET/OFLP200) using Oracle servers only, bypassing SQLite files
   and simulating the action of DBReplicaSvc to choose the correct one.
   Returns None in case a connection cannot be established.
   debug=True produces debug printout to show servers being tried

Definition at line 130 of file AtlCoolLib.py.

130 def indirectOpen(coolstr,readOnly=True,debug=False):
131  """Obtain a connection to the database coolstr (e.g.
132  COOLONL_INDET/OFLP200) using Oracle servers only, bypassing SQLite files
133  and simulating the action of DBReplicaSvc to choose the correct one.
134  Returns None in case a connection cannot be established.
135  debug=True produces debug printout to show servers being tried"""
136  dbSvc=cool.DatabaseSvcFactory.databaseService()
137  connstr=transConn(coolstr)
138 
139  # split the name into schema and dbinstance
140  splitname=connstr.split('/')
141  forceSQLite='ATLAS_COOL_FORCESQLITE' in os.environ
142  if (debug and forceSQLite):
143  print ("ATLAS_COOL_FORCESQLITE: Force consideration of SQLite replicas")
144  if (len(splitname)!=2 or readOnly is False or forceSQLite):
145  try:
146  db=dbSvc.openDatabase(connstr,readOnly)
147  except Exception as e:
148  # if writeable connection on readonly filesystem, get
149  # 'cannot be established error' - retry readonly
150  if (not readOnly and ('attempt to write a readonly database' in e.__repr__())):
151  print ("Writeable open failed - retry in readonly mode")
152  db=dbSvc.openDatabase(connstr,True)
153  else:
154  raise
155  return db
156  if (debug): print ("Trying to establish connection for %s from Oracle" % connstr)
157  schema=splitname[0]
158  dbinst=splitname[1]
159  # list of servers to try, first one at beginning
160  serverlist=replicaList()
161  if (debug): print (serverlist)
162  # will pop candidates from end of list - so reverse it first
163  serverlist.reverse()
164  while len(serverlist)>0:
165  server=serverlist.pop()
166  # deal with frontier server - use only if FRONTIER_SERVER is set
167  if server=='ATLF':
168  if ('FRONTIER_SERVER' in os.environ):
169  connstr='frontier://ATLF/();schema=ATLAS_%s;dbname=%s' % (schema,dbinst)
170  else:
171  # skip ATLF replica if FRONTIER_SERVER not set
172  continue
173  elif server=='atlas_dd': continue
174  else:
175  connstr='oracle://%s;schema=ATLAS_%s;dbname=%s' % (server,schema,dbinst)
176  if (debug): print ("Attempting to open %s" % connstr)
177  try:
178  dbconn=dbSvc.openDatabase(connstr)
179  if (dbconn is not None and dbconn.isOpen()):
180  if (debug): print ("Established connection to %s" % server)
181  return dbconn
182  if (debug): print ("Cannot connect to %s" % server)
183  except Exception:
184  if (debug): print ("Exception connecting to %s" % server)
185  # all replicas tried - give up
186  print ("All available replicas tried - giving up")
187  return None
188 

◆ pathResolver()

def python.AtlCoolLib.pathResolver (   leaf,
  retFile = True 
)
Find the file leaf using the DATAPATH variable to look for it
Return a read-only file object, or None if not found.
If retFile is false, just return the pathname.
Current directory takes precendence if file is there

Definition at line 213 of file AtlCoolLib.py.

213 def pathResolver(leaf,retFile=True):
214  """Find the file leaf using the DATAPATH variable to look for it
215  Return a read-only file object, or None if not found.
216  If retFile is false, just return the pathname.
217  Current directory takes precendence if file is there"""
218  try:
219  paths=os.environ['DATAPATH'].split(':')
220  except Exception:
221  # DATAPATH not set - just use current directory
222  paths=[]
223  paths=['.']+paths
224  for path in paths:
225  try:
226  os.stat(path+'/'+leaf)
227  if (retFile):
228  return open(path+'/'+leaf,'r')
229  else:
230  return path+'/'+leaf
231  except OSError:
232  pass
233  return None
234 

◆ readOpen()

def python.AtlCoolLib.readOpen (   conn)
Open COOL database with given connection for reading

Definition at line 49 of file AtlCoolLib.py.

49 def readOpen(conn):
50  """
51  Open COOL database with given connection for reading
52  """
53  dbSvc=cool.DatabaseSvcFactory.databaseService()
54  conn2=transConn(conn)
55  try:
56  db=dbSvc.openDatabase(conn2,True)
57  except Exception as e:
58  print (e)
59  print ('Could not connect to',conn)
60  return None
61  return db
62 

◆ replicaList()

def python.AtlCoolLib.replicaList ( )
Return list of Oracle database server names to try, mimicing action of
Athena DBReplicaSvc

Definition at line 189 of file AtlCoolLib.py.

189 def replicaList():
190  """Return list of Oracle database server names to try, mimicing action of
191  Athena DBReplicaSvc"""
192  configfile=pathResolver('dbreplica.config')
193  if configfile is None:
194  print ("Cannot find dbreplica.config")
195  return None
196  hostname=getHostname()
197  best=0
198  serverlist=[]
199  for line in configfile.readlines():
200  epos=line.find('=')
201  if (epos>0 and line[0]!="#"):
202  domains=line[0:epos].split()
203  for dom in domains:
204  if ((hostname[-len(dom):]==dom and len(dom)>best) or (best==0 and dom=='default')):
205  best=len(dom)
206  serverlist=line[epos+1:].split()
207  configfile.close()
208  if (len(serverlist)==0):
209  print ("No suitable servers found")
210  return None
211  return serverlist
212 

◆ tests()

def python.AtlCoolLib.tests ( )

Definition at line 273 of file AtlCoolLib.py.

273 def tests():
274  print ('AtlCoolLib tests')
275  db=forceOpen("TESTCOOL")
276  if (db is None):
277  print ('Could not create test database')
278  sys.exit(1)
279  spec=cool.RecordSpecification()
280  spec.extend('testString',cool.StorageType.String255)
281  folder=ensureFolder(db,'/TEST/TEST1',spec,athenaDesc(True,'CondAttrListCollection'),cool.FolderVersioning.MULTI_VERSION)
282  if (folder is None):
283  print ('Could not create test folder')
284  sys.exit(1)
285  print ('All done')
286  return
287 

◆ timeString()

def python.AtlCoolLib.timeString (   iovkey)

Definition at line 120 of file AtlCoolLib.py.

120 def timeString(iovkey):
121  "Convert the IOVkey (63 bit) to a string representing timestamp"
122  if (iovkey==cool.ValidityKeyMin):
123  return "ValidityKeyMin"
124  elif (iovkey==cool.ValidityKeyMax):
125  return "ValidityKeyMax"
126  else:
127  stime=int(iovkey/1000000000)
128  return time.asctime(time.gmtime(stime))+" UTC"
129 

◆ timeVal()

def python.AtlCoolLib.timeVal (   val)

Definition at line 107 of file AtlCoolLib.py.

107 def timeVal(val):
108  "Convert argument to time in seconds, treating as a literal or date"
109  try:
110  a=int(val)
111  return a
112  except ValueError:
113  try:
114  ts=time.strptime(val+'/UTC','%Y-%m-%d:%H:%M:%S/%Z')
115  return int(calendar.timegm(ts))
116  except ValueError:
117  print ("ERROR in time specification, use e.g. 2007-05-25:14:01:00")
118  sys.exit(-1)
119 

◆ transConn()

def python.AtlCoolLib.transConn (   conn)
Translate simple connection string (no slash) to mycool.db with given
instance, all others left alone

Definition at line 18 of file AtlCoolLib.py.

18 def transConn(conn):
19  """
20  Translate simple connection string (no slash) to mycool.db with given
21  instance, all others left alone
22  """
23  if ('/' not in conn):
24  return 'sqlite://X;schema=mycool.db;dbname='+conn
25  else:
26  return conn
27 
python.AtlCoolLib.forceOpen
def forceOpen(conn)
Definition: AtlCoolLib.py:28
python.AtlCoolLib.replicaList
def replicaList()
Definition: AtlCoolLib.py:189
AtlasMcWeight::decode
double decode(number_type binnedWeight)
Convert weight from unsigned to double.
Definition: AtlasMcWeight.cxx:32
python.AtlCoolLib.readOpen
def readOpen(conn)
Definition: AtlCoolLib.py:49
CaloCellPos2Ntuple.int
int
Definition: CaloCellPos2Ntuple.py:24
transConn
std::string transConn(const std::string &inconn)
Definition: openCoraCool.cxx:323
python.AtlCoolLib.tests
def tests()
Definition: AtlCoolLib.py:273
python.AtlCoolLib.athenaDesc
def athenaDesc(runLumi, datatype)
Definition: AtlCoolLib.py:81
python.AtlCoolLib.timeVal
def timeVal(val)
Definition: AtlCoolLib.py:107
python.AtlCoolLib.timeString
def timeString(iovkey)
Definition: AtlCoolLib.py:120
Trk::open
@ open
Definition: BinningType.h:40
python.AtlCoolLib.getHostname
def getHostname()
Definition: AtlCoolLib.py:235
python.AtlCoolLib.pathResolver
def pathResolver(leaf, retFile=True)
Definition: AtlCoolLib.py:213
python.AtlCoolLib.ensureFolder
def ensureFolder(db, folder, spec, desc, version=cool.FolderVersioning.SINGLE_VERSION)
Definition: AtlCoolLib.py:63
str
Definition: BTagTrackIpAccessor.cxx:11
python.AtlCoolLib.indirectOpen
def indirectOpen(coolstr, readOnly=True, debug=False)
Definition: AtlCoolLib.py:130
Trk::split
@ split
Definition: LayerMaterialProperties.h:38