CMS 3D CMS Logo

Functions
tools Namespace Reference

Functions

def check_proxy ()
 
def compute_product_string (product_string)
 
def create_single_iov_db (inputs, run_number, output_db)
 
def get_iovs (db, tag)
 
def get_process_object (cfg)
 
def get_tags (global_tag, records)
 
def getDatasetStr (datasetpath)
 
def getTerminalSize ()
 
def haddLocal (localdir, result_file, extension='root')
 
def interrupt (signum, frame)
 
def listFilesLocal (paths, extension='.root')
 
def loadCmsProcess (psetPath)
 
def loadCmsProcessFile (psetName)
 
def make_unique_runranges (ali_producer)
 
def prependPaths (process, seqname)
 
def remove_existing_object (path)
 
def replace_factors (product_string, name, value)
 
def replaceTemplate (template, opts)
 
def run_checked (cmd, suppress_stderr=False)
 
def stdinWait (text, default, time, timeoutDisplay=None, kwargs)
 

Function Documentation

def tools.check_proxy ( )
Check if GRID proxy has been initialized.

Definition at line 219 of file tools.py.

220  """Check if GRID proxy has been initialized."""
221 
222  try:
223  with open(os.devnull, "w") as dump:
224  subprocess.check_call(["voms-proxy-info", "--exists"],
225  stdout = dump, stderr = dump)
226  except subprocess.CalledProcessError:
227  return False
228  return True
229 
230 
def check_proxy()
Definition: tools.py:219
def tools.compute_product_string (   product_string)
Takes `product_string` and returns the product of the factors as string.

Arguments:
- `product_string`: string containing product ('<factor>*<factor>*...')

Definition at line 208 of file tools.py.

References objects.autophobj.float, and str.

208 def compute_product_string(product_string):
209  """Takes `product_string` and returns the product of the factors as string.
210 
211  Arguments:
212  - `product_string`: string containing product ('<factor>*<factor>*...')
213  """
214 
215  factors = [float(f) for f in product_string.split("*")]
216  return str(reduce(lambda x,y: x*y, factors))
217 
218 
#define str(s)
def compute_product_string(product_string)
Definition: tools.py:208
def tools.create_single_iov_db (   inputs,
  run_number,
  output_db 
)
Create an sqlite file with single-IOV tags for alignment payloads.

Arguments:
- `inputs`: dictionary with input needed for payload extraction
- `run_number`: run for which the IOVs are selected
- `output_db`: name of the output sqlite file

Definition at line 13 of file tools.py.

References join(), remove_existing_object(), run_checked(), and str.

13 def create_single_iov_db(inputs, run_number, output_db):
14  """Create an sqlite file with single-IOV tags for alignment payloads.
15 
16  Arguments:
17  - `inputs`: dictionary with input needed for payload extraction
18  - `run_number`: run for which the IOVs are selected
19  - `output_db`: name of the output sqlite file
20  """
21 
22  # find the IOV containing `run_number`
23  for record,tag in six.iteritems(inputs):
24  run_is_covered = False
25  for iov in reversed(tag["iovs"]):
26  if iov <= run_number:
27  tag["since"] = str(iov)
28  run_is_covered = True
29  break
30  if not run_is_covered:
31  msg = ("Run number {0:d} is not covered in '{1:s}' ({2:s}) from"
32  " '{3:s}'.".format(run_number, tag["tag"], record,
33  global_tag))
34  print msg
35  print "Aborting..."
36  sys.exit(1)
37 
38  result = {}
39  remove_existing_object(output_db)
40 
41  for record,tag in six.iteritems(inputs):
42  result[record] = {"connect": "sqlite_file:"+output_db,
43  "tag": "_".join([tag["tag"], tag["since"]])}
44 
45  if tag["connect"] == "pro":
46  source_connect = "frontier://FrontierProd/CMS_CONDITIONS"
47  elif tag["connect"] == "dev":
48  source_connect = "frontier://FrontierPrep/CMS_CONDITIONS"
49  else:
50  source_connect = tag["connect"]
51 
52  cmd = ("conddb_import",
53  "-f", source_connect,
54  "-c", result[record]["connect"],
55  "-i", tag["tag"],
56  "-t", result[record]["tag"],
57  "-b", str(run_number),
58  "-e", str(run_number))
59  run_checked(cmd)
60  if len(inputs) > 0:
61  run_checked(["sqlite3", output_db, "update iov set since=1"])
62 
63  return result
64 
65 
def remove_existing_object(path)
Definition: tools.py:231
def create_single_iov_db(inputs, run_number, output_db)
Definition: tools.py:13
def run_checked(cmd, suppress_stderr=False)
Definition: tools.py:66
static std::string join(char **cmd)
Definition: RemoteFile.cc:18
#define str(s)
def tools.get_iovs (   db,
  tag 
)
Retrieve the list of IOVs from `db` for `tag`.

Arguments:
- `db`: database connection string
- `tag`: tag of database record

Definition at line 166 of file tools.py.

References Vispa.Plugins.EdmBrowser.EdmDataAccessor.all(), ALCARECOTkAlBeamHalo_cff.filter, createfilelist.int, and python.rootplot.root2matplotlib.replace().

166 def get_iovs(db, tag):
167  """Retrieve the list of IOVs from `db` for `tag`.
168 
169  Arguments:
170  - `db`: database connection string
171  - `tag`: tag of database record
172  """
173 
174  db = db.replace("sqlite_file:", "").replace("sqlite:", "")
175  db = db.replace("frontier://FrontierProd/CMS_CONDITIONS", "pro")
176  db = db.replace("frontier://FrontierPrep/CMS_CONDITIONS", "dev")
177 
178  con = conddb.connect(url = conddb.make_url(db))
179  session = con.session()
180  IOV = session.get_dbtype(conddb.IOV)
181 
182  iovs = set(session.query(IOV.since).filter(IOV.tag_name == tag).all())
183  if len(iovs) == 0:
184  print "No IOVs found for tag '"+tag+"' in database '"+db+"'."
185  sys.exit(1)
186 
187  session.close()
188 
189  return sorted([int(item[0]) for item in iovs])
190 
191 
def replace(string, replacements)
def get_iovs(db, tag)
Definition: tools.py:166
def tools.get_process_object (   cfg)
Returns cms.Process object defined in `cfg`.

Arguments:
- `cfg`: path to CMSSW config file

Definition at line 86 of file tools.py.

87  """Returns cms.Process object defined in `cfg`.
88 
89  Arguments:
90  - `cfg`: path to CMSSW config file
91  """
92 
93  sys.path.append(os.path.dirname(cfg)) # add location to python path
94  cache_stdout = sys.stdout
95  sys.stdout = open(os.devnull, "w") # suppress unwanted output
96  try:
97  __configuration = \
98  importlib.import_module(os.path.splitext(os.path.basename(cfg))[0])
99  except Exception as e:
100  print "Problem detected in configuration file '{0}'.".format(cfg)
101  raise e
102  sys.stdout = cache_stdout
103  sys.path.pop() # clean up python path again
104  try:
105  os.remove(cfg+"c") # try to remove temporary .pyc file
106  except OSError as e:
107  if e.args == (2, "No such file or directory"): pass
108  else: raise
109 
110  return __configuration.process
111 
112 
def get_process_object(cfg)
Definition: tools.py:86
def tools.get_tags (   global_tag,
  records 
)
Get tags for `records` contained in `global_tag`.

Arguments:
- `global_tag`: global tag of interest
- `records`: database records of interest

Definition at line 131 of file tools.py.

References Vispa.Plugins.EdmBrowser.EdmDataAccessor.all(), and ALCARECOTkAlBeamHalo_cff.filter.

131 def get_tags(global_tag, records):
132  """Get tags for `records` contained in `global_tag`.
133 
134  Arguments:
135  - `global_tag`: global tag of interest
136  - `records`: database records of interest
137  """
138 
139  if len(records) == 0: return {} # avoid useless DB query
140 
141  # check for auto GT
142  if global_tag.startswith("auto:"):
143  import Configuration.AlCa.autoCond as AC
144  try:
145  global_tag = AC.autoCond[global_tag.split("auto:")[-1]]
146  except KeyError:
147  print "Unsupported auto GT:", global_tag
148  sys.exit(1)
149 
150  # setting up the DB session
151  con = conddb.connect(url = conddb.make_url())
152  session = con.session()
153  GlobalTagMap = session.get_dbtype(conddb.GlobalTagMap)
154 
155  # query tag names for records of interest contained in `global_tag`
156  tags = session.query(GlobalTagMap.record, GlobalTagMap.tag_name).\
157  filter(GlobalTagMap.global_tag_name == global_tag,
158  GlobalTagMap.record.in_(records)).all()
159 
160  # closing the DB session
161  session.close()
162 
163  return {item[0]: {"tag": item[1], "connect": "pro"} for item in tags}
164 
165 
def get_tags(global_tag, records)
Definition: tools.py:131
def tools.getDatasetStr (   datasetpath)

Definition at line 19 of file tools.py.

19 def getDatasetStr(datasetpath):
20  datasetstr = datasetpath
21  datasetstr.strip()
22  if datasetstr[0] == '/': datasetstr = datasetstr[1:]
23  datasetstr = datasetstr.replace('/','_')
24 
25  return datasetstr
26 
def getDatasetStr(datasetpath)
Definition: tools.py:19
def tools.getTerminalSize ( )

Definition at line 95 of file tools.py.

References createfilelist.int.

Referenced by CrabHelper.CrabHelper.check_crabtask().

96  #taken from http://stackoverflow.com/a/566752
97  # returns width, size of terminal
98  env = os.environ
99  def ioctl_GWINSZ(fd):
100  try:
101  import fcntl, termios, struct, os
102  cr = struct.unpack('hh', fcntl.ioctl(fd, termios.TIOCGWINSZ,
103  '1234'))
104  except:
105  return
106  return cr
107  cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2)
108  if not cr:
109  try:
110  fd = os.open(os.ctermid(), os.O_RDONLY)
111  cr = ioctl_GWINSZ(fd)
112  os.close(fd)
113  except:
114  pass
115  if not cr:
116  cr = (env.get('LINES', 25), env.get('COLUMNS', 80))
117 
118  ### Use get(key[, default]) instead of a try/catch
119  #try:
120  # cr = (env['LINES'], env['COLUMNS'])
121  #except:
122  # cr = (25, 80)
123  return int(cr[1]), int(cr[0])
124 
def getTerminalSize()
Definition: tools.py:95
def tools.haddLocal (   localdir,
  result_file,
  extension = 'root' 
)

Definition at line 40 of file tools.py.

References listFilesLocal().

Referenced by DTWorkflow.DTWorkflow.prepare_common_write().

40 def haddLocal(localdir,result_file,extension = 'root'):
41  if not os.path.exists( localdir ):
42  raise ValueError("localdir for hadd operation does not exist" )
43 
44  files = listFilesLocal([localdir],extension)
45  process = subprocess.Popen( ['hadd','-f', result_file] + files,
46  stdout=subprocess.PIPE,
47  stderr=subprocess.STDOUT)
48  stdout = process.communicate()[0]
49  return process.returncode
50 
def haddLocal(localdir, result_file, extension='root')
Definition: tools.py:40
def listFilesLocal(paths, extension='.root')
Definition: tools.py:27
def tools.interrupt (   signum,
  frame 
)

Definition at line 92 of file tools.py.

92 def interrupt(signum, frame):
93  raise Exception("")
94 
def interrupt(signum, frame)
Definition: tools.py:92
def tools.listFilesLocal (   paths,
  extension = '.root' 
)

Definition at line 27 of file tools.py.

Referenced by haddLocal().

27 def listFilesLocal(paths, extension = '.root'):
28  file_paths = []
29  for path in paths:
30  if not os.path.exists( path ):
31  log.error( "Specified input path '%s' does not exist!" % path )
32  continue
33  if path.endswith( extension ):
34  file_paths.append( path )
35  for root, dirnames, filenames in os.walk( path ):
36  for filename in fnmatch.filter( filenames, '*' + extension ):
37  file_paths.append( os.path.join( root, filename ) )
38  return file_paths
39 
def listFilesLocal(paths, extension='.root')
Definition: tools.py:27
def tools.loadCmsProcess (   psetPath)

Definition at line 55 of file tools.py.

Referenced by DTTtrigWorkflow.DTttrigWorkflow.prepare_residuals_correction(), DTTtrigWorkflow.DTttrigWorkflow.prepare_residuals_submit(), DTVdriftWorkflow.DTvdriftWorkflow.prepare_segment_write(), DTTtrigWorkflow.DTttrigWorkflow.prepare_timeboxes_correction(), DTTtrigWorkflow.DTttrigWorkflow.prepare_validation_submit(), and DTTtrigWorkflow.DTttrigWorkflow.prepare_validation_write().

55 def loadCmsProcess(psetPath):
56  module = __import__(psetPath)
57  process = sys.modules[psetPath].process
58 
59  import copy
60  #FIXME: clone process
61  #processNew = copy.deepcopy(process)
62  processNew = copy.copy(process)
63  return processNew
64 
def loadCmsProcess(psetPath)
Definition: tools.py:55
def tools.loadCmsProcessFile (   psetName)

Definition at line 51 of file tools.py.

51 def loadCmsProcessFile(psetName):
52  pset = imp.load_source("psetmodule",psetName)
53  return pset.process
54 
def loadCmsProcessFile(psetName)
Definition: tools.py:51
def tools.make_unique_runranges (   ali_producer)
Derive unique run ranges from AlignmentProducer PSet.

Arguments:
- `ali_producer`: cms.PSet containing AlignmentProducer configuration

Definition at line 113 of file tools.py.

References createfilelist.int.

113 def make_unique_runranges(ali_producer):
114  """Derive unique run ranges from AlignmentProducer PSet.
115 
116  Arguments:
117  - `ali_producer`: cms.PSet containing AlignmentProducer configuration
118  """
119 
120  if (hasattr(ali_producer, "RunRangeSelection") and
121  len(ali_producer.RunRangeSelection) > 0):
122  iovs = set([int(iov)
123  for sel in ali_producer.RunRangeSelection
124  for iov in sel.RunRanges])
125  if len(iovs) == 0: return [1] # single IOV starting from run 1
126  return sorted(iovs)
127  else:
128  return [1] # single IOV starting from run 1
129 
130 
def make_unique_runranges(ali_producer)
Definition: tools.py:113
def tools.prependPaths (   process,
  seqname 
)

Definition at line 65 of file tools.py.

Referenced by DTWorkflow.DTWorkflow.add_preselection(), and DTWorkflow.DTWorkflow.add_raw_option().

65 def prependPaths(process,seqname):
66  for path in process.paths:
67  getattr(process,path)._seq = getattr(process,seqname)*getattr(process,path)._seq
68 
def prependPaths(process, seqname)
Definition: tools.py:65
def tools.remove_existing_object (   path)
Tries to remove file or directory located at `path`. If the user
has no delete permissions, the object is moved to a backup
file. If this fails it tries 5 times in total and then asks to
perform a cleanup by a user with delete permissions.

Arguments:
- `name`: name of the object to be (re)moved

Definition at line 231 of file tools.py.

Referenced by create_single_iov_db().

232  """
233  Tries to remove file or directory located at `path`. If the user
234  has no delete permissions, the object is moved to a backup
235  file. If this fails it tries 5 times in total and then asks to
236  perform a cleanup by a user with delete permissions.
237 
238  Arguments:
239  - `name`: name of the object to be (re)moved
240  """
241 
242  if os.path.exists(path):
243  remove_method = shutil.rmtree if os.path.isdir(path) else os.remove
244  move_method = shutil.move if os.path.isdir(path) else os.rename
245  try:
246  remove_method(path)
247  except OSError as e:
248  if e.args != (13, "Permission denied"): raise
249  backup_path = path.rstrip("/")+"~"
250  for _ in xrange(5):
251  try:
252  if os.path.exists(backup_path): remove_method(backup_path)
253  move_method(path, backup_path)
254  break
255  except OSError as e:
256  if e.args != (13, "Permission denied"): raise
257  backup_path += "~"
258  if os.path.exists(path):
259  msg = ("Cannot remove '{}' due to missing 'delete' ".format(path)
260  +"permissions and the limit of 5 backups is reached. Please "
261  "ask a user with 'delete' permissions to clean up.")
262  print msg
263  sys.exit(1)
264 
def remove_existing_object(path)
Definition: tools.py:231
def tools.replace_factors (   product_string,
  name,
  value 
)
Takes a `product_string` and replaces all factors with `name` by `value`.

Arguments:
- `product_string`: input string containing a product
- `name`: name of the factor
- `value`: value of the factor

Definition at line 192 of file tools.py.

References str.

192 def replace_factors(product_string, name, value):
193  """Takes a `product_string` and replaces all factors with `name` by `value`.
194 
195  Arguments:
196  - `product_string`: input string containing a product
197  - `name`: name of the factor
198  - `value`: value of the factor
199  """
200 
201  value = str(value) # ensure it's a string
202  return re.sub(r"^"+name+r"$", value, # single factor
203  re.sub(r"[*]"+name+r"$", r"*"+value, # rhs
204  re.sub(r"^"+name+r"[*]", value+r"*", # lhs
205  re.sub(r"[*]"+name+r"[*]", r"*"+value+r"*",
206  product_string))))
207 
def replace_factors(product_string, name, value)
Definition: tools.py:192
#define str(s)
def tools.replaceTemplate (   template,
  opts 
)

Definition at line 9 of file tools.py.

References str.

9 def replaceTemplate(template,**opts):
10  result = open(template).read()
11  for item in opts:
12  old = '@@%s@@'%item
13  new = str(opts[item])
14  print "Replacing",old,"to",new
15  result = result.replace(old,new)
16 
17  return result
18 
def replaceTemplate(template, opts)
Definition: tools.py:9
#define str(s)
def tools.run_checked (   cmd,
  suppress_stderr = False 
)
Run `cmd` and exit in case of failures.

Arguments:
- `cmd`: list containing the strings of the command
- `suppress_stderr`: suppress output from stderr

Definition at line 66 of file tools.py.

References join().

Referenced by create_single_iov_db().

66 def run_checked(cmd, suppress_stderr = False):
67  """Run `cmd` and exit in case of failures.
68 
69  Arguments:
70  - `cmd`: list containing the strings of the command
71  - `suppress_stderr`: suppress output from stderr
72  """
73 
74  try:
75  with open(os.devnull, "w") as devnull:
76  if suppress_stderr:
77  subprocess.check_call(cmd, stdout = devnull, stderr = devnull)
78  else:
79  subprocess.check_call(cmd, stdout = devnull)
80  except subprocess.CalledProcessError as e:
81  print "Problem in running the following command:"
82  print " ".join(e.cmd)
83  sys.exit(1)
84 
85 
def run_checked(cmd, suppress_stderr=False)
Definition: tools.py:66
static std::string join(char **cmd)
Definition: RemoteFile.cc:18
def tools.stdinWait (   text,
  default,
  time,
  timeoutDisplay = None,
  kwargs 
)

Definition at line 69 of file tools.py.

Referenced by CrabHelper.CrabHelper.check_crabtask().

69 def stdinWait(text, default, time, timeoutDisplay = None, **kwargs):
70  # taken and adjusted from http://stackoverflow.com/a/25860968
71  signal.signal(signal.SIGALRM, interrupt)
72  signal.alarm(time) # sets timeout
73  global timeout
74  try:
75  inp = raw_input(text)
76  signal.alarm(0)
77  timeout = False
78  except (KeyboardInterrupt):
79  printInterrupt = kwargs.get("printInterrupt", True)
80  if printInterrupt:
81  print "Keyboard interrupt"
82  timeout = True # Do this so you don't mistakenly get input when there is none
83  inp = default
84  except:
85  timeout = True
86  if not timeoutDisplay is None:
87  print timeoutDisplay
88  signal.alarm(0)
89  inp = default
90  return inp
91 
def stdinWait(text, default, time, timeoutDisplay=None, kwargs)
Definition: tools.py:69