CMS 3D CMS Logo

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Pages
cmsLHEtoEOSManager.py
Go to the documentation of this file.
1 #! /usr/bin/env python
2 
3 __version__ = "$Revision: 1.12 $"
4 
5 import os
6 import subprocess
7 import time
8 import re
9 
10 defaultEOSRootPath = '/eos/cms/store/lhe'
11 defaultEOSLoadPath = 'root://eoscms/'
12 defaultEOSlistCommand = 'xrd eoscms dirlist '
13 defaultEOSmkdirCommand = 'xrd eoscms mkdir '
14 defaultEOSfeCommand = 'xrd eoscms existfile '
15 defaultEOScpCommand = 'xrdcp -np '
16 
17 def findXrdDir(theDirRecord):
18 
19  elements = theDirRecord.split(' ')
20  if len(elements) > 1:
21  return elements[-1].rstrip('\n').split('/')[-1]
22  else:
23  return None
24 
25 def articleExist(artId):
26 
27  itExists = False
28  theCommand = defaultEOSlistCommand+' '+defaultEOSRootPath
29  dirList = subprocess.Popen(["/bin/sh","-c",theCommand], stdout=subprocess.PIPE)
30  for line in dirList.stdout.readlines():
31  if findXrdDir(line) == str(artId):
32  itExists = True
33 
34  return itExists
35 
37 
38  artList = [0]
39 
40  theCommand = defaultEOSlistCommand+' '+defaultEOSRootPath
41  dirList = subprocess.Popen(["/bin/sh","-c",theCommand], stdout=subprocess.PIPE)
42  for line in dirList.stdout.readlines():
43  try:
44  if line.rstrip('\n') != '':
45  artList.append(int(findXrdDir(line)))
46  except:
47  break
48 
49  return max(artList)
50 
51 
52 def fileUpload(uploadPath,lheList, checkSumList, reallyDoIt):
53 
54  inUploadScript = ''
55  index = 0
56  for f in lheList:
57  realFileName = f.split('/')[-1]
58  # Check the file existence
59  newFileName = uploadPath+'/'+str(realFileName)
60  addFile = True
61  additionalOption = ''
62  theCommand = defaultEOSfeCommand+' '+newFileName
63  exeFullList = subprocess.Popen(["/bin/sh","-c",theCommand], stdout=subprocess.PIPE)
64  result = exeFullList.stdout.readlines()
65  if result[0].rstrip('\n') == 'The file exists.':
66  addFile = False
67  print 'File '+newFileName+' already exists: do you want to overwrite? [y/n]'
68  reply = raw_input()
69  if reply == 'y' or reply == 'Y':
70  addFile = True
71  additionalOption = ' -f '
72  print ''
73  print 'Overwriting file '+newFileName+'\n'
74  # add the file
75  if addFile:
76 # print 'Adding file '+str(f)+'\n'
77  inUploadScript = defaultEOScpCommand + additionalOption + ' ' + str(f) + ' ' + defaultEOSLoadPath+uploadPath + '/' + str(realFileName)
78  print 'Uploading file %s...' % str(f)
79  if reallyDoIt:
80  exeRealUpload = subprocess.Popen(["/bin/sh","-c",inUploadScript])
81  exeRealUpload.communicate()
82  eosCheckSumCommand = '/afs/cern.ch/project/eos/installation/0.3.15/bin/eos.select find --checksum ' + uploadPath + '/' + str(realFileName) + ' | awk \'{print $2}\' | cut -d= -f2'
83  exeEosCheckSum = subprocess.Popen(eosCheckSumCommand ,shell=True, stdout=subprocess.PIPE)
84  EosCheckSum = exeEosCheckSum.stdout.read()
85  assert exeEosCheckSum.wait() == 0
86  print 'checksum: eos = ' + EosCheckSum + 'orig file = ' + checkSumList[index] + '\n'
87  if checkSumList[index] not in EosCheckSum:
88  print 'WARNING! The checksum for file ' + str(realFileName) + ' in EOS\n'
89  print EosCheckSum + '\n'
90  print 'does not match the checksum of the original one\n'
91  print checkSumList[index] + '\n'
92  print 'please try to re-upload file ' + str(realFileName) + ' to EOS.\n'
93  index = index+1
94 
95 # launch the upload shell script
96 
97 # print '\n Launching upload script \n'+inUploadScript+'\n at '+time.asctime(time.localtime(time.time()))+' ...\n'
98 # if reallyDoIt:
99 # exeRealUpload = subprocess.Popen(["/bin/sh","-c",inUploadScript])
100 # exeRealUpload.communicate()
101  print '\n Upload ended at '+time.asctime(time.localtime(time.time()))
102 
103 #################################################################################################
104 
105 if __name__ == '__main__':
106 
107  import optparse
108 
109  # Here we define an option parser to handle commandline options..
110  usage='cmsLHEtoEOSManager.py <options>'
111  parser = optparse.OptionParser(usage)
112  parser.add_option('-f', '--file',
113  help='LHE local file list to be uploaded, separated by ","' ,
114  default='',
115  dest='fileList')
116 
117  parser.add_option('-F', '--files-from', metavar = 'FILE',
118  help='File containing the list of LHE local files be uploaded, one file per line')
119 
120  parser.add_option('-n', '--new',
121  help='Create a new article' ,
122  action='store_true',
123  default=False,
124  dest='newId')
125 
126  parser.add_option('-u', '--update',
127  help='Update the article <Id>' ,
128  default=0,
129  dest='artIdUp')
130 
131  parser.add_option('-l', '--list',
132  help='List the files in article <Id>' ,
133  default=0,
134  dest='artIdLi')
135 
136  parser.add_option('-d', '--dry-run',
137  help='dry run, it does nothing, but you can see what it would do',
138  action='store_true',
139  default=False,
140  dest='dryRun')
141 
142  parser.add_option('-c', '--compress',
143  help='compress the local .lhe file with xz before upload',
144  action='store_true',
145  default=False,
146  dest='compress')
147 
148  (options,args) = parser.parse_args()
149 
150  # print banner
151 
152  print ''
153  print 'cmsLHEtoEOSmanager '+__version__[1:-1]
154  print ''
155  print 'Running on ',time.asctime(time.localtime(time.time()))
156  print ''
157 
158  reallyDoIt = not options.dryRun
159 
160  # Now some fault control. If an error is found we raise an exception
161  if not options.newId and options.artIdUp==0 and options.artIdLi==0:
162  raise Exception('Please specify the action to be taken, either "-n", "-u" or "-l"!')
163 
164  if options.fileList == '' and not options.files_from and (options.newId or options.artIdUp!=0):
165  raise Exception('Please provide the input file list!')
166 
167  if (options.newId and (options.artIdUp != 0 or options.artIdLi != 0)) or (options.artIdUp != 0 and options.artIdLi != 0):
168  raise Exception('Options "-n", "-u" and "-l" are mutually exclusive, please choose only one!')
169 
170  if options.newId:
171  print 'Action: create new article\n'
172  elif options.artIdUp != 0:
173  print 'Action: update article '+str(options.artIdUp)+'\n'
174  elif options.artIdLi != 0:
175  print 'Action: list content of article '+str(options.artIdLi)+'\n'
176 
177  if options.artIdLi==0:
178  theList = []
179  if len(options.fileList) > 0:
180  theList=(options.fileList.split(','))
181 
182  if options.files_from:
183  try:
184  f = open(options.files_from)
185  except IOError:
186  raise Exception('Cannot open the file list, \'%s\'' % options.files_from)
187  for l in f:
188  l = l.strip()
189  if len(l) == 0 or l[0] == '#':
190  continue
191  theList.append(l)
192 
193  theCompressedFilesList = []
194  theCheckSumList = []
195  for f in theList:
196  # Check the file name extension
197  print f
198  if not ( f.lower().endswith(".lhe") or f.lower().endswith(".lhe.xz") ):
199  raise Exception('Input file name must have the "lhe" or "lhe.xz" final extension!')
200  if( f.lower().endswith(".lhe.xz") ):
201  print "Important! Input file "+f+" is already zipped: please make sure you verified its integrity with xmllint before zipping it. You can do it with:\n"
202  print "xmllint file.lhe\n"
203  print "Otherwise it is best to pass the unzipped file to this script and let it check its integrity and compress the file with the --compress option\n"
204  exeCheckSum = subprocess.Popen(["/afs/cern.ch/cms/caf/bin/cms_adler32",f], stdout=subprocess.PIPE)
205  getCheckSum = subprocess.Popen(["awk", "{print $1}"], stdin=exeCheckSum.stdout, stdout=subprocess.PIPE)
206  exeCheckSum.stdout.close()
207  output,err = getCheckSum.communicate()
208  print 'orig file checksum = ' + output + '\n'
209  theCheckSumList.append(output)
210  # Check the local file existence
211  if not os.path.exists(f):
212  raise Exception('Input file '+f+' does not exists')
213  if( f.lower().endswith(".lhe") ):
214  theCheckIntegrityCommand = 'xmllint -noout '+f
215  exeCheckIntegrity = subprocess.Popen(["/bin/sh","-c", theCheckIntegrityCommand])
216  intCode = exeCheckIntegrity.wait()
217  if(intCode is not 0):
218  raise Exception('Input file '+f+ ' is corrupted')
219  if reallyDoIt and options.compress:
220  print "Compressing file",f
221  if( f.lower().endswith(".lhe.xz") ):
222  raise Exception('Input file '+f+' is already compressed! This is inconsistent with the --compress option!')
223  theCompressionCommand = 'xz '+f
224  exeCompression = subprocess.Popen(["/bin/sh","-c",theCompressionCommand])
225  exeCompression.communicate()
226  exeCheckSum = subprocess.Popen(["/afs/cern.ch/cms/caf/bin/cms_adler32",f+".xz"], stdout=subprocess.PIPE)
227  getCheckSum = subprocess.Popen(["awk", "{print $1}"], stdin=exeCheckSum.stdout, stdout=subprocess.PIPE)
228  exeCheckSum.stdout.close()
229  output,err = getCheckSum.communicate()
230  print 'orig file checksum = ' + output + '\n'
231  theCheckSumList.append(output)
232  theCompressedFilesList.append(f+'.xz')
233  if reallyDoIt and options.compress:
234  theList = theCompressedFilesList
235 
236  newArt = 0
237  uploadPath = ''
238 
239 # new article
240 
241  if options.newId:
242  oldArt = lastArticle()
243  newArt = oldArt+1
244  print 'Creating new article with identifier '+str(newArt)+' ...\n'
245  uploadPath = defaultEOSRootPath+'/'+str(newArt)
246  theCommand = defaultEOSmkdirCommand+' '+uploadPath
247  if reallyDoIt:
248  exeUpload = subprocess.Popen(["/bin/sh","-c",theCommand])
249  exeUpload.communicate()
250 
251 # update article
252 
253  elif options.artIdUp != 0:
254  newArt = options.artIdUp
255  if articleExist(newArt):
256  uploadPath = defaultEOSRootPath+'/'+str(newArt)
257  else:
258  raise Exception('Article '+str(newArt)+' to be updated does not exist!')
259 
260 # list article
261 
262  elif options.artIdLi !=0:
263  listPath = defaultEOSRootPath+'/'+str(options.artIdLi)
264  theCommand = defaultEOSlistCommand+' '+listPath
265  exeList = subprocess.Popen(["/bin/sh","-c",theCommand], stdout=subprocess.PIPE)
266  for line in exeList.stdout.readlines():
267  if findXrdDir(line) != None:
268  print findXrdDir(line)
269 
270 
271  if newArt > 0:
272  fileUpload(uploadPath,theList, theCheckSumList, reallyDoIt)
273  listPath = defaultEOSRootPath+'/'+str(newArt)
274  print ''
275  print 'Listing the '+str(newArt)+' article content after upload:'
276  theCommand = defaultEOSlistCommand+' '+listPath
277  if reallyDoIt:
278  exeFullList = subprocess.Popen(["/bin/sh","-c",theCommand])
279  exeFullList.communicate()
280  else:
281  print 'Dry run, nothing was done'
282 
const T & max(const T &a, const T &b)
if(conf.exists("allCellsPositionCalc"))
double split
Definition: MVATrainer.cc:139