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")
24 logger.log("net: restarting openvswitch")
25 rc = os.system("service openvswitch restart")
26 rc = os.system("service openvswitch status")
29 logger.log("net: failed to restart openvswitch")
32 def InitInterfaces(logger, plc, data, root="", files_only=False, program="NodeManager"):
35 sysconfig = "{}/etc/sysconfig/network-scripts".format(root)
37 os.makedirs(sysconfig)
39 if e.errno != errno.EEXIST:
42 # query running network interfaces
44 ips = dict(list(zip(list(devs.values()), list(devs.keys()))))
47 macs[sioc.gifhwaddr(dev).lower()] = dev
51 hostname = data.get('hostname',socket.gethostname())
53 # assume data['interfaces'] contains this node's Interfaces
54 # can cope with 4.3 ('networks') or 5.0 ('interfaces')
56 interfaces = data['interfaces']
58 interfaces = data['networks']
59 failedToGetSettings = False
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<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
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') )
78 # The names of the bridge devices
81 for interface in interfaces:
82 logger.verbose('net:InitInterfaces interface {}: {}'.format(device_id, interface))
83 logger.verbose('net:InitInterfaces macs = {}'.format(macs))
84 logger.verbose('net:InitInterfaces ips = {}'.format(ips))
85 # Get interface name preferably from MAC address, falling back
87 hwaddr=interface['mac']
88 if hwaddr != None: hwaddr=hwaddr.lower()
90 orig_ifname = macs[hwaddr]
91 elif interface['ip'] in ips:
92 orig_ifname = ips[interface['ip']]
97 logger.verbose('net:InitInterfaces orig_ifname = {}'.format(orig_ifname))
99 details = prepDetails(interface, hostname)
101 if interface['is_primary']:
102 gateway = interface['gateway']
104 if 'interface_tag_ids' in interface:
106 interface_tag_ids = "interface_tag_ids"
107 interface_tag_id = "interface_tag_id"
111 interface_tag_ids = "nodenetwork_setting_ids"
112 interface_tag_id = "nodenetwork_setting_id"
115 if len(interface[interface_tag_ids]) > 0:
117 filter = { interface_tag_id : interface[interface_tag_ids] }
119 settings = plc.GetInterfaceTags(filter)
121 settings = plc.GetNodeNetworkSettings(filter)
123 logger.log("net:InitInterfaces FATAL: failed call GetInterfaceTags({})"
125 failedToGetSettings = True
126 continue # on to the next interface
128 for setting in settings:
129 settingname = setting[name_key].upper()
130 if ((settingname in ('IFNAME','ALIAS','CFGOPTIONS','DRIVER','VLAN','TYPE','DEVICETYPE')) or \
131 (re.search('^IPADDR[0-9]+$|^NETMASK[0-9]+$', settingname))):
132 # TD: Added match for secondary IPv4 configuration.
133 details[settingname]=setting['value']
134 # IPv6 support on IPv4 interface
135 elif settingname in ('IPV6ADDR','IPV6_DEFAULTGW','IPV6ADDR_SECONDARIES', 'IPV6_AUTOCONF'):
136 # TD: Added IPV6_AUTOCONF.
137 details[settingname]=setting['value']
138 details['IPV6INIT']='yes'
140 elif settingname in \
141 [ "MODE", "ESSID", "NW", "FREQ", "CHANNEL", "SENS", "RATE",
142 "KEY", "KEY1", "KEY2", "KEY3", "KEY4", "SECURITYMODE",
143 "IWCONFIG", "IWPRIV" ] :
144 details [settingname] = setting['value']
145 details ['TYPE']='Wireless'
147 elif settingname in [ 'BRIDGE' ]:
148 details['BRIDGE'] = setting['value']
149 elif settingname in [ 'OVS_BRIDGE' ]:
150 # If openvswitch isn't running, then we'll lose network
151 # connectivity when we reconfigure eth0.
152 if ovs_check(logger):
153 details['OVS_BRIDGE'] = setting['value']
154 details['TYPE'] = "OVSPort"
155 details['DEVICETYPE'] = "ovs"
157 logger.log("net:InitInterfaces ERROR: OVS_BRIDGE specified, yet ovs is not running")
159 logger.log("net:InitInterfaces WARNING: ignored setting named {}"
160 .format(setting[name_key]))
162 # support aliases to interfaces either by name or HWADDR
163 if 'ALIAS' in details:
164 if 'HWADDR' in details:
165 hwaddr = details['HWADDR'].lower()
166 del details['HWADDR']
168 hwifname = macs[hwaddr]
169 if ('IFNAME' in details) and details['IFNAME'] != hwifname:
170 logger.log("net:InitInterfaces WARNING: alias ifname ({}) and hwaddr ifname ({}) do not match"
171 .format(details['IFNAME'], hwifname))
172 details['IFNAME'] = hwifname
174 logger.log('net:InitInterfaces WARNING: mac addr {} for alias not found'.format(hwaddr))
176 if 'IFNAME' in details:
177 # stupid RH /etc/sysconfig/network-scripts/ifup-aliases:new_interface()
178 # checks if the "$DEVNUM" only consists of '^[0-9A-Za-z_]*$'. Need to make
179 # our aliases compliant.
180 parts = details['ALIAS'].split('_')
183 isValid=isValid and part.isalnum()
186 devices_map["{}:{}".format(details['IFNAME'], details['ALIAS'])] = details
188 logger.log("net:InitInterfaces WARNING: interface alias ({}) not a valid string for RH ifup-aliases"
189 .format(details['ALIAS']))
191 logger.log("net:InitInterfaces WARNING: interface alias ({}) not matched to an interface"
192 .format(details['ALIAS']))
194 elif ('BRIDGE' in details or 'OVS_BRIDGE' in details) and 'IFNAME' in details:
195 # The bridge inherits the mac of the first attached interface.
196 ifname = details['IFNAME']
198 if 'BRIDGE' in details:
199 bridgeName = details['BRIDGE']
200 bridgeType = 'Bridge'
202 bridgeName = details['OVS_BRIDGE']
203 bridgeType = 'OVSBridge'
205 logger.log('net:InitInterfaces: {} detected. Adding {} to devices_map'
206 .format(bridgeType, ifname))
207 devices_map[ifname] = removeBridgedIfaceDetails(details)
209 logger.log('net:InitInterfaces: Adding {} {}'.format(bridgeType, bridgeName))
210 bridgeDetails = prepDetails(interface)
212 # TD: Add configuration for secondary IPv4 and IPv6 addresses to the bridge.
213 if len(interface[interface_tag_ids]) > 0:
214 filter = { interface_tag_id : interface[interface_tag_ids] }
217 settings = plc.GetInterfaceTags(filter)
219 settings = plc.GetNodeNetworkSettings(filter)
221 logger.log("net:InitInterfaces FATAL: failed call GetInterfaceTags({})"
223 failedToGetSettings = True
224 continue # on to the next interface
226 for setting in settings:
227 settingname = setting[name_key].upper()
228 if (re.search('^IPADDR[0-9]+$|^NETMASK[0-9]+$', settingname)):
229 # TD: Added match for secondary IPv4 configuration.
230 bridgeDetails[settingname]=setting['value']
231 # IPv6 support on IPv4 interface
232 elif settingname in ('IPV6ADDR','IPV6_DEFAULTGW','IPV6ADDR_SECONDARIES', 'IPV6_AUTOCONF'):
233 # TD: Added IPV6_AUTOCONF.
234 bridgeDetails[settingname]=setting['value']
235 bridgeDetails['IPV6INIT']='yes'
237 bridgeDevices.append(bridgeName)
238 bridgeDetails['TYPE'] = bridgeType
239 if bridgeType == 'OVSBridge':
240 bridgeDetails['DEVICETYPE'] = 'ovs'
241 if bridgeDetails['BOOTPROTO'] == 'dhcp':
242 del bridgeDetails['BOOTPROTO']
243 bridgeDetails['OVSBOOTPROTO'] = 'dhcp'
244 bridgeDetails['OVSDHCPINTERFACES'] = ifname
245 devices_map[bridgeName] = bridgeDetails
247 if 'IFNAME' in details:
248 ifname = details['IFNAME']
255 ifname="eth{}".format(device_id - 1)
256 if ifname not in devices_map:
259 if os.path.exists("{}/ifcfg-{}".format(sysconfig, ifname)):
260 logger.log("net:InitInterfaces WARNING: possibly blowing away {} configuration"
262 devices_map[ifname] = details
264 logger.log('net:InitInterfaces: Device map: {}'.format(devices_map))
265 m = modprobe.Modprobe()
267 m.input("{}/etc/modprobe.conf".format(root))
270 for (dev, details) in devices_map.items():
271 # get the driver string "moduleName option1=a option2=b"
272 driver=details.get('DRIVER','')
274 driver=driver.split()
275 kernelmodule=driver[0]
276 m.aliasset(dev,kernelmodule)
277 options=" ".join(driver[1:])
279 m.optionsset(dev,options)
280 m.output("{}/etc/modprobe.conf".format(root), program)
282 # clean up after any ifcfg-$dev script that's no longer listed as
283 # part of the Interfaces associated with this node
285 # list all network-scripts
286 files = os.listdir(sysconfig)
288 # filter out the ifcfg-* files
291 if f.find("ifcfg-") == 0:
294 # remove loopback (lo) from ifcfgs list
296 if lo in ifcfgs: ifcfgs.remove(lo)
298 # remove known devices from ifcfgs list
299 for (dev, details) in devices_map.items():
301 if ifcfg in ifcfgs: ifcfgs.remove(ifcfg)
303 # delete the remaining ifcfgs from
304 deletedSomething = False
306 if not failedToGetSettings:
308 dev = ifcfg[len('ifcfg-'):]
309 path = "{}/ifcfg-{}".format(sysconfig, dev)
311 logger.verbose("net:InitInterfaces removing {} {}".format(dev, path))
312 os.system("/sbin/ifdown {}".format(dev))
313 deletedSomething=True
316 # wait a bit for the one or more ifdowns to have taken effect
320 # Write network configuration file
321 with open("{}/etc/sysconfig/network".format(root), "w") as networkconf:
322 networkconf.write("NETWORKING=yes\nHOSTNAME={}\n".format(hostname))
323 if gateway is not None:
324 networkconf.write("GATEWAY={}\n".format(gateway))
326 # Process ifcfg-$dev changes / additions
329 for (dev, details) in devices_map.items():
330 (fd, tmpnam) = tempfile.mkstemp(dir=sysconfig)
331 f = os.fdopen(fd, "w")
332 f.write("# Autogenerated by pyplnet... do not edit!\n")
333 if 'DRIVER' in details:
334 f.write("# using {} driver for device {}\n".format(details['DRIVER'], dev))
335 f.write('DEVICE={}\n'.format(dev))
337 # print the configuration values
338 for (key, val) in details.items():
339 if key not in ('IFNAME','ALIAS','CFGOPTIONS','DRIVER','GATEWAY'):
340 f.write('{}="{}"\n'.format(key, val))
342 # print the configuration specific option values (if any)
343 if 'CFGOPTIONS' in details:
344 cfgoptions = details['CFGOPTIONS']
345 f.write('#CFGOPTIONS are {}\n'.format(cfgoptions))
346 for cfgoption in cfgoptions.split():
347 key,val = cfgoption.split('=')
351 f.write('{}="{}"\n'.format(key, val))
354 # compare whether two files are the same
355 def comparefiles(a,b):
357 logger.verbose("net:InitInterfaces comparing {} with {}".format(a, b))
358 if not os.path.exists(a) or not os.path.exists(b):
366 return buf_a == buf_b
370 src_route_changed = False
371 if ('PRIMARY' not in details and 'GATEWAY' in details and
372 details['GATEWAY'] != ''):
374 (fd, rule_tmpnam) = tempfile.mkstemp(dir=sysconfig)
375 os.write(fd, "from {} lookup {}\n".format(details['IPADDR'], table))
377 rule_dest = "{}/rule-{}".format(sysconfig, dev)
378 if not comparefiles(rule_tmpnam, rule_dest):
379 os.rename(rule_tmpnam, rule_dest)
380 os.chmod(rule_dest, 0o644)
381 src_route_changed = True
383 os.unlink(rule_tmpnam)
384 (fd, route_tmpnam) = tempfile.mkstemp(dir=sysconfig)
385 netmask = struct.unpack("I", socket.inet_aton(details['NETMASK']))[0]
386 ip = struct.unpack("I", socket.inet_aton(details['IPADDR']))[0]
387 network = socket.inet_ntoa(struct.pack("I", (ip & netmask)))
388 netmask = socket.ntohl(netmask)
390 while (netmask & (1 << i)) == 0:
393 os.write(fd, "{}/{} dev {} table {}\n".format(network, prefix, dev, table))
394 os.write(fd, "default via {} dev {} table {}\n".format(details['GATEWAY'], dev, table))
396 route_dest = "{}/route-{}".format(sysconfig, dev)
397 if not comparefiles(route_tmpnam, route_dest):
398 os.rename(route_tmpnam, route_dest)
399 os.chmod(route_dest, 0o644)
400 src_route_changed = True
402 os.unlink(route_tmpnam)
404 path = "{}/ifcfg-{}".format(sysconfig,dev)
405 if not os.path.exists(path):
406 logger.verbose('net:InitInterfaces adding configuration for {}'.format(dev))
407 # add ifcfg-$dev configuration file
408 os.rename(tmpnam,path)
412 elif not comparefiles(tmpnam,path) or src_route_changed:
413 logger.verbose('net:InitInterfaces Configuration change for {}'.format(dev))
415 logger.verbose('net:InitInterfaces ifdown {}'.format(dev))
416 # invoke ifdown for the old configuration
417 os.system("/sbin/ifdown {}".format(dev))
418 # wait a few secs for ifdown to complete
421 logger.log('replacing configuration for {}'.format(dev))
422 # replace ifcfg-$dev configuration file
423 os.rename(tmpnam,path)
427 # tmpnam & path are identical
432 with file("{}/ifcfg-{}".format(sysconfig, dev), "r") as fb:
433 for line in fb.readlines():
435 if parts[0][0]=="#":continue
436 if parts[0].find('='):
437 name,value = parts[0].split('=')
438 # clean up name & value
440 value = value.strip()
441 value = value.strip("'")
442 value = value.strip('"')
443 cfgvariables[name]=value
446 if name in cfgvariables:
447 value=cfgvariables[name]
448 value = value.lower()
452 # skip over device configs with ONBOOT=no
453 if getvar("ONBOOT") == 'no': continue
455 # don't bring up slave devices, the network scripts will
456 # handle those correctly
457 if getvar("SLAVE") == 'yes': continue
459 # Delay bringing up any bridge devices
460 if dev in bridgeDevices: continue
463 logger.verbose('net:InitInterfaces bringing up {}'.format(dev))
464 os.system("/sbin/ifup {}".format(dev))
466 # Bring up the bridge devices
467 for bridge in bridgeDevices:
468 if not files_only and bridge in newdevs:
469 logger.verbose('net:InitInterfaces bringing up bridge {}'.format(bridge))
470 os.system("/sbin/ifup {}".format(bridge))
473 # Prepare the interface details.
475 def prepDetails(interface, hostname=''):
477 details['ONBOOT'] = 'yes'
478 details['USERCTL'] = 'no'
479 # attempt to work around issues seen starting with f23
480 details['NM_CONTROLLED'] = 'no'
482 details['HWADDR'] = interface['mac']
483 if interface['is_primary']:
484 details['PRIMARY'] = 'yes'
486 if interface['method'] == "static":
487 details['BOOTPROTO'] = "static"
488 details['IPADDR'] = interface['ip']
489 details['NETMASK'] = interface['netmask']
490 details['GATEWAY'] = interface['gateway']
491 if interface['is_primary']:
492 if interface['dns1']:
493 details['DNS1'] = interface['dns1']
494 if interface['dns2']:
495 details['DNS2'] = interface['dns2']
497 elif interface['method'] == "dhcp":
498 details['BOOTPROTO'] = "dhcp"
499 details['PERSISTENT_DHCLIENT'] = "yes"
500 if interface['hostname']:
501 details['DHCP_HOSTNAME'] = interface['hostname']
503 details['DHCP_HOSTNAME'] = hostname
504 if not interface['is_primary']:
505 details['DHCLIENTARGS'] = "-R subnet-mask"
510 # Remove duplicate entry from the bridged interface's configuration file.
512 def removeBridgedIfaceDetails(details):
513 # TD: Also added secondary IPv4 keys and IPv6 keys to the keys to be removed.
514 allKeys = [ 'PRIMARY', 'PERSISTENT_DHCLIENT', 'DHCLIENTARGS', 'DHCP_HOSTNAME',
515 'BOOTPROTO', 'IPADDR', 'NETMASK', 'GATEWAY', 'DNS1', 'DNS2',
516 'IPV6ADDR', 'IPV6_DEFAULTGW', 'IPV6ADDR_SECONDARIES',
517 'IPV6_AUTOCONF', 'IPV6INIT' ]
518 for i in range(1, 256):
519 allKeys.append('IPADDR' + str(i))
520 allKeys.append('NETMASK' + str(i))
526 # TD: Also turn off IPv6
527 details['IPV6INIT'] = 'no'
528 details['IPV6_AUTOCONF'] = 'no'
532 if __name__ == "__main__":
536 parser = optparse.OptionParser(usage="plnet [-v] [-f] [-p <program>] -r root node_id")
537 parser.add_option("-v", "--verbose", action="store_true", dest="verbose")
538 parser.add_option("-r", "--root", action="store", type="string",
539 dest="root", default=None)
540 parser.add_option("-f", "--files-only", action="store_true",
542 parser.add_option("-p", "--program", action="store", type="string",
543 dest="program", default="plnet")
544 (options, args) = parser.parse_args()
545 if len(args) != 1 or options.root is None:
547 print("Missing root or node_id", file=sys.stderr)
551 node = shell.GetNodes({'node_id': [int(args[0])]})
553 interfaces = shell.GetInterfaces({'interface_id': node[0]['interface_ids']})
554 except AttributeError:
555 interfaces = shell.GetNodeNetworks({'nodenetwork_id':node[0]['nodenetwork_ids']})
559 data = {'hostname': node[0]['hostname'], 'interfaces': interfaces}
561 def __init__(self, verbose):
562 self.verbosity = verbose
563 def log(self, msg, loglevel=2):
566 def verbose(self, msg):
568 l = logger(options.verbose)
569 InitInterfaces(l, shell, data, options.root, options.files_only)