1 #!/usr/bin/python /usr/bin/plcsh
17 def InitInterfaces(logger, plc, data, root="", files_only=False, program="NodeManager"):
20 sysconfig = "%s/etc/sysconfig/network-scripts" % root
22 os.makedirs(sysconfig)
24 if e.errno != errno.EEXIST:
27 # query running network interfaces
29 ips = dict(zip(devs.values(), devs.keys()))
32 macs[sioc.gifhwaddr(dev).lower()] = dev
36 hostname = data.get('hostname',socket.gethostname())
38 # assume data['interfaces'] contains this node's Interfaces
39 # can cope with 4.3 ('networks') or 5.0 ('interfaces')
41 interfaces = data['interfaces']
43 interfaces = data['networks']
44 failedToGetSettings = False
46 # NOTE: GetInterfaces/NodeNetworks does not necessarily order the interfaces
47 # returned. Because 'interface'is decremented as each interface is processed,
48 # by the time is_primary=True (primary) interface is reached, the device
49 # "eth%s" % interface, is not eth0. But, something like eth-4, or eth-12.
50 # This code sorts the interfaces, placing is_primary=True interfaces first.
51 # There is a lot of room for improvement to how this
52 # script handles interfaces and how it chooses the primary interface.
53 def compare_by (fieldname):
54 def compare_two_dicts (a, b):
55 return cmp(a[fieldname], b[fieldname])
56 return compare_two_dicts
58 # NOTE: by sorting on 'is_primary' and then reversing (since False is sorted
59 # before True) all 'is_primary' interfaces are at the beginning of the list.
60 interfaces.sort( compare_by('is_primary') )
63 for interface in interfaces:
64 logger.verbose('net:InitInterfaces interface %d: %r'%(device_id,interface))
65 logger.verbose('net:InitInterfaces macs = %r' % macs)
66 logger.verbose('net:InitInterfaces ips = %r' % ips)
67 # Get interface name preferably from MAC address, falling back
69 hwaddr=interface['mac']
70 if hwaddr <> None: hwaddr=hwaddr.lower()
72 orig_ifname = macs[hwaddr]
73 elif interface['ip'] in ips:
74 orig_ifname = ips[interface['ip']]
79 logger.verbose('net:InitInterfaces orig_ifname = %s' % orig_ifname)
82 details['ONBOOT']='yes'
83 details['USERCTL']='no'
85 details['HWADDR'] = interface['mac']
86 if interface['is_primary']:
87 details['PRIMARY']='yes'
89 if interface['method'] == "static":
90 details['BOOTPROTO'] = "static"
91 details['IPADDR'] = interface['ip']
92 details['NETMASK'] = interface['netmask']
93 details['GATEWAY'] = interface['gateway']
94 if interface['is_primary']:
95 gateway = interface['gateway']
97 details['DNS1'] = interface['dns1']
99 details['DNS2'] = interface['dns2']
101 elif interface['method'] == "dhcp":
102 details['BOOTPROTO'] = "dhcp"
103 details['PERSISTENT_DHCLIENT'] = "yes"
104 if interface['hostname']:
105 details['DHCP_HOSTNAME'] = interface['hostname']
107 details['DHCP_HOSTNAME'] = hostname
108 if not interface['is_primary']:
109 details['DHCLIENTARGS'] = "-R subnet-mask"
111 if 'interface_tag_ids' in interface:
113 interface_tag_ids = "interface_tag_ids"
114 interface_tag_id = "interface_tag_id"
118 interface_tag_ids = "nodenetwork_setting_ids"
119 interface_tag_id = "nodenetwork_setting_id"
122 if len(interface[interface_tag_ids]) > 0:
125 settings = plc.GetInterfaceTags({interface_tag_id:interface[interface_tag_ids]})
127 settings = plc.GetNodeNetworkSettings({interface_tag_id:interface[interface_tag_ids]})
129 logger.log("net:InitInterfaces FATAL: failed call GetInterfaceTags({'interface_tag_id':{%s})"% \
130 interface[interface_tag_ids])
131 failedToGetSettings = True
132 continue # on to the next interface
134 for setting in settings:
135 settingname = setting[name_key].upper()
136 if settingname in ('IFNAME','ALIAS','CFGOPTIONS','DRIVER'):
137 details[settingname]=setting['value']
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'
146 logger.log("net:InitInterfaces WARNING: ignored setting named %s"%setting[name_key])
148 # support aliases to interfaces either by name or HWADDR
149 if 'ALIAS' in details:
150 if 'HWADDR' in details:
151 hwaddr = details['HWADDR'].lower()
152 del details['HWADDR']
154 hwifname = macs[hwaddr]
155 if ('IFNAME' in details) and details['IFNAME'] <> hwifname:
156 logger.log("net:InitInterfaces WARNING: alias ifname (%s) and hwaddr ifname (%s) do not match"%\
157 (details['IFNAME'],hwifname))
158 details['IFNAME'] = hwifname
160 logger.log('net:InitInterfaces WARNING: mac addr %s for alias not found' %(hwaddr))
162 if 'IFNAME' in details:
163 # stupid RH /etc/sysconfig/network-scripts/ifup-aliases:new_interface()
164 # checks if the "$DEVNUM" only consists of '^[0-9A-Za-z_]*$'. Need to make
165 # our aliases compliant.
166 parts = details['ALIAS'].split('_')
169 isValid=isValid and part.isalnum()
172 devices_map["%s:%s" % (details['IFNAME'],details['ALIAS'])] = details
174 logger.log("net:InitInterfaces WARNING: interface alias (%s) not a valid string for RH ifup-aliases"% details['ALIAS'])
176 logger.log("net:InitInterfaces WARNING: interface alias (%s) not matched to an interface"% details['ALIAS'])
179 if 'IFNAME' in details:
180 ifname = details['IFNAME']
187 ifname="eth%d" % (device_id-1)
188 if ifname not in devices_map:
191 if os.path.exists("%s/ifcfg-%s"%(sysconfig,ifname)):
192 logger.log("net:InitInterfaces WARNING: possibly blowing away %s configuration"%ifname)
193 devices_map[ifname] = details
195 m = modprobe.Modprobe()
197 m.input("%s/etc/modprobe.conf" % root)
200 for (dev, details) in devices_map.iteritems():
201 # get the driver string "moduleName option1=a option2=b"
202 driver=details.get('DRIVER','')
204 driver=driver.split()
205 kernelmodule=driver[0]
206 m.aliasset(dev,kernelmodule)
207 options=" ".join(driver[1:])
209 m.optionsset(dev,options)
210 m.output("%s/etc/modprobe.conf" % root, program)
212 # clean up after any ifcfg-$dev script that's no longer listed as
213 # part of the Interfaces associated with this node
215 # list all network-scripts
216 files = os.listdir(sysconfig)
218 # filter out the ifcfg-* files
221 if f.find("ifcfg-") == 0:
224 # remove loopback (lo) from ifcfgs list
226 if lo in ifcfgs: ifcfgs.remove(lo)
228 # remove known devices from icfgs list
229 for (dev, details) in devices_map.iteritems():
231 if ifcfg in ifcfgs: ifcfgs.remove(ifcfg)
233 # delete the remaining ifcfgs from
234 deletedSomething = False
236 if not failedToGetSettings:
238 dev = ifcfg[len('ifcfg-'):]
239 path = "%s/ifcfg-%s" % (sysconfig,dev)
241 logger.verbose("net:InitInterfaces removing %s %s"%(dev,path))
242 os.system("/sbin/ifdown %s" % dev)
243 deletedSomething=True
246 # wait a bit for the one or more ifdowns to have taken effect
250 # Write network configuration file
251 networkconf = file("%s/etc/sysconfig/network" % root, "w")
252 networkconf.write("NETWORKING=yes\nHOSTNAME=%s\n" % hostname)
253 if gateway is not None:
254 networkconf.write("GATEWAY=%s\n" % gateway)
257 # Process ifcfg-$dev changes / additions
259 for (dev, details) in devices_map.iteritems():
260 (fd, tmpnam) = tempfile.mkstemp(dir=sysconfig)
261 f = os.fdopen(fd, "w")
262 f.write("# Autogenerated by pyplnet... do not edit!\n")
263 if 'DRIVER' in details:
264 f.write("# using %s driver for device %s\n" % (details['DRIVER'],dev))
265 f.write('DEVICE=%s\n' % dev)
267 # print the configuration values
268 for (key, val) in details.iteritems():
269 if key not in ('IFNAME','ALIAS','CFGOPTIONS','DRIVER','GATEWAY'):
270 f.write('%s=%s\n' % (key, val))
272 # print the configuration specific option values (if any)
273 if 'CFGOPTIONS' in details:
274 cfgoptions = details['CFGOPTIONS']
275 f.write('#CFGOPTIONS are %s\n' % cfgoptions)
276 for cfgoption in cfgoptions.split():
277 key,val = cfgoption.split('=')
281 f.write('%s="%s"\n' % (key,val))
284 # compare whether two files are the same
285 def comparefiles(a,b):
287 logger.verbose("net:InitInterfaces comparing %s with %s" % (a,b))
288 if not os.path.exists(a): return False
293 if not os.path.exists(b): return False
298 return buf_a == buf_b
302 src_route_changed = False
303 if ('PRIMARY' not in details and 'GATEWAY' in details and
304 details['GATEWAY'] != ''):
306 while dev[i - 1].isdigit():
308 table = 10 + int(dev[i:])
309 (fd, rule_tmpnam) = tempfile.mkstemp(dir=sysconfig)
310 os.write(fd, "from %s lookup %d\n" % (details['IPADDR'], table))
312 rule_dest = "%s/rule-%s" % (sysconfig, dev)
313 if not comparefiles(rule_tmpnam, rule_dest):
314 os.rename(rule_tmpnam, rule_dest)
315 os.chmod(rule_dest, 0644)
316 src_route_changed = True
318 os.unlink(rule_tmpnam)
319 (fd, route_tmpnam) = tempfile.mkstemp(dir=sysconfig)
320 netmask = struct.unpack("I", socket.inet_aton(details['NETMASK']))[0]
321 ip = struct.unpack("I", socket.inet_aton(details['IPADDR']))[0]
322 network = socket.inet_ntoa(struct.pack("I", (ip & netmask)))
323 netmask = socket.ntohl(netmask)
325 while (netmask & (1 << i)) == 0:
328 os.write(fd, "%s/%d dev %s table %d\n" % (network, prefix, dev, table))
329 os.write(fd, "default via %s dev %s table %d\n" % (details['GATEWAY'], dev, table))
331 route_dest = "%s/route-%s" % (sysconfig, dev)
332 if not comparefiles(route_tmpnam, route_dest):
333 os.rename(route_tmpnam, route_dest)
334 os.chmod(route_dest, 0644)
335 src_route_changed = True
337 os.unlink(route_tmpnam)
339 path = "%s/ifcfg-%s" % (sysconfig,dev)
340 if not os.path.exists(path):
341 logger.verbose('net:InitInterfaces adding configuration for %s' % dev)
342 # add ifcfg-$dev configuration file
343 os.rename(tmpnam,path)
347 elif not comparefiles(tmpnam,path) or src_route_changed:
348 logger.verbose('net:InitInterfaces Configuration change for %s' % dev)
350 logger.verbose('net:InitInterfaces ifdown %s' % dev)
351 # invoke ifdown for the old configuration
352 os.system("/sbin/ifdown %s" % dev)
353 # wait a few secs for ifdown to complete
356 logger.log('replacing configuration for %s' % dev)
357 # replace ifcfg-$dev configuration file
358 os.rename(tmpnam,path)
362 # tmpnam & path are identical
367 fb = file("%s/ifcfg-%s"%(sysconfig,dev),"r")
368 for line in fb.readlines():
370 if parts[0][0]=="#":continue
371 if parts[0].find('='):
372 name,value = parts[0].split('=')
373 # clean up name & value
375 value = value.strip()
376 value = value.strip("'")
377 value = value.strip('"')
378 cfgvariables[name]=value
382 if name in cfgvariables:
383 value=cfgvariables[name]
384 value = value.lower()
388 # skip over device configs with ONBOOT=no
389 if getvar("ONBOOT") == 'no': continue
391 # don't bring up slave devices, the network scripts will
392 # handle those correctly
393 if getvar("SLAVE") == 'yes': continue
396 logger.verbose('net:InitInterfaces bringing up %s' % dev)
397 os.system("/sbin/ifup %s" % dev)
399 if __name__ == "__main__":
403 parser = optparse.OptionParser(usage="plnet [-v] [-f] [-p <program>] -r root node_id")
404 parser.add_option("-v", "--verbose", action="store_true", dest="verbose")
405 parser.add_option("-r", "--root", action="store", type="string",
406 dest="root", default=None)
407 parser.add_option("-f", "--files-only", action="store_true",
409 parser.add_option("-p", "--program", action="store", type="string",
410 dest="program", default="plnet")
411 (options, args) = parser.parse_args()
412 if len(args) != 1 or options.root is None:
414 print >>sys.stderr, "Missing root or node_id"
418 node = shell.GetNodes({'node_id': [int(args[0])]})
420 interfaces = shell.GetInterfaces({'interface_id': node[0]['interface_ids']})
421 except AttributeError:
422 interfaces = shell.GetNodeNetworks({'nodenetwork_id':node[0]['nodenetwork_ids']})
426 data = {'hostname': node[0]['hostname'], 'interfaces': interfaces}
428 def __init__(self, verbose):
429 self.verbosity = verbose
430 def log(self, msg, loglevel=2):
433 def verbose(self, msg):
435 l = logger(options.verbose)
436 InitInterfaces(l, shell, data, options.root, options.files_only)