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 30 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 35 of file crabFunctions.py.

35  def __init__(self, debug=0, logger = None , workingArea = None, voGroup = None, username = None):
36 
37  setConsoleLogLevel(LOGLEVEL_MUTE)
38  self.debug = debug
39  if workingArea is not None:
40  self.workingArea = workingArea
41  else:
42  self.workingArea = os.getcwd()
43  self.dry_run = False
44  if voGroup is not None:
45  self.voGroup = voGroup
46  else:
47  self.voGroup = "dcms"
48  if username is not None:
49  self.username = username
50  else:
51  self.username = None
52 
53  if logger is not None:
54  self.logger = logger.getChild("CrabController")
55  else:
56  # add instance logger as logger to root
57  self.logger = logging.getLogger("CrabController")
58  # check if handlers are present for root logger
59  # we assume that the default logging is not configured
60  # if handler is present
61  if len(logging.getLogger().handlers) < 1 :
62  ch = logging.FileHandler('crabController.log', mode='a', encoding=None, delay=False)
63  ch.setLevel(logging.DEBUG)
64  # create formatter
65  formatter = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s' )
66  # add formatter to ch
67  ch.setFormatter(formatter)
68  self.logger.addHandler(ch)
69 
70  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 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()
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 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 
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 140 of file crabFunctions.py.

References crabFunctions.CrabController.username.

Referenced by crabFunctions.CrabController.checkwrite().

140  def checkusername(self):
141  #depreceated string: cmd = 'crab checkHNname --voGroup=dcms'
142  #~ cmd = 'crab checkusername --voGroup=dcms'
143  try:
144  username = os.environ["CERNUSERNAME"]
145  return username
146  except:pass
147  res = crabCommand('checkusername')
148  try:
149  self.username = res['username']
150  return res['username']
151  except:
152  return "noHNname"
153 
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 80 of file crabFunctions.py.

References crabFunctions.CrabController.checkusername(), crabFunctions.CrabController.username, and crabFunctions.CrabController.voGroup.

80  def checkwrite(self,site='T2_DE_RWTH',path='noPath'):
81  if self.username is None: self.checkusername()
82  try:
83  self.logger.info( "Checking if user can write to /store/user/%s on site %s with voGroup %s"%(self.username,site , self.voGroup) )
84  if not 'noPath' in path:
85  res = crabCommand('checkwrite','--site',site,'--voGroup',self.voGroup,'--lfn', path)
86  else:
87  res = crabCommand('checkwrite','--site',site,'--voGroup',self.voGroup)
88  if res['status'] == 'SUCCESS':
89  self.logger.info("Checkwrite was sucessfully called.")
90  return True
91  else:
92  self.logger.error( "The crab checkwrite command failed for site: %s"%site )
93  return False
94  except:
95  self.logger.error( 'Unable to perform crab checkwrite')
96  return False
97 
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 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 
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 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 
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 200 of file crabFunctions.py.

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

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 
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 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:
234  cfo = imp.load_source("pycfg", pset, cfgfile )
235  config = cfo.config
236  del cfo
237  return config
238  except:
239  return False
240 
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 214 of file crabFunctions.py.

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

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

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

121  def resubmit(self,name,joblist = None):
122  if self.dry_run:
123  self.logger.info('Dry-run: Created config file. ')
124  return {}
125  #~ if joblist is not None:
126  #~ jobstring ="%s"%','.join(joblist)
127  #~ cmd = ('resubmit','--wait', '--jobids=',jobstring, os.path.join(self.workingArea,self._prepareFoldername(name)) )
128  if False:
129  pass
130  else:
131  cmd = ('resubmit','--wait', os.path.join(self.workingArea,self._prepareFoldername(name)) )
132  res = self.callCrabCommand( cmd )
133  self.logger.info("crab resumbit called for task %s"%name)
134  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 160 of file crabFunctions.py.

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

160  def status(self,name):
161  if self.dry_run:
162  self.logger.info('Dry-run: Created config file. crab command would have been: %s'%cmd)
163  else:
164  try:
165  if not "crab_" in name:
166  callname = "crab_" + name
167  else:
168  callname = name
169  res = self.callCrabCommand( ('status', '--long', callname) )
170  #print res
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 
def status(self, name)
Check crab status.
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 103 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 harvestTrackValidationPlots.str.

103  def submit(self,name):
104  if self.dry_run:
105  res = self.callCrabCommand(('submit', '--dryrun', name))
106  self.logger.info('Dry-run: You may check the created config and sandbox')
107  else:
108  res = self.callCrabCommand(('submit','--wait' , name))
109  self.logger.info("crab sumbit called for task %s"%name)
110  if self.debug > 1:
111  self.logger.info(str(res))
112  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.

Member Data Documentation

crabFunctions.CrabController.crab_q

Definition at line 70 of file crabFunctions.py.

Referenced by crabFunctions.CrabController.callCrabCommand().

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

Definition at line 54 of file crabFunctions.py.

Referenced by o2olib.O2OMgr.logger().

crabFunctions.CrabController.username
crabFunctions.CrabController.voGroup

Definition at line 45 of file crabFunctions.py.

Referenced by crabFunctions.CrabController.checkwrite().

crabFunctions.CrabController.workingArea