1 #!/usr/bin/python /usr/bin/plcsh
16 def InitInterfaces(logger, plc, data, root="", files_only=False, program="NodeManager"):
19 sysconfig = "%s/etc/sysconfig/network-scripts" % root
21 os.makedirs(sysconfig)
23 if e.errno != errno.EEXIST:
26 # query running network interfaces
28 ips = dict(zip(devs.values(), devs.keys()))
31 macs[sioc.gifhwaddr(dev).lower()] = dev
35 hostname = data.get('hostname',socket.gethostname())
37 # assume data['interfaces'] contains this node's Interfaces
38 # can cope with 4.3 ('networks') or 5.0 ('interfaces')
40 interfaces = data['interfaces']
42 interfaces = data['networks']
43 failedToGetSettings = False
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
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') )
62 # The names of the bridge devices
65 for interface in interfaces:
66 logger.verbose('net:InitInterfaces interface %d: %r'%(device_id,interface))
67 logger.verbose('net:InitInterfaces macs = %r' % macs)
68 logger.verbose('net:InitInterfaces ips = %r' % ips)
69 # Get interface name preferably from MAC address, falling back
71 hwaddr=interface['mac']
72 if hwaddr <> None: hwaddr=hwaddr.lower()
74 orig_ifname = macs[hwaddr]
75 elif interface['ip'] in ips:
76 orig_ifname = ips[interface['ip']]
81 logger.verbose('net:InitInterfaces orig_ifname = %s' % orig_ifname)
83 details = prepDetails(interface, hostname)
85 if interface['is_primary']:
86 gateway = interface['gateway']
88 if 'interface_tag_ids' in interface:
90 interface_tag_ids = "interface_tag_ids"
91 interface_tag_id = "interface_tag_id"
95 interface_tag_ids = "nodenetwork_setting_ids"
96 interface_tag_id = "nodenetwork_setting_id"
99 if len(interface[interface_tag_ids]) > 0:
102 settings = plc.GetInterfaceTags({interface_tag_id:interface[interface_tag_ids]})
104 settings = plc.GetNodeNetworkSettings({interface_tag_id:interface[interface_tag_ids]})
106 logger.log("net:InitInterfaces FATAL: failed call GetInterfaceTags({'interface_tag_id':{%s})"% \
107 interface[interface_tag_ids])
108 failedToGetSettings = True
109 continue # on to the next interface
111 for setting in settings:
112 settingname = setting[name_key].upper()
113 if settingname in ('IFNAME','ALIAS','CFGOPTIONS','DRIVER','VLAN'):
114 details[settingname]=setting['value']
115 # IPv6 support on IPv4 interface
116 elif settingname in ('IPV6ADDR','IPV6_DEFAULTGW','IPV6ADDR_SECONDARIES'):
117 details[settingname]=setting['value']
118 details['IPV6INIT']='yes'
120 elif settingname in \
121 [ "MODE", "ESSID", "NW", "FREQ", "CHANNEL", "SENS", "RATE",
122 "KEY", "KEY1", "KEY2", "KEY3", "KEY4", "SECURITYMODE",
123 "IWCONFIG", "IWPRIV" ] :
124 details [settingname] = setting['value']
125 details ['TYPE']='Wireless'
127 elif settingname in [ 'BRIDGE' ]:
128 details['BRIDGE'] = setting['value']
129 elif settingname in [ 'OVS_BRIDGE' ]:
130 details['OVS_BRIDGE'] = setting['value']
131 details['TYPE'] = "OVSPort"
132 details['DEVICETYPE'] = "ovs"
134 logger.log("net:InitInterfaces WARNING: ignored setting named %s"%setting[name_key])
136 # support aliases to interfaces either by name or HWADDR
137 if 'ALIAS' in details:
138 if 'HWADDR' in details:
139 hwaddr = details['HWADDR'].lower()
140 del details['HWADDR']
142 hwifname = macs[hwaddr]
143 if ('IFNAME' in details) and details['IFNAME'] <> hwifname:
144 logger.log("net:InitInterfaces WARNING: alias ifname (%s) and hwaddr ifname (%s) do not match"%\
145 (details['IFNAME'],hwifname))
146 details['IFNAME'] = hwifname
148 logger.log('net:InitInterfaces WARNING: mac addr %s for alias not found' %(hwaddr))
150 if 'IFNAME' in details:
151 # stupid RH /etc/sysconfig/network-scripts/ifup-aliases:new_interface()
152 # checks if the "$DEVNUM" only consists of '^[0-9A-Za-z_]*$'. Need to make
153 # our aliases compliant.
154 parts = details['ALIAS'].split('_')
157 isValid=isValid and part.isalnum()
160 devices_map["%s:%s" % (details['IFNAME'],details['ALIAS'])] = details
162 logger.log("net:InitInterfaces WARNING: interface alias (%s) not a valid string for RH ifup-aliases"% details['ALIAS'])
164 logger.log("net:InitInterfaces WARNING: interface alias (%s) not matched to an interface"% details['ALIAS'])
166 elif ('BRIDGE' in details or 'OVS_BRIDGE' in details) and 'IFNAME' in details:
167 # The bridge inherits the mac of the first attached interface.
168 ifname = details['IFNAME']
170 if 'BRIDGE' in details:
171 bridgeName = details['BRIDGE']
172 bridgeType = 'Bridge'
174 bridgeName = details['OVS_BRIDGE']
175 bridgeType = 'OVSBridge'
177 logger.log('net:InitInterfaces: %s detected. Adding %s to devices_map' % (bridgeType, ifname))
178 devices_map[ifname] = removeBridgedIfaceDetails(details)
180 logger.log('net:InitInterfaces: Adding %s %s' % (bridgeType, bridgeName))
181 bridgeDetails = prepDetails(interface)
182 bridgeDevices.append(bridgeName)
183 bridgeDetails['TYPE'] = bridgeType
184 if bridgeType == 'OVSBridge':
185 bridgeDetails['DEVICETYPE'] = 'ovs'
186 if bridgeDetails['BOOTPROTO'] == 'dhcp':
187 del bridgeDetails['BOOTPROTO']
188 bridgeDetails['OVSBOOTPROTO'] = 'dhcp'
189 bridgeDetails['OVSDHCPINTERFACES'] = ifname
190 devices_map[bridgeName] = bridgeDetails
192 if 'IFNAME' in details:
193 ifname = details['IFNAME']
200 ifname="eth%d" % (device_id-1)
201 if ifname not in devices_map:
204 if os.path.exists("%s/ifcfg-%s"%(sysconfig,ifname)):
205 logger.log("net:InitInterfaces WARNING: possibly blowing away %s configuration"%ifname)
206 devices_map[ifname] = details
208 logger.log('net:InitInterfaces: Device map: %r' % devices_map)
209 m = modprobe.Modprobe()
211 m.input("%s/etc/modprobe.conf" % root)
214 for (dev, details) in devices_map.iteritems():
215 # get the driver string "moduleName option1=a option2=b"
216 driver=details.get('DRIVER','')
218 driver=driver.split()
219 kernelmodule=driver[0]
220 m.aliasset(dev,kernelmodule)
221 options=" ".join(driver[1:])
223 m.optionsset(dev,options)
224 m.output("%s/etc/modprobe.conf" % root, program)
226 # clean up after any ifcfg-$dev script that's no longer listed as
227 # part of the Interfaces associated with this node
229 # list all network-scripts
230 files = os.listdir(sysconfig)
232 # filter out the ifcfg-* files
235 if f.find("ifcfg-") == 0:
238 # remove loopback (lo) from ifcfgs list
240 if lo in ifcfgs: ifcfgs.remove(lo)
242 # remove known devices from ifcfgs list
243 for (dev, details) in devices_map.iteritems():
245 if ifcfg in ifcfgs: ifcfgs.remove(ifcfg)
247 # delete the remaining ifcfgs from
248 deletedSomething = False
250 if not failedToGetSettings:
252 dev = ifcfg[len('ifcfg-'):]
253 path = "%s/ifcfg-%s" % (sysconfig,dev)
255 logger.verbose("net:InitInterfaces removing %s %s"%(dev,path))
256 os.system("/sbin/ifdown %s" % dev)
257 deletedSomething=True
260 # wait a bit for the one or more ifdowns to have taken effect
264 # Write network configuration file
265 networkconf = file("%s/etc/sysconfig/network" % root, "w")
266 networkconf.write("NETWORKING=yes\nHOSTNAME=%s\n" % hostname)
267 if gateway is not None:
268 networkconf.write("GATEWAY=%s\n" % gateway)
271 # Process ifcfg-$dev changes / additions
274 for (dev, details) in devices_map.iteritems():
275 (fd, tmpnam) = tempfile.mkstemp(dir=sysconfig)
276 f = os.fdopen(fd, "w")
277 f.write("# Autogenerated by pyplnet... do not edit!\n")
278 if 'DRIVER' in details:
279 f.write("# using %s driver for device %s\n" % (details['DRIVER'],dev))
280 f.write('DEVICE=%s\n' % dev)
282 # print the configuration values
283 for (key, val) in details.iteritems():
284 if key not in ('IFNAME','ALIAS','CFGOPTIONS','DRIVER','GATEWAY'):
285 f.write('%s="%s"\n' % (key, val))
287 # print the configuration specific option values (if any)
288 if 'CFGOPTIONS' in details:
289 cfgoptions = details['CFGOPTIONS']
290 f.write('#CFGOPTIONS are %s\n' % cfgoptions)
291 for cfgoption in cfgoptions.split():
292 key,val = cfgoption.split('=')
296 f.write('%s="%s"\n' % (key,val))
299 # compare whether two files are the same
300 def comparefiles(a,b):
302 logger.verbose("net:InitInterfaces comparing %s with %s" % (a,b))
303 if not os.path.exists(a): return False
308 if not os.path.exists(b): return False
313 return buf_a == buf_b
317 src_route_changed = False
318 if ('PRIMARY' not in details and 'GATEWAY' in details and
319 details['GATEWAY'] != ''):
321 (fd, rule_tmpnam) = tempfile.mkstemp(dir=sysconfig)
322 os.write(fd, "from %s lookup %d\n" % (details['IPADDR'], table))
324 rule_dest = "%s/rule-%s" % (sysconfig, dev)
325 if not comparefiles(rule_tmpnam, rule_dest):
326 os.rename(rule_tmpnam, rule_dest)
327 os.chmod(rule_dest, 0644)
328 src_route_changed = True
330 os.unlink(rule_tmpnam)
331 (fd, route_tmpnam) = tempfile.mkstemp(dir=sysconfig)
332 netmask = struct.unpack("I", socket.inet_aton(details['NETMASK']))[0]
333 ip = struct.unpack("I", socket.inet_aton(details['IPADDR']))[0]
334 network = socket.inet_ntoa(struct.pack("I", (ip & netmask)))
335 netmask = socket.ntohl(netmask)
337 while (netmask & (1 << i)) == 0:
340 os.write(fd, "%s/%d dev %s table %d\n" % (network, prefix, dev, table))
341 os.write(fd, "default via %s dev %s table %d\n" % (details['GATEWAY'], dev, table))
343 route_dest = "%s/route-%s" % (sysconfig, dev)
344 if not comparefiles(route_tmpnam, route_dest):
345 os.rename(route_tmpnam, route_dest)
346 os.chmod(route_dest, 0644)
347 src_route_changed = True
349 os.unlink(route_tmpnam)
351 path = "%s/ifcfg-%s" % (sysconfig,dev)
352 if not os.path.exists(path):
353 logger.verbose('net:InitInterfaces adding configuration for %s' % dev)
354 # add ifcfg-$dev configuration file
355 os.rename(tmpnam,path)
359 elif not comparefiles(tmpnam,path) or src_route_changed:
360 logger.verbose('net:InitInterfaces Configuration change for %s' % dev)
362 logger.verbose('net:InitInterfaces ifdown %s' % dev)
363 # invoke ifdown for the old configuration
364 os.system("/sbin/ifdown %s" % dev)
365 # wait a few secs for ifdown to complete
368 logger.log('replacing configuration for %s' % dev)
369 # replace ifcfg-$dev configuration file
370 os.rename(tmpnam,path)
374 # tmpnam & path are identical
379 fb = file("%s/ifcfg-%s"%(sysconfig,dev),"r")
380 for line in fb.readlines():
382 if parts[0][0]=="#":continue
383 if parts[0].find('='):
384 name,value = parts[0].split('=')
385 # clean up name & value
387 value = value.strip()
388 value = value.strip("'")
389 value = value.strip('"')
390 cfgvariables[name]=value
394 if name in cfgvariables:
395 value=cfgvariables[name]
396 value = value.lower()
400 # skip over device configs with ONBOOT=no
401 if getvar("ONBOOT") == 'no': continue
403 # don't bring up slave devices, the network scripts will
404 # handle those correctly
405 if getvar("SLAVE") == 'yes': continue
407 # Delay bringing up any bridge devices
408 if dev in bridgeDevices: continue
411 logger.verbose('net:InitInterfaces bringing up %s' % dev)
412 os.system("/sbin/ifup %s" % dev)
414 # Bring up the bridge devices
415 for bridge in bridgeDevices:
416 if not files_only and bridge in newdevs:
417 logger.verbose('net:InitInterfaces bringing up bridge %s' % bridge)
418 os.system("/sbin/ifup %s" % bridge)
421 # Prepare the interface details.
423 def prepDetails(interface, hostname=''):
425 details['ONBOOT'] = 'yes'
426 details['USERCTL'] = 'no'
428 details['HWADDR'] = interface['mac']
429 if interface['is_primary']:
430 details['PRIMARY'] = 'yes'
432 if interface['method'] == "static":
433 details['BOOTPROTO'] = "static"
434 details['IPADDR'] = interface['ip']
435 details['NETMASK'] = interface['netmask']
436 details['GATEWAY'] = interface['gateway']
437 if interface['is_primary']:
438 if interface['dns1']:
439 details['DNS1'] = interface['dns1']
440 if interface['dns2']:
441 details['DNS2'] = interface['dns2']
443 elif interface['method'] == "dhcp":
444 details['BOOTPROTO'] = "dhcp"
445 details['PERSISTENT_DHCLIENT'] = "yes"
446 if interface['hostname']:
447 details['DHCP_HOSTNAME'] = interface['hostname']
449 details['DHCP_HOSTNAME'] = hostname
450 if not interface['is_primary']:
451 details['DHCLIENTARGS'] = "-R subnet-mask"
456 # Remove duplicate entry from the bridged interface's configuration file.
458 def removeBridgedIfaceDetails(details):
459 for key in [ 'PRIMARY', 'PERSISTENT_DHCLIENT', 'DHCLIENTARGS', 'DHCP_HOSTNAME',
460 'BOOTPROTO', 'IPADDR', 'NETMASK', 'GATEWAY', 'DNS1', 'DNS2' ]:
465 if __name__ == "__main__":
469 parser = optparse.OptionParser(usage="plnet [-v] [-f] [-p <program>] -r root node_id")
470 parser.add_option("-v", "--verbose", action="store_true", dest="verbose")
471 parser.add_option("-r", "--root", action="store", type="string",
472 dest="root", default=None)
473 parser.add_option("-f", "--files-only", action="store_true",
475 parser.add_option("-p", "--program", action="store", type="string",
476 dest="program", default="plnet")
477 (options, args) = parser.parse_args()
478 if len(args) != 1 or options.root is None:
480 print >>sys.stderr, "Missing root or node_id"
484 node = shell.GetNodes({'node_id': [int(args[0])]})
486 interfaces = shell.GetInterfaces({'interface_id': node[0]['interface_ids']})
487 except AttributeError:
488 interfaces = shell.GetNodeNetworks({'nodenetwork_id':node[0]['nodenetwork_ids']})
492 data = {'hostname': node[0]['hostname'], 'interfaces': interfaces}
494 def __init__(self, verbose):
495 self.verbosity = verbose
496 def log(self, msg, loglevel=2):
499 def verbose(self, msg):
501 l = logger(options.verbose)
502 InitInterfaces(l, shell, data, options.root, options.files_only)