CMS 3D CMS Logo

CrabHelper.py
Go to the documentation of this file.
1 from __future__ import print_function
2 import logging
3 import sys
4 import os
5 from importlib import import_module
6 import subprocess
7 import time
8 import tools
9 
10 log = logging.getLogger(__name__)
12 
13  def __init__(self):
14  # perform imports only when creating instance. This allows to use the classmethods e.g.for
15  # CLI construction before crab is sourced.
16  self.crabFunctions = import_module('CalibMuon.DTCalibration.Workflow.Crabtools.crabFunctions')
17  # cached member variables
18  self._crab = None
19  self._cert_info = None
20 
21  def submit_crab_task(self):
22  # create a crab config
23  log.info("Creating crab config")
24  self.create_crab_config()
25  #write crab config
26  full_crab_config_filename = self.write_crabConfig()
27  if self.options.no_exec:
28  log.info("Runing with option no-exec exiting")
29  return True
30  #submit crab job
31  log.info("Submitting crab job")
32  self.crab.submit(full_crab_config_filename)
33  log.info("crab job submitted. Waiting 30 seconds before first status call")
34  time.sleep( 30 )
35  task = self.crabFunctions.CrabTask(crab_config = full_crab_config_filename)
36  task.update()
37  success_states = ( 'QUEUED', 'SUBMITTED', "COMPLETED", "FINISHED")
38  if task.state in success_states:
39  log.info("Job in state %s" % task.state )
40  return True
41  else:
42  log.error("Job submission not successful, crab state:%s" % task.state)
43  raise RuntimeError("Job submission not successful, crab state:%s" % task.state)
44 
45  def check_crabtask(self):
47  task = self.crabFunctions.CrabTask(crab_config = self.crab_config_filepath,
48  initUpdate = False)
49  if self.options.no_exec:
50  log.info("Nothing to check in no-exec mode")
51  return True
52  for n_check in range(self.options.max_checks):
53  task.update()
54  if task.state in ( "COMPLETED"):
55  print("Crab task complete. Getting output locally")
56  output_path = os.path.join( self.local_path, "unmerged_results" )
57  self.get_output_files(task, output_path)
58  return True
59  if task.state in ("SUBMITFAILED", "FAILED"):
60  print("Crab task failed")
61  return False
62  possible_job_states = ["nUnsubmitted",
63  "nIdle",
64  "nRunning",
65  "nTransferring",
66  "nCooloff",
67  "nFailed",
68  "nFinished",
69  "nComplete" ]
70 
71  jobinfos = ""
72  for jobstate in possible_job_states:
73  njobs_in_state = getattr(task, jobstate)
74  if njobs_in_state > 0:
75  jobinfos+="%s: %d " % (jobstate[1:], njobs_in_state)
76 
77  #clear line for reuse
78  sys.stdout.write("\r")
79  sys.stdout.write("".join([" " for i in range(tools.getTerminalSize()[0])]))
80  sys.stdout.write("\r")
81  prompt_text = "Check (%d/%d). Task state: %s (%s). Press q and enter to stop checks: " % (n_check,
82  self.options.max_checks, task.state, jobinfos)
83  user_input = tools.stdinWait(prompt_text, "", self.options.check_interval)
84  if user_input in ("q","Q"):
85  return False
86  print("Task not completed after %d checks (%d minutes)" % ( self.options.max_checks,
87  int( self.options.check_interval / 60. )))
88  return False
89 
91  process = subprocess.Popen(['voms-proxy-info', '-timeleft'],
92  stdout=subprocess.PIPE,
93  stderr=subprocess.STDOUT)
94  stdout = process.communicate()[0]
95  if process.returncode != 0:
96  return 0
97  else:
98  return int(stdout)
99 
100  def voms_proxy_create(self, passphrase = None):
101  voms = 'cms'
102  if passphrase:
103  p = subprocess.Popen(['voms-proxy-init', '--voms', voms, '--valid', '192:00'],
104  stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.STDOUT)
105  stdout = p.communicate(input=passphrase+'\n')[0]
106  retcode = p.returncode
107  if not retcode == 0:
108  raise ProxyError('Proxy initialization command failed: %s'%stdout)
109  else:
110  retcode = subprocess.call(['voms-proxy-init', '--voms', voms, '--valid', '192:00'])
111  if not retcode == 0:
112  raise ProxyError('Proxy initialization command failed.')
113 
114 
116  """ Create a crab config object dependent on the chosen command option"""
117  from CalibMuon.DTCalibration.Workflow.Crabtools.crabConfigParser import CrabConfigParser
119  """ Fill common options in crab config """
120  ### General section
121  self.crab_config.add_section('General')
122  if "/" in self.crab_taskname:
123  raise ValueError( 'Sample contains "/" which is not allowed' )
124  self.crab_config.set( 'General', 'requestName', self.crab_taskname )
125  self.crab_config.set( 'General', 'workArea', self.local_path)
126  if self.options.no_log:
127  self.crab_config.set( 'General', 'transferLogs', 'False' )
128  else:
129  self.crab_config.set( 'General', 'transferLogs', 'True' )
130  ### JobType section
131  self.crab_config.add_section('JobType')
132  self.crab_config.set( 'JobType', 'pluginName', 'Analysis' )
133  self.crab_config.set( 'JobType', 'psetName', self.pset_path )
134  self.crab_config.set( 'JobType', 'outputFiles', self.output_files)
135  if self.input_files:
136  self.crab_config.set( 'JobType', 'inputFiles', self.input_files)
137  ### Data section
138  self.crab_config.add_section('Data')
139  self.crab_config.set('Data', 'inputDataset', self.options.datasetpath)
140  # set job splitting options
141  if self.options.datasettype =="MC":
142  self.crab_config.set('Data', 'splitting', 'FileBased')
143  self.crab_config.set('Data', 'unitsPerJob', str(self.options.filesPerJob) )
144  else:
145  self.crab_config.set('Data', 'splitting', 'LumiBased')
146  self.crab_config.set('Data', 'unitsPerJob', str(self.options.lumisPerJob) )
147  if self.options.runselection:
148  self.crab_config.set( "Data",
149  "runRange",
150  ",".join( self.options.runselection )
151  )
152  # set output path in compliance with crab3 structure
153  self.crab_config.set('Data', 'publication', False)
154  self.crab_config.set('Data', 'outputDatasetTag', self.remote_out_path["outputDatasetTag"])
155  self.crab_config.set('Data', 'outLFNDirBase', self.remote_out_path["outLFNDirBase"] )
156 
157  # set site section options
158  self.crab_config.add_section('Site')
159  self.crab_config.set('Site', 'storageSite', self.options.output_site)
160  self.crab_config.set('Site', 'whitelist', self.options.ce_white_list)
161  self.crab_config.set('Site', 'blacklist', self.options.ce_black_list)
162 
163  #set user section options if necessary
164 # if self.cert_info.voGroup or self.cert_info.voRole:
165 # self.crab_config.add_section('User')
166 # if self.cert_info.voGroup:
167 # self.crab_config.set('User', "voGroup", self.cert_info.voGroup)
168 # if self.cert_info.voRole:
169 # self.crab_config.set('User', "voRole", self.cert_info.voRole)
170  log.debug("Created crab config: %s " % self.crab_config_filename)
171 
172  def write_crabConfig(self):
173  """ Write crab config file in working dir with label option as name """
174  base_path = os.path.join( self.options.working_dir,self.local_path)
175  filename = os.path.join( base_path, self.crab_config_filename)
176  if not os.path.exists(base_path):
177  os.makedirs(base_path)
178  if os.path.exists(filename):
179  raise IOError("file %s alrady exits"%(filename))
180  self.crab_config.writeCrabConfig(filename)
181  log.info( 'created crab config file %s'%filename )
182  return filename
183 
185  crabtask = CrabTask( crab_config = self.crab_config_filename )
186  splitinfo = crabtask.crabConfig.Data.outputDatasetTag.split("_")
187  run, trial = splitinfo[0].split("Run")[-1], splitinfo[1].split("v")[-1]
188  if not self.options.run:
189  self.options.run = int(run)
190  self.options.trail = int(trial)
191  if not hasattr(self.options, "datasetpath"):
192  self.options.datasetpath = crabtask.crabConfig.Data.inputDataset
193  if not hasattr(self.options, "label"):
194  self.options.label = crabtask.crabConfig.General.requestName.split("_")[0]
195 
196  @property
197  def crab(self):
198  """ Retuns a CrabController instance from cache or creates new
199  on on first call """
200  if self._crab is None:
201  if self.cert_info.voGroup:
202  self._crab = self.crabFunctions.CrabController(voGroup = self.cert_info.voGroup)
203  else:
204  self._crab = self.crabFunctions.CrabController()
205  return self._crab
206 
207  @property
208  def cert_info(self):
209  if not self._cert_info:
210  if not self.voms_proxy_time_left() > 0:
211  warn_msg = "No valid proxy, a default proxy without a specific"
212  warn_msg = "VOGroup will be used"
213  self.voms_proxy_create()
214  log.warning(warn_msg)
215  self._cert_info = self.crabFunctions.CertInfo()
216  return self._cert_info
217 
218  @property
220  if hasattr(self.options, "crab_config_path"):
221  return self.options.crab_config_path
222  return 'crab_%s_cfg.py' % self.crab_taskname
223 
224  @property
226  base_path = os.path.join( self.options.working_dir,self.local_path)
227  return os.path.join( base_path, self.crab_config_filename)
228 
229  @property
230  def crab_taskname(self):
231  taskname = self.options.label + "_" + self.options.workflow + "_"
232  if hasattr( self.options, "workflow_mode"):
233  taskname+= self.options.workflow_mode + "_"
234  taskname += "run_" + str(self.options.run) + "_v" + str(self.options.trial)
235  return taskname
S & print(S &os, JobReport::InputFile const &f)
Definition: JobReport.cc:66
def fill_options_from_crab_config(self)
Definition: CrabHelper.py:184
def create_crab_config(self)
Definition: CrabHelper.py:115
This module extends the python configparser to create crab3 config files.
def crab_config_filepath(self)
Definition: CrabHelper.py:225
def voms_proxy_create(self, passphrase=None)
Definition: CrabHelper.py:100
def getTerminalSize()
Definition: tools.py:96
def submit_crab_task(self)
Definition: CrabHelper.py:21
static std::string join(char **cmd)
Definition: RemoteFile.cc:18
def voms_proxy_time_left(self)
Definition: CrabHelper.py:90
def write_crabConfig(self)
Definition: CrabHelper.py:172
def stdinWait(text, default, time, timeoutDisplay=None, kwargs)
Definition: tools.py:70
def crab_taskname(self)
Definition: CrabHelper.py:230
def check_crabtask(self)
Definition: CrabHelper.py:45
#define str(s)
double split
Definition: MVATrainer.cc:139
def crab_config_filename(self)
Definition: CrabHelper.py:219