CMS 3D CMS Logo

List of all members | Public Member Functions | Public Attributes | Private Member Functions
crabFunctions.CrabController Class Reference

The CrabController class. More...

Public Member Functions

def __init__ (self, debug=0, logger=None, workingArea=None, voGroup=None, username=None)
 The constructor. More...
 
def callCrabCommand (self, crabArgs)
 Call crab command in a new process and return result dict. More...
 
def checkusername (self)
 Returns the hn name for a user with valid proxy. More...
 
def checkwrite (self, site='T2_DE_RWTH', path='noPath')
 Check if crab can write to specified site. More...
 
def commandlineOptions (self, parser=optparse.OptionParser( 'usage:%prog'))
 Populates an existing optparse parser or returns a new one with options for crab functions. More...
 
def crabFolders (self)
 Return list of all crab folders in workin area (default cwd) More...
 
def getlog (self, name)
 Call crab getlog. More...
 
def readCrabConfig (self, name)
 Read a crab config and return python object. More...
 
def report (self, name)
 Call crab report command and return path to lumiSummary. More...
 
def resubmit (self, name, joblist=None)
 Resubmit all failed tasks in job or specified list of jobs in task. More...
 
def status (self, name)
 Check crab status. More...
 
def submit (self, name)
 Check if crab can write to specified site. More...
 

Public Attributes

 crab_q
 
 debug
 
 dry_run
 
 logger
 
 username
 
 voGroup
 
 workingArea
 

Private Member Functions

def _prepareFoldername (self, name)
 Add crab_ to Foldername if needed. More...
 

Detailed Description

The CrabController class.

This class can be used to manage Analyses using crab3

Definition at line 31 of file crabFunctions.py.

Constructor & Destructor Documentation

◆ __init__()

def crabFunctions.CrabController.__init__ (   self,
  debug = 0,
  logger = None,
  workingArea = None,
  voGroup = None,
  username = None 
)

The constructor.

Parameters
selfThe object pointer.
selfA previously defined logger. Crab log messages will use this logger as their parent logger.

Definition at line 36 of file crabFunctions.py.

36  def __init__(self, debug=0, logger = None , workingArea = None, voGroup = None, username = None):
37 
38  setConsoleLogLevel(LOGLEVEL_MUTE)
39  self.debug = debug
40  if workingArea is not None:
41  self.workingArea = workingArea
42  else:
43  self.workingArea = os.getcwd()
44  self.dry_run = False
45  if voGroup is not None:
46  self.voGroup = voGroup
47  else:
48  self.voGroup = "dcms"
49  if username is not None:
50  self.username = username
51  else:
52  self.username = None
53 
54  if logger is not None:
55  self.logger = logger.getChild("CrabController")
56  else:
57  # add instance logger as logger to root
58  self.logger = logging.getLogger("CrabController")
59  # check if handlers are present for root logger
60  # we assume that the default logging is not configured
61  # if handler is present
62  if len(logging.getLogger().handlers) < 1 :
63  ch = logging.FileHandler('crabController.log', mode='a', encoding=None, delay=False)
64  ch.setLevel(logging.DEBUG)
65  # create formatter
66  formatter = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s' )
67  # add formatter to ch
68  ch.setFormatter(formatter)
69  self.logger.addHandler(ch)
70 
71  self.crab_q = Queue()
def __init__(self, dataset, job_number, job_id, job_name, isDA, isMC, applyBOWS, applyEXTRACOND, extraconditions, runboundary, lumilist, intlumi, maxevents, gt, allFromGT, alignmentDB, alignmentTAG, apeDB, apeTAG, bowDB, bowTAG, vertextype, tracktype, refittertype, ttrhtype, applyruncontrol, ptcut, CMSSW_dir, the_dir)

Member Function Documentation

◆ _prepareFoldername()

def crabFunctions.CrabController._prepareFoldername (   self,
  name 
)
private

Add crab_ to Foldername if needed.

Parameters
getlog(self,name)

Definition at line 254 of file crabFunctions.py.

Referenced by crabFunctions.CrabController.getlog(), crabFunctions.CrabController.report(), and crabFunctions.CrabController.resubmit().

254  def _prepareFoldername(self, name):
255  if name.startswith("crab_"):
256  crabfolder = '%s'%name
257  else:
258  crabfolder = "crab_%s "%name
259  return crabfolder.strip()

◆ callCrabCommand()

def crabFunctions.CrabController.callCrabCommand (   self,
  crabArgs 
)

Call crab command in a new process and return result dict.

Parameters
selfThe object pointer
crabArgsA list of arguments for crab beginning with the command

Definition at line 188 of file crabFunctions.py.

References crabFunctions.CrabController.crab_q.

Referenced by crabFunctions.CrabController.getlog(), crabFunctions.CrabController.report(), crabFunctions.CrabController.resubmit(), crabFunctions.CrabController.status(), and crabFunctions.CrabController.submit().

188  def callCrabCommand( self, crabArgs ):
189  crabCommandProcessArgs = (self.crab_q, crabArgs)
190  p = Process(target=crabCommandProcess, args=(crabCommandProcessArgs))
191  p.start()
192  res = self.crab_q.get()
193  p.join()
194  return res
195 

◆ checkusername()

def crabFunctions.CrabController.checkusername (   self)

Returns the hn name for a user with valid proxy.

self: CrabController

Parameters
selfThe object pointer.
Returns
users hypernews name

Definition at line 141 of file crabFunctions.py.

References crabFunctions.CrabController.username.

Referenced by crabFunctions.CrabController.checkwrite().

141  def checkusername(self):
142  #depreceated string: cmd = 'crab checkHNname --voGroup=dcms'
143  #~ cmd = 'crab checkusername --voGroup=dcms'
144  try:
145  username = os.environ["CERNUSERNAME"]
146  return username
147  except:pass
148  res = crabCommand('checkusername')
149  try:
150  self.username = res['username']
151  return res['username']
152  except:
153  return "noHNname"
154 

◆ checkwrite()

def crabFunctions.CrabController.checkwrite (   self,
  site = 'T2_DE_RWTH',
  path = 'noPath' 
)

Check if crab can write to specified site.

self: CrabController

Parameters
selfThe object pointer. site string
siteThe Site symbol [default:T2_DE_RWTH] path string
pathlfn path to check write permission in. see twiki WorkBookCRAB3Tutorial
Returns
boolean which is True if user can write to site and False otherwise

Definition at line 81 of file crabFunctions.py.

References crabFunctions.CrabController.checkusername(), relativeConstraints.error, info(), crabFunctions.CrabController.logger, crabFunctions.CrabController.username, and crabFunctions.CrabController.voGroup.

81  def checkwrite(self,site='T2_DE_RWTH',path='noPath'):
82  if self.username is None: self.checkusername()
83  try:
84  self.logger.info( "Checking if user can write to /store/user/%s on site %s with voGroup %s"%(self.username,site , self.voGroup) )
85  if not 'noPath' in path:
86  res = crabCommand('checkwrite','--site',site,'--voGroup',self.voGroup,'--lfn', path)
87  else:
88  res = crabCommand('checkwrite','--site',site,'--voGroup',self.voGroup)
89  if res['status'] == 'SUCCESS':
90  self.logger.info("Checkwrite was sucessfully called.")
91  return True
92  else:
93  self.logger.error( "The crab checkwrite command failed for site: %s"%site )
94  return False
95  except:
96  self.logger.error( 'Unable to perform crab checkwrite')
97  return False
98 
static const TGPicture * info(bool iBackgroundIsBlack)

◆ commandlineOptions()

def crabFunctions.CrabController.commandlineOptions (   self,
  parser = optparse.OptionParser( 'usage: %prog' ) 
)

Populates an existing optparse parser or returns a new one with options for crab functions.

This functions populates a previously created (or new) instance of a optparse parser object with options needed by crab functions. It is possible to add three kinds of options:

  • options where a error should be raised if the option was previously defined
  • options where previous definitions should be kept
  • options where previous definitions should be overriden Optparse parser instance
    Parameters
    parserA previously created parser oject which should be extenden [default: new instance]
    Returns
    A new or extenden optparse parser instance

Definition at line 271 of file crabFunctions.py.

271  def commandlineOptions(self,parser = optparse.OptionParser( 'usage: %prog' )):
272  # we first need to call parse_args with a dummy string at the beginning to
273  # check for existing options later
274  (currentoptions, args ) = parser.parse_args([" "])
275 
276  # The following block shows how variables should be added, where
277  # conflicts are possible if the option is overridden by this function
278  # they raise a value error
279  #try:
280  # parser.add_option( '--someOption',metavar='DIR',default=None,
281  # help='Dummy option for future integration')
282  #except OptionConflictError as e:
283  # conditionalLog(crablog,"There are conflicts extending the optparse options object",'error')
284  # conditionalLog(crablog,e.strerror,'error')
285 
286  # options where it is checked if they exists and new options are added
287  # otherwise
288  if not hasattr(currentoptions, 'dry_run'):
289  parser.add_option( '--dry-run', action='store_true', default=False,
290  help='Do everything except calling CRAB or registering samples to the database.' )
291  if not hasattr(currentoptions, 'workingArea'):
292  parser.add_option( '--workingArea',metavar='DIR',default=os.getcwd(),help='The area (full or relative path) where to create the CRAB project directory. '
293  'If the area doesn\'t exist, CRAB will try to create it using the mkdir command' \
294  ' (without -p option). Defaults to the current working directory.' )
295 
296 
297  # Some options can be added without expected trouble with other parser
298  # parts, simply because it is quite fixed what they represent.
299  # those variables should be added here and will throw no exception if
300  # they already exist in the parser
301  #parser.set_conflict_handler('resolve')
302  #parser.add_option( '--someOption',metavar='DIR',default=None,
303  # help='Dummy option for future integration')
304 
305  return parser
306 
307 
308 

◆ crabFolders()

def crabFunctions.CrabController.crabFolders (   self)

Return list of all crab folders in workin area (default cwd)

Parameters
selfThe object pointer

Definition at line 246 of file crabFunctions.py.

References crabFunctions.CrabController.workingArea.

246  def crabFolders(self):
247  results = []
248  dirlist = [ x for x in os.listdir( self.workingArea ) if (x.startswith('crab_') and os.path.isdir( os.path.join(self.workingArea,x) ) )]
249  return dirlist
250 

◆ getlog()

def crabFunctions.CrabController.getlog (   self,
  name 
)

Call crab getlog.

Parameters
selfThe object pointer. name string

Definition at line 200 of file crabFunctions.py.

References crabFunctions.CrabController._prepareFoldername(), crabFunctions.CrabController.callCrabCommand(), relativeConstraints.error, and crabFunctions.CrabController.logger.

200  def getlog(self, name):
201  foldername = self._prepareFoldername( name)
202  try:
203  #res = crabCommand('--quiet','status', dir = 'crab_%s' % name)
204  res = self.callCrabCommand( ('getlog', '%s' % foldername) )
205  return res['success'], res['failed']
206  except:
207  self.logger.error("Error calling crab getlog for %s" %foldername)
208  return {}, {}
209 

◆ readCrabConfig()

def crabFunctions.CrabController.readCrabConfig (   self,
  name 
)

Read a crab config and return python object.

Parameters
selfThe object pointer.
nameThe sample name (crab request name)

Definition at line 227 of file crabFunctions.py.

227  def readCrabConfig( self, name ):
228  try:
229  if os.path.exists(name):
230  pset = name
231  else:
232  pset = 'crab_%s_cfg.py' % name
233  with open( pset, 'r') as cfgfile: cfo = imp.load_source("pycfg", pset, cfgfile )
234  config = cfo.config
235  del cfo
236  return config
237  except:
238  return False
239 
240 

◆ report()

def crabFunctions.CrabController.report (   self,
  name 
)

Call crab report command and return path to lumiSummary.

Parameters
selfThe object pointer
nameThe crab3 request name, a.k.a the sample name

Definition at line 214 of file crabFunctions.py.

References crabFunctions.CrabController._prepareFoldername(), crabFunctions.CrabController.callCrabCommand(), relativeConstraints.error, and crabFunctions.CrabController.logger.

214  def report(self, name):
215  foldername = self._prepareFoldername( name)
216  try:
217  res = self.callCrabCommand( ('report', '%s' % foldername) )
218  return res['analyzedLumis']
219  except:
220  self.logger.error("Error calling crab report for %s" %foldername)
221 
222 

◆ resubmit()

def crabFunctions.CrabController.resubmit (   self,
  name,
  joblist = None 
)

Resubmit all failed tasks in job or specified list of jobs in task.

self: CrabController

Parameters
selfThe object pointer. name string
nameThe crab3 request name, a.k.a the sample name joblist list of strings
joblistThe crab3 request name, a.k.a the sample name

Definition at line 122 of file crabFunctions.py.

References crabFunctions.CrabController._prepareFoldername(), crabFunctions.CrabController.callCrabCommand(), crabFunctions.CrabController.dry_run, info(), crabFunctions.CrabController.logger, and crabFunctions.CrabController.workingArea.

122  def resubmit(self,name,joblist = None):
123  if self.dry_run:
124  self.logger.info('Dry-run: Created config file. ')
125  return {}
126  #~ if joblist is not None:
127  #~ jobstring ="%s"%','.join(joblist)
128  #~ cmd = ('resubmit','--wait', '--jobids=',jobstring, os.path.join(self.workingArea,self._prepareFoldername(name)) )
129  if False:
130  pass
131  else:
132  cmd = ('resubmit','--wait', os.path.join(self.workingArea,self._prepareFoldername(name)) )
133  res = self.callCrabCommand( cmd )
134  self.logger.info("crab resumbit called for task %s"%name)
135  return res
static const TGPicture * info(bool iBackgroundIsBlack)

◆ status()

def crabFunctions.CrabController.status (   self,
  name 
)

Check crab status.

self: CrabController

Parameters
selfThe object pointer. name string
nameThe crab3 request name, a.k.a the sample name

Definition at line 161 of file crabFunctions.py.

References crabFunctions.CrabController.callCrabCommand(), crabFunctions.CrabController.dry_run, relativeConstraints.error, info(), crabFunctions.CrabController.logger, and print().

161  def status(self,name):
162  if self.dry_run:
163  self.logger.info('Dry-run: Created config file. crab command would have been: %s'%cmd)
164  else:
165  try:
166  if not "crab_" in name:
167  callname = "crab_" + name
168  else:
169  callname = name
170  res = self.callCrabCommand( ('status', '--long', callname) )
171  if 'taskFailureMsg' in res and 'jobs' in res:
172  return res['status'], res['jobs'], res['taskFailureMsg']
173  elif 'jobs' in res and 'taskFailureMsg' not in res:
174  return res['status'], res['jobs'],None
175  elif 'jobs' not in res and 'taskFailureMsg' in res:
176  return res['status'], {},res['taskFailureMsg']
177  else:
178  return res['status'],{},None
179  except Exception as e:
180  print(e)
181  self.logger.error("Can not run crab status request")
182  return "NOSTATE",{},None
183 
static const TGPicture * info(bool iBackgroundIsBlack)
void print(TMatrixD &m, const char *label=nullptr, bool mathematicaFormat=false)
Definition: Utilities.cc:47

◆ submit()

def crabFunctions.CrabController.submit (   self,
  name 
)

Check if crab can write to specified site.

Parameters
selfThe object pointer. name string
nameThe crab3 config file name

Definition at line 104 of file crabFunctions.py.

References crabFunctions.CrabController.callCrabCommand(), ALIUtils.debug, crabFunctions.CrabController.debug, DTTTrigCorrectionFirst.debug, DTT0CalibrationRMS.debug, DTTTrigWriter.debug, DTTPDeadWriter.debug, DTNoiseComputation.debug, DTT0Calibration.debug, DTTTrigCalibration.debug, DTTMax.debug, DTVDriftCalibration.debug, crabFunctions.CrabController.dry_run, info(), crabFunctions.CrabController.logger, and str.

104  def submit(self,name):
105  if self.dry_run:
106  res = self.callCrabCommand(('submit', '--dryrun', name))
107  self.logger.info('Dry-run: You may check the created config and sandbox')
108  else:
109  res = self.callCrabCommand(('submit','--wait' , name))
110  self.logger.info("crab sumbit called for task %s"%name)
111  if self.debug > 1:
112  self.logger.info(str(res))
113  return res
static const TGPicture * info(bool iBackgroundIsBlack)
#define str(s)

Member Data Documentation

◆ crab_q

crabFunctions.CrabController.crab_q

Definition at line 71 of file crabFunctions.py.

Referenced by crabFunctions.CrabController.callCrabCommand().

◆ debug

◆ dry_run

crabFunctions.CrabController.dry_run

◆ logger

◆ username

crabFunctions.CrabController.username

◆ voGroup

crabFunctions.CrabController.voGroup

Definition at line 46 of file crabFunctions.py.

Referenced by crabFunctions.CrabController.checkwrite().

◆ workingArea

crabFunctions.CrabController.workingArea