hostinfo.py 12.2 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.automount
Anders Blomdell's avatar
Anders Blomdell committed
5
6
import hostinfo.dhcpd
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
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
import optparse
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

class VerboseOptionParser(optparse.OptionParser):
    def error(self, msg):
        self.print_help()
        optparse.OptionParser.error(self, msg)

attr_weight = {
    ('host', 'name') : 1,
    ('interface', 'ip') : 1,
    ('interface', 'ether') : 2,
    ('subnet', 'network') : 1,
    ('subnet', 'domain') : 2,
    ('subnet', 'broadcast') : 3,
    ('subnet', 'netmask') : 4,
    ('subnet', 'gateway') : 5,
    ('subnet', 'name_servers') : 6,
}
Anders Blomdell's avatar
Anders Blomdell committed
92

Anders Blomdell's avatar
Anders Blomdell committed
93
94
95
96
97
98
99
100
101
102
103
#def cmp(a,b):
#    if a < b:
#        return -1
#    elif a == b:
#        return 0
#    else:
#        return 1

def host_order(a,b):
    def at_top(n):
        # Place hosts without ethernet or ip address at top
Anders Blomdell's avatar
Anders Blomdell committed
104
105
        for i1 in n._interface_:
            if i1.ethernet[0]:
Anders Blomdell's avatar
Anders Blomdell committed
106
                return False
Anders Blomdell's avatar
Anders Blomdell committed
107
108
109
110
            for i2 in i1._ip_:
                if i2.address[0]:
                    return False
                pass
Anders Blomdell's avatar
Anders Blomdell committed
111
112
113
114
115
            pass
        return True
    def at_bottom(n):
        # Place hosts with ethernet but without ip address at bottom
        result = False
Anders Blomdell's avatar
Anders Blomdell committed
116
117
        for i1 in n._interface_:
            if i1.ethernet[0]:
Anders Blomdell's avatar
Anders Blomdell committed
118
                result = True
Anders Blomdell's avatar
Anders Blomdell committed
119
120
121
122
            for i2 in i1._ip_:
                if i2.address[0]:
                    return False
                pass
Anders Blomdell's avatar
Anders Blomdell committed
123
124
125
126
127
            pass
        return result
    if (at_top(a) == at_top(b) and at_bottom(a) == at_bottom(b)):
        return cmp(a.name[0], b.name[0])
    elif at_top(a):
Anders Blomdell's avatar
Anders Blomdell committed
128
        return -1
Anders Blomdell's avatar
Anders Blomdell committed
129
    elif at_top(b):
Anders Blomdell's avatar
Anders Blomdell committed
130
        return 1
Anders Blomdell's avatar
Anders Blomdell committed
131
132
133
134
135
136
137
    elif at_bottom(a):
        return 1
    elif at_bottom(b):
        return -1
    else:
        raise Exception('Should never happen')

Anders Blomdell's avatar
Anders Blomdell committed
138
tag_weight = {
Anders Blomdell's avatar
Anders Blomdell committed
139
140
141
142
143
144
145
    ('hostinfo', 'soa')        : (1,
                                  None),
    ('hostinfo', 'subnet')      : (2,
                                   lambda a,b: cmp(a.network[0],b.network[0])),
    ('hostinfo', 'netgroup')    : (3,
                                   lambda a,b: cmp(a.name[0],b.name[0])),
    ('hostinfo', 'host')        : (4,
Anders Blomdell's avatar
Anders Blomdell committed
146
147
                                   host_order),
    ('host', 'automount')       : (1,
Anders Blomdell's avatar
Anders Blomdell committed
148
                                   lambda a,b: cmp(a.host[0],b.host[0])),
Anders Blomdell's avatar
Anders Blomdell committed
149
    ('host', 'mio')             : (2,
Anders Blomdell's avatar
Anders Blomdell committed
150
151
152
                                   None),
    ('interface', 'kickstart')  : (1,
                                   None),
Anders Blomdell's avatar
Anders Blomdell committed
153
154
155
    ('interface', 'ip')         : (2,
                                   None),
    ('interface', 'alias')      : (3,
Anders Blomdell's avatar
Anders Blomdell committed
156
                                   None),
Anders Blomdell's avatar
Anders Blomdell committed
157
    ('interface', 'dhcpserver') : (4,
Anders Blomdell's avatar
Anders Blomdell committed
158
                                   None),
Anders Blomdell's avatar
Anders Blomdell committed
159
    ('interface', 'nameserver') : (5,
Anders Blomdell's avatar
Anders Blomdell committed
160
161
162
                                   None),
    ('automount', 'entry')      : (1,
                                   lambda a,b: cmp(a.key[0],b.key[0])),
Anders Blomdell's avatar
Anders Blomdell committed
163
164
165
166
167
168
169
170
171
172
173
174
175
176
}

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

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

if __name__ == '__main__':
Anders Blomdell's avatar
Anders Blomdell committed
209
    optParser = VerboseOptionParser(usage="%prog [options] [hostinfo]")
Anders Blomdell's avatar
Anders Blomdell committed
210
211
212
    optParser.add_option("--host",
                         action="store", 
                         help="The host to generate information for")
Anders Blomdell's avatar
Anders Blomdell committed
213
214
215
216
217
218
    optParser.add_option("--automount",
                         action="store",  metavar="DIR",
                         help="generate automount maps in DIR")
    optParser.add_option("--auto_domain",
                         action="store",  metavar="DOMAIN",
                         help="DOMAIN name for automount maps")
Anders Blomdell's avatar
Anders Blomdell committed
219
220
221
    optParser.add_option("--dfs",
                         action="store",  metavar="DIR",
                         help="generate DIR/*/(dfslink|autolink)")
Anders Blomdell's avatar
Anders Blomdell committed
222
223
224
    optParser.add_option("--dhcpd",
                         action="store",  metavar="DIR",
                         help="generate DIR/dhcpd.conf file")
Anders Blomdell's avatar
Anders Blomdell committed
225
226
227
    optParser.add_option("--ethers",
                         action="store", metavar="FILE",
                         help="Generate ethers FILE")
Anders Blomdell's avatar
Anders Blomdell committed
228
229
230
    optParser.add_option("--ifconfig",
                         action="store", metavar="DIR",
                         help="Generate DIR/ifcfg-eth*")
Anders Blomdell's avatar
Anders Blomdell committed
231
232
233
    optParser.add_option("--kickstart",
                         action="store",  metavar="DIR",
                         help="kickstart files should be fetched from DIR")
Anders Blomdell's avatar
Anders Blomdell committed
234
235
236
    optParser.add_option("--macosx_auto",
                         action="store", metavar="DIR",
                         help="Generate MacOSX autmount maps")
Anders Blomdell's avatar
Anders Blomdell committed
237
238
239
240
241
242
    optParser.add_option("--mio",
                         action="store_true", default=False, 
                         help="output mio tree")
    optParser.add_option("--named",
                         action="store", metavar="DIR",
                         help="Generate DIR/named.conf and DIR/named/*")
Anders Blomdell's avatar
Anders Blomdell committed
243
244
245
    optParser.add_option("--netgroup",
                         action="store", metavar="FILE",
                         help="Generate netgroup FILE")
Anders Blomdell's avatar
Anders Blomdell committed
246
247
248
    optParser.add_option("--next_server",
                         action="store", metavar="HOST",
                         help="Use HOST as DHCP next-server")
Anders Blomdell's avatar
Anders Blomdell committed
249
250
251
    optParser.add_option("--pretty",
                         action="store_true", default=False, 
                         help="pretty-print XML tree")
Anders Blomdell's avatar
Anders Blomdell committed
252
253
254
    optParser.add_option("--pxelinux",
                         action="store",  metavar="DIR", 
                         help="symlink DIR/<ethernet> to <kickstart>")
Anders Blomdell's avatar
Anders Blomdell committed
255
256
257
258
    optParser.add_option("--role",
                         default=[],
                         action="append",  metavar="ROLE", 
                         help="check if machine has ROLE")
Anders Blomdell's avatar
Anders Blomdell committed
259
260
261
    optParser.add_option("--samba",
                         action="store",  metavar="FILE",
                         help="generate samba share FILE")
Anders Blomdell's avatar
Anders Blomdell committed
262
263
    optParser.add_option("--yp",
                         action="store",  metavar="DIR",
Anders Blomdell's avatar
Anders Blomdell committed
264
265
266
267
                         help="generate DIR/{hosts,ethers,etc} information")
    optParser.add_option("--yp_auto_domain",
                         action="store",  metavar="DOMAIN",
                         help="DOMAIN name for yp automounter maps")
Anders Blomdell's avatar
Anders Blomdell committed
268
269
270
271

    (options, args) = optParser.parse_args(sys.argv[1:])

    
Anders Blomdell's avatar
Anders Blomdell committed
272
    host = options.host or os.uname()[1].split('.')[0]
Anders Blomdell's avatar
Anders Blomdell committed
273
274
275
276
277
278
279
280
281

    if not args:
        tree = hostinfo.parser.parse("/etc/hostinfo.xml")
    elif len(args) == 1:
        tree = hostinfo.parser.parse(args[0])
    else:
        raise Exception("Only one hostinfo file allowed")
    
    file = {}
Anders Blomdell's avatar
Anders Blomdell committed
282
283
284
285
286
    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
287
288
289
290
    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
291
    if options.dhcpd:
Anders Blomdell's avatar
Anders Blomdell committed
292
293
294
295
296
        name = "%s/dhcpd.conf" % options.dhcpd
        if options.kickstart:
            kickstart = os.path.abspath(options.kickstart)
        else:
            kickstart = None
Anders Blomdell's avatar
Anders Blomdell committed
297
298
299
            pass
        file[name] = hostinfo.dhcpd.conf(tree, host, kickstart,
                                         next_server=options.next_server)
Anders Blomdell's avatar
Anders Blomdell committed
300
    
Anders Blomdell's avatar
Anders Blomdell committed
301
302
303
    if options.ethers:
        file[options.ethers] = hostinfo.yp.ethers(tree)

Anders Blomdell's avatar
Anders Blomdell committed
304
305
306
307
    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
308
309
310
311
    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
312
313
314
315
316
317
318
319
    if options.mio:
        mio = hostinfo.mio.generate(tree)
        print mio.encode("iso8859-1")
        
    if options.named:
        for (f, c) in hostinfo.named.generate(tree, host):
            file["%s/%s" % (options.named, f)] = c

Anders Blomdell's avatar
Anders Blomdell committed
320
321
322
    if options.netgroup:
        file[options.netgroup] = hostinfo.yp.netgroup(tree)

Anders Blomdell's avatar
Anders Blomdell committed
323
    if options.pxelinux:
Anders Blomdell's avatar
Anders Blomdell committed
324
325
326
327
328
        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
329
            
Anders Blomdell's avatar
Anders Blomdell committed
330
    if options.pretty:
Anders Blomdell's avatar
Anders Blomdell committed
331
        result = "<?xml version='1.0' encoding='utf-8'?>\n\n"
Anders Blomdell's avatar
Anders Blomdell committed
332
        result += tree._xml(attr_sort=attr_sort, tag_sort=tag_sort)
Anders Blomdell's avatar
Anders Blomdell committed
333
        print result.encode("utf-8")
Anders Blomdell's avatar
Anders Blomdell committed
334

Anders Blomdell's avatar
Anders Blomdell committed
335
336
337
338
339
    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
340
    if options.yp:
Anders Blomdell's avatar
Anders Blomdell committed
341
        for (f, c) in hostinfo.yp.generate(tree, options.yp_auto_domain):
Anders Blomdell's avatar
Anders Blomdell committed
342
343
            file["%s/%s" % (options.yp, f)] = c

Anders Blomdell's avatar
Anders Blomdell committed
344
345
346
    if options.samba:
        file[options.samba] = hostinfo.samba.share(tree, host)

Anders Blomdell's avatar
Anders Blomdell committed
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
    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
365
366
    for name in symlink.keys():
        if os.path.lexists(name) and not os.path.islink(name):
Anders Blomdell's avatar
Anders Blomdell committed
367
            print "'%s' exists but is not a link" % name
Anders Blomdell's avatar
Anders Blomdell committed
368
369
370
371
372
373
374
375
376
377
        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
378
    sys.exit(result)