ATLAS Offline Software
AtlRunQueryAMI.py
Go to the documentation of this file.
1 #!/bin/env python
2 
3 # Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
4 #
5 # ----------------------------------------------------------------
6 # Script : AtlRunQueryAMI.py
7 # Project: AtlRunQuery
8 # Purpose: Utility to retrieve information from AMI
9 # Authors: Andreas Hoecker (CERN), Joerg Stelzer (DESY)
10 # Created: Nov 10, 2009
11 # ----------------------------------------------------------------
12 #
13 
14 from __future__ import print_function
15 import re
16 
17 class ARQ_AMI:
18 
19  _amiclient = None
20  store = {}
21  all_periods = None
22 
23 
24  @classmethod
25  def getAmiClient(cls, amiconf = None, verbose = False):
26  """get ami client
27  param amiconf: name of file with AMI user and pw
28 
29  If a valid filename is specified, it tries to read the
30  username and password from there. If that does not succeed or
31  no filename is specified, voms based authentication is tried.
32  """
33  from pyAMI.pyAMI import AMI,pyAMIEndPoint
34  from os import stat,path
35 
36  useConfigFile = False
37  if amiconf:
38  if not path.exists(amiconf):
39  if verbose:
40  print ("WARNING: AMI config file", amiconf, "does not exist. Need to rely on valid voms proxy.")
41  elif stat(amiconf).st_mode & path.stat.S_IRUSR == 0:
42  if verbose:
43  print ("WARNING: AMI config file", amiconf, "exists but is not readable. Need to rely on valid voms proxy.")
44  else:
45  useConfigFile = True
46 
47  if useConfigFile:
48  pyAMIEndPoint.setType("replica")
49  ami=AMI()
50  ami.readConfig(amiconf)
51  if ami.checkAuth():
52  print ("... connecting to CERN AMI replica with user+pw")
53  return ami
54  pyAMIEndPoint.setType("main")
55  ami.certAuth()
56  if ami.checkAuth():
57  print ("... connecting to AMI main server with user+pw")
58  return ami
59 
60  print ("WARNING: Authentication in config file",amiconf,"not valid, check format, user, pw. Need to rely on valid voms proxy.")
61 
62 
63  pyAMIEndPoint.setType("replica")
64  ami=AMI()
65  if ami.checkAuth():
66  print ("... connecting to CERN replica using voms-proxy")
67  return ami
68 
69 
70  pyAMIEndPoint.setType("main")
71  ami.certAuth()
72  if ami.checkAuth():
73  print ("... connecting to main server using voms-proxy")
74  return ami
75 
76 
77  if verbose:
78  print ("WARNING voms-proxy authentication not valid. No access to AMI.")
79  return None
80 
81 
82  @classmethod
83  def amiclient(cls):
84  if cls._amiclient is None:
85  from os import getenv
86  from CoolRunQuery.utils.AtlRunQueryUtils import runsOnServer
87  if runsOnServer():
88  home = "/data/atrqadm/data/"
89  else:
90  home = getenv('HOME')
91  if not home:
92  home = '~'
93  conffilename = home + "/private/AMIConf.txt"
94  cls._amiclient = cls.getAmiClient(conffilename)
95  if cls._amiclient is None:
96  print ("ERROR: voms-proxy authentication not valid and no AMI configuration file",conffilename,"supplied. No access to AMI!")
97  cls._amiclient="No AMI"
98  return cls._amiclient
99 
100  @classmethod
102  try:
103  from pyAMI.pyAMI import AMI
104  amiclient = AMI()
105  amiclient.readConfig("./AMIConf.txt")
106  return amiclient
107  except ImportError:
108  print ('ERROR: could not load pyAMI')
109  return None
110 
111 
112  @classmethod
113  def amiexec(cls, cmdList):
114  try:
115  result = cls.amiclient().execute(cmdList)
116  return result.getDict()
117  except Exception as ex:
118  print ("AMI exception '",type(ex),"' occured")
119  import traceback
120  traceback.print_exc()
121  return {}
122 
123 
124  @classmethod
125  def get_periods_for_run(cls, run):
126  try:
127  run = int(run)
128  except ValueError:
129  return []
130  if run not in cls.store:
131  try:
132  print ('GetDataPeriodsForRun', '-runNumber=%i' % run)
133  #result = cls.amiclient().execute(['GetDataPeriodsForRun', '-runNumber=%i' % run])
134  result = cls.amiexec(['GetDataPeriodsForRun', '-runNumber=%i' % run])
135  #cls.store[run] = sorted([ (int(e['periodLevel']),e['period'],e['project']) for e in result.getDict()['Element_Info'].values() ])
136  cls.store[run] = sorted([ (int(e['periodLevel']),e['period'],e['project']) for e in result['Element_Info'].values() ])
137  except Exception:
138  print ("Exception")
139  cls.store[run] = []
140  return [x[1] for x in cls.store[run]]
141 
142 
143  @classmethod
144  def get_periods(cls, year, level):
145  try:
146  cmd = ['ListDataPeriods', '-createdSince=2009-01-01 00:00:00' ]
147  if year>2000:
148  cmd += [ '-projectName=data%02i%%' % (year-2000) ]
149  if level in [1,2,3]:
150  cmd += [ '-periodLevel=%i' % level ]
151  #result = cls.amiclient().execute(cmd)
152  result = cls.amiexec(cmd)
153  #rows = [ (e['period'], e['projectName']) for e in result.getDict()['Element_Info'].values() ]
154  rows = [ (e['period'], e['projectName']) for e in result['Element_Info'].values() ]
155  return sorted(rows)
156  except Exception:
157  import traceback
158  traceback.printExc()
159  return []
160 
161 
162  @classmethod
163  def get_all_periods(cls):
164  if cls.all_periods is not None:
165  return cls.all_periods
166  cls.all_periods = []
167  p = re.compile(r"(?P<period>(?P<periodletter>[A-Za-z]+)(?P<periodnumber>\d+)?)$")
168  try:
169  result = cls.get_periods(0, 0)
170  for period, projectName in result:
171  m = p.match(period)
172  if not m:
173  continue
174  year = int(projectName[4:6])
175  period_letter = m.group('periodletter')
176  period_number = int(m.group('periodnumber')) if m.group('periodnumber') else 0
177  if len(period_letter)!=1:
178  pc = 0
179  else:
180  pc = 10000*year + 100*(ord(period_letter.upper())-65) + period_number
181  cls.all_periods += [ ((year, period, pc), projectName+".period" + period) ]
182  cls.all_periods.sort()
183  except Exception:
184  import traceback
185  traceback.print_exc()
186  pass
187  return cls.all_periods
188 
189 
190  @classmethod
191  def get_runs(cls, period, year):
192  try:
193  cmd = ['GetRunsForDataPeriod', '-period=%s' % period]
194  if year>2000:
195  cmd += [ '-projectName=data%02i%%' % (year-2000) ]
196  #result = cls.amiclient().execute(cmd)
197  result = cls.amiexec(cmd)
198  #print ("amiCommand",' '.join(cmd) )
199  #r = sorted([ int(e['runNumber']) for e in result.getDict()['Element_Info'].values() ])
200  r = sorted([ int(e['runNumber']) for e in result['Element_Info'].values() ])
201  return r
202  except (ValueError, KeyError):
203  pass
204 
205 
206 
207 # for testing purpose
208 if __name__ == "__main__":
209 
210  choice = 1
211  while choice != 0:
212  print ("\n1 - periods for run")
213  print ("2 - runs for period (and year)")
214  print ("3 - periods (by year and/or level)")
215  print ("4 - all periods (different format)")
216  print ("5 - test AMI authentication")
217  print ("\n0 - exit\n")
218 
219  choice = input(" enter your choice: ")
220  choice = int(choice) if choice.isdigit() else 0
221  if choice==1:
222  run = int(input(" run number: "))
223  print (ARQ_AMI.get_periods_for_run( [run] ))
224  elif choice==2:
225  period = input(" period : ")
226  year = input(" year <RET> = all : ")
227  year = int(year) if year.isdigit() else 0
228  print (', '.join([str(x) for x in ARQ_AMI.get_runs(period, year)]))
229  elif choice==3:
230  year = input(" year <RET> = all : ")
231  year = int(year) if year.isdigit() else 0
232  period = input(" period [1|2|3] <RET> = all : ")
233  period = int(period) if period.isdigit() else 0
234  print (ARQ_AMI.get_periods(year, period))
235  elif choice==4:
236  print (ARQ_AMI.get_all_periods())
237  elif choice==5:
238  ami = ARQ_AMI.amiclient()
239  if ami!="No AMI":
240  print ("Successfully connected to AMI")
241  else:
242  print ("Failed to connect to AMI")
python.AtlRunQueryAMI.ARQ_AMI.get_all_periods
def get_all_periods(cls)
Definition: AtlRunQueryAMI.py:163
CaloCellPos2Ntuple.int
int
Definition: CaloCellPos2Ntuple.py:24
python.AtlRunQueryAMI.ARQ_AMI.get_periods
def get_periods(cls, year, level)
Definition: AtlRunQueryAMI.py:144
python.AtlRunQueryAMI.ARQ_AMI.getAmiClient
def getAmiClient(cls, amiconf=None, verbose=False)
Definition: AtlRunQueryAMI.py:25
python.utils.AtlRunQueryUtils.runsOnServer
def runsOnServer()
Definition: AtlRunQueryUtils.py:48
python.Bindings.values
values
Definition: Control/AthenaPython/python/Bindings.py:805
LArG4FSStartPointFilterLegacy.execute
execute
Definition: LArG4FSStartPointFilterLegacy.py:20
python.AtlRunQueryAMI.ARQ_AMI.get_runs
def get_runs(cls, period, year)
Definition: AtlRunQueryAMI.py:191
PlotPulseshapeFromCool.input
input
Definition: PlotPulseshapeFromCool.py:106
python.AtlRunQueryAMI.ARQ_AMI.all_periods
all_periods
Definition: AtlRunQueryAMI.py:21
beamspotman.stat
stat
Definition: beamspotman.py:266
DerivationFramework::TriggerMatchingUtils::sorted
std::vector< typename T::value_type > sorted(T begin, T end)
Helper function to create a sorted vector from an unsorted one.
python.AtlRunQueryAMI.ARQ_AMI
Definition: AtlRunQueryAMI.py:17
TCS::join
std::string join(const std::vector< std::string > &v, const char c=',')
Definition: Trigger/TrigT1/L1Topo/L1TopoCommon/Root/StringUtils.cxx:10
python.AtlRunQueryAMI.ARQ_AMI._amiclient
_amiclient
Definition: AtlRunQueryAMI.py:19
python.AtlRunQueryAMI.ARQ_AMI.OpenAMIConnection
def OpenAMIConnection(cls)
Definition: AtlRunQueryAMI.py:101
python.AtlRunQueryAMI.ARQ_AMI.get_periods_for_run
def get_periods_for_run(cls, run)
Definition: AtlRunQueryAMI.py:125
SCT_ConditionsAlgorithms::CoveritySafe::getenv
std::string getenv(const std::string &variableName)
get an environment variable
Definition: SCT_ConditionsUtilities.cxx:17
python.AtlRunQueryAMI.ARQ_AMI.amiexec
def amiexec(cls, cmdList)
Definition: AtlRunQueryAMI.py:113
python.CaloScaleNoiseConfig.type
type
Definition: CaloScaleNoiseConfig.py:78
str
Definition: BTagTrackIpAccessor.cxx:11
python.AtlRunQueryAMI.ARQ_AMI.store
dictionary store
Definition: AtlRunQueryAMI.py:20
python.AtlRunQueryAMI.ARQ_AMI.amiclient
def amiclient(cls)
Definition: AtlRunQueryAMI.py:83