os.tmpnam is unsafe.
[pyplnet.git] / plnet.py
1 # $Id$
2
3 import os
4 import socket
5 import time
6 import tempfile
7
8 import sioc
9 import modprobe
10
11 def InitInterfaces(logger, plc, data, root="", files_only=False):
12     sysconfig = "%s/etc/sysconfig/network-scripts" % root
13
14     # query running network interfaces
15     devs = sioc.gifconf()
16     ips = dict(zip(devs.values(), devs.keys()))
17     macs = {}
18     for dev in devs:
19         macs[sioc.gifhwaddr(dev).lower()] = dev
20
21     # assume data['networks'] contains this node's NodeNetworks
22     interfaces = {}
23     interface = 1
24     hostname = data.get('hostname',socket.gethostname())
25     networks = data['networks']
26     failedToGetSettings = False
27     for network in networks:
28         logger.verbose('net:InitInterfaces interface %d: %s'%(interface,network))
29         logger.verbose('net:InitInterfaces macs = %s' % macs)
30         logger.verbose('net:InitInterfaces ips = %s' % ips)
31         # Get interface name preferably from MAC address, falling back
32         # on IP address.
33         hwaddr=network['mac']
34         if hwaddr <> None: hwaddr=hwaddr.lower()
35         if hwaddr in macs:
36             orig_ifname = macs[hwaddr]
37         elif network['ip'] in ips:
38             orig_ifname = ips[network['ip']]
39         else:
40             orig_ifname = None
41
42         if orig_ifname:
43                 logger.verbose('net:InitInterfaces orig_ifname = %s' % orig_ifname)
44         
45         inter = {}
46         inter['ONBOOT']='yes'
47         inter['USERCTL']='no'
48         if network['mac']:
49             inter['HWADDR'] = network['mac']
50
51         if network['method'] == "static":
52             inter['BOOTPROTO'] = "static"
53             inter['IPADDR'] = network['ip']
54             inter['NETMASK'] = network['netmask']
55
56         elif network['method'] == "dhcp":
57             inter['BOOTPROTO'] = "dhcp"
58             if network['hostname']:
59                 inter['DHCP_HOSTNAME'] = network['hostname']
60             else:
61                 inter['DHCP_HOSTNAME'] = hostname 
62             if not network['is_primary']:
63                 inter['DHCLIENTARGS'] = "-R subnet-mask"
64
65         if len(network['interface_tag_ids']) > 0:
66             try:
67                 settings = plc.GetInterfaceTags({'interface_tag_id':
68                                                  network['interface_tag_ids']})
69             except:
70                 logger.log("net:InitInterfaces FATAL: failed call GetInterfaceTags({'interface_tag_id':{%s})"% \
71                            network['interface_tag_ids'])
72                 failedToGetSettings = True
73                 continue # on to the next network
74
75             for setting in settings:
76                 # to explicitly set interface name
77                 settingname = setting['name'].upper()
78                 if settingname in ('IFNAME','ALIAS','CFGOPTIONS','DRIVER'):
79                     inter[settingname]=setting['value']
80                 else:
81                     logger.log("net:InitInterfaces WARNING: ignored setting named %s"%setting['name'])
82
83         # support aliases to interfaces either by name or HWADDR
84         if 'ALIAS' in inter:
85             if 'HWADDR' in inter:
86                 hwaddr = inter['HWADDR'].lower()
87                 del inter['HWADDR']
88                 if hwaddr in macs:
89                     hwifname = macs[hwaddr]
90                     if ('IFNAME' in inter) and inter['IFNAME'] <> hwifname:
91                         logger.log("net:InitInterfaces WARNING: alias ifname (%s) and hwaddr ifname (%s) do not match"%\
92                                        (inter['IFNAME'],hwifname))
93                         inter['IFNAME'] = hwifname
94                 else:
95                     logger.log('net:InitInterfaces WARNING: mac addr %s for alias not found' %(hwaddr,alias))
96
97             if 'IFNAME' in inter:
98                 # stupid RH /etc/sysconfig/network-scripts/ifup-aliases:new_interface()
99                 # checks if the "$DEVNUM" only consists of '^[0-9A-Za-z_]*$'. Need to make
100                 # our aliases compliant.
101                 parts = inter['ALIAS'].split('_')
102                 isValid=True
103                 for part in parts:
104                     isValid=isValid and part.isalnum()
105
106                 if isValid:
107                     interfaces["%s:%s" % (inter['IFNAME'],inter['ALIAS'])] = inter 
108                 else:
109                     logger.log("net:InitInterfaces WARNING: interface alias (%s) not a valid string for RH ifup-aliases"% inter['ALIAS'])
110             else:
111                 logger.log("net:InitInterfaces WARNING: interface alias (%s) not matched to an interface"% inter['ALIAS'])
112             interface -= 1
113         else:
114             if ('IFNAME' not in inter) and not orig_ifname:
115                 ifname="eth%d" % (interface-1)
116                 # should check if $ifname is an eth already defines
117                 if os.path.exists("%s/ifcfg-%s"%(sysconfig,ifname)):
118                     logger.log("net:InitInterfaces WARNING: possibly blowing away %s configuration"%ifname)
119             else:
120                 if ('IFNAME' not in inter) and orig_ifname:
121                     ifname = orig_ifname
122                 else:
123                     ifname = inter['IFNAME']
124                 interface -= 1
125             interfaces[ifname] = inter
126                 
127     m = modprobe.Modprobe()
128     m.input("%s/etc/modprobe.conf" % root)
129     for (dev, inter) in interfaces.iteritems():
130         # get the driver string "moduleName option1=a option2=b"
131         driver=inter.get('DRIVER','')
132         if driver <> '':
133             driver=driver.split()
134             kernelmodule=driver[0]
135             m.aliasset(dev,kernelmodule)
136             options=" ".join(driver[1:])
137             if options <> '':
138                 m.optionsset(dev,options)
139     m.output("%s/etc/modprobe.conf" % root)
140
141     # clean up after any ifcfg-$dev script that's no longer listed as
142     # part of the NodeNetworks associated with this node
143
144     # list all network-scripts
145     files = os.listdir(sysconfig)
146
147     # filter out the ifcfg-* files
148     ifcfgs=[]
149     for f in files:
150         if f.find("ifcfg-") == 0:
151             ifcfgs.append(f)
152
153     # remove loopback (lo) from ifcfgs list
154     lo = "ifcfg-lo"
155     if lo in ifcfgs: ifcfgs.remove(lo)
156
157     # remove known devices from icfgs list
158     for (dev, inter) in interfaces.iteritems():
159         ifcfg = 'ifcfg-'+dev
160         if ifcfg in ifcfgs: ifcfgs.remove(ifcfg)
161
162     # delete the remaining ifcfgs from 
163     deletedSomething = False
164
165     if not failedToGetSettings:
166         for ifcfg in ifcfgs:
167             dev = ifcfg[len('ifcfg-'):]
168             path = "%s/ifcfg-%s" % (sysconfig,dev)
169             logger.verbose("net:InitInterfaces removing %s %s"%(dev,path))
170             os.system("/sbin/ifdown %s" % dev)
171             deletedSomething=True
172             os.unlink(path)
173
174     # wait a bit for the one or more ifdowns to have taken effect
175     if deletedSomething:
176         time.sleep(2)
177
178     # Process ifcg-$dev changes / additions
179     newdevs = []
180     for (dev, inter) in interfaces.iteritems():
181         (fd, tmpnam) = tempfile.mkstemp(dir=sysconfig)
182         f = os.fdopen(fd, "w")
183         f.write("# Autogenerated by NodeManager/net.py.... do not edit!\n")
184         if 'DRIVER' in inter:
185             f.write("# using %s driver for device %s\n" % (inter['DRIVER'],dev))
186         f.write('DEVICE="%s"\n' % dev)
187         
188         # print the configuration values
189         for (key, val) in inter.iteritems():
190             if key not in ('IFNAME','ALIAS','CFGOPTIONS','DRIVER'):
191                 f.write('%s="%s"\n' % (key, val))
192
193         # print the configuration specific option values (if any)
194         if 'CFGOPTIONS' in inter:
195             cfgoptions = inter['CFGOPTIONS']
196             f.write('#CFGOPTIONS are %s\n' % cfgoptions)
197             for cfgoption in cfgoptions.split():
198                 key,val = cfgoption.split('=')
199                 key=key.strip()
200                 key=key.upper()
201                 val=val.strip()
202                 f.write('%s="%s"\n' % (key,val))
203         f.close()
204
205         # compare whether two files are the same
206         def comparefiles(a,b):
207             try:
208                 logger.verbose("net:InitInterfaces comparing %s with %s" % (a,b))
209                 if not os.path.exists(a): return False
210                 fb = open(a)
211                 buf_a = fb.read()
212                 fb.close()
213
214                 if not os.path.exists(b): return False
215                 fb = open(b)
216                 buf_b = fb.read()
217                 fb.close()
218
219                 return buf_a == buf_b
220             except IOError, e:
221                 return False
222
223         path = "%s/ifcfg-%s" % (sysconfig,dev)
224         if not os.path.exists(path):
225             logger.verbose('net:InitInterfaces adding configuration for %s' % dev)
226             # add ifcfg-$dev configuration file
227             os.rename(tmpnam,path)
228             os.chmod(path,0644)
229             newdevs.append(dev)
230             
231         elif not comparefiles(tmpnam,path):
232             logger.verbose('net:InitInterfaces Configuration change for %s' % dev)
233             logger.verbose('net:InitInterfaces ifdown %s' % dev)
234             # invoke ifdown for the old configuration
235             os.system("/sbin/ifdown %s" % dev)
236             # wait a few secs for ifdown to complete
237             time.sleep(2)
238
239             logger.log('replacing configuration for %s' % dev)
240             # replace ifcfg-$dev configuration file
241             os.rename(tmpnam,path)
242             os.chmod(path,0644)
243             newdevs.append(dev)
244         else:
245             # tmpnam & path are identical
246             os.unlink(tmpnam)
247
248     for dev in newdevs:
249         cfgvariables = {}
250         fb = file("%s/ifcfg-%s"%(sysconfig,dev),"r")
251         for line in fb.readlines():
252             parts = line.split()
253             if parts[0][0]=="#":continue
254             if parts[0].find('='):
255                 name,value = parts[0].split('=')
256                 # clean up name & value
257                 name = name.strip()
258                 value = value.strip()
259                 value = value.strip("'")
260                 value = value.strip('"')
261                 cfgvariables[name]=value
262         fb.close()
263
264         def getvar(name):
265             if name in cfgvariables:
266                 value=cfgvariables[name]
267                 value = value.lower()
268                 return value
269             return ''
270
271         # skip over device configs with ONBOOT=no
272         if getvar("ONBOOT") == 'no': continue
273
274         # don't bring up slave devices, the network scripts will
275         # handle those correctly
276         if getvar("SLAVE") == 'yes': continue
277
278         logger.verbose('net:InitInterfaces bringing up %s' % dev)
279         os.system("/sbin/ifup %s" % dev)
280