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