CMS 3D CMS Logo

Classes | Functions
uploadConditions Namespace Reference

Classes

class  ConditionsUploader
 
class  HTTP
 
class  HTTPError
 

Functions

def addToTarFile (tarFile, fileobj, arcname)
 
def get_version (url)
 
def getCredentials (options)
 
def getInput (default, prompt='')
 
def getInputChoose (optionsList, default, prompt='')
 
def getInputRepeat (prompt='')
 
def getInputWorkflow (prompt='')
 
def main ()
 
def parse_arguments ()
 
def re_upload (options)
 
def run_upload (parameters)
 
def runWizard (basename, dataFilename, metadataFilename)
 
def testTier0Upload ()
 
def upload (options, arguments)
 
def uploadAllFiles (options, arguments)
 
def uploadTier0Files (filenames, username, password, cookieFileName=None)
 

Detailed Description

Primary Author:
Joshua Dawes - CERN, CMS - The University of Manchester

Debugging, Integration and Maintenance:
Andres Cardenas - CERN, CMS - Universidad San Francisco

Upload script wrapper - controls the automatic update system.

Note: the name of the file follows a different convention to the others because it should be the same as the current upload script name.

Takes user arguments and passes them to the main upload module CondDBFW.uploads, once the correct version exists.

1. Ask the server corresponding to the database we're uploading to which version of CondDBFW it has (query the /conddbfw_version/ url).
2. Decide which directory that we can write to - either the current local directory, or /tmp/random_string/.
3. Pull the commit returned from the server into the directory from step 2.
4. Invoke the CondDBFW.uploads module with the arguments given to this script.
Script that uploads to the new CMS conditions uploader.
Adapted to the new infrastructure from v6 of the upload.py script for the DropBox from Miguel Ojeda.

Function Documentation

◆ addToTarFile()

def uploadConditions.addToTarFile (   tarFile,
  fileobj,
  arcname 
)

Definition at line 428 of file uploadConditions.py.

Referenced by uploadConditions.ConditionsUploader.uploadFile().

428 def addToTarFile(tarFile, fileobj, arcname):
429  tarInfo = tarFile.gettarinfo(fileobj = fileobj, arcname = arcname)
430  tarInfo.mode = 0o400
431  tarInfo.uid = tarInfo.gid = tarInfo.mtime = 0
432  tarInfo.uname = tarInfo.gname = 'root'
433  tarFile.addfile(tarInfo, fileobj)
434 
def addToTarFile(tarFile, fileobj, arcname)

◆ get_version()

def uploadConditions.get_version (   url)

Definition at line 435 of file uploadConditions.py.

References beamvalidation.exit(), data_sources.json_data_node.make(), parse_arguments(), print(), and run_upload().

Referenced by ValidationMatrix_v2.ReleaseComparison.compare().

435 def get_version(url):
436  return requests.get(url + "script_version/", verify=False)
437 
438 

◆ getCredentials()

def uploadConditions.getCredentials (   options)

Definition at line 617 of file uploadConditions.py.

References getInput().

Referenced by uploadAllFiles().

617 def getCredentials( options ):
618 
619  username = None
620  password = None
621  netrcPath = None
622  if authPathEnvVar in os.environ:
623  authPath = os.environ[authPathEnvVar]
624  netrcPath = os.path.join(authPath,'.netrc')
625  if options.authPath is not None:
626  netrcPath = os.path.join( options.authPath,'.netrc' )
627  try:
628  # Try to find the netrc entry
629  (username, account, password) = netrc.netrc( netrcPath ).authenticators(options.netrcHost)
630  except Exception:
631  # netrc entry not found, ask for the username and password
632  logging.info(
633  'netrc entry "%s" not found: if you wish not to have to retype your password, you can add an entry in your .netrc file. However, beware of the risks of having your password stored as plaintext. Instead.',
634  options.netrcHost)
635 
636  # Try to get a default username
637  defaultUsername = getpass.getuser()
638  if defaultUsername is None:
639  defaultUsername = '(not found)'
640 
641  username = getInput(defaultUsername, '\nUsername [%s]: ' % defaultUsername)
642  password = getpass.getpass('Password: ')
643 
644  return username, password
645 
646 
def getInput(default, prompt='')
def getCredentials(options)

◆ getInput()

def uploadConditions.getInput (   default,
  prompt = '' 
)
Like raw_input() but with a default and automatic strip().
Like input() but with a default and automatic strip().

Definition at line 61 of file uploadConditions.py.

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

61 def getInput(default, prompt = ''):
62  '''Like raw_input() but with a default and automatic strip().
63  '''
64 
65  answer = raw_input(prompt)
66  if answer:
67  return answer.strip()
68 
69  return default.strip()
70 
71 
def getInput(default, prompt='')

◆ getInputChoose()

def uploadConditions.getInputChoose (   optionsList,
  default,
  prompt = '' 
)
Makes the user choose from a list of options.

Definition at line 85 of file uploadConditions.py.

References getInput(), createfilelist.int, and print().

Referenced by runWizard().

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

◆ getInputRepeat()

def uploadConditions.getInputRepeat (   prompt = '')
Like raw_input() but repeats if nothing is provided and automatic strip().
Like input() but repeats if nothing is provided and automatic strip().

Definition at line 100 of file uploadConditions.py.

References print().

Referenced by runWizard().

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

◆ getInputWorkflow()

def uploadConditions.getInputWorkflow (   prompt = '')
Like getInput() but tailored to get target workflows (synchronization options).

Definition at line 72 of file uploadConditions.py.

References getInput(), and print().

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

◆ main()

def uploadConditions.main ( )
Entry point.

Definition at line 886 of file uploadConditions.py.

References print(), re_upload(), and upload().

886 def main():
887  '''Entry point.
888  '''
889 
890  parser = optparse.OptionParser(usage =
891  'Usage: %prog [options] <file> [<file> ...]\n'
892  )
893 
894  parser.add_option('-d', '--debug',
895  dest = 'debug',
896  action="store_true",
897  default = False,
898  help = 'Switch on printing debug information. Default: %default',
899  )
900 
901  parser.add_option('-b', '--backend',
902  dest = 'backend',
903  default = defaultBackend,
904  help = 'dropBox\'s backend to upload to. Default: %default',
905  )
906 
907  parser.add_option('-H', '--hostname',
908  dest = 'hostname',
909  default = defaultHostname,
910  help = 'dropBox\'s hostname. Default: %default',
911  )
912 
913  parser.add_option('-u', '--urlTemplate',
914  dest = 'urlTemplate',
915  default = defaultUrlTemplate,
916  help = 'dropBox\'s URL template. Default: %default',
917  )
918 
919  parser.add_option('-f', '--temporaryFile',
920  dest = 'temporaryFile',
921  default = defaultTemporaryFile,
922  help = 'Temporary file that will be used to store the first tar file. Note that it then will be moved to a file with the hash of the file as its name, so there will be two temporary files created in fact. Default: %default',
923  )
924 
925  parser.add_option('-n', '--netrcHost',
926  dest = 'netrcHost',
927  default = defaultNetrcHost,
928  help = 'The netrc host (machine) from where the username and password will be read. Default: %default',
929  )
930 
931  parser.add_option('-a', '--authPath',
932  dest = 'authPath',
933  default = None,
934  help = 'The path of the .netrc file for the authentication. Default: $HOME',
935  )
936 
937  parser.add_option('-r', '--reUpload',
938  dest = 'reUpload',
939  default = None,
940  help = 'The hash of the file to upload again.',
941  )
942 
943  (options, arguments) = parser.parse_args()
944 
945  logLevel = logging.INFO
946  if options.debug:
947  logLevel = logging.DEBUG
948  logging.basicConfig(
949  format = '[%(asctime)s] %(levelname)s: %(message)s',
950  level = logLevel,
951  )
952 
953  if len(arguments) < 1:
954  if options.reUpload is None:
955  parser.print_help()
956  return -2
957  else:
958  return re_upload(options)
959  if options.reUpload is not None:
960  print("ERROR: options -r can't be specified on a new file upload.")
961  return -2
962 
963  return upload(options, arguments)
964 
def upload(options, arguments)
void print(TMatrixD &m, const char *label=nullptr, bool mathematicaFormat=false)
Definition: Utilities.cc:47
def re_upload(options)

◆ parse_arguments()

def uploadConditions.parse_arguments ( )

Definition at line 232 of file uploadConditions.py.

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

Referenced by get_version(), and uploads.uploader.send_metadata().

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

◆ re_upload()

def uploadConditions.re_upload (   options)

Definition at line 802 of file uploadConditions.py.

References edm.decode(), fileinputsource_cfi.read, str, and upload().

Referenced by main().

802 def re_upload( options ):
803  netrcPath = None
804  logDbSrv = prodLogDbSrv
805  if options.hostname == defaultDevHostname:
806  logDbSrv = devLogDbSrv
807  if options.authPath is not None:
808  netrcPath = os.path.join( options.authPath,'.netrc' )
809  try:
810  netrcKey = '%s/%s' %(logDbSrv,logDbSchema)
811  # Try to find the netrc entry
812  (username, account, password) = netrc.netrc( netrcPath ).authenticators( netrcKey )
813  except IOError as e:
814  logging.error('Cannot access netrc file.')
815  return 1
816  except Exception as e:
817  logging.error('Netrc file is invalid: %s' %str(e))
818  return 1
819  conStr = '%s/%s@%s' %(username,password,logDbSrv)
820  con = cx_Oracle.connect( conStr )
821  cur = con.cursor()
822  fh = options.reUpload
823  cur.execute('SELECT FILECONTENT, STATE FROM FILES WHERE FILEHASH = :HASH',{'HASH':fh})
824  res = cur.fetchall()
825  found = False
826  fdata = None
827  for r in res:
828  found = True
829  logging.info("Found file %s in state '%s;" %(fh,r[1]))
830  fdata = r[0].read().decode('bz2')
831  con.close()
832  if not found:
833  logging.error("No file uploaded found with hash %s" %fh)
834  return 1
835  # writing as a tar file and open it ( is there a why to open it in memory?)
836  fname = '%s.tar' %fh
837  with open(fname, "wb" ) as f:
838  f.write(fdata)
839  rname = 'reupload_%s' %fh
840  with tarfile.open(fname) as tar:
841  tar.extractall()
842  os.remove(fname)
843  dfile = 'data.db'
844  mdfile = 'metadata.txt'
845  if os.path.exists(dfile):
846  os.utime(dfile,None)
847  os.chmod(dfile,0o755)
848  os.rename(dfile,'%s.db' %rname)
849  else:
850  logging.error('Tar file does not contain the data file')
851  return 1
852  if os.path.exists(mdfile):
853  os.utime(mdfile,None)
854  os.chmod(mdfile,0o755)
855  mdata = None
856  with open(mdfile) as md:
857  mdata = json.load(md)
858  datelabel = datetime.now().strftime("%y-%m-%d %H:%M:%S")
859  if mdata is None:
860  logging.error('Metadata file is empty.')
861  return 1
862  logging.debug('Preparing new metadata file...')
863  mdata['userText'] = 'reupload %s : %s' %(datelabel,mdata['userText'])
864  with open( '%s.txt' %rname, 'wb') as jf:
865  jf.write( json.dumps( mdata, sort_keys=True, indent = 2 ) )
866  jf.write('\n')
867  os.remove(mdfile)
868  else:
869  logging.error('Tar file does not contain the metadata file')
870  return 1
871  logging.info('Files %s prepared for the upload.' %rname)
872  arguments = [rname]
873  return upload(options, arguments)
874 
def upload(options, arguments)
def re_upload(options)
bool decode(bool &, std::string_view)
Definition: types.cc:72
#define str(s)

◆ run_upload()

def uploadConditions.run_upload (   parameters)
Imports CondDBFW.uploads and runs the upload with the upload metadata obtained.

Definition at line 47 of file uploadConditions.py.

References beamvalidation.exit().

Referenced by get_version().

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

◆ runWizard()

def uploadConditions.runWizard (   basename,
  dataFilename,
  metadataFilename 
)

Definition at line 111 of file uploadConditions.py.

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

Referenced by parse_arguments(), and uploadAllFiles().

111 def runWizard(basename, dataFilename, metadataFilename):
112  while True:
113  print('''\nWizard for metadata for %s
114 
115 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)
116 
117  # Try to get the available inputTags
118  try:
119  dataConnection = sqlite3.connect(dataFilename)
120  dataCursor = dataConnection.cursor()
121  dataCursor.execute('select name from sqlite_master where type == "table"')
122  tables = set(zip(*dataCursor.fetchall())[0])
123 
124  # only conddb V2 supported...
125  if 'TAG' in tables:
126  dataCursor.execute('select NAME from TAG')
127  # In any other case, do not try to get the inputTags
128  else:
129  raise Exception()
130 
131  inputTags = dataCursor.fetchall()
132  if len(inputTags) == 0:
133  raise Exception()
134  inputTags = list(zip(*inputTags))[0]
135 
136  except Exception:
137  inputTags = []
138 
139  if len(inputTags) == 0:
140  print('\nI could not find any input tag in your data file, but you can still specify one manually.')
141 
142  inputTag = getInputRepeat(
143  '\nWhich is the input tag (i.e. the tag to be read from the SQLite data file)?\ne.g. BeamSpotObject_ByRun\ninputTag: ')
144 
145  else:
146  print('\nI found the following input tags in your SQLite data file:')
147  for (index, inputTag) in enumerate(inputTags):
148  print(' %s) %s' % (index, inputTag))
149 
150  inputTag = getInputChoose(inputTags, '0',
151  '\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]: ')
152 
153  databases = {
154  'oraprod': 'oracle://cms_orcon_prod/CMS_CONDITIONS',
155  'prod': 'oracle://cms_orcon_prod/CMS_CONDITIONS',
156  'oradev': 'oracle://cms_orcoff_prep/CMS_CONDITIONS',
157  'prep': 'oracle://cms_orcoff_prep/CMS_CONDITIONS',
158  }
159 
160  destinationDatabase = ''
161  ntry = 0
162  print('\nWhich is the destination database where the tags should be exported?')
163  print('\n%s) %s' % ('oraprod', databases['oraprod']))
164  print('\n%s) %s' % ('oradev', databases['oradev']))
165 
166  while ( destinationDatabase not in databases.values() ):
167  if ntry==0:
168  inputMessage = \
169  '\nPossible choices: oraprod or oradev \ndestinationDatabase: '
170  elif ntry==1:
171  inputMessage = \
172  '\nPlease choose one of the two valid destinations: oraprod or oradev \ndestinationDatabase: '
173  else:
174  raise Exception('No valid destination chosen. Bailing out...')
175 
176  databaseInput = getInputRepeat(inputMessage).lower()
177  if databaseInput in databases.keys():
178  destinationDatabase = databases[databaseInput]
179  ntry += 1
180 
181  while True:
182  since = getInput('',
183  '\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 []: ')
184  if not since:
185  since = None
186  break
187  else:
188  try:
189  since = int(since)
190  break
191  except ValueError:
192  print('The since value has to be an integer or empty (null).')
193 
194  userText = getInput('',
195  '\nWrite any comments/text you may want to describe your request\ne.g. Muon alignment scenario for...\nuserText []: ')
196 
197  destinationTags = {}
198  while True:
199  destinationTag = getInput('',
200  '\nWhich is the next destination tag to be added (leave empty to stop)?\ne.g. BeamSpotObjects_PCL_byRun_v0_offline\ndestinationTag []: ')
201  if not destinationTag:
202  if len(destinationTags) == 0:
203  print('There must be at least one destination tag.')
204  continue
205  break
206 
207  if destinationTag in destinationTags:
208  print(
209  'You already added this destination tag. Overwriting the previous one with this new one.')
210 
211  destinationTags[destinationTag] = {
212  }
213 
214  metadata = {
215  'destinationDatabase': destinationDatabase,
216  'destinationTags': destinationTags,
217  'inputTag': inputTag,
218  'since': since,
219  'userText': userText,
220  }
221 
222  metadata = json.dumps(metadata, sort_keys=True, indent=4)
223  print('\nThis is the generated metadata:\n%s' % metadata)
224 
225  if getInput('n',
226  '\nIs it fine (i.e. save in %s and *upload* the conditions if this is the latest file)?\nAnswer [n]: ' % metadataFilename).lower() == 'y':
227  break
228  print('Saving generated metadata in %s...', metadataFilename)
229  with open(metadataFilename, 'wb') as metadataFile:
230  metadataFile.write(metadata)
231 
def getInput(default, prompt='')
def getInputChoose(optionsList, default, prompt='')
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
def runWizard(basename, dataFilename, metadataFilename)
def getInputRepeat(prompt='')

◆ testTier0Upload()

def uploadConditions.testTier0Upload ( )

Definition at line 965 of file uploadConditions.py.

References uploadTier0Files().

965 def testTier0Upload():
966 
967  global defaultNetrcHost
968 
969  (username, account, password) = netrc.netrc().authenticators(defaultNetrcHost)
970 
971  filenames = ['testFiles/localSqlite-top2']
972 
973  uploadTier0Files(filenames, username, password, cookieFileName = None)
974 
975 
def uploadTier0Files(filenames, username, password, cookieFileName=None)

◆ upload()

def uploadConditions.upload (   options,
  arguments 
)

Definition at line 875 of file uploadConditions.py.

References print(), and uploadAllFiles().

Referenced by main(), and re_upload().

875 def upload(options, arguments):
876  results = uploadAllFiles(options, arguments)
877 
878  if 'status' not in results:
879  print('Unexpected error.')
880  return -1
881  ret = results['status']
882  print(results)
883  print("upload ended with code: %s" %ret)
884  return ret
885 
def upload(options, arguments)
void print(TMatrixD &m, const char *label=nullptr, bool mathematicaFormat=false)
Definition: Utilities.cc:47
def uploadAllFiles(options, arguments)

◆ uploadAllFiles()

def uploadConditions.uploadAllFiles (   options,
  arguments 
)

Definition at line 647 of file uploadConditions.py.

References getCredentials(), getInput(), runWizard(), and str.

Referenced by upload().

647 def uploadAllFiles(options, arguments):
648 
649  ret = {}
650  ret['status'] = 0
651 
652  # Check that we can read the data and metadata files
653  # If the metadata file does not exist, start the wizard
654  for filename in arguments:
655  basepath = filename.rsplit('.db', 1)[0].rsplit('.txt', 1)[0]
656  basename = os.path.basename(basepath)
657  dataFilename = '%s.db' % basepath
658  metadataFilename = '%s.txt' % basepath
659 
660  logging.info('Checking %s...', basename)
661 
662  # Data file
663  try:
664  with open(dataFilename, 'rb') as dataFile:
665  pass
666  except IOError as e:
667  errMsg = 'Impossible to open SQLite data file %s' %dataFilename
668  logging.error( errMsg )
669  ret['status'] = -3
670  ret['error'] = errMsg
671  return ret
672 
673  # Check the data file
674  empty = True
675  try:
676  dbcon = sqlite3.connect( dataFilename )
677  dbcur = dbcon.cursor()
678  dbcur.execute('SELECT * FROM IOV')
679  rows = dbcur.fetchall()
680  for r in rows:
681  empty = False
682  dbcon.close()
683  if empty:
684  errMsg = 'The input SQLite data file %s contains no data.' %dataFilename
685  logging.error( errMsg )
686  ret['status'] = -4
687  ret['error'] = errMsg
688  return ret
689  except Exception as e:
690  errMsg = 'Check on input SQLite data file %s failed: %s' %(dataFilename,str(e))
691  logging.error( errMsg )
692  ret['status'] = -5
693  ret['error'] = errMsg
694  return ret
695 
696  # Metadata file
697  try:
698  with open(metadataFilename, 'rb') as metadataFile:
699  pass
700  except IOError as e:
701  if e.errno != errno.ENOENT:
702  errMsg = 'Impossible to open file %s (for other reason than not existing)' %metadataFilename
703  logging.error( errMsg )
704  ret['status'] = -4
705  ret['error'] = errMsg
706  return ret
707 
708  if getInput('y', '\nIt looks like the metadata file %s does not exist. Do you want me to create it and help you fill it?\nAnswer [y]: ' % metadataFilename).lower() != 'y':
709  errMsg = 'Metadata file %s does not exist' %metadataFilename
710  logging.error( errMsg )
711  ret['status'] = -5
712  ret['error'] = errMsg
713  return ret
714  # Wizard
715  runWizard(basename, dataFilename, metadataFilename)
716 
717  # Upload files
718  try:
719  dropBox = ConditionsUploader(options.hostname, options.urlTemplate)
720 
721  # Authentication
722  username, password = getCredentials(options)
723 
724  results = {}
725  for filename in arguments:
726  backend = options.backend
727  basepath = filename.rsplit('.db', 1)[0].rsplit('.txt', 1)[0]
728  metadataFilename = '%s.txt' % basepath
729  with open(metadataFilename, 'rb') as metadataFile:
730  metadata = json.load( metadataFile )
731  # When dest db = prep the hostname has to be set to dev.
732  forceHost = False
733  destDb = metadata['destinationDatabase']
734  if destDb.startswith('oracle://cms_orcon_prod') or destDb.startswith('oracle://cms_orcoff_prep'):
735  hostName = defaultHostname
736  if destDb.startswith('oracle://cms_orcoff_prep'):
737  hostName = defaultDevHostname
738  dropBox.setHost( hostName )
739  authRet = dropBox.signIn( username, password )
740  if not authRet==0:
741  msg = "Error trying to connect to the server. Aborting."
742  if authRet==-2:
743  msg = "Error while signin in. Aborting."
744  logging.error(msg)
745  return { 'status' : authRet, 'error' : msg }
746  results[filename] = dropBox.uploadFile(filename, options.backend, options.temporaryFile)
747  else:
748  results[filename] = False
749  logging.error("DestinationDatabase %s is not valid. Skipping the upload." %destDb)
750  if not results[filename]:
751  if ret['status']<0:
752  ret['status'] = 0
753  ret['status'] += 1
754  ret['files'] = results
755  logging.debug("all files processed, logging out now.")
756 
757  dropBox.signOut()
758 
759  except HTTPError as e:
760  logging.error('got HTTP error: %s', str(e))
761  return { 'status' : -1, 'error' : str(e) }
762 
763  return ret
764 
def getInput(default, prompt='')
def getCredentials(options)
def uploadAllFiles(options, arguments)
def runWizard(basename, dataFilename, metadataFilename)
#define str(s)

◆ uploadTier0Files()

def uploadConditions.uploadTier0Files (   filenames,
  username,
  password,
  cookieFileName = None 
)
Uploads a bunch of files coming from Tier0.
This has the following requirements:
    * Username/Password based authentication.
    * Uses the online backend.
    * Ignores errors related to the upload/content (e.g. duplicated file).

Definition at line 765 of file uploadConditions.py.

Referenced by testTier0Upload().

765 def uploadTier0Files(filenames, username, password, cookieFileName = None):
766  '''Uploads a bunch of files coming from Tier0.
767  This has the following requirements:
768  * Username/Password based authentication.
769  * Uses the online backend.
770  * Ignores errors related to the upload/content (e.g. duplicated file).
771  '''
772 
773  dropBox = ConditionsUploader()
774 
775  dropBox.signIn(username, password)
776 
777  for filename in filenames:
778  try:
779  result = dropBox.uploadFile(filename, backend = 'test')
780  except HTTPError as e:
781  if e.code == 400:
782  # 400 Bad Request: This is an exception related to the upload
783  # being wrong for some reason (e.g. duplicated file).
784  # Since for Tier0 this is not an issue, continue
785  logging.error('HTTP Exception 400 Bad Request: Upload-related, skipping. Message: %s', e)
786  continue
787 
788  # In any other case, re-raise.
789  raise
790 
791  #-toDo: add a flag to say if we should retry or not. So far, all retries are done server-side (Tier-0),
792  # if we flag as failed any retry would not help and would result in the same error (e.g.
793  # when a file with an identical hash is uploaded again)
794  #-review(2015-09-25): get feedback from tests at Tier-0 (action: AP)
795 
796  if not result: # dropbox reported an error when uploading, do not retry.
797  logging.error('Error from dropbox, upload-related, skipping.')
798  continue
799 
800  dropBox.signOut()
801 
def uploadTier0Files(filenames, username, password, cookieFileName=None)