1 #!/usr/bin/python /usr/bin/plcsh
17 def ovs_check(logger):
18 """ Return True if openvswitch is running, False otherwise. Try restarting
21 rc = os.system("service openvswitch status")
23 logger.log("net: restarting openvswitch")
24 rc = os.system("service openvswitch restart")
25 rc = os.system("service openvswitch status")
27 logger.log("net: failed to restart openvswitch")
31 def InitInterfaces(logger, plc, data, root="", files_only=False, program="NodeManager"):
34 sysconfig = "%s/etc/sysconfig/network-scripts" % root
36 os.makedirs(sysconfig)
38 if e.errno != errno.EEXIST:
41 # query running network interfaces
43 ips = dict(zip(devs.values(), devs.keys()))
46 macs[sioc.gifhwaddr(dev).lower()] = dev
50 hostname = data.get('hostname',socket.gethostname())
52 # assume data['interfaces'] contains this node's Interfaces
53 # can cope with 4.3 ('networks') or 5.0 ('interfaces')
55 interfaces = data['interfaces']
57 interfaces = data['networks']
58 failedToGetSettings = False
60 # NOTE: GetInterfaces/NodeNetworks does not necessarily order the interfaces
61 # returned. Because 'interface' is decremented as each interface is processed,
62 # by the time is_primary=True (primary) interface is reached, the device
63 # "eth%s" % interface, is not eth0. But, something like eth-4, or eth-12.
64 # This code sorts the interfaces, placing is_primary=True interfaces first.
65 # There is a lot of room for improvement to how this
66 # script handles interfaces and how it chooses the primary interface.
67 def compare_by (fieldname):
68 def compare_two_dicts (a, b):
69 return cmp(a[fieldname], b[fieldname])
70 return compare_two_dicts
72 # NOTE: by sorting on 'is_primary' and then reversing (since False is sorted
73 # before True) all 'is_primary' interfaces are at the beginning of the list.
74 interfaces.sort( compare_by('is_primary') )
77 # The names of the bridge devices
80 for interface in interfaces:
81 logger.verbose('net:InitInterfaces interface %d: %r'%(device_id,interface))
82 logger.verbose('net:InitInterfaces macs = %r' % macs)
83 logger.verbose('net:InitInterfaces ips = %r' % ips)
84 # Get interface name preferably from MAC address, falling back
86 hwaddr=interface['mac']
87 if hwaddr <> None: hwaddr=hwaddr.lower()
89 orig_ifname = macs[hwaddr]
90 elif interface['ip'] in ips:
91 orig_ifname = ips[interface['ip']]
96 logger.verbose('net:InitInterfaces orig_ifname = %s' % orig_ifname)
98 details = prepDetails(interface, hostname)
100 if interface['is_primary']:
101 gateway = interface['gateway']
103 if 'interface_tag_ids' in interface:
105 interface_tag_ids = "interface_tag_ids"
106 interface_tag_id = "interface_tag_id"
110 interface_tag_ids = "nodenetwork_setting_ids"
111 interface_tag_id = "nodenetwork_setting_id"
114 if len(interface[interface_tag_ids]) > 0:
117 settings = plc.GetInterfaceTags({interface_tag_id:interface[interface_tag_ids]})
119 settings = plc.GetNodeNetworkSettings({interface_tag_id:interface[interface_tag_ids]})
121 logger.log("net:InitInterfaces FATAL: failed call GetInterfaceTags({'interface_tag_id':{%s})"% \
122 interface[interface_tag_ids])
123 failedToGetSettings = True
124 continue # on to the next interface
126 for setting in settings:
127 settingname = setting[name_key].upper()
128 if ((settingname in ('IFNAME','ALIAS','CFGOPTIONS','DRIVER','VLAN','TYPE','DEVICETYPE')) or \
129 (re.search('^IPADDR[0-9]+$|^NETMASK[0-9]+$', settingname))):
130 # TD: Added match for secondary IPv4 configuration.
131 details[settingname]=setting['value']
132 # IPv6 support on IPv4 interface
133 elif settingname in ('IPV6ADDR','IPV6_DEFAULTGW','IPV6ADDR_SECONDARIES', 'IPV6_AUTOCONF'):
134 # TD: Added IPV6_AUTOCONF.
135 details[settingname]=setting['value']
136 details['IPV6INIT']='yes'
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'
145 elif settingname in [ 'BRIDGE' ]:
146 details['BRIDGE'] = setting['value']
147 elif settingname in [ 'OVS_BRIDGE' ]:
148 # If openvswitch isn't running, then we'll lose network
149 # connectivity when we reconfigure eth0.
150 if ovs_check(logger):
151 details['OVS_BRIDGE'] = setting['value']
152 details['TYPE'] = "OVSPort"
153 details['DEVICETYPE'] = "ovs"
155 logger.log("net:InitInterfaces ERROR: OVS_BRIDGE specified, yet ovs is not running")
157 logger.log("net:InitInterfaces WARNING: ignored setting named %s"%setting[name_key])
159 # support aliases to interfaces either by name or HWADDR
160 if 'ALIAS' in details:
161 if 'HWADDR' in details:
162 hwaddr = details['HWADDR'].lower()
163 del details['HWADDR']
165 hwifname = macs[hwaddr]
166 if ('IFNAME' in details) and details['IFNAME'] <> hwifname:
167 logger.log("net:InitInterfaces WARNING: alias ifname (%s) and hwaddr ifname (%s) do not match"%\
168 (details['IFNAME'],hwifname))
169 details['IFNAME'] = hwifname
171 logger.log('net:InitInterfaces WARNING: mac addr %s for alias not found' %(hwaddr))
173 if 'IFNAME' in details:
174 # stupid RH /etc/sysconfig/network-scripts/ifup-aliases:new_interface()
175 # checks if the "$DEVNUM" only consists of '^[0-9A-Za-z_]*$'. Need to make
176 # our aliases compliant.
177 parts = details['ALIAS'].split('_')
180 isValid=isValid and part.isalnum()
183 devices_map["%s:%s" % (details['IFNAME'],details['ALIAS'])] = details
185 logger.log("net:InitInterfaces WARNING: interface alias (%s) not a valid string for RH ifup-aliases"% details['ALIAS'])
187 logger.log("net:InitInterfaces WARNING: interface alias (%s) not matched to an interface"% details['ALIAS'])
189 elif ('BRIDGE' in details or 'OVS_BRIDGE' in details) and 'IFNAME' in details:
190 # The bridge inherits the mac of the first attached interface.
191 ifname = details['IFNAME']
193 if 'BRIDGE' in details:
194 bridgeName = details['BRIDGE']
195 bridgeType = 'Bridge'
197 bridgeName = details['OVS_BRIDGE']
198 bridgeType = 'OVSBridge'
200 logger.log('net:InitInterfaces: %s detected. Adding %s to devices_map' % (bridgeType, ifname))
201 devices_map[ifname] = removeBridgedIfaceDetails(details)
203 logger.log('net:InitInterfaces: Adding %s %s' % (bridgeType, bridgeName))
204 bridgeDetails = prepDetails(interface)
206 # TD: Add configuration for secondary IPv4 and IPv6 addresses to the bridge.
207 if len(interface[interface_tag_ids]) > 0:
210 settings = plc.GetInterfaceTags({interface_tag_id:interface[interface_tag_ids]})
212 settings = plc.GetNodeNetworkSettings({interface_tag_id:interface[interface_tag_ids]})
214 logger.log("net:InitInterfaces FATAL: failed call GetInterfaceTags({'interface_tag_id':{%s})"% \
215 interface[interface_tag_ids])
216 failedToGetSettings = True
217 continue # on to the next interface
219 for setting in settings:
220 settingname = setting[name_key].upper()
221 if (re.search('^IPADDR[0-9]+$|^NETMASK[0-9]+$', settingname)):
222 # TD: Added match for secondary IPv4 configuration.
223 bridgeDetails[settingname]=setting['value']
224 # IPv6 support on IPv4 interface
225 elif settingname in ('IPV6ADDR','IPV6_DEFAULTGW','IPV6ADDR_SECONDARIES', 'IPV6_AUTOCONF'):
226 # TD: Added IPV6_AUTOCONF.
227 bridgeDetails[settingname]=setting['value']
228 bridgeDetails['IPV6INIT']='yes'
230 bridgeDevices.append(bridgeName)
231 bridgeDetails['TYPE'] = bridgeType
232 if bridgeType == 'OVSBridge':
233 bridgeDetails['DEVICETYPE'] = 'ovs'
234 if bridgeDetails['BOOTPROTO'] == 'dhcp':
235 del bridgeDetails['BOOTPROTO']
236 bridgeDetails['OVSBOOTPROTO'] = 'dhcp'
237 bridgeDetails['OVSDHCPINTERFACES'] = ifname
238 devices_map[bridgeName] = bridgeDetails
240 if 'IFNAME' in details:
241 ifname = details['IFNAME']
248 ifname="eth%d" % (device_id-1)
249 if ifname not in devices_map:
252 if os.path.exists("%s/ifcfg-%s"%(sysconfig,ifname)):
253 logger.log("net:InitInterfaces WARNING: possibly blowing away %s configuration"%ifname)
254 devices_map[ifname] = details
256 logger.log('net:InitInterfaces: Device map: %r' % devices_map)
257 m = modprobe.Modprobe()
259 m.input("%s/etc/modprobe.conf" % root)
262 for (dev, details) in devices_map.iteritems():
263 # get the driver string "moduleName option1=a option2=b"
264 driver=details.get('DRIVER','')
266 driver=driver.split()
267 kernelmodule=driver[0]
268 m.aliasset(dev,kernelmodule)
269 options=" ".join(driver[1:])
271 m.optionsset(dev,options)
272 m.output("%s/etc/modprobe.conf" % root, program)
274 # clean up after any ifcfg-$dev script that's no longer listed as
275 # part of the Interfaces associated with this node
277 # list all network-scripts
278 files = os.listdir(sysconfig)
280 # filter out the ifcfg-* files
283 if f.find("ifcfg-") == 0:
286 # remove loopback (lo) from ifcfgs list
288 if lo in ifcfgs: ifcfgs.remove(lo)
290 # remove known devices from ifcfgs list
291 for (dev, details) in devices_map.iteritems():
293 if ifcfg in ifcfgs: ifcfgs.remove(ifcfg)
295 # delete the remaining ifcfgs from
296 deletedSomething = False
298 if not failedToGetSettings:
300 dev = ifcfg[len('ifcfg-'):]
301 path = "%s/ifcfg-%s" % (sysconfig,dev)
303 logger.verbose("net:InitInterfaces removing %s %s"%(dev,path))
304 os.system("/sbin/ifdown %s" % dev)
305 deletedSomething=True
308 # wait a bit for the one or more ifdowns to have taken effect
312 # Write network configuration file
313 networkconf = file("%s/etc/sysconfig/network" % root, "w")
314 networkconf.write("NETWORKING=yes\nHOSTNAME=%s\n" % hostname)
315 if gateway is not None:
316 networkconf.write("GATEWAY=%s\n" % gateway)
319 # Process ifcfg-$dev changes / additions
322 for (dev, details) in devices_map.iteritems():
323 (fd, tmpnam) = tempfile.mkstemp(dir=sysconfig)
324 f = os.fdopen(fd, "w")
325 f.write("# Autogenerated by pyplnet... do not edit!\n")
326 if 'DRIVER' in details:
327 f.write("# using %s driver for device %s\n" % (details['DRIVER'],dev))
328 f.write('DEVICE=%s\n' % dev)
330 # print the configuration values
331 for (key, val) in details.iteritems():
332 if key not in ('IFNAME','ALIAS','CFGOPTIONS','DRIVER','GATEWAY'):
333 f.write('%s="%s"\n' % (key, val))
335 # print the configuration specific option values (if any)
336 if 'CFGOPTIONS' in details:
337 cfgoptions = details['CFGOPTIONS']
338 f.write('#CFGOPTIONS are %s\n' % cfgoptions)
339 for cfgoption in cfgoptions.split():
340 key,val = cfgoption.split('=')
344 f.write('%s="%s"\n' % (key,val))
347 # compare whether two files are the same
348 def comparefiles(a,b):
350 logger.verbose("net:InitInterfaces comparing %s with %s" % (a,b))
351 if not os.path.exists(a): return False
356 if not os.path.exists(b): return False
361 return buf_a == buf_b
365 src_route_changed = False
366 if ('PRIMARY' not in details and 'GATEWAY' in details and
367 details['GATEWAY'] != ''):
369 (fd, rule_tmpnam) = tempfile.mkstemp(dir=sysconfig)
370 os.write(fd, "from %s lookup %d\n" % (details['IPADDR'], table))
372 rule_dest = "%s/rule-%s" % (sysconfig, dev)
373 if not comparefiles(rule_tmpnam, rule_dest):
374 os.rename(rule_tmpnam, rule_dest)
375 os.chmod(rule_dest, 0644)
376 src_route_changed = True
378 os.unlink(rule_tmpnam)
379 (fd, route_tmpnam) = tempfile.mkstemp(dir=sysconfig)
380 netmask = struct.unpack("I", socket.inet_aton(details['NETMASK']))[0]
381 ip = struct.unpack("I", socket.inet_aton(details['IPADDR']))[0]
382 network = socket.inet_ntoa(struct.pack("I", (ip & netmask)))
383 netmask = socket.ntohl(netmask)
385 while (netmask & (1 << i)) == 0:
388 os.write(fd, "%s/%d dev %s table %d\n" % (network, prefix, dev, table))
389 os.write(fd, "default via %s dev %s table %d\n" % (details['GATEWAY'], dev, table))
391 route_dest = "%s/route-%s" % (sysconfig, dev)
392 if not comparefiles(route_tmpnam, route_dest):
393 os.rename(route_tmpnam, route_dest)
394 os.chmod(route_dest, 0644)
395 src_route_changed = True
397 os.unlink(route_tmpnam)
399 path = "%s/ifcfg-%s" % (sysconfig,dev)
400 if not os.path.exists(path):
401 logger.verbose('net:InitInterfaces adding configuration for %s' % dev)
402 # add ifcfg-$dev configuration file
403 os.rename(tmpnam,path)
407 elif not comparefiles(tmpnam,path) or src_route_changed:
408 logger.verbose('net:InitInterfaces Configuration change for %s' % dev)
410 logger.verbose('net:InitInterfaces ifdown %s' % dev)
411 # invoke ifdown for the old configuration
412 os.system("/sbin/ifdown %s" % dev)
413 # wait a few secs for ifdown to complete
416 logger.log('replacing configuration for %s' % dev)
417 # replace ifcfg-$dev configuration file
418 os.rename(tmpnam,path)
422 # tmpnam & path are identical
427 fb = file("%s/ifcfg-%s"%(sysconfig,dev),"r")
428 for line in fb.readlines():
430 if parts[0][0]=="#":continue
431 if parts[0].find('='):
432 name,value = parts[0].split('=')
433 # clean up name & value
435 value = value.strip()
436 value = value.strip("'")
437 value = value.strip('"')
438 cfgvariables[name]=value
442 if name in cfgvariables:
443 value=cfgvariables[name]
444 value = value.lower()
448 # skip over device configs with ONBOOT=no
449 if getvar("ONBOOT") == 'no': continue
451 # don't bring up slave devices, the network scripts will
452 # handle those correctly
453 if getvar("SLAVE") == 'yes': continue
455 # Delay bringing up any bridge devices
456 if dev in bridgeDevices: continue
459 logger.verbose('net:InitInterfaces bringing up %s' % dev)
460 os.system("/sbin/ifup %s" % dev)
462 # Bring up the bridge devices
463 for bridge in bridgeDevices:
464 if not files_only and bridge in newdevs:
465 logger.verbose('net:InitInterfaces bringing up bridge %s' % bridge)
466 os.system("/sbin/ifup %s" % bridge)
469 # Prepare the interface details.
471 def prepDetails(interface, hostname=''):
473 details['ONBOOT'] = 'yes'
474 details['USERCTL'] = 'no'
476 details['HWADDR'] = interface['mac']
477 if interface['is_primary']:
478 details['PRIMARY'] = 'yes'
480 if interface['method'] == "static":
481 details['BOOTPROTO'] = "static"
482 details['IPADDR'] = interface['ip']
483 details['NETMASK'] = interface['netmask']
484 details['GATEWAY'] = interface['gateway']
485 if interface['is_primary']:
486 if interface['dns1']:
487 details['DNS1'] = interface['dns1']
488 if interface['dns2']:
489 details['DNS2'] = interface['dns2']
491 elif interface['method'] == "dhcp":
492 details['BOOTPROTO'] = "dhcp"
493 details['PERSISTENT_DHCLIENT'] = "yes"
494 if interface['hostname']:
495 details['DHCP_HOSTNAME'] = interface['hostname']
497 details['DHCP_HOSTNAME'] = hostname
498 if not interface['is_primary']:
499 details['DHCLIENTARGS'] = "-R subnet-mask"
504 # Remove duplicate entry from the bridged interface's configuration file.
506 def removeBridgedIfaceDetails(details):
507 # TD: Also added secondary IPv4 keys and IPv6 keys to the keys to be removed.
508 allKeys = [ 'PRIMARY', 'PERSISTENT_DHCLIENT', 'DHCLIENTARGS', 'DHCP_HOSTNAME',
509 'BOOTPROTO', 'IPADDR', 'NETMASK', 'GATEWAY', 'DNS1', 'DNS2',
510 'IPV6ADDR', 'IPV6_DEFAULTGW', 'IPV6ADDR_SECONDARIES',
511 'IPV6_AUTOCONF', 'IPV6INIT' ]
512 for i in range(1, 256):
513 allKeys.append('IPADDR' + str(i))
514 allKeys.append('NETMASK' + str(i))
520 # TD: Also turn off IPv6
521 details['IPV6INIT'] = 'no'
522 details['IPV6_AUTOCONF'] = 'no'
526 if __name__ == "__main__":
530 parser = optparse.OptionParser(usage="plnet [-v] [-f] [-p <program>] -r root node_id")
531 parser.add_option("-v", "--verbose", action="store_true", dest="verbose")
532 parser.add_option("-r", "--root", action="store", type="string",
533 dest="root", default=None)
534 parser.add_option("-f", "--files-only", action="store_true",
536 parser.add_option("-p", "--program", action="store", type="string",
537 dest="program", default="plnet")
538 (options, args) = parser.parse_args()
539 if len(args) != 1 or options.root is None:
541 print >>sys.stderr, "Missing root or node_id"
545 node = shell.GetNodes({'node_id': [int(args[0])]})
547 interfaces = shell.GetInterfaces({'interface_id': node[0]['interface_ids']})
548 except AttributeError:
549 interfaces = shell.GetNodeNetworks({'nodenetwork_id':node[0]['nodenetwork_ids']})
553 data = {'hostname': node[0]['hostname'], 'interfaces': interfaces}
555 def __init__(self, verbose):
556 self.verbosity = verbose
557 def log(self, msg, loglevel=2):
560 def verbose(self, msg):
562 l = logger(options.verbose)
563 InitInterfaces(l, shell, data, options.root, options.files_only)