summaryrefslogtreecommitdiffstats
path: root/src/lib/Bcfg2/Options.py
blob: 788f67aabc9c9ec6584b969309b99429f56e5c0e (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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
"""Option parsing library for utilities."""

import re
import os
import sys
import copy
import shlex
import getopt
import Bcfg2.Client.Tools
# Compatibility imports
from Bcfg2.Bcfg2Py3k import ConfigParser

def bool_cook(x):
    if x:
        return True
    else:
        return False

class OptionFailure(Exception):
    pass

DEFAULT_CONFIG_LOCATION = '/etc/bcfg2.conf' #/etc/bcfg2.conf
DEFAULT_INSTALL_PREFIX = '/usr' #/usr

class DefaultConfigParser(ConfigParser.ConfigParser):
    def get(self, section, option, **kwargs):
        """ convenience method for getting config items """
        default = None
        if 'default' in kwargs:
            default = kwargs['default']
            del kwargs['default']
        try:
            return ConfigParser.ConfigParser.get(self, section, option,
                                                 **kwargs)
        except (ConfigParser.NoSectionError, ConfigParser.NoOptionError):
            if default is not None:
                return default
            else:
                raise

    def getboolean(self, section, option, **kwargs):
        """ convenience method for getting boolean config items """
        default = None
        if 'default' in kwargs:
            default = kwargs['default']
            del kwargs['default']
        try:
            return ConfigParser.ConfigParser.getboolean(self, section,
                                                        option, **kwargs)
        except (ConfigParser.NoSectionError, ConfigParser.NoOptionError,
                ValueError):
            if default is not None:
                return default
            else:
                raise


class Option(object):
    def get_cooked_value(self, value):
        if self.boolean:
            return True
        if self.cook:
            return self.cook(value)
        else:
            return value

    def __init__(self, desc, default, cmd=False, odesc=False,
                 env=False, cf=False, cook=False, long_arg=False):
        self.desc = desc
        self.default = default
        self.cmd = cmd
        self.long = long_arg
        if not self.long:
            if cmd and (cmd[0] != '-' or len(cmd) != 2):
                raise OptionFailure("Poorly formed command %s" % cmd)
        else:
            if cmd and (not cmd.startswith('--')):
                raise OptionFailure("Poorly formed command %s" % cmd)
        self.odesc = odesc
        self.env = env
        self.cf = cf
        self.boolean = False
        if not odesc and not cook:
            self.boolean = True
        self.cook = cook

    def buildHelpMessage(self):
        msg = ''
        if self.cmd:
            if not self.long:
                msg = self.cmd.ljust(3)
            else:
                msg = self.cmd
            if self.odesc:
                if self.long:
                    msg = "%-28s" % ("%s=%s" % (self.cmd, self.odesc))
                else:
                    msg += '%-25s' % (self.odesc)
            else:
                msg += '%-25s' % ('')
            msg += "%s\n" % self.desc
        return msg

    def buildGetopt(self):
        gstr = ''
        if self.long:
            return gstr
        if self.cmd:
            gstr = self.cmd[1]
            if self.odesc:
                gstr += ':'
        return gstr

    def buildLongGetopt(self):
        if self.odesc:
            return self.cmd[2:]+'='
        else:
            return self.cmd[2:]

    def parse(self, opts, rawopts, configparser=None):
        if self.cmd and opts:
            # Processing getopted data
            optinfo = [opt[1] for opt in opts if opt[0] == self.cmd]
            if optinfo:
                if optinfo[0]:
                    self.value = self.get_cooked_value(optinfo[0])
                else:
                    self.value = True
                return
        if self.cmd and self.cmd in rawopts:
            data = rawopts[rawopts.index(self.cmd) + 1]
            self.value = self.get_cooked_value(data)
            return
        # No command line option found
        if self.env and self.env in os.environ:
            self.value = self.get_cooked_value(os.environ[self.env])
            return
        if self.cf and configparser:
            try:
                self.value = self.get_cooked_value(configparser.get(*self.cf))
                return
            except (ConfigParser.NoSectionError, ConfigParser.NoOptionError):
                pass
        # Default value not cooked
        self.value = self.default

class OptionSet(dict):
    def __init__(self, *args, **kwargs):
        dict.__init__(self, *args)
        self.hm = self.buildHelpMessage()
        if 'configfile' in kwargs:
            self.cfile = kwargs['configfile']
        else:
            self.cfile = DEFAULT_CONFIG_LOCATION
        self.cfp = DefaultConfigParser()
        if (len(self.cfp.read(self.cfile)) == 0 and
            ('quiet' not in kwargs or not kwargs['quiet'])):
            print("Warning! Unable to read specified configuration file: %s" %
                  self.cfile)

    def buildGetopt(self):
        return ''.join([opt.buildGetopt() for opt in list(self.values())])

    def buildLongGetopt(self):
        return [opt.buildLongGetopt() for opt in list(self.values())
                if opt.long]

    def buildHelpMessage(self):
        if hasattr(self, 'hm'):
            return self.hm
        hlist = []  # list of _non-empty_ help messages
        for opt in list(self.values()):
            hm = opt.buildHelpMessage()
            if hm != '':
                hlist.append(hm)
        return '     '.join(hlist)

    def helpExit(self, msg='', code=1):
        if msg:
            print(msg)
        print("Usage:\n     %s" % self.buildHelpMessage())
        raise SystemExit(code)

    def parse(self, argv, do_getopt=True):
        '''Parse options from command line.'''
        if do_getopt:
            try:
                opts, args = getopt.getopt(argv, self.buildGetopt(),
                                           self.buildLongGetopt())
            except getopt.GetoptError:
                err = sys.exc_info()[1]
                self.helpExit(err)
            if '-h' in argv:
                self.helpExit('', 0)
            self['args'] = args
        for key in list(self.keys()):
            if key == 'args':
                continue
            option = self[key]
            if do_getopt:
                option.parse(opts, [], configparser=self.cfp)
            else:
                option.parse([], argv, configparser=self.cfp)
            if hasattr(option, 'value'):
                val = option.value
                self[key] = val

def list_split(c_string):
    if c_string:
        return re.split("\s*,\s*", c_string)
    return []

def colon_split(c_string):
    if c_string:
        return c_string.split(':')
    return []

def get_bool(s):
    # these values copied from ConfigParser.RawConfigParser.getboolean
    # with the addition of True and False
    truelist = ["1", "yes", "True", "true", "on"]
    falselist = ["0", "no", "False", "false", "off"]
    if s in truelist:
        return True
    elif s in falselist:
        return False
    else:
        raise ValueError

# General options
CFILE = Option('Specify configuration file', DEFAULT_CONFIG_LOCATION, cmd='-C',
               odesc='<conffile>')
LOCKFILE = Option('Specify lockfile',
           "/var/lock/bcfg2.run",
           cf=('components', 'lockfile'),
           odesc='<Path to lockfile>')
HELP = Option('Print this usage message', False, cmd='-h')
DEBUG = Option("Enable debugging output", False, cmd='-d')
VERBOSE = Option("Enable verbose output", False, cmd='-v')
DAEMON = Option("Daemonize process, storing pid", False,
                cmd='-D', odesc="<pidfile>")
INSTALL_PREFIX = Option('Installation location', cf=('server', 'prefix'),
                        default=DEFAULT_INSTALL_PREFIX, odesc='</path>')
SENDMAIL_PATH = Option('Path to sendmail', cf=('reports', 'sendmailpath'),
                       default='/usr/lib/sendmail')
INTERACTIVE = Option('Run interactively, prompting the user for each change',
                     default=False,
                     cmd='-I', )
ENCODING = Option('Encoding of cfg files',
                  default='UTF-8',
                  cmd='-E',
                  odesc='<encoding>',
                  cf=('components', 'encoding'))
PARANOID_PATH = Option('Specify path for paranoid file backups',
                       default='/var/cache/bcfg2', cf=('paranoid', 'path'),
                       odesc='<paranoid backup path>')
PARANOID_MAX_COPIES = Option('Specify the number of paranoid copies you want',
                             default=1, cf=('paranoid', 'max_copies'),
                             odesc='<max paranoid copies>')
OMIT_LOCK_CHECK = Option('Omit lock check', default=False, cmd='-O')
CORE_PROFILE = Option('profile',
                      default=False, cmd='-p', )
FILES_ON_STDIN = Option('Operate on a list of files supplied on stdin',
                        cmd='--stdin', default=False, long_arg=True)
SCHEMA_PATH = Option('Path to XML Schema files', cmd='--schema',
                     odesc='<schema path>',
                     default="%s/share/bcfg2/schemas" % DEFAULT_INSTALL_PREFIX,
                     long_arg=True)
REQUIRE_SCHEMA = Option("Require property files to have matching schema files",
                        cmd="--require-schema", default=False, long_arg=True)

# Metadata options
MDATA_OWNER = Option('Default Path owner',
                     default='root', cf=('mdata', 'owner'),
                     odesc='owner permissions')
MDATA_GROUP = Option('Default Path group',
                     default='root', cf=('mdata', 'group'),
                     odesc='group permissions')
MDATA_IMPORTANT = Option('Default Path priority (importance)',
                     default='False', cf=('mdata', 'important'),
                     odesc='Important entries are installed first')
MDATA_PERMS = Option('Default Path permissions',
                     '644', cf=('mdata', 'perms'),
                     odesc='octal permissions')
MDATA_PARANOID = Option('Default Path paranoid setting',
                     'true', cf=('mdata', 'paranoid'),
                     odesc='Path paranoid setting')
MDATA_SENSITIVE = Option('Default Path sensitive setting',
                     'false', cf=('mdata', 'sensitive'),
                     odesc='Path sensitive setting')

# Server options
SERVER_REPOSITORY = Option('Server repository path', '/var/lib/bcfg2',
                           cf=('server', 'repository'), cmd='-Q',
                           odesc='<repository path>')
SERVER_PLUGINS = Option('Server plugin list', cf=('server', 'plugins'),
                        # default server plugins
                        default=[
                                 'Bundler',
                                 'Cfg',
                                 'Metadata',
                                 'Pkgmgr',
                                 'Rules',
                                 'SSHbase',
                                ],
                        cook=list_split)
SERVER_MCONNECT = Option('Server Metadata Connector list', cook=list_split,
                         cf=('server', 'connectors'), default=['Probes'], )
SERVER_FILEMONITOR = Option('Server file monitor', cf=('server', 'filemonitor'),
                            default='default', odesc='File monitoring driver')
SERVER_LISTEN_ALL = Option('Listen on all interfaces',
                           cf=('server', 'listen_all'),
                           cmd='--listen-all',
                           default=False,
                           long_arg=True,
                           cook=get_bool,
                           odesc='True|False')
SERVER_LOCATION = Option('Server Location', cf=('components', 'bcfg2'),
                         default='https://localhost:6789', cmd='-S',
                         odesc='https://server:port')
SERVER_STATIC = Option('Server runs on static port', cf=('components', 'bcfg2'),
                       default=False, cook=bool_cook)
SERVER_KEY = Option('Path to SSL key', cf=('communication', 'key'),
                    default=False, cmd='--ssl-key', odesc='<ssl key>',
                    long_arg=True)
SERVER_CERT = Option('Path to SSL certificate', default='/etc/bcfg2.key',
                     cf=('communication', 'certificate'), odesc='<ssl cert>')
SERVER_CA = Option('Path to SSL CA Cert', default=None,
                   cf=('communication', 'ca'), odesc='<ca cert>')
SERVER_PASSWORD = Option('Communication Password', cmd='-x', odesc='<password>',
                         cf=('communication', 'password'), default=False)
SERVER_PROTOCOL = Option('Server Protocol', cf=('communication', 'procotol'),
                         default='xmlrpc/ssl')
# Client options
CLIENT_KEY = Option('Path to SSL key', cf=('communication', 'key'),
                    default=None, cmd="--ssl-key", odesc='<ssl key>',
                    long_arg=True)
CLIENT_CERT = Option('Path to SSL certificate', default=None, cmd="--ssl-cert",
                     cf=('communication', 'certificate'), odesc='<ssl cert>',
                     long_arg=True)
CLIENT_CA = Option('Path to SSL CA Cert', default=None, cmd="--ca-cert",
                   cf=('communication', 'ca'), odesc='<ca cert>',
                   long_arg=True)
CLIENT_SCNS = Option('List of server commonNames', default=None, cmd="--ssl-cns",
                     cf=('communication', 'serverCommonNames'),
                     odesc='<commonName1:commonName2>', cook=list_split,
                     long_arg=True)
CLIENT_PROFILE = Option('Assert the given profile for the host',
                        default=False, cmd='-p', odesc="<profile>")
CLIENT_RETRIES = Option('The number of times to retry network communication',
                        default='3', cmd='-R', cf=('communication', 'retries'),
                        odesc="<retry count>")
CLIENT_DRYRUN = Option('Do not actually change the system',
                       default=False, cmd='-n', )
CLIENT_EXTRA_DISPLAY = Option('enable extra entry output',
                              default=False, cmd='-e', )
CLIENT_PARANOID = Option('Make automatic backups of config files',
                         default=False,
                         cmd='-P',
                         cook=get_bool,
                         cf=('client', 'paranoid'))
CLIENT_DRIVERS = Option('Specify tool driver set', cmd='-D',
                        cf=('client', 'drivers'),
                        odesc="<driver1,driver2>", cook=list_split,
                        default=Bcfg2.Client.Tools.default)
CLIENT_CACHE = Option('Store the configuration in a file',
                      default=False, cmd='-c', odesc="<cache path>")
CLIENT_REMOVE = Option('Force removal of additional configuration items',
                       default=False, cmd='-r', odesc="<entry type|all>")
CLIENT_BUNDLE = Option('Only configure the given bundle(s)', default=[],
                       cmd='-b', odesc='<bundle:bundle>', cook=colon_split)
CLIENT_BUNDLEQUICK = Option('only verify/configure the given bundle(s)', default=False,
                       cmd='-Q')
CLIENT_INDEP = Option('Only configure independent entries, ignore bundles', default=False,
                       cmd='-z')
CLIENT_KEVLAR = Option('Run in kevlar (bulletproof) mode', default=False,
                       cmd='-k', )
CLIENT_DLIST = Option('Run client in server decision list mode', default='none',
                      cf=('client', 'decision'),
                      cmd='-l', odesc='<whitelist|blacklist|none>')
CLIENT_FILE = Option('Configure from a file rather than querying the server',
                     default=False, cmd='-f', odesc='<specification path>')
CLIENT_QUICK = Option('Disable some checksum verification', default=False,
                      cmd='-q', )
CLIENT_USER = Option('The user to provide for authentication', default='root',
                     cmd='-u', cf=('communication', 'user'), odesc='<user>')
CLIENT_SERVICE_MODE = Option('Set client service mode', default='default',
                             cmd='-s', odesc='<default|disabled|build>')
CLIENT_TIMEOUT = Option('Set the client XML-RPC timeout', default=90,
                        cmd='-t', cf=('communication', 'timeout'),
                        odesc='<timeout>')

# bcfg2-test options
TEST_NOSEOPTS = Option('Options to pass to nosetests', default=[],
                       cmd='--nose-options', cf=('bcfg2_test', 'nose_options'),
                       odesc='<opts>', long_arg=True, cook=shlex.split)
TEST_IGNORE = Option('Ignore these entries if they fail to build.', default=[],
                     cmd='--ignore',
                     cf=('bcfg2_test', 'ignore_entries'), long_arg=True,
                     odesc='<Type>:<name>,<Type>:<name>', cook=list_split)

# APT client tool options
CLIENT_APT_TOOLS_INSTALL_PATH = Option('Apt tools install path',
                                       cf=('APT', 'install_path'),
                                       default='/usr')
CLIENT_APT_TOOLS_VAR_PATH = Option('Apt tools var path',
                                   cf=('APT', 'var_path'), default='/var')
CLIENT_SYSTEM_ETC_PATH = Option('System etc path', cf=('APT', 'etc_path'),
                         default='/etc')

# Logging options
LOGGING_FILE_PATH = Option('Set path of file log', default=None,
                           cmd='-o', odesc='<path>', cf=('logging', 'path'))

# Plugin-specific options
CFG_VALIDATION = Option('Run validation on Cfg files', default=True,
                        cf=('cfg', 'validation'), cmd='--cfg-validation',
                        long_arg=True, cook=get_bool)

class OptionParser(OptionSet):
    """
       OptionParser bootstraps option parsing,
       getting the value of the config file
    """
    def __init__(self, args):
        self.Bootstrap = OptionSet([('configfile', CFILE)], quiet=True)
        self.Bootstrap.parse(sys.argv[1:], do_getopt=False)
        OptionSet.__init__(self, args, configfile=self.Bootstrap['configfile'])
        self.optinfo = copy.copy(args)

    def HandleEvent(self, event):
        if 'configfile' not in self or not isinstance(self['configfile'], str):
            # we haven't parsed options yet, or CFILE wasn't included
            # in the options
            return
        if event.filename != self['configfile']:
            print("Got event for unknown file: %s" % event.filename)
            return
        if event.code2str() == 'deleted':
            return
        self.reparse()

    def reparse(self):
        for key, opt in self.optinfo.items():
            self[key] = opt
        if "args" not in self.optinfo:
            del self['args']
        self.parse(self.argv, self.do_getopt)

    def parse(self, argv, do_getopt=True):
        self.argv = argv
        self.do_getopt = do_getopt
        OptionSet.parse(self, self.argv, do_getopt=self.do_getopt)

    def add_option(self, name, opt):
        self[name] = opt
        self.optinfo[name] = opt

    def update(self, optdict):
        dict.update(self, optdict)
        self.optinfo.update(optdict)