summaryrefslogtreecommitdiffstats
path: root/src/sbin/bcfg2-info
blob: 5303aa02b144b9740f9720654e3e8d21f3916334 (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
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
#!/usr/bin/env python
"""This tool loads the Bcfg2 core into an interactive debugger."""

import os
import sys
import cmd
import errno
import getopt
import fnmatch
import logging
import tempfile
import lxml.etree
import traceback
from code import InteractiveConsole

try:
    try:
        import cProfile as profile
    except:
        import profile
    import pstats
    have_profile = True
except:
    have_profile = False

import Bcfg2.Logger
import Bcfg2.Options
import Bcfg2.Server.Core
import Bcfg2.Server.Plugins.Metadata
import Bcfg2.Server.Plugin

try:
    import Bcfg2.Server.Plugins.SGenshi
    has_genshi = True
except ImportError:
    has_genshi = False

logger = logging.getLogger('bcfg2-info')
USAGE = """Commands:
build <hostname> <filename> - Build config for hostname, writing to filename
builddir <hostname> <dirname> - Build config for hostname, writing separate files to dirname
buildall <directory> [<hostnames*>] - Build configs for all clients in directory
buildallfile <directory> <filename> [<hostnames*>] - Build config file for all clients in directory
buildfile <filename> <hostname> - Build config file for hostname (not written to disk)
buildbundle <bundle> <hostname> - Render a templated bundle for hostname (not written to disk)
bundles - Print out group/bundle information
clients - Print out client/profile information
config - Print out the configuration of the Bcfg2 server
debug - Shell out to native python interpreter
event_debug - Display filesystem events as they are processed
groups - List groups
help - Print this list of available commands
mappings <type*> <name*> - Print generator mappings for optional type and name
packageresolve <hostname> <package> [<package>...] - Resolve the specified set of packages
packagesources <hostname> - Show package sources
profile <command> <args> - Profile a single bcfg2-info command
quit - Exit the bcfg2-info command line
showentries <hostname> <type> - Show abstract configuration entries for a given host
showclient <client1> <client2> - Show metadata for given hosts
update - Process pending file events"""

BUILDDIR_USAGE = """Usage: builddir [-f] <hostname> <output dir>

Generates a config for client <hostname> and writes the
individual configuration files out separately in a tree
under <output dir>.  The <output dir> directory must be
rooted under /tmp unless the -f argument is provided, in
which case it can be located anywhere.

NOTE: Currently only handles file entries and writes
all content with the default owner and permissions.  These
could be much more permissive than would be created by the
Bcfg2 client itself."""


class mockLog(object):
    def error(self, *args, **kwargs):
        pass

    def info(self, *args, **kwargs):
        pass

    def debug(self, *args, **kwargs):
        pass


class dummyError(Exception):
    """This is just a dummy."""
    pass


class FileNotBuilt(Exception):
    """Thrown when File entry contains no content."""
    def __init__(self, value):
        Exception.__init__(self)
        self.value = value
    def __str__(self):
        return repr(self.value)


def getClientList(hostglobs):
    """ given a host glob, get a list of clients that match it """
    # special cases to speed things up:
    if '*' in hostglobs:
        return list(self.metadata.clients.keys())
    has_wildcards = False
    for glob in hostglobs:
        # check if any wildcard characters are in the string
        if set('*?[]') & set(glob):
            has_wildcards = True
            break
    if not has_wildcards:
        return hostglobs

    rv = set()
    clist = set(self.metadata.clients.keys())
    for glob in hostglobs:
        for client in clist:
            if fnmatch.fnmatch(client, glob):
                rv.update(client)
        clist.difference_update(rv)
    return list(rv)

def printTabular(rows):
    """Print data in tabular format."""
    cmax = tuple([max([len(str(row[index])) for row in rows]) + 1 \
                    for index in range(len(rows[0]))])
    fstring = (" %%-%ss |" * len(cmax)) % cmax
    fstring = ('|'.join([" %%-%ss "] * len(cmax))) % cmax
    print(fstring % rows[0])
    print((sum(cmax) + (len(cmax) * 2) + (len(cmax) - 1)) * '=')
    for row in rows[1:]:
        print(fstring % row)

def displayTrace(trace, num=80, sort=('time', 'calls')):
    stats = pstats.Stats(trace)
    stats.sort_stats('cumulative', 'calls', 'time')
    stats.print_stats(200)

class infoCore(cmd.Cmd, Bcfg2.Server.Core.Core):
    """Main class for bcfg2-info."""
    def __init__(self, repo, plgs, passwd, encoding, event_debug,
                 filemonitor='default', setup=None):
        cmd.Cmd.__init__(self)
        try:
            Bcfg2.Server.Core.Core.__init__(self, repo, plgs, passwd,
                                            encoding, filemonitor=filemonitor,
                                            setup=setup)
            if event_debug:
                self.fam.debug = True
        except Bcfg2.Server.Core.CoreInitError:
            msg = sys.exc_info()[1]
            print("Core load failed because %s" % msg)
            raise SystemExit(1)
        self.prompt = '> '
        self.cont = True
        self.fam.handle_events_in_interval(4)

    def do_loop(self):
        """Looping."""
        self.cont = True
        while self.cont:
            try:
                self.cmdloop('Welcome to bcfg2-info\n'
                             'Type "help" for more information')
            except SystemExit:
                raise
            except Bcfg2.Server.Plugin.PluginExecutionError:
                continue
            except KeyboardInterrupt:
                print("Ctrl-C pressed exiting...")
                self.do_exit([])
            except dummyError:
                continue
            except:
                logger.error("Command failure", exc_info=1)

    def do_debug(self, args):
        """Debugging mode for more details."""
        try:
            opts, _ = getopt.getopt(args.split(), 'nf:')
        except:
            print("Usage: debug [-n] [-f <command list>]")
            return
        self.cont = False
        scriptmode = False
        interactive = True
        for opt in opts:
            if opt[0] == '-f':
                scriptmode = True
                spath = opt[1]
            elif opt[0] == '-n':
                interactive = False
        sh = InteractiveConsole(locals())
        if scriptmode:
            for command in [c.strip() for c in open(spath).readlines()]:
                if command:
                    sh.push(command)
        if interactive:
            print("Dropping to python interpreter; press ^D to resume")
            try:
                import IPython
                if hasattr(IPython, "Shell"):
                    shell = IPython.Shell.IPShell(argv=[], user_ns=locals())
                    shell.mainloop()
                elif hasattr(IPython, "embed"):
                    IPython.embed(user_ns=locals())
                else:
                    raise ImportError
            except ImportError:
                try:
                    import bpython.cli
                    bpython.cli.main(locals_=locals())
                except ImportError:
                    sh.interact()

    def do_quit(self, _):
        """
           Exit program.
           Usage: [quit|exit]
        """
        for plugin in list(self.plugins.values()):
            plugin.shutdown()
        os._exit(0)

    do_EOF = do_quit
    do_exit = do_quit

    def do_help(self, _):
        """Print out usage info."""
        print(USAGE)

    def do_update(self, _):
        """Process pending filesystem events."""
        self.fam.handle_events_in_interval(0.1)

    def do_build(self, args):
        """Build client configuration."""
        alist = args.split()
        path_force = False
        for arg in alist:
            if arg == '-f':
                alist.remove('-f')
                path_force = True
        if len(alist) == 2:
            client, ofile = alist
            if not ofile.startswith('/tmp') and not path_force:
                print("Refusing to write files outside of /tmp without -f option")
                return
            lxml.etree.ElementTree(self.BuildConfiguration(client)).write(ofile,
                                       encoding='UTF-8', xml_declaration=True,
                                       pretty_print=True)
        else:
            print('Usage: build [-f] <hostname> <output file>')

    def help_builddir(self):
        """Display help for builddir command."""
        print(BUILDDIR_USAGE)

    def do_builddir(self, args):
        """Build client configuration as separate files within a dir."""
        alist = args.split()
        path_force = False
        if '-f' in args:
            alist.remove('-f')
            path_force = True
        if len(alist) == 2:
            client, odir = alist
            if not odir.startswith('/tmp') and not path_force:
                print("Refusing to write files outside of /tmp without -f option")
                return
            client_config = self.BuildConfiguration(client)
            if client_config.tag == 'error':
                print("Building client configuration failed.")
                return

            for struct in client_config:
                for entry in struct:
                    if entry.tag == 'Path':
                        entry.set('name', odir + '/' + entry.get('name'))

            log = mockLog()
            import Bcfg2.Client.Tools.POSIX
            p = Bcfg2.Client.Tools.POSIX.POSIX(log, setup, client_config)
            states = dict()
            p.Inventory(states)
            p.Install(list(states.keys()), states)
        else:
            print('Error: Incorrect number of parameters.')
            self.help_builddir()

    def do_buildall(self, args):
        alist = args.split()
        if len(alist) < 1:
            print("Usage: buildall <directory> [<hostnames*>]")
            return

        destdir = alist[0]
        try:
            os.mkdir(destdir)
        except OSError:
            err = sys.exc_info()[1]
            if err.errno != 17:
                print("Could not create %s: %s" % (destdir, err))
        if len(alist) > 1:
            clients = getClientList(alist[1:])
        else:
            clients = list(self.metadata.clients.keys())
        for client in clients:
            self.do_build("%s %s" % (client, os.path.join(destdir,
                                                          client + ".xml")))

    def do_buildallfile(self, args):
        """Build a config file for all clients."""
        usage = 'Usage: buildallfile [--altsrc=<altsrc>] <directory> <filename> [<hostnames*>]'
        try:
            opts, args = getopt.gnu_getopt(args.split(), '', ['altsrc='])
        except:
            print(usage)
            return
        altsrc = None
        for opt in opts:
            if opt[0] == '--altsrc':
                altsrc = opt[1]
        if len(args) < 2:
            print(usage)
            return

        destdir = args[0]
        filename = args[1]
        try:
            os.mkdir(destdir)
        except OSError:
            err = sys.exc_info()[1]
            if err.errno != 17:
                print("Could not create %s: %s" % (destdir, err))
        if len(args) > 2:
            clients = getClientList(args[1:])
        else:
            clients = list(self.metadata.clients.keys())
        if altsrc:
            args = "--altsrc %s -f %%s %%s %%s" % altsrc
        else:
            args = "-f %s %s %s"
        for client in clients:
            self.do_buildfile(args % (os.path.join(destdir, client),
                                      filename, client))

    def do_buildfile(self, args):
        """Build a config file for client."""
        usage = 'Usage: buildfile [-f <outfile>] [--altsrc=<altsrc>] filename hostname'
        try:
            opts, alist = getopt.gnu_getopt(args.split(), 'f:', ['altsrc='])
        except:
            print(usage)
            return
        altsrc = None
        outfile = None
        for opt in opts:
            if opt[0] == '--altsrc':
                altsrc = opt[1]
            elif opt[0] == '-f':
                outfile = opt[1]
        if len(alist) != 2:
            print(usage)
            return

        fname, client = alist
        entry = lxml.etree.Element('Path', type='file', name=fname)
        if altsrc:
            entry.set("altsrc", altsrc)
        try:
            metadata = self.build_metadata(client)
            self.Bind(entry, metadata)
            data = lxml.etree.tostring(entry, encoding="UTF-8",
                                       xml_declaration=True)
            if outfile:
                open(outfile, 'w').write(data)
            else:
                print(data)
        except IOError:
            err = sys.exc_info()[1]
            print("Could not write to %s: %s" % (outfile, err))
            print(data)
        except Exception:
            print("Failed to build entry %s for host %s: %s" % 
                (fname, client, traceback.format_exc().splitlines()[-1]))
            raise

    def do_buildbundle(self, args):
        """Render a bundle for client."""
        if len(args.split()) == 2:
            bname, client = args.split()
            try:
                metadata = self.build_metadata(client)
                if bname in self.plugins['Bundler'].entries:
                    bundle = self.plugins['Bundler'].entries[bname]
                    if (has_genshi and
                        isinstance(bundle,
                                   Bcfg2.Server.Plugins.SGenshi.SGenshiTemplateFile)):
                        stream = bundle.template.generate(metadata=metadata)
                        print(stream.render("xml"))
                    else:
                        print(bundle.data)
                else:
                    print("No such bundle %s" % bname)
            except:
                err = sys.exc_info()[1]
                print("Failed to render bundle %s for host %s: %s" % (bname,
                                                                      client,
                                                                      err))
        else:
            print('Usage: buildbundle filename hostname')

    def do_bundles(self, _):
        """Print out group/bundle info."""
        data = [('Group', 'Bundles')]
        groups = list(self.metadata.groups.keys())
        groups.sort()
        for group in groups:
            data.append((group,
                         ','.join(self.metadata.groups[group][0])))
        printTabular(data)

    def do_clients(self, _):
        """Print out client info."""
        data = [('Client', 'Profile')]
        clist = list(self.metadata.clients.keys())
        clist.sort()
        for client in clist:
            data.append((client, self.metadata.clients[client]))
        printTabular(data)

    def do_config(self, _):
        """Print out the current configuration of Bcfg2."""
        output = [
                ('Description', 'Value'),
                ('Path Bcfg2 repository', setup['repo']),
                ('Plugins', setup['plugins']),
                ('Password', setup['password']),
                ('Server Metadata Connector', setup['mconnect']),
                ('Filemonitor', setup['filemonitor']),
                ('Server address',    setup['location']),
                ('Static', setup['static']),
                ('Path to key', setup['key']),
                ('Path to SSL certificate', setup['cert']),
                ('Path to SSL CA certificate', setup['ca']),
                ('Protocol', setup['protocol']),
                ('Logging', setup['logging'])
                ]
        printTabular(output)

    def do_showentries(self, args):
        """Show abstract configuration entries for a given host."""
        arglen = len(args.split())
        if arglen not in [1, 2]:
            print("Usage: showentries <hostname> <type>")
            return
        client = args.split()[0]
        try:
            meta = self.build_metadata(client)
        except Bcfg2.Server.Plugins.Metadata.MetadataConsistencyError:
            print("Unable to find metadata for host %s" % client)
            return
        structures = self.GetStructures(meta)
        output = [('entrytype', 'name')]
        if arglen == 1:
            for item in structures:
                for child in item.getchildren():
                    output.append((child.tag, child.get('name')))
        if arglen == 2:
            etype = args.split()[1]
            for item in structures:
                for child in item.getchildren():
                    if child.tag in [etype, "Bound%s" % etype]:
                        output.append((child.tag, child.get('name')))
        printTabular(output)

    def do_groups(self, _):
        """Print out group info."""
        data = [("Groups", "Profile", "Category", "Contains")]
        grouplist = list(self.metadata.groups.keys())
        grouplist.sort()
        for group in grouplist:
            if group in self.metadata.profiles:
                prof = 'yes'
            else:
                prof = 'no'
            if group in self.metadata.categories:
                cat = self.metadata.categories[group]
            else:
                cat = ''
            gdata = [grp for grp in self.metadata.groups[group][1]]
            if group in gdata:
                gdata.remove(group)
            data.append((group, prof, cat, ','.join(gdata)))
        printTabular(data)

    def do_showclient(self, args):
        """Print host metadata."""
        data = [('Client', 'Profile', "Groups", "Bundles")]
        if not len(args):
            print("Usage:\nshowclient <client> ... <clientN>")
            return
        for client in args.split():
            try:
                client_meta = self.build_metadata(client)
            except:
                print("Client %s not defined" % client)
                continue
            print("Hostname:\t%s" % client_meta.hostname)
            print("Profile:\t%s" % client_meta.profile)
            print("Groups:\t\t%s" % list(client_meta.groups)[0])
            for grp in list(client_meta.groups)[1:]:
                print("\t\t%s" % grp)
            if client_meta.bundles:
                print("Bundles:\t%s" % list(client_meta.bundles)[0])
            for bnd in list(client_meta.bundles)[1:]:
                print("\t\t%s" % bnd)
            if client_meta.connectors:
                print("Connector data")
                print("=" * 80)
                for conn in client_meta.connectors:
                    if getattr(client_meta, conn):
                        print("%s:\t%s" % (conn, getattr(client_meta, conn)))
                        print("=" * 80)

    def do_mappings(self, args):
        """Print out mapping info."""
        # Dump all mappings unless type specified
        data = [('Plugin', 'Type', 'Name')]
        arglen = len(args.split())
        for generator in self.generators:
            if arglen == 0:
                etypes = list(generator.Entries.keys())
            else:
                etypes = [args.split()[0]]
            if arglen == 2:
                interested = [(etype, [args.split()[1]])
                              for etype in etypes]
            else:
                interested = [(etype, generator.Entries[etype])
                              for etype in etypes
                              if etype in generator.Entries]
            for etype, names in interested:
                for name in [name for name in names if name in
                             generator.Entries.get(etype, {})]:
                    data.append((generator.name, etype, name))
        printTabular(data)

    def do_event_debug(self, args):
        self.fam.debug = True

    def do_cfgdebug(self, args):
        try:
            meta = self.build_metadata(args)
        except Bcfg2.Server.Plugins.Metadata.MetadataConsistencyError:
            print("Unable to find metadata for host %s" % args)
            return
        structures = self.GetStructures(meta)
        for clist in [struct.findall('Path') for struct in structures]:
            for cfile in clist:
                if cfile.get('name') in \
                        self.plugins['Cfg'].Entries['ConfigFile']:
                    cset = self.plugins['Cfg'].entries[cfile.get('name')]
                    cand = cset.get_matching(meta)
                    fields = ['all', 'group']
                    while len(cand) > 1 and fields:
                        field = fields.pop(0)
                        [cand.remove(c) for c in cand[:]
                         if getattr(c.specific, field)]
                    if len(cand) != 1:
                        sys.stderr.write("Entry %s failed" % cfile.get('name'))
                        continue
                    print(cand[0].name)

    def do_packageresolve(self, args):
        arglist = args.split(" ")
        if len(arglist) < 2:
            print("Usage: packageresolve <hostname> <package> [<package>...]")
            return

        hostname = arglist[0]
        initial = arglist[1:]
        metadata = self.build_metadata(hostname)
        self.plugins['Packages'].toggle_debug()
        collection = self.plugins['Packages']._get_collection(metadata)
        packages, unknown = collection.complete(initial)
        newpkgs = list(packages.difference(initial))
        print("%d initial packages" % len(initial))
        print("    %s" % "\n    ".join(initial))
        print("%d new packages added" % len(newpkgs))
        if newpkgs:
            print("    %s" % "\n    ".join(newpkgs))
        print("%d unknown packages" % len(unknown))
        if unknown:
            print("    %s" % "\n    ".join(unknown))

    def do_packagesources(self, args):
        try:
            metadata = self.build_metadata(args)
        except Bcfg2.Server.Plugins.Metadata.MetadataConsistencyError:
            print("Unable to build metadata for host %s" % args)
            return
        collection = self.plugins['Packages']._get_collection(metadata)
        print collection.sourcelist()

    def do_profile(self, arg):
        """."""
        if not have_profile:
            print("Profiling functionality not available.")
            return
        tracefname = tempfile.mktemp()
        p = profile.Profile()
        p.runcall(self.onecmd, arg)
        displayTrace(p)

    def Run(self, args):
        """."""
        if args:
            self.onecmd(" ".join(args))
            os._exit(0)
        else:
            self.do_loop()

if __name__ == '__main__':
    Bcfg2.Logger.setup_logging('bcfg2-info', to_syslog=False)
    optinfo = dict(profile=Bcfg2.Options.CORE_PROFILE,
                   mconnect=Bcfg2.Options.SERVER_MCONNECT,
                   interactive=Bcfg2.Options.INTERACTIVE)
    optinfo.update(Bcfg2.Options.CLI_COMMON_OPTIONS)
    optinfo.update(Bcfg2.Options.SERVER_COMMON_OPTIONS)
    setup = Bcfg2.Options.OptionParser(optinfo)
    setup.hm = "\n".join(["     bcfg2-info [options] [command <command args>]",
                          "Options:",
                          setup.buildHelpMessage(),
                          USAGE])

    setup.parse(sys.argv[1:])
    if setup['args'] and setup['args'][0] == 'help':
        print(setup.hm)
        sys.exit(0)
    elif setup['profile'] and have_profile:
        prof = profile.Profile()
        loop = prof.runcall(infoCore, setup['repo'], setup['plugins'],
                            setup['password'], setup['encoding'],
                            setup['debug'], setup['filemonitor'],
                            setup)
        displayTrace(prof)
    else:
        if setup['profile']:
            print("Profiling functionality not available.")
        loop = infoCore(setup['repo'], setup['plugins'], setup['password'],
                        setup['encoding'], setup['debug'],
                        setup['filemonitor'], setup)

    loop.Run(setup['args'])