CMS 3D CMS Logo

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Groups Pages
o2o_helper.py
Go to the documentation of this file.
1 '''
2 Helper Script for StripO2O
3 @author: Huilin Qu
4 '''
5 
6 import os
7 import subprocess
8 import logging
9 import json
10 import smtplib
11 from email.mime.multipart import MIMEMultipart
12 from email.mime.text import MIMEText
13 import sqlite3
14 
16  '''Kill a subprocess without throwing OSError.
17  Used for cleaning up subprocesses when the main script crashes.'''
18  try:
19  p.terminate()
20  except OSError:
21  pass
22 
23 
24 def configLogger(logfile,loglevel=logging.INFO):
25  '''Setting up logging to both file and console.
26  @see: https://docs.python.org/2/howto/logging-cookbook.html
27  '''
28  # set up logging to file
29  logging.basicConfig(level=loglevel,
30  format='[%(asctime)s] %(levelname)s: %(message)s',
31  filename=logfile,
32  filemode='w')
33  # define a Handler which writes INFO messages or higher to the sys.stderr
34  console = logging.StreamHandler()
35  console.setLevel(loglevel)
36  # set a format which is simpler for console use
37  formatter = logging.Formatter('[%(levelname)s] %(message)s')
38  # tell the handler to use this format
39  console.setFormatter(formatter)
40  # add the handler to the root logger
41  logging.getLogger('').addHandler(console)
42 
43 def insert_to_file(template, target, replace_dict):
44  '''Update the template file based on the replace_dict, and write to the target.'''
45  logging.debug('Creating "%s" from template "%s" using dictionary:'%(target, template))
46  logging.debug(replace_dict)
47  with open(template, 'r') as input_file:
48  config=input_file.read()
49  with open(target, 'w') as output_file:
50  for key, value in replace_dict.items():
51  config = config.replace(key, value)
52  output_file.write(config)
53  return config
54 
55 def create_metadata(metadataFilename, inputTag, destTags, destDb, since, userText):
56  '''Create metadata file for the conditionsUpload service.
57  @see: uploadConditions.runWizard()
58  @see: https://twiki.cern.ch/twiki/bin/view/CMS/DropBox
59 
60  Keyword arguments:
61  metadataFilename -- output metadata filename
62  inputTag -- input tag name
63  destTags -- a list of destination tags
64  destDb -- [destinationDatabase] in metadata
65  since -- [since] in metadata
66  userText -- [userText] in metadata
67  '''
68  if isinstance(destTags, str):
69  destTags = [destTags]
70  if since:
71  since = int(since) # convert to int if since is not None (input since can be a str)
72  destinationTags = {}
73  for destinationTag in destTags:
74  destinationTags[destinationTag] = {}
75  metadata = {
76  'destinationDatabase': destDb,
77  'destinationTags': destinationTags,
78  'inputTag': inputTag,
79  'since': since,
80  'userText': userText,
81  }
82  logging.info('Writing metadata in %s', metadataFilename)
83  logging.debug(metadata)
84  with open(metadataFilename, 'wb') as metadataFile:
85  metadataFile.write(json.dumps(metadata, sort_keys=True, indent=4))
86 
87 def upload_payload(dbFile, inputTag, destTags, destDb, since, userText):
88  '''Upload payload using conditionUploader. '''
89  if isinstance(destTags, str):
90  destTags = [destTags]
91  metadataFilename = dbFile.replace('.db', '.txt')
92  create_metadata(metadataFilename, inputTag, destTags, destDb, since, userText)
93  logging.info('Uploading tag [%s] from %s to [%s] in %s:' % (inputTag, dbFile, ','.join(destTags), destDb))
94  command = "uploadConditions.py %s" % dbFile
95  pipe = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
96  out = pipe.communicate()[0]
97  logging.info(out)
98  logging.info('@@@Upload return code = %d@@@' % pipe.returncode)
99  if pipe.returncode != 0:
100  raise RuntimeError('Upload FAILED!')
101 
102 
103 def copy_payload(dbFile, inputTag, destTags, destDb, since, userText):
104  '''Upload payload using conddb copy.'''
105  if isinstance(destTags, str):
106  destTags = [destTags]
107  if destDb.lower() == 'oracle://cms_orcon_prod/cms_conditions':
108  copyDestDb = 'onlineorapro'
109  elif destDb.lower() == 'oracle://cms_orcoff_prep/cms_conditions':
110  copyDestDb = 'oradev'
111  else:
112  copyDestDb = destDb
113  success = 0
114  def copy(dest):
115  command = 'conddb --force --yes --db {db} copy {inputTag} {destTag} --destdb {destDb} --synchronize --note "{note}"'.format(
116  db=dbFile, inputTag=inputTag, destTag=dest, destDb=copyDestDb, note=userText)
117  logging.info('Copy tag [%s] from %s to [%s] in %s:' % (inputTag, dbFile, dest, destDb))
118  logging.debug(command)
119  pipe = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
120  out = pipe.communicate()[0]
121  logging.info(out)
122  return pipe.returncode
123  for dest in destTags:
124  returncode = copy(dest)
125  if returncode == 0: success += 1
126  logging.info('@@@Upload return code = %d@@@' % (success - len(destTags)))
127  if success != len(destTags):
128  raise RuntimeError('Upload FAILED!')
129 
130 
131 def send_mail(subject, message, send_to, send_from, text_attachments=[]):
132  '''Send an email. [send_to] needs to be a list.'''
133  msg = MIMEMultipart()
134  msg['Subject'] = subject
135  msg['From'] = send_from
136  msg['To'] = ','.join(send_to)
137  msg.attach(MIMEText(message))
138 
139  for fn in text_attachments:
140  with open(fn, 'rb') as txtfile:
141  attachment = MIMEText(txtfile.read())
142  attachment.add_header('Content-Disposition', 'attachment', filename=os.path.basename(fn))
143  msg.attach(attachment)
144 
145  s = smtplib.SMTP('localhost')
146  s.sendmail(send_from, send_to, msg.as_string())
147  s.quit()
148 
149 def exists_iov(dbFile, tag):
150  '''Check if there exists any IOV for a specific tag in the given sqlite file.'''
151  dataConnection = sqlite3.connect(dbFile)
152  dataCursor = dataConnection.cursor()
153  dataCursor.execute('select SINCE from IOV where TAG_NAME=:tag_name', {'tag_name' : tag})
154  return len(dataCursor.fetchall()) > 0
def send_mail
Definition: o2o_helper.py:131
def upload_payload
Definition: o2o_helper.py:87
def create_metadata
Definition: o2o_helper.py:55
def exists_iov
Definition: o2o_helper.py:149
def copy_payload
Definition: o2o_helper.py:103
def insert_to_file
Definition: o2o_helper.py:43
def kill_subproc_noexcept
Definition: o2o_helper.py:15
def configLogger
Definition: o2o_helper.py:24
static std::string join(char **cmd)
Definition: RemoteFile.cc:19