pvl/args.py
author Tero Marttila <terom@paivola.fi>
Mon, 01 Apr 2013 03:11:43 +0300
changeset 7 95d06ed3c395
parent 1 ce931075b69e
child 9 5e9290c55d77
permissions -rw-r--r--
pvl.socket: move from pvl-irker
"""
    CLI argument handling; common stuff: logging
"""

import optparse
import logging

import pwd, grp, os, sys

import logging; log = logging.getLogger('pvl.args')

def parser (parser) :
    """
        Return an optparse.OptionGroup.
    """

    general = optparse.OptionGroup(parser, "General options")

    general.add_option('-q', '--quiet',     dest='loglevel', action='store_const', const=logging.ERROR, help="Less output")
    general.add_option('-v', '--verbose',   dest='loglevel', action='store_const', const=logging.INFO,  help="More output")
    general.add_option('-D', '--debug',     dest='loglevel', action='store_const', const=logging.DEBUG, help="Even more output")
    general.add_option('--log-file',                                                                    help="Log to file")
    general.add_option('--debug-module',    action='append', metavar='MODULE', 
            help="Enable logging for the given logger/module name")
    
    general.add_option('--uid',             help="Change uid")
    general.add_option('--gid',             help="Change gid")

    # defaults
    parser.set_defaults(
        logname             = parser.prog,
        loglevel            = logging.WARN,
        debug_module        = [],
    )
 
    return general

def options (**options) :
    """
        Synthensise options.
    """

    return optparse.Values(options)

def apply_setid (options, rootok=None) :
    """
        Drop privileges if running as root.

        XXX: this feature isn't very useful (import-time issues etc), but in certain cases (syslog-ng -> python),
        it's difficult to avoid this without some extra wrapper tool..?
    """

    # --uid -> pw
    if not options.uid :
        pw = None
    elif options.uid.isdigit() :
        pw = pwd.getpwuid(int(options.uid))
    else :
        pw = pwd.getpwnam(options.uid)

    # --gid -> gr
    if not options.gid and not pw :
        gr = None
    elif not options.gid :
        gr = grp.getgrgid(pw.pw_gid)
    elif options.gid.isdigit() :
        gr = grp.getgrgid(str(options.gid))
    else :
        gr = grp.getgrnam(options.gid)
    
    if gr :
        # XXX: secondary groups? seem to get cleared
        log.info("setgid: %s: %s", gr.gr_name, gr.gr_gid)
        os.setgid(gr.gr_gid)

    if pw :
        log.info("setuid: %s: %s", pw.pw_name, pw.pw_uid)
        os.setuid(pw.pw_uid)
    
    elif os.getuid() == 0 :
        if rootok :
            log.info("running as root")
        else :
            log.error("refusing to run as root, use --uid 0 to override")
            sys.exit(2)

def apply (options, logname=None, rootok=True) :
    """
        Apply the optparse options.
    """

    if logname :
        prefix = options.logname + ': '
    else :
        prefix = ''

    # configure
    logging.basicConfig(
        # XXX: log Class.__init__ as Class, not __init__?
        format      = prefix + '%(name)-20s: %(levelname)5s %(funcName)s: %(message)s',
        level       = options.loglevel,
        filename    = options.log_file,
    )

    # TODO: use --quiet for stdout output?
    options.quiet = options.loglevel > logging.WARN
    
    if options.uid or options.gid or not rootok :
        # set uid/gid
        apply_setid(options, rootok=rootok)

    # enable debugging for specific targets
    for logger in options.debug_module :
        logging.getLogger(logger).setLevel(logging.DEBUG)