]> scripts.mit.edu Git - wizard.git/blob - wizard/command/__init__.py
More documentation improvements.
[wizard.git] / wizard / command / __init__.py
1 import logging
2 import traceback
3 import os
4 import sys
5 import optparse
6 import errno
7 import pwd
8 import shutil
9 import cStringIO
10
11 import wizard
12 from wizard import util
13
14 logging_setup = False
15
16 def boolish(val):
17     """
18     Parse the contents of an environment variable as a boolean.
19     This recognizes more values as ``False`` than :func:`bool` would.
20
21         >>> boolish("0")
22         False
23         >>> boolish("no")
24         False
25         >>> boolish("1")
26         True
27     """
28     try:
29         return bool(int(val))
30     except (ValueError, TypeError):
31         if val == "No" or val == "no" or val == "false" or val == "False":
32             return False
33         return bool(val)
34
35 def setup_logger(options, numeric_args):
36     global logging_setup
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:
44         logger.addHandler(stderr)
45     else:
46         logger.addHandler(NullLogHandler()) # prevent default
47     if options.log_file:
48         setup_file_logger(options.log_file, options.debug)
49     if options.debug:
50         logger.setLevel(logging.DEBUG)
51     else:
52         stderr.setLevel(logging.WARNING)
53         if options.verbose:
54             stderr.setLevel(logging.INFO)
55     logging_setup = True
56     return logger
57
58 def setup_file_logger(log_file, debug):
59     logger = logging.getLogger()
60     file = logging.FileHandler(log_file)
61     logformatter = logging.Formatter("%(asctime)s %(levelname)s: %(message)s", "%Y-%m-%d %H:%M")
62     file.setFormatter(logformatter)
63     logger.addHandler(file)
64     if not debug:
65         file.setLevel(logging.INFO)
66     return file
67
68 def make_base_args(options, **grab):
69     """Takes parsed options, and breaks them back into a command
70     line string that we can pass into a subcommand"""
71     args = []
72     grab["debug"]   = "--debug"
73     grab["verbose"] = "--verbose"
74     grab["quiet"]   = "--quiet"
75     #grab["log_db"] = "--log-db"
76     for k,flag in grab.items():
77         value = getattr(options, k)
78         if not value: continue
79         args.append(flag)
80         if type(value) is not bool:
81             args.append(str(value))
82     return args
83
84 def security_check_homedir(location):
85     """
86     Performs a check against a directory to determine if current
87     directory's owner has a home directory that is a parent directory.
88     This protects against malicious mountpoints, and is roughly equivalent
89     to the suexec checks.
90     """
91     try:
92         uid = util.get_dir_uid(location)
93         real = os.path.realpath(location)
94         if not real.startswith(pwd.getpwuid(uid).pw_dir + "/"):
95             logging.error("Security check failed, owner of deployment and "
96                     "owner of home directory mismatch for %s" % location)
97             return False
98     except KeyError:
99         logging.error("Security check failed, could not look up "
100                 "owner of %s (uid %d)" % (location, uid))
101         return False
102     except OSError as e:
103         logging.error("OSError: %s" % str(e))
104         return False
105     return True
106
107 def calculate_log_name(log_dir, i):
108     """
109     Calculates a log entry given a numeric identifier, and
110     directory under operation.
111     """
112     return os.path.join(log_dir, "%04d.log" % i)
113
114 def create_logdir(log_dir):
115     """
116     Creates a log directory and chmods it 777 to enable de-priviledged
117     processes to create files.
118     """
119     try:
120         os.mkdir(log_dir)
121     except OSError as e:
122         if e.errno != errno.EEXIST:
123             raise
124         #if create_subdirs:
125         #    log_dir = os.path.join(log_dir, str(int(time.time())))
126         #    os.mkdir(log_dir) # if fails, be fatal
127         #    # XXX: update last symlink
128     os.chmod(log_dir, 0o777)
129
130 class Report(object):
131     #: Set of indices that should be skipped
132     skip = None
133     #: Dict of append names to counts.  You should manually increment these as necessary
134     fails = None
135     #: Names of the files objects
136     names = None
137     def __init__(self, names, fobjs, skip, fails):
138         self.skip = skip
139         self.names = names
140         self.fails = fails
141         for name, fobj in zip(names, fobjs):
142             setattr(self, name, fobj)
143     def flush(self):
144         for n in self.names:
145             getattr(self, n).flush()
146
147 def report_files(log_dir, names):
148     return [os.path.join(os.path.join(log_dir, "%s.txt" % x)) for x in names]
149
150 def read_reports(log_dir, names):
151     """
152     Reads a number of reports files.  The return value is a :class:`Report`
153     object with attributes that are open file objects that correspond to ``names``.
154     """
155     return Report(names, [(os.path.exists(f) and open(f, "r") or cStringIO.StringIO()) for f in report_files(log_dir, names)], set(), {})
156
157 def open_reports(log_dir, names=('warnings', 'errors'), redo=False, append_names=()):
158     """
159     Returns a :class:`Report` object configured appropriately for the
160     parameters passed.  This object has attributes names + append_names which
161     contain file objects opened as "w".  ``names`` report files are cleared unconditionally
162     when they are opened (i.e. are not preserved from run to run.)  ``append_names``
163     report files are not cleared unless ``redo`` is True, and persist over
164     runs: assuming the convention that [0001] is the index of the deployment,
165     the ``skip`` attribute on the returned report object contains indexes that
166     should be skipped.
167     """
168     skip = set()
169     fails = {}
170     if not redo:
171         rr = read_reports(log_dir, append_names)
172         def build_set(skip, fails, name, fobj):
173             lines = fobj.read().strip().splitlines()
174             skip |= set(int(l[1:5]) for l in lines)
175             fails[name] = len(lines)
176             fobj.close()
177         for name in append_names:
178             build_set(skip, fails, name, getattr(rr, name))
179     else:
180         names += append_names
181         for name in append_names:
182             fails[name] = 0
183         append_names = ()
184     files = report_files(log_dir, names)
185     append_files = report_files(log_dir, append_names)
186     # backup old reports
187     old_reports = os.path.join(log_dir, "old-reports")
188     rundir = os.path.join(old_reports, "run")
189     if not os.path.exists(old_reports):
190         os.mkdir(old_reports)
191     else:
192         util.safe_unlink(rundir)
193     for f in files:
194         if os.path.exists(f):
195             os.rename(f, rundir)
196     for f in append_files:
197         if os.path.exists(f):
198             shutil.copy(f, rundir)
199     return Report(names + append_names, [open(f, "w") for f in files] + [open(f, "a") for f in append_files], skip, fails)
200
201 class NullLogHandler(logging.Handler):
202     """Log handler that doesn't do anything"""
203     def emit(self, record):
204         pass
205
206 class WizardOptionParser(optparse.OptionParser):
207     """Configures some default user-level options"""
208     store_help = False
209     def __init__(self, *args, **kwargs):
210         kwargs["add_help_option"] = False
211         if "store_help" in kwargs:
212             self.store_help = kwargs["store_help"]
213             del kwargs["store_help"]
214         optparse.OptionParser.__init__(self, *args, **kwargs)
215     def parse_all(self, *args, **kwargs):
216         if self.store_help:
217             self.add_option("-h", "--help", action="store_true", default=False, dest="help", help=optparse.SUPPRESS_HELP)
218         else:
219             self.add_option("-h", "--help", action="help", help=optparse.SUPPRESS_HELP)
220         group = optparse.OptionGroup(self, "Common Options")
221         group.add_option("-v", "--verbose", dest="verbose", action="store_true",
222                 default=boolish(os.getenv("WIZARD_VERBOSE")), help="Turns on verbose output.  Envvar is WIZARD_VERBOSE")
223         group.add_option("--debug", dest="debug", action="store_true",
224                 default=boolish(os.getenv("WIZARD_DEBUG")), help="Turns on debugging output.  Envvar is WIZARD_DEBUG")
225         group.add_option("-q", "--quiet", dest="quiet", action="store_true",
226                 default=boolish(os.getenv("WIZARD_QUIET")), help="Turns off output to stdout. Envvar is WIZARD_QUIET")
227         group.add_option("--log-file", dest="log_file", metavar="FILE",
228                 default=None, help="Logs verbose output to file")
229         self.add_option_group(group)
230         options, numeric_args = self.parse_args(*args, **kwargs)
231         setup_logger(options, numeric_args)
232         # we're going to process the global --log-dir/--seen dependency here
233         if hasattr(options, "seen") and hasattr(options, "log_dir"):
234             if not options.seen and options.log_dir:
235                 options.seen = os.path.join(options.log_dir, "seen.txt")
236         return options, numeric_args
237
238 class OptionBaton(object):
239     """Command classes may define options that they sub-commands may
240     use.  Since wizard --global-command subcommand is not a supported
241     mode of operation, these options have to be passed down the command
242     chain until a option parser is ready to take it; this baton is
243     what is passed down."""
244     def __init__(self):
245         self.store = {}
246     def add(self, *args, **kwargs):
247         key = kwargs["dest"] # require this to be set
248         self.store[key] = optparse.make_option(*args, **kwargs)
249     def push(self, option_parser, *args):
250         """Hands off parameters to option parser"""
251         for key in args:
252             option_parser.add_option(self.store[key])
253
254 class Error(wizard.Error):
255     """Base error class for all command errors"""
256     pass