|
ATLAS Offline Software
|
|
def | findFile (pathvar, fname) |
| Find a named file along a colon separated PATH type variable. More...
|
|
def | getAncestry (listMyOrphans=False) |
| List all processes and parents and form a dictionary where the parent key lists all child PIDs. More...
|
|
def | listChildren (psTree=None, parent=os.getpid(), listOrphans=False) |
| Find all the children of a particular PID (calls itself recursively to descend into each leaf) More...
|
|
def | infanticide (childPIDs=None, sleepTime=3, message=True, listOrphans=False) |
| Kill all PIDs. More...
|
|
def | call (args, bufsize=0, executable=None, stdin=None, preexec_fn=None, close_fds=False, shell=False, cwd=None, env=None, universal_newlines=False, startupinfo=None, creationflags=0, message="", logger=msg, loglevel=None, timeout=None, retry=2, timefactor=1.5, sleeptime=10) |
|
def | asetupReport () |
| Return a string with a report of the current athena setup. More...
|
|
def | releaseIsOlderThan (major, minor=None) |
| Test (to the best of our knowledge) if the current release is older than a major, minor version number. More...
|
|
def | asetupReleaseIsOlderThan (asetup_string, major, minor=None) |
| Test (to the best of our knowledge) if the asetup release is older than a major, minor version number. More...
|
|
def | shQuoteStrings (strArray=sys.argv) |
| Quote a string array so that it can be echoed back on the command line in a cut 'n' paste safe way. More...
|
|
def | lineByLine (filename, strip=True, removeTimestamp=True, substepName=None) |
| Generator to return lines and line count from a file. More...
|
|
def | prettyXML (element, indent=' ', poolFileCatalogFormat=False) |
| XML pretty print an ElementTree.ELement object. More...
|
|
def | isodate () |
| Return isoformated 'now' string. More...
|
|
def | forceToAlphaNum (string) |
| Strip a string down to alpha-numeric characters only. More...
|
|
def | cmpMetadata (metadata1, metadata2, guidCheck='valid') |
| Compare metadata for files, but taking into account that GUID can vary. More...
|
|
def | unpackTarFile (filename, directory=".") |
| Unpack a given tarfile. More...
|
|
def | unpackDBRelease (tarball, dbversion=None) |
| Ensure that the DBRelease tarball has been unpacked. More...
|
|
def | setupDBRelease (setup) |
| Run a DBRelease setup. More...
|
|
def | cvmfsDBReleaseCheck (dbrelease) |
| Validate a DBRelease exists on cvmfs and return the path to the setup script. More...
|
|
def | pickledDump (argdict) |
| Dump a list of arguments to the pickle file given in the 'dumpPickle' argument. More...
|
|
def | JSONDump (argdict) |
| Dump a list of arguments to the JSON file given in the 'dumpJSON' argument. More...
|
|
def | convertToStr (in_string) |
| Recursively convert unicode to str, useful when we have just loaded something from json (TODO: make the transforms happy with unicode as well as plain str!) More...
|
|
def | cliToKey (option) |
| Convert a command line option to the dictionary key that will be used by argparse. More...
|
|
def | printHR (the_object) |
| print in a human-readable way the items of a given object More...
|
|
def | uniqueIdentifier () |
| return a URL-safe, base 64-encoded pseudorandom UUID More...
|
|
def | units (quantity=None, unitSingular="unit", unitPlural="units") |
| return either singular or plural units as appropriate for a given quantity More...
|
|
def | isInteractiveEnv () |
|
def | initialise_processes () |
| initisation procedure for processes of process pool More...
|
|
def | ValgrindCommand (defaultOptions=True, extraOptionsList=None, AthenaSerialisedConfigurationFile="athenaConf.pkl", returnFormat="string") |
|
def | VTuneCommand (defaultOptions=True, extraOptionsList=None, AthenaSerialisedConfigurationFile="athenaConf.pkl", returnFormat="string") |
| return VTune command @detail This function returns a VTune command for use with Athena. More...
|
|
def | calcCpuTime (start, stop) |
|
def | calcWallTime (start, stop) |
|
def | bind_port (host, port) |
|
def | reportEventsPassedSimFilter (log) |
| summarize events passed the ISF_SimEventFilter @detail this function sums up all events passed the ISF_SimEventFilter out of all total events. More...
|
|
◆ asetupReleaseIsOlderThan()
def python.trfUtils.asetupReleaseIsOlderThan |
( |
|
asetup_string, |
|
|
|
major, |
|
|
|
minor = None |
|
) |
| |
Test (to the best of our knowledge) if the asetup release is older than a major, minor version number.
- Parameters
-
asetup_string | asetup string |
major | Major release number |
minor | Minor release number (if not specified, will not be matched against) |
- Returns
- Boolean if current release is found to be older
Definition at line 303 of file trfUtils.py.
309 split_string = asetup_string.split(
',')
311 if 'master' in split_string:
315 reg_exp = re.compile(
r'(?P<major>\d+)\.(?P<minor>\d+)\.(?P<other>.*)')
316 for part
in split_string:
318 match = re.match(reg_exp, part)
320 relmajor =
int(match.group(
'major'))
321 relminor =
int(match.group(
'minor'))
322 msg.info(
'Detected asetup release {0}.{1}(.{2})'.
format(relmajor, relminor, match.group(
'other')))
327 reg_exp = re.compile(
r'(?P<major>\d+)\.(?P<minor>\d+)')
328 for part
in split_string:
330 match = re.match(reg_exp, part)
332 relmajor =
int(match.group(
'major'))
333 relminor =
int(match.group(
'minor'))
334 msg.info(
'Detected asetup release {0}.{1}'.
format(relmajor, relminor))
339 raise RuntimeError(
'asetup version could not be parsed')
348 if minor
is None or relminor >= minor:
352 except Exception
as e:
353 msg.warning(
'Exception thrown when attempting to detect asetup athena version ({0}) from {1}. No release check possible'.
format(e, asetup_string))
◆ asetupReport()
def python.trfUtils.asetupReport |
( |
| ) |
|
Return a string with a report of the current athena setup.
Definition at line 223 of file trfUtils.py.
225 eVars = [
'AtlasBaseDir',
'AtlasProject',
'AtlasVersion',
'AtlasPatch',
'AtlasPatchVersion',
'CMTCONFIG',
'TestArea']
226 if "AtlasProject" in os.environ:
227 CMake_Platform =
"{0}_PLATFORM".
format(os.environ[
"AtlasProject"])
228 if CMake_Platform
in os.environ:
229 eVars.remove(
"CMTCONFIG")
230 eVars.append(CMake_Platform)
232 if eVar
in os.environ:
233 setupMsg +=
'\t%s=%s\n' % (eVar, os.environ[eVar])
235 if 'WorkDir_DIR' in os.environ
and os.access(os.environ[
'WorkDir_DIR'], os.R_OK):
246 setupMsg+=
"No readable patch area found"
248 return setupMsg.rstrip()
◆ bind_port()
def python.trfUtils.bind_port |
( |
|
host, |
|
|
|
port |
|
) |
| |
Definition at line 1698 of file trfUtils.py.
1700 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
1702 s.bind((host, port))
1703 except socket.error
as e:
1705 print(
"Port %s is already in use" %port)
◆ calcCpuTime()
def python.trfUtils.calcCpuTime |
( |
|
start, |
|
|
|
stop |
|
) |
| |
Definition at line 1683 of file trfUtils.py.
1686 cpuTime =
reduce(
lambda x1, x2: x1+x2,
list(map(
lambda x1, x2: x2-x1, start[2:4], stop[2:4])))
◆ calcWallTime()
def python.trfUtils.calcWallTime |
( |
|
start, |
|
|
|
stop |
|
) |
| |
Definition at line 1691 of file trfUtils.py.
1694 wallTime = stop[4] - start[4]
◆ call()
def python.trfUtils.call |
( |
|
args, |
|
|
|
bufsize = 0 , |
|
|
|
executable = None , |
|
|
|
stdin = None , |
|
|
|
preexec_fn = None , |
|
|
|
close_fds = False , |
|
|
|
shell = False , |
|
|
|
cwd = None , |
|
|
|
env = None , |
|
|
|
universal_newlines = False , |
|
|
|
startupinfo = None , |
|
|
|
creationflags = 0 , |
|
|
|
message = "" , |
|
|
|
logger = msg , |
|
|
|
loglevel = None , |
|
|
|
timeout = None , |
|
|
|
retry = 2 , |
|
|
|
timefactor = 1.5 , |
|
|
|
sleeptime = 10 |
|
) |
| |
Definition at line 155 of file trfUtils.py.
155 def call(args, bufsize=0, executable=None, stdin=None, preexec_fn=None, close_fds=False, shell=False, cwd=None, env=None, universal_newlines=False, startupinfo=None, creationflags=0, message="", logger=msg, loglevel=None, timeout=None, retry=2, timefactor=1.5, sleeptime=10):
158 line=p.stdout.readline()
160 line=
"%s%s" % (message, line.rstrip())
164 logger.log(loglevel, line)
167 line=p.stdout.readline()
169 line=
"%s%s" % (message, line.strip())
173 logger.log(loglevel, line)
174 line=p.stdout.readline()
177 loglevel=logging.DEBUG
179 if timeout
is None or timeout<=0:
180 msg.info(
'Executing %s...', args)
181 starttime = time.time()
182 p=Popen(args=args, bufsize=bufsize, executable=executable, stdin=stdin, stdout=PIPE, stderr=STDOUT, preexec_fn=preexec_fn, close_fds=close_fds, shell=shell, cwd=cwd, env=env, universal_newlines=universal_newlines, startupinfo=startupinfo, creationflags=creationflags)
183 while p.poll()
is None:
186 if timeout
is not None:
187 msg.info(
'Executed call within %d s.', time.time()-starttime)
193 msg.info(
'Try %i out of %i (time limit %ss) to call %s.', n+1, retry+1, timeout, args)
194 starttime = time.time()
195 endtime=starttime+timeout
196 p=Popen(args=args, bufsize=bufsize, executable=executable, stdin=stdin, stdout=PIPE, stderr=STDOUT, preexec_fn=preexec_fn, close_fds=close_fds, shell=shell, cwd=cwd, env=env, universal_newlines=universal_newlines, startupinfo=startupinfo, creationflags=creationflags)
197 while p.poll()
is None and time.time()<endtime:
200 msg.warning(
'Timeout limit of %d s reached. Kill subprocess and its children.', timeout)
205 msg.info(
'Checking if something is left in buffer.')
208 msg.info(
'Going to sleep for %d s.', sleeptime)
209 time.sleep(sleeptime)
212 sleeptime*=timefactor
215 msg.info(
'Executed call within %d s.', time.time()-starttime)
218 msg.warning(
'All %i tries failed!', n)
◆ cliToKey()
def python.trfUtils.cliToKey |
( |
|
option | ) |
|
Convert a command line option to the dictionary key that will be used by argparse.
Definition at line 652 of file trfUtils.py.
653 return option.lstrip(
'-').
replace(
'-',
'_')
◆ cmpMetadata()
def python.trfUtils.cmpMetadata |
( |
|
metadata1, |
|
|
|
metadata2, |
|
|
|
guidCheck = 'valid' |
|
) |
| |
Compare metadata for files, but taking into account that GUID can vary.
Compare metadata dictionaries, but allowing for differences in the file_guid property as this is generated randomly for file types without an intrinsic GUID
- Parameters
-
metadata1 | Filel metadata dictionary |
metadata2 | File2 metadata dictionary |
giudCheck | How to compare GUIDs. Valid values are:
equal GUIDs must be the same
valid GUIDs must be valid, but don't have to be the same
ignore The file_guid key is ignored
|
- Returns
- True if metadata is the same, otherwise False
Definition at line 464 of file trfUtils.py.
464 def cmpMetadata(metadata1, metadata2, guidCheck = 'valid'):
466 allFiles =
set(metadata1) |
set(metadata2)
467 if len(allFiles) > len(metadata1)
or len(allFiles) > len(metadata2):
468 msg.warning(
'In metadata comparison file lists are not equal - fails ({0} != {1}'.
format(metadata1, metadata2))
470 for fname
in allFiles:
471 allKeys =
set(metadata1[fname]) |
set(metadata2[fname])
472 if len(allKeys) > len(metadata1[fname])
or len(allFiles) > len(metadata2[fname]):
473 msg.warning(
'In metadata comparison key lists are not equal - fails')
476 if key ==
'file_guid':
477 if guidCheck ==
'ignore':
479 elif guidCheck ==
'equal':
480 if metadata1[fname][
'file_guid'].
upper() == metadata2[fname][
'file_guid'].
upper():
483 msg.warning(
'In metadata comparison strict GUID comparison failed.')
485 elif guidCheck ==
'valid':
487 uuid.UUID(metadata1[fname][
'file_guid'])
488 uuid.UUID(metadata2[fname][
'file_guid'])
491 msg.warning(
'In metadata comparison found invalid GUID strings.')
493 if metadata1[fname][key] != metadata2[fname][key]:
494 msg.warning(
'In metadata comparison found different key values: {0!s} != {1!s}'.
format(metadata1[fname][key], metadata2[fname][key]))
◆ convertToStr()
def python.trfUtils.convertToStr |
( |
|
in_string | ) |
|
Recursively convert unicode to str, useful when we have just loaded something from json (TODO: make the transforms happy with unicode as well as plain str!)
Definition at line 636 of file trfUtils.py.
637 if isinstance(in_string, dict):
639 elif isinstance(in_string, list):
643 elif in_string.__class__.__name__ ==
'unicode':
644 return in_string.encode(
'utf-8')
645 elif in_string.__class__.__name__ ==
'bytes':
646 return in_string.decode(
'utf-8')
◆ cvmfsDBReleaseCheck()
def python.trfUtils.cvmfsDBReleaseCheck |
( |
|
dbrelease | ) |
|
Validate a DBRelease exists on cvmfs and return the path to the setup script.
- Parameters
-
dbrelease | The DBRelease number (X.Y.Z[.A]) or "current" |
- Exceptions
-
- Returns
- Path to setup.py script for this DBRelease
Definition at line 569 of file trfUtils.py.
571 dbdMatch = re.match(
r'([\d\.]+|current)$', dbrelease)
572 msg.debug(
'Attempting to setup DBRelease {0} from cvmfs'.
format(dbrelease))
574 if 'VO_ATLAS_SW_DIR' in os.environ:
575 msg.debug(
'Found site defined path to ATLAS software: {0}'.
format(os.environ[
'VO_ATLAS_SW_DIR']))
576 dbsetup = path.join(os.environ[
'VO_ATLAS_SW_DIR'],
'database',
'DBRelease', dbrelease,
'setup.py')
577 if os.access(dbsetup, os.R_OK):
579 msg.warning(
'Site defined path to ATLAS software seems invalid (failed to access {0}). Will also try standard cvmfs path.'.
format(dbsetup))
581 msg.debug(
'Using standard CVMFS path to ATLAS software')
583 dbsetup = path.join(
'/cvmfs/atlas.cern.ch/repo/sw/database/DBRelease', dbrelease,
'setup.py')
584 if not os.access(dbsetup, os.R_OK):
585 raise trfExceptions.TransformSetupException(trfExit.nameToCode(
'TRF_DBRELEASE_PROBLEM'),
586 'CVMFS DBRelease setup file {0} was not readable'.
format(dbsetup))
587 msg.debug(
'Using cvmfs based dbrelease: {0}'.
format(path.dirname(dbsetup)))
589 raise trfExceptions.TransformSetupException(trfExit.nameToCode(
'TRF_DBRELEASE_PROBLEM'),
590 'Unable to interpret DBRelease "{0}" as either a tarball or a CVMFS release directory'.
format(dbrelease))
◆ findFile()
def python.trfUtils.findFile |
( |
|
pathvar, |
|
|
|
fname |
|
) |
| |
Find a named file along a colon separated PATH type variable.
Note will also work for finding directories
- Returns
- Full path to file or
None
is file is not found
Definition at line 37 of file trfUtils.py.
39 msg.debug(
'Finding full path for {fileName} in path {path}'.
format(
43 if fname.startswith(
'/'):
47 pathElements = pathvar.split(
':')
48 for pathElement
in pathElements:
49 if path.exists(path.join(pathElement, fname)):
50 return(path.join(pathElement, fname))
◆ forceToAlphaNum()
def python.trfUtils.forceToAlphaNum |
( |
|
string | ) |
|
Strip a string down to alpha-numeric characters only.
- Note
- This is used to force executor names and substep aliases to a form that the substep argument parser will recognise. None is still allowed as this is the default for "unset" in some cases.
Definition at line 443 of file trfUtils.py.
444 if string
is None or string.isalnum():
450 msg.warning(
"String {0} was stripped to alphanumeric characters only: {1}".
format(string, newstring))
◆ getAncestry()
def python.trfUtils.getAncestry |
( |
|
listMyOrphans = False | ) |
|
List all processes and parents and form a dictionary where the parent key lists all child PIDs.
- Parameters
-
listMyOrphans | If this is True , then processes which share the same pgid as this process and have parent PID=1 (i.e., init) get added to this process's children, which allows these orphans to be added to the kill list. N.B. this means that orphans have two entries - as child of init and a child of this process |
Definition at line 62 of file trfUtils.py.
63 psCmd = [
'ps',
'ax',
'-o',
'pid,ppid,pgid,args',
'-m']
66 msg.debug(
'Executing %s', psCmd)
67 p = Popen(psCmd, stdout=PIPE, stderr=PIPE)
68 stdout = p.communicate()[0]
71 msg.error(
'Failed to execute "ps" to get process ancestry: %s',
repr(e))
77 for line
in stdout.decode().
split(
'\n'):
79 (pid, ppid, pgid, cmd) = line.split(
None, 3)
87 childDict[ppid].
append(pid)
89 childDict[ppid] = [pid]
90 if listMyOrphans
and ppid == 1
and pgid == myPgid:
91 msg.info(
"Adding PID {0} to list of my children as it seems to be orphaned: {1}".
format(pid, cmd))
92 if myPid
in childDict:
93 childDict[myPid].
append(pid)
95 childDict[myPid] = [pid]
◆ infanticide()
def python.trfUtils.infanticide |
( |
|
childPIDs = None , |
|
|
|
sleepTime = 3 , |
|
|
|
message = True , |
|
|
|
listOrphans = False |
|
) |
| |
Kill all PIDs.
- Note
- Even if this function is used, subprocess objects need to join() with the child to prevent it becoming a zombie
- Parameters
-
childPIDs | Explicit list of PIDs to kill; if absent then listChildren() is called |
sleepTime | Time between SIGTERM and SIGKILL |
message | Boolean if messages should be printed |
listOrphans | Parameter value to pass to getAncestry(), if necessary (beware, killing orphans is dangerous, you may kill "upstream" processes; Caveat Emptor) |
Definition at line 132 of file trfUtils.py.
132 def infanticide(childPIDs = None, sleepTime = 3, message = True, listOrphans = False):
133 if childPIDs
is None:
136 if len(childPIDs) > 0
and message:
137 msg.info(
'Killing these child processes: {0}...'.
format(childPIDs))
139 for pid
in childPIDs:
141 os.kill(pid, signal.SIGTERM)
145 time.sleep(sleepTime)
147 for pid
in childPIDs:
149 os.kill(pid, signal.SIGKILL)
◆ initialise_processes()
def python.trfUtils.initialise_processes |
( |
| ) |
|
initisation procedure for processes of process pool
Definition at line 855 of file trfUtils.py.
861 signal.signal(signal.SIGINT, signal.SIG_IGN)
◆ isInteractiveEnv()
def python.trfUtils.isInteractiveEnv |
( |
| ) |
|
Definition at line 703 of file trfUtils.py.
704 isInteractiveEnv =
False
706 if 'PS1' in os.environ
or 'prompt' in os.environ:
707 isInteractiveEnv =
True
708 elif os.isatty(sys.stdout.fileno())
or os.isatty(sys.stdin.fileno()):
709 isInteractiveEnv =
True
711 return isInteractiveEnv
◆ isodate()
def python.trfUtils.isodate |
( |
| ) |
|
Return isoformated 'now' string.
Uses datetime.isoformat method, but suppressing microseconds
Definition at line 434 of file trfUtils.py.
435 return datetime.now().
replace(microsecond=0).isoformat()
◆ JSONDump()
def python.trfUtils.JSONDump |
( |
|
argdict | ) |
|
Dump a list of arguments to the JSON file given in the 'dumpJSON' argument.
Definition at line 617 of file trfUtils.py.
618 if 'dumpJSON' not in argdict:
622 theArgumentDictionary = {}
623 for k, v
in argdict.items():
626 if isinstance(v, argument):
627 theArgumentDictionary[k] = getattr(v,
"dumpvalue", v.value)
629 theArgumentDictionary[k] = v
630 with open(argdict[
'dumpJSON'],
'w')
as JSONFile:
632 json.dump(theArgumentDictionary, JSONFile, sort_keys=
True, indent=2)
◆ lineByLine()
def python.trfUtils.lineByLine |
( |
|
filename, |
|
|
|
strip = True , |
|
|
|
removeTimestamp = True , |
|
|
|
substepName = None |
|
) |
| |
Generator to return lines and line count from a file.
- Parameters
-
filename | Filename to open and deliver lines from |
strip | If lines get stripped before being returned (default True ) |
removeTimestamp | Removes timestamp from left.(default True ) Since strings are removed only from left, this option requires explicit removal of substepName. |
substepName | Removes substepName from left, if it's value is provided. (default None ) |
- Note
- This is useful so that multiple parts of code can co-operatively take lines from the file
Definition at line 372 of file trfUtils.py.
372 def lineByLine(filename, strip=True, removeTimestamp=True, substepName=None):
374 encargs = {
'encoding' :
'utf8'}
375 f =
open(filename,
'r', **encargs)
378 if substepName
and isinstance(substepName, str):
379 line = line.lstrip(substepName)
381 line = line.lstrip(
'0123456789:-, ')
384 yield line, linecounter
◆ listChildren()
def python.trfUtils.listChildren |
( |
|
psTree = None , |
|
|
|
parent = os.getpid() , |
|
|
|
listOrphans = False |
|
) |
| |
Find all the children of a particular PID (calls itself recursively to descend into each leaf)
- Note
- The list of child PIDs is reversed, so the grandchildren are listed before the children, etc. so signaling left to right is correct
- Parameters
-
- Returns
children
List of child PIDs Take a psTree dictionary and list all children
Definition at line 109 of file trfUtils.py.
109 def listChildren(psTree = None, parent = os.getpid(), listOrphans =
False):
110 '''Take a psTree dictionary and list all children'''
114 msg.debug(
"List children of %d (%s)", parent, psTree.get(parent, []))
117 children.extend(psTree[parent])
118 for child
in psTree[parent]:
◆ pickledDump()
def python.trfUtils.pickledDump |
( |
|
argdict | ) |
|
Dump a list of arguments to the pickle file given in the 'dumpPickle' argument.
- Note
- This is a copy of the JSONDump function, but should in fact be deprecated soon so no point in merging the common parts! TODO: Deprecate me!
Definition at line 598 of file trfUtils.py.
599 if 'dumpPickle' not in argdict:
603 theArgumentDictionary = {}
604 for k, v
in argdict.items():
605 if k ==
'dumpPickle':
607 if isinstance(v, argument):
608 theArgumentDictionary[k] = getattr(v,
"dumpvalue", v.value)
610 theArgumentDictionary[k] = v
611 with open(argdict[
'dumpPickle'],
'wb')
as pickleFile:
612 import pickle
as pickle
613 pickle.dump(theArgumentDictionary, pickleFile)
◆ prettyXML()
def python.trfUtils.prettyXML |
( |
|
element, |
|
|
|
indent = ' ' , |
|
|
|
poolFileCatalogFormat = False |
|
) |
| |
XML pretty print an ElementTree.ELement object.
- Parameters
-
element | ElementTree.ELement object to print |
indent | Indent parameter for minidom toprettyxml method |
poolFileCatalogFormat | Whether to reformat the XML as a classic POOLFILECATALOG document |
- Returns
- String with the pretty printed XML version
- Note
- This is rather a convoluted way to get the correct DOCTYPE set and there's probably a better way to do it, but as this is a deprecated way of delivering metadata upstream it's not worth improving at this stage.
Definition at line 397 of file trfUtils.py.
397 def prettyXML(element, indent = ' ', poolFileCatalogFormat = False):
400 xmlstring = ElementTree.tostring(element,
'utf-8')
402 metadataDoc = minidom.parseString(xmlstring)
405 msg.warning(
'Error parsing ElementTree string - will try removing hex literals ({0!r})'.
format(xmlstring))
406 xmlstring = xmlstring.replace(
'\x00',
'')
407 metadataDoc = minidom.parseString(xmlstring)
410 if poolFileCatalogFormat
is False:
411 return metadataDoc.toprettyxml(indent=indent, encoding=
'UTF-8')
415 imp = minidom.DOMImplementation()
416 doctype = imp.createDocumentType(qualifiedName=
'POOLFILECATALOG', publicId=
'', systemId=
'InMemory')
417 doc = imp.createDocument(
None,
'POOLFILECATALOG', doctype)
421 refel = doc.documentElement
422 for child
in metadataDoc.childNodes:
423 if child.nodeType==child.ELEMENT_NODE:
424 doc.replaceChild(doc.importNode(child,
True), doc.documentElement)
426 elif child.nodeType!=child.DOCUMENT_TYPE_NODE:
427 doc.insertBefore(doc.importNode(child,
True), refel)
429 return doc.toprettyxml(indent=indent, encoding=
'UTF-8')
◆ printHR()
def python.trfUtils.printHR |
( |
|
the_object | ) |
|
print in a human-readable way the items of a given object
This function prints in a human-readable way the items of a given object.
- Parameters
-
Definition at line 660 of file trfUtils.py.
662 if isinstance(the_object, dict):
663 for key, value
in sorted(the_object.items()):
664 print(
u'{key}: {value}'.
format(key = key, value = value))
666 elif isinstance(the_object, list)
or isinstance(the_object, tuple):
667 for element
in the_object:
◆ releaseIsOlderThan()
def python.trfUtils.releaseIsOlderThan |
( |
|
major, |
|
|
|
minor = None |
|
) |
| |
Test (to the best of our knowledge) if the current release is older than a major, minor version number.
There's no unambiguous reference to the release that encompasses all of the development builds (dev, devval, migs), but almost everything can be determined from AtlasVersion
and AtlasBaseDir
. If neither of those contain version information then we assume a development build that is new by definition (so we return False
)
- Parameters
-
major | Major release number |
minor | Minor release number (if not specified, will not be matched against) |
- Returns
- Boolean if current release is found to be older
Definition at line 261 of file trfUtils.py.
262 if 'AtlasVersion' not in os.environ
or 'AtlasBaseDir' not in os.environ:
263 msg.warning(
"Could not find 'AtlasVersion' and 'AtlasBaseDir' in the environment - no release match possible")
267 relRegExp = re.compile(
r'(?P<major>\d+)\.(?P<minor>\d+)\.(?P<other>.*)')
268 relMatch = re.match(relRegExp, os.environ[
'AtlasVersion'])
271 leafDir = path.basename(os.environ[
'AtlasBaseDir'])
272 relMatch = re.match(relRegExp, leafDir)
274 msg.info(
'No identifiable numbered release found from AtlasVersion or AtlasBaseDir - assuming dev/devval/mig')
277 relmajor =
int(relMatch.group(
'major'))
278 relminor =
int(relMatch.group(
'minor'))
279 msg.info(
'Detected release major {0}, minor {1} (.{2}) from environment'.
format(relmajor, relminor, relMatch.group(
'other')))
288 if minor
is None or relminor >= minor:
292 except Exception
as e:
293 msg.warning(
'Exception thrown when attempting to detect athena version ({0}). No release check possible'.
format(e))
◆ reportEventsPassedSimFilter()
def python.trfUtils.reportEventsPassedSimFilter |
( |
|
log | ) |
|
summarize events passed the ISF_SimEventFilter @detail this function sums up all events passed the ISF_SimEventFilter out of all total events.
All this inforamation is extracted from log.ReSim
Definition at line 1716 of file trfUtils.py.
1722 regExp = re.compile(
r'ISF_SimEventFi[lter|...]+\s.*INFO.*accepted\s*(?P<events>[0-9]*)\s*out of\s*(?P<total>[0-9]*).*')
1725 except IOError
as e:
1726 msg.warning(
'Failed to open transform logfile {0}: {1:s}'.
format(log, e))
1731 for line, lineCounter
in myGen:
1732 m = regExp.match(line)
1734 passed_events +=
int(m.group(
'events'))
1735 total_events +=
int(m.group(
'total'))
1736 resimevents = passed_events
1738 if resimevents
is not None:
1739 msg.info(
"Summary of events passed the ISF_SimEventFilter: {0} events of total {1}".
format(passed_events, total_events) )
1741 msg.warning(
"Returning null value for the resimevents. No line matched with the regExp for extracting events passed the ISF_SimEventFilter")
◆ setupDBRelease()
def python.trfUtils.setupDBRelease |
( |
|
setup | ) |
|
Run a DBRelease setup.
- Parameters
-
setup | DMRelease setup script location (absolute or relative path) |
- Returns
- : None
Definition at line 543 of file trfUtils.py.
545 dbdir=path.abspath(path.dirname(setup))
546 msg.debug(
'Will add {0} to sys.path to load DBRelease setup module'.
format(dbdir))
549 sys.path.insert(0, dbdir)
550 from setup
import Setup
554 msg.debug(
'DBRelease setup module was initialised successfully')
555 except ImportError
as e:
556 errMsg =
'Import error while trying to load DB Setup module: {0}'.
format(e)
558 raise trfExceptions.TransformSetupException(trfExit.nameToCode(
'TRF_DBRELEASE_PROBLEM'), errMsg)
559 except Exception
as e:
560 errMsg =
'Unexpected error while trying to load DB Setup module: {0}'.
format(e)
562 raise trfExceptions.TransformSetupException(trfExit.nameToCode(
'TRF_DBRELEASE_PROBLEM'), errMsg)
◆ shQuoteStrings()
def python.trfUtils.shQuoteStrings |
( |
|
strArray = sys.argv | ) |
|
Quote a string array so that it can be echoed back on the command line in a cut 'n' paste safe way.
- Parameters
-
strArray | Array of strings to quote |
Technique is to first quote any pre-existing single quotes, then single quote all of the array elements so that the shell sees them as a single argument
Definition at line 361 of file trfUtils.py.
362 return [
"'" + qstring.replace(
"'",
"\\'") +
"'" for qstring
in strArray ]
◆ uniqueIdentifier()
def python.trfUtils.uniqueIdentifier |
( |
| ) |
|
return a URL-safe, base 64-encoded pseudorandom UUID
This function returns a URL-safe, base 64-encoded pseudorandom Universally Unique IDentifier (UUID).
- Returns
- string of URL-safe, base 64-encoded pseudorandom UUID
Definition at line 678 of file trfUtils.py.
679 return str(base64.urlsafe_b64encode(uuid.uuid4().bytes).strip(
"="))
◆ units()
def python.trfUtils.units |
( |
|
quantity = None , |
|
|
|
unitSingular = "unit" , |
|
|
|
unitPlural = "units" |
|
) |
| |
return either singular or plural units as appropriate for a given quantity
This function returns either singular or plural units as appropriate for a given quantity. So, a quantity of 1 would cause the return of singular units and a quantity of 2 would cause the return of plural units.
- Parameters
-
quantity | the numerical quantity |
unitSingular | the string for singular units |
unitSingular | the string for plural units |
- Returns
- string of singular or plural units
Definition at line 691 of file trfUtils.py.
693 unitSingular = "unit",
◆ unpackDBRelease()
def python.trfUtils.unpackDBRelease |
( |
|
tarball, |
|
|
|
dbversion = None |
|
) |
| |
Ensure that the DBRelease tarball has been unpacked.
Extract the dbversion number and look for an unpacked directory. If found then this release is already setup. If not then try to unpack the tarball.
- Parameters
-
tarball | The tarball file |
dbversion | The version number (if not given the look at the tarball name to get it) |
- Exceptions
-
- Returns
- Two element tuple: (
True
if release was unpacked or False
if release was already unpacked, dbsetup path)
Definition at line 520 of file trfUtils.py.
521 if dbversion
is None:
522 dbdMatch = re.match(
r'DBRelease-([\d\.]+)\.tar\.gz', path.basename(tarball))
524 raise trfExceptions.TransformSetupException(trfExit.nameToCode(
'TRF_DBRELEASE_PROBLEM'),
525 'Could not find a valid version in the DBRelease tarball: {0}'.
format(tarball))
526 dbversion = dbdMatch.group(1)
527 dbsetup = path.abspath(path.join(
"DBRelease", dbversion,
"setup.py"))
528 if os.access(dbsetup, os.R_OK):
529 msg.debug(
'DBRelease {0} is already unpacked, found {1}'.
format(tarball, dbsetup))
530 return False, dbsetup
532 msg.debug(
'Will attempt to unpack DBRelease {0}'.
format(tarball))
534 msg.info(
'DBRelease {0} was unpacked'.
format(tarball))
535 if not os.access(dbsetup, os.R_OK):
536 raise trfExceptions.TransformSetupException(trfExit.nameToCode(
'TRF_DBRELEASE_PROBLEM'),
537 'DBRelease setup file {0} was not readable, even after unpacking {1}'.
format(dbsetup, tarball))
◆ unpackTarFile()
def python.trfUtils.unpackTarFile |
( |
|
filename, |
|
|
|
directory = "." |
|
) |
| |
Unpack a given tarfile.
- Parameters
-
filename | Tar file to unpck |
directory | Directory target for the unpacking |
Definition at line 501 of file trfUtils.py.
503 tar = tarfile.open(filename)
504 tar.extractall(path=directory)
506 except Exception
as e:
507 errMsg =
'Error encountered while unpacking {0} to {1}: {2}'.
format(filename, directory, e)
509 raise trfExceptions.TransformSetupException(trfExit.nameToCode(
'TRF_SETUP'), errMsg)
◆ ValgrindCommand()
def python.trfUtils.ValgrindCommand |
( |
|
defaultOptions = True , |
|
|
|
extraOptionsList = None , |
|
|
|
AthenaSerialisedConfigurationFile = "athenaConf.pkl" , |
|
|
|
returnFormat = "string" |
|
) |
| |
Definition at line 1576 of file trfUtils.py.
1577 defaultOptions = True,
1578 extraOptionsList = None,
1579 AthenaSerialisedConfigurationFile = "athenaConf.pkl",
1580 returnFormat = "string"
1586 suppressionFilesAndCorrespondingPathEnvironmentVariables = {
1587 "etc/valgrind-root.supp":
"ROOTSYS",
1588 "Gaudi.supp":
"DATAPATH",
1589 "oracleDB.supp":
"DATAPATH",
1590 "valgrindRTT.supp":
"DATAPATH",
1591 "root.supp":
"DATAPATH"
1593 optionsList = [
"valgrind"]
1596 optionsList.append(
"--num-callers=30")
1597 optionsList.append(
"--tool=memcheck")
1598 optionsList.append(
"--leak-check=full")
1599 optionsList.append(
"--smc-check=all")
1601 if extraOptionsList:
1602 for option
in extraOptionsList:
1603 optionsList.append(option)
1605 for suppressionFile, pathEnvironmentVariable
in suppressionFilesAndCorrespondingPathEnvironmentVariables.items():
1606 suppFile =
findFile(os.environ[pathEnvironmentVariable], suppressionFile)
1608 optionsList.append(
"--suppressions=" + suppFile)
1610 msg.warning(
"Bad path to suppression file: {sfile}, {path} not defined".
format(
1611 sfile = suppressionFile, path = pathEnvironmentVariable)
1613 optionsList.append(
"$(which python)")
1614 optionsList.append(
"$(which athena.py)")
1615 optionsList.append(AthenaSerialisedConfigurationFile)
1617 if returnFormat
is None or returnFormat ==
"string":
1618 return(
" ".
join(optionsList))
1619 elif returnFormat ==
"list":
1623 "error: invalid Valgrind command format request (requested " +
1624 "format: {format}; valid formats: string, list)".
format(
1625 format = returnFormat
◆ VTuneCommand()
def python.trfUtils.VTuneCommand |
( |
|
defaultOptions = True , |
|
|
|
extraOptionsList = None , |
|
|
|
AthenaSerialisedConfigurationFile = "athenaConf.pkl" , |
|
|
|
returnFormat = "string" |
|
) |
| |
return VTune command @detail This function returns a VTune command for use with Athena.
The command is returned as a string (by default) or a list, as requested using the argument returnFormat. The function will return a default VTune command specification, unless the user suppress them through an option. To append additional options to the command specification the argument extraOptionsList is used. This causes the list of extra specified command options to be appended to the command specification, which will contain the default options unless these are suppressed. The Athena serialised configuration file is specified using the argument AthenaSerialisedConfigurationFile.
- Returns
- command as string
Definition at line 1642 of file trfUtils.py.
1643 defaultOptions = True,
1644 extraOptionsList = None,
1645 AthenaSerialisedConfigurationFile = "athenaConf.pkl",
1646 returnFormat = "string"
1652 optionsList = [
"vtune"]
1655 optionsList.append(
"-run-pass-thru=--no-altstack")
1656 optionsList.append(
"-mrte-mode=native")
1658 isCollectSpecified=
False
1659 if extraOptionsList:
1660 for option
in extraOptionsList:
1661 optionsList.append(option)
1662 if option.startswith(
"-collect="):
1663 isCollectSpecified=
True
1664 if not isCollectSpecified:
1665 optionsList.append(
"-collect=hotspots")
1666 optionsList.append(
"-- $(which python)")
1667 optionsList.append(
"$(which athena.py)")
1668 optionsList.append(AthenaSerialisedConfigurationFile)
1670 if returnFormat
is None or returnFormat ==
"string":
1671 return(
" ".
join(optionsList))
1672 elif returnFormat ==
"list":
1676 "error: invalid VTune command format request (requested " +
1677 "format: {format}; valid formats: string, list)".
format(
1678 format = returnFormat
◆ msg
std::string replace(std::string s, const std::string &s2, const std::string &s3)
def bind_port(host, port)
def printHR(the_object)
print in a human-readable way the items of a given object
def pickledDump(argdict)
Dump a list of arguments to the pickle file given in the 'dumpPickle' argument.
def lineByLine(filename, strip=True, removeTimestamp=True, substepName=None)
Generator to return lines and line count from a file.
def getAncestry(listMyOrphans=False)
List all processes and parents and form a dictionary where the parent key lists all child PIDs.
def resetTrfSignalHandlers()
Restore signal handlers to the default ones.
def prettyXML(element, indent=' ', poolFileCatalogFormat=False)
XML pretty print an ElementTree.ELement object.
def calcCpuTime(start, stop)
def VTuneCommand(defaultOptions=True, extraOptionsList=None, AthenaSerialisedConfigurationFile="athenaConf.pkl", returnFormat="string")
return VTune command @detail This function returns a VTune command for use with Athena.
def cmpMetadata(metadata1, metadata2, guidCheck='valid')
Compare metadata for files, but taking into account that GUID can vary.
def ValgrindCommand(defaultOptions=True, extraOptionsList=None, AthenaSerialisedConfigurationFile="athenaConf.pkl", returnFormat="string")
def reportEventsPassedSimFilter(log)
summarize events passed the ISF_SimEventFilter @detail this function sums up all events passed the IS...
void reduce(HepMC::GenEvent *ge, std::vector< HepMC::GenParticlePtr > toremove)
Remove unwanted particles from the event, collapsing the graph structure consistently.
def isodate()
Return isoformated 'now' string.
def cliToKey(option)
Convert a command line option to the dictionary key that will be used by argparse.
def call(args, bufsize=0, executable=None, stdin=None, preexec_fn=None, close_fds=False, shell=False, cwd=None, env=None, universal_newlines=False, startupinfo=None, creationflags=0, message="", logger=msg, loglevel=None, timeout=None, retry=2, timefactor=1.5, sleeptime=10)
def setupDBRelease(setup)
Run a DBRelease setup.
def asetupReleaseIsOlderThan(asetup_string, major, minor=None)
Test (to the best of our knowledge) if the asetup release is older than a major, minor version number...
def units(quantity=None, unitSingular="unit", unitPlural="units")
return either singular or plural units as appropriate for a given quantity
std::string repr(PyObject *o)
returns the string representation of a python object equivalent of calling repr(o) in python
def convertToStr(in_string)
Recursively convert unicode to str, useful when we have just loaded something from json (TODO: make t...
def uniqueIdentifier()
return a URL-safe, base 64-encoded pseudorandom UUID
std::vector< typename T::value_type > sorted(T begin, T end)
Helper function to create a sorted vector from an unsorted one.
constexpr std::enable_if_t< is_bitmask_v< E >, E & > set(E &lhs, E rhs)
Convenience function to set bits in a class enum bitmask.
void print(char *figname, TCanvas *c1)
std::string join(const std::vector< std::string > &v, const char c=',')
def releaseIsOlderThan(major, minor=None)
Test (to the best of our knowledge) if the current release is older than a major, minor version numbe...
def initialise_processes()
initisation procedure for processes of process pool
def calcWallTime(start, stop)
def findFile(pathvar, fname)
Find a named file along a colon separated PATH type variable.
def cvmfsDBReleaseCheck(dbrelease)
Validate a DBRelease exists on cvmfs and return the path to the setup script.
def JSONDump(argdict)
Dump a list of arguments to the JSON file given in the 'dumpJSON' argument.
def shQuoteStrings(strArray=sys.argv)
Quote a string array so that it can be echoed back on the command line in a cut 'n' paste safe way.
def forceToAlphaNum(string)
Strip a string down to alpha-numeric characters only.
def unpackDBRelease(tarball, dbversion=None)
Ensure that the DBRelease tarball has been unpacked.
def asetupReport()
Return a string with a report of the current athena setup.
def listChildren(psTree=None, parent=os.getpid(), listOrphans=False)
Find all the children of a particular PID (calls itself recursively to descend into each leaf)
def unpackTarFile(filename, directory=".")
Unpack a given tarfile.
def infanticide(childPIDs=None, sleepTime=3, message=True, listOrphans=False)
Kill all PIDs.