4 from AthenaCommon.Logging
import logging
8 log = logging.getLogger(
"TrigConfFrontier.py" )
13 '(serverurl=http://atlasfrontier-local.cern.ch:8000/atlr)(serverurl=http://atlasfrontier-ai.cern.ch:8000/atlr)'
15 ['http://atlasfrontier-local.cern.ch:8000/atlr','http://atlasfrontier-ai.cern.ch:8000/atlr']
17 from re
import findall
18 return findall(
r'\(serverurl=(.*?)\)',frontier_servers)
23 Expects input string to be a URL or $FRONTIER_SERVER
24 Returns an accessible URL or None"""
26 if re.match(
"http://",url):
29 if re.match(
r'\(serverurl=(.*?)\)',url):
34 log.setLevel(loglevel)
36 if len(url_list) == 0:
37 log.warning(
"Cannot find a valid frontier connection, will not return a Frontier cursor")
40 log.info(f
"Will use Frontier server at {urls}")
47 """Replaces the bound variables with the specified values,
48 disables variable binding
50 for var,val
in list(bindvars.items()):
51 if query.find(
":%s" % var)<0:
52 raise NameError(
"variable '%s' is not a bound variable in this query: %s" % (var, query) )
53 if isinstance (val, int):
54 query = query.replace(
":%s" % var,
"%s" % val)
56 query = query.replace(
":%s" % var,
"%r" % val)
57 log.debug(
"Resolving bound variable '%s' with %r", var,val)
58 log.debug(
"Resolved query: %s", query)
63 def __init__(self, urls, schema, refreshFlag=False, doDecode=True, retrieveZiplevel="zip", encoding="utf-8"):
64 self.
urls = [
str(x) +
"/Frontier" for x
in urls]
72 s =
"Using Frontier URL: %s\n" % self.
urls
73 s +=
"Schema: %s\n" % self.
schema
82 log.debug(
"Frontier URLs : %s", self.
urls)
84 log.debug(
"Query : %s", query)
86 import base64, zlib, urllib.request, urllib.error, urllib.parse
92 compQuery = zlib.compress(query.encode(
"utf-8"),9)
93 base64Query = base64.binascii.b2a_base64(compQuery).
decode(
"utf-8")
95 log.debug(
"Frontier Request : %s", encQuery)
96 frontierRequest=
"%s/type=frontier_request:1:DEFAULT&encoding=BLOB%s&p1=%s" % (url, self.
retrieveZiplevel, encQuery)
97 request = urllib.request.Request(frontierRequest)
99 request.add_header(
"pragma",
"no-cache")
101 frontierId =
"TrigConfFrontier 1.0"
102 request.add_header(
"X-Frontier-Id", frontierId)
104 queryStart = time.localtime()
105 log.debug(
"Query started: %s", time.strftime(
"%m/%d/%y %H:%M:%S %Z", queryStart))
108 result = urllib.request.urlopen(request,timeout=10).
read().
decode(
'utf-8')
111 queryEnd = time.localtime()
112 log.debug(
"Query ended: %s", time.strftime(
"%m/%d/%y %H:%M:%S %Z", queryEnd))
113 log.debug(
"Query time: %s [seconds]", (t2-t1))
114 log.debug(
"Result size: %i [seconds]", len(result))
118 except urllib.error.HTTPError:
119 log.warning(
"Problem with Frontier connection to %s trying next server", url)
120 except Exception
as err:
121 log.warning(
"Problem with the request {0}".
format(err))
123 raise Exception(
"All servers failed")
131 ''' Parse the response, looking for errors '''
132 from xml.dom.minidom
import parseString
135 globalError = dom.getElementsByTagName(
"global_error")
136 for node
in globalError:
137 raise Exception(node.getAttribute(
"msg"))
139 qualityList = dom.getElementsByTagName(
"quality")
140 for node
in qualityList:
141 if int(node.getAttribute(
"error")) > 0:
142 raise Exception(node.getAttribute(
"message"))
145 from xml.dom.minidom
import parseString
146 import base64, zlib, curses.ascii, re
149 dataList = dom.getElementsByTagName(
"data")
154 for data
in dataList:
155 for node
in data.childNodes:
157 if node.nodeName ==
"keepalive":
162 if node.data.strip() ==
"":
165 print (keepalives,
"keepalives received\n")
168 row = base64.decodebytes(node.data.encode())
170 row = zlib.decompress(row).
decode(
"ISO-8859-1")
173 if sys.version_info[0] < 3:
174 row = row.encode(
'ascii',
'xmlcharrefreplace')
176 endFirstRow = row.find(
'\x07')
177 firstRow = row[:endFirstRow]
179 if curses.ascii.isctrl(c):
180 firstRow = firstRow.replace(c,
' ')
181 fields = [x
for i,x
in enumerate(firstRow.split())
if i%2==0]
182 types = [x
for i,x
in enumerate(firstRow.split())
if i%2==1]
184 for _f,t
in zip(fields, types):
185 if t.startswith(
"NUMBER"):
186 if _f
in [
"HPR_VALUE",
"L1CI_GLOBAL_JET_SCALE",
"L1CI_GLOBAL_EM_SCALE"]:
194 log.debug(
"Fields : %r", fields)
195 log.debug(
"DB Types : %r", types)
196 log.debug(
"Python Types: %r", ptypes)
198 row = row[endFirstRow+1:]
200 row_h = row.rstrip(
'\x07')
203 row_h = re.sub(
"^.*?{",
"{",row_h)
205 row_h = row_h.replace(
"\x07\x06",
'.nNn.\x06')
211 pattern = re.compile(
"\x06\x00\x00..",flags=re.S)
212 row_h = pattern.sub(
'.xXx.',row_h)
213 row_h = row_h.replace(
"\x86",
'.xXx.')
215 row_h = row_h.split(
'.nNn.')
216 row_h = [r.split(
'.xXx.')
for r
in row_h]
220 if r[0]==
'': r[0:1]=[]
221 r = tuple([
t(v)
for t,v
in zip(ptypes,r)])
229 from TrigConfigSvc.TrigConfigSvcUtils
import interpretConnection
231 cursor =
getFrontierCursor( urls = connectionParameters[
'url'], schema = connectionParameters[
'schema'])
232 cursor.execute(query, bindvars)
233 log.info(
"Raw response:")
234 log.info(cursor.result)
235 cursor.decodeResult()
236 log.info(
"Decoded response:")
237 log.info(cursor.result[0][0])
238 if cursor.result[0][0] !=
'MC_pp_v7':
243 if __name__==
"__main__":
244 log = logging.getLogger(
"TrigConfFrontier.py" )
245 log.setLevel(logging.DEBUG)
247 dbalias =
"TRIGGERDBMC"
248 query =
"select distinct HPS.HPS_NAME from ATLAS_CONF_TRIGGER_RUN2_MC.HLT_PRESCALE_SET HPS where HPS.HPS_ID = :psk"
249 bindvars = {
"psk": 260 }