summaryrefslogtreecommitdiffstats
path: root/src/sbin/bcfg2-lint
blob: 0e9a32e495e98f8dd25fca14d8743cd4c95bf302 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
#!/usr/bin/env python

"""This tool examines your Bcfg2 specifications for errors."""

import sys
import inspect
import logging
import Bcfg2.Logger
import Bcfg2.Options
import Bcfg2.Server.Core
import Bcfg2.Server.Lint
# Compatibility imports
from Bcfg2.Compat import ConfigParser

logger = logging.getLogger('bcfg2-lint')

def run_serverless_plugins(plugins, config=None, setup=None, errorhandler=None):
    logger.debug("Running serverless plugins")
    for plugin_name, plugin in list(plugins.items()):
        run_plugin(plugin, plugin_name, errorhandler=errorhandler,
                   setup=setup, config=config, files=files)

def run_server_plugins(plugins, config=None, setup=None, errorhandler=None):
    core = load_server(setup)
    logger.debug("Running server plugins")
    for plugin_name, plugin in list(plugins.items()):
        run_plugin(plugin, plugin_name, args=[core], errorhandler=errorhandler,
                   setup=setup, config=config, files=files)

def run_plugin(plugin, plugin_name, setup=None, errorhandler=None,
               args=None, config=None, files=None):
    logger.debug("  Running %s" % plugin_name)
    if args is None:
        args = []

    if errorhandler is None:
        errorhandler = get_errorhandler(config)

    if config is not None and config.has_section(plugin_name):
        arg = setup
        for key, val in config.items(plugin_name):
            arg[key] = val
        args.append(arg)
    else:
        args.append(setup)
        
    # older versions of python do not support mixing *-magic and
    # non-*-magic (e.g., "plugin(*args, files=files)", so we do this
    # all with *-magic
    kwargs = dict(files=files, errorhandler=errorhandler)
    
    return plugin(*args, **kwargs).Run()

def get_errorhandler(config):
    """ get a Bcfg2.Server.Lint.ErrorHandler object """
    if config.has_section("errors"):
        conf = dict(config.items("errors"))
    else:
        conf = None
    return Bcfg2.Server.Lint.ErrorHandler(config=conf)

def load_server(setup):
    """ load server """
    core = Bcfg2.Server.Core.BaseCore(setup)
    core.fam.handle_events_in_interval(4)
    return core

def load_plugin(module, obj_name=None):
    parts = module.split(".")
    if obj_name is None:
        obj_name = parts[-1]

    mod = __import__(module)
    for p in parts[1:]:
        mod = getattr(mod, p)
    return getattr(mod, obj_name)

if __name__ == '__main__':
    optinfo = dict(config=Bcfg2.Options.LINT_CONFIG,
                   showerrors=Bcfg2.Options.LINT_SHOW_ERRORS,
                   stdin=Bcfg2.Options.LINT_FILES_ON_STDIN,
                   schema=Bcfg2.Options.SCHEMA_PATH,
                   plugins=Bcfg2.Options.SERVER_PLUGINS)
    optinfo.update(Bcfg2.Options.CLI_COMMON_OPTIONS)
    optinfo.update(Bcfg2.Options.SERVER_COMMON_OPTIONS)
    setup = Bcfg2.Options.OptionParser(optinfo)
    setup.parse(sys.argv[1:])

    log_args = dict(to_syslog=setup['syslog'], to_console=logging.WARNING)
    if setup['verbose']:
        log_args['to_console'] = logging.DEBUG
    Bcfg2.Logger.setup_logging('bcfg2-info', **log_args)

    config = ConfigParser.SafeConfigParser()
    config.read(setup['configfile'])
    config.read(setup['config'])

    # get list of plugins to run
    if setup['args']:
        plugin_list = setup['args']
    elif "bcfg2-repo-validate" in sys.argv[0]:
        plugin_list = 'Duplicates,RequiredAttrs,Validate'.split(',')
    else:
        try:
            plugin_list = config.get('lint', 'plugins').split(',')
        except (ConfigParser.NoOptionError, ConfigParser.NoSectionError):
            plugin_list = Bcfg2.Server.Lint.__all__

    if setup['stdin']:
        files = [s.strip() for s in sys.stdin.readlines()]
    else:
        files = None

    allplugins = dict()
    for plugin in plugin_list:
        try:
            allplugins[plugin] = load_plugin("Bcfg2.Server.Lint." + plugin)
        except ImportError:
            try:
                allplugins[plugin] = \
                    load_plugin("Bcfg2.Server.Plugins." + plugin,
                                obj_name=plugin + "Lint")
            except (ImportError, AttributeError):
                 err = sys.exc_info()[1]
                 logger.error("Failed to load plugin %s: %s" % (plugin + "Lint",
                                                                err))
        except AttributeError:
            err = sys.exc_info()[1]
            logger.error("Failed to load plugin %s: %s" % (obj_name, err))
            
    serverplugins = dict()
    serverlessplugins = dict()
    for plugin_name, plugin in allplugins.items():
        if [c for c in inspect.getmro(plugin)
            if c == Bcfg2.Server.Lint.ServerPlugin]:
            serverplugins[plugin_name] = plugin
        else:
            serverlessplugins[plugin_name] = plugin

    errorhandler = get_errorhandler(config)

    if setup['showerrors']:
        for plugin in serverplugins.values() + serverlessplugins.values():
            errorhandler.RegisterErrors(getattr(plugin, 'Errors')())

        print("%-35s %-35s" % ("Error name", "Handler"))
        for err, handler in errorhandler._handlers.items():
            print("%-35s %-35s" % (err, handler.__name__))
        raise SystemExit(0)

    run_serverless_plugins(serverlessplugins,
                           errorhandler=errorhandler,
                           config=config, setup=setup)

    if serverplugins:
        if errorhandler.errors:
            # it would be swell if we could try to start the server
            # even if there were errors with the serverless plugins,
            # but since XML parsing errors occur in the FAM thread
            # (not in the core server thread), there's no way we can
            # start the server and try to catch exceptions --
            # bcfg2-lint isn't in the same stack as the exceptions.
            # so we're forced to assume that a serverless plugin error
            # will prevent the server from starting
            print("Serverless plugins encountered errors, skipping server "
                  "plugins")
        else:
            run_server_plugins(serverplugins, errorhandler=errorhandler,
                               config=config, setup=setup)

    if errorhandler.errors or errorhandler.warnings or setup['verbose']:
        print("%d errors" % errorhandler.errors)
        print("%d warnings" % errorhandler.warnings)

    if errorhandler.errors:
        raise SystemExit(2)
    elif errorhandler.warnings:
        raise SystemExit(3)