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']
51 if network['is_primary']:
52 inter['PRIMARY']='yes'
54 if network['method'] == "static":
55 inter['BOOTPROTO'] = "static"
56 inter['IPADDR'] = network['ip']
57 inter['NETMASK'] = network['netmask']
59 elif network['method'] == "dhcp":
60 inter['BOOTPROTO'] = "dhcp"
61 inter['PERSISTENT_DHCLIENT'] = "yes"
62 if network['hostname']:
63 inter['DHCP_HOSTNAME'] = network['hostname']
65 inter['DHCP_HOSTNAME'] = hostname
66 if not network['is_primary']:
67 inter['DHCLIENTARGS'] = "-R subnet-mask"
69 if len(network['interface_tag_ids']) > 0:
71 settings = plc.GetInterfaceTags({'interface_tag_id':
72 network['interface_tag_ids']})
74 logger.log("net:InitInterfaces FATAL: failed call GetInterfaceTags({'interface_tag_id':{%s})"% \
75 network['interface_tag_ids'])
76 failedToGetSettings = True
77 continue # on to the next network
79 for setting in settings:
80 # to explicitly set interface name
81 settingname = setting['name'].upper()
82 if settingname in ('IFNAME','ALIAS','CFGOPTIONS','DRIVER'):
83 inter[settingname]=setting['value']
85 logger.log("net:InitInterfaces WARNING: ignored setting named %s"%setting['name'])
87 # support aliases to interfaces either by name or HWADDR
90 hwaddr = inter['HWADDR'].lower()
93 hwifname = macs[hwaddr]
94 if ('IFNAME' in inter) and inter['IFNAME'] <> hwifname:
95 logger.log("net:InitInterfaces WARNING: alias ifname (%s) and hwaddr ifname (%s) do not match"%\
96 (inter['IFNAME'],hwifname))
97 inter['IFNAME'] = hwifname
99 logger.log('net:InitInterfaces WARNING: mac addr %s for alias not found' %(hwaddr,alias))
101 if 'IFNAME' in inter:
102 # stupid RH /etc/sysconfig/network-scripts/ifup-aliases:new_interface()
103 # checks if the "$DEVNUM" only consists of '^[0-9A-Za-z_]*$'. Need to make
104 # our aliases compliant.
105 parts = inter['ALIAS'].split('_')
108 isValid=isValid and part.isalnum()
111 interfaces["%s:%s" % (inter['IFNAME'],inter['ALIAS'])] = inter
113 logger.log("net:InitInterfaces WARNING: interface alias (%s) not a valid string for RH ifup-aliases"% inter['ALIAS'])
115 logger.log("net:InitInterfaces WARNING: interface alias (%s) not matched to an interface"% inter['ALIAS'])
118 if ('IFNAME' not in inter) and not orig_ifname:
119 ifname="eth%d" % (interface-1)
120 # should check if $ifname is an eth already defines
121 if os.path.exists("%s/ifcfg-%s"%(sysconfig,ifname)):
122 logger.log("net:InitInterfaces WARNING: possibly blowing away %s configuration"%ifname)
124 if ('IFNAME' not in inter) and orig_ifname:
127 ifname = inter['IFNAME']
129 interfaces[ifname] = inter
131 m = modprobe.Modprobe()
133 m.input("%s/etc/modprobe.conf" % root, program)
136 for (dev, inter) in interfaces.iteritems():
137 # get the driver string "moduleName option1=a option2=b"
138 driver=inter.get('DRIVER','')
140 driver=driver.split()
141 kernelmodule=driver[0]
142 m.aliasset(dev,kernelmodule)
143 options=" ".join(driver[1:])
145 m.optionsset(dev,options)
146 m.output("%s/etc/modprobe.conf" % root)
148 # clean up after any ifcfg-$dev script that's no longer listed as
149 # part of the NodeNetworks associated with this node
151 # list all network-scripts
152 files = os.listdir(sysconfig)
154 # filter out the ifcfg-* files
157 if f.find("ifcfg-") == 0:
160 # remove loopback (lo) from ifcfgs list
162 if lo in ifcfgs: ifcfgs.remove(lo)
164 # remove known devices from icfgs list
165 for (dev, inter) in interfaces.iteritems():
167 if ifcfg in ifcfgs: ifcfgs.remove(ifcfg)
169 # delete the remaining ifcfgs from
170 deletedSomething = False
172 if not failedToGetSettings:
174 dev = ifcfg[len('ifcfg-'):]
175 path = "%s/ifcfg-%s" % (sysconfig,dev)
177 logger.verbose("net:InitInterfaces removing %s %s"%(dev,path))
178 os.system("/sbin/ifdown %s" % dev)
179 deletedSomething=True
182 # wait a bit for the one or more ifdowns to have taken effect
186 # Process ifcg-$dev changes / additions
188 for (dev, inter) in interfaces.iteritems():
189 (fd, tmpnam) = tempfile.mkstemp(dir=sysconfig)
190 f = os.fdopen(fd, "w")
191 f.write("# Autogenerated by NodeManager/net.py.... do not edit!\n")
192 if 'DRIVER' in inter:
193 f.write("# using %s driver for device %s\n" % (inter['DRIVER'],dev))
194 f.write('DEVICE="%s"\n' % dev)
196 # print the configuration values
197 for (key, val) in inter.iteritems():
198 if key not in ('IFNAME','ALIAS','CFGOPTIONS','DRIVER'):
199 f.write('%s="%s"\n' % (key, val))
201 # print the configuration specific option values (if any)
202 if 'CFGOPTIONS' in inter:
203 cfgoptions = inter['CFGOPTIONS']
204 f.write('#CFGOPTIONS are %s\n' % cfgoptions)
205 for cfgoption in cfgoptions.split():
206 key,val = cfgoption.split('=')
210 f.write('%s="%s"\n' % (key,val))
213 # compare whether two files are the same
214 def comparefiles(a,b):
216 logger.verbose("net:InitInterfaces comparing %s with %s" % (a,b))
217 if not os.path.exists(a): return False
222 if not os.path.exists(b): return False
227 return buf_a == buf_b
231 path = "%s/ifcfg-%s" % (sysconfig,dev)
232 if not os.path.exists(path):
233 logger.verbose('net:InitInterfaces adding configuration for %s' % dev)
234 # add ifcfg-$dev configuration file
235 os.rename(tmpnam,path)
239 elif not comparefiles(tmpnam,path):
240 logger.verbose('net:InitInterfaces Configuration change for %s' % dev)
242 logger.verbose('net:InitInterfaces ifdown %s' % dev)
243 # invoke ifdown for the old configuration
244 os.system("/sbin/ifdown %s" % dev)
245 # wait a few secs for ifdown to complete
248 logger.log('replacing configuration for %s' % dev)
249 # replace ifcfg-$dev configuration file
250 os.rename(tmpnam,path)
254 # tmpnam & path are identical
259 fb = file("%s/ifcfg-%s"%(sysconfig,dev),"r")
260 for line in fb.readlines():
262 if parts[0][0]=="#":continue
263 if parts[0].find('='):
264 name,value = parts[0].split('=')
265 # clean up name & value
267 value = value.strip()
268 value = value.strip("'")
269 value = value.strip('"')
270 cfgvariables[name]=value
274 if name in cfgvariables:
275 value=cfgvariables[name]
276 value = value.lower()
280 # skip over device configs with ONBOOT=no
281 if getvar("ONBOOT") == 'no': continue
283 # don't bring up slave devices, the network scripts will
284 # handle those correctly
285 if getvar("SLAVE") == 'yes': continue
288 logger.verbose('net:InitInterfaces bringing up %s' % dev)
289 os.system("/sbin/ifup %s" % dev)
291 if __name__ == "__main__":
295 parser = optparse.OptionParser(usage="plnet [-v] [-f] [-p <program>] -r root node_id")
296 parser.add_option("-v", "--verbose", action="store_true", dest="verbose")
297 parser.add_option("-r", "--root", action="store", type="string",
298 dest="root", default=None)
299 parser.add_option("-f", "--files-only", action="store_true",
301 parser.add_option("-p", "--program", action="store", type="string",
302 dest="program", default="plnet")
303 (options, args) = parser.parse_args()
304 if len(args) != 1 or options.root is None:
305 print >>sys.stderr, "Missing root or node_id"
309 node = shell.GetNodes({'node_id': [int(args[0])]})
310 networks = shell.GetInterfaces({'interface_id': node[0]['interface_ids']})
312 data = {'hostname': node[0]['hostname'], 'networks': networks}
314 def __init__(self, verbose):
315 self.verbosity = verbose
316 def log(self, msg, loglevel=2):
319 def verbose(self, msg):
321 l = logger(options.verbose)
322 InitInterfaces(l, shell, data, options.root, options.files_only)