1 #!/usr/bin/python /usr/bin/plcsh
12 def InitInterfaces(logger, plc, data, root="", files_only=False, program="NodeManager"):
13 sysconfig = "%s/etc/sysconfig/network-scripts" % root
15 # query running network interfaces
17 ips = dict(zip(devs.values(), devs.keys()))
20 macs[sioc.gifhwaddr(dev).lower()] = dev
22 # assume data['networks'] contains this node's NodeNetworks
25 hostname = data.get('hostname',socket.gethostname())
26 networks = data['networks']
27 failedToGetSettings = False
28 for network in networks:
29 logger.verbose('net:InitInterfaces interface %d: %s'%(interface,network))
30 logger.verbose('net:InitInterfaces macs = %s' % macs)
31 logger.verbose('net:InitInterfaces ips = %s' % ips)
32 # Get interface name preferably from MAC address, falling back
35 if hwaddr <> None: hwaddr=hwaddr.lower()
37 orig_ifname = macs[hwaddr]
38 elif network['ip'] in ips:
39 orig_ifname = ips[network['ip']]
44 logger.verbose('net:InitInterfaces orig_ifname = %s' % orig_ifname)
50 inter['HWADDR'] = network['mac']
52 if network['method'] == "static":
53 inter['BOOTPROTO'] = "static"
54 inter['IPADDR'] = network['ip']
55 inter['NETMASK'] = network['netmask']
57 elif network['method'] == "dhcp":
58 inter['BOOTPROTO'] = "dhcp"
59 inter['PERSISTENT_DHCLIENT'] = "yes"
60 if network['hostname']:
61 inter['DHCP_HOSTNAME'] = network['hostname']
63 inter['DHCP_HOSTNAME'] = hostname
64 if not network['is_primary']:
65 inter['DHCLIENTARGS'] = "-R subnet-mask"
67 if len(network['interface_tag_ids']) > 0:
69 settings = plc.GetInterfaceTags({'interface_tag_id':
70 network['interface_tag_ids']})
72 logger.log("net:InitInterfaces FATAL: failed call GetInterfaceTags({'interface_tag_id':{%s})"% \
73 network['interface_tag_ids'])
74 failedToGetSettings = True
75 continue # on to the next network
77 for setting in settings:
78 # to explicitly set interface name
79 settingname = setting['name'].upper()
80 if settingname in ('IFNAME','ALIAS','CFGOPTIONS','DRIVER'):
81 inter[settingname]=setting['value']
83 logger.log("net:InitInterfaces WARNING: ignored setting named %s"%setting['name'])
85 # support aliases to interfaces either by name or HWADDR
88 hwaddr = inter['HWADDR'].lower()
91 hwifname = macs[hwaddr]
92 if ('IFNAME' in inter) and inter['IFNAME'] <> hwifname:
93 logger.log("net:InitInterfaces WARNING: alias ifname (%s) and hwaddr ifname (%s) do not match"%\
94 (inter['IFNAME'],hwifname))
95 inter['IFNAME'] = hwifname
97 logger.log('net:InitInterfaces WARNING: mac addr %s for alias not found' %(hwaddr,alias))
100 # stupid RH /etc/sysconfig/network-scripts/ifup-aliases:new_interface()
101 # checks if the "$DEVNUM" only consists of '^[0-9A-Za-z_]*$'. Need to make
102 # our aliases compliant.
103 parts = inter['ALIAS'].split('_')
106 isValid=isValid and part.isalnum()
109 interfaces["%s:%s" % (inter['IFNAME'],inter['ALIAS'])] = inter
111 logger.log("net:InitInterfaces WARNING: interface alias (%s) not a valid string for RH ifup-aliases"% inter['ALIAS'])
113 logger.log("net:InitInterfaces WARNING: interface alias (%s) not matched to an interface"% inter['ALIAS'])
116 if ('IFNAME' not in inter) and not orig_ifname:
117 ifname="eth%d" % (interface-1)
118 # should check if $ifname is an eth already defines
119 if os.path.exists("%s/ifcfg-%s"%(sysconfig,ifname)):
120 logger.log("net:InitInterfaces WARNING: possibly blowing away %s configuration"%ifname)
122 if ('IFNAME' not in inter) and orig_ifname:
125 ifname = inter['IFNAME']
127 interfaces[ifname] = inter
129 m = modprobe.Modprobe()
131 m.input("%s/etc/modprobe.conf" % root, program)
134 for (dev, inter) in interfaces.iteritems():
135 # get the driver string "moduleName option1=a option2=b"
136 driver=inter.get('DRIVER','')
138 driver=driver.split()
139 kernelmodule=driver[0]
140 m.aliasset(dev,kernelmodule)
141 options=" ".join(driver[1:])
143 m.optionsset(dev,options)
144 m.output("%s/etc/modprobe.conf" % root)
146 # clean up after any ifcfg-$dev script that's no longer listed as
147 # part of the NodeNetworks associated with this node
149 # list all network-scripts
150 files = os.listdir(sysconfig)
152 # filter out the ifcfg-* files
155 if f.find("ifcfg-") == 0:
158 # remove loopback (lo) from ifcfgs list
160 if lo in ifcfgs: ifcfgs.remove(lo)
162 # remove known devices from icfgs list
163 for (dev, inter) in interfaces.iteritems():
165 if ifcfg in ifcfgs: ifcfgs.remove(ifcfg)
167 # delete the remaining ifcfgs from
168 deletedSomething = False
170 if not failedToGetSettings:
172 dev = ifcfg[len('ifcfg-'):]
173 path = "%s/ifcfg-%s" % (sysconfig,dev)
175 logger.verbose("net:InitInterfaces removing %s %s"%(dev,path))
176 os.system("/sbin/ifdown %s" % dev)
177 deletedSomething=True
180 # wait a bit for the one or more ifdowns to have taken effect
184 # Process ifcg-$dev changes / additions
186 for (dev, inter) in interfaces.iteritems():
187 (fd, tmpnam) = tempfile.mkstemp(dir=sysconfig)
188 f = os.fdopen(fd, "w")
189 f.write("# Autogenerated by NodeManager/net.py.... do not edit!\n")
190 if 'DRIVER' in inter:
191 f.write("# using %s driver for device %s\n" % (inter['DRIVER'],dev))
192 f.write('DEVICE="%s"\n' % dev)
194 # print the configuration values
195 for (key, val) in inter.iteritems():
196 if key not in ('IFNAME','ALIAS','CFGOPTIONS','DRIVER'):
197 f.write('%s="%s"\n' % (key, val))
199 # print the configuration specific option values (if any)
200 if 'CFGOPTIONS' in inter:
201 cfgoptions = inter['CFGOPTIONS']
202 f.write('#CFGOPTIONS are %s\n' % cfgoptions)
203 for cfgoption in cfgoptions.split():
204 key,val = cfgoption.split('=')
208 f.write('%s="%s"\n' % (key,val))
211 # compare whether two files are the same
212 def comparefiles(a,b):
214 logger.verbose("net:InitInterfaces comparing %s with %s" % (a,b))
215 if not os.path.exists(a): return False
220 if not os.path.exists(b): return False
225 return buf_a == buf_b
229 path = "%s/ifcfg-%s" % (sysconfig,dev)
230 if not os.path.exists(path):
231 logger.verbose('net:InitInterfaces adding configuration for %s' % dev)
232 # add ifcfg-$dev configuration file
233 os.rename(tmpnam,path)
237 elif not comparefiles(tmpnam,path):
238 logger.verbose('net:InitInterfaces Configuration change for %s' % dev)
240 logger.verbose('net:InitInterfaces ifdown %s' % dev)
241 # invoke ifdown for the old configuration
242 os.system("/sbin/ifdown %s" % dev)
243 # wait a few secs for ifdown to complete
246 logger.log('replacing configuration for %s' % dev)
247 # replace ifcfg-$dev configuration file
248 os.rename(tmpnam,path)
252 # tmpnam & path are identical
257 fb = file("%s/ifcfg-%s"%(sysconfig,dev),"r")
258 for line in fb.readlines():
260 if parts[0][0]=="#":continue
261 if parts[0].find('='):
262 name,value = parts[0].split('=')
263 # clean up name & value
265 value = value.strip()
266 value = value.strip("'")
267 value = value.strip('"')
268 cfgvariables[name]=value
272 if name in cfgvariables:
273 value=cfgvariables[name]
274 value = value.lower()
278 # skip over device configs with ONBOOT=no
279 if getvar("ONBOOT") == 'no': continue
281 # don't bring up slave devices, the network scripts will
282 # handle those correctly
283 if getvar("SLAVE") == 'yes': continue
286 logger.verbose('net:InitInterfaces bringing up %s' % dev)
287 os.system("/sbin/ifup %s" % dev)
289 if __name__ == "__main__":
293 parser = optparse.OptionParser(usage="plnet [-v] [-f] [-p <program>] -r root node_id")
294 parser.add_option("-v", "--verbose", action="store_true", dest="verbose")
295 parser.add_option("-r", "--root", action="store", type="string",
296 dest="root", default=None)
297 parser.add_option("-f", "--files-only", action="store_true",
299 parser.add_option("-p", "--program", action="store", type="string",
300 dest="program", default="plnet")
301 (options, args) = parser.parse_args()
302 if len(args) != 1 or options.root is None:
303 print >>sys.stderr, "Missing root or node_id"
307 node = shell.GetNodes({'node_id': [int(args[0])]})
308 networks = shell.GetInterfaces({'interface_id': node[0]['interface_ids']})
310 data = {'hostname': node[0]['hostname'], 'networks': networks}
312 def __init__(self, verbose):
313 self.verbosity = verbose
314 def log(self, msg, loglevel=2):
317 def verbose(self, msg):
319 l = logger(options.verbose)
320 InitInterfaces(l, shell, data, options.root, options.files_only)