hostinfo.py 13.5 KB
Newer Older
Anders Blomdell's avatar
Anders Blomdell committed
1
#!/usr/bin/python
Anders Blomdell's avatar
Anders Blomdell committed
2
3

import copy
Anders Blomdell's avatar
Anders Blomdell committed
4
import hostinfo
Anders Blomdell's avatar
Anders Blomdell committed
5
import hostinfo.automount
Anders Blomdell's avatar
Anders Blomdell committed
6
import hostinfo.ifconfig
Anders Blomdell's avatar
Anders Blomdell committed
7
import hostinfo.macosx_auto
Anders Blomdell's avatar
Anders Blomdell committed
8
9
10
import hostinfo.mio
import hostinfo.named
import hostinfo.parser
Anders Blomdell's avatar
Anders Blomdell committed
11
import hostinfo.pxelinux
Anders Blomdell's avatar
Anders Blomdell committed
12
import hostinfo.samba
Anders Blomdell's avatar
Anders Blomdell committed
13
import hostinfo.yp
Anders Blomdell's avatar
Anders Blomdell committed
14
import hostinfo.role
Anders Blomdell's avatar
Anders Blomdell committed
15
import hostinfo.util
Anders Blomdell's avatar
Anders Blomdell committed
16
import argparse
Anders Blomdell's avatar
Anders Blomdell committed
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
import os
import sys

"""
  This program parses hostinfo.xml files. The following tags/attribute
  structure is currently used:

  <hostinfo             -- Top level tag
    modification_time   -- Syntetic attribute (.xml mtime)
  >
    <soa                -- SOA info for named files
       domain           -- SOA domain (all if not set)
       nameserver       -- primary nameserver for domain
       email            -- email for domain
       ttl              -- default TTL for SOA
       refresh          -- refresh interval
       retry            -- retry interval
       expire           -- expire interval
       minimum          -- minimum interval
    />
    <subnet             -- subnet information (named, dhcpd)
       broadcast        -- broadcast address for subnet
       domain           -- subnet domain name
       name_servers     -- subnet nameservers
       netmask          -- subnet netmask
       network          -- subnet network
       routers          -- subnet routers
    />
    <host               -- host specific information
       info             -- catchall for useful info
       name             -- hostname (FQN if ends with .)
    >
      <interface        -- host interface information
          ethernet      -- ethernet address
          ip            -- ip address
          name          -- optional name for this ip address
      >
        <dhcpserver     -- interface serves as a dhcpserver
        />
        <nameserver
           domain       -- interface is nameserver for this domain
        <kickstart
           file         -- kickstart file to use
        />
        <alias
           name         -- alias for this interface
        <dhcp
          value         -- extra dhcp data for host
        />
      </interface>
    </host>

  </hostinfo>
"""

# Fix for older python version that does not have True and False defined
if not hasattr(__builtins__, "True"):
    __builtins__["True"] = 1
    __builtins__["False"] = 0

attr_weight = {
    ('host', 'name') : 1,
Anders Blomdell's avatar
Anders Blomdell committed
79
80
81
82
83
    ('disk', 'host') : 1,
    ('disk', 'root') : 2,
    ('disk', 'id') : 3,
    ('disk', 'size') : 4,
    ('disk', 'format') : 5,
Anders Blomdell's avatar
Anders Blomdell committed
84
85
86
    ('interface', 'ip') : 1,
    ('interface', 'ether') : 2,
    ('subnet', 'network') : 1,
Anders Blomdell's avatar
Anders Blomdell committed
87
    ('subnet', 'prefix') : 1,
Anders Blomdell's avatar
Anders Blomdell committed
88
89
90
91
92
93
    ('subnet', 'domain') : 2,
    ('subnet', 'broadcast') : 3,
    ('subnet', 'netmask') : 4,
    ('subnet', 'gateway') : 5,
    ('subnet', 'name_servers') : 6,
}
Anders Blomdell's avatar
Anders Blomdell committed
94

Anders Blomdell's avatar
Anders Blomdell committed
95
96
97
class AttributeDict(dict): 
    __getattr__ = dict.__getitem__

Anders Blomdell's avatar
Anders Blomdell committed
98
99
100
101
102
103
104
105
106
def network_order(a, b):
    a_net = hostinfo.util.network(a)
    b_net = hostinfo.util.network(b)
    if not a_net or not b_net:
        return cmp(a,b)
    if a_net.version == b_net.version:
        return cmp(a_net, b_net)
    return cmp(a_net.version, b_net.version)

Anders Blomdell's avatar
Anders Blomdell committed
107
def host_order(a,b):
Anders Blomdell's avatar
Anders Blomdell committed
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
    def fqn(host):
        n = host.name[0]
        return n and n.endswith('.')
    def select(f, c):
        return [ f(e) for e in c if f(e) ]
    def ether(host):
        return select(lambda i: i.ethernet[0], host._interface_)
    def ip(host):
        ipv4 = select(hostinfo.util.address, host._interface_._ip_)
        ipv6 = select(hostinfo.util.address, host._interface_._ipv6_)
        return ipv4 + ipv6
    def no_addr(host):
        return not ether(host) and not ip(host)
    def all_addr(host):
        return ether(host) and ip(host)

    # Fully qualified names
    if fqn(a) or fqn(b): 
        if fqn(a) and fqn(b): return cmp(a.name[0], b.name[0])
        if fqn(a): return -1
        if fqn(b): return 1
        pass
    
    #  Hosts without ether an ip address (reusable names)
    if no_addr(a) or no_addr(b):
        if no_addr(a) and no_addr(b): return cmp(a.name[0], b.name[0])
        if no_addr(a): return -1
        if no_addr(b): return 1
        pass

    # Hosts with ip and ether (active machines)
    if all_addr(a) or all_addr(b):
        if all_addr(a) and all_addr(b): return cmp(a.name[0], b.name[0])
        if all_addr(a): return -1
        if all_addr(b): return 1
        pass
    # This should be machines with ether but no ip (decommissioned)
    if ip(a): 
        raise hostinfo.util.HostinfoException('Unexpected ip address %s' %
                                              a.name[0], where=a)
    if ip(b): 
        raise hostinfo.util.HostinfoException('Unexpected ip address %s' %
                                              b.name[0], where=b)
    return cmp(a.name[0], b.name[0])
Anders Blomdell's avatar
Anders Blomdell committed
152

Anders Blomdell's avatar
Anders Blomdell committed
153
tag_weight = {
Anders Blomdell's avatar
Anders Blomdell committed
154
155
156
157
    ('hostinfo', 'soa')         : (1, None),
    ('hostinfo', 'subnet')      : (2, network_order),
    ('hostinfo', 'nameserver')  : (3, None),
    ('hostinfo', 'netgroup')    : (4,
Anders Blomdell's avatar
Anders Blomdell committed
158
                                   lambda a,b: cmp(a.name[0],b.name[0])),
Anders Blomdell's avatar
Anders Blomdell committed
159
160
161
162
    ('hostinfo', 'host')        : (5, host_order),
    ('host', 'role')            : (1, None),
    ('host', 'automount')       : (2, lambda a,b: cmp(a.host[0],b.host[0])),
    ('host', 'mio')             : (3, None),
Anders Blomdell's avatar
Anders Blomdell committed
163
    ('host', 'qemu')            : (4, None),
Anders Blomdell's avatar
Anders Blomdell committed
164
165
    ('interface', 'kickstart')  : (1, None),
    ('interface', 'ip')         : (2, None),
Anders Blomdell's avatar
Anders Blomdell committed
166
167
168
169
    ('interface', 'ipv6')       : (3, None),
    ('interface', 'alias')      : (4, None),
    ('interface', 'dhcpserver') : (5, None),
    ('interface', 'nameserver') : (6, None),
Anders Blomdell's avatar
Anders Blomdell committed
170
    ('automount', 'entry')      : (1, lambda a,b: cmp(a.key[0],b.key[0])),
Anders Blomdell's avatar
Anders Blomdell committed
171
172
173
174
175
176
177
178
179
180
181
182
183
184
}

def attr_sort(node, a, b):
    try:
        aw = attr_weight[node._tag, a]
    except:
        aw = 0

    try:
        bw = attr_weight[node._tag, b]
    except:
        bw = 0

    if aw and bw:
Anders Blomdell's avatar
Anders Blomdell committed
185
        return cmp(aw, bw)
Anders Blomdell's avatar
Anders Blomdell committed
186
187
188
189
190
    elif aw:
        return -1
    elif bw:
        return 1
    else:
Anders Blomdell's avatar
Anders Blomdell committed
191
        return cmp(a, b)
Anders Blomdell's avatar
Anders Blomdell committed
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207

def tag_sort(parent, a, b):
    try:
        (aw, sort) = tag_weight[parent._tag, a._tag]
    except:
        aw = 0

    try:
        (bw, sort) = tag_weight[parent._tag, b._tag]
    except:
        bw = 0

    if aw and bw:
        if aw == bw and sort:
            return sort(a,b)
        else:
Anders Blomdell's avatar
Anders Blomdell committed
208
            return cmp(aw, bw)
Anders Blomdell's avatar
Anders Blomdell committed
209
210
211
212
213
214
215
216
    elif aw:
        return -1
    elif bw:
        return 1
    else:
        return None

if __name__ == '__main__':
Anders Blomdell's avatar
Anders Blomdell committed
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
    optParser = argparse.ArgumentParser(usage="%(prog)s [options] [hostinfo]")
    optParser.add_argument("hostinfo_xml", nargs='?',
                           default="/etc/hostinfo.xml",
                           help="hostinfo file")
    optParser.add_argument("--host",
                           default=os.uname()[1].split('.')[0],
                           action="store", 
                           help="The host to generate information for")
    optParser.add_argument("--automount",
                           action="store",  metavar="DIR",
                           help="generate automount maps in DIR")
    optParser.add_argument("--auto_domain",
                           action="store",  metavar="DOMAIN",
                           help="DOMAIN name for automount maps")
    optParser.add_argument("--dfs",
                           action="store",  metavar="DIR",
                           help="generate DIR/*/(dfslink|autolink)")
    optParser.add_argument("--dhcpd",
                           action="store",  metavar="DIR",
                           help="generate DIR/dhcpd.conf file")
    optParser.add_argument("--dhcpd6",
                           action="store",  metavar="DIR",
                           help="generate DIR/dhcpd6.conf file")
    optParser.add_argument("--ethers",
                           action="store", metavar="FILE",
                           help="Generate ethers FILE")
    optParser.add_argument("--ifconfig",
                           action="store", metavar="DIR",
                           help="Generate DIR/ifcfg-eth*")
Anders Blomdell's avatar
Anders Blomdell committed
246
247
248
    optParser.add_argument("--kickstart", 
                           action="store",  metavar="PREFIX",
                           help="kickstart file PREFIX")
Anders Blomdell's avatar
Anders Blomdell committed
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
    optParser.add_argument("--macosx_auto",
                           action="store", metavar="DIR",
                           help="Generate MacOSX autmount maps")
    optParser.add_argument("--mio",
                           action="store_true", default=False, 
                           help="output mio tree")
    optParser.add_argument("--named",
                           action="store", metavar="DIR",
                           help="Generate DIR/named.conf and DIR/named/*")
    optParser.add_argument("--netgroup",
                           action="store", metavar="FILE",
                           help="Generate netgroup FILE")
    optParser.add_argument("--next_server",
                           action="store", metavar="HOST",
                           help="Use HOST as DHCP next-server")
    optParser.add_argument("--pretty",
                           action="store_true", default=False, 
                           help="pretty-print XML tree")
    optParser.add_argument("--pxelinux",
                           action="store",  metavar="DIR", 
                           help="symlink DIR/<ethernet> to <kickstart>")
    optParser.add_argument("--role",
                           default=[],
                           action="append",  metavar="ROLE", 
                           help="check if machine has ROLE")
Anders Blomdell's avatar
Anders Blomdell committed
274
275
276
277
    optParser.add_argument("--role-holder",
                           default=[],
                           action="store",  metavar="ROLE", 
                           help="check which machine currently holding ROLE")
Anders Blomdell's avatar
Anders Blomdell committed
278
279
280
281
282
283
284
285
286
    optParser.add_argument("--samba",
                           action="store",  metavar="FILE",
                           help="generate samba share FILE")
    optParser.add_argument("--yp",
                           action="store",  metavar="DIR",
                           help="generate DIR/{hosts,ethers,etc} information")
    optParser.add_argument("--yp_auto_domain",
                           action="store",  metavar="DOMAIN",
                           help="DOMAIN name for yp automounter maps")
Anders Blomdell's avatar
Anders Blomdell committed
287

Anders Blomdell's avatar
Anders Blomdell committed
288
289
    options = optParser.parse_args(sys.argv[1:])
    hostinfo.options = options
Anders Blomdell's avatar
Anders Blomdell committed
290

Anders Blomdell's avatar
Anders Blomdell committed
291
    tree = hostinfo.parser.parse(options.hostinfo_xml, include_comments=True)
Anders Blomdell's avatar
Anders Blomdell committed
292
    host = options.host
Anders Blomdell's avatar
Anders Blomdell committed
293
294

    file = {}
Anders Blomdell's avatar
Anders Blomdell committed
295
296
297
298
299
    symlink = {}
    if options.dfs:
        for (f, c) in hostinfo.samba.msdfs(tree):
            symlink["%s/%s" % (options.dfs, f)] = c

Anders Blomdell's avatar
Anders Blomdell committed
300
301
302
303
    if options.automount:
        for (f, c) in hostinfo.automount.generate(tree,options.auto_domain):
            file["%s/%s" % (options.automount, f)] = c

Anders Blomdell's avatar
Anders Blomdell committed
304
    if options.dhcpd:
Anders Blomdell's avatar
Anders Blomdell committed
305
        file["%s/dhcpd.conf" % options.dhcpd] = hostinfo.dhcpd.generate(
Anders Blomdell's avatar
Anders Blomdell committed
306
            tree, options)
Anders Blomdell's avatar
Anders Blomdell committed
307
308
309
310
311
312
313
        pass

    if options.dhcpd6:
        file["%s/dhcpd6.conf" % options.dhcpd6] = hostinfo.dhcpd_ipv6.generate(
            tree, options)
        pass
            
Anders Blomdell's avatar
Anders Blomdell committed
314
    
Anders Blomdell's avatar
Anders Blomdell committed
315
316
317
    if options.ethers:
        file[options.ethers] = hostinfo.yp.ethers(tree)

Anders Blomdell's avatar
Anders Blomdell committed
318
319
320
321
    if options.ifconfig:
        for (f, c) in hostinfo.ifconfig.generate(tree, host):
            file["%s/%s" % (options.ifconfig, f)] = c
        
Anders Blomdell's avatar
Anders Blomdell committed
322
323
324
325
    if options.macosx_auto:
        for (f, c) in hostinfo.macosx_auto.generate(tree):
            file["%s/%s" % (options.macosx_auto, f)] = c
        
Anders Blomdell's avatar
Anders Blomdell committed
326
327
328
329
330
    if options.mio:
        mio = hostinfo.mio.generate(tree)
        print mio.encode("iso8859-1")
        
    if options.named:
Anders Blomdell's avatar
Anders Blomdell committed
331
        for (f, c) in hostinfo.named.generate(tree, options):
Anders Blomdell's avatar
Anders Blomdell committed
332
333
            file["%s/%s" % (options.named, f)] = c

Anders Blomdell's avatar
Anders Blomdell committed
334
335
336
    if options.netgroup:
        file[options.netgroup] = hostinfo.yp.netgroup(tree)

Anders Blomdell's avatar
Anders Blomdell committed
337
    if options.pxelinux:
Anders Blomdell's avatar
Anders Blomdell committed
338
339
340
341
342
        ksinfo = ""
        for (mac, host, ksfile) in hostinfo.pxelinux.generate(tree, host):
            ksinfo += "%s %s %s\n" % (mac, host, ksfile)
            # symlink["%s/%s" % (options.pxelinux, mac)] = ksfile
        file["%s/ksinfo" % options.pxelinux] = ksinfo
Anders Blomdell's avatar
Anders Blomdell committed
343
            
Anders Blomdell's avatar
Anders Blomdell committed
344
    if options.pretty:
Anders Blomdell's avatar
Anders Blomdell committed
345
        result = "<?xml version='1.0' encoding='utf-8'?>\n\n"
Anders Blomdell's avatar
Anders Blomdell committed
346
        result += tree._xml(attr_sort=attr_sort, tag_sort=tag_sort)
Anders Blomdell's avatar
Anders Blomdell committed
347
        print result.encode("utf-8")
Anders Blomdell's avatar
Anders Blomdell committed
348
        sys.exit(0)
Anders Blomdell's avatar
Anders Blomdell committed
349

Anders Blomdell's avatar
Anders Blomdell committed
350
351
352
353
354
    if options.role:
        roles = hostinfo.role.generate(tree, host, options.role)
        # print "Roles:",",".join(roles)
        sys.exit(len(roles) != len(options.role))
        
Anders Blomdell's avatar
Anders Blomdell committed
355
356
357
358
359
    if options.role_holder:
        who = hostinfo.role.holder(tree, options.role_holder)
        print who
        pass
        
Anders Blomdell's avatar
Anders Blomdell committed
360
    if options.yp:
Anders Blomdell's avatar
Anders Blomdell committed
361
        for (f, c) in hostinfo.yp.generate(tree, options.yp_auto_domain):
Anders Blomdell's avatar
Anders Blomdell committed
362
363
            file["%s/%s" % (options.yp, f)] = c

Anders Blomdell's avatar
Anders Blomdell committed
364
365
366
    if options.samba:
        file[options.samba] = hostinfo.samba.share(tree, host)

Anders Blomdell's avatar
Anders Blomdell committed
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
    result = 1
    for name in file.keys():
        write = False
        try:
            f = open(name)
            conf = f.read()
            f.close()
            write = conf != file[name].encode("iso8859-1")
        except IOError, e:
            write = True

        if write:
            print name
            result = 0
            f = open(name, "w")
            f.write(file[name].encode("iso8859-1"))
            f.close()

Anders Blomdell's avatar
Anders Blomdell committed
385
386
    for name in symlink.keys():
        if os.path.lexists(name) and not os.path.islink(name):
Anders Blomdell's avatar
Anders Blomdell committed
387
            print "'%s' exists but is not a link" % name
Anders Blomdell's avatar
Anders Blomdell committed
388
389
390
391
392
393
394
395
396
397
        elif not os.path.lexists(name):
            print "Creating '%s' -> '%s'" % (name, symlink[name])
            os.symlink(symlink[name], name)
            result = 0
        elif os.readlink(name) != symlink[name]:
            print "Changing '%s' -> '%s'" % (name, symlink[name])
            os.unlink(name)
            os.symlink(symlink[name], name)
            result = 0

Anders Blomdell's avatar
Anders Blomdell committed
398
    sys.exit(result)