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
112 settingname = setting['name'].upper()
113 if settingname in ('IFNAME','ALIAS','CFGOPTIONS','DRIVER'):
114 inter[settingname]=setting['value']
116 logger.log("net:InitInterfaces WARNING: ignored setting named %s"%setting['name'])
118 # support aliases to interfaces either by name or HWADDR
120 if 'HWADDR' in inter:
121 hwaddr = inter['HWADDR'].lower()
124 hwifname = macs[hwaddr]
125 if ('IFNAME' in inter) and inter['IFNAME'] <> hwifname:
126 logger.log("net:InitInterfaces WARNING: alias ifname (%s) and hwaddr ifname (%s) do not match"%\
127 (inter['IFNAME'],hwifname))
128 inter['IFNAME'] = hwifname
130 logger.log('net:InitInterfaces WARNING: mac addr %s for alias not found' %(hwaddr,alias))
132 if 'IFNAME' in inter:
133 # stupid RH /etc/sysconfig/network-scripts/ifup-aliases:new_interface()
134 # checks if the "$DEVNUM" only consists of '^[0-9A-Za-z_]*$'. Need to make
135 # our aliases compliant.
136 parts = inter['ALIAS'].split('_')
139 isValid=isValid and part.isalnum()
142 interfaces["%s:%s" % (inter['IFNAME'],inter['ALIAS'])] = inter
144 logger.log("net:InitInterfaces WARNING: interface alias (%s) not a valid string for RH ifup-aliases"% inter['ALIAS'])
146 logger.log("net:InitInterfaces WARNING: interface alias (%s) not matched to an interface"% inter['ALIAS'])
149 if ('IFNAME' not in inter) and not orig_ifname:
150 ifname="eth%d" % (interface-1)
151 # should check if $ifname is an eth already defines
152 if os.path.exists("%s/ifcfg-%s"%(sysconfig,ifname)):
153 logger.log("net:InitInterfaces WARNING: possibly blowing away %s configuration"%ifname)
155 if ('IFNAME' not in inter) and orig_ifname:
158 ifname = inter['IFNAME']
160 interfaces[ifname] = inter
162 m = modprobe.Modprobe()
164 m.input("%s/etc/modprobe.conf" % root, program)
167 for (dev, inter) in interfaces.iteritems():
168 # get the driver string "moduleName option1=a option2=b"
169 driver=inter.get('DRIVER','')
171 driver=driver.split()
172 kernelmodule=driver[0]
173 m.aliasset(dev,kernelmodule)
174 options=" ".join(driver[1:])
176 m.optionsset(dev,options)
177 m.output("%s/etc/modprobe.conf" % root)
179 # clean up after any ifcfg-$dev script that's no longer listed as
180 # part of the NodeNetworks associated with this node
182 # list all network-scripts
183 files = os.listdir(sysconfig)
185 # filter out the ifcfg-* files
188 if f.find("ifcfg-") == 0:
191 # remove loopback (lo) from ifcfgs list
193 if lo in ifcfgs: ifcfgs.remove(lo)
195 # remove known devices from icfgs list
196 for (dev, inter) in interfaces.iteritems():
198 if ifcfg in ifcfgs: ifcfgs.remove(ifcfg)
200 # delete the remaining ifcfgs from
201 deletedSomething = False
203 if not failedToGetSettings:
205 dev = ifcfg[len('ifcfg-'):]
206 path = "%s/ifcfg-%s" % (sysconfig,dev)
208 logger.verbose("net:InitInterfaces removing %s %s"%(dev,path))
209 os.system("/sbin/ifdown %s" % dev)
210 deletedSomething=True
213 # wait a bit for the one or more ifdowns to have taken effect
217 # Write network configuration file
218 networkconf = file("%s/etc/sysconfig/network" % root, "w")
219 networkconf.write("NETWORKING=yes\nHOSTNAME=%s\n" % hostname)
220 if gateway is not None:
221 networkconf.write("GATEWAY=%s\n" % gateway)
224 # Process ifcfg-$dev changes / additions
226 for (dev, inter) in interfaces.iteritems():
227 (fd, tmpnam) = tempfile.mkstemp(dir=sysconfig)
228 f = os.fdopen(fd, "w")
229 f.write("# Autogenerated by pyplnet... do not edit!\n")
230 if 'DRIVER' in inter:
231 f.write("# using %s driver for device %s\n" % (inter['DRIVER'],dev))
232 f.write('DEVICE=%s\n' % dev)
234 # print the configuration values
235 for (key, val) in inter.iteritems():
236 if key not in ('IFNAME','ALIAS','CFGOPTIONS','DRIVER'):
237 f.write('%s=%s\n' % (key, val))
239 # print the configuration specific option values (if any)
240 if 'CFGOPTIONS' in inter:
241 cfgoptions = inter['CFGOPTIONS']
242 f.write('#CFGOPTIONS are %s\n' % cfgoptions)
243 for cfgoption in cfgoptions.split():
244 key,val = cfgoption.split('=')
248 f.write('%s="%s"\n' % (key,val))
251 # compare whether two files are the same
252 def comparefiles(a,b):
254 logger.verbose("net:InitInterfaces comparing %s with %s" % (a,b))
255 if not os.path.exists(a): return False
260 if not os.path.exists(b): return False
265 return buf_a == buf_b
269 path = "%s/ifcfg-%s" % (sysconfig,dev)
270 if not os.path.exists(path):
271 logger.verbose('net:InitInterfaces adding configuration for %s' % dev)
272 # add ifcfg-$dev configuration file
273 os.rename(tmpnam,path)
277 elif not comparefiles(tmpnam,path):
278 logger.verbose('net:InitInterfaces Configuration change for %s' % dev)
280 logger.verbose('net:InitInterfaces ifdown %s' % dev)
281 # invoke ifdown for the old configuration
282 os.system("/sbin/ifdown %s" % dev)
283 # wait a few secs for ifdown to complete
286 logger.log('replacing configuration for %s' % dev)
287 # replace ifcfg-$dev configuration file
288 os.rename(tmpnam,path)
292 # tmpnam & path are identical
297 fb = file("%s/ifcfg-%s"%(sysconfig,dev),"r")
298 for line in fb.readlines():
300 if parts[0][0]=="#":continue
301 if parts[0].find('='):
302 name,value = parts[0].split('=')
303 # clean up name & value
305 value = value.strip()
306 value = value.strip("'")
307 value = value.strip('"')
308 cfgvariables[name]=value
312 if name in cfgvariables:
313 value=cfgvariables[name]
314 value = value.lower()
318 # skip over device configs with ONBOOT=no
319 if getvar("ONBOOT") == 'no': continue
321 # don't bring up slave devices, the network scripts will
322 # handle those correctly
323 if getvar("SLAVE") == 'yes': continue
326 logger.verbose('net:InitInterfaces bringing up %s' % dev)
327 os.system("/sbin/ifup %s" % dev)
329 if __name__ == "__main__":
333 parser = optparse.OptionParser(usage="plnet [-v] [-f] [-p <program>] -r root node_id")
334 parser.add_option("-v", "--verbose", action="store_true", dest="verbose")
335 parser.add_option("-r", "--root", action="store", type="string",
336 dest="root", default=None)
337 parser.add_option("-f", "--files-only", action="store_true",
339 parser.add_option("-p", "--program", action="store", type="string",
340 dest="program", default="plnet")
341 (options, args) = parser.parse_args()
342 if len(args) != 1 or options.root is None:
343 print >>sys.stderr, "Missing root or node_id"
347 node = shell.GetNodes({'node_id': [int(args[0])]})
349 networks = shell.GetInterfaces({'interface_id': node[0]['interface_ids']})
350 except AttributeError:
351 networks = shell.GetNodeNetworks({'nodenetwork_id':node[0]['nodenetwork_ids']})
355 data = {'hostname': node[0]['hostname'], 'networks': networks}
357 def __init__(self, verbose):
358 self.verbosity = verbose
359 def log(self, msg, loglevel=2):
362 def verbose(self, msg):
364 l = logger(options.verbose)
365 InitInterfaces(l, shell, data, options.root, options.files_only)