hostinfo.py 13.3 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
79
80
81
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,
    ('interface', 'ip') : 1,
    ('interface', 'ether') : 2,
    ('subnet', 'network') : 1,
Anders Blomdell's avatar
Anders Blomdell committed
82
    ('subnet', 'prefix') : 1,
Anders Blomdell's avatar
Anders Blomdell committed
83
84
85
86
87
88
    ('subnet', 'domain') : 2,
    ('subnet', 'broadcast') : 3,
    ('subnet', 'netmask') : 4,
    ('subnet', 'gateway') : 5,
    ('subnet', 'name_servers') : 6,
}
Anders Blomdell's avatar
Anders Blomdell committed
89

Anders Blomdell's avatar
Anders Blomdell committed
90
91
92
class AttributeDict(dict): 
    __getattr__ = dict.__getitem__

Anders Blomdell's avatar
Anders Blomdell committed
93
94
95
96
97
98
99
100
101
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
102
def host_order(a,b):
Anders Blomdell's avatar
Anders Blomdell committed
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
    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
147

Anders Blomdell's avatar
Anders Blomdell committed
148
tag_weight = {
Anders Blomdell's avatar
Anders Blomdell committed
149
150
151
152
153
    ('hostinfo', 'soa')         : (1, None),
    ('hostinfo', 'subnet')      : (2, network_order),
#                                   lambda a,b: cmp(a.network[0],b.network[0])),
    ('hostinfo', 'nameserver')  : (3, None),
    ('hostinfo', 'netgroup')    : (4,
Anders Blomdell's avatar
Anders Blomdell committed
154
                                   lambda a,b: cmp(a.name[0],b.name[0])),
Anders Blomdell's avatar
Anders Blomdell committed
155
156
157
158
159
160
161
162
163
164
    ('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),
    ('interface', 'kickstart')  : (1, None),
    ('interface', 'ip')         : (2, None),
    ('interface', 'alias')      : (3, None),
    ('interface', 'dhcpserver') : (4, None),
    ('interface', 'nameserver') : (5, None),
    ('automount', 'entry')      : (1, lambda a,b: cmp(a.key[0],b.key[0])),
Anders Blomdell's avatar
Anders Blomdell committed
165
166
167
168
169
170
171
172
173
174
175
176
177
178
}

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
179
        return cmp(aw, bw)
Anders Blomdell's avatar
Anders Blomdell committed
180
181
182
183
184
    elif aw:
        return -1
    elif bw:
        return 1
    else:
Anders Blomdell's avatar
Anders Blomdell committed
185
        return cmp(a, b)
Anders Blomdell's avatar
Anders Blomdell committed
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201

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
202
            return cmp(aw, bw)
Anders Blomdell's avatar
Anders Blomdell committed
203
204
205
206
207
208
209
210
    elif aw:
        return -1
    elif bw:
        return 1
    else:
        return None

if __name__ == '__main__':
Anders Blomdell's avatar
Anders Blomdell committed
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
    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
240
241
242
    optParser.add_argument("--kickstart", 
                           action="store",  metavar="PREFIX",
                           help="kickstart file PREFIX")
Anders Blomdell's avatar
Anders Blomdell committed
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
    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
268
269
270
271
    optParser.add_argument("--role-holder",
                           default=[],
                           action="store",  metavar="ROLE", 
                           help="check which machine currently holding ROLE")
Anders Blomdell's avatar
Anders Blomdell committed
272
273
274
275
276
277
278
279
280
    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
281

Anders Blomdell's avatar
Anders Blomdell committed
282
283
    options = optParser.parse_args(sys.argv[1:])
    hostinfo.options = options
Anders Blomdell's avatar
Anders Blomdell committed
284

Anders Blomdell's avatar
Anders Blomdell committed
285
286
    tree = hostinfo.parser.parse(options.hostinfo_xml)
    host = options.host
Anders Blomdell's avatar
Anders Blomdell committed
287
288

    file = {}
Anders Blomdell's avatar
Anders Blomdell committed
289
290
291
292
293
    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
294
295
296
297
    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
298
    if options.dhcpd:
Anders Blomdell's avatar
Anders Blomdell committed
299
        file["%s/dhcpd.conf" % options.dhcpd] = hostinfo.dhcpd.generate(
Anders Blomdell's avatar
Anders Blomdell committed
300
            tree, options)
Anders Blomdell's avatar
Anders Blomdell committed
301
302
303
304
305
306
307
        pass

    if options.dhcpd6:
        file["%s/dhcpd6.conf" % options.dhcpd6] = hostinfo.dhcpd_ipv6.generate(
            tree, options)
        pass
            
Anders Blomdell's avatar
Anders Blomdell committed
308
    
Anders Blomdell's avatar
Anders Blomdell committed
309
310
311
    if options.ethers:
        file[options.ethers] = hostinfo.yp.ethers(tree)

Anders Blomdell's avatar
Anders Blomdell committed
312
313
314
315
    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
316
317
318
319
    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
320
321
322
323
324
    if options.mio:
        mio = hostinfo.mio.generate(tree)
        print mio.encode("iso8859-1")
        
    if options.named:
Anders Blomdell's avatar
Anders Blomdell committed
325
        for (f, c) in hostinfo.named.generate(tree, options):
Anders Blomdell's avatar
Anders Blomdell committed
326
327
            file["%s/%s" % (options.named, f)] = c

Anders Blomdell's avatar
Anders Blomdell committed
328
329
330
    if options.netgroup:
        file[options.netgroup] = hostinfo.yp.netgroup(tree)

Anders Blomdell's avatar
Anders Blomdell committed
331
    if options.pxelinux:
Anders Blomdell's avatar
Anders Blomdell committed
332
333
334
335
336
        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
337
            
Anders Blomdell's avatar
Anders Blomdell committed
338
    if options.pretty:
Anders Blomdell's avatar
Anders Blomdell committed
339
        result = "<?xml version='1.0' encoding='utf-8'?>\n\n"
Anders Blomdell's avatar
Anders Blomdell committed
340
        result += tree._xml(attr_sort=attr_sort, tag_sort=tag_sort)
Anders Blomdell's avatar
Anders Blomdell committed
341
        print result.encode("utf-8")
Anders Blomdell's avatar
Anders Blomdell committed
342
        sys.exit(0)
Anders Blomdell's avatar
Anders Blomdell committed
343

Anders Blomdell's avatar
Anders Blomdell committed
344
345
346
347
348
    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
349
350
351
352
353
    if options.role_holder:
        who = hostinfo.role.holder(tree, options.role_holder)
        print who
        pass
        
Anders Blomdell's avatar
Anders Blomdell committed
354
    if options.yp:
Anders Blomdell's avatar
Anders Blomdell committed
355
        for (f, c) in hostinfo.yp.generate(tree, options.yp_auto_domain):
Anders Blomdell's avatar
Anders Blomdell committed
356
357
            file["%s/%s" % (options.yp, f)] = c

Anders Blomdell's avatar
Anders Blomdell committed
358
359
360
    if options.samba:
        file[options.samba] = hostinfo.samba.share(tree, host)

Anders Blomdell's avatar
Anders Blomdell committed
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
    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
379
380
    for name in symlink.keys():
        if os.path.lexists(name) and not os.path.islink(name):
Anders Blomdell's avatar
Anders Blomdell committed
381
            print "'%s' exists but is not a link" % name
Anders Blomdell's avatar
Anders Blomdell committed
382
383
384
385
386
387
388
389
390
391
        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
392
    sys.exit(result)