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