CMS 3D CMS Logo

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Groups Pages
Functions | Variables
uploadConditions_v2 Namespace Reference

Functions

def get_version
 
def getInput
 
def getInputChoose
 
def getInputRepeat
 
def getInputWorkflow
 
def parse_arguments
 
def run_upload
 
def runWizard
 

Variables

int __version__ = 1
 
list final_service_url = upload_metadata["server"]
 
string horizontal_rule = "="
 
tuple response = get_version(final_service_url)
 
tuple server_version = json.loads(response)
 
tuple upload_metadata = parse_arguments()
 
dictionary upload_metadata_argument = {}
 

Function Documentation

def uploadConditions_v2.get_version (   url)

Definition at line 453 of file uploadConditions_v2.py.

454 def get_version(url):
455  query = url_query(url=url + "script_version/")
456  response = query.send()
457  return response
458 
def uploadConditions_v2.getInput (   default,
  prompt = '' 
)
Like raw_input() but with a default and automatic strip().

Definition at line 62 of file uploadConditions_v2.py.

Referenced by getInputChoose(), getInputWorkflow(), parse_arguments(), and runWizard().

62 
63 def getInput(default, prompt = ''):
64  '''Like raw_input() but with a default and automatic strip().
65  '''
66 
67  answer = raw_input(prompt)
68  if answer:
69  return answer.strip()
70 
71  return default.strip()
72 
def uploadConditions_v2.getInputChoose (   optionsList,
  default,
  prompt = '' 
)
Makes the user choose from a list of options.

Definition at line 86 of file uploadConditions_v2.py.

References getInput(), and print().

Referenced by runWizard().

86 
87 def getInputChoose(optionsList, default, prompt = ''):
88  '''Makes the user choose from a list of options.
89  '''
90 
91  while True:
92  index = getInput(default, prompt)
93 
94  try:
95  return optionsList[int(index)]
96  except ValueError:
97  print('Please specify an index of the list (i.e. integer).')
98  except IndexError:
99  print('The index you provided is not in the given list.')
100 
void print(TMatrixD &m, const char *label=nullptr, bool mathematicaFormat=false)
Definition: Utilities.cc:47
def uploadConditions_v2.getInputRepeat (   prompt = '')
Like raw_input() but repeats if nothing is provided and automatic strip().

Definition at line 101 of file uploadConditions_v2.py.

References print().

Referenced by runWizard().

102 def getInputRepeat(prompt = ''):
103  '''Like raw_input() but repeats if nothing is provided and automatic strip().
104  '''
105 
106  while True:
107  answer = raw_input(prompt)
108  if answer:
109  return answer.strip()
110 
111  print('You need to provide a value.')
void print(TMatrixD &m, const char *label=nullptr, bool mathematicaFormat=false)
Definition: Utilities.cc:47
def uploadConditions_v2.getInputWorkflow (   prompt = '')
Like getInput() but tailored to get target workflows (synchronization options).

Definition at line 73 of file uploadConditions_v2.py.

References getInput(), and print().

73 
74 def getInputWorkflow(prompt = ''):
75  '''Like getInput() but tailored to get target workflows (synchronization options).
76  '''
77 
78  while True:
79  workflow = getInput(defaultWorkflow, prompt)
80 
81  if workflow in frozenset(['offline', 'hlt', 'express', 'prompt', 'pcl']):
82  return workflow
83 
84  print('Please specify one of the allowed workflows. See above for the explanation on each of them.')
85 
void print(TMatrixD &m, const char *label=nullptr, bool mathematicaFormat=false)
Definition: Utilities.cc:47
def uploadConditions_v2.parse_arguments ( )

Definition at line 233 of file uploadConditions_v2.py.

References beamvalidation.exit(), getInput(), join(), print(), runWizard(), and str.

234 def parse_arguments():
235  # read in command line arguments, and build metadata dictionary from them
236  parser = optparse.OptionParser(description="CMS Conditions Upload Script in CondDBFW.",
237  usage = 'Usage: %prog [options] <file>')
238 
239  # metadata arguments
240  parser.add_option("-i", "--inputTag", type=str,\
241  help="Tag to take IOVs + Payloads from in --sourceDB.")
242  parser.add_option("-t", "--destinationTag", type=str,\
243  help="Tag to copy IOVs + Payloads to in --destDB.")
244  parser.add_option("-D", "--destinationDatabase", type=str,\
245  help="Database to copy IOVs + Payloads to.")
246  parser.add_option("-s", "--since", type=int,\
247  help="Since to take IOVs from.")
248  parser.add_option("-u", "--userText", type=str,\
249  help="Description of --destTag (can be empty).")
250 
251  # non-metadata arguments
252  parser.add_option("-m", "--metadataFile", type=str, help="Metadata file to take metadata from.")
253 
254  parser.add_option("-d", "--debug", action="store_true", default=False)
255  parser.add_option("-v", "--verbose", action="store_true", default=False)
256  parser.add_option("-T", "--testing", action="store_true")
257  parser.add_option("--fcsr-filter", type=str, help="Synchronization to take FCSR from for local filtering of IOVs.")
258 
259  parser.add_option("-n", "--netrc", help = 'The netrc host (machine) from where the username and password will be read.')
260 
261  parser.add_option("-a", "--authPath", help = 'The path of the .netrc file for the authentication. Default: $HOME')
262 
263  parser.add_option("-H", "--hashToUse")
264 
265  parser.add_option("-S", "--server")
266 
267  parser.add_option("-o", "--review-options", action="store_true")
268 
269  parser.add_option("-r", "--replay-file")
270 
271  (command_line_data, arguments) = parser.parse_args()
272 
273  if len(arguments) < 1:
274  if command_line_data.hashToUse == None:
275  parser.print_help()
276  exit(-2)
277 
278  command_line_data.sourceDB = arguments[0]
279 
280  if command_line_data.replay_file:
281  dictionary = json.loads("".join(open(command_line_data.replay_file, "r").readlines()))
282  command_line_data.tier0_response = dictionary["tier0_response"]
283 
284  # default is the production server, which can point to either database anyway
285  server_alias_to_url = {
286  "prep" : "https://cms-conddb-dev.cern.ch/cmsDbCondUpload/",
287  "dev" : "https://cms-conddb-dev.cern.ch/cmsDbCondUpload/",
288  "prod" : "https://cms-conddb.cern.ch/cmsDbCondUpload/"
289  }
290 
291  # if prep, prod or None were given, convert to URLs in dictionary server_alias_to_url
292  # if not, assume a URL has been given and use this instead
293  if command_line_data.server in server_alias_to_url.keys():
294  command_line_data.server = server_alias_to_url[command_line_data.server]
295 
296  # resolve destination databases
297  database_alias_to_connection = {
298  "prep": "oracle://cms_orcoff_prep/CMS_CONDITIONS",
299  "dev": "oracle://cms_orcoff_prep/CMS_CONDITIONS",
300  "prod": "oracle://cms_orcon_adg/CMS_CONDITIONS"
301  }
302 
303  if command_line_data.destinationDatabase in database_alias_to_connection.keys():
304  command_line_data.destinationDatabase = database_alias_to_connection[command_line_data.destinationDatabase]
305 
306 
307  # use netrc to get username and password
308  try:
309  netrc_file = command_line_data.netrc
310  auth_path = command_line_data.authPath
311  if not auth_path is None:
312  if netrc_file is None:
313  netrc_file = os.path.join(auth_path,'.netrc')
314  else:
315  netrc_file = os.path.join(auth_path, netrc_file)
316 
317  netrc_authenticators = netrc.netrc(netrc_file).authenticators("ConditionUploader")
318  if netrc_authenticators == None:
319  print("Your netrc file must contain the key 'ConditionUploader'.")
320  manual_input = raw_input("Do you want to try to type your credentials? ")
321  if manual_input == "y":
322  # ask for username and password
323  username = raw_input("Username: ")
324  password = getpass.getpass("Password: ")
325  else:
326  exit()
327  else:
328  username = netrc_authenticators[0]
329  password = netrc_authenticators[2]
330  except:
331  print("Couldn't obtain your credentials (either from netrc or manual input).")
332  exit()
333 
334  command_line_data.username = username
335  command_line_data.password = password
336  # this will be used as the final destinationTags value by all input methods
337  # apart from the metadata file
338  command_line_data.destinationTags = {command_line_data.destinationTag:{}}
339 
340  """
341  Construct metadata_dictionary:
342  Currently, this is 3 cases:
343 
344  1) An IOV is being appended to an existing Tag with an existing Payload.
345  In this case, we just take all data from the command line.
346 
347  2) No metadata file is given, so we assume that ALL upload metadata is coming from the command line.
348 
349  3) A metadata file is given, hence we parse the file, and then iterate through command line arguments
350  since these override the options set in the metadata file.
351 
352  """
353 
354  # Hash to use, entirely from command line
355  if command_line_data.hashToUse != None:
356  command_line_data.userText = ""
357  metadata_dictionary = command_line_data.__dict__
358  elif command_line_data.metadataFile == None:
359  if command_line_data.sourceDB != None and (command_line_data.inputTag == None or command_line_data.destinationTag == None or command_line_data.destinationDatabase == None):
360  basepath = command_line_data.sourceDB.rsplit('.db', 1)[0].rsplit('.txt', 1)[0]
361  basename = os.path.basename(basepath)
362  dataFilename = '%s.db' % basepath
363  metadataFilename = '%s.txt' % basepath
364 
365  # Data file
366  try:
367  with open(dataFilename, 'rb') as dataFile:
368  pass
369  except IOError as e:
370  errMsg = 'Impossible to open SQLite data file %s' %dataFilename
371  print( errMsg )
372  ret['status'] = -3
373  ret['error'] = errMsg
374  return ret
375 
376  # Metadata file
377 
378  command_line_data.sourceDB = dataFilename
379 
380  try:
381  with open(metadataFilename, 'rb') as metadataFile:
382  pass
383  except IOError as e:
384  if e.errno != errno.ENOENT:
385  errMsg = 'Impossible to open file %s (for other reason than not existing)' %metadataFilename
386  ret = {}
387  ret['status'] = -4
388  ret['error'] = errMsg
389  exit (ret)
390 
391  if getInput('y', '\nIt looks like the metadata file %s does not exist and not enough parameters were received in the command line. Do you want me to create it and help you fill it?\nAnswer [y]: ' % metadataFilename).lower() != 'y':
392  errMsg = 'Metadata file %s does not exist' %metadataFilename
393  ret = {}
394  ret['status'] = -5
395  ret['error'] = errMsg
396  exit(ret)
397  # Wizard
398  runWizard(basename, dataFilename, metadataFilename)
399  command_line_data.metadataFile = metadataFilename
400  else:
401  command_line_data.userText = command_line_data.userText\
402  if command_line_data.userText != None\
403  else str(raw_input("Tag's description [can be empty]:"))
404  metadata_dictionary = command_line_data.__dict__
405 
406  if command_line_data.metadataFile != None:
407  metadata_dictionary = json.loads("".join(open(os.path.abspath(command_line_data.metadataFile), "r").readlines()))
408  metadata_dictionary["username"] = username
409  metadata_dictionary["password"] = password
410  metadata_dictionary["userText"] = metadata_dictionary.get("userText")\
411  if metadata_dictionary.get("userText") != None\
412  else str(raw_input("Tag's description [can be empty]:"))
413 
414  # go through command line options and, if they are set, overwrite entries
415  for (option_name, option_value) in command_line_data.__dict__.items():
416  # if the metadata_dictionary sets this, overwrite it
417  if option_name != "destinationTags":
418  if option_value != None or (option_value == None and not(option_name in metadata_dictionary.keys())):
419  # if option_value has a value, override the metadata file entry
420  # or if option_value is None but the metadata file doesn't give a value,
421  # set the entry to None as well
422  metadata_dictionary[option_name] = option_value
423  else:
424  if option_value != {None:{}}:
425  metadata_dictionary["destinationTags"] = {option_value:{}}
426  elif option_value == {None:{}} and not("destinationTags" in metadata_dictionary.keys()):
427  metadata_dictionary["destinationTags"] = {None:{}}
428 
429  if command_line_data.review_options:
430  defaults = {
431  "since" : "Since of first IOV",
432  "userText" : "Populated by upload process",
433  "netrc" : "None given",
434  "fcsr_filter" : "Don't apply",
435  "hashToUse" : "Using local SQLite file instead"
436  }
437  print("Configuration to use for the upload:")
438  for key in metadata_dictionary:
439  if not(key) in ["username", "password", "destinationTag"]:
440  value_to_print = metadata_dictionary[key] if metadata_dictionary[key] != None else defaults[key]
441  print("\t%s : %s" % (key, value_to_print))
442 
443  if raw_input("\nDo you want to continue? [y/n] ") != "y":
444  exit()
445 
446  if metadata_dictionary["server"] == None:
447  if metadata_dictionary["destinationDatabase"] == "oracle://cms_orcoff_prep/CMS_CONDITIONS":
448  metadata_dictionary["server"] = server_alias_to_url["prep"]
449  else:
450  metadata_dictionary["server"] = server_alias_to_url["prod"]
451 
452  return metadata_dictionary
void print(TMatrixD &m, const char *label=nullptr, bool mathematicaFormat=false)
Definition: Utilities.cc:47
static std::string join(char **cmd)
Definition: RemoteFile.cc:19
#define str(s)
def uploadConditions_v2.run_upload (   parameters)
Imports CondDBFW.uploads and runs the upload with the upload metadata obtained.

Definition at line 48 of file uploadConditions_v2.py.

References beamvalidation.exit().

48 
49 def run_upload(**parameters):
50  """
51  Imports CondDBFW.uploads and runs the upload with the upload metadata obtained.
52  """
53  try:
54  import CondCore.Utilities.CondDBFW.uploads as uploads
55  except Exception as e:
56  traceback.print_exc()
57  exit("CondDBFW or one of its dependencies could not be imported.\n"\
58  + "If the CondDBFW directory exists, you are likely not in a CMSSW environment.")
59  # we have CondDBFW, so just call the module with the parameters given in the command line
60  uploader = uploads.uploader(**parameters)
61  result = uploader.upload()
def uploadConditions_v2.runWizard (   basename,
  dataFilename,
  metadataFilename 
)

Definition at line 112 of file uploadConditions_v2.py.

References getInput(), getInputChoose(), getInputRepeat(), print(), and ComparisonHelper.zip().

Referenced by parse_arguments().

113 def runWizard(basename, dataFilename, metadataFilename):
114  while True:
115  print('''\nWizard for metadata for %s
116 
117 I will ask you some questions to fill the metadata file. For some of the questions there are defaults between square brackets (i.e. []), leave empty (i.e. hit Enter) to use them.''' % basename)
118 
119  # Try to get the available inputTags
120  try:
121  dataConnection = sqlite3.connect(dataFilename)
122  dataCursor = dataConnection.cursor()
123  dataCursor.execute('select name from sqlite_master where type == "table"')
124  tables = set(zip(*dataCursor.fetchall())[0])
125 
126  # only conddb V2 supported...
127  if 'TAG' in tables:
128  dataCursor.execute('select NAME from TAG')
129  # In any other case, do not try to get the inputTags
130  else:
131  raise Exception()
132 
133  inputTags = dataCursor.fetchall()
134  if len(inputTags) == 0:
135  raise Exception()
136  inputTags = list(zip(*inputTags))[0]
137 
138  except Exception:
139  inputTags = []
140 
141  if len(inputTags) == 0:
142  print('\nI could not find any input tag in your data file, but you can still specify one manually.')
143 
144  inputTag = getInputRepeat(
145  '\nWhich is the input tag (i.e. the tag to be read from the SQLite data file)?\ne.g. BeamSpotObject_ByRun\ninputTag: ')
146 
147  else:
148  print('\nI found the following input tags in your SQLite data file:')
149  for (index, inputTag) in enumerate(inputTags):
150  print(' %s) %s' % (index, inputTag))
151 
152  inputTag = getInputChoose(inputTags, '0',
153  '\nWhich is the input tag (i.e. the tag to be read from the SQLite data file)?\ne.g. 0 (you select the first in the list)\ninputTag [0]: ')
154 
155  databases = {
156  'oraprod': 'oracle://cms_orcon_prod/CMS_CONDITIONS',
157  'prod': 'oracle://cms_orcon_prod/CMS_CONDITIONS',
158  'oradev': 'oracle://cms_orcoff_prep/CMS_CONDITIONS',
159  'prep': 'oracle://cms_orcoff_prep/CMS_CONDITIONS',
160  }
161 
162  destinationDatabase = ''
163  ntry = 0
164  print('\nWhich is the destination database where the tags should be exported?')
165  print('\n%s) %s' % ('oraprod', databases['oraprod']))
166  print('\n%s) %s' % ('oradev', databases['oradev']))
167 
168  while ( destinationDatabase not in databases.values() ):
169  if ntry==0:
170  inputMessage = \
171  '\nPossible choices: oraprod or oradev \ndestinationDatabase: '
172  elif ntry==1:
173  inputMessage = \
174  '\nPlease choose one of the two valid destinations: oraprod or oradev \ndestinationDatabase: '
175  else:
176  raise Exception('No valid destination chosen. Bailing out...')
177 
178  databaseInput = getInputRepeat(inputMessage).lower()
179  if databaseInput in databases.keys():
180  destinationDatabase = databases[databaseInput]
181  ntry += 1
182 
183  while True:
184  since = getInput('',
185  '\nWhich is the given since? (if not specified, the one from the SQLite data file will be taken -- note that even if specified, still this may not be the final since, depending on the synchronization options you select later: if the synchronization target is not offline, and the since you give is smaller than the next possible one (i.e. you give a run number earlier than the one which will be started/processed next in prompt/hlt/express), the DropBox will move the since ahead to go to the first safe run instead of the value you gave)\ne.g. 1234\nsince []: ')
186  if not since:
187  since = None
188  break
189  else:
190  try:
191  since = int(since)
192  break
193  except ValueError:
194  print('The since value has to be an integer or empty (null).')
195 
196  userText = getInput('',
197  '\nWrite any comments/text you may want to describe your request\ne.g. Muon alignment scenario for...\nuserText []: ')
198 
199  destinationTags = {}
200  while True:
201  destinationTag = getInput('',
202  '\nWhich is the next destination tag to be added (leave empty to stop)?\ne.g. BeamSpotObjects_PCL_byRun_v0_offline\ndestinationTag []: ')
203  if not destinationTag:
204  if len(destinationTags) == 0:
205  print('There must be at least one destination tag.')
206  continue
207  break
208 
209  if destinationTag in destinationTags:
210  print(
211  'You already added this destination tag. Overwriting the previous one with this new one.')
212 
213  destinationTags[destinationTag] = {
214  }
215 
216  metadata = {
217  'destinationDatabase': destinationDatabase,
218  'destinationTags': destinationTags,
219  'inputTag': inputTag,
220  'since': since,
221  'userText': userText,
222  }
223 
224  metadata = json.dumps(metadata, sort_keys=True, indent=4)
225  print('\nThis is the generated metadata:\n%s' % metadata)
226 
227  if getInput('n',
228  '\nIs it fine (i.e. save in %s and *upload* the conditions if this is the latest file)?\nAnswer [n]: ' % metadataFilename).lower() == 'y':
229  break
230  print('Saving generated metadata in %s...'% metadataFilename)
231  with open(metadataFilename, 'wb') as metadataFile:
232  metadataFile.write(metadata)
OutputIterator zip(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result, Compare comp)
void print(TMatrixD &m, const char *label=nullptr, bool mathematicaFormat=false)
Definition: Utilities.cc:47

Variable Documentation

int uploadConditions_v2.__version__ = 1

Definition at line 22 of file uploadConditions_v2.py.

list uploadConditions_v2.final_service_url = upload_metadata["server"]

Definition at line 464 of file uploadConditions_v2.py.

string uploadConditions_v2.horizontal_rule = "="

Definition at line 46 of file uploadConditions_v2.py.

tuple uploadConditions_v2.response = get_version(final_service_url)

Definition at line 466 of file uploadConditions_v2.py.

tuple uploadConditions_v2.server_version = json.loads(response)

Definition at line 467 of file uploadConditions_v2.py.

tuple uploadConditions_v2.upload_metadata = parse_arguments()

Definition at line 461 of file uploadConditions_v2.py.

dictionary uploadConditions_v2.upload_metadata_argument = {}

Definition at line 493 of file uploadConditions_v2.py.