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()

Member Function Documentation

◆ _prepareFoldername()

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

Add crab_ to Foldername if needed.

Parameters
getlog(self,name)

Definition at line 255 of file crabFunctions.py.

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

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

◆ 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 189 of file crabFunctions.py.

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

References crabFunctions.CrabController.crab_q.

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

◆ checkusername()

def crabFunctions.CrabController.checkusername (   self)

Returns the hn name for a user with valid proxy.

@type self: CrabController

Parameters
selfThe object pointer.
Returns
users hypernews name

Definition at line 141 of file crabFunctions.py.

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 

References crabFunctions.CrabController.username.

Referenced by crabFunctions.CrabController.checkwrite().

◆ checkwrite()

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

Check if crab can write to specified site.

@type self: CrabController

Parameters
selfThe object pointer. @type site string
siteThe Site symbol [default:T2_DE_RWTH] @type 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.

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 

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

◆ 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 @type 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 272 of file crabFunctions.py.

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

◆ crabFolders()

def crabFunctions.CrabController.crabFolders (   self)

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

Parameters
selfThe object pointer

Definition at line 247 of file crabFunctions.py.

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

References crabFunctions.CrabController.workingArea.

◆ getlog()

def crabFunctions.CrabController.getlog (   self,
  name 
)

Call crab getlog.

Parameters
selfThe object pointer. @type name string

Definition at line 201 of file crabFunctions.py.

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

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

◆ 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 228 of file crabFunctions.py.

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

◆ 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 215 of file crabFunctions.py.

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

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

◆ resubmit()

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

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

@type self: CrabController

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

Definition at line 122 of file crabFunctions.py.

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

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

◆ status()

def crabFunctions.CrabController.status (   self,
  name 
)

Check crab status.

@type self: CrabController

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

Definition at line 161 of file crabFunctions.py.

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  #print res
172  if 'taskFailureMsg' in res and 'jobs' in res:
173  return res['status'], res['jobs'], res['taskFailureMsg']
174  elif 'jobs' in res and 'taskFailureMsg' not in res:
175  return res['status'], res['jobs'],None
176  elif 'jobs' not in res and 'taskFailureMsg' in res:
177  return res['status'], {},res['taskFailureMsg']
178  else:
179  return res['status'],{},None
180  except Exception as e:
181  print(e)
182  self.logger.error("Can not run crab status request")
183  return "NOSTATE",{},None
184 

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

◆ submit()

def crabFunctions.CrabController.submit (   self,
  name 
)

Check if crab can write to specified site.

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

Definition at line 104 of file crabFunctions.py.

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

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

Member Data Documentation

◆ crab_q

crabFunctions.CrabController.crab_q

Definition at line 71 of file crabFunctions.py.

Referenced by crabFunctions.CrabController.callCrabCommand().

◆ debug

crabFunctions.CrabController.debug

◆ dry_run

crabFunctions.CrabController.dry_run

◆ logger

crabFunctions.CrabController.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
mps_update.status
status
Definition: mps_update.py:69
info
static const TGPicture * info(bool iBackgroundIsBlack)
Definition: FWCollectionSummaryWidget.cc:153
relativeConstraints.error
error
Definition: relativeConstraints.py:53
indexGenCompare.submit
submit
Definition: indexGenCompare.py:117
str
#define str(s)
Definition: TestProcessor.cc:52
print
void print(TMatrixD &m, const char *label=nullptr, bool mathematicaFormat=false)
Definition: Utilities.cc:46
edmIntegrityCheck.report
report
Definition: edmIntegrityCheck.py:349