1 #!/usr/bin/python /usr/bin/plcsh
16 def ovs_check(logger):
17 """ Return True if openvswitch is running, False otherwise. Try restarting
20 rc = os.system("service openvswitch status")
22 logger.log("net: restarting openvswitch")
23 rc = os.system("service openvswitch restart")
24 rc = os.system("service openvswitch status")
26 logger.log("net: failed to restart openvswitch")
30 def InitInterfaces(logger, plc, data, root="", files_only=False, program="NodeManager"):
33 sysconfig = "%s/etc/sysconfig/network-scripts" % root
35 os.makedirs(sysconfig)
37 if e.errno != errno.EEXIST:
40 # query running network interfaces
42 ips = dict(zip(devs.values(), devs.keys()))
45 macs[sioc.gifhwaddr(dev).lower()] = dev
49 hostname = data.get('hostname',socket.gethostname())
51 # assume data['interfaces'] contains this node's Interfaces
52 # can cope with 4.3 ('networks') or 5.0 ('interfaces')
54 interfaces = data['interfaces']
56 interfaces = data['networks']
57 failedToGetSettings = False
59 # NOTE: GetInterfaces/NodeNetworks does not necessarily order the interfaces
60 # returned. Because 'interface' is decremented as each interface is processed,
61 # by the time is_primary=True (primary) interface is reached, the device
62 # "eth%s" % interface, is not eth0. But, something like eth-4, or eth-12.
63 # This code sorts the interfaces, placing is_primary=True interfaces first.
64 # There is a lot of room for improvement to how this
65 # script handles interfaces and how it chooses the primary interface.
66 def compare_by (fieldname):
67 def compare_two_dicts (a, b):
68 return cmp(a[fieldname], b[fieldname])
69 return compare_two_dicts
71 # NOTE: by sorting on 'is_primary' and then reversing (since False is sorted
72 # before True) all 'is_primary' interfaces are at the beginning of the list.
73 interfaces.sort( compare_by('is_primary') )
76 # The names of the bridge devices
79 for interface in interfaces:
80 logger.verbose('net:InitInterfaces interface %d: %r'%(device_id,interface))
81 logger.verbose('net:InitInterfaces macs = %r' % macs)
82 logger.verbose('net:InitInterfaces ips = %r' % ips)
83 # Get interface name preferably from MAC address, falling back
85 hwaddr=interface['mac']
86 if hwaddr <> None: hwaddr=hwaddr.lower()
88 orig_ifname = macs[hwaddr]
89 elif interface['ip'] in ips:
90 orig_ifname = ips[interface['ip']]
95 logger.verbose('net:InitInterfaces orig_ifname = %s' % orig_ifname)
97 details = prepDetails(interface, hostname)
99 if interface['is_primary']:
100 gateway = interface['gateway']
102 if 'interface_tag_ids' in interface:
104 interface_tag_ids = "interface_tag_ids"
105 interface_tag_id = "interface_tag_id"
109 interface_tag_ids = "nodenetwork_setting_ids"
110 interface_tag_id = "nodenetwork_setting_id"
113 if len(interface[interface_tag_ids]) > 0:
116 settings = plc.GetInterfaceTags({interface_tag_id:interface[interface_tag_ids]})
118 settings = plc.GetNodeNetworkSettings({interface_tag_id:interface[interface_tag_ids]})
120 logger.log("net:InitInterfaces FATAL: failed call GetInterfaceTags({'interface_tag_id':{%s})"% \
121 interface[interface_tag_ids])
122 failedToGetSettings = True
123 continue # on to the next interface
125 for setting in settings:
126 settingname = setting[name_key].upper()
127 if settingname in ('IFNAME','ALIAS','CFGOPTIONS','DRIVER','VLAN','TYPE','DEVICETYPE'):
128 details[settingname]=setting['value']
129 # IPv6 support on IPv4 interface
130 elif settingname in ('IPV6ADDR','IPV6_DEFAULTGW','IPV6ADDR_SECONDARIES'):
131 details[settingname]=setting['value']
132 details['IPV6INIT']='yes'
134 elif settingname in \
135 [ "MODE", "ESSID", "NW", "FREQ", "CHANNEL", "SENS", "RATE",
136 "KEY", "KEY1", "KEY2", "KEY3", "KEY4", "SECURITYMODE",
137 "IWCONFIG", "IWPRIV" ] :
138 details [settingname] = setting['value']
139 details ['TYPE']='Wireless'
141 elif settingname in [ 'BRIDGE' ]:
142 details['BRIDGE'] = setting['value']
143 elif settingname in [ 'OVS_BRIDGE' ]:
144 # If openvswitch isn't running, then we'll lose network
145 # connectivity when we reconfigure eth0.
146 if ovs_check(logger):
147 details['OVS_BRIDGE'] = setting['value']
148 details['TYPE'] = "OVSPort"
149 details['DEVICETYPE'] = "ovs"
151 logger.log("net:InitInterfaces ERROR: OVS_BRIDGE specified, yet ovs is not running")
153 logger.log("net:InitInterfaces WARNING: ignored setting named %s"%setting[name_key])
155 # support aliases to interfaces either by name or HWADDR
156 if 'ALIAS' in details:
157 if 'HWADDR' in details:
158 hwaddr = details['HWADDR'].lower()
159 del details['HWADDR']
161 hwifname = macs[hwaddr]
162 if ('IFNAME' in details) and details['IFNAME'] <> hwifname:
163 logger.log("net:InitInterfaces WARNING: alias ifname (%s) and hwaddr ifname (%s) do not match"%\
164 (details['IFNAME'],hwifname))
165 details['IFNAME'] = hwifname
167 logger.log('net:InitInterfaces WARNING: mac addr %s for alias not found' %(hwaddr))
169 if 'IFNAME' in details:
170 # stupid RH /etc/sysconfig/network-scripts/ifup-aliases:new_interface()
171 # checks if the "$DEVNUM" only consists of '^[0-9A-Za-z_]*$'. Need to make
172 # our aliases compliant.
173 parts = details['ALIAS'].split('_')
176 isValid=isValid and part.isalnum()
179 devices_map["%s:%s" % (details['IFNAME'],details['ALIAS'])] = details
181 logger.log("net:InitInterfaces WARNING: interface alias (%s) not a valid string for RH ifup-aliases"% details['ALIAS'])
183 logger.log("net:InitInterfaces WARNING: interface alias (%s) not matched to an interface"% details['ALIAS'])
185 elif ('BRIDGE' in details or 'OVS_BRIDGE' in details) and 'IFNAME' in details:
186 # The bridge inherits the mac of the first attached interface.
187 ifname = details['IFNAME']
189 if 'BRIDGE' in details:
190 bridgeName = details['BRIDGE']
191 bridgeType = 'Bridge'
193 bridgeName = details['OVS_BRIDGE']
194 bridgeType = 'OVSBridge'
196 logger.log('net:InitInterfaces: %s detected. Adding %s to devices_map' % (bridgeType, ifname))
197 devices_map[ifname] = removeBridgedIfaceDetails(details)
199 logger.log('net:InitInterfaces: Adding %s %s' % (bridgeType, bridgeName))
200 bridgeDetails = prepDetails(interface)
201 bridgeDevices.append(bridgeName)
202 bridgeDetails['TYPE'] = bridgeType
203 if bridgeType == 'OVSBridge':
204 bridgeDetails['DEVICETYPE'] = 'ovs'
205 if bridgeDetails['BOOTPROTO'] == 'dhcp':
206 del bridgeDetails['BOOTPROTO']
207 bridgeDetails['OVSBOOTPROTO'] = 'dhcp'
208 bridgeDetails['OVSDHCPINTERFACES'] = ifname
209 devices_map[bridgeName] = bridgeDetails
211 if 'IFNAME' in details:
212 ifname = details['IFNAME']
219 ifname="eth%d" % (device_id-1)
220 if ifname not in devices_map:
223 if os.path.exists("%s/ifcfg-%s"%(sysconfig,ifname)):
224 logger.log("net:InitInterfaces WARNING: possibly blowing away %s configuration"%ifname)
225 devices_map[ifname] = details
227 logger.log('net:InitInterfaces: Device map: %r' % devices_map)
228 m = modprobe.Modprobe()
230 m.input("%s/etc/modprobe.conf" % root)
233 for (dev, details) in devices_map.iteritems():
234 # get the driver string "moduleName option1=a option2=b"
235 driver=details.get('DRIVER','')
237 driver=driver.split()
238 kernelmodule=driver[0]
239 m.aliasset(dev,kernelmodule)
240 options=" ".join(driver[1:])
242 m.optionsset(dev,options)
243 m.output("%s/etc/modprobe.conf" % root, program)
245 # clean up after any ifcfg-$dev script that's no longer listed as
246 # part of the Interfaces associated with this node
248 # list all network-scripts
249 files = os.listdir(sysconfig)
251 # filter out the ifcfg-* files
254 if f.find("ifcfg-") == 0:
257 # remove loopback (lo) from ifcfgs list
259 if lo in ifcfgs: ifcfgs.remove(lo)
261 # remove known devices from ifcfgs list
262 for (dev, details) in devices_map.iteritems():
264 if ifcfg in ifcfgs: ifcfgs.remove(ifcfg)
266 # delete the remaining ifcfgs from
267 deletedSomething = False
269 if not failedToGetSettings:
271 dev = ifcfg[len('ifcfg-'):]
272 path = "%s/ifcfg-%s" % (sysconfig,dev)
274 logger.verbose("net:InitInterfaces removing %s %s"%(dev,path))
275 os.system("/sbin/ifdown %s" % dev)
276 deletedSomething=True
279 # wait a bit for the one or more ifdowns to have taken effect
283 # Write network configuration file
284 networkconf = file("%s/etc/sysconfig/network" % root, "w")
285 networkconf.write("NETWORKING=yes\nHOSTNAME=%s\n" % hostname)
286 if gateway is not None:
287 networkconf.write("GATEWAY=%s\n" % gateway)
290 # Process ifcfg-$dev changes / additions
293 for (dev, details) in devices_map.iteritems():
294 (fd, tmpnam) = tempfile.mkstemp(dir=sysconfig)
295 f = os.fdopen(fd, "w")
296 f.write("# Autogenerated by pyplnet... do not edit!\n")
297 if 'DRIVER' in details:
298 f.write("# using %s driver for device %s\n" % (details['DRIVER'],dev))
299 f.write('DEVICE=%s\n' % dev)
301 # print the configuration values
302 for (key, val) in details.iteritems():
303 if key not in ('IFNAME','ALIAS','CFGOPTIONS','DRIVER','GATEWAY'):
304 f.write('%s="%s"\n' % (key, val))
306 # print the configuration specific option values (if any)
307 if 'CFGOPTIONS' in details:
308 cfgoptions = details['CFGOPTIONS']
309 f.write('#CFGOPTIONS are %s\n' % cfgoptions)
310 for cfgoption in cfgoptions.split():
311 key,val = cfgoption.split('=')
315 f.write('%s="%s"\n' % (key,val))
318 # compare whether two files are the same
319 def comparefiles(a,b):
321 logger.verbose("net:InitInterfaces comparing %s with %s" % (a,b))
322 if not os.path.exists(a): return False
327 if not os.path.exists(b): return False
332 return buf_a == buf_b
336 src_route_changed = False
337 if ('PRIMARY' not in details and 'GATEWAY' in details and
338 details['GATEWAY'] != ''):
340 (fd, rule_tmpnam) = tempfile.mkstemp(dir=sysconfig)
341 os.write(fd, "from %s lookup %d\n" % (details['IPADDR'], table))
343 rule_dest = "%s/rule-%s" % (sysconfig, dev)
344 if not comparefiles(rule_tmpnam, rule_dest):
345 os.rename(rule_tmpnam, rule_dest)
346 os.chmod(rule_dest, 0644)
347 src_route_changed = True
349 os.unlink(rule_tmpnam)
350 (fd, route_tmpnam) = tempfile.mkstemp(dir=sysconfig)
351 netmask = struct.unpack("I", socket.inet_aton(details['NETMASK']))[0]
352 ip = struct.unpack("I", socket.inet_aton(details['IPADDR']))[0]
353 network = socket.inet_ntoa(struct.pack("I", (ip & netmask)))
354 netmask = socket.ntohl(netmask)
356 while (netmask & (1 << i)) == 0:
359 os.write(fd, "%s/%d dev %s table %d\n" % (network, prefix, dev, table))
360 os.write(fd, "default via %s dev %s table %d\n" % (details['GATEWAY'], dev, table))
362 route_dest = "%s/route-%s" % (sysconfig, dev)
363 if not comparefiles(route_tmpnam, route_dest):
364 os.rename(route_tmpnam, route_dest)
365 os.chmod(route_dest, 0644)
366 src_route_changed = True
368 os.unlink(route_tmpnam)
370 path = "%s/ifcfg-%s" % (sysconfig,dev)
371 if not os.path.exists(path):
372 logger.verbose('net:InitInterfaces adding configuration for %s' % dev)
373 # add ifcfg-$dev configuration file
374 os.rename(tmpnam,path)
378 elif not comparefiles(tmpnam,path) or src_route_changed:
379 logger.verbose('net:InitInterfaces Configuration change for %s' % dev)
381 logger.verbose('net:InitInterfaces ifdown %s' % dev)
382 # invoke ifdown for the old configuration
383 os.system("/sbin/ifdown %s" % dev)
384 # wait a few secs for ifdown to complete
387 logger.log('replacing configuration for %s' % dev)
388 # replace ifcfg-$dev configuration file
389 os.rename(tmpnam,path)
393 # tmpnam & path are identical
398 fb = file("%s/ifcfg-%s"%(sysconfig,dev),"r")
399 for line in fb.readlines():
401 if parts[0][0]=="#":continue
402 if parts[0].find('='):
403 name,value = parts[0].split('=')
404 # clean up name & value
406 value = value.strip()
407 value = value.strip("'")
408 value = value.strip('"')
409 cfgvariables[name]=value
413 if name in cfgvariables:
414 value=cfgvariables[name]
415 value = value.lower()
419 # skip over device configs with ONBOOT=no
420 if getvar("ONBOOT") == 'no': continue
422 # don't bring up slave devices, the network scripts will
423 # handle those correctly
424 if getvar("SLAVE") == 'yes': continue
426 # Delay bringing up any bridge devices
427 if dev in bridgeDevices: continue
430 logger.verbose('net:InitInterfaces bringing up %s' % dev)
431 os.system("/sbin/ifup %s" % dev)
433 # Bring up the bridge devices
434 for bridge in bridgeDevices:
435 if not files_only and bridge in newdevs:
436 logger.verbose('net:InitInterfaces bringing up bridge %s' % bridge)
437 os.system("/sbin/ifup %s" % bridge)
440 # Prepare the interface details.
442 def prepDetails(interface, hostname=''):
444 details['ONBOOT'] = 'yes'
445 details['USERCTL'] = 'no'
447 details['HWADDR'] = interface['mac']
448 if interface['is_primary']:
449 details['PRIMARY'] = 'yes'
451 if interface['method'] == "static":
452 details['BOOTPROTO'] = "static"
453 details['IPADDR'] = interface['ip']
454 details['NETMASK'] = interface['netmask']
455 details['GATEWAY'] = interface['gateway']
456 if interface['is_primary']:
457 if interface['dns1']:
458 details['DNS1'] = interface['dns1']
459 if interface['dns2']:
460 details['DNS2'] = interface['dns2']
462 elif interface['method'] == "dhcp":
463 details['BOOTPROTO'] = "dhcp"
464 details['PERSISTENT_DHCLIENT'] = "yes"
465 if interface['hostname']:
466 details['DHCP_HOSTNAME'] = interface['hostname']
468 details['DHCP_HOSTNAME'] = hostname
469 if not interface['is_primary']:
470 details['DHCLIENTARGS'] = "-R subnet-mask"
475 # Remove duplicate entry from the bridged interface's configuration file.
477 def removeBridgedIfaceDetails(details):
478 for key in [ 'PRIMARY', 'PERSISTENT_DHCLIENT', 'DHCLIENTARGS', 'DHCP_HOSTNAME',
479 'BOOTPROTO', 'IPADDR', 'NETMASK', 'GATEWAY', 'DNS1', 'DNS2' ]:
484 if __name__ == "__main__":
488 parser = optparse.OptionParser(usage="plnet [-v] [-f] [-p <program>] -r root node_id")
489 parser.add_option("-v", "--verbose", action="store_true", dest="verbose")
490 parser.add_option("-r", "--root", action="store", type="string",
491 dest="root", default=None)
492 parser.add_option("-f", "--files-only", action="store_true",
494 parser.add_option("-p", "--program", action="store", type="string",
495 dest="program", default="plnet")
496 (options, args) = parser.parse_args()
497 if len(args) != 1 or options.root is None:
499 print >>sys.stderr, "Missing root or node_id"
503 node = shell.GetNodes({'node_id': [int(args[0])]})
505 interfaces = shell.GetInterfaces({'interface_id': node[0]['interface_ids']})
506 except AttributeError:
507 interfaces = shell.GetNodeNetworks({'nodenetwork_id':node[0]['nodenetwork_ids']})
511 data = {'hostname': node[0]['hostname'], 'interfaces': interfaces}
513 def __init__(self, verbose):
514 self.verbosity = verbose
515 def log(self, msg, loglevel=2):
518 def verbose(self, msg):
520 l = logger(options.verbose)
521 InitInterfaces(l, shell, data, options.root, options.files_only)