test
CMS 3D CMS Logo

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Pages
crabWrap.py
Go to the documentation of this file.
1 import os,time,sys
2 from crab import Crab,common,parseOptions,CrabException
3 from crabStatusFromReport import crabStatusFromReport
4 
5 def computeSummaryCRAB260(up_task):
6  """
7  Computes jobs summary for given task
8  """
9  taskId = str(up_task['name'])
10  task_unique_name = str(up_task['name'])
11  ended = None
12 
13  summary = {}
14  nJobs = 0
15  for job in up_task.jobs :
16  id = str(job.runningJob['jobId'])
17  jobStatus = str(job.runningJob['statusScheduler'])
18  jobState = str(job.runningJob['state'])
19  dest = str(job.runningJob['destination']).split(':')[0]
20  exe_exit_code = str(job.runningJob['applicationReturnCode'])
21  job_exit_code = str(job.runningJob['wrapperReturnCode'])
22  ended = str(job['closed'])
23  printline=''
24  if dest == 'None' : dest = ''
25  if exe_exit_code == 'None' : exe_exit_code = ''
26  if job_exit_code == 'None' : job_exit_code = ''
27  if job.runningJob['state'] == 'SubRequested' : jobStatus = 'Submitting'
28  if job.runningJob['state'] == 'Terminated': jobStatus = 'Done'
29 
30  if jobStatus in summary: summary[jobStatus] += 1
31  else: summary[jobStatus] = 1
32  nJobs += 1
33 
34  for item in summary: summary[item] = 100.*summary[item]/nJobs
35 
36  return summary
37 
38 def computeSummaryCRAB251(up_task):
39  "Computes jobs summary for given task"
40 
41  taskId = str(up_task['name'])
42  task_unique_name = str(up_task['name'])
43  ended = None
44 
45  summary = {}
46  nJobs = 0
47  for job in up_task.jobs :
48  id = str(job.runningJob['jobId'])
49  jobStatus = str(job.runningJob['statusScheduler'])
50  dest = str(job.runningJob['destination']).split(':')[0]
51  exe_exit_code = str(job.runningJob['applicationReturnCode'])
52  job_exit_code = str(job.runningJob['wrapperReturnCode'])
53  ended = str(job['standardInput'])
54  printline=''
55  if dest == 'None' : dest = ''
56  if exe_exit_code == 'None' : exe_exit_code = ''
57  if job_exit_code == 'None' : job_exit_code = ''
58  #printline+="%-6s %-18s %-36s %-13s %-16s %-4s" % (id,jobStatus,dest,exe_exit_code,job_exit_code,ended)
59  #print printline
60  if jobStatus in summary: summary[jobStatus] += 1
61  else: summary[jobStatus] = 1
62  nJobs += 1
63 
64  for item in summary: summary[item] = 100.*summary[item]/nJobs
65 
66  return summary
67 
68 computeSummary = computeSummaryCRAB260
69 
71  """
72  Returns jobs summary
73  """
74  task = common._db.getTask()
75  upTask = common.scheduler.queryEverything(task['id'])
76  return computeSummary(upTask)
77 
78 def summaryServer(self):
79  """
80  Returns jobs summary
81  """
82  #self.resynchClientSide()
83 
84  upTask = common._db.getTask()
85  return computeSummary(upTask)
86 
87 """
88 # Add method to Status classes
89 import Status
90 import StatusServer
91 Status.Status.summary = summaryStandAlone
92 StatusServer.StatusServer.summary = summaryServer
93 """
94 
95 def crabAction(options, action = None):
96 
97  options = parseOptions(options)
98 
99  crab = Crab()
100  result = None
101  try:
102  crab.initialize_(options)
103  crab.run()
104  if action: result = action(crab)
105  del crab
106  print 'Log file is %s%s.log'%(common.work_space.logDir(),common.prog_name)
107  except CrabException as e:
108  del crab
109  #print '\n' + common.prog_name + ': ' + str(e) + '\n'
110  raise
111 
112  if (common.logger): common.logger.delete()
113 
114  if result: return result
115 
116 def crabActionCRAB251(options, action = None):
117 
118  options = parseOptions(options)
119 
120  result = None
121  try:
122  crab = Crab(options)
123  crab.run()
124  common.apmon.free()
125  if action: result = action(crab)
126  del crab
127  #print 'Log file is %s%s.log'%(common.work_space.logDir(),common.prog_name)
128  #print '\n############################## E N D ####################################\n'
129  except CrabException as e:
130  print '\n' + common.prog_name + ': ' + str(e) + '\n'
131  pass
132  pass
133  #if (common.logger): common.logger.delete()
134 
135  if result: return result
136 
137 def crabCreate(dir = '.', crabCfg_name = 'crab.cfg'):
138 
139  cwd = os.getcwd()
140  os.chdir(dir)
141 
142  options = ['-create','-cfg',crabCfg_name]
143 
144  project = crabAction(options,lambda crab: common.work_space.topDir())
145 
146  os.chdir(cwd)
147 
148  return project
149 
150 def crabSubmit(project):
151  options = ['-submit','-c',project]
152 
153  crabAction(options)
154 
155  return
156 
157 def crabStatus(project):
158  options = ['-status']
159  if project:
160  options.append('-c')
161  options.append(project)
162 
163  def action(crab):
164  #act = '-status'
165  #return crab.actions[act].summary()
166  xml = crab.cfg_params.get("USER.xml_report",'')
167  return common.work_space.shareDir() + xml
168 
169  xmlreport = crabAction(options,action)
170  status = crabStatusFromReport(xmlreport)
171 
172  return status
173 
174 def convertStatus(status):
175  """
176  doneStatus = ['Done','Done (success)','Cleared','Retrieved']
177  failedStatus = ['Aborted','Done (failed)','Killed','Cancelled']
178  ignoreStatus = ['Created']
179  """
180  doneStatus = ['SD','E']
181  failedStatus = ['A','DA','K']
182  runningStatus = ['R']
183  ignoreStatus = ['C']
184  sumDone = 0.0
185  sumFailed = 0.0
186  sumRunning = 0.0
187  sumIgnore = 0.0
188  for key in status:
189  if key in doneStatus: sumDone += status[key]
190  if key in failedStatus: sumFailed += status[key]
191  if key in runningStatus: sumRunning += status[key]
192  if key in ignoreStatus: sumIgnore += status[key]
193 
194  # frac(done)' = N*frac(done)/(N - N*frac(ignore)) = frac(done)/(1 - frac(ignore))
195  fracDone = 100.0*sumDone/(100.0 - sumIgnore)
196  fracFailed = 100.0*sumFailed/(100.0 - sumIgnore)
197  fracRun = 100.0*sumRunning/(100.0 - sumIgnore)
198 
199  result = {'Finished':fracDone,
200  'Failed':fracFailed,
201  'Running':fracRun}
202 
203  return result
204 
205 def checkStatus(project, threshold = 95.0):
206 
207  status = crabStatus(project)
208 
209  print "Percentage of jobs per status:"
210  maxLength = max( [len(x) for x in status] )
211  for item in status:
212  print "%*s: %.0f%%" % (maxLength,item,status[item])
213 
214 
215  statusNew = convertStatus(status)
216 
217  print "Relative percentage finished: %.0f%%" % statusNew['Finished']
218  print "Relative percentage failed : %.0f%%" % statusNew['Failed']
219  print "Relative percentage running : %.0f%%" % statusNew['Running']
220 
221  finished = False
222  # Condition for stopping
223  #if fracFailed > 50.0: raise RuntimeError,'Too many jobs have failed (%.0f%%).' % fracFailed
224 
225  # Condition for considering it finished
226  if statusNew['Finished'] >= threshold: finished = True
227 
228  return finished
229 
230 def getOutput(project):
231  options = ['-getoutput']
232  if project:
233  options.append('-c')
234  options.append(project)
235 
236  crabAction(options)
237 
238  return
239 
240 def crabWatch(action,project = None, threshold = 95.0):
241  #for i in range(5):
242  while True:
243  if checkStatus(project,threshold): break
244  time.sleep(180)
245 
246  print "Finished..."
247 
248  action(project)
249 
250  return
251 
253  pythonpathenv = os.environ['PYTHONPATH']
254  pythonpathbegin = pythonpathenv.split(':')[0].rstrip('/')
255  pythonpathend = pythonpathenv.split(':')[-1].rstrip('/')
256 
257  indexBegin = sys.path.index(pythonpathbegin)
258  if 'CRABPSETPYTHON' in os.environ: sys.path.insert( indexBegin, os.environ['CRABPSETPYTHON'] )
259  if 'CRABDLSAPIPYTHON' in os.environ: sys.path.insert( indexBegin, os.environ['CRABDLSAPIPYTHON'] )
260  if 'CRABDBSAPIPYTHON' in os.environ: sys.path.insert( indexBegin, os.environ['CRABDBSAPIPYTHON'] )
261 
262  if os.environ['SCRAM_ARCH'].find('32') != -1 and 'CRABPYSQLITE' in os.environ:
263  sys.path.insert( indexBegin, os.environ['CRABPYSQLITE'] )
264  elif os.environ['SCRAM_ARCH'].find('64') != -1 and 'CRABPYSQLITE64' in os.environ:
265  sys.path.insert( indexBegin, os.environ['CRABPYSQLITE64'] )
266 
267  indexEnd = sys.path.index(pythonpathend) + 1
268  if 'CRABPYTHON' in os.environ:
269  if indexEnd >= len(sys.path): sys.path.append( os.environ['CRABPYTHON'] )
270  else: sys.path.insert( indexEnd, os.environ['CRABPYTHON'] )
271 
272  #print sys.path
273 
274  #os.environ['LD_LIBRARY_PATH'] = os.environ['GLITE_LOCATION'] + '/lib' + ':' + os.environ['LD_LIBRARY_PATH']
275  os.environ['VOMS_PROXY_INFO_DONT_VERIFY_AC'] = '1'
276  #print os.environ['LD_LIBRARY_PATH']
277  #print os.environ['VOMS_PROXY_INFO_DONT_VERIFY_AC']
278 
279  """
280  export LD_LIBRARY_PATH=${GLITE_LOCATION}/lib:${LD_LIBRARY_PATH}
281  export VOMS_PROXY_INFO_DONT_VERIFY_AC=1
282  """
283 
284  ## Get rid of some useless warning
285  try:
286  import warnings
287  warnings.simplefilter("ignore", RuntimeWarning)
288  # import socket
289  # socket.setdefaulttimeout(15) # Default timeout in seconds
290  except ImportError:
291  pass # too bad, you'll get the warning
292 
293  # Remove libraries which over-ride CRAB libs and DBS_CONFIG setting
294  badPaths = []
295  if 'DBSCMD_HOME' in os.environ: # CMSSW's DBS, remove last bit of path
296  badPaths.append('/'.join(os.environ['DBSCMD_HOME'].split('/')[:-1]))
297  if 'DBS_CLIENT_CONFIG' in os.environ:
298  del os.environ['DBS_CLIENT_CONFIG']
299 
300  def pathIsGood(checkPath):
301  """
302  Filter function for badPaths
303  """
304  for badPath in badPaths:
305  if checkPath.find(badPath) != -1:
306  return False
307  return True
308 
309  sys.path = filter(pathIsGood, sys.path)
310 
311 def run(project = None, threshold = 95.0):
312 
313  crabWatch(getOutput,project,threshold)
314 
315  return
316 
317 if __name__ == '__main__':
318  project = None
319  threshold = 95.0
320  for opt in sys.argv:
321  if opt[:8] == 'project=':
322  project = opt[8:]
323  print "Running on CRAB project",project
324  if opt[:10] == 'threshold=':
325  threshold = float(opt[10:])
326  print "Using threshold",threshold
327 
328  run(project,threshold)
computeSummary
Definition: crabWrap.py:68
def crabActionCRAB251
Definition: crabWrap.py:116
def crabAction
Definition: crabWrap.py:95
def summaryServer
Definition: crabWrap.py:78
def initCrabEnvironment
Definition: crabWrap.py:252
void find(edm::Handle< EcalRecHitCollection > &hits, DetId thisDet, std::vector< EcalRecHitCollection::const_iterator > &hit, bool debug=false)
Definition: FindCaloHit.cc:7
def crabCreate
Definition: crabWrap.py:137
def run
Definition: crabWrap.py:311
def computeSummaryCRAB260
Definition: crabWrap.py:5
def summaryStandAlone
Definition: crabWrap.py:70
def convertStatus
Definition: crabWrap.py:174
def crabSubmit
Definition: crabWrap.py:150
static std::string join(char **cmd)
Definition: RemoteFile.cc:18
def crabStatus
Definition: crabWrap.py:157
string action
Definition: mps_fire.py:28
def checkStatus
Definition: crabWrap.py:205
def computeSummaryCRAB251
Definition: crabWrap.py:38
def getOutput
Definition: crabWrap.py:230
def crabWatch
Definition: crabWrap.py:240
double split
Definition: MVATrainer.cc:139