]> scripts.mit.edu Git - wizard.git/blob - wizard/command/__init__.py
62a561b4ae9366154efbee7f8c1d0f68abcfedd3
[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
9 import wizard
10 from wizard import util
11
12 logging_setup = False
13
14 def boolish(val):
15     """
16     Parse the contents of an environment variable as a boolean.
17     This recognizes more values as ``False`` than :func:`bool` would.
18
19         >>> boolish("0")
20         False
21         >>> boolish("no")
22         False
23         >>> boolish("1")
24         True
25     """
26     try:
27         return bool(int(val))
28     except (ValueError, TypeError):
29         if val == "No" or val == "no" or val == "false" or val == "False":
30             return False
31         return bool(val)
32
33 def makeLogger(options, numeric_args):
34     global logging_setup
35     if logging_setup: return logging.getLogger()
36     logger = logging.getLogger()
37     logger.handlers = [] # under certain cases, a spurious stream handler is set. We don't know why
38     logger.setLevel(logging.INFO)
39     stderr = logging.StreamHandler(sys.stderr)
40     stderr.setFormatter(logging.Formatter('%(levelname)s: %(message)s'))
41     if not options.quiet: logger.addHandler(stderr)
42     else: logger.addHandler(NullLogHandler()) # prevent default
43     if options.log_file:
44         file = logging.FileHandler(options.log_file)
45         logformatter = logging.Formatter("%(asctime)s %(levelname)s: %(message)s", "%H:%M:%S")
46         file.setFormatter(logformatter)
47         logger.addHandler(file)
48     if options.debug:
49         logger.setLevel(logging.DEBUG)
50     else:
51         stderr.setLevel(logging.WARNING)
52         if options.verbose:
53             stderr.setLevel(logging.INFO)
54         if options.log_file:
55             file.setLevel(logging.INFO)
56     def our_excepthook(type, value, tb):
57         logging.error("".join(traceback.format_exception(type,value,tb)))
58         sys.exit(1)
59     sys.excepthook = our_excepthook
60     logging_setup = True
61     return logger
62
63 def makeBaseArgs(options, **grab):
64     """Takes parsed options, and breaks them back into a command
65     line string that we can pass into a subcommand"""
66     args = []
67     grab["debug"]   = "--debug"
68     grab["verbose"] = "--verbose"
69     grab["quiet"]   = "--quiet"
70     #grab["log_db"] = "--log-db"
71     for k,flag in grab.items():
72         value = getattr(options, k)
73         if not value: continue
74         args.append(flag)
75         if type(value) is not bool:
76             args.append(str(value))
77     return args
78
79 def security_check_homedir(location):
80     """
81     Performs a check against a directory to determine if current
82     directory's owner has a home directory that is a parent directory.
83     This protects against malicious mountpoints, and is roughly equivalent
84     to the suexec checks.
85     """
86     uid = util.get_dir_uid(location)
87     real = os.path.realpath(location)
88     try:
89         if not real.startswith(pwd.getpwuid(uid).pw_dir + "/"):
90             logging.error("Security check failed, owner of deployment and"
91                     "owner of home directory mismatch for %s" % d.location)
92             return False
93     except KeyError:
94         logging.error("Security check failed, could not look up"
95                 "owner of %s (uid %d)" % (location, uid))
96         return False
97     return True
98
99 def calculate_log_name(log_dir, i, dir):
100     """
101     Calculates a log entry given a log directory, numeric identifier, and
102     directory under operation.
103     """
104     return os.path.join(log_dir, "%04d" % i + dir.replace('/', '-') + ".log")
105
106 def open_logs(log_dir, log_names=('warnings', 'errors')):
107     """
108     Opens a number of log files for auxiliary reporting.  You can override what
109     log files to generate using ``log_names``, which corresponds to the tuple
110     of log files you will receive, i.e. the default returns a tuple
111     ``(warnings.log file object, errors.log file object)``.
112
113     .. note::
114
115         The log directory is chmod'ed 777 after creation, to enable
116         de-priviledged processes to create files.
117     """
118     # must not be on AFS, since subprocesses won't be
119     # able to write to the logfiles do the to the AFS patch.
120     try:
121         os.mkdir(log_dir)
122     except OSError as e:
123         if e.errno != errno.EEXIST:
124             raise
125         #if create_subdirs:
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)
130     return (open(os.path.join(os.path.join(log_dir, "%s.log" % x)), "a") for x in log_names)
131
132 class NullLogHandler(logging.Handler):
133     """Log handler that doesn't do anything"""
134     def emit(self, record):
135         pass
136
137 class WizardOptionParser(optparse.OptionParser):
138     """Configures some default user-level options"""
139     def __init__(self, *args, **kwargs):
140         kwargs["add_help_option"] = False
141         optparse.OptionParser.__init__(self, *args, **kwargs)
142     def parse_all(self, argv):
143         self.add_option("-h", "--help", action="help", help=optparse.SUPPRESS_HELP)
144         group = optparse.OptionGroup(self, "Common Options")
145         group.add_option("-v", "--verbose", dest="verbose", action="store_true",
146                 default=boolish(os.getenv("WIZARD_VERBOSE")), help="Turns on verbose output.  Envvar is WIZARD_VERBOSE")
147         group.add_option("--debug", dest="debug", action="store_true",
148                 default=boolish(os.getenv("WIZARD_DEBUG")), help="Turns on debugging output.  Envvar is WIZARD_DEBUG")
149         group.add_option("-q", "--quiet", dest="quiet", action="store_true",
150                 default=boolish(os.getenv("WIZARD_QUIET")), help="Turns off output to stdout. Envvar is WIZARD_QUIET")
151         group.add_option("--log-file", dest="log_file", metavar="FILE",
152                 default=None, help="Logs verbose output to file")
153         self.add_option_group(group)
154         options, numeric_args = self.parse_args(argv)
155         makeLogger(options, numeric_args)
156         return options, numeric_args
157
158 class OptionBaton(object):
159     """Command classes may define options that they sub-commands may
160     use.  Since wizard --global-command subcommand is not a supported
161     mode of operation, these options have to be passed down the command
162     chain until a option parser is ready to take it; this baton is
163     what is passed down."""
164     def __init__(self):
165         self.store = {}
166     def add(self, *args, **kwargs):
167         key = kwargs["dest"] # require this to be set
168         self.store[key] = optparse.make_option(*args, **kwargs)
169     def push(self, option_parser, *args):
170         """Hands off parameters to option parser"""
171         for key in args:
172             option_parser.add_option(self.store[key])
173
174 class Error(wizard.Error):
175     """Base error class for all command errors"""
176     pass