ATLAS Offline Software
Loading...
Searching...
No Matches
python.AtlCoolLib Namespace Reference

Classes

class  coolTool
class  RangeList
class  TimeStampToRLB

Functions

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

Detailed Description

Module defining utilities for ATLAS command line/python use of COOL

Function Documentation

◆ athenaDesc()

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 80 of file AtlCoolLib.py.

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

◆ ensureFolder()

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 62 of file AtlCoolLib.py.

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

◆ forceOpen()

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 27 of file AtlCoolLib.py.

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

◆ getHostname()

python.AtlCoolLib.getHostname ( )

Definition at line 234 of file AtlCoolLib.py.

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

◆ indirectOpen()

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 129 of file AtlCoolLib.py.

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

◆ pathResolver()

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 212 of file AtlCoolLib.py.

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

◆ readOpen()

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

Definition at line 48 of file AtlCoolLib.py.

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

◆ replicaList()

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

Definition at line 188 of file AtlCoolLib.py.

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

◆ tests()

python.AtlCoolLib.tests ( )

Definition at line 272 of file AtlCoolLib.py.

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

◆ timeString()

python.AtlCoolLib.timeString ( iovkey)

Definition at line 119 of file AtlCoolLib.py.

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

◆ timeVal()

python.AtlCoolLib.timeVal ( val)

Definition at line 106 of file AtlCoolLib.py.

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

◆ transConn()

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

Definition at line 17 of file AtlCoolLib.py.

17def transConn(conn):
18 """
19 Translate simple connection string (no slash) to mycool.db with given
20 instance, all others left alone
21 """
22 if ('/' not in conn):
23 return 'sqlite://X;schema=mycool.db;dbname='+conn
24 else:
25 return conn
26