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 if network['is_primary']:
66 gateway = network['gateway']
68 elif network['method'] == "dhcp":
69 inter['BOOTPROTO'] = "dhcp"
70 inter['PERSISTENT_DHCLIENT'] = "yes"
71 if network['hostname']:
72 inter['DHCP_HOSTNAME'] = network['hostname']
74 inter['DHCP_HOSTNAME'] = hostname
75 if not network['is_primary']:
76 inter['DHCLIENTARGS'] = "-R subnet-mask"
78 if len(network['interface_tag_ids']) > 0:
80 settings = plc.GetInterfaceTags({'interface_tag_id':
81 network['interface_tag_ids']})
83 logger.log("net:InitInterfaces FATAL: failed call GetInterfaceTags({'interface_tag_id':{%s})"% \
84 network['interface_tag_ids'])
85 failedToGetSettings = True
86 continue # on to the next network
88 for setting in settings:
89 # to explicitly set interface name
90 settingname = setting['name'].upper()
91 if settingname in ('IFNAME','ALIAS','CFGOPTIONS','DRIVER'):
92 inter[settingname]=setting['value']
94 logger.log("net:InitInterfaces WARNING: ignored setting named %s"%setting['name'])
96 # support aliases to interfaces either by name or HWADDR
99 hwaddr = inter['HWADDR'].lower()
102 hwifname = macs[hwaddr]
103 if ('IFNAME' in inter) and inter['IFNAME'] <> hwifname:
104 logger.log("net:InitInterfaces WARNING: alias ifname (%s) and hwaddr ifname (%s) do not match"%\
105 (inter['IFNAME'],hwifname))
106 inter['IFNAME'] = hwifname
108 logger.log('net:InitInterfaces WARNING: mac addr %s for alias not found' %(hwaddr,alias))
110 if 'IFNAME' in inter:
111 # stupid RH /etc/sysconfig/network-scripts/ifup-aliases:new_interface()
112 # checks if the "$DEVNUM" only consists of '^[0-9A-Za-z_]*$'. Need to make
113 # our aliases compliant.
114 parts = inter['ALIAS'].split('_')
117 isValid=isValid and part.isalnum()
120 interfaces["%s:%s" % (inter['IFNAME'],inter['ALIAS'])] = inter
122 logger.log("net:InitInterfaces WARNING: interface alias (%s) not a valid string for RH ifup-aliases"% inter['ALIAS'])
124 logger.log("net:InitInterfaces WARNING: interface alias (%s) not matched to an interface"% inter['ALIAS'])
127 if ('IFNAME' not in inter) and not orig_ifname:
128 ifname="eth%d" % (interface-1)
129 # should check if $ifname is an eth already defines
130 if os.path.exists("%s/ifcfg-%s"%(sysconfig,ifname)):
131 logger.log("net:InitInterfaces WARNING: possibly blowing away %s configuration"%ifname)
133 if ('IFNAME' not in inter) and orig_ifname:
136 ifname = inter['IFNAME']
138 interfaces[ifname] = inter
140 m = modprobe.Modprobe()
142 m.input("%s/etc/modprobe.conf" % root, program)
145 for (dev, inter) in interfaces.iteritems():
146 # get the driver string "moduleName option1=a option2=b"
147 driver=inter.get('DRIVER','')
149 driver=driver.split()
150 kernelmodule=driver[0]
151 m.aliasset(dev,kernelmodule)
152 options=" ".join(driver[1:])
154 m.optionsset(dev,options)
155 m.output("%s/etc/modprobe.conf" % root)
157 # clean up after any ifcfg-$dev script that's no longer listed as
158 # part of the NodeNetworks associated with this node
160 # list all network-scripts
161 files = os.listdir(sysconfig)
163 # filter out the ifcfg-* files
166 if f.find("ifcfg-") == 0:
169 # remove loopback (lo) from ifcfgs list
171 if lo in ifcfgs: ifcfgs.remove(lo)
173 # remove known devices from icfgs list
174 for (dev, inter) in interfaces.iteritems():
176 if ifcfg in ifcfgs: ifcfgs.remove(ifcfg)
178 # delete the remaining ifcfgs from
179 deletedSomething = False
181 if not failedToGetSettings:
183 dev = ifcfg[len('ifcfg-'):]
184 path = "%s/ifcfg-%s" % (sysconfig,dev)
186 logger.verbose("net:InitInterfaces removing %s %s"%(dev,path))
187 os.system("/sbin/ifdown %s" % dev)
188 deletedSomething=True
191 # wait a bit for the one or more ifdowns to have taken effect
195 # Write network configuration file
196 networkconf = file("%s/etc/sysconfig/network" % root, "w")
197 networkconf.write("NETWORKING=yes\nHOSTNAME=%s\n" % hostname)
198 if gateway is not None:
199 networkconf.write("GATEWAY=%s\n" % gateway)
202 # Process ifcfg-$dev changes / additions
204 for (dev, inter) in interfaces.iteritems():
205 (fd, tmpnam) = tempfile.mkstemp(dir=sysconfig)
206 f = os.fdopen(fd, "w")
207 f.write("# Autogenerated by pyplnet... do not edit!\n")
208 if 'DRIVER' in inter:
209 f.write("# using %s driver for device %s\n" % (inter['DRIVER'],dev))
210 f.write('DEVICE=%s\n' % dev)
212 # print the configuration values
213 for (key, val) in inter.iteritems():
214 if key not in ('IFNAME','ALIAS','CFGOPTIONS','DRIVER'):
215 f.write('%s=%s\n' % (key, val))
217 # print the configuration specific option values (if any)
218 if 'CFGOPTIONS' in inter:
219 cfgoptions = inter['CFGOPTIONS']
220 f.write('#CFGOPTIONS are %s\n' % cfgoptions)
221 for cfgoption in cfgoptions.split():
222 key,val = cfgoption.split('=')
226 f.write('%s="%s"\n' % (key,val))
229 # compare whether two files are the same
230 def comparefiles(a,b):
232 logger.verbose("net:InitInterfaces comparing %s with %s" % (a,b))
233 if not os.path.exists(a): return False
238 if not os.path.exists(b): return False
243 return buf_a == buf_b
247 path = "%s/ifcfg-%s" % (sysconfig,dev)
248 if not os.path.exists(path):
249 logger.verbose('net:InitInterfaces adding configuration for %s' % dev)
250 # add ifcfg-$dev configuration file
251 os.rename(tmpnam,path)
255 elif not comparefiles(tmpnam,path):
256 logger.verbose('net:InitInterfaces Configuration change for %s' % dev)
258 logger.verbose('net:InitInterfaces ifdown %s' % dev)
259 # invoke ifdown for the old configuration
260 os.system("/sbin/ifdown %s" % dev)
261 # wait a few secs for ifdown to complete
264 logger.log('replacing configuration for %s' % dev)
265 # replace ifcfg-$dev configuration file
266 os.rename(tmpnam,path)
270 # tmpnam & path are identical
275 fb = file("%s/ifcfg-%s"%(sysconfig,dev),"r")
276 for line in fb.readlines():
278 if parts[0][0]=="#":continue
279 if parts[0].find('='):
280 name,value = parts[0].split('=')
281 # clean up name & value
283 value = value.strip()
284 value = value.strip("'")
285 value = value.strip('"')
286 cfgvariables[name]=value
290 if name in cfgvariables:
291 value=cfgvariables[name]
292 value = value.lower()
296 # skip over device configs with ONBOOT=no
297 if getvar("ONBOOT") == 'no': continue
299 # don't bring up slave devices, the network scripts will
300 # handle those correctly
301 if getvar("SLAVE") == 'yes': continue
304 logger.verbose('net:InitInterfaces bringing up %s' % dev)
305 os.system("/sbin/ifup %s" % dev)
307 if __name__ == "__main__":
311 parser = optparse.OptionParser(usage="plnet [-v] [-f] [-p <program>] -r root node_id")
312 parser.add_option("-v", "--verbose", action="store_true", dest="verbose")
313 parser.add_option("-r", "--root", action="store", type="string",
314 dest="root", default=None)
315 parser.add_option("-f", "--files-only", action="store_true",
317 parser.add_option("-p", "--program", action="store", type="string",
318 dest="program", default="plnet")
319 (options, args) = parser.parse_args()
320 if len(args) != 1 or options.root is None:
321 print >>sys.stderr, "Missing root or node_id"
325 node = shell.GetNodes({'node_id': [int(args[0])]})
326 networks = shell.GetInterfaces({'interface_id': node[0]['interface_ids']})
328 data = {'hostname': node[0]['hostname'], 'networks': networks}
330 def __init__(self, verbose):
331 self.verbosity = verbose
332 def log(self, msg, loglevel=2):
335 def verbose(self, msg):
337 l = logger(options.verbose)
338 InitInterfaces(l, shell, data, options.root, options.files_only)