1 #!/usr/bin/python /usr/bin/plcsh
12 def InitInterfaces(logger, plc, data, root="", files_only=False):
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 if network['hostname']:
60 inter['DHCP_HOSTNAME'] = network['hostname']
62 inter['DHCP_HOSTNAME'] = hostname
63 if not network['is_primary']:
64 inter['DHCLIENTARGS'] = "-R subnet-mask"
66 if len(network['interface_tag_ids']) > 0:
68 settings = plc.GetInterfaceTags({'interface_tag_id':
69 network['interface_tag_ids']})
71 logger.log("net:InitInterfaces FATAL: failed call GetInterfaceTags({'interface_tag_id':{%s})"% \
72 network['interface_tag_ids'])
73 failedToGetSettings = True
74 continue # on to the next network
76 for setting in settings:
77 # to explicitly set interface name
78 settingname = setting['name'].upper()
79 if settingname in ('IFNAME','ALIAS','CFGOPTIONS','DRIVER'):
80 inter[settingname]=setting['value']
82 logger.log("net:InitInterfaces WARNING: ignored setting named %s"%setting['name'])
84 # support aliases to interfaces either by name or HWADDR
87 hwaddr = inter['HWADDR'].lower()
90 hwifname = macs[hwaddr]
91 if ('IFNAME' in inter) and inter['IFNAME'] <> hwifname:
92 logger.log("net:InitInterfaces WARNING: alias ifname (%s) and hwaddr ifname (%s) do not match"%\
93 (inter['IFNAME'],hwifname))
94 inter['IFNAME'] = hwifname
96 logger.log('net:InitInterfaces WARNING: mac addr %s for alias not found' %(hwaddr,alias))
99 # stupid RH /etc/sysconfig/network-scripts/ifup-aliases:new_interface()
100 # checks if the "$DEVNUM" only consists of '^[0-9A-Za-z_]*$'. Need to make
101 # our aliases compliant.
102 parts = inter['ALIAS'].split('_')
105 isValid=isValid and part.isalnum()
108 interfaces["%s:%s" % (inter['IFNAME'],inter['ALIAS'])] = inter
110 logger.log("net:InitInterfaces WARNING: interface alias (%s) not a valid string for RH ifup-aliases"% inter['ALIAS'])
112 logger.log("net:InitInterfaces WARNING: interface alias (%s) not matched to an interface"% inter['ALIAS'])
115 if ('IFNAME' not in inter) and not orig_ifname:
116 ifname="eth%d" % (interface-1)
117 # should check if $ifname is an eth already defines
118 if os.path.exists("%s/ifcfg-%s"%(sysconfig,ifname)):
119 logger.log("net:InitInterfaces WARNING: possibly blowing away %s configuration"%ifname)
121 if ('IFNAME' not in inter) and orig_ifname:
124 ifname = inter['IFNAME']
126 interfaces[ifname] = inter
128 m = modprobe.Modprobe()
129 m.input("%s/etc/modprobe.conf" % root)
130 for (dev, inter) in interfaces.iteritems():
131 # get the driver string "moduleName option1=a option2=b"
132 driver=inter.get('DRIVER','')
134 driver=driver.split()
135 kernelmodule=driver[0]
136 m.aliasset(dev,kernelmodule)
137 options=" ".join(driver[1:])
139 m.optionsset(dev,options)
140 m.output("%s/etc/modprobe.conf" % root)
142 # clean up after any ifcfg-$dev script that's no longer listed as
143 # part of the NodeNetworks associated with this node
145 # list all network-scripts
146 files = os.listdir(sysconfig)
148 # filter out the ifcfg-* files
151 if f.find("ifcfg-") == 0:
154 # remove loopback (lo) from ifcfgs list
156 if lo in ifcfgs: ifcfgs.remove(lo)
158 # remove known devices from icfgs list
159 for (dev, inter) in interfaces.iteritems():
161 if ifcfg in ifcfgs: ifcfgs.remove(ifcfg)
163 # delete the remaining ifcfgs from
164 deletedSomething = False
166 if not failedToGetSettings:
168 dev = ifcfg[len('ifcfg-'):]
169 path = "%s/ifcfg-%s" % (sysconfig,dev)
171 logger.verbose("net:InitInterfaces removing %s %s"%(dev,path))
172 os.system("/sbin/ifdown %s" % dev)
173 deletedSomething=True
176 # wait a bit for the one or more ifdowns to have taken effect
180 # Process ifcg-$dev changes / additions
182 for (dev, inter) in interfaces.iteritems():
183 (fd, tmpnam) = tempfile.mkstemp(dir=sysconfig)
184 f = os.fdopen(fd, "w")
185 f.write("# Autogenerated by NodeManager/net.py.... do not edit!\n")
186 if 'DRIVER' in inter:
187 f.write("# using %s driver for device %s\n" % (inter['DRIVER'],dev))
188 f.write('DEVICE="%s"\n' % dev)
190 # print the configuration values
191 for (key, val) in inter.iteritems():
192 if key not in ('IFNAME','ALIAS','CFGOPTIONS','DRIVER'):
193 f.write('%s="%s"\n' % (key, val))
195 # print the configuration specific option values (if any)
196 if 'CFGOPTIONS' in inter:
197 cfgoptions = inter['CFGOPTIONS']
198 f.write('#CFGOPTIONS are %s\n' % cfgoptions)
199 for cfgoption in cfgoptions.split():
200 key,val = cfgoption.split('=')
204 f.write('%s="%s"\n' % (key,val))
207 # compare whether two files are the same
208 def comparefiles(a,b):
210 logger.verbose("net:InitInterfaces comparing %s with %s" % (a,b))
211 if not os.path.exists(a): return False
216 if not os.path.exists(b): return False
221 return buf_a == buf_b
225 path = "%s/ifcfg-%s" % (sysconfig,dev)
226 if not os.path.exists(path):
227 logger.verbose('net:InitInterfaces adding configuration for %s' % dev)
228 # add ifcfg-$dev configuration file
229 os.rename(tmpnam,path)
233 elif not comparefiles(tmpnam,path):
234 logger.verbose('net:InitInterfaces Configuration change for %s' % dev)
236 logger.verbose('net:InitInterfaces ifdown %s' % dev)
237 # invoke ifdown for the old configuration
238 os.system("/sbin/ifdown %s" % dev)
239 # wait a few secs for ifdown to complete
242 logger.log('replacing configuration for %s' % dev)
243 # replace ifcfg-$dev configuration file
244 os.rename(tmpnam,path)
248 # tmpnam & path are identical
253 fb = file("%s/ifcfg-%s"%(sysconfig,dev),"r")
254 for line in fb.readlines():
256 if parts[0][0]=="#":continue
257 if parts[0].find('='):
258 name,value = parts[0].split('=')
259 # clean up name & value
261 value = value.strip()
262 value = value.strip("'")
263 value = value.strip('"')
264 cfgvariables[name]=value
268 if name in cfgvariables:
269 value=cfgvariables[name]
270 value = value.lower()
274 # skip over device configs with ONBOOT=no
275 if getvar("ONBOOT") == 'no': continue
277 # don't bring up slave devices, the network scripts will
278 # handle those correctly
279 if getvar("SLAVE") == 'yes': continue
282 logger.verbose('net:InitInterfaces bringing up %s' % dev)
283 os.system("/sbin/ifup %s" % dev)
285 if __name__ == "__main__":
289 parser = optparse.OptionParser()
290 parser.add_option("-v", "--verbose", action="store_true", dest="verbose")
291 parser.add_option("-r", "--root", action="store", type="string",
292 dest="root", default=None)
293 parser.add_option("-f", "--files-only", action="store_true",
295 (options, args) = parser.parse_args()
296 if len(args) != 1 or options.root is None:
297 print >>sys.stderr, \
298 "Usage: %s [-v] [-f] -r <root> node_id" % sys.argv[0]
301 node = shell.GetNodes({'node_id': [int(args[0])]})
302 networks = shell.GetInterfaces({'interface_id': node[0]['interface_ids']})
304 data = {'hostname': node[0]['hostname'], 'networks': networks}
306 def __init__(self, verbose):
307 self.verbosity = verbose
308 def log(self, msg, loglevel=2):
311 def verbose(self, msg):
313 l = logger(options.verbose)
314 InitInterfaces(l, shell, data, options.root, options.files_only)