Use source based routing if secondary interfaces specify different gateway.
[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 global version
14 version = 4.3
15
16 def InitInterfaces(logger, plc, data, root="", files_only=False, program="NodeManager"):
17     global version
18
19     sysconfig = "%s/etc/sysconfig/network-scripts" % root
20     try:
21         os.makedirs(sysconfig)
22     except OSError, e:
23         if e.errno != errno.EEXIST:
24             raise e
25
26     # query running network interfaces
27     devs = sioc.gifconf()
28     ips = dict(zip(devs.values(), devs.keys()))
29     macs = {}
30     for dev in devs:
31         macs[sioc.gifhwaddr(dev).lower()] = dev
32
33     devices_map = {}
34     device_id = 1
35     hostname = data.get('hostname',socket.gethostname())
36     gateway = None
37     # assume data['interfaces'] contains this node's Interfaces
38     # can cope with 4.3 ('networks') or 5.0 ('interfaces')
39     try:
40         interfaces = data['interfaces']
41     except:
42         interfaces = data['networks']
43     failedToGetSettings = False
44
45     # NOTE: GetInterfaces/NodeNetworks does not necessarily order the interfaces
46     # returned.  Because 'interface'is decremented as each interface is processed,
47     # by the time is_primary=True (primary) interface is reached, the device
48     # "eth%s" % interface, is not eth0.  But, something like eth-4, or eth-12.
49     # This code sorts the interfaces, placing is_primary=True interfaces first.  
50     # There is a lot of room for improvement to how this
51     # script handles interfaces and how it chooses the primary interface.
52     def compare_by (fieldname):
53         def compare_two_dicts (a, b):
54             return cmp(a[fieldname], b[fieldname])
55         return compare_two_dicts
56
57     # NOTE: by sorting on 'is_primary' and then reversing (since False is sorted
58     # before True) all 'is_primary' interfaces are at the beginning of the list.
59     interfaces.sort( compare_by('is_primary') )
60     interfaces.reverse()
61
62     for interface in interfaces:
63         logger.verbose('net:InitInterfaces interface %d: %r'%(device_id,interface))
64         logger.verbose('net:InitInterfaces macs = %r' % macs)
65         logger.verbose('net:InitInterfaces ips = %r' % ips)
66         # Get interface name preferably from MAC address, falling back
67         # on IP address.
68         hwaddr=interface['mac']
69         if hwaddr <> None: hwaddr=hwaddr.lower()
70         if hwaddr in macs:
71             orig_ifname = macs[hwaddr]
72         elif interface['ip'] in ips:
73             orig_ifname = ips[interface['ip']]
74         else:
75             orig_ifname = None
76
77         if orig_ifname:
78             logger.verbose('net:InitInterfaces orig_ifname = %s' % orig_ifname)
79
80         details = {}
81         details['ONBOOT']='yes'
82         details['USERCTL']='no'
83         if interface['mac']:
84             details['HWADDR'] = interface['mac']
85         if interface['is_primary']:
86             details['PRIMARY']='yes'
87
88         if interface['method'] == "static":
89             details['BOOTPROTO'] = "static"
90             details['IPADDR'] = interface['ip']
91             details['NETMASK'] = interface['netmask']
92             details['GATEWAY'] = interface['gateway']
93             if interface['is_primary']:
94                 gateway = interface['gateway']
95                 if interface['dns1']:
96                     details['DNS1'] = interface['dns1']
97                 if interface['dns2']:
98                     details['DNS2'] = interface['dns2']
99
100         elif interface['method'] == "dhcp":
101             details['BOOTPROTO'] = "dhcp"
102             details['PERSISTENT_DHCLIENT'] = "yes"
103             if interface['hostname']:
104                 details['DHCP_HOSTNAME'] = interface['hostname']
105             else:
106                 details['DHCP_HOSTNAME'] = hostname 
107             if not interface['is_primary']:
108                 details['DHCLIENTARGS'] = "-R subnet-mask"
109
110         if 'interface_tag_ids' in interface:
111             version = 4.3
112             interface_tag_ids = "interface_tag_ids"
113             interface_tag_id = "interface_tag_id"
114             name_key = "tagname"
115         else:
116             version = 4.2
117             interface_tag_ids = "nodenetwork_setting_ids"
118             interface_tag_id = "nodenetwork_setting_id"
119             name_key = "name"
120
121         if len(interface[interface_tag_ids]) > 0:
122             try:
123                 if version == 4.3:
124                     settings = plc.GetInterfaceTags({interface_tag_id:interface[interface_tag_ids]})
125                 else:
126                     settings = plc.GetNodeNetworkSettings({interface_tag_id:interface[interface_tag_ids]})
127             except:
128                 logger.log("net:InitInterfaces FATAL: failed call GetInterfaceTags({'interface_tag_id':{%s})"% \
129                            interface[interface_tag_ids])
130                 failedToGetSettings = True
131                 continue # on to the next interface
132
133             for setting in settings:
134                 settingname = setting[name_key].upper()
135                 if settingname in ('IFNAME','ALIAS','CFGOPTIONS','DRIVER'):
136                     details[settingname]=setting['value']
137                 # wireless settings
138                 elif settingname in \
139                         [  "MODE", "ESSID", "NW", "FREQ", "CHANNEL", "SENS", "RATE",
140                            "KEY", "KEY1", "KEY2", "KEY3", "KEY4", "SECURITYMODE", 
141                            "IWCONFIG", "IWPRIV" ] :
142                     details [settingname] = setting['value']
143                     details ['TYPE']='Wireless'
144                 else:
145                     logger.log("net:InitInterfaces WARNING: ignored setting named %s"%setting[name_key])
146
147         # support aliases to interfaces either by name or HWADDR
148         if 'ALIAS' in details:
149             if 'HWADDR' in details:
150                 hwaddr = details['HWADDR'].lower()
151                 del details['HWADDR']
152                 if hwaddr in macs:
153                     hwifname = macs[hwaddr]
154                     if ('IFNAME' in details) and details['IFNAME'] <> hwifname:
155                         logger.log("net:InitInterfaces WARNING: alias ifname (%s) and hwaddr ifname (%s) do not match"%\
156                                        (details['IFNAME'],hwifname))
157                         details['IFNAME'] = hwifname
158                 else:
159                     logger.log('net:InitInterfaces WARNING: mac addr %s for alias not found' %(hwaddr))
160
161             if 'IFNAME' in details:
162                 # stupid RH /etc/sysconfig/network-scripts/ifup-aliases:new_interface()
163                 # checks if the "$DEVNUM" only consists of '^[0-9A-Za-z_]*$'. Need to make
164                 # our aliases compliant.
165                 parts = details['ALIAS'].split('_')
166                 isValid=True
167                 for part in parts:
168                     isValid=isValid and part.isalnum()
169
170                 if isValid:
171                     devices_map["%s:%s" % (details['IFNAME'],details['ALIAS'])] = details 
172                 else:
173                     logger.log("net:InitInterfaces WARNING: interface alias (%s) not a valid string for RH ifup-aliases"% details['ALIAS'])
174             else:
175                 logger.log("net:InitInterfaces WARNING: interface alias (%s) not matched to an interface"% details['ALIAS'])
176             device_id -= 1
177         else:
178             if 'IFNAME' in details:
179                 ifname = details['IFNAME']
180                 device_id -= 1
181             elif orig_ifname:
182                 ifname = orig_ifname
183                 device_id -= 1
184             else:
185                 while True:
186                     ifname="eth%d" % (device_id-1)
187                     if ifname not in devices_map:
188                         break
189                     device_id += 1
190                 if os.path.exists("%s/ifcfg-%s"%(sysconfig,ifname)):
191                     logger.log("net:InitInterfaces WARNING: possibly blowing away %s configuration"%ifname)
192             devices_map[ifname] = details
193         device_id += 1 
194     m = modprobe.Modprobe()
195     try:
196         m.input("%s/etc/modprobe.conf" % root)
197     except:
198         pass
199     for (dev, details) in devices_map.iteritems():
200         # get the driver string "moduleName option1=a option2=b"
201         driver=details.get('DRIVER','')
202         if driver <> '':
203             driver=driver.split()
204             kernelmodule=driver[0]
205             m.aliasset(dev,kernelmodule)
206             options=" ".join(driver[1:])
207             if options <> '':
208                 m.optionsset(dev,options)
209     m.output("%s/etc/modprobe.conf" % root, program)
210
211     # clean up after any ifcfg-$dev script that's no longer listed as
212     # part of the Interfaces associated with this node
213
214     # list all network-scripts
215     files = os.listdir(sysconfig)
216
217     # filter out the ifcfg-* files
218     ifcfgs=[]
219     for f in files:
220         if f.find("ifcfg-") == 0:
221             ifcfgs.append(f)
222
223     # remove loopback (lo) from ifcfgs list
224     lo = "ifcfg-lo"
225     if lo in ifcfgs: ifcfgs.remove(lo)
226
227     # remove known devices from icfgs list
228     for (dev, details) in devices_map.iteritems():
229         ifcfg = 'ifcfg-'+dev
230         if ifcfg in ifcfgs: ifcfgs.remove(ifcfg)
231
232     # delete the remaining ifcfgs from 
233     deletedSomething = False
234
235     if not failedToGetSettings:
236         for ifcfg in ifcfgs:
237             dev = ifcfg[len('ifcfg-'):]
238             path = "%s/ifcfg-%s" % (sysconfig,dev)
239             if not files_only:
240                 logger.verbose("net:InitInterfaces removing %s %s"%(dev,path))
241                 os.system("/sbin/ifdown %s" % dev)
242             deletedSomething=True
243             os.unlink(path)
244
245     # wait a bit for the one or more ifdowns to have taken effect
246     if deletedSomething:
247         time.sleep(2)
248
249     # Write network configuration file
250     networkconf = file("%s/etc/sysconfig/network" % root, "w")
251     networkconf.write("NETWORKING=yes\nHOSTNAME=%s\n" % hostname)
252     if gateway is not None:
253         networkconf.write("GATEWAY=%s\n" % gateway)
254     networkconf.close()
255
256     # Process ifcfg-$dev changes / additions
257     newdevs = []
258     for (dev, details) in devices_map.iteritems():
259         (fd, tmpnam) = tempfile.mkstemp(dir=sysconfig)
260         f = os.fdopen(fd, "w")
261         f.write("# Autogenerated by pyplnet... do not edit!\n")
262         if 'DRIVER' in details:
263             f.write("# using %s driver for device %s\n" % (details['DRIVER'],dev))
264         f.write('DEVICE=%s\n' % dev)
265         
266         # print the configuration values
267         for (key, val) in details.iteritems():
268             if key not in ('IFNAME','ALIAS','CFGOPTIONS','DRIVER'):
269                 f.write('%s=%s\n' % (key, val))
270
271         # print the configuration specific option values (if any)
272         if 'CFGOPTIONS' in details:
273             cfgoptions = details['CFGOPTIONS']
274             f.write('#CFGOPTIONS are %s\n' % cfgoptions)
275             for cfgoption in cfgoptions.split():
276                 key,val = cfgoption.split('=')
277                 key=key.strip()
278                 key=key.upper()
279                 val=val.strip()
280                 f.write('%s="%s"\n' % (key,val))
281         f.close()
282         os.close(fd)
283
284         # compare whether two files are the same
285         def comparefiles(a,b):
286             try:
287                 logger.verbose("net:InitInterfaces comparing %s with %s" % (a,b))
288                 if not os.path.exists(a): return False
289                 fb = open(a)
290                 buf_a = fb.read()
291                 fb.close()
292
293                 if not os.path.exists(b): return False
294                 fb = open(b)
295                 buf_b = fb.read()
296                 fb.close()
297
298                 return buf_a == buf_b
299             except IOError, e:
300                 return False
301
302         src_route_changed = False
303         if ('PRIMARY' not in details and 'GATEWAY' in details and
304             details['GATEWAY'] != ''):
305             i = len(dev) - 1
306             while dev[i - 1].isdigit():
307                 i -= 1
308             table = 10 + int(dev[i:])
309             (fd, rule_tmpnam) = tempfile.mkstemp(dir=sysconfig)
310             os.write(fd, "from %s lookup %d\n" % (details['IPADDR'], table))
311             os.close(fd)
312             rule_dest = "%s/rule-%s" % (sysconfig, dev)
313             if not comparefiles(rule_tmpnam, rule_dest):
314                 os.unlink(rule_dest)
315                 os.rename(rule_tmpnam, rule_dest)
316                 os.chmod(0644, rule_dest)
317                 src_route_changed = True
318             else:
319                 os.unlink(rule_tmpnam)
320             (fd, route_tmpnam) = tempfile.mkstemp(dir=sysconfig)
321             netmask = struct.unpack("I", socket.inet_aton(details['NETMASK']))[0]
322             ip = struct.unpack("I", socket.inet_aton(details['IPADDR']))[0]
323             network = socket.inet_ntoa(struct.pack("I", (ip & netmask)))
324             netmask = socket.ntohl(netmask)
325             i = 0
326             while (netmask & (1 << i)) == 0:
327                 i += 1
328             prefix = 32 - i
329             os.write(fd, "%s/%d dev %s table %d\n" % (network, prefix, dev, table))
330             os.write(fd, "default via %s dev %s table %d\n" % (details['GATEWAY'], dev, table))
331             os.close(fd)
332             route_dest = "%s/route-%s" % (sysconfig, dev)
333             if not comparefiles(route_tmpnam, route_dest):
334                 os.unlink(route_dest)
335                 os.rename(route_tmpnam, route_dest)
336                 os.chmod(0644, route_dest)
337                 src_route_changed = True
338             else:
339                 os.unlink(route_tmpnam)
340
341         path = "%s/ifcfg-%s" % (sysconfig,dev)
342         if not os.path.exists(path):
343             logger.verbose('net:InitInterfaces adding configuration for %s' % dev)
344             # add ifcfg-$dev configuration file
345             os.rename(tmpnam,path)
346             os.chmod(path,0644)
347             newdevs.append(dev)
348             
349         elif not comparefiles(tmpnam,path) or src_route_changed:
350             logger.verbose('net:InitInterfaces Configuration change for %s' % dev)
351             if not files_only:
352                 logger.verbose('net:InitInterfaces ifdown %s' % dev)
353                 # invoke ifdown for the old configuration
354                 os.system("/sbin/ifdown %s" % dev)
355                 # wait a few secs for ifdown to complete
356                 time.sleep(2)
357
358             logger.log('replacing configuration for %s' % dev)
359             # replace ifcfg-$dev configuration file
360             os.rename(tmpnam,path)
361             os.chmod(path,0644)
362             newdevs.append(dev)
363         else:
364             # tmpnam & path are identical
365             os.unlink(tmpnam)
366
367     for dev in newdevs:
368         cfgvariables = {}
369         fb = file("%s/ifcfg-%s"%(sysconfig,dev),"r")
370         for line in fb.readlines():
371             parts = line.split()
372             if parts[0][0]=="#":continue
373             if parts[0].find('='):
374                 name,value = parts[0].split('=')
375                 # clean up name & value
376                 name = name.strip()
377                 value = value.strip()
378                 value = value.strip("'")
379                 value = value.strip('"')
380                 cfgvariables[name]=value
381         fb.close()
382
383         def getvar(name):
384             if name in cfgvariables:
385                 value=cfgvariables[name]
386                 value = value.lower()
387                 return value
388             return ''
389
390         # skip over device configs with ONBOOT=no
391         if getvar("ONBOOT") == 'no': continue
392
393         # don't bring up slave devices, the network scripts will
394         # handle those correctly
395         if getvar("SLAVE") == 'yes': continue
396
397         if not files_only:
398             logger.verbose('net:InitInterfaces bringing up %s' % dev)
399             os.system("/sbin/ifup %s" % dev)
400
401 if __name__ == "__main__":
402     import optparse
403     import sys
404
405     parser = optparse.OptionParser(usage="plnet [-v] [-f] [-p <program>] -r root node_id")
406     parser.add_option("-v", "--verbose", action="store_true", dest="verbose")
407     parser.add_option("-r", "--root", action="store", type="string",
408                       dest="root", default=None)
409     parser.add_option("-f", "--files-only", action="store_true",
410                       dest="files_only")
411     parser.add_option("-p", "--program", action="store", type="string",
412                       dest="program", default="plnet")
413     (options, args) = parser.parse_args()
414     if len(args) != 1 or options.root is None:
415         print >>sys.stderr, "Missing root or node_id"
416         parser.print_help()
417         sys.exit(1)
418
419     node = shell.GetNodes({'node_id': [int(args[0])]})
420     try:
421         interfaces = shell.GetInterfaces({'interface_id': node[0]['interface_ids']})
422     except AttributeError:
423         interfaces = shell.GetNodeNetworks({'nodenetwork_id':node[0]['nodenetwork_ids']})
424         version = 4.2
425
426
427     data = {'hostname': node[0]['hostname'], 'interfaces': interfaces}
428     class logger:
429         def __init__(self, verbose):
430             self.verbosity = verbose
431         def log(self, msg, loglevel=2):
432             if self.verbosity:
433                 print msg
434         def verbose(self, msg):
435             self.log(msg, 1)
436     l = logger(options.verbose)
437     InitInterfaces(l, shell, data, options.root, options.files_only)