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