1 #!/usr/bin/python /usr/bin/plcsh
13 def InitInterfaces(logger, plc, data, root="", files_only=False, program="NodeManager"):
14 sysconfig = "%s/etc/sysconfig/network-scripts" % root
16 os.makedirs(sysconfig)
18 if e.errno != errno.EEXIST:
21 # query running network interfaces
23 ips = dict(zip(devs.values(), devs.keys()))
26 macs[sioc.gifhwaddr(dev).lower()] = dev
28 # assume data['networks'] contains this node's NodeNetworks
31 hostname = data.get('hostname',socket.gethostname())
33 networks = data['networks']
34 failedToGetSettings = False
35 for network in networks:
36 logger.verbose('net:InitInterfaces interface %d: %s'%(interface,network))
37 logger.verbose('net:InitInterfaces macs = %s' % macs)
38 logger.verbose('net:InitInterfaces ips = %s' % ips)
39 # Get interface name preferably from MAC address, falling back
42 if hwaddr <> None: hwaddr=hwaddr.lower()
44 orig_ifname = macs[hwaddr]
45 elif network['ip'] in ips:
46 orig_ifname = ips[network['ip']]
51 logger.verbose('net:InitInterfaces orig_ifname = %s' % orig_ifname)
57 inter['HWADDR'] = network['mac']
58 if network['is_primary']:
59 inter['PRIMARY']='yes'
61 if network['method'] == "static":
62 inter['BOOTPROTO'] = "static"
63 inter['IPADDR'] = network['ip']
64 inter['NETMASK'] = network['netmask']
65 inter['DNS1'] = network['dns1']
66 inter['DNS2'] = network['dns2']
67 if network['is_primary']:
68 gateway = network['gateway']
70 elif network['method'] == "dhcp":
71 inter['BOOTPROTO'] = "dhcp"
72 inter['PERSISTENT_DHCLIENT'] = "yes"
73 if network['hostname']:
74 inter['DHCP_HOSTNAME'] = network['hostname']
76 inter['DHCP_HOSTNAME'] = hostname
77 if not network['is_primary']:
78 inter['DHCLIENTARGS'] = "-R subnet-mask"
80 if len(network['nodenetwork_setting_ids']) > 0:
82 settings = plc.GetNodeNetworkSettings({'nodenetwork_setting_id':
83 network['nodenetwork_setting_ids']})
85 logger.log("net:InitInterfaces FATAL: failed call GetNodeNetworkSettings({'nodenetwork_setting_id':{%s})"% \
86 network['nodenetwork_setting_ids'])
87 failedToGetSettings = True
88 continue # on to the next network
90 for setting in settings:
91 # to explicitly set interface name
92 settingname = setting['name'].upper()
93 if settingname in ('IFNAME','ALIAS','CFGOPTIONS','DRIVER'):
94 inter[settingname]=setting['value']
96 logger.log("net:InitInterfaces WARNING: ignored setting named %s"%setting['name'])
98 # support aliases to interfaces either by name or HWADDR
100 if 'HWADDR' in inter:
101 hwaddr = inter['HWADDR'].lower()
104 hwifname = macs[hwaddr]
105 if ('IFNAME' in inter) and inter['IFNAME'] <> hwifname:
106 logger.log("net:InitInterfaces WARNING: alias ifname (%s) and hwaddr ifname (%s) do not match"%\
107 (inter['IFNAME'],hwifname))
108 inter['IFNAME'] = hwifname
110 logger.log('net:InitInterfaces WARNING: mac addr %s for alias not found' %(hwaddr,alias))
112 if 'IFNAME' in inter:
113 # stupid RH /etc/sysconfig/network-scripts/ifup-aliases:new_interface()
114 # checks if the "$DEVNUM" only consists of '^[0-9A-Za-z_]*$'. Need to make
115 # our aliases compliant.
116 parts = inter['ALIAS'].split('_')
119 isValid=isValid and part.isalnum()
122 interfaces["%s:%s" % (inter['IFNAME'],inter['ALIAS'])] = inter
124 logger.log("net:InitInterfaces WARNING: interface alias (%s) not a valid string for RH ifup-aliases"% inter['ALIAS'])
126 logger.log("net:InitInterfaces WARNING: interface alias (%s) not matched to an interface"% inter['ALIAS'])
129 if ('IFNAME' not in inter) and not orig_ifname:
130 ifname="eth%d" % (interface-1)
131 # should check if $ifname is an eth already defines
132 if os.path.exists("%s/ifcfg-%s"%(sysconfig,ifname)):
133 logger.log("net:InitInterfaces WARNING: possibly blowing away %s configuration"%ifname)
135 if ('IFNAME' not in inter) and orig_ifname:
138 ifname = inter['IFNAME']
140 interfaces[ifname] = inter
142 m = modprobe.Modprobe()
144 m.input("%s/etc/modprobe.conf" % root, program)
147 for (dev, inter) in interfaces.iteritems():
148 # get the driver string "moduleName option1=a option2=b"
149 driver=inter.get('DRIVER','')
151 driver=driver.split()
152 kernelmodule=driver[0]
153 m.aliasset(dev,kernelmodule)
154 options=" ".join(driver[1:])
156 m.optionsset(dev,options)
157 m.output("%s/etc/modprobe.conf" % root)
159 # clean up after any ifcfg-$dev script that's no longer listed as
160 # part of the NodeNetworks associated with this node
162 # list all network-scripts
163 files = os.listdir(sysconfig)
165 # filter out the ifcfg-* files
168 if f.find("ifcfg-") == 0:
171 # remove loopback (lo) from ifcfgs list
173 if lo in ifcfgs: ifcfgs.remove(lo)
175 # remove known devices from icfgs list
176 for (dev, inter) in interfaces.iteritems():
178 if ifcfg in ifcfgs: ifcfgs.remove(ifcfg)
180 # delete the remaining ifcfgs from
181 deletedSomething = False
183 if not failedToGetSettings:
185 dev = ifcfg[len('ifcfg-'):]
186 path = "%s/ifcfg-%s" % (sysconfig,dev)
188 logger.verbose("net:InitInterfaces removing %s %s"%(dev,path))
189 os.system("/sbin/ifdown %s" % dev)
190 deletedSomething=True
193 # wait a bit for the one or more ifdowns to have taken effect
197 # Write network configuration file
198 networkconf = file("%s/etc/sysconfig/network" % root, "w")
199 networkconf.write("NETWORKING=yes\nHOSTNAME=%s\n" % hostname)
200 if gateway is not None:
201 networkconf.write("GATEWAY=%s\n" % gateway)
204 # Process ifcfg-$dev changes / additions
206 for (dev, inter) in interfaces.iteritems():
207 (fd, tmpnam) = tempfile.mkstemp(dir=sysconfig)
208 f = os.fdopen(fd, "w")
209 f.write("# Autogenerated by pyplnet... do not edit!\n")
210 if 'DRIVER' in inter:
211 f.write("# using %s driver for device %s\n" % (inter['DRIVER'],dev))
212 f.write('DEVICE=%s\n' % dev)
214 # print the configuration values
215 for (key, val) in inter.iteritems():
216 if key not in ('IFNAME','ALIAS','CFGOPTIONS','DRIVER'):
217 f.write('%s=%s\n' % (key, val))
219 # print the configuration specific option values (if any)
220 if 'CFGOPTIONS' in inter:
221 cfgoptions = inter['CFGOPTIONS']
222 f.write('#CFGOPTIONS are %s\n' % cfgoptions)
223 for cfgoption in cfgoptions.split():
224 key,val = cfgoption.split('=')
228 f.write('%s="%s"\n' % (key,val))
231 # compare whether two files are the same
232 def comparefiles(a,b):
234 logger.verbose("net:InitInterfaces comparing %s with %s" % (a,b))
235 if not os.path.exists(a): return False
240 if not os.path.exists(b): return False
245 return buf_a == buf_b
249 path = "%s/ifcfg-%s" % (sysconfig,dev)
250 if not os.path.exists(path):
251 logger.verbose('net:InitInterfaces adding configuration for %s' % dev)
252 # add ifcfg-$dev configuration file
253 os.rename(tmpnam,path)
257 elif not comparefiles(tmpnam,path):
258 logger.verbose('net:InitInterfaces Configuration change for %s' % dev)
260 logger.verbose('net:InitInterfaces ifdown %s' % dev)
261 # invoke ifdown for the old configuration
262 os.system("/sbin/ifdown %s" % dev)
263 # wait a few secs for ifdown to complete
266 logger.log('replacing configuration for %s' % dev)
267 # replace ifcfg-$dev configuration file
268 os.rename(tmpnam,path)
272 # tmpnam & path are identical
277 fb = file("%s/ifcfg-%s"%(sysconfig,dev),"r")
278 for line in fb.readlines():
280 if parts[0][0]=="#":continue
281 if parts[0].find('='):
282 name,value = parts[0].split('=')
283 # clean up name & value
285 value = value.strip()
286 value = value.strip("'")
287 value = value.strip('"')
288 cfgvariables[name]=value
292 if name in cfgvariables:
293 value=cfgvariables[name]
294 value = value.lower()
298 # skip over device configs with ONBOOT=no
299 if getvar("ONBOOT") == 'no': continue
301 # don't bring up slave devices, the network scripts will
302 # handle those correctly
303 if getvar("SLAVE") == 'yes': continue
306 logger.verbose('net:InitInterfaces bringing up %s' % dev)
307 os.system("/sbin/ifup %s" % dev)
309 if __name__ == "__main__":
313 parser = optparse.OptionParser(usage="plnet [-v] [-f] [-p <program>] -r root node_id")
314 parser.add_option("-v", "--verbose", action="store_true", dest="verbose")
315 parser.add_option("-r", "--root", action="store", type="string",
316 dest="root", default=None)
317 parser.add_option("-f", "--files-only", action="store_true",
319 parser.add_option("-p", "--program", action="store", type="string",
320 dest="program", default="plnet")
321 (options, args) = parser.parse_args()
322 if len(args) != 1 or options.root is None:
323 print >>sys.stderr, "Missing root or node_id"
327 node = shell.GetNodes({'node_id': [int(args[0])]})
328 networks = shell.GetNodeNetworks({'nodenetwork_id': node[0]['nodenetwork_ids']})
330 data = {'hostname': node[0]['hostname'], 'networks': networks}
332 def __init__(self, verbose):
333 self.verbosity = verbose
334 def log(self, msg, loglevel=2):
337 def verbose(self, msg):
339 l = logger(options.verbose)
340 InitInterfaces(l, shell, data, options.root, options.files_only)