rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
break
if job.inputdata._name != 'EventPicking': break
def split(self,job):
allcontentsSize.append(guid, lfn, contents_size[guid])
allcontentsSize.append((guid, lfn, contents_size[guid]))
def get_contents(self,backnav=False, overlap=True, filesize=False, size=False): '''Helper function to access dataset content'''
contentsSize.append(guid, lfn, contents_size[guid])
contentsSize.append((guid, lfn, contents_size[guid]))
def get_contents(self,backnav=False, overlap=True, filesize=False, size=False): '''Helper function to access dataset content'''
return self.merge(jobs.subjobs,outputdir = jobs.outputdir, ignorefailed = ignorefailed, overwrite = overwrite)
if outputdir is None: outputdir = jobs.outputdir return self.merge(jobs.subjobs,outputdir = outputdir, ignorefailed = ignorefailed, overwrite = overwrite)
def merge(self, jobs, outputdir = None, ignorefailed = None, overwrite = None): """ Method to merge the output of jobs. jobs may be a single job instance or a sequence of Jobs outputdir is the name of the directry to put the merge results in. It will be created if needed. ignorefailed and overwrite have the same meani...
return self.merge(jobs.subjobs,outputdir = jobs.outputdir, ignorefailed = ignorefailed, overwrite = overwrite)
if outputdir is None: outputdir = jobs.outputdir return self.merge(jobs.subjobs,outputdir = outputdir, ignorefailed = ignorefailed, overwrite = overwrite)
def merge(self, jobs, outputdir = None, ignorefailed = None, overwrite = None):
obj._data[attr] = obj._schema.getDefaultValue(attr)
if item._meta["sequence"] == 1: obj._data[attr] = makeGangaListByRef(obj._schema.getDefaultValue(attr)) else: obj._data[attr] = obj._schema.getDefaultValue(attr)
def end_element(name): ###logger.debug('End element: name=%s', name)
raise ApplicationConfigurationError("Invalid Task name!")
raise ApplicationConfigurationError(None, "Invalid Task name!")
def check(self): self.initAliases() if not all(ss.isalnum() for ss in self.name.split(".")): logger.error("Invalid character in task name! Task names are now used for DQ2 datasets; so no spaces, slashes or other special characters are allowed.") raise ApplicationConfigurationError("Invalid Task name!") super(AnaTask,se...
raise TreeError(4, "Not a job object")
raise TreeError(4, "Not a job/slice/list object")
def add(self, job, path = None): """Adds job to the job tree into the current folder. If path to a folder is provided as a parameter than adds job to that folder. """ if isinstance(job, GPIProxyObject): job = job._impl if isinstance(job, Job): self.__select_dir(path)[job.getFQID('.')] = job.getFQID('.') #job.id self._s...
cmd += " -dst " + os.path.basename(f) + ".ref RootCollection" tag_ref_files.append(os.path.basename(f)+".ref.root")
cmd += " -dst " + os.path.basename(taglfns[0]) + ".ref RootCollection" tag_ref_files.append(os.path.basename(taglfns[0])+".ref.root")
def findReferences( infile ): """Find the references from this input TAG file""" global _refCache, _streamRef # Find the links to the stream required cmd = "CollListFileGUID -src " + infile + " RootCollection -queryopt "+ _streamRef +" | cut -d' ' -f 1" rc, out = getstatusoutput(cmd) if (rc!=0): print "ERROR: error du...
print tag_ref_files for f in taglfns: print "Checking: " + os.path.basename(f)+".ref.root" if not os.path.exists(os.path.basename(f)+".ref.root"): print "Copying..." tag_ref_files.append(os.path.basename(f)+".ref.root") shutil.copyfile(os.path.basename(taglfns[0]) + ".ref.root", os.path.basename(f)+".ref.root")
def findReferences( infile ): """Find the references from this input TAG file""" global _refCache, _streamRef # Find the links to the stream required cmd = "CollListFileGUID -src " + infile + " RootCollection -queryopt "+ _streamRef +" | cut -d' ' -f 1" rc, out = getstatusoutput(cmd) if (rc!=0): print "ERROR: error du...
print tag_ref_files
def findReferences( infile ): """Find the references from this input TAG file""" global _refCache, _streamRef # Find the links to the stream required cmd = "CollListFileGUID -src " + infile + " RootCollection -queryopt "+ _streamRef +" | cut -d' ' -f 1" rc, out = getstatusoutput(cmd) if (rc!=0): print "ERROR: error du...
requirementsSoftware = ['VO-atlas-production-%s-%s' %(app.atlas_production, cmtconfig )]
requirementsSoftware = ['VO-atlas-%s-%s-%s' %(app.atlas_project.lower(), app.atlas_production, cmtconfig )]
def master_prepare( self, app, appconfig): """Prepare the master job"""
subjobDownload = options.get('subjobDownload')
def retrieve(self, type=None, name=None, **options ): """Retrieve files listed in outputdata and registered in output from remote SE to local filesystem in background thread""" from Ganga.GPIDev.Lib.Job import Job from GangaAtlas.Lib.ATLASDataset import Download import os, threading job = self._getParent()
if len(job.subjobs) > 0:
if len(job.subjobs) > 0 and subjobDownload:
def retrieve(self, type=None, name=None, **options ): """Retrieve files listed in outputdata and registered in output from remote SE to local filesystem in background thread""" from Ganga.GPIDev.Lib.Job import Job from GangaAtlas.Lib.ATLASDataset import Download import os, threading job = self._getParent()
filenames = job.outputdata.output for fileinfo in filenames: filename = fileinfo.split(',')[1]
if masterJob and not subjobDownload:
def retrieve(self, type=None, name=None, **options ): """Retrieve files listed in outputdata and registered in output from remote SE to local filesystem in background thread""" from Ganga.GPIDev.Lib.Job import Job from GangaAtlas.Lib.ATLASDataset import Download import os, threading job = self._getParent()
cmd = '%s -H %s -f %s %s' %(exe, outputlocation, filename, job.outputdata.datasetname)
cmd = '%s -H %s %s' %(exe, outputlocation, job.outputdata.datasetname)
def retrieve(self, type=None, name=None, **options ): """Retrieve files listed in outputdata and registered in output from remote SE to local filesystem in background thread""" from Ganga.GPIDev.Lib.Job import Job from GangaAtlas.Lib.ATLASDataset import Download import os, threading job = self._getParent()
cmd = '%s -s %s -H %s -f %s %s' %(exe, job.outputdata.location, outputlocation, filename, job.outputdata.datasetname)
cmd = '%s -H %s %s' %(exe, outputlocation, job.outputdata.datasetname)
def retrieve(self, type=None, name=None, **options ): """Retrieve files listed in outputdata and registered in output from remote SE to local filesystem in background thread""" from Ganga.GPIDev.Lib.Job import Job from GangaAtlas.Lib.ATLASDataset import Download import os, threading job = self._getParent()
if job.inputdata and len(app.sites)>0: from dq2.info.TiersOfATLAS import whichCloud,ToACache inclouds=[] for site in app.sites: cloudSite=whichCloud(app.sites[0]) if cloudSite not in inclouds: inclouds.append(cloudSite) outclouds=[] for cloudSite in inclouds: for cloudID, eachCloud in ToACache.dbcloud.iteritems(): if...
def master_prepare(self,app,appmasterconfig):
print outclouds if len(outclouds)>0: if not job.backend.requirements.cloud: job.backend.requirements.cloud=outclouds[0] else: try: assert job.backend.requirements.cloud in outclouds except: raise ApplicationConfigurationError(None,'Input dataset not available in target cloud %s. Please try any of the following %s' % (...
def master_prepare(self,app,appmasterconfig):
self.__job.info.monitor.jmdfile = WNConfig.LOG_DIR + os.sep + escapedJobID + os.sep + UIConfig.PUBLISHER_JMD_FILE
jmdDir = WNConfig.LOG_DIR + os.sep + escapedJobID if not os.path.exists(jmdDir): os.makedirs(jmdDir, 0600) self.__job.info.monitor.jmdfile = jmdDir + os.sep + UIConfig.PUBLISHER_JMD_FILE
def __startJobListener(self): """ Start the job listener for live monitoring support """ if not isinstance(self.__job.info.monitor, JobExecutionMonitor.JobExecutionMonitor): return
def execute_build_job(trafo, sources, parameters): tmpdir = '/tmp/%s' % commands.getoutput('uuidgen') os.system("mkdir %s && cd %s" % (tmpdir, tmpdir)) status, output = commands.getstatusoutput("cd %s && wget %s && ln -s %s ." % (tmpdir, trafo, sources)) if status != 0: print output raise ApplicationConfigurationError...
def execute_build_job(trafo, sources, parameters): tmpdir = '/tmp/%s' % commands.getoutput('uuidgen') os.system("mkdir %s && cd %s" % (tmpdir, tmpdir)) status, output = commands.getstatusoutput("cd %s && wget %s && ln -s %s ." % (tmpdir, trafo, sources)) if status != 0: print output raise ApplicationConfigurationError...
def make_local_libds(self, jspec, sources, nobuild): if nobuild: tmpdir = '/tmp/%s' % commands.getoutput('uuidgen') os.system("mkdir %s" % (tmpdir)) status, output = commands.getstatusoutput("cd %s && cp %s %s" % (tmpdir, sources, self.library)) else: tmpdir = execute_build_job(jspec.transformation, sources, jspec.jobP...
def make_local_libds(self, jspec, sources, nobuild): if nobuild: tmpdir = '/tmp/%s' % commands.getoutput('uuidgen') os.system("mkdir %s" % (tmpdir)) status, output = commands.getstatusoutput("cd %s && cp %s %s" % (tmpdir, sources, self.library)) else: tmpdir = execute_build_job(jspec.transformation, sources, jspec.jobP...
rc, out = AthenaUtils.getAthenaVer() if not rc: raise ApplicationConfigurationError(None, 'CMT could not parse correct environment ! \n Did you start/setup ganga in the run/ or cmt/ subdirectory of your athena analysis package ?') self.userarea = out['workArea']
def master_prepare(self,app,appconfig): '''Prepare the master job'''
ua = os.path.abspath(self.userarea)
rc, out = AthenaUtils.getAthenaVer() if not rc: raise ApplicationConfigurationError(None, 'CMT could not parse correct environment ! \n Did you start/setup ganga in the run/ or cmt/ subdirectory of your athena analysis package ?') userarea = out['workArea'] ua = os.path.abspath(userarea)
def master_prepare(self,app,appconfig): '''Prepare the master job'''
logger.info("Creating a build job for %s"%','.join(bjsites)) bjspecs=[] for bjsite in bjsites: tmpLibDS = job.outputdata.datasetname+'.lib' jspec = JobSpec() jspec.jobDefinitionID = job.id jspec.jobName = commands.getoutput('uuidgen') jspec.AtlasRelease = 'Atlas-%s' % app.atlas_release jspec.homepackag...
if app.athena_compile: logger.info("Creating a build job for %s"%','.join(bjsites)) bjspecs=[] for bjsite in bjsites: tmpLibDS = job.outputdata.datasetname+'.lib' jspec = JobSpec() jspec.jobDefinitionID = job.id jspec.jobName = commands.getoutput('uuidgen') jspec.AtlasRelease = 'Atlas-%s' % app.atlas_r...
def master_prepare(self,app,appconfig): '''Prepare the master job'''
if local_libds: self.make_local_libds(jspec, inputsandbox, local_libds_nobuild) job.backend.libds = self.libDataset jspec = None self.fileBO = getLibFileSpecFromLibDS(self.libDataset) return bjspecs
return bjspecs else: return []
def master_prepare(self,app,appconfig): '''Prepare the master job'''
if not job.backend.libds: flib = FileSpec() flib.lfn = self.libraries[job.backend.site] flib.type = 'input' flib.dataset = self.libDatasets[job.backend.site] flib.dispatchDBlock = self.libDatasets[job.backend.site] else: flib = FileSpec() flib.lfn = self.fileBO.lfn flib.GUID ...
if job.application.athena_compile: if not job.backend.libds: flib = FileSpec() flib.lfn = self.libraries[job.backend.site] flib.type = 'input' flib.dataset = self.libDatasets[job.backend.site] flib.dispatchDBlock = self.libDatasets[job.backend.site] else: flib = FileSpec() flib.lfn ...
def prepare(self,app,appsubconfig,appmasterconfig,jobmasterconfig): '''prepare the subjob specific configuration'''
param = '-l %s ' % self.libraries[job.backend.site]
if app.athena_compile: param = '-l %s ' % self.libraries[job.backend.site]
def prepare(self,app,appsubconfig,appmasterconfig,jobmasterconfig): '''prepare the subjob specific configuration'''
if len(subtask_dsname) > dq2_config['OUTPUTDATASET_NAMELENGTH']: logger.debug("Proposed dataset name longer than limit (%d). Restricting dataset name..." % dq2_config['OUTPUTDATASET_NAMELENGTH']) while len(subtask_dsname) > dq2_config['OUTPUTDATASET_NAMELENGTH']:
max_length_site = len("ALBERTA-WESTGRID-T2_SCRATCHDISK ") max_length = dq2_config['OUTPUTDATASET_NAMELENGTH'] - max_length_site if len(subtask_dsname) > max_length: logger.debug("Proposed dataset name longer than limit (%d). Restricting dataset name..." % max_length) while len(subtask_dsname) > max_length:
def get_dataset_name(self): task = self._getParent() name_base = ["user",getNickname(),task.creation_date,"task_%s" % task.id] if self.inputdata.dataset: subtask_dsname = ".".join(name_base +["subtask_%s" % task.transforms.index(self), str(self.inputdata.dataset[0].strip("/"))]) else: subtask_dsname = ".".join(name_bas...
outputdata = DQ2OutputDataset() try: outputdata.create_dataset(subtask_dsname) except DQDatasetExistsException: pass try: infos = []
infos = {} for oinfo in j.outputdata.output:
def checkCompletedApp(self, app): task = self._getParent() j = app._getParent() for odat in j.outputdata.outputdata: # Look out: if this is changed, there is anothher one like it below! if 0==len([f for f in j.outputdata.output if ".".join(odat.split(".")[:-1]) in f]): logger.error("Job %s has not produced %s file, onl...
for oinfo in j.outputdata.output: info = oinfo.split(",") master_replica = dq2.getMasterReplicaLocation(info[0]) if master_replica: info[5] = master_replica
info = oinfo.split(",") master_replica = dq2.getMasterReplicaLocation(info[0]) if master_replica: info[5] = master_replica else: replicas = dq2.listDatasetReplicas(info[0]).values() if len(replicas) == 0: info[5] = getPandaClient().PandaSites[info[5]]["ddm"]
def checkCompletedApp(self, app): task = self._getParent() j = app._getParent() for odat in j.outputdata.outputdata: # Look out: if this is changed, there is anothher one like it below! if 0==len([f for f in j.outputdata.output if ".".join(odat.split(".")[:-1]) in f]): logger.error("Job %s has not produced %s file, onl...
replicas = dq2.listDatasetReplicas(info[0]).values() if len(replicas) == 0: info[5] = getPandaClient().PandaSites[info[5]]["ddm"] else: complete, incomplete = replicas[0].values() info[5] = (complete + incomplete)[0] if info[4][:3] == "ad:": info[4] = info[4][3:] info[0] = subtask_dsname infos.append(",".join(info))
complete, incomplete = replicas[0].values() info[5] = (complete + incomplete)[0] if info[4][:3] == "ad:": info[4] = info[4][3:]
def checkCompletedApp(self, app): task = self._getParent() j = app._getParent() for odat in j.outputdata.outputdata: # Look out: if this is changed, there is anothher one like it below! if 0==len([f for f in j.outputdata.output if ".".join(odat.split(".")[:-1]) in f]): logger.error("Job %s has not produced %s file, onl...
outputdata.register_datasets_details(None, infos) except DQFileExistsInDatasetException: pass
datasetname = subtask_dsname + '.' + info[5] info[0] = datasetname infos.setdefault(datasetname, []).append(",".join(info)) for ds in infos.keys(): outputdata = DQ2OutputDataset() try: outputdata.create_dataset(ds) except DQDatasetExistsException: pass try: outputdata.register_datasets_details(None, infos[ds]) except ...
def checkCompletedApp(self, app): task = self._getParent() j = app._getParent() for odat in j.outputdata.outputdata: # Look out: if this is changed, there is anothher one like it below! if 0==len([f for f in j.outputdata.output if ".".join(odat.split(".")[:-1]) in f]): logger.error("Job %s has not produced %s file, onl...
try: dq2.registerDatasetsInContainer(task_container, [ subtask_dsname ]) except DQContainerAlreadyHasDataset: pass except Exception, x: logger.error('Problem registering dataset %s in container %s: %s %s' %( subtask_dsname, task_container, x.__class__, x))
for ds in infos.keys(): try: dq2.registerDatasetsInContainer(task_container, [ ds ] ) except DQContainerAlreadyHasDataset: pass except Exception, x: logger.error('Problem registering dataset %s in container %s: %s %s' %( subtask_dsname, task_container, x.__class__, x))
def checkCompletedApp(self, app): task = self._getParent() j = app._getParent() for odat in j.outputdata.outputdata: # Look out: if this is changed, there is anothher one like it below! if 0==len([f for f in j.outputdata.output if ".".join(odat.split(".")[:-1]) in f]): logger.error("Job %s has not produced %s file, onl...
input_sandbox_uris.append( idx['remote'][f] )
input_sandbox_uris.append( idx['remote'][ os.path.basename(f) ] )
def preparejob(self,jobconfig,master_job_sandbox): '''Prepare the JDL'''
raise NameError, "ERROR: DATASETNAME not defined"
print "DATASETNAME not defined !" if not datasettype == 'TIER3': sys.exit(EC_Configuration) else: datasetnames = []
def register_datasets_in_container(container, dataset): """Register dataset in container""" if not container.endswith('/'): containerName = container+'/' # Check if container already exists containerinfo = {} try: dq2_lock.acquire() try: containerinfo = dq2.listDatasets(containerName) except: containerinfo = {} final...
dsetList.append(ln.split('=')[1].strip() + "/")
if resolve_dataset_name(ln.split('=')[1].strip()): dsetList.append(ln.split('=')[1].strip() + "/") else: dsetList.append(ln.split('=')[1].strip())
def search(self, pattern='', maxresults = 2, extraargs = []): argument=[] dsetList = [] if self.goodRunListXML.name != '':
result = [] result.append("{") result.append("\"id\": %s," % addQuotes(job.fqid)) result.append("\"status\": %s," % addQuotes(job.status)) result.append("\"name\": %s," % addQuotes(job.name)) result.append("\"application\": %s," % addQuotes(job.application.__class__.__name__)) result.append("\"backend\": %s," % addQuo...
undefinedAttribute = 'UNDEFINED' try: result = [] result.append("{") result.append("\"id\": %s," % addQuotes(job.fqid)) result.append("\"status\": %s," % addQuotes(job.status)) result.append("\"name\": %s," % addQuotes(job.name)) result.append("\"application\": %s," % addQuotes(job.application.__class__.__name__)) re...
def get_job_JSON(job): result = [] result.append("{") result.append("\"id\": %s," % addQuotes(job.fqid)) result.append("\"status\": %s," % addQuotes(job.status)) result.append("\"name\": %s," % addQuotes(job.name)) result.append("\"application\": %s," % addQuotes(job.application.__class__.__name__)) result.append("\"...
jobs_dictionary[job.id] = JobRelatedInfo(get_job_JSON(job), job.time.timestamps['new'])
try: jobs_dictionary[job.id] = JobRelatedInfo(get_job_JSON(job), job.time.timestamps['new']) except RegistryKeyError: pass
def fill_jobs_dictionary(): for job in jobs: jobs_dictionary[job.id] = JobRelatedInfo(get_job_JSON(job), job.time.timestamps['new'])
exeDir = os.getcwd() webMonitoringLink = os.path.join(os.path.dirname(exeDir), 'python', 'Ganga', 'Core', 'WebMonitoringGUI', 'client', 'index.html' )
webMonitoringLink = os.path.join(config['System']['GANGA_PYTHONPATH'], 'Ganga', 'Core', 'WebMonitoringGUI', 'client', 'index.html' )
def getMonitoringLink(port): exeDir = os.getcwd() webMonitoringLink = os.path.join(os.path.dirname(exeDir), 'python', 'Ganga', 'Core', 'WebMonitoringGUI', 'client', 'index.html' ) return 'file://' + webMonitoringLink + '?port=' + str(port)
logger.info('Proceeding without an input dataset.')
logger.info('Submitting without an input dataset.')
def master_prepare(self,app,appconfig): '''Prepare the master job'''
if len(job.subjobs) == 0 and job.backend.site == 'AUTO': raise ApplicationConfigurationError(None,'Error: backend.site=AUTO after brokerage. Report to DA Help Forum')
def master_prepare(self,app,appconfig): '''Prepare the master job'''
for sj in job.subjobs: sitesdict[sj.backend.site] = 1 bjsites = sitesdict.keys()
bjsites = [] if job.subjobs: for sj in job.subjobs: sitesdict[sj.backend.site] = 1 bjsites = sitesdict.keys() else: bjsites = [job.backend.site]
def master_prepare(self,app,appconfig): '''Prepare the master job'''
return ''.join (random.choice (string.letters) for ii in range (length + 1))
return ''.join ([random.choice (string.letters) for ii in range (length + 1)])
def random_string (length): return ''.join (random.choice (string.letters) for ii in range (length + 1))
self.dirty_objs = {}
self.dirty_objs = []
def __init__(self, name, doc, dirty_flush_counter=10, update_index_time = 30): """Registry constructor, giving public name and documentation""" self.name = name self.doc = doc self._started = False self.dirty_flush_counter = dirty_flush_counter self.dirty_objs = {} self.dirty_hits = 0 self.update_index_time = update_in...
self.dirty_objs = {}
self.dirty_objs = []
def clean(self,force=False): """Deletes all elements of the registry, if no other sessions are present. if force == True it removes them regardless of other sessions. Returns True on success, False on failure.""" if not self._started: raise RegistryAccessError("Cannot clean a disconnected repository!") self._lock.acqui...
del self.dirty_objs[obj]
self.dirty_objs.remove(obj)
def _remove(self,obj,auto_removed=0): """ Private method removing the obj from the registry. This method always called. This method may be overriden in the subclass to trigger additional actions on the removal. 'auto_removed' is set to true if this method is called in the context of obj.remove() method to avoid recursi...
self.dirty_objs[obj] = 1
if not obj in self.dirty_objs: self.dirty_objs.append(obj)
def _dirty(self,obj): """ Mark an object as dirty. Trigger automatic flush after specified number of dirty hits Raise RepositoryError Raise RegistryAccessError Raise RegistryLockError""" logger.debug("_dirty(%s)" % id(obj)) self._write_access(obj) self._lock.acquire() try: self.dirty_objs[obj] = 1 self.dirty_hits += 1 ...
self.dirty_objs[obj] = 1
if not obj in self.dirty_objs: self.dirty_objs.append(obj)
def _flush(self, objs=[]): """Flush a set of objects to the persistency layer immediately Raise RepositoryError Raise RegistryAccessError Raise RegistryLockError""" #print self.name, objs, self.dirty_objs logger.debug("_flush(%s)" % objs) if not self._started: raise RegistryAccessError("Cannot flush to a disconnected r...
for obj in self.dirty_objs.keys():
for obj in self.dirty_objs:
def _flush(self, objs=[]): """Flush a set of objects to the persistency layer immediately Raise RepositoryError Raise RegistryAccessError Raise RegistryLockError""" #print self.name, objs, self.dirty_objs logger.debug("_flush(%s)" % objs) if not self._started: raise RegistryAccessError("Cannot flush to a disconnected r...
self.dirty_objs = {}
self.dirty_objs = []
def _flush(self, objs=[]): """Flush a set of objects to the persistency layer immediately Raise RepositoryError Raise RegistryAccessError Raise RegistryLockError""" #print self.name, objs, self.dirty_objs logger.debug("_flush(%s)" % objs) if not self._started: raise RegistryAccessError("Cannot flush to a disconnected r...
del self.dirty_objs[obj]
self.dirty_objs.remove(obj)
def _release_lock(self, obj): """Release the lock on a given object. Raise RepositoryError Raise RegistryAccessError Raise ObjectNotInRegistryError""" if not self._started: raise RegistryAccessError("Cannot manipulate locks of a disconnected repository!") logger.debug("_release_lock(%s)" % obj) self._lock.acquire() try...
repositoryPath = "repository/$usr/LocalXML/6.0/jobs/0xxx"
repositoryPath = "repository/$usr/LocalXML/6.0/jobs/$thousandsNumxxx"
def report_inner(job=None): userInfoDirName = "userreport" tempDirName = "reportsRepository" #job relevant info inputDirName = "inputdir" outputDirName = "outputdir" jobSummaryFileName = "jobsummary.txt" jobFullPrintFileName = "jobfullprint.txt" #non job relevant info - user's info environFileName = "environ.txt" user...
raise BackendError('Panda','Cannot submit to %s because it is in your requirements.excluded_sites list'%(self.site,s['status']))
raise BackendError('Panda','Cannot submit to %s because it is in your requirements.excluded_sites list'%self.site)
def list_ddm_sites(self,allowTape=False): from pandatools import Client spacetokens = [] if self.site == 'AUTO': sites=Client.PandaSites.keys() for s in sites: if Client.PandaSites[s]['status'] not in ['online'] or s in self.requirements.excluded_sites or (not self.requirements.anyCloud and Client.PandaSites[s]['cloud'...
if 0==len([f for f in j.outputdata.output if odat in f]):
if 0==len([f for f in j.outputdata.output if ".".join(odat.split(".")[:-1]) in f]):
def checkCompletedApp(self, app): j = app._getParent() for odat in j.outputdata.outputdata: if 0==len([f for f in j.outputdata.output if odat in f]): logger.error("Job %s has not produced %s file, only: %s" % (j.id, odat, j.outputdata.output)) return False # if this is the first app to complete the partition... if self...
logger.info('removing job %d',self.id)
def remove(self,force=False): '''Remove the job.
logger.warning('<end of first 255 bytes of output>')
logger.warning('<end of first %d bytes of output>',BYTES)
def cmd(self,cmd,soutfile=None,allowed_exit=[0], capture_stderr=False): "Execute an OS command and captures the stderr and stdout which are returned in a file"
self.user_area_path = tmpDir
if self.user_area_path != '': if not os.path.exists(self.user_area_path): logger.warning('user_area_path %s does not exist! Using %s instead.', self.user_area_path, tmpDir ) self.user_area_path = tmpDir else: self.user_area_path = tmpDir
def prepare(self, **options): """Extract Athena job configuration and prepare job for submission"""
'actualqueue' : SimpleItem(defvalue='',protected=1,copyable=0,doc='queue name where the job was submitted.')
'actualqueue' : SimpleItem(defvalue='',protected=1,copyable=0,doc='queue name where the job was submitted.'), 'actualCE' : SimpleItem(defvalue='',protected=1,copyable=0,doc='hostname where the job is/was running.')
def shell_cmd(cmd,soutfile=None,allowed_exit=[0]): if not soutfile: import tempfile soutfile = tempfile.mktemp() # FIXME: garbbing stdout is done by shell magic and probably should be implemented in python directly cmd = "%s > %s 2>&1" % (cmd,soutfile) logger.debug("running shell command: %s",cmd) rc = os.system(cmd...
pid,queue,exitcode=None,None,None
pid,queue,actualCE,exitcode=None,None,None,None
def get_status(f): """Give (pid,queue,exit code) for job"""
return pid,queue,exitcode
return pid,queue,actualCE,exitcode
def get_status(f): """Give (pid,queue,exit code) for job"""
mactualCE = reactualCE.search(stat) if mactualCE: actualCE = str(mactualCE.group('actualCE'))
def get_status(f): """Give (pid,queue,exit code) for job"""
pid,queue,exitcode = get_status(statusfile)
pid,queue,actualCE,exitcode = get_status(statusfile)
def get_status(f): """Give (pid,queue,exit code) for job"""
j.backend.actualqueue = queue
j.backend.actualqueue = queue if actualCE: j.backend.actualCE = actualCE
def get_status(f): """Give (pid,queue,exit code) for job"""
rc, output = commands.getstatusoutput('tar rf %s -C %s %s' % (inputsandbox, path, fn))
rc, output = commands.getstatusoutput('tar -h -r -f %s -C %s %s' % (inputsandbox, path, fn))
def master_prepare(self,app,appconfig): '''Prepare the master job'''
else: env_str = ""
def master_prepare(self,app,appconfig): '''Prepare the master job'''
'sandboxcache' : ComponentItem('LCGSandboxCache',copyable=1,doc='Interface for handling oversized input sandbox'),
'sandboxcache' : ComponentItem('GridSandboxCache',copyable=1,doc='Interface for handling oversized input sandbox'),
def __cream_resolveOSBList__(job, jdl): osbURIList = [] re_osb = re.compile('^.*OutputSandbox\s+\=\s+\{(.*)\}$') for l in jdl.split(';'): m = re_osb.match( l ) if m: osb = m.group(1) osb = re.sub(r'\s?\"\s?', '', osb) for f in osb.split(','): if not urlparse(f)[0]: osbURIList.append('%s/%s' % ( job.backend.osbURI, ...
logger.warning('Monitoring loop should not have been called for job %d as status is already %s',job.id,job.status)
logger.warning('Monitoring loop should not have been called for job %d as status is already %s',job.getFQID('.'),job.status)
def updateGangaJobStatus(job,status): '''map backend job status to Ganga job status'''
datasetnameComp = self.datasetname + '.' + self.location
if not datasetnameTemp.endswith('.' + self.location): datasetnameComp = self.datasetname + '.' + self.location else: datasetnameComp = self.datasetname
def fill(self, type=None, name=None, **options ): """Determine outputdata and outputsandbox locations of finished jobs and fill output variable"""
datasetnameComp = self.datasetname + '.' + outputInfo.split(',')[4]
datasetnameComp = self.datasetname + '.' + outputInfo.split(',')[5]
def fill(self, type=None, name=None, **options ): """Determine outputdata and outputsandbox locations of finished jobs and fill output variable"""
if job.backend.requirements.cloud == 'ALL' and not job.backend.requirements.sites and job.outputdata and job.outputdata._name == 'DQ2OutputDataset':
if hasattr(job.backend.requirements, 'cloud') and job.backend.requirements.cloud == 'ALL' and not job.backend.requirements.sites and job.outputdata and job.outputdata._name == 'DQ2OutputDataset':
def split(self,job):
def merge(self, sum_outputdir = None, subjobs = None, **options ):
def merge(self, subjobs = None, sum_outputdir = None, **options ):
def merge(self, sum_outputdir = None, subjobs = None, **options ): '''Merge local root tuples of subjobs output'''
ipythonFile = open(os.path.join(userHomeDir, '.ipython/history'), 'r')
ipythonFile = open(os.path.join(os.environ['IPYTHONDIR'], 'history'), 'r')
def renameDataFiles(directory):
if job.inputdata and self.inputdatatype=='DQ2':
if job.inputdata and self.inputdatatype=='DQ2' and not job.inputdata.tag_info:
def prepare(self,app,appsubconfig,appmasterconfig,jobmasterconfig): '''prepare the subjob specific configuration'''
if job.inputdata: param += '-i "%s" ' % job.inputdata.names
if job.inputdata: input_files = job.inputdata.names if job.inputdata.tag_info: tag_file = job.inputdata.tag_info.keys()[0] if job.inputdata.tag_info[tag_file]['path'] != '' and job.inputdata.tag_info[tag_file]['dataset'] == '': param += '--shipInput ' if self.runConfig.input.collRefName: param += '--collRefName %s...
def prepare(self,app,appsubconfig,appmasterconfig,jobmasterconfig): '''prepare the subjob specific configuration'''
for fname in [f.name for f in job.inputsandbox]:
for fname in [os.path.abspath(f.name) for f in job.inputsandbox]:
def master_prepare(self,app,appconfig): '''Prepare the master job'''
path = fname[:fname.rfind(os.sep)] f = fname[fname.rfind(os.sep)+1:]
path = os.path.dirname(fname) fn = os.path.basename(fname) rd = os.path.abspath(self.rundirectory) if rd in path: fn = fname[len(rd)+1:] path = rd
def master_prepare(self,app,appconfig): '''Prepare the master job'''
input_files = ['.'.join( tag_file.split(".")[:len(tag_file.split("."))-2] )]
input_files = ['.'.join( tag_file.split(".")[:len(tag_file.split("."))-3] ) + '.ref.root']
def prepare(self,app,appsubconfig,appmasterconfig,jobmasterconfig): '''prepare the subjob specific configuration'''
guid_boundaries.append(job.inputdata.tag_info[tag_file2]['refs'][0][2])
for ref in job.inputdata.tag_info[tag_file2]['refs']: guid_boundaries.append(ref[2])
def prepare(self,app,appsubconfig,appmasterconfig,jobmasterconfig): '''prepare the subjob specific configuration'''
return "%s (pid %s) sice %s" % (".".join(si[:-3]),si[-2],time.ctime(int(si[-3])/1000))
return "%s (pid %s) since %s" % (".".join(si[:-3]),si[-2],time.ctime(int(si[-3])/1000))
def session_to_info(self,session): si = session.split(".") try: return "%s (pid %s) sice %s" % (".".join(si[:-3]),si[-2],time.ctime(int(si[-3])/1000)) except Exception: return session
jobdate = time.strftime('%Y%m%d')
jobdate = time.strftime('%Y%m%d%H%M%S')
def dq2outputdatasetname(datasetname, jobid, isGroupDS, groupname): jobdate = time.strftime('%Y%m%d') usertag = config['usertag'] # Get DN or nickname username = gridProxy.identity(safe=True) if config['ALLOW_MISSING_NICKNAME_DQ2OUTPUTDATASET']: nickname = getNickname(allowMissingNickname=True) else: nickname = getNi...
'datasetname' : SimpleItem(defvalue='', doc='Name of the DQ2 output dataset automatically filled by the job'),
'datasetname' : SimpleItem(defvalue='', filter="checkNameConsistency", doc='Name of the DQ2 output dataset automatically filled by the job'),
def list_locations_siteindex(self,dataset=None, timeout=15, days=2, replicaList=False):
'isGroupDS' : SimpleItem(defvalue = False, doc = 'Use group datasetname prefix'), 'groupname' : SimpleItem(defvalue='', doc='Name of the group to be used if isGroupDS=True'),
def list_locations_siteindex(self,dataset=None, timeout=15, days=2, replicaList=False):
print 'My status',self.status,status
def force_status(self,status,force=False): ''' Force job to enter the "failed" or "completed" state. This may be used for marking jobs "bad" jobs or jobs which are stuck in one of the internal ganga states (e.g. completing).
mpat = re.compile(r'(\[(?P<section>\S+)\]|)(?P<option>\S+)=(?P<value>.+)')
mpat = re.compile(r'(\[(?P<section>\S+)\]|)(?P<option>[a-zA-z0-9._]+)=(?P<value>.+)')
def parse_cmdline_config_options(cmdline_options): """ Parse a list of command line config options and return a list of triplets (section,option,value). In case of parsing errors, raise ConfigError exception. """ import re mpat = re.compile(r'(\[(?P<section>\S+)\]|)(?P<option>\S+)=(?P<value>.+)') section = None
targets = [] if job.backend.CE: targets.append('CE_%s' % job.backend.CE) for site in job.backend.requirements.sites: if site: targets.append('SITE_%s' % site) targetcsv = ','.join(targets) return CommonUtil.strip_to_none(targetcsv)
if hasattr(job.backend, 'CE'): targets = [] if job.backend.CE: targets.append('CE_%s' % job.backend.CE) for site in job.backend.requirements.sites: if site: targets.append('SITE_%s' % site) targetcsv = ','.join(targets) return CommonUtil.strip_to_none(targetcsv) else: return CommonUtil.hostname()
def cl_target(job): """Build target. Only run on client.""" targets = [] if job.backend.CE: targets.append('CE_%s' % job.backend.CE) for site in job.backend.requirements.sites: if site: targets.append('SITE_%s' % site) targetcsv = ','.join(targets) return CommonUtil.strip_to_none(targetcsv)
print fsize print config['BoundSandboxLimit']
def __check_and_prestage_inputfile__(self, file): '''Checks the given input file size and if it's size is over "BoundSandboxLimit", prestage it to a grid SE.
print md5sum
def __check_and_prestage_inputfile__(self, file): '''Checks the given input file size and if it's size is over "BoundSandboxLimit", prestage it to a grid SE.
sjs.getOutputWorkspace().remove(preserve_top=True)
def resubmit(self): """Resubmit a failed or completed job. """
self.getOutputWorkspace().remove(preserve_top=True)
def resubmit(self): """Resubmit a failed or completed job. """
def keyPressed(): return select.select([sys.stdin], [], [], 0) == ([sys.stdin], [], []) p = os.path.expanduser("~/.GangaJEM") if not os.path.exists(p): os.mkdir(p) timeout = 60 print "* " print "* Thank you for trying this beta version of the Job Execution Monitor!" print "* " print "* This version brings a major re...
try: def keyPressed(): return select.select([sys.stdin], [], [], 0) == ([sys.stdin], [], []) p = os.path.expanduser("~/.GangaJEM") if not os.path.exists(p): os.mkdir(p) timeout = 60 print "* " print "* Thank you for trying this beta version of the Job Execution Monitor!" print "* " print "* This version brings a maj...
def keyPressed(): return select.select([sys.stdin], [], [], 0) == ([sys.stdin], [], [])
time.sleep(0.01) if timeout == 0: print "* ...yes. will gather information about your job runs." break timeout = timeout - 1 ts = time.time() except KeyboardInterrupt: fd = open(p + "/anonymous", "w") fd.write(".\n") fd.close() self.anonymous = True print "* ...no. statistics about your job runs will be anonymized....
timeout = timeout - 1 ts = time.time() except KeyboardInterrupt: fd = open(p + "/anonymous", "w") fd.write(".\n") fd.close() self.anonymous = True print "* ...no. statistics about your job runs will be anonymized." except: pass else: if os.path.exists(p + "/anonymous"): self.anonymous = True except: self.anonymous =...
def keyPressed(): return select.select([sys.stdin], [], [], 0) == ([sys.stdin], [], [])
for d in self.changed_ids.itervalues():
for d in self.registry.changed_ids.itervalues():
def remove(self): self.registry._lock.acquire() try: if len(self.registry.repository.lock([self.id])) == 0: errstr = "Could not lock '%s' object #%i!" % (self.registry.name,self.id) try: errstr += " Object is locked by session '%s' " % self.registry.repository.get_lock_session(self.id) except Exception, x: print x pass...
'BACKEND' : self.job_info.backend.__class__.__name__
'BACKEND' : self.job_info.backend.__class__.__name__, 'BATCH' : batch, 'GANGA_HOSTNAME' : host, 'JOB_UUID' : jj.info.uuid, 'JOB_NAME' : jj.name
def getJobInfo(self): """Create job_info from Job object.""" j = self.job_info # called on client, so job_info is Job object ji = { 'fqid': j.fqid, 'EXECUTION_BACKEND': self.dynamic_util.cl_execution_backend(j), 'OWNERDN': self.dynamic_util.cl_ownerdn(), 'JOB_ID_INSIDE_THE_TASK': self.dynamic_util.cl_job_id_inside_the_...
if job._getRoot().splitter and job._getRoot().splitter.numevtsperjob > 0 :
if job._getRoot().splitter and hasattr(job._getRoot().splitter, 'numevtsperjob') and job._getRoot().splitter.numevtsperjob > 0 :
def prepare(self,app,appsubconfig,appmasterconfig,jobmasterconfig): """prepare the subjob specific configuration"""
if (configSETYPE == 'dpm'):
if (configSETYPE == 'dpm') and files[lfn].has_key('surl'):
def _makeJobO(files, tag=False, type='TAG', version=12, dtype='MC', usePrependJobO=False): if version >= 13: versionString='ServiceMgr.' else: versionString = '' # sort lfns = files.keys() lfns.sort() # open jobO joName = 'input.py' outFile = open(joName,'w') if usePrependJobO: joName = 'preJobO.py' outFilePre = open...
return 'backend_CE'
def cl_target(job): return 'backend_CE' """Build target. Only run on client.""" """ if hasattr(job.backend, 'CE'): targets = [] if job.backend.CE: targets.append('CE_%s' % job.backend.CE) for site in job.backend.requirements.sites: if site: targets.append('SITE_%s' % site) targetcsv = ','.join(targets) return CommonUti...
"""
def cl_target(job): return 'backend_CE' """Build target. Only run on client.""" """ if hasattr(job.backend, 'CE'): targets = [] if job.backend.CE: targets.append('CE_%s' % job.backend.CE) for site in job.backend.requirements.sites: if site: targets.append('SITE_%s' % site) targetcsv = ','.join(targets) return CommonUti...
return '' """
return CommonUtil.hostname()
def cl_target(job): return 'backend_CE' """Build target. Only run on client.""" """ if hasattr(job.backend, 'CE'): targets = [] if job.backend.CE: targets.append('CE_%s' % job.backend.CE) for site in job.backend.requirements.sites: if site: targets.append('SITE_%s' % site) targetcsv = ','.join(targets) return CommonUti...
if it's not defined
if it's None or not defined
def _getMonClasses(option): """ for a given app,backend pair return the monitoring classes or an empty string if it's not defined """ try: return mc[option] except (ConfigError,KeyError): return ''