CMS 3D CMS Logo

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Pages
uploadConditions.py
Go to the documentation of this file.
1 #!/usr/bin/env python
2 '''Script that uploads to the new CMS conditions uploader.
3 Adapted to the new infrastructure from v6 of the upload.py script for the DropBox from Miguel Ojeda.
4 '''
5 
6 __author__ = 'Andreas Pfeiffer'
7 __copyright__ = 'Copyright 2015, CERN CMS'
8 __credits__ = ['Giacomo Govi', 'Salvatore Di Guida', 'Miguel Ojeda', 'Andreas Pfeiffer']
9 __license__ = 'Unknown'
10 __maintainer__ = 'Andreas Pfeiffer'
11 __email__ = 'andreas.pfeiffer@cern.ch'
12 __version__ = 1
13 
14 
15 import os
16 import sys
17 import optparse
18 import hashlib
19 import tarfile
20 import netrc
21 import getpass
22 import errno
23 import sqlite3
24 import json
25 import tempfile
26 
27 defaultBackend = 'online'
28 defaultHostname = 'cms-conddb-prod.cern.ch'
29 defaultDevHostname = 'cms-conddb-dev.cern.ch'
30 defaultUrlTemplate = 'https://%s/cmsDbUpload/'
31 defaultTemporaryFile = 'upload.tar.bz2'
32 defaultNetrcHost = 'ConditionUploader'
33 defaultWorkflow = 'offline'
34 
35 # common/http.py start (plus the "# Try to extract..." section bit)
36 import time
37 import logging
38 import cStringIO
39 
40 import pycurl
41 import copy
42 
43 def getInput(default, prompt = ''):
44  '''Like raw_input() but with a default and automatic strip().
45  '''
46 
47  answer = raw_input(prompt)
48  if answer:
49  return answer.strip()
50 
51  return default.strip()
52 
53 
54 def getInputWorkflow(prompt = ''):
55  '''Like getInput() but tailored to get target workflows (synchronization options).
56  '''
57 
58  while True:
59  workflow = getInput(defaultWorkflow, prompt)
60 
61  if workflow in frozenset(['offline', 'hlt', 'express', 'prompt', 'pcl']):
62  return workflow
63 
64  logging.error('Please specify one of the allowed workflows. See above for the explanation on each of them.')
65 
66 
67 def getInputChoose(optionsList, default, prompt = ''):
68  '''Makes the user choose from a list of options.
69  '''
70 
71  while True:
72  index = getInput(default, prompt)
73 
74  try:
75  return optionsList[int(index)]
76  except ValueError:
77  logging.error('Please specify an index of the list (i.e. integer).')
78  except IndexError:
79  logging.error('The index you provided is not in the given list.')
80 
81 
82 def getInputRepeat(prompt = ''):
83  '''Like raw_input() but repeats if nothing is provided and automatic strip().
84  '''
85 
86  while True:
87  answer = raw_input(prompt)
88  if answer:
89  return answer.strip()
90 
91  logging.error('You need to provide a value.')
92 
93 
94 def runWizard(basename, dataFilename, metadataFilename):
95  while True:
96  print '''\nWizard for metadata for %s
97 
98 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
99 
100  # Try to get the available inputTags
101  try:
102  dataConnection = sqlite3.connect(dataFilename)
103  dataCursor = dataConnection.cursor()
104  dataCursor.execute('select name from sqlite_master where type == "table"')
105  tables = set(zip(*dataCursor.fetchall())[0])
106 
107  # only conddb V2 supported...
108  if 'TAG' in tables:
109  dataCursor.execute('select NAME from TAG')
110  # In any other case, do not try to get the inputTags
111  else:
112  raise Exception()
113 
114  inputTags = dataCursor.fetchall()
115  if len(inputTags) == 0:
116  raise Exception()
117  inputTags = zip(*inputTags)[0]
118 
119  except Exception:
120  inputTags = []
121 
122  if len(inputTags) == 0:
123  print '\nI could not find any input tag in your data file, but you can still specify one manually.'
124 
125  inputTag = getInputRepeat(
126  '\nWhich is the input tag (i.e. the tag to be read from the SQLite data file)?\ne.g. BeamSpotObject_ByRun\ninputTag: ')
127 
128  else:
129  print '\nI found the following input tags in your SQLite data file:'
130  for (index, inputTag) in enumerate(inputTags):
131  print ' %s) %s' % (index, inputTag)
132 
133  inputTag = getInputChoose(inputTags, '0',
134  '\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]: ')
135 
136  destinationDatabase = ''
137  ntry = 0
138  while ( destinationDatabase != 'oracle://cms_orcon_prod/CMS_CONDITIONS' and destinationDatabase != 'oracle://cms_orcoff_prep/CMS_CONDITIONS' ):
139  if ntry==0:
140  inputMessage = \
141  '\nWhich is the destination database where the tags should be exported? \nPossible choices: oracle://cms_orcon_prod/CMS_CONDITIONS (for prod) or oracle://cms_orcoff_prep/CMS_CONDITIONS (for prep) \ndestinationDatabase: '
142  elif ntry==1:
143  inputMessage = \
144  '\nPlease choose one of the two valid destinations: \noracle://cms_orcon_prod/CMS_CONDITIONS (for prod) or oracle://cms_orcoff_prep/CMS_CONDITIONS (for prep) \
145 \ndestinationDatabase: '
146  else:
147  raise Exception('No valid destination chosen. Bailing out...')
148  destinationDatabase = getInputRepeat(inputMessage)
149  ntry += 1
150 
151  while True:
152  since = getInput('',
153  '\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 []: ')
154  if not since:
155  since = None
156  break
157  else:
158  try:
159  since = int(since)
160  break
161  except ValueError:
162  logging.error('The since value has to be an integer or empty (null).')
163 
164  userText = getInput('',
165  '\nWrite any comments/text you may want to describe your request\ne.g. Muon alignment scenario for...\nuserText []: ')
166 
167  destinationTags = {}
168  while True:
169  destinationTag = getInput('',
170  '\nWhich is the next destination tag to be added (leave empty to stop)?\ne.g. BeamSpotObjects_PCL_byRun_v0_offline\ndestinationTag []: ')
171  if not destinationTag:
172  if len(destinationTags) == 0:
173  logging.error('There must be at least one destination tag.')
174  continue
175  break
176 
177  if destinationTag in destinationTags:
178  logging.warning(
179  'You already added this destination tag. Overwriting the previous one with this new one.')
180 
181  destinationTags[destinationTag] = {
182  }
183 
184  metadata = {
185  'destinationDatabase': destinationDatabase,
186  'destinationTags': destinationTags,
187  'inputTag': inputTag,
188  'since': since,
189  'userText': userText,
190  }
191 
192  metadata = json.dumps(metadata, sort_keys=True, indent=4)
193  print '\nThis is the generated metadata:\n%s' % metadata
194 
195  if getInput('n',
196  '\nIs it fine (i.e. save in %s and *upload* the conditions if this is the latest file)?\nAnswer [n]: ' % metadataFilename).lower() == 'y':
197  break
198  logging.info('Saving generated metadata in %s...', metadataFilename)
199  with open(metadataFilename, 'wb') as metadataFile:
200  metadataFile.write(metadata)
201 
203  '''A common HTTP exception.
204 
205  self.code is the response HTTP code as an integer.
206  self.response is the response body (i.e. page).
207  '''
208 
209  def __init__(self, code, response):
210  self.code = code
211  self.response = response
212 
213  # Try to extract the error message if possible (i.e. known error page format)
214  try:
215  self.args = (response.split('<p>')[1].split('</p>')[0], )
216  except Exception:
217  self.args = (self.response, )
218 
219 
220 CERN_SSO_CURL_CAPATH = '/etc/pki/tls/certs'
221 
222 class HTTP(object):
223  '''Class used for querying URLs using the HTTP protocol.
224  '''
225 
226  retryCodes = frozenset([502, 503])
227 
228  def __init__(self):
229  self.setBaseUrl()
230  self.setRetries()
231 
232  self.curl = pycurl.Curl()
233  self.curl.setopt(self.curl.COOKIEFILE, '') # in memory
234 
235  #-toDo: make sure we have the right options set here to use ssl
236  #-review(2015-09-25): check and see - action: AP
237  # self.curl.setopt(self.curl.SSL_VERIFYPEER, 1)
238  self.curl.setopt(self.curl.SSL_VERIFYPEER, 0)
239  self.curl.setopt(self.curl.SSL_VERIFYHOST, 2)
240 
241  self.baseUrl = None
242 
243  self.token = None
244 
245  def getCookies(self):
246  '''Returns the list of cookies.
247  '''
248  return self.curl.getinfo(self.curl.INFO_COOKIELIST)
249 
250  def discardCookies(self):
251  '''Discards cookies.
252  '''
253  self.curl.setopt(self.curl.COOKIELIST, 'ALL')
254 
255 
256  def setBaseUrl(self, baseUrl = ''):
257  '''Allows to set a base URL which will be prefixed to all the URLs
258  that will be queried later.
259  '''
260  self.baseUrl = baseUrl
261 
262 
263  def setProxy(self, proxy = ''):
264  '''Allows to set a proxy.
265  '''
266  self.curl.setopt(self.curl.PROXY, proxy)
267 
268 
269  def setTimeout(self, timeout = 0):
270  '''Allows to set a timeout.
271  '''
272  self.curl.setopt(self.curl.TIMEOUT, timeout)
273 
274 
275  def setRetries(self, retries = ()):
276  '''Allows to set retries.
277 
278  The retries are a sequence of the seconds to wait per retry.
279 
280  The retries are done on:
281  * PyCurl errors (includes network problems, e.g. not being able
282  to connect to the host).
283  * 502 Bad Gateway (for the moment, to avoid temporary
284  Apache-CherryPy issues).
285  * 503 Service Temporarily Unavailable (for when we update
286  the frontends).
287  '''
288  self.retries = retries
289 
290  def getToken(self, username, password):
291 
292  url = self.baseUrl + 'token'
293 
294  self.curl.setopt(pycurl.URL, url)
295  self.curl.setopt(pycurl.VERBOSE, 0)
296 
297  #-toDo: check if/why these are needed ...
298  #-ap: hmm ...
299  # self.curl.setopt(pycurl.DNS_CACHE_TIMEOUT, 0)
300  # self.curl.setopt(pycurl.IPRESOLVE, pycurl.IPRESOLVE_V4)
301  #-end hmmm ...
302  #-review(2015-09-25): check and see - action: AP
303 
304 
305  self.curl.setopt(pycurl.HTTPHEADER, ['Accept: application/json'])
306  # self.curl.setopt( self.curl.POST, {})
307  self.curl.setopt(self.curl.HTTPGET, 0)
308 
309  response = cStringIO.StringIO()
310  self.curl.setopt(pycurl.WRITEFUNCTION, response.write)
311  self.curl.setopt(pycurl.USERPWD, '%s:%s' % (username, password) )
312 
313  logging.debug('going to connect to server at: %s' % url )
314 
315  self.curl.perform()
316  code = self.curl.getinfo(pycurl.RESPONSE_CODE)
317  logging.debug('got: %s ', str(code))
318 
319  try:
320  self.token = json.loads( response.getvalue() )['token']
321  except Exception as e:
322  logging.error('http::getToken> got error from server: %s ', str(e) )
323  if 'No JSON object could be decoded' in str(e):
324  return None
325  logging.error("error getting token: %s", str(e))
326  return None
327 
328  logging.debug('token: %s', self.token)
329  logging.debug('returning: %s', response.getvalue())
330 
331  return response.getvalue()
332 
333  def query(self, url, data = None, files = None, keepCookies = True):
334  '''Queries a URL, optionally with some data (dictionary).
335 
336  If no data is specified, a GET request will be used.
337  If some data is specified, a POST request will be used.
338 
339  If files is specified, it must be a dictionary like data but
340  the values are filenames.
341 
342  By default, cookies are kept in-between requests.
343 
344  A HTTPError exception is raised if the response's HTTP code is not 200.
345  '''
346 
347  if not keepCookies:
348  self.discardCookies()
349 
350  url = self.baseUrl + url
351 
352  # make sure the logs are safe ... at least somewhat :)
353  data4log = copy.copy(data)
354  if data4log:
355  if 'password' in data4log.keys():
356  data4log['password'] = '*'
357 
358  retries = [0] + list(self.retries)
359 
360  while True:
361  logging.debug('Querying %s with data %s and files %s (retries left: %s, current sleep: %s)...', url, data4log, files, len(retries), retries[0])
362 
363  time.sleep(retries.pop(0))
364 
365  try:
366  self.curl.setopt(self.curl.URL, url)
367  self.curl.setopt(self.curl.HTTPGET, 1)
368 
369  # from now on we use the token we got from the login
370  self.curl.setopt(pycurl.USERPWD, '%s:""' % ( str(self.token), ) )
371  self.curl.setopt(pycurl.HTTPHEADER, ['Accept: application/json'])
372 
373  if data is not None or files is not None:
374  # If there is data or files to send, use a POST request
375 
376  finalData = {}
377 
378  if data is not None:
379  finalData.update(data)
380 
381  if files is not None:
382  for (key, fileName) in files.items():
383  finalData[key] = (self.curl.FORM_FILE, fileName)
384  self.curl.setopt( self.curl.HTTPPOST, finalData.items() )
385 
386  self.curl.setopt(pycurl.VERBOSE, 0)
387 
388  response = cStringIO.StringIO()
389  self.curl.setopt(self.curl.WRITEFUNCTION, response.write)
390  self.curl.perform()
391 
392  code = self.curl.getinfo(self.curl.RESPONSE_CODE)
393 
394  if code in self.retryCodes and len(retries) > 0:
395  logging.debug('Retrying since we got the %s error code...', code)
396  continue
397 
398  if code != 200:
399  raise HTTPError(code, response.getvalue())
400 
401  return response.getvalue()
402 
403  except pycurl.error as e:
404  if len(retries) == 0:
405  raise e
406  logging.debug('Retrying since we got the %s pycurl exception...', str(e))
407 
408 # common/http.py end
409 
410 def addToTarFile(tarFile, fileobj, arcname):
411  tarInfo = tarFile.gettarinfo(fileobj = fileobj, arcname = arcname)
412  tarInfo.mode = 0o400
413  tarInfo.uid = tarInfo.gid = tarInfo.mtime = 0
414  tarInfo.uname = tarInfo.gname = 'root'
415  tarFile.addfile(tarInfo, fileobj)
416 
417 class ConditionsUploader(object):
418  '''Upload conditions to the CMS conditions uploader service.
419  '''
420 
421  def __init__(self, hostname = defaultHostname, urlTemplate = defaultUrlTemplate):
422  self.hostname = hostname
423  self.urlTemplate = urlTemplate
424  self.userName = None
425  self.http = None
426  self.password = None
427 
428  def setHost( self, hostname ):
429  self.hostname = hostname
430 
431  def signIn(self, username, password):
432  ''' init the server.
433  '''
434  self.http = HTTP()
435  self.http.setBaseUrl(self.urlTemplate % self.hostname)
436  '''Signs in the server.
437  '''
438 
439  logging.info('%s: Signing in user %s ...', self.hostname, username)
440  try:
441  self.token = self.http.getToken(username, password)
442  except Exception as e:
443  logging.error("Caught exception when trying to get token for user %s from %s: %s" % (username, self.hostname, str(e)) )
444  return False
445 
446  if not self.token:
447  logging.error("could not get token for user %s from %s" % (username, self.hostname) )
448  return False
449 
450  logging.debug( "got: '%s'", str(self.token) )
451  self.userName = username
452  self.password = password
453  return True
454 
455  def signInAgain(self):
456  return self.signIn( self.userName, self.password )
457 
458  def signOut(self):
459  '''Signs out the server.
460  '''
461 
462  logging.info('%s: Signing out...', self.hostname)
463  # self.http.query('logout')
464  self.token = None
465 
466 
467  def _checkForUpdates(self):
468  '''Updates this script, if a new version is found.
469  '''
470 
471  logging.debug('%s: Checking if a newer version of this script is available ...', self.hostname)
472  version = int(self.http.query('getUploadScriptVersion'))
473 
474  if version <= __version__:
475  logging.debug('%s: Script is up-to-date.', self.hostname)
476  return
477 
478  logging.info('%s: Updating to a newer version (%s) than the current one (%s): downloading ...', self.hostname, version, __version__)
479 
480  uploadScript = self.http.query('getUploadScript')
481 
482  self.signOut()
483 
484  logging.info('%s: ... saving the new version ...', self.hostname)
485  with open(sys.argv[0], 'wb') as f:
486  f.write(uploadScript)
487 
488  logging.info('%s: ... executing the new version...', self.hostname)
489  os.execl(sys.executable, *([sys.executable] + sys.argv))
490 
491 
492  def uploadFile(self, filename, backend = defaultBackend, temporaryFile = defaultTemporaryFile):
493  '''Uploads a file to the dropBox.
494 
495  The filename can be without extension, with .db or with .txt extension.
496  It will be stripped and then both .db and .txt files are used.
497  '''
498 
499  basepath = filename.rsplit('.db', 1)[0].rsplit('.txt', 1)[0]
500  basename = os.path.basename(basepath)
501 
502  logging.debug('%s: %s: Creating tar file for upload ...', self.hostname, basename)
503 
504  try:
505  tarFile = tarfile.open(temporaryFile, 'w:bz2')
506 
507  with open('%s.db' % basepath, 'rb') as data:
508  addToTarFile(tarFile, data, 'data.db')
509  except Exception as e:
510  msg = 'Error when creating tar file. \n'
511  msg += 'Please check that you have write access to the directory you are running,\n'
512  msg += 'and that you have enough space on this disk (df -h .)\n'
513  logging.error(msg)
514  raise Exception(msg)
515 
516  with tempfile.NamedTemporaryFile() as metadata:
517  with open('%s.txt' % basepath, 'rb') as originalMetadata:
518  json.dump(json.load(originalMetadata), metadata, sort_keys = True, indent = 4)
519 
520  metadata.seek(0)
521  addToTarFile(tarFile, metadata, 'metadata.txt')
522 
523  tarFile.close()
524 
525  logging.debug('%s: %s: Calculating hash...', self.hostname, basename)
526 
527  fileHash = hashlib.sha1()
528  with open(temporaryFile, 'rb') as f:
529  while True:
530  data = f.read(4 * 1024 * 1024)
531  if not data:
532  break
533  fileHash.update(data)
534 
535  fileHash = fileHash.hexdigest()
536  fileInfo = os.stat(temporaryFile)
537  fileSize = fileInfo.st_size
538 
539  logging.debug('%s: %s: Hash: %s', self.hostname, basename, fileHash)
540 
541  logging.info('%s: %s: Uploading file (%s, size %s) to the %s backend...', self.hostname, basename, fileHash, fileSize, backend)
542  os.rename(temporaryFile, fileHash)
543  try:
544  ret = self.http.query('uploadFile',
545  {
546  'backend': backend,
547  'fileName': basename,
548  'userName': self.userName,
549  },
550  files = {
551  'uploadedFile': fileHash,
552  }
553  )
554  except Exception as e:
555  logging.error('Error from uploading: %s' % str(e))
556  ret = json.dumps( { "status": -1, "upload" : { 'itemStatus' : { basename : {'status':'failed', 'info':str(e)}}}, "error" : str(e)} )
557 
558  os.unlink(fileHash)
559 
560  statusInfo = json.loads(ret)['upload']
561  logging.debug( 'upload returned: %s', statusInfo )
562 
563  okTags = []
564  skippedTags = []
565  failedTags = []
566  for tag, info in statusInfo['itemStatus'].items():
567  logging.debug('checking tag %s, info %s', tag, str(json.dumps(info, indent=4,sort_keys=True)) )
568  if 'ok' in info['status'].lower() :
569  okTags.append( tag )
570  logging.info('tag %s successfully uploaded', tag)
571  if 'skip' in info['status'].lower() :
572  skippedTags.append( tag )
573  logging.warning('found tag %s to be skipped. reason: \n ... \t%s ', tag, info['info'])
574  if 'fail' in info['status'].lower() :
575  failedTags.append( tag )
576  logging.error('found tag %s failed to upload. reason: \n ... \t%s ', tag, info['info'])
577 
578  if len(okTags) > 0: logging.info ("tags sucessfully uploaded: %s ", str(okTags) )
579  if len(skippedTags) > 0: logging.warning("tags SKIPped to upload : %s ", str(skippedTags) )
580  if len(failedTags) > 0: logging.error ("tags FAILed to upload : %s ", str(failedTags) )
581 
582  fileLogURL = 'https://%s/logs/dropBox/getFileLog?fileHash=%s'
583  logging.info('file log at: %s', fileLogURL % (self.hostname,fileHash))
584 
585  return len(okTags)>0
586 
587 def authenticateUser(dropBox, options):
588 
589  try:
590  # Try to find the netrc entry
591  (username, account, password) = netrc.netrc().authenticators(options.netrcHost)
592  except Exception:
593  # netrc entry not found, ask for the username and password
594  logging.info(
595  '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.',
596  options.netrcHost)
597 
598  # Try to get a default username
599  defaultUsername = getpass.getuser()
600  if defaultUsername is None:
601  defaultUsername = '(not found)'
602 
603  username = getInput(defaultUsername, '\nUsername [%s]: ' % defaultUsername)
604  password = getpass.getpass('Password: ')
605 
606  # Now we have a username and password, authenticate with them
607  return dropBox.signIn(username, password)
608 
609 
610 def uploadAllFiles(options, arguments):
611 
612  ret = {}
613  ret['status'] = 0
614 
615  # Check that we can read the data and metadata files
616  # If the metadata file does not exist, start the wizard
617  for filename in arguments:
618  basepath = filename.rsplit('.db', 1)[0].rsplit('.txt', 1)[0]
619  basename = os.path.basename(basepath)
620  dataFilename = '%s.db' % basepath
621  metadataFilename = '%s.txt' % basepath
622 
623  logging.info('Checking %s...', basename)
624 
625  # Data file
626  try:
627  with open(dataFilename, 'rb') as dataFile:
628  pass
629  except IOError as e:
630  errMsg = 'Impossible to open SQLite data file %s' %dataFilename
631  logging.error( errMsg )
632  ret['status'] = -3
633  ret['error'] = errMsg
634  return ret
635 
636  # Metadata file
637  try:
638  with open(metadataFilename, 'rb') as metadataFile:
639  pass
640  except IOError as e:
641  if e.errno != errno.ENOENT:
642  errMsg = 'Impossible to open file %s (for other reason than not existing)' %metadataFilename
643  logging.error( errMsg )
644  ret['status'] = -4
645  ret['error'] = errMsg
646  return ret
647 
648  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':
649  errMsg = 'Metadata file %s does not exist' %metadataFilename
650  logging.error( errMsg )
651  ret['status'] = -5
652  ret['error'] = errMsg
653  return ret
654  # Wizard
655  runWizard(basename, dataFilename, metadataFilename)
656 
657  # Upload files
658  try:
659  dropBox = ConditionsUploader(options.hostname, options.urlTemplate)
660 
661  # Authentication
662  if not authenticateUser(dropBox, options):
663  logging.error("Error authenticating user. Aborting.")
664  return { 'status' : -2, 'error' : "Error authenticating user. Aborting." }
665 
666  # At this point we must be authenticated
667  dropBox._checkForUpdates()
668 
669  results = {}
670  for filename in arguments:
671  backend = options.backend
672  basepath = filename.rsplit('.db', 1)[0].rsplit('.txt', 1)[0]
673  metadataFilename = '%s.txt' % basepath
674  with open(metadataFilename, 'rb') as metadataFile:
675  metadata = json.load( metadataFile )
676  # When dest db = prep the hostname has to be set to dev.
677  forceHost = False
678  destDb = metadata['destinationDatabase']
679  if destDb.startswith('oracle://cms_orcon_prod') or destDb.startswith('oracle://cms_orcoff_prep'):
680  if destDb.startswith('oracle://cms_orcoff_prep'):
681  dropBox.setHost( defaultDevHostname )
682  dropBox.signInAgain()
683  forceHost = True
684  results[filename] = dropBox.uploadFile(filename, options.backend, options.temporaryFile)
685  if forceHost:
686  # set back the hostname to the original global setting
687  dropBox.setHost( options.hostname )
688  dropBox.signInAgain()
689  else:
690  results[filename] = False
691  logging.error("DestinationDatabase %s is not valid. Skipping the upload." %destDb)
692  if not results[filename]:
693  if ret['status']<0:
694  ret['status'] = 0
695  ret['status'] += 1
696  ret['files'] = results
697  logging.debug("all files processed, logging out now.")
698 
699  dropBox.signOut()
700 
701  except HTTPError as e:
702  logging.error('got HTTP error: %s', str(e))
703  return { 'status' : -1, 'error' : str(e) }
704 
705  return ret
706 
707 def uploadTier0Files(filenames, username, password, cookieFileName = None):
708  '''Uploads a bunch of files coming from Tier0.
709  This has the following requirements:
710  * Username/Password based authentication.
711  * Uses the online backend.
712  * Ignores errors related to the upload/content (e.g. duplicated file).
713  '''
714 
715  dropBox = ConditionsUploader()
716 
717  dropBox.signIn(username, password)
718 
719  for filename in filenames:
720  try:
721  result = dropBox.uploadFile(filename, backend = 'test')
722  except HTTPError as e:
723  if e.code == 400:
724  # 400 Bad Request: This is an exception related to the upload
725  # being wrong for some reason (e.g. duplicated file).
726  # Since for Tier0 this is not an issue, continue
727  logging.error('HTTP Exception 400 Bad Request: Upload-related, skipping. Message: %s', e)
728  continue
729 
730  # In any other case, re-raise.
731  raise
732 
733  #-toDo: add a flag to say if we should retry or not. So far, all retries are done server-side (Tier-0),
734  # if we flag as failed any retry would not help and would result in the same error (e.g.
735  # when a file with an identical hash is uploaded again)
736  #-review(2015-09-25): get feedback from tests at Tier-0 (action: AP)
737 
738  if not result: # dropbox reported an error when uploading, do not retry.
739  logging.error('Error from dropbox, upload-related, skipping.')
740  continue
741 
742  dropBox.signOut()
743 
744 
745 def main():
746  '''Entry point.
747  '''
748 
749  parser = optparse.OptionParser(usage =
750  'Usage: %prog [options] <file> [<file> ...]\n'
751  )
752 
753  parser.add_option('-d', '--debug',
754  dest = 'debug',
755  action="store_true",
756  default = False,
757  help = 'Switch on printing debug information. Default: %default',
758  )
759 
760  parser.add_option('-b', '--backend',
761  dest = 'backend',
762  default = defaultBackend,
763  help = 'dropBox\'s backend to upload to. Default: %default',
764  )
765 
766  parser.add_option('-H', '--hostname',
767  dest = 'hostname',
768  default = defaultHostname,
769  help = 'dropBox\'s hostname. Default: %default',
770  )
771 
772  parser.add_option('-u', '--urlTemplate',
773  dest = 'urlTemplate',
774  default = defaultUrlTemplate,
775  help = 'dropBox\'s URL template. Default: %default',
776  )
777 
778  parser.add_option('-f', '--temporaryFile',
779  dest = 'temporaryFile',
780  default = defaultTemporaryFile,
781  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',
782  )
783 
784  parser.add_option('-n', '--netrcHost',
785  dest = 'netrcHost',
786  default = defaultNetrcHost,
787  help = 'The netrc host (machine) from where the username and password will be read. Default: %default',
788  )
789 
790  (options, arguments) = parser.parse_args()
791 
792  if len(arguments) < 1:
793  parser.print_help()
794  return -2
795 
796  logLevel = logging.INFO
797  if options.debug:
798  logLevel = logging.DEBUG
799  logging.basicConfig(
800  format = '[%(asctime)s] %(levelname)s: %(message)s',
801  level = logLevel,
802  )
803 
804  results = uploadAllFiles(options, arguments)
805 
806  if not results.has_key('status'):
807  print 'Unexpected error.'
808  return -1
809  ret = results['status']
810  print results
811  print "upload ended with code: %s" %ret
812  #for hash, res in results.items():
813  # print "\t %s : %s " % (hash, str(res))
814  return ret
815 
817 
818  global defaultNetrcHost
819 
820  (username, account, password) = netrc.netrc().authenticators(defaultNetrcHost)
821 
822  filenames = ['testFiles/localSqlite-top2']
823 
824  uploadTier0Files(filenames, username, password, cookieFileName = None)
825 
826 
827 if __name__ == '__main__':
828 
829  sys.exit(main())
830  # testTier0Upload()
Definition: main.py:1
double split
Definition: MVATrainer.cc:139
How EventSelector::AcceptEvent() decides whether to accept an event for output otherwise it is excluding the probing of A single or multiple positive and the trigger will pass if any such matching triggers are PASS or EXCEPTION[A criterion thatmatches no triggers at all is detected and causes a throw.] A single negative with an expectation of appropriate bit checking in the decision and the trigger will pass if any such matching triggers are FAIL or EXCEPTION A wildcarded negative criterion that matches more than one trigger in the trigger list("!*","!HLTx*"if it matches 2 triggers or more) will accept the event if all the matching triggers are FAIL.It will reject the event if any of the triggers are PASS or EXCEPTION(this matches the behavior of"!*"before the partial wildcard feature was incorporated).Triggers which are in the READY state are completely ignored.(READY should never be returned since the trigger paths have been run