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