12 from wizard import util
18 Parse the contents of an environment variable as a boolean.
19 This recognizes more values as ``False`` than :func:`bool` would.
30 except (ValueError, TypeError):
31 if val == "No" or val == "no" or val == "false" or val == "False":
35 def makeLogger(options, numeric_args):
37 if logging_setup: return logging.getLogger()
38 logger = logging.getLogger()
39 logger.handlers = [] # under certain cases, a spurious stream handler is set. We don't know why
40 logger.setLevel(logging.INFO)
41 stderr = logging.StreamHandler(sys.stderr)
42 stderr.setFormatter(logging.Formatter('%(levelname)s: %(message)s'))
43 if not options.quiet: logger.addHandler(stderr)
44 else: logger.addHandler(NullLogHandler()) # prevent default
45 if options.log_file: addFileLogger(options.log_file, options.debug)
47 logger.setLevel(logging.DEBUG)
49 stderr.setLevel(logging.WARNING)
51 stderr.setLevel(logging.INFO)
52 def our_excepthook(type, value, tb):
53 logging.error("".join(traceback.format_exception(type,value,tb)))
55 sys.excepthook = our_excepthook
59 def addFileLogger(log_file, debug):
60 logger = logging.getLogger()
61 file = logging.FileHandler(log_file)
62 logformatter = logging.Formatter("%(asctime)s %(levelname)s: %(message)s", "%Y-%m-%d %H:%M")
63 file.setFormatter(logformatter)
64 logger.addHandler(file)
66 file.setLevel(logging.INFO)
69 def makeBaseArgs(options, **grab):
70 """Takes parsed options, and breaks them back into a command
71 line string that we can pass into a subcommand"""
73 grab["debug"] = "--debug"
74 grab["verbose"] = "--verbose"
75 grab["quiet"] = "--quiet"
76 #grab["log_db"] = "--log-db"
77 for k,flag in grab.items():
78 value = getattr(options, k)
79 if not value: continue
81 if type(value) is not bool:
82 args.append(str(value))
85 def security_check_homedir(location):
87 Performs a check against a directory to determine if current
88 directory's owner has a home directory that is a parent directory.
89 This protects against malicious mountpoints, and is roughly equivalent
93 uid = util.get_dir_uid(location)
94 real = os.path.realpath(location)
95 if not real.startswith(pwd.getpwuid(uid).pw_dir + "/"):
96 logging.error("Security check failed, owner of deployment and "
97 "owner of home directory mismatch for %s" % location)
100 logging.error("Security check failed, could not look up "
101 "owner of %s (uid %d)" % (location, uid))
104 logging.error("OSError: %s" % str(e))
108 def calculate_log_name(log_dir, i):
110 Calculates a log entry given a numeric identifier, and
111 directory under operation.
113 return os.path.join(log_dir, "%04d.log" % i)
115 def create_logdir(log_dir):
117 Creates a log directory and chmods it 777 to enable de-priviledged
118 processes to create files.
123 if e.errno != errno.EEXIST:
126 # log_dir = os.path.join(log_dir, str(int(time.time())))
127 # os.mkdir(log_dir) # if fails, be fatal
128 # # XXX: update last symlink
129 os.chmod(log_dir, 0o777)
131 class Report(object):
132 #: Set of indices that should be skipped
134 def __init__(self, names, fobjs, skip):
136 for name, fobj in zip(names, fobjs):
137 setattr(self, name, fobj)
139 def report_files(log_dir, names):
140 return [os.path.join(os.path.join(log_dir, "%s.txt" % x)) for x in names]
142 def read_reports(log_dir, names):
144 Reads a number of reports files. The return value is a :class:`Report`
145 object with attributes that are open file objects that correspond to ``names``.
147 return Report(names, [(os.path.exists(f) and open(f, "r") or cStringIO.StringIO()) for f in report_files(log_dir, names)], set())
149 def open_reports(log_dir, names=('warnings', 'errors'), redo=False, append_names=()):
151 Returns a :class:`Report` object configured appropriately for the
152 parameters passed. This object has attributes names + append_names which
153 contain file objects opened as "w". ``names`` report files are cleared unconditionally
154 when they are opened (i.e. are not preserved from run to run.) ``append_names``
155 report files are not cleared unless ``redo`` is True, and persist over
156 runs: assuming the convention that [0001] is the index of the deployment,
157 the ``skip`` attribute on the returned report object contains indexes that
162 rr = read_reports(log_dir, append_names)
163 def build_set(skip, fobj):
164 skip |= set(int(l[1:5]) for l in fobj.read().splitlines())
166 for name in append_names:
167 build_set(skip, getattr(rr, name))
169 names += append_names
171 files = report_files(log_dir, names)
172 append_files = report_files(log_dir, append_names)
174 old_reports = os.path.join(log_dir, "old-reports")
175 rundir = os.path.join(old_reports, "run")
176 if not os.path.exists(old_reports):
177 os.mkdir(old_reports)
179 util.safe_unlink(rundir)
181 if os.path.exists(f):
183 for f in append_files:
184 if os.path.exists(f):
185 shutil.copy(f, rundir)
186 return Report(names + append_names, [open(f, "w") for f in files] + [open(f, "a") for f in append_files], skip)
188 class NullLogHandler(logging.Handler):
189 """Log handler that doesn't do anything"""
190 def emit(self, record):
193 class WizardOptionParser(optparse.OptionParser):
194 """Configures some default user-level options"""
195 def __init__(self, *args, **kwargs):
196 kwargs["add_help_option"] = False
197 optparse.OptionParser.__init__(self, *args, **kwargs)
198 def parse_all(self, argv):
199 self.add_option("-h", "--help", action="help", help=optparse.SUPPRESS_HELP)
200 group = optparse.OptionGroup(self, "Common Options")
201 group.add_option("-v", "--verbose", dest="verbose", action="store_true",
202 default=boolish(os.getenv("WIZARD_VERBOSE")), help="Turns on verbose output. Envvar is WIZARD_VERBOSE")
203 group.add_option("--debug", dest="debug", action="store_true",
204 default=boolish(os.getenv("WIZARD_DEBUG")), help="Turns on debugging output. Envvar is WIZARD_DEBUG")
205 group.add_option("-q", "--quiet", dest="quiet", action="store_true",
206 default=boolish(os.getenv("WIZARD_QUIET")), help="Turns off output to stdout. Envvar is WIZARD_QUIET")
207 group.add_option("--log-file", dest="log_file", metavar="FILE",
208 default=None, help="Logs verbose output to file")
209 self.add_option_group(group)
210 options, numeric_args = self.parse_args(argv)
211 makeLogger(options, numeric_args)
212 # we're going to process the global --log-dir/--seen dependency here
213 if hasattr(options, "seen") and hasattr(options, "log_dir"):
214 if not options.seen and options.log_dir:
215 options.seen = os.path.join(options.log_dir, "seen.txt")
216 return options, numeric_args
218 class OptionBaton(object):
219 """Command classes may define options that they sub-commands may
220 use. Since wizard --global-command subcommand is not a supported
221 mode of operation, these options have to be passed down the command
222 chain until a option parser is ready to take it; this baton is
223 what is passed down."""
226 def add(self, *args, **kwargs):
227 key = kwargs["dest"] # require this to be set
228 self.store[key] = optparse.make_option(*args, **kwargs)
229 def push(self, option_parser, *args):
230 """Hands off parameters to option parser"""
232 option_parser.add_option(self.store[key])
234 class Error(wizard.Error):
235 """Base error class for all command errors"""