test
CMS 3D CMS Logo

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Pages
popcon2dropbox.py
Go to the documentation of this file.
1 import subprocess
2 import json
3 import netrc
4 import sqlite3
5 import os
6 import shutil
7 from datetime import datetime
8 
9 confFileName ='popcon2dropbox.json'
10 fileNameForDropBox = 'input_for_dropbox'
11 dbFileForDropBox = '%s.db' %fileNameForDropBox
12 dbLogFile = '%s_log.db' %fileNameForDropBox
13 errorInUploadFileFolder = 'upload_errors'
14 dateformatForFolder = "%y-%m-%d-%H-%M-%S"
15 dateformatForLabel = "%y-%m-%d %H:%M:%S"
16 
17 """
18 import upload_popcon
19 
20 class CondMetaData(object):
21  def __init__( self, fileName ):
22  self.md = {}
23  self.datef = datetime.now()
24  with open(fileName) as jf:
25  try:
26  self.md = json.load(jf)
27  except ValueError as e:
28  errorMessage = 'CondMetaData.__init__: Problem in decoding JSON file. Original error: ' + e.message
29  raise ValueError(errorMessage)
30 
31  def authPath( self ):
32  apath = ''
33  if self.md.has_key('authenticationPath'):
34  apath = self.md.get('authenticationPath')
35  return apath
36 
37  def authSys( self ):
38  asys = 1
39  if self.md.has_key('authenticationSys'):
40  asys = self.md.get('authenticationSystem')
41  return asys
42 
43  def destinationDatabase( self ):
44  return self.md.get('destinationDatabase')
45 
46  def logDbFileName( self ):
47  return self.md.get('logDbFileName')
48 
49  def records( self ):
50  return self.md.get('records')
51 
52  def dumpMetadataForUpload( self, inputtag, desttag, comment ):
53  uploadMd = {}
54  uploadMd['destinationDatabase'] = self.destinationDatabase()
55  tags = {}
56  tagInfo = {}
57  tags[ desttag ] = tagInfo
58  uploadMd['destinationTags'] = tags
59  uploadMd['inputTag'] = inputtag
60  uploadMd['since'] = None
61  datelabel = self.datef.strftime(dateformatForLabel)
62  uploadMd['userText'] = '%s : %s' %(datelabel,comment)
63  with open( '%s.txt' %fileNameForDropBox, 'wb') as jf:
64  jf.write( json.dumps( uploadMd, sort_keys=True, indent = 2 ) )
65  jf.write('\n')
66 def dumpMetadataForUpload( destDb, destTag, comment ):
67  uploadMd = {}
68  uploadMd['destinationDatabase'] = destDb
69  tags = {}
70  tagInfo = {}
71  tags[ destTag ] = tagInfo
72  uploadMd['destinationTags'] = tags
73  uploadMd['inputTag'] = destTag
74  uploadMd['since'] = None
75  datef = datetime.now()
76  #datelabel = datef.strftime(dateformatForLabel)
77  uploadMd['userText'] = '%s : %s' %(datelabel,comment)
78  with open( '%s.txt' %fileNameForDropBox, 'wb') as jf:
79  jf.write( json.dumps( uploadMd, sort_keys=True, indent = 2 ) )
80  jf.write('\n')
81 """
82 
83 def upload( destDb, destTag, comment, authPath ):
84  #md = CondMetaData(cfileName)
85  datef = datetime.now()
86 
87  # check if the expected input file is there...
88  if not os.path.exists( dbFileForDropBox ):
89  print 'The input sqlite file has not been produced.'
90  return -1
91 
92  empty = True
93  try:
94  dbcon = sqlite3.connect( dbFileForDropBox )
95  dbcur = dbcon.cursor()
96  dbcur.execute('SELECT * FROM IOV')
97  rows = dbcur.fetchall()
98  for r in rows:
99  empty = False
100  dbcon.close()
101  if empty:
102  print 'The input sqlite file produced contains no data. The upload will be skipped.'
103  return 0
104  except Exception as e:
105  print 'Check on input data failed: %s' %str(e)
106  return -2
107 
108  # first remove any existing metadata file...
109  if os.path.exists( '%s.txt' %fileNameForDropBox ):
110  os.remove( '%s.txt' %fileNameForDropBox )
111 
112  ret = 0
113  # dump Metadata for the Upload
114  uploadMd = {}
115  uploadMd['destinationDatabase'] = destDb
116  tags = {}
117  tagInfo = {}
118  tags[ destTag ] = tagInfo
119  uploadMd['destinationTags'] = tags
120  uploadMd['inputTag'] = destTag
121  uploadMd['since'] = None
122  datelabel = datef.strftime(dateformatForLabel)
123  commentStr = ''
124  if not comment is None:
125  commentStr = comment
126  uploadMd['userText'] = '%s : %s' %(datelabel,commentStr)
127  with open( '%s.txt' %fileNameForDropBox, 'wb') as jf:
128  jf.write( json.dumps( uploadMd, sort_keys=True, indent = 2 ) )
129  jf.write('\n')
130 
131  # run the upload
132  uploadCommand = 'uploadConditions.py %s' %fileNameForDropBox
133  if not authPath is None:
134  uploadCommand += ' -a %s' %authPath
135  try:
136  pipe = subprocess.Popen( uploadCommand, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT )
137  stdout = pipe.communicate()[0]
138  print stdout
139  retCode = pipe.returncode
140  if retCode != 0:
141  # save a copy of the files in case of upload failure...
142  leafFolderName = datef.strftime(dateformatForFolder)
143  fileFolder = os.path.join( errorInUploadFileFolder, leafFolderName)
144  if not os.path.exists(fileFolder):
145  os.makedirs(fileFolder)
146  df= '%s.db' %fileNameForDropBox
147  mf= '%s.txt' %fileNameForDropBox
148  dataDestFile = os.path.join( fileFolder, df)
149  if not os.path.exists(dataDestFile):
150  shutil.copy2(df, dataDestFile)
151  shutil.copy2(mf,os.path.join(fileFolder,mf))
152  print "Upload failed. Data file and metadata saved in folder '%s'" %os.path.abspath(fileFolder)
153  ret |= retCode
154  except Exception as e:
155  ret |= 1
156  print e
157  return ret
158 
159 def run( args ):
160  if os.path.exists( '%s.db' %fileNameForDropBox ):
161  print "Removing files with name %s" %fileNameForDropBox
162  os.remove( '%s.db' %fileNameForDropBox )
163  if os.path.exists( '%s.txt' %fileNameForDropBox ):
164  os.remove( '%s.txt' %fileNameForDropBox )
165  command = 'cmsRun %s ' %args.job_file
166  command += ' destinationDatabase=%s' %args.destDb
167  command += ' destinationTag=%s' %args.destTag
168  command += ' 2>&1'
169  pipe = subprocess.Popen( command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT )
170  stdout = pipe.communicate()[0]
171  retCode = pipe.returncode
172  print stdout
173  print 'Return code is: %s' %retCode
174  if retCode!=0:
175  print 'O2O job failed. Skipping upload.'
176  return retCode
177  return upload( args.destDb, args.destTag, args.comment, args.auth )