10 from wizard import util
16 Parse the contents of an environment variable as a boolean.
17 This recognizes more values as ``False`` than :func:`bool` would.
28 except (ValueError, TypeError):
29 if val == "No" or val == "no" or val == "false" or val == "False":
33 def makeLogger(options, numeric_args):
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
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)
49 logger.setLevel(logging.DEBUG)
51 stderr.setLevel(logging.WARNING)
53 stderr.setLevel(logging.INFO)
55 file.setLevel(logging.INFO)
56 def our_excepthook(type, value, tb):
57 logging.error("".join(traceback.format_exception(type,value,tb)))
59 sys.excepthook = our_excepthook
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"""
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
75 if type(value) is not bool:
76 args.append(str(value))
79 def security_check_homedir(location):
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
86 uid = util.get_dir_uid(location)
87 real = os.path.realpath(location)
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)
94 logging.error("Security check failed, could not look up"
95 "owner of %s (uid %d)" % (location, uid))
99 def calculate_log_name(log_dir, i, dir):
101 Calculates a log entry given a log directory, numeric identifier, and
102 directory under operation.
104 return os.path.join(log_dir, "%04d" % i + dir.replace('/', '-') + ".log")
106 def open_logs(log_dir, log_names=('warnings', 'errors')):
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)``.
115 The log directory is chmod'ed 777 after creation, to enable
116 de-priviledged processes to create files.
118 # must not be on AFS, since subprocesses won't be
119 # able to write to the logfiles do the to the AFS patch.
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)
130 return (open(os.path.join(os.path.join(log_dir, "%s.log" % x)), "a") for x in log_names)
132 class NullLogHandler(logging.Handler):
133 """Log handler that doesn't do anything"""
134 def emit(self, record):
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
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."""
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"""
172 option_parser.add_option(self.store[key])
174 class Error(wizard.Error):
175 """Base error class for all command errors"""