summaryrefslogtreecommitdiffstats
path: root/src/sbin/bcfg2-info
blob: cf369bd4d631b74e9de1b6ae23194d1cf8c01790 (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
#!/usr/bin/python -i
'''This tool loads the Bcfg2 core into an interactive debugger'''
__revision__ = '$Revision: 5014 $'

import copy, logging, lxml.etree, sys, time, cmd
import Bcfg2.Logger, Bcfg2.Server.Core, os
import Bcfg2.Server.Plugins.Metadata, Bcfg2.Server.Plugin
import Bcfg2.Options

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

class dummyError(Exception):
    pass

def printTabular(rows):
    '''print data in tabular format'''
    cmax = tuple([max([len(str(row[index])) for row in rows]) + 1 for index in xrange(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

class infoCore(cmd.Cmd, Bcfg2.Server.Core.Core):

    def __init__(self, repo, plgs, passwd, vcs, encoding, event_debug):
        cmd.Cmd.__init__(self)
        try:
            Bcfg2.Server.Core.Core.__init__(self, repo, plgs, passwd, vcs,
                                            encoding)
            if event_debug:
                self.fam.debug = True
        except Bcfg2.Server.Core.CoreInitError, msg:
            print "Core load failed because %s" % msg
            raise SystemExit(1)
        self.prompt = '> '
        self.cont = True
        i = 0
        while self.fam.Service() or i < 5:
            i += 1
        
    def do_loop(self):
        self.cont = True
        while self.cont:
            try:
                self.cmdloop()
            except SystemExit, val:
                raise
            except Bcfg2.Server.Plugin.PluginExecutionError:
                continue
            except dummyError:
                continue
            except:
                logger.error("command failure", exc_info=1)

    def do_debug(self, _):
        self.cont = False
        print "dropping to python interpreter; run loop.do_loop() to resume"
        raise dummyError

    def do_quit(self, _):
        """Exit program.
Usage: [quit|exit]"""
        raise SystemExit(0)

    do_EOF = do_quit
    do_exit = do_quit

    def do_help(self, _):
        '''print out usage info'''
        print 'Commands:'
        print 'build <hostname> <filename> - build config for hostname, writing to filename'
        print 'buildall <directory> - build configs for all clients in directory'
        print 'buildfile <filename> <hostname> - build config file for hostname (not written to disk)'
        print 'bundles - print out group/bundle information'
        print 'clients - print out client/profile information'
        print 'debug - shell out to native python interpreter'
        print 'event_debug - display filesystem events as they are processed'
        print 'generators - list current versions of generators'
        print 'groups - list groups'
        print 'help - print this text'
        print 'mappings <type*> <name*>- print generator mappings for optional type and name'
        print 'quit'
        print 'showentries <hostname> <type> - show abstract configuration entries for a given host'
        print 'showclient <client1> <client2> - show metadata for given hosts'
        print 'update - process pending file events'
        print 'version - print version of this tool'


    def do_update(self, _):
        '''Process pending fs events'''
        self.fam.Service()

    def do_version(self, _):
        '''print out code version'''
        print __revision__
        
    def do_build(self, args):
        '''build client configuration'''
        if len(args.split()) == 2:
            client, ofile = args.split()
            output = open(ofile, 'w')
            data = lxml.etree.tostring(self.BuildConfiguration(client), encoding='UTF-8', xml_declaration=True)
            output.write(data)
            output.close()
        else:
            print 'Usage: build <hostname> <output file>'

    def do_buildall(self, args):
        if len(args.split()) != 1:
            print "Usage: buildall <directory>"
            return
        try:
            os.mkdir(args)
        except:
            pass
        for client in self.metadata.clients:
            self.do_build("%s %s/%s.xml" % (client, args, client))

    def do_buildfile(self, args):
        '''build a config file for client'''
        if len(args.split()) == 2:
            fname, client = args.split()
            entry = lxml.etree.Element('ConfigFile', name=fname)
            metadata = self.build_metadata(client)
            self.Bind(entry, metadata)
            print lxml.etree.tostring(entry, encoding="UTF-8", xml_declaration=True)
        else:
            print 'Usage: buildfile filename hostname'

    def do_bundles(self, _):
        '''print out group/bundle info'''
        data = [('Group', 'Bundles')]
        groups = 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 = self.metadata.clients.keys()
        clist.sort()
        for client in clist:
            data.append((client, self.metadata.clients[client]))
        printTabular(data)

    def do_generators(self, _):
        '''print out generator info'''
        for generator in self.generators:
            print generator.__version__

    def do_showentries(self, args):
        '''show abstract configuration entries for a given host'''
        arglen = len(args.split())
        if arglen not in [2, 3]:
            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 = 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 complete_showclient(self, text, line, begidx, endidx):
        return [entry for entry in self.metadata.clients \
                if entry.startswith(text)] 

    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
                
            numbundles = len(client_meta.bundles)
            numgroups = len(client_meta.groups)
            num = max((numbundles, numgroups))
            for i in range(0, num):
                if i == 0:
                    c = client_meta.hostname
                    p = client_meta.profile
                else:
                    c = ""
                    p = ""
                if i < numbundles:
                    b = client_meta.bundles[i]
                else:
                    b = ""
                if i < numgroups:
                    g = client_meta.groups[i]
                else:
                    g = ""
                data.append((c, p, g, b))
        if len(data) > 1:
            printTabular(data)

    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 = 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" % client
            return
        structures = self.GetStructures(meta)
        for clist in [struct.findall('ConfigFile') 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:
                        print >>sys.stderr, "Entry %s failed" % cfile.get('name')
                        continue
                    print cand[0].name

if __name__ == '__main__':
    Bcfg2.Logger.setup_logging('bcfg2-info', to_syslog=False)
    optinfo = {
            'configfile': Bcfg2.Options.CFILE, 
            'help': Bcfg2.Options.HELP,
              }
    optinfo.update({'repo': Bcfg2.Options.SERVER_REPOSITORY,
                    'vcs': Bcfg2.Options.SERVER_VCS,
                    'plugins': Bcfg2.Options.SERVER_PLUGINS,
                    'password': Bcfg2.Options.SERVER_PASSWORD,
                    'event debug': Bcfg2.Options.DEBUG,
                    'encoding': Bcfg2.Options.ENCODING})
    setup = Bcfg2.Options.OptionParser(optinfo)
    setup.parse(sys.argv[1:])
    print setup
    loop = infoCore(setup['repo'], setup['plugins'], 
                    setup['password'], setup['vcs'], setup['encoding'],
                    '-d' in sys.argv)
    if "args" in setup and setup['args']:
        loop.onecmd(" ".join(setup['args']))
        raise SystemExit(0)
    else:
        loop.do_loop()