1 #!/usr/bin/python /usr/bin/plcsh
16 def InitInterfaces(logger, plc, data, root="", files_only=False, program="NodeManager"):
19 sysconfig = "%s/etc/sysconfig/network-scripts" % root
21 os.makedirs(sysconfig)
23 if e.errno != errno.EEXIST:
26 # query running network interfaces
28 ips = dict(zip(devs.values(), devs.keys()))
31 macs[sioc.gifhwaddr(dev).lower()] = dev
33 # assume data['networks'] contains this node's NodeNetworks
36 hostname = data.get('hostname',socket.gethostname())
38 networks = data['networks']
39 failedToGetSettings = False
40 for network in networks:
41 logger.verbose('net:InitInterfaces interface %d: %s'%(interface,network))
42 logger.verbose('net:InitInterfaces macs = %s' % macs)
43 logger.verbose('net:InitInterfaces ips = %s' % ips)
44 # Get interface name preferably from MAC address, falling back
47 if hwaddr <> None: hwaddr=hwaddr.lower()
49 orig_ifname = macs[hwaddr]
50 elif network['ip'] in ips:
51 orig_ifname = ips[network['ip']]
56 logger.verbose('net:InitInterfaces orig_ifname = %s' % orig_ifname)
62 inter['HWADDR'] = network['mac']
63 if network['is_primary']:
64 inter['PRIMARY']='yes'
66 if network['method'] == "static":
67 inter['BOOTPROTO'] = "static"
68 inter['IPADDR'] = network['ip']
69 inter['NETMASK'] = network['netmask']
70 inter['DNS1'] = network['dns1']
71 inter['DNS2'] = network['dns2']
72 if network['is_primary']:
73 gateway = network['gateway']
75 elif network['method'] == "dhcp":
76 inter['BOOTPROTO'] = "dhcp"
77 inter['PERSISTENT_DHCLIENT'] = "yes"
78 if network['hostname']:
79 inter['DHCP_HOSTNAME'] = network['hostname']
81 inter['DHCP_HOSTNAME'] = hostname
82 if not network['is_primary']:
83 inter['DHCLIENTARGS'] = "-R subnet-mask"
86 plc.GetInterfaceTags()
88 except AttributeError:
92 interface_tag_ids = "interface_tag_ids"
93 interface_tag_id = "interface_tag_id"
95 interface_tag_ids = "nodenetwork_setting_ids"
96 interface_tag_id = "nodenetwork_setting_id"
98 if len(network[interface_tag_ids]) > 0:
101 settings = plc.GetInterfaceTags({interface_tag_id:network[interface_tag_ids]})
103 settings = plc.GetNodeNetworkSettings({interface_tag_id:network[interface_tag_ids]})
105 logger.log("net:InitInterfaces FATAL: failed call GetInterfaceTags({'interface_tag_id':{%s})"% \
106 network['interface_tag_ids'])
107 failedToGetSettings = True
108 continue # on to the next network
110 for setting in settings:
111 # to explicitly set interface name
116 settingname = setting[name_key].upper()
117 if settingname in ('IFNAME','ALIAS','CFGOPTIONS','DRIVER'):
118 inter[settingname]=setting['value']
120 elif settingname in \
121 [ "MODE", "ESSID", "NW", "FREQ", "CHANNEL", "SENS", "RATE",
122 "KEY", "KEY1", "KEY2", "KEY3", "KEY4", "SECURITYMODE",
123 "IWCONFIG", "IWPRIV" ] :
124 inter [settingname] = setting['value']
125 inter ['TYPE']='Wireless'
127 logger.log("net:InitInterfaces WARNING: ignored setting named %s"%setting[name_key])
129 # support aliases to interfaces either by name or HWADDR
131 if 'HWADDR' in inter:
132 hwaddr = inter['HWADDR'].lower()
135 hwifname = macs[hwaddr]
136 if ('IFNAME' in inter) and inter['IFNAME'] <> hwifname:
137 logger.log("net:InitInterfaces WARNING: alias ifname (%s) and hwaddr ifname (%s) do not match"%\
138 (inter['IFNAME'],hwifname))
139 inter['IFNAME'] = hwifname
141 logger.log('net:InitInterfaces WARNING: mac addr %s for alias not found' %(hwaddr,alias))
143 if 'IFNAME' in inter:
144 # stupid RH /etc/sysconfig/network-scripts/ifup-aliases:new_interface()
145 # checks if the "$DEVNUM" only consists of '^[0-9A-Za-z_]*$'. Need to make
146 # our aliases compliant.
147 parts = inter['ALIAS'].split('_')
150 isValid=isValid and part.isalnum()
153 interfaces["%s:%s" % (inter['IFNAME'],inter['ALIAS'])] = inter
155 logger.log("net:InitInterfaces WARNING: interface alias (%s) not a valid string for RH ifup-aliases"% inter['ALIAS'])
157 logger.log("net:InitInterfaces WARNING: interface alias (%s) not matched to an interface"% inter['ALIAS'])
160 if ('IFNAME' not in inter) and not orig_ifname:
161 ifname="eth%d" % (interface-1)
162 # should check if $ifname is an eth already defines
163 if os.path.exists("%s/ifcfg-%s"%(sysconfig,ifname)):
164 logger.log("net:InitInterfaces WARNING: possibly blowing away %s configuration"%ifname)
166 if ('IFNAME' not in inter) and orig_ifname:
169 ifname = inter['IFNAME']
171 interfaces[ifname] = inter
173 m = modprobe.Modprobe()
175 m.input("%s/etc/modprobe.conf" % root)
178 for (dev, inter) in interfaces.iteritems():
179 # get the driver string "moduleName option1=a option2=b"
180 driver=inter.get('DRIVER','')
182 driver=driver.split()
183 kernelmodule=driver[0]
184 m.aliasset(dev,kernelmodule)
185 options=" ".join(driver[1:])
187 m.optionsset(dev,options)
188 m.output("%s/etc/modprobe.conf" % root, program)
190 # clean up after any ifcfg-$dev script that's no longer listed as
191 # part of the NodeNetworks associated with this node
193 # list all network-scripts
194 files = os.listdir(sysconfig)
196 # filter out the ifcfg-* files
199 if f.find("ifcfg-") == 0:
202 # remove loopback (lo) from ifcfgs list
204 if lo in ifcfgs: ifcfgs.remove(lo)
206 # remove known devices from icfgs list
207 for (dev, inter) in interfaces.iteritems():
209 if ifcfg in ifcfgs: ifcfgs.remove(ifcfg)
211 # delete the remaining ifcfgs from
212 deletedSomething = False
214 if not failedToGetSettings:
216 dev = ifcfg[len('ifcfg-'):]
217 path = "%s/ifcfg-%s" % (sysconfig,dev)
219 logger.verbose("net:InitInterfaces removing %s %s"%(dev,path))
220 os.system("/sbin/ifdown %s" % dev)
221 deletedSomething=True
224 # wait a bit for the one or more ifdowns to have taken effect
228 # Write network configuration file
229 networkconf = file("%s/etc/sysconfig/network" % root, "w")
230 networkconf.write("NETWORKING=yes\nHOSTNAME=%s\n" % hostname)
231 if gateway is not None:
232 networkconf.write("GATEWAY=%s\n" % gateway)
235 # Process ifcfg-$dev changes / additions
237 for (dev, inter) in interfaces.iteritems():
238 (fd, tmpnam) = tempfile.mkstemp(dir=sysconfig)
239 f = os.fdopen(fd, "w")
240 f.write("# Autogenerated by pyplnet... do not edit!\n")
241 if 'DRIVER' in inter:
242 f.write("# using %s driver for device %s\n" % (inter['DRIVER'],dev))
243 f.write('DEVICE=%s\n' % dev)
245 # print the configuration values
246 for (key, val) in inter.iteritems():
247 if key not in ('IFNAME','ALIAS','CFGOPTIONS','DRIVER'):
248 f.write('%s=%s\n' % (key, val))
250 # print the configuration specific option values (if any)
251 if 'CFGOPTIONS' in inter:
252 cfgoptions = inter['CFGOPTIONS']
253 f.write('#CFGOPTIONS are %s\n' % cfgoptions)
254 for cfgoption in cfgoptions.split():
255 key,val = cfgoption.split('=')
259 f.write('%s="%s"\n' % (key,val))
262 # compare whether two files are the same
263 def comparefiles(a,b):
265 logger.verbose("net:InitInterfaces comparing %s with %s" % (a,b))
266 if not os.path.exists(a): return False
271 if not os.path.exists(b): return False
276 return buf_a == buf_b
280 path = "%s/ifcfg-%s" % (sysconfig,dev)
281 if not os.path.exists(path):
282 logger.verbose('net:InitInterfaces adding configuration for %s' % dev)
283 # add ifcfg-$dev configuration file
284 os.rename(tmpnam,path)
288 elif not comparefiles(tmpnam,path):
289 logger.verbose('net:InitInterfaces Configuration change for %s' % dev)
291 logger.verbose('net:InitInterfaces ifdown %s' % dev)
292 # invoke ifdown for the old configuration
293 os.system("/sbin/ifdown %s" % dev)
294 # wait a few secs for ifdown to complete
297 logger.log('replacing configuration for %s' % dev)
298 # replace ifcfg-$dev configuration file
299 os.rename(tmpnam,path)
303 # tmpnam & path are identical
308 fb = file("%s/ifcfg-%s"%(sysconfig,dev),"r")
309 for line in fb.readlines():
311 if parts[0][0]=="#":continue
312 if parts[0].find('='):
313 name,value = parts[0].split('=')
314 # clean up name & value
316 value = value.strip()
317 value = value.strip("'")
318 value = value.strip('"')
319 cfgvariables[name]=value
323 if name in cfgvariables:
324 value=cfgvariables[name]
325 value = value.lower()
329 # skip over device configs with ONBOOT=no
330 if getvar("ONBOOT") == 'no': continue
332 # don't bring up slave devices, the network scripts will
333 # handle those correctly
334 if getvar("SLAVE") == 'yes': continue
337 logger.verbose('net:InitInterfaces bringing up %s' % dev)
338 os.system("/sbin/ifup %s" % dev)
340 if __name__ == "__main__":
344 parser = optparse.OptionParser(usage="plnet [-v] [-f] [-p <program>] -r root node_id")
345 parser.add_option("-v", "--verbose", action="store_true", dest="verbose")
346 parser.add_option("-r", "--root", action="store", type="string",
347 dest="root", default=None)
348 parser.add_option("-f", "--files-only", action="store_true",
350 parser.add_option("-p", "--program", action="store", type="string",
351 dest="program", default="plnet")
352 (options, args) = parser.parse_args()
353 if len(args) != 1 or options.root is None:
354 print >>sys.stderr, "Missing root or node_id"
358 node = shell.GetNodes({'node_id': [int(args[0])]})
360 networks = shell.GetInterfaces({'interface_id': node[0]['interface_ids']})
361 except AttributeError:
362 networks = shell.GetNodeNetworks({'nodenetwork_id':node[0]['nodenetwork_ids']})
366 data = {'hostname': node[0]['hostname'], 'networks': networks}
368 def __init__(self, verbose):
369 self.verbosity = verbose
370 def log(self, msg, loglevel=2):
373 def verbose(self, msg):
375 l = logger(options.verbose)
376 InitInterfaces(l, shell, data, options.root, options.files_only)