CMS 3D CMS Logo

hippyaddtobaddatafiles.py
Go to the documentation of this file.
1 #!/usr/bin/env python3
2 
3 from __future__ import print_function
4 
5 import argparse, contextlib, os, re, shutil, subprocess, tempfile, time
6 
7 if __name__ == "__main__":
8  def abspath(path):
9  if not os.path.exists(path): raise ValueError(path+" does not exist")
10  return os.path.abspath(path)
11 
12  p = argparse.ArgumentParser()
13  p.add_argument("cfgfile", type=abspath)
14  p.add_argument("baddatafileslist", nargs="?", default=None)
15  args = p.parse_args()
16 
17 def runcfg(cfgfile, badfilelist):
18  try:
19  subprocess.check_output(["cmsRun", cfgfile], stderr=subprocess.STDOUT)
20  except subprocess.CalledProcessError as e:
21  if "FallbackFileOpenError" in e.output:
22  output = e.output.split("An exception of category 'FallbackFileOpenError' occurred while")[1]
23  filename = re.search("Failed to open the file '[^']*(/store/.*[.]root)", output).group(1)
24  with OneAtATime(badfilelist+".tmp", 2) as f:
25  with open(badfilelist) as f:
26  contents = set(f.read().split())
27  if filename in contents:
28  raise RuntimeError(filename+"\nis already in\n"+badfilelist+"\n\nExiting to avoid an infinite loop. Maybe you have this running on the same cfg file multiple times?")
29  contents.add(filename)
30  contents = sorted(contents)
31  with open(badfilelist, "w") as f:
32  f.write("\n".join(contents)+"\n")
33  print("found and added a bad file:\n"+filename)
34  else:
35  raise
36  return runcfg(cfgfile, badfilelist)
37  print("all files left are good")
38 
39 @contextlib.contextmanager
40 def cd(newdir):
41  """http://stackoverflow.com/a/24176022/5228524"""
42  prevdir = os.getcwd()
43  os.chdir(os.path.expanduser(newdir))
44  try:
45  yield
46  finally:
47  os.chdir(prevdir)
48 
49 def cdtemp(): return cd(tempfile.mkdtemp())
50 
52  def __init__(self, name, message=None):
53  self.filename = name
54  self.__message = message
55  self.pwd = os.getcwd()
56  self.fd = self.f = None
57  self.bool = False
58 
59  @property
60  def wouldbevalid(self):
61  if self: return True
62  with self:
63  return bool(self)
64 
65  def __open(self):
66  self.fd = os.open(self.filename, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
67 
68  def __enter__(self):
69  with cd(self.pwd):
70  try:
71  self.__open()
72  except OSError:
73  return None
74 
75  self.f = os.fdopen(self.fd, 'w')
76 
77  try:
78  if self.__message is not None:
79  self.f.write(self.__message+"\n")
80  except IOError:
81  pass
82  try:
83  self.f.close()
84  except IOError:
85  pass
86  self.bool = True
87  return True
88 
89  def __exit__(self, *args):
90  if self:
91  try:
92  with cd(self.pwd):
93  os.remove(self.filename)
94  except OSError:
95  pass #ignore it
96  self.fd = self.f = None
97  self.bool = False
98 
99  def __nonzero__(self):
100  return self.bool
101 
103  def __init__(self, name, delay, message=None, printmessage=None, task="doing this"):
104  super(OneAtATime, self).__init__(name, message=message)
105  self.delay = delay
106  if printmessage is None:
107  printmessage = "Another process is already {task}! Waiting {delay} seconds."
108  printmessage = printmessage.format(delay=delay, task=task)
109  self.__printmessage = printmessage
110 
111  def __enter__(self):
112  while True:
113  result = super(OneAtATime, self).__enter__()
114  if result:
115  return result
116  print(self.__printmessage)
117  time.sleep(self.delay)
118 
119 if __name__ == "__main__":
120  with cdtemp():
121  shutil.copy(args.cfgfile, ".")
122 
123  badfilelist = args.badfilelist
124  if badfilelist is None:
125  badfilelist = os.path.join(os.path.dirname(cfgfile, "../../../run/DataFiles/baddatafiles.txt"))
126 
127  runcfg(os.path.basename(args.cfgfile), args.badfilelist)
void print(TMatrixD &m, const char *label=nullptr, bool mathematicaFormat=false)
Definition: Utilities.cc:47
def runcfg(cfgfile, badfilelist)
static std::string join(char **cmd)
Definition: RemoteFile.cc:21
def __init__(self, name, delay, message=None, printmessage=None, task="doing this")