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

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, debug=0, logger=None, workingArea=None, voGroup=None, username=None)
The constructor.

Member Function Documentation

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.

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

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()
def _prepareFoldername(self, name)
Add crab_ to Foldername if needed.
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.

References crabFunctions.CrabController.crab_q.

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

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 
def callCrabCommand(self, crabArgs)
Call crab command in a new process and return result dict.
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 
def checkusername(self)
Returns the hn name for a user with valid proxy.
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(), 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 
def checkusername(self)
Returns the hn name for a user with valid proxy.
def checkwrite(self, site='T2_DE_RWTH', path='noPath')
Check if crab can write to specified site.
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 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 
def commandlineOptions(self, parser=optparse.OptionParser( 'usage:%prog'))
Populates an existing optparse parser or returns a new one with options for crab functions.
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.

References crabFunctions.CrabController.workingArea.

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 
def crabFolders(self)
Return list of all crab folders in workin area (default cwd)
def crabFunctions.CrabController.getlog (   self,
  name 
)

Call crab getlog.

Parameters
selfThe object pointer. name string

Definition at line 201 of file crabFunctions.py.

References crabFunctions.CrabController._prepareFoldername(), and crabFunctions.CrabController.callCrabCommand().

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 
def _prepareFoldername(self, name)
Add crab_ to Foldername if needed.
def getlog(self, name)
Call crab getlog.
def callCrabCommand(self, crabArgs)
Call crab command in a new process and return result dict.
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 
def readCrabConfig(self, name)
Read a crab config and return python object.
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.

References crabFunctions.CrabController._prepareFoldername(), and crabFunctions.CrabController.callCrabCommand().

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 
def _prepareFoldername(self, name)
Add crab_ to Foldername if needed.
def callCrabCommand(self, crabArgs)
Call crab command in a new process and return result dict.
def report(self, name)
Call crab report command and return path to lumiSummary.
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, 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
def _prepareFoldername(self, name)
Add crab_ to Foldername if needed.
def resubmit(self, name, joblist=None)
Resubmit all failed tasks in job or specified list of jobs in task.
def callCrabCommand(self, crabArgs)
Call crab command in a new process and return result dict.
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, and edm.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  #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 
def status(self, name)
Check crab status.
S & print(S &os, JobReport::InputFile const &f)
Definition: JobReport.cc:65
def callCrabCommand(self, crabArgs)
Call crab command in a new process and return result dict.
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, DTTPDeadWriter.debug, DTTTrigWriter.debug, DTT0CalibrationRMS.debug, DTT0Calibration.debug, DTNoiseComputation.debug, DTTTrigCalibration.debug, DTTMax.debug, DTVDriftCalibration.debug, crabFunctions.CrabController.dry_run, 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
def submit(self, name)
Check if crab can write to specified site.
def callCrabCommand(self, crabArgs)
Call crab command in a new process and return result dict.
#define str(s)

Member Data Documentation

crabFunctions.CrabController.crab_q

Definition at line 71 of file crabFunctions.py.

Referenced by crabFunctions.CrabController.callCrabCommand().

crabFunctions.CrabController.debug
crabFunctions.CrabController.dry_run
crabFunctions.CrabController.logger

Definition at line 55 of file crabFunctions.py.

Referenced by o2olib.O2OMgr.logger().

crabFunctions.CrabController.username
crabFunctions.CrabController.voGroup

Definition at line 46 of file crabFunctions.py.

Referenced by crabFunctions.CrabController.checkwrite().

crabFunctions.CrabController.workingArea