CMS 3D CMS Logo

List of all members | Public Member Functions | Public Attributes | Private Member Functions
upload_popcon.ConditionsUploader Class Reference
Inheritance diagram for upload_popcon.ConditionsUploader:

Public Member Functions

def __init__ (self, hostname=defaultHostname, urlTemplate=defaultUrlTemplate)
 
def setHost (self, hostname)
 
def signIn (self, username, password)
 
def signInAgain (self)
 
def signOut (self)
 
def uploadFile (self, filename, backend=defaultBackend, temporaryFile=defaultTemporaryFile)
 

Public Attributes

 hostname
 
 http
 
 password
 
 token
 
 urlTemplate
 
 userName
 

Private Member Functions

def _uploadFile (self, filename, backend=defaultBackend, temporaryFile=defaultTemporaryFile)
 

Detailed Description

Upload conditions to the CMS conditions uploader service.

Definition at line 259 of file upload_popcon.py.

Constructor & Destructor Documentation

◆ __init__()

def upload_popcon.ConditionsUploader.__init__ (   self,
  hostname = defaultHostname,
  urlTemplate = defaultUrlTemplate 
)

Definition at line 263 of file upload_popcon.py.

263  def __init__(self, hostname = defaultHostname, urlTemplate = defaultUrlTemplate):
264  self.hostname = hostname
265  self.urlTemplate = urlTemplate
266  self.userName = None
267  self.http = None
268  self.password = None
269 

Member Function Documentation

◆ _uploadFile()

def upload_popcon.ConditionsUploader._uploadFile (   self,
  filename,
  backend = defaultBackend,
  temporaryFile = defaultTemporaryFile 
)
private

Definition at line 340 of file upload_popcon.py.

340  def _uploadFile(self, filename, backend = defaultBackend, temporaryFile = defaultTemporaryFile):
341 
342  basepath = filename.rsplit('.db', 1)[0].rsplit('.txt', 1)[0]
343  basename = os.path.basename(basepath)
344 
345  logging.debug('%s: %s: Creating tar file for upload ...', self.hostname, basename)
346 
347  try:
348  tarFile = tarfile.open(temporaryFile, 'w:bz2')
349 
350  with open('%s.db' % basepath, 'rb') as data:
351  addToTarFile(tarFile, data, 'data.db')
352  except Exception as e:
353  msg = 'Error when creating tar file. \n'
354  msg += 'Please check that you have write access to the directory you are running,\n'
355  msg += 'and that you have enough space on this disk (df -h .)\n'
356  logging.error(msg)
357  raise Exception(msg)
358 
359  with tempfile.NamedTemporaryFile() as metadata:
360  with open('%s.txt' % basepath, 'rb') as originalMetadata:
361  json.dump(json.load(originalMetadata), metadata, sort_keys = True, indent = 4)
362 
363  metadata.seek(0)
364  addToTarFile(tarFile, metadata, 'metadata.txt')
365 
366  tarFile.close()
367 
368  logging.debug('%s: %s: Calculating hash...', self.hostname, basename)
369 
370  fileHash = hashlib.sha1()
371  with open(temporaryFile, 'rb') as f:
372  while True:
373  data = f.read(4 * 1024 * 1024)
374  if not data:
375  break
376  fileHash.update(data)
377 
378  fileHash = fileHash.hexdigest()
379  fileInfo = os.stat(temporaryFile)
380  fileSize = fileInfo.st_size
381 
382  logging.debug('%s: %s: Hash: %s', self.hostname, basename, fileHash)
383 
384  logging.info('%s: %s: Uploading file (%s, size %s) to the %s backend...', self.hostname, basename, fileHash, fileSize, backend)
385  os.rename(temporaryFile, fileHash)
386  try:
387  ret = self.http.query('uploadFile',
388  {
389  'backend': backend,
390  'fileName': basename,
391  'userName': self.userName,
392  },
393  files = {
394  'uploadedFile': fileHash,
395  }
396  )
397  except Exception as e:
398  logging.error('Error from uploading: %s' % str(e))
399  ret = json.dumps( { "status": -1, "upload" : { 'itemStatus' : { basename : {'status':'failed', 'info':str(e)}}}, "error" : str(e)} )
400 
401  os.unlink(fileHash)
402 
403  statusInfo = json.loads(ret)['upload']
404  logging.debug( 'upload returned: %s', statusInfo )
405 
406  okTags = []
407  skippedTags = []
408  failedTags = []
409  for tag, info in statusInfo['itemStatus'].items():
410  logging.debug('checking tag %s, info %s', tag, str(json.dumps(info, indent=4,sort_keys=True)) )
411  if 'ok' in info['status'].lower() :
412  okTags.append( tag )
413  logging.info('tag %s successfully uploaded', tag)
414  if 'skip' in info['status'].lower() :
415  skippedTags.append( tag )
416  logging.warning('found tag %s to be skipped. reason: \n ... \t%s ', tag, info['info'])
417  if 'fail' in info['status'].lower() :
418  failedTags.append( tag )
419  logging.error('found tag %s failed to upload. reason: \n ... \t%s ', tag, info['info'])
420 
421  if len(okTags) > 0: logging.info ("tags sucessfully uploaded: %s ", str(okTags) )
422  if len(skippedTags) > 0: logging.warning("tags SKIPped to upload : %s ", str(skippedTags) )
423  if len(failedTags) > 0: logging.error ("tags FAILed to upload : %s ", str(failedTags) )
424 
425  fileLogURL = 'https://%s/logs/dropBox/getFileLog?fileHash=%s'
426  logging.info('file log at: %s', fileLogURL % (self.hostname,fileHash))
427 
428  return len(okTags)>0

References upload_popcon.addToTarFile(), upload_popcon.ConditionsUploader.hostname, upload_popcon.ConditionsUploader.http, mps_monitormerge.items, str, cond::auth::ServiceCredentials.userName, cond::CredentialData.userName, and upload_popcon.ConditionsUploader.userName.

Referenced by upload_popcon.ConditionsUploader.uploadFile().

◆ setHost()

def upload_popcon.ConditionsUploader.setHost (   self,
  hostname 
)

Definition at line 270 of file upload_popcon.py.

270  def setHost( self, hostname ):
271  self.hostname = hostname
272 

References upload_popcon.ConditionsUploader.hostname.

Referenced by upload_popcon.ConditionsUploader.uploadFile().

◆ signIn()

def upload_popcon.ConditionsUploader.signIn (   self,
  username,
  password 
)
init the server.

Definition at line 273 of file upload_popcon.py.

273  def signIn(self, username, password):
274  ''' init the server.
275  '''
276  self.http = HTTP()
277  if socket.getfqdn().strip().endswith('.cms'):
278  self.http.setProxy('https://cmsproxy.cms:3128/')
279  self.http.setBaseUrl(self.urlTemplate % self.hostname)
280  '''Signs in the server.
281  '''
282 
283  logging.info('%s: Signing in user %s ...', self.hostname, username)
284  try:
285  self.token = self.http.getToken(username, password)
286  except Exception as e:
287  logging.error("Caught exception when trying to get token for user %s from %s: %s" % (username, self.hostname, str(e)) )
288  return False
289 
290  if not self.token:
291  logging.error("could not get token for user %s from %s" % (username, self.hostname) )
292  return False
293 
294  logging.debug( "got: '%s'", str(self.token) )
295  self.userName = username
296  self.password = password
297  return True
298 

References upload_popcon.ConditionsUploader.hostname, upload_popcon.ConditionsUploader.http, digitizers_cfi.strip, and upload_popcon.ConditionsUploader.urlTemplate.

Referenced by upload_popcon.ConditionsUploader.signInAgain().

◆ signInAgain()

def upload_popcon.ConditionsUploader.signInAgain (   self)

◆ signOut()

def upload_popcon.ConditionsUploader.signOut (   self)
Signs out the server.

Definition at line 302 of file upload_popcon.py.

302  def signOut(self):
303  '''Signs out the server.
304  '''
305 
306  logging.info('%s: Signing out...', self.hostname)
307  # self.http.query('logout')
308  self.token = None
309 
310 

References upload_popcon.ConditionsUploader.hostname, upload_popcon.HTTP.token, and upload_popcon.ConditionsUploader.token.

Referenced by uploadConditions.ConditionsUploader._checkForUpdates().

◆ uploadFile()

def upload_popcon.ConditionsUploader.uploadFile (   self,
  filename,
  backend = defaultBackend,
  temporaryFile = defaultTemporaryFile 
)
Uploads a file to the dropBox.

The filename can be without extension, with .db or with .txt extension.
It will be stripped and then both .db and .txt files are used.

Definition at line 311 of file upload_popcon.py.

311  def uploadFile(self, filename, backend = defaultBackend, temporaryFile = defaultTemporaryFile):
312  '''Uploads a file to the dropBox.
313 
314  The filename can be without extension, with .db or with .txt extension.
315  It will be stripped and then both .db and .txt files are used.
316  '''
317 
318  basepath = filename.rsplit('.db', 1)[0].rsplit('.txt', 1)[0]
319  metadataFilename = '%s.txt' % basepath
320  with open(metadataFilename, 'rb') as metadataFile:
321  metadata = json.load( metadataFile )
322  # When dest db = prep the hostname has to be set to dev.
323  forceHost = False
324  destDb = metadata['destinationDatabase']
325  ret = False
326  if destDb.startswith('oracle://cms_orcon_prod') or destDb.startswith('oracle://cms_orcoff_prep'):
327  if destDb.startswith('oracle://cms_orcoff_prep'):
328  self.setHost( defaultDevHostname )
329  self.signInAgain()
330  forceHost = True
331  ret = self._uploadFile(filename, backend, temporaryFile)
332  if forceHost:
333  # set back the hostname to the original global setting
334  self.setHost( defaultHostname )
335  self.signInAgain()
336  else:
337  logging.error("DestinationDatabase %s is not valid. Skipping the upload." %destDb)
338  return ret
339 

References upload_popcon.ConditionsUploader._uploadFile(), upload_popcon.ConditionsUploader.setHost(), and upload_popcon.ConditionsUploader.signInAgain().

Member Data Documentation

◆ hostname

upload_popcon.ConditionsUploader.hostname

◆ http

upload_popcon.ConditionsUploader.http

◆ password

upload_popcon.ConditionsUploader.password

◆ token

upload_popcon.ConditionsUploader.token

◆ urlTemplate

upload_popcon.ConditionsUploader.urlTemplate

◆ userName

upload_popcon.ConditionsUploader.userName
upload_popcon.addToTarFile
def addToTarFile(tarFile, fileobj, arcname)
Definition: upload_popcon.py:252
digitizers_cfi.strip
strip
Definition: digitizers_cfi.py:19
mps_monitormerge.items
list items
Definition: mps_monitormerge.py:29
conditionUploadTest.uploadFile
def uploadFile(fileName, logFileName)
Definition: conditionUploadTest.py:88
query
Definition: query.py:1
str
#define str(s)
Definition: TestProcessor.cc:53
Exception
HTTP
Definition: HTTP.py:1
EcalCondTools.getToken
def getToken(db, tag, since)
Definition: EcalCondTools.py:334