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
33 # assume data['networks'] contains this node's NodeNetworks
36 hostname = data.get('hostname',socket.gethostname())
38 networks = data['networks']
39 failedToGetSettings = False
40 for network in networks:
41 logger.verbose('net:InitInterfaces interface %d: %s'%(interface,network))
42 logger.verbose('net:InitInterfaces macs = %s' % macs)
43 logger.verbose('net:InitInterfaces ips = %s' % ips)
44 # Get interface name preferably from MAC address, falling back
47 if hwaddr <> None: hwaddr=hwaddr.lower()
49 orig_ifname = macs[hwaddr]
50 elif network['ip'] in ips:
51 orig_ifname = ips[network['ip']]
56 logger.verbose('net:InitInterfaces orig_ifname = %s' % orig_ifname)
62 inter['HWADDR'] = network['mac']
63 if network['is_primary']:
64 inter['PRIMARY']='yes'
66 if network['method'] == "static":
67 inter['BOOTPROTO'] = "static"
68 inter['IPADDR'] = network['ip']
69 inter['NETMASK'] = network['netmask']
70 inter['DNS1'] = network['dns1']
71 inter['DNS2'] = network['dns2']
72 if network['is_primary']:
73 gateway = network['gateway']
75 elif network['method'] == "dhcp":
76 inter['BOOTPROTO'] = "dhcp"
77 inter['PERSISTENT_DHCLIENT'] = "yes"
78 if network['hostname']:
79 inter['DHCP_HOSTNAME'] = network['hostname']
81 inter['DHCP_HOSTNAME'] = hostname
82 if not network['is_primary']:
83 inter['DHCLIENTARGS'] = "-R subnet-mask"
86 plc.GetInterfaceTags()
88 except AttributeError:
92 interface_tag_ids = "interface_tag_ids"
93 interface_tag_id = "interface_tag_id"
95 interface_tag_ids = "nodenetwork_setting_ids"
96 interface_tag_id = "nodenetwork_setting_id"
98 if len(network[interface_tag_ids]) > 0:
101 settings = plc.GetInterfaceTags({interface_tag_id:network[interface_tag_ids]})
103 settings = plc.GetNodeNetworkSettings({interface_tag_id:network[interface_tag_ids]})
105 logger.log("net:InitInterfaces FATAL: failed call GetInterfaceTags({'interface_tag_id':{%s})"% \
106 network['interface_tag_ids'])
107 failedToGetSettings = True
108 continue # on to the next network
110 for setting in settings:
111 # to explicitly set interface name
116 settingname = setting[name_key].upper()
117 if settingname in ('IFNAME','ALIAS','CFGOPTIONS','DRIVER'):
118 inter[settingname]=setting['value']
120 logger.log("net:InitInterfaces WARNING: ignored setting named %s"%setting[name_key])
122 # support aliases to interfaces either by name or HWADDR
124 if 'HWADDR' in inter:
125 hwaddr = inter['HWADDR'].lower()
128 hwifname = macs[hwaddr]
129 if ('IFNAME' in inter) and inter['IFNAME'] <> hwifname:
130 logger.log("net:InitInterfaces WARNING: alias ifname (%s) and hwaddr ifname (%s) do not match"%\
131 (inter['IFNAME'],hwifname))
132 inter['IFNAME'] = hwifname
134 logger.log('net:InitInterfaces WARNING: mac addr %s for alias not found' %(hwaddr,alias))
136 if 'IFNAME' in inter:
137 # stupid RH /etc/sysconfig/network-scripts/ifup-aliases:new_interface()
138 # checks if the "$DEVNUM" only consists of '^[0-9A-Za-z_]*$'. Need to make
139 # our aliases compliant.
140 parts = inter['ALIAS'].split('_')
143 isValid=isValid and part.isalnum()
146 interfaces["%s:%s" % (inter['IFNAME'],inter['ALIAS'])] = inter
148 logger.log("net:InitInterfaces WARNING: interface alias (%s) not a valid string for RH ifup-aliases"% inter['ALIAS'])
150 logger.log("net:InitInterfaces WARNING: interface alias (%s) not matched to an interface"% inter['ALIAS'])
153 if ('IFNAME' not in inter) and not orig_ifname:
154 ifname="eth%d" % (interface-1)
155 # should check if $ifname is an eth already defines
156 if os.path.exists("%s/ifcfg-%s"%(sysconfig,ifname)):
157 logger.log("net:InitInterfaces WARNING: possibly blowing away %s configuration"%ifname)
159 if ('IFNAME' not in inter) and orig_ifname:
162 ifname = inter['IFNAME']
164 interfaces[ifname] = inter
166 m = modprobe.Modprobe()
168 m.input("%s/etc/modprobe.conf" % root)
171 for (dev, inter) in interfaces.iteritems():
172 # get the driver string "moduleName option1=a option2=b"
173 driver=inter.get('DRIVER','')
175 driver=driver.split()
176 kernelmodule=driver[0]
177 m.aliasset(dev,kernelmodule)
178 options=" ".join(driver[1:])
180 m.optionsset(dev,options)
181 m.output("%s/etc/modprobe.conf" % root, program)
183 # clean up after any ifcfg-$dev script that's no longer listed as
184 # part of the NodeNetworks associated with this node
186 # list all network-scripts
187 files = os.listdir(sysconfig)
189 # filter out the ifcfg-* files
192 if f.find("ifcfg-") == 0:
195 # remove loopback (lo) from ifcfgs list
197 if lo in ifcfgs: ifcfgs.remove(lo)
199 # remove known devices from icfgs list
200 for (dev, inter) in interfaces.iteritems():
202 if ifcfg in ifcfgs: ifcfgs.remove(ifcfg)
204 # delete the remaining ifcfgs from
205 deletedSomething = False
207 if not failedToGetSettings:
209 dev = ifcfg[len('ifcfg-'):]
210 path = "%s/ifcfg-%s" % (sysconfig,dev)
212 logger.verbose("net:InitInterfaces removing %s %s"%(dev,path))
213 os.system("/sbin/ifdown %s" % dev)
214 deletedSomething=True
217 # wait a bit for the one or more ifdowns to have taken effect
221 # Write network configuration file
222 networkconf = file("%s/etc/sysconfig/network" % root, "w")
223 networkconf.write("NETWORKING=yes\nHOSTNAME=%s\n" % hostname)
224 if gateway is not None:
225 networkconf.write("GATEWAY=%s\n" % gateway)
228 # Process ifcfg-$dev changes / additions
230 for (dev, inter) in interfaces.iteritems():
231 (fd, tmpnam) = tempfile.mkstemp(dir=sysconfig)
232 f = os.fdopen(fd, "w")
233 f.write("# Autogenerated by pyplnet... do not edit!\n")
234 if 'DRIVER' in inter:
235 f.write("# using %s driver for device %s\n" % (inter['DRIVER'],dev))
236 f.write('DEVICE=%s\n' % dev)
238 # print the configuration values
239 for (key, val) in inter.iteritems():
240 if key not in ('IFNAME','ALIAS','CFGOPTIONS','DRIVER'):
241 f.write('%s=%s\n' % (key, val))
243 # print the configuration specific option values (if any)
244 if 'CFGOPTIONS' in inter:
245 cfgoptions = inter['CFGOPTIONS']
246 f.write('#CFGOPTIONS are %s\n' % cfgoptions)
247 for cfgoption in cfgoptions.split():
248 key,val = cfgoption.split('=')
252 f.write('%s="%s"\n' % (key,val))
255 # compare whether two files are the same
256 def comparefiles(a,b):
258 logger.verbose("net:InitInterfaces comparing %s with %s" % (a,b))
259 if not os.path.exists(a): return False
264 if not os.path.exists(b): return False
269 return buf_a == buf_b
273 path = "%s/ifcfg-%s" % (sysconfig,dev)
274 if not os.path.exists(path):
275 logger.verbose('net:InitInterfaces adding configuration for %s' % dev)
276 # add ifcfg-$dev configuration file
277 os.rename(tmpnam,path)
281 elif not comparefiles(tmpnam,path):
282 logger.verbose('net:InitInterfaces Configuration change for %s' % dev)
284 logger.verbose('net:InitInterfaces ifdown %s' % dev)
285 # invoke ifdown for the old configuration
286 os.system("/sbin/ifdown %s" % dev)
287 # wait a few secs for ifdown to complete
290 logger.log('replacing configuration for %s' % dev)
291 # replace ifcfg-$dev configuration file
292 os.rename(tmpnam,path)
296 # tmpnam & path are identical
301 fb = file("%s/ifcfg-%s"%(sysconfig,dev),"r")
302 for line in fb.readlines():
304 if parts[0][0]=="#":continue
305 if parts[0].find('='):
306 name,value = parts[0].split('=')
307 # clean up name & value
309 value = value.strip()
310 value = value.strip("'")
311 value = value.strip('"')
312 cfgvariables[name]=value
316 if name in cfgvariables:
317 value=cfgvariables[name]
318 value = value.lower()
322 # skip over device configs with ONBOOT=no
323 if getvar("ONBOOT") == 'no': continue
325 # don't bring up slave devices, the network scripts will
326 # handle those correctly
327 if getvar("SLAVE") == 'yes': continue
330 logger.verbose('net:InitInterfaces bringing up %s' % dev)
331 os.system("/sbin/ifup %s" % dev)
333 if __name__ == "__main__":
337 parser = optparse.OptionParser(usage="plnet [-v] [-f] [-p <program>] -r root node_id")
338 parser.add_option("-v", "--verbose", action="store_true", dest="verbose")
339 parser.add_option("-r", "--root", action="store", type="string",
340 dest="root", default=None)
341 parser.add_option("-f", "--files-only", action="store_true",
343 parser.add_option("-p", "--program", action="store", type="string",
344 dest="program", default="plnet")
345 (options, args) = parser.parse_args()
346 if len(args) != 1 or options.root is None:
347 print >>sys.stderr, "Missing root or node_id"
351 node = shell.GetNodes({'node_id': [int(args[0])]})
353 networks = shell.GetInterfaces({'interface_id': node[0]['interface_ids']})
354 except AttributeError:
355 networks = shell.GetNodeNetworks({'nodenetwork_id':node[0]['nodenetwork_ids']})
359 data = {'hostname': node[0]['hostname'], 'networks': networks}
361 def __init__(self, verbose):
362 self.verbosity = verbose
363 def log(self, msg, loglevel=2):
366 def verbose(self, msg):
368 l = logger(options.verbose)
369 InitInterfaces(l, shell, data, options.root, options.files_only)