Add DNS* settings for static configuration.
[pyplnet.git] / plnet.py
1 #!/usr/bin/python /usr/bin/plcsh
2 # $Id$
3
4 import os
5 import socket
6 import time
7 import tempfile
8 import errno
9
10 import sioc
11 import modprobe
12
13 def InitInterfaces(logger, plc, data, root="", files_only=False, program="NodeManager"):
14     sysconfig = "%s/etc/sysconfig/network-scripts" % root
15     try:
16         os.makedirs(sysconfig)
17     except OSError, e:
18         if e.errno != errno.EEXIST:
19             raise e
20
21     # query running network interfaces
22     devs = sioc.gifconf()
23     ips = dict(zip(devs.values(), devs.keys()))
24     macs = {}
25     for dev in devs:
26         macs[sioc.gifhwaddr(dev).lower()] = dev
27
28     # assume data['networks'] contains this node's NodeNetworks
29     interfaces = {}
30     interface = 1
31     hostname = data.get('hostname',socket.gethostname())
32     gateway = None
33     networks = data['networks']
34     failedToGetSettings = False
35     for network in networks:
36         logger.verbose('net:InitInterfaces interface %d: %s'%(interface,network))
37         logger.verbose('net:InitInterfaces macs = %s' % macs)
38         logger.verbose('net:InitInterfaces ips = %s' % ips)
39         # Get interface name preferably from MAC address, falling back
40         # on IP address.
41         hwaddr=network['mac']
42         if hwaddr <> None: hwaddr=hwaddr.lower()
43         if hwaddr in macs:
44             orig_ifname = macs[hwaddr]
45         elif network['ip'] in ips:
46             orig_ifname = ips[network['ip']]
47         else:
48             orig_ifname = None
49
50         if orig_ifname:
51                 logger.verbose('net:InitInterfaces orig_ifname = %s' % orig_ifname)
52         
53         inter = {}
54         inter['ONBOOT']='yes'
55         inter['USERCTL']='no'
56         if network['mac']:
57             inter['HWADDR'] = network['mac']
58         if network['is_primary']:
59             inter['PRIMARY']='yes'
60
61         if network['method'] == "static":
62             inter['BOOTPROTO'] = "static"
63             inter['IPADDR'] = network['ip']
64             inter['NETMASK'] = network['netmask']
65             inter['DNS1'] = network['dns1']
66             inter['DNS2'] = network['dns2']
67             if network['is_primary']:
68                 gateway = network['gateway']
69
70         elif network['method'] == "dhcp":
71             inter['BOOTPROTO'] = "dhcp"
72             inter['PERSISTENT_DHCLIENT'] = "yes"
73             if network['hostname']:
74                 inter['DHCP_HOSTNAME'] = network['hostname']
75             else:
76                 inter['DHCP_HOSTNAME'] = hostname 
77             if not network['is_primary']:
78                 inter['DHCLIENTARGS'] = "-R subnet-mask"
79
80         if len(network['interface_tag_ids']) > 0:
81             try:
82                 settings = plc.GetInterfaceTags({'interface_tag_id':
83                                                  network['interface_tag_ids']})
84             except:
85                 logger.log("net:InitInterfaces FATAL: failed call GetInterfaceTags({'interface_tag_id':{%s})"% \
86                            network['interface_tag_ids'])
87                 failedToGetSettings = True
88                 continue # on to the next network
89
90             for setting in settings:
91                 # to explicitly set interface name
92                 settingname = setting['name'].upper()
93                 if settingname in ('IFNAME','ALIAS','CFGOPTIONS','DRIVER'):
94                     inter[settingname]=setting['value']
95                 else:
96                     logger.log("net:InitInterfaces WARNING: ignored setting named %s"%setting['name'])
97
98         # support aliases to interfaces either by name or HWADDR
99         if 'ALIAS' in inter:
100             if 'HWADDR' in inter:
101                 hwaddr = inter['HWADDR'].lower()
102                 del inter['HWADDR']
103                 if hwaddr in macs:
104                     hwifname = macs[hwaddr]
105                     if ('IFNAME' in inter) and inter['IFNAME'] <> hwifname:
106                         logger.log("net:InitInterfaces WARNING: alias ifname (%s) and hwaddr ifname (%s) do not match"%\
107                                        (inter['IFNAME'],hwifname))
108                         inter['IFNAME'] = hwifname
109                 else:
110                     logger.log('net:InitInterfaces WARNING: mac addr %s for alias not found' %(hwaddr,alias))
111
112             if 'IFNAME' in inter:
113                 # stupid RH /etc/sysconfig/network-scripts/ifup-aliases:new_interface()
114                 # checks if the "$DEVNUM" only consists of '^[0-9A-Za-z_]*$'. Need to make
115                 # our aliases compliant.
116                 parts = inter['ALIAS'].split('_')
117                 isValid=True
118                 for part in parts:
119                     isValid=isValid and part.isalnum()
120
121                 if isValid:
122                     interfaces["%s:%s" % (inter['IFNAME'],inter['ALIAS'])] = inter 
123                 else:
124                     logger.log("net:InitInterfaces WARNING: interface alias (%s) not a valid string for RH ifup-aliases"% inter['ALIAS'])
125             else:
126                 logger.log("net:InitInterfaces WARNING: interface alias (%s) not matched to an interface"% inter['ALIAS'])
127             interface -= 1
128         else:
129             if ('IFNAME' not in inter) and not orig_ifname:
130                 ifname="eth%d" % (interface-1)
131                 # should check if $ifname is an eth already defines
132                 if os.path.exists("%s/ifcfg-%s"%(sysconfig,ifname)):
133                     logger.log("net:InitInterfaces WARNING: possibly blowing away %s configuration"%ifname)
134             else:
135                 if ('IFNAME' not in inter) and orig_ifname:
136                     ifname = orig_ifname
137                 else:
138                     ifname = inter['IFNAME']
139                 interface -= 1
140             interfaces[ifname] = inter
141                 
142     m = modprobe.Modprobe()
143     try:
144         m.input("%s/etc/modprobe.conf" % root, program)
145     except:
146         pass
147     for (dev, inter) in interfaces.iteritems():
148         # get the driver string "moduleName option1=a option2=b"
149         driver=inter.get('DRIVER','')
150         if driver <> '':
151             driver=driver.split()
152             kernelmodule=driver[0]
153             m.aliasset(dev,kernelmodule)
154             options=" ".join(driver[1:])
155             if options <> '':
156                 m.optionsset(dev,options)
157     m.output("%s/etc/modprobe.conf" % root)
158
159     # clean up after any ifcfg-$dev script that's no longer listed as
160     # part of the NodeNetworks associated with this node
161
162     # list all network-scripts
163     files = os.listdir(sysconfig)
164
165     # filter out the ifcfg-* files
166     ifcfgs=[]
167     for f in files:
168         if f.find("ifcfg-") == 0:
169             ifcfgs.append(f)
170
171     # remove loopback (lo) from ifcfgs list
172     lo = "ifcfg-lo"
173     if lo in ifcfgs: ifcfgs.remove(lo)
174
175     # remove known devices from icfgs list
176     for (dev, inter) in interfaces.iteritems():
177         ifcfg = 'ifcfg-'+dev
178         if ifcfg in ifcfgs: ifcfgs.remove(ifcfg)
179
180     # delete the remaining ifcfgs from 
181     deletedSomething = False
182
183     if not failedToGetSettings:
184         for ifcfg in ifcfgs:
185             dev = ifcfg[len('ifcfg-'):]
186             path = "%s/ifcfg-%s" % (sysconfig,dev)
187             if not files_only:
188                 logger.verbose("net:InitInterfaces removing %s %s"%(dev,path))
189                 os.system("/sbin/ifdown %s" % dev)
190             deletedSomething=True
191             os.unlink(path)
192
193     # wait a bit for the one or more ifdowns to have taken effect
194     if deletedSomething:
195         time.sleep(2)
196
197     # Write network configuration file
198     networkconf = file("%s/etc/sysconfig/network" % root, "w")
199     networkconf.write("NETWORKING=yes\nHOSTNAME=%s\n" % hostname)
200     if gateway is not None:
201         networkconf.write("GATEWAY=%s\n" % gateway)
202     networkconf.close()
203
204     # Process ifcfg-$dev changes / additions
205     newdevs = []
206     for (dev, inter) in interfaces.iteritems():
207         (fd, tmpnam) = tempfile.mkstemp(dir=sysconfig)
208         f = os.fdopen(fd, "w")
209         f.write("# Autogenerated by pyplnet... do not edit!\n")
210         if 'DRIVER' in inter:
211             f.write("# using %s driver for device %s\n" % (inter['DRIVER'],dev))
212         f.write('DEVICE=%s\n' % dev)
213         
214         # print the configuration values
215         for (key, val) in inter.iteritems():
216             if key not in ('IFNAME','ALIAS','CFGOPTIONS','DRIVER'):
217                 f.write('%s=%s\n' % (key, val))
218
219         # print the configuration specific option values (if any)
220         if 'CFGOPTIONS' in inter:
221             cfgoptions = inter['CFGOPTIONS']
222             f.write('#CFGOPTIONS are %s\n' % cfgoptions)
223             for cfgoption in cfgoptions.split():
224                 key,val = cfgoption.split('=')
225                 key=key.strip()
226                 key=key.upper()
227                 val=val.strip()
228                 f.write('%s="%s"\n' % (key,val))
229         f.close()
230
231         # compare whether two files are the same
232         def comparefiles(a,b):
233             try:
234                 logger.verbose("net:InitInterfaces comparing %s with %s" % (a,b))
235                 if not os.path.exists(a): return False
236                 fb = open(a)
237                 buf_a = fb.read()
238                 fb.close()
239
240                 if not os.path.exists(b): return False
241                 fb = open(b)
242                 buf_b = fb.read()
243                 fb.close()
244
245                 return buf_a == buf_b
246             except IOError, e:
247                 return False
248
249         path = "%s/ifcfg-%s" % (sysconfig,dev)
250         if not os.path.exists(path):
251             logger.verbose('net:InitInterfaces adding configuration for %s' % dev)
252             # add ifcfg-$dev configuration file
253             os.rename(tmpnam,path)
254             os.chmod(path,0644)
255             newdevs.append(dev)
256             
257         elif not comparefiles(tmpnam,path):
258             logger.verbose('net:InitInterfaces Configuration change for %s' % dev)
259             if not files_only:
260                 logger.verbose('net:InitInterfaces ifdown %s' % dev)
261                 # invoke ifdown for the old configuration
262                 os.system("/sbin/ifdown %s" % dev)
263                 # wait a few secs for ifdown to complete
264                 time.sleep(2)
265
266             logger.log('replacing configuration for %s' % dev)
267             # replace ifcfg-$dev configuration file
268             os.rename(tmpnam,path)
269             os.chmod(path,0644)
270             newdevs.append(dev)
271         else:
272             # tmpnam & path are identical
273             os.unlink(tmpnam)
274
275     for dev in newdevs:
276         cfgvariables = {}
277         fb = file("%s/ifcfg-%s"%(sysconfig,dev),"r")
278         for line in fb.readlines():
279             parts = line.split()
280             if parts[0][0]=="#":continue
281             if parts[0].find('='):
282                 name,value = parts[0].split('=')
283                 # clean up name & value
284                 name = name.strip()
285                 value = value.strip()
286                 value = value.strip("'")
287                 value = value.strip('"')
288                 cfgvariables[name]=value
289         fb.close()
290
291         def getvar(name):
292             if name in cfgvariables:
293                 value=cfgvariables[name]
294                 value = value.lower()
295                 return value
296             return ''
297
298         # skip over device configs with ONBOOT=no
299         if getvar("ONBOOT") == 'no': continue
300
301         # don't bring up slave devices, the network scripts will
302         # handle those correctly
303         if getvar("SLAVE") == 'yes': continue
304
305         if not files_only:
306             logger.verbose('net:InitInterfaces bringing up %s' % dev)
307             os.system("/sbin/ifup %s" % dev)
308
309 if __name__ == "__main__":
310     import optparse
311     import sys
312
313     parser = optparse.OptionParser(usage="plnet [-v] [-f] [-p <program>] -r root node_id")
314     parser.add_option("-v", "--verbose", action="store_true", dest="verbose")
315     parser.add_option("-r", "--root", action="store", type="string",
316                       dest="root", default=None)
317     parser.add_option("-f", "--files-only", action="store_true",
318                       dest="files_only")
319     parser.add_option("-p", "--program", action="store", type="string",
320                       dest="program", default="plnet")
321     (options, args) = parser.parse_args()
322     if len(args) != 1 or options.root is None:
323         print >>sys.stderr, "Missing root or node_id"
324         parser.print_help()
325         sys.exit(1)
326
327     node = shell.GetNodes({'node_id': [int(args[0])]})
328     networks = shell.GetInterfaces({'interface_id': node[0]['interface_ids']})
329
330     data = {'hostname': node[0]['hostname'], 'networks': networks}
331     class logger:
332         def __init__(self, verbose):
333             self.verbosity = verbose
334         def log(self, msg, loglevel=2):
335             if self.verbosity:
336                 print msg
337         def verbose(self, msg):
338             self.log(msg, 1)
339     l = logger(options.verbose)
340     InitInterfaces(l, shell, data, options.root, options.files_only)