CMS 3D CMS Logo

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