CMS 3D CMS Logo

FrontierCondition_GT_autoExpress_cfi.py
Go to the documentation of this file.
1 from __future__ import print_function
2 import FWCore.ParameterSet.Config as cms
4 
5 # Default Express GT: it is the GT that will be used in case we are not able
6 # to retrieve the one used at Tier0.
7 # It should be kept in synch with Express processing at Tier0: what the url
8 # https://cmsweb.cern.ch/t0wmadatasvc/prod/express_config
9 # would tell you.
10 GlobalTag.globaltag = "103X_dataRun2_Express_v2"
11 
12 # ===== auto -> Automatically get the GT string from current Tier0 configuration via a Tier0Das call.
13 # This needs a valid proxy to access the cern.ch network from the .cms one.
14 #
15 auto=False
16 
17 # The implementation of the class is reused from the condition upload service.
18 #TODO: make this class a common utility under Conditions or Config.DP
19 import json
20 import os
21 import pycurl
22 import subprocess
23 import sys
24 import time
25 
26 tier0Url = 'https://cmsweb.cern.ch/t0wmadatasvc/prod/'
27 
29  '''Tier0 exception.
30  '''
31 
32  def __init__(self, message):
33  self.args = (message, )
34 
35 def unique(seq, keepstr=True):
36  t = type(seq)
37  if t in (unicode, str):
38  t = (list, t('').join)[bool(keepstr)]
39  try:
40  remaining = set(seq)
41  seen = set()
42  return t(c for c in seq if (c in remaining and not remaining.remove(c)))
43  except TypeError: # hashing didn't work, see if seq is sortable
44  try:
45  from itertools import groupby
46  s = sorted(enumerate(seq),key=lambda i_v1:(i_v1[1],i_v1[0]))
47  return t(next(g) for k,g in groupby(s, lambda i_v: i_v[1]))
48  except: # not sortable, use brute force
49  seen = []
50  return t(c for c in seq if not (c in seen or seen.append(c)))
51 
53 
54  def __init__( self, uri, timeOut, retries, retryPeriod, proxy, debug ):
55  """
56  Parameters:
57  uri: Tier0DataSvc URI;
58  timeOut: time out for Tier0DataSvc HTTPS calls;
59  retries: maximum retries for Tier0DataSvc HTTPS calls;
60  retryPeriod: sleep time between two Tier0DataSvc HTTPS calls;
61  proxy: HTTP proxy for accessing Tier0DataSvc HTTPS calls;
62  debug: if set to True, enables debug information.
63  """
64  self._uri = uri
65  self._timeOut = timeOut
66  self._retries = retries
67  self._retryPeriod = retryPeriod
68  self._proxy = proxy
69  self._debug = debug
70 
71  def setDebug( self ):
72  self._debug = True
73 
74  def unsetDebug( self ):
75  self._debug = False
76 
77  def setProxy( self, proxy ):
78  self._proxy = proxy
79 
80  def _queryTier0DataSvc( self, url ):
81  """
82  Queries Tier0DataSvc.
83  url: Tier0DataSvc URL.
84  @returns: dictionary, from whence the required information must be retrieved according to the API call.
85  Raises if connection error, bad response, or timeout after retries occur.
86  """
87 
88  userAgent = "User-Agent: DQMIntegration/2.0 python/%d.%d.%d PycURL/%s" % ( sys.version_info[ :3 ] + ( pycurl.version_info()[ 1 ], ) )
89 
90  proxy = ""
91  if self._proxy: proxy = ' --proxy %s ' % self._proxy
92 
93  debug = " -s -S "
94  if self._debug: debug = " -v "
95 
96  cmd = '/usr/bin/curl -k -L --user-agent "%s" %s --connect-timeout %i --retry %i %s %s ' % (userAgent, proxy, self._timeOut, self._retries, debug, url)
97 
98  process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
99  (stdoutdata, stderrdata) = process.communicate()
100  retcode = process.returncode
101 
102  if retcode != 0 or stderrdata:
103  msg = "looks like curl returned an error: retcode=%s" % (retcode,)
104  msg += ' msg = "'+str(stderrdata)+'"'
105  raise Tier0Error(msg)
106 
107  return json.loads( ''.join(stdoutdata).replace( "'", '"').replace(' None', ' "None"') )
108 
109  def getFirstSafeRun( self ):
110  """
111  Queries Tier0DataSvc to get the first condition safe run.
112  Parameters:
113  @returns: integer, the run number.
114  Raises if connection error, bad response, timeout after retries occur, or if the run number is not available.
115  """
116  firstConditionSafeRunAPI = "firstconditionsaferun"
117  safeRunDict = self._queryTier0DataSvc( os.path.join( self._uri, firstConditionSafeRunAPI ) )
118  if safeRunDict is None:
119  errStr = """First condition safe run is not available in Tier0DataSvc from URL \"%s\" """ %( os.path.join( self._uri, firstConditionSafeRunAPI ), )
120  if self._proxy:
121  errStr += """ using proxy \"%s\".""" %( str( self._proxy ), )
122  raise Tier0Error( errStr )
123  return int(safeRunDict['result'][0])
124 
125  def getGlobalTag( self, config ):
126  """
127  Queries Tier0DataSvc to get the most recent Global Tag for a given workflow.
128  Parameters:
129  config: Tier0DataSvc API call for the workflow to be looked for;
130  @returns: a string with the Global Tag name.
131  Raises if connection error, bad response, timeout after retries occur, or if no Global Tags are available.
132  """
133  data = self._queryTier0DataSvc( os.path.join( self._uri, config ) )
134  gtnames = sorted(unique( [ str( di[ 'global_tag' ] ) for di in data['result'] if di[ 'global_tag' ] is not None ] ))
135  try:
136  recentGT = gtnames[-1]
137  return recentGT
138  except IndexError:
139  errStr = """No Global Tags for \"%s\" are available in Tier0DataSvc from URL \"%s\" """ %( config, os.path.join( self._uri, config ) )
140  if self._proxy:
141  errStr += """ using proxy \"%s\".""" %( str( self._proxy ), )
142  raise Tier0Error( errStr )
143 
144 if auto:
145  proxyurl = None
146  if 'http_proxy' in os.environ:
147  proxyurl = os.environ[ 'http_proxy' ]
148  t0 = Tier0Handler( tier0Url, 5, 5, 5, proxyurl, False )
149 
150  try:
151  # Get the express GT from Tie0 DataService API
152  GlobalTag.globaltag = cms.string( t0.getGlobalTag( 'express_config' ) )
153  print("The query to the Tier0 DataService returns the express GT: \"%s\"" % ( GlobalTag.globaltag.value(), ))
154  except Tier0Error as error:
155  # the web query did not succeed, fall back to the default
156  print("Error in querying the Tier0 DataService")
157  print(error)
158  print("Falling back to the default value of the express GT: \"%s\"" % ( GlobalTag.globaltag.value(), ))
159 else:
160  print("Using hardcoded GT: \"%s\"" % GlobalTag.globaltag.value())
def replace(string, replacements)
S & print(S &os, JobReport::InputFile const &f)
Definition: JobReport.cc:66
def __init__(self, uri, timeOut, retries, retryPeriod, proxy, debug)
static std::string join(char **cmd)
Definition: RemoteFile.cc:18
#define str(s)