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 = 'Dropbox'
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  results = {}
613 
614  # Check that we can read the data and metadata files
615  # If the metadata file does not exist, start the wizard
616  for filename in arguments:
617  basepath = filename.rsplit('.db', 1)[0].rsplit('.txt', 1)[0]
618  basename = os.path.basename(basepath)
619  dataFilename = '%s.db' % basepath
620  metadataFilename = '%s.txt' % basepath
621 
622  logging.info('Checking %s...', basename)
623 
624  # Data file
625  try:
626  with open(dataFilename, 'rb') as dataFile:
627  pass
628  except IOError as e:
629  logging.error('Impossible to open SQLite data file %s', dataFilename)
630  return -3
631 
632  # Metadata file
633  try:
634  with open(metadataFilename, 'rb') as metadataFile:
635  pass
636  except IOError as e:
637  if e.errno != errno.ENOENT:
638  logging.error('Impossible to open file %s (for other reason than not existing)', metadataFilename)
639  return -4
640 
641  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':
642  logging.error('Metadata file %s does not exist', metadataFilename)
643  return -5
644 
645  # Wizard
646  runWizard(basename, dataFilename, metadataFilename)
647 
648  # Upload files
649  try:
650  dropBox = ConditionsUploader(options.hostname, options.urlTemplate)
651 
652  # Authentication
653  if not authenticateUser(dropBox, options):
654  logging.error("Error authenticating user. Aborting.")
655  return { 'status' : -2, 'error' : "Error authenticating user. Aborting." }
656 
657  # At this point we must be authenticated
658  dropBox._checkForUpdates()
659 
660  for filename in arguments:
661  backend = options.backend
662  basepath = filename.rsplit('.db', 1)[0].rsplit('.txt', 1)[0]
663  metadataFilename = '%s.txt' % basepath
664  with open(metadataFilename, 'rb') as metadataFile:
665  metadata = json.load( metadataFile )
666  # When dest db = prep the hostname has to be set to dev.
667  forceHost = False
668  destDb = metadata['destinationDatabase']
669  if destDb.startswith('oracle://cms_orcon_prod') or destDb.startswith('oracle://cms_orcoff_prep'):
670  if destDb.startswith('oracle://cms_orcoff_prep'):
671  dropBox.setHost( defaultDevHostname )
672  dropBox.signInAgain()
673  forceHost = True
674  results[filename] = dropBox.uploadFile(filename, options.backend, options.temporaryFile)
675  if forceHost:
676  # set back the hostname to the original global setting
677  dropBox.setHost( options.hostname )
678  dropBox.signInAgain()
679  else:
680  results[filename] = False
681  logging.error("DestinationDatabase %s is not valid. Skipping the upload." %destDb)
682 
683  logging.debug("all files processed, logging out now.")
684 
685  dropBox.signOut()
686 
687  except HTTPError as e:
688  logging.error('got HTTP error: %s', str(e))
689  return { 'status' : -1, 'error' : str(e) }
690 
691  return results
692 
693 def uploadTier0Files(filenames, username, password, cookieFileName = None):
694  '''Uploads a bunch of files coming from Tier0.
695  This has the following requirements:
696  * Username/Password based authentication.
697  * Uses the online backend.
698  * Ignores errors related to the upload/content (e.g. duplicated file).
699  '''
700 
701  dropBox = ConditionsUploader()
702 
703  dropBox.signIn(username, password)
704 
705  for filename in filenames:
706  try:
707  result = dropBox.uploadFile(filename, backend = 'test')
708  except HTTPError as e:
709  if e.code == 400:
710  # 400 Bad Request: This is an exception related to the upload
711  # being wrong for some reason (e.g. duplicated file).
712  # Since for Tier0 this is not an issue, continue
713  logging.error('HTTP Exception 400 Bad Request: Upload-related, skipping. Message: %s', e)
714  continue
715 
716  # In any other case, re-raise.
717  raise
718 
719  #-toDo: add a flag to say if we should retry or not. So far, all retries are done server-side (Tier-0),
720  # if we flag as failed any retry would not help and would result in the same error (e.g.
721  # when a file with an identical hash is uploaded again)
722  #-review(2015-09-25): get feedback from tests at Tier-0 (action: AP)
723 
724  if not result: # dropbox reported an error when uploading, do not retry.
725  logging.error('Error from dropbox, upload-related, skipping.')
726  continue
727 
728  dropBox.signOut()
729 
730 
731 def main():
732  '''Entry point.
733  '''
734 
735  parser = optparse.OptionParser(usage =
736  'Usage: %prog [options] <file> [<file> ...]\n'
737  )
738 
739  parser.add_option('-d', '--debug',
740  dest = 'debug',
741  action="store_true",
742  default = False,
743  help = 'Switch on printing debug information. Default: %default',
744  )
745 
746  parser.add_option('-b', '--backend',
747  dest = 'backend',
748  default = defaultBackend,
749  help = 'dropBox\'s backend to upload to. Default: %default',
750  )
751 
752  parser.add_option('-H', '--hostname',
753  dest = 'hostname',
754  default = defaultHostname,
755  help = 'dropBox\'s hostname. Default: %default',
756  )
757 
758  parser.add_option('-u', '--urlTemplate',
759  dest = 'urlTemplate',
760  default = defaultUrlTemplate,
761  help = 'dropBox\'s URL template. Default: %default',
762  )
763 
764  parser.add_option('-f', '--temporaryFile',
765  dest = 'temporaryFile',
766  default = defaultTemporaryFile,
767  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',
768  )
769 
770  parser.add_option('-n', '--netrcHost',
771  dest = 'netrcHost',
772  default = defaultNetrcHost,
773  help = 'The netrc host (machine) from where the username and password will be read. Default: %default',
774  )
775 
776  (options, arguments) = parser.parse_args()
777 
778  if len(arguments) < 1:
779  parser.print_help()
780  return -2
781 
782  logLevel = logging.INFO
783  if options.debug:
784  logLevel = logging.DEBUG
785  logging.basicConfig(
786  format = '[%(asctime)s] %(levelname)s: %(message)s',
787  level = logLevel,
788  )
789 
790  results = uploadAllFiles(options, arguments)
791 
792  print "uploadAllFiles returned:"
793  for hash, res in results.items():
794  print "\t %s : %s " % (hash, str(res))
795 
797 
798  global defaultNetrcHost
799 
800  (username, account, password) = netrc.netrc().authenticators(defaultNetrcHost)
801 
802  filenames = ['testFiles/localSqlite-top2']
803 
804  uploadTier0Files(filenames, username, password, cookieFileName = None)
805 
806 
807 if __name__ == '__main__':
808 
809  sys.exit(main())
810  # 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