Make the plnet module a script that uses plcsh to get info for a node.
[pyplnet.git] / plnet.py
1 #!/usr/bin/python /usr/bin/plcsh
2 # $Id$
3
4 import os
5 import socket
6 import time
7 import tempfile
8
9 import sioc
10 import modprobe
11
12 def InitInterfaces(logger, plc, data, root="", files_only=False):
13     sysconfig = "%s/etc/sysconfig/network-scripts" % root
14
15     # query running network interfaces
16     devs = sioc.gifconf()
17     ips = dict(zip(devs.values(), devs.keys()))
18     macs = {}
19     for dev in devs:
20         macs[sioc.gifhwaddr(dev).lower()] = dev
21
22     # assume data['networks'] contains this node's NodeNetworks
23     interfaces = {}
24     interface = 1
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
33         # on IP address.
34         hwaddr=network['mac']
35         if hwaddr <> None: hwaddr=hwaddr.lower()
36         if hwaddr in macs:
37             orig_ifname = macs[hwaddr]
38         elif network['ip'] in ips:
39             orig_ifname = ips[network['ip']]
40         else:
41             orig_ifname = None
42
43         if orig_ifname:
44                 logger.verbose('net:InitInterfaces orig_ifname = %s' % orig_ifname)
45         
46         inter = {}
47         inter['ONBOOT']='yes'
48         inter['USERCTL']='no'
49         if network['mac']:
50             inter['HWADDR'] = network['mac']
51
52         if network['method'] == "static":
53             inter['BOOTPROTO'] = "static"
54             inter['IPADDR'] = network['ip']
55             inter['NETMASK'] = network['netmask']
56
57         elif network['method'] == "dhcp":
58             inter['BOOTPROTO'] = "dhcp"
59             if network['hostname']:
60                 inter['DHCP_HOSTNAME'] = network['hostname']
61             else:
62                 inter['DHCP_HOSTNAME'] = hostname 
63             if not network['is_primary']:
64                 inter['DHCLIENTARGS'] = "-R subnet-mask"
65
66         if len(network['interface_tag_ids']) > 0:
67             try:
68                 settings = plc.GetInterfaceTags({'interface_tag_id':
69                                                  network['interface_tag_ids']})
70             except:
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
75
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']
81                 else:
82                     logger.log("net:InitInterfaces WARNING: ignored setting named %s"%setting['name'])
83
84         # support aliases to interfaces either by name or HWADDR
85         if 'ALIAS' in inter:
86             if 'HWADDR' in inter:
87                 hwaddr = inter['HWADDR'].lower()
88                 del inter['HWADDR']
89                 if hwaddr in macs:
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
95                 else:
96                     logger.log('net:InitInterfaces WARNING: mac addr %s for alias not found' %(hwaddr,alias))
97
98             if 'IFNAME' in inter:
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('_')
103                 isValid=True
104                 for part in parts:
105                     isValid=isValid and part.isalnum()
106
107                 if isValid:
108                     interfaces["%s:%s" % (inter['IFNAME'],inter['ALIAS'])] = inter 
109                 else:
110                     logger.log("net:InitInterfaces WARNING: interface alias (%s) not a valid string for RH ifup-aliases"% inter['ALIAS'])
111             else:
112                 logger.log("net:InitInterfaces WARNING: interface alias (%s) not matched to an interface"% inter['ALIAS'])
113             interface -= 1
114         else:
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)
120             else:
121                 if ('IFNAME' not in inter) and orig_ifname:
122                     ifname = orig_ifname
123                 else:
124                     ifname = inter['IFNAME']
125                 interface -= 1
126             interfaces[ifname] = inter
127                 
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','')
133         if driver <> '':
134             driver=driver.split()
135             kernelmodule=driver[0]
136             m.aliasset(dev,kernelmodule)
137             options=" ".join(driver[1:])
138             if options <> '':
139                 m.optionsset(dev,options)
140     m.output("%s/etc/modprobe.conf" % root)
141
142     # clean up after any ifcfg-$dev script that's no longer listed as
143     # part of the NodeNetworks associated with this node
144
145     # list all network-scripts
146     files = os.listdir(sysconfig)
147
148     # filter out the ifcfg-* files
149     ifcfgs=[]
150     for f in files:
151         if f.find("ifcfg-") == 0:
152             ifcfgs.append(f)
153
154     # remove loopback (lo) from ifcfgs list
155     lo = "ifcfg-lo"
156     if lo in ifcfgs: ifcfgs.remove(lo)
157
158     # remove known devices from icfgs list
159     for (dev, inter) in interfaces.iteritems():
160         ifcfg = 'ifcfg-'+dev
161         if ifcfg in ifcfgs: ifcfgs.remove(ifcfg)
162
163     # delete the remaining ifcfgs from 
164     deletedSomething = False
165
166     if not failedToGetSettings:
167         for ifcfg in ifcfgs:
168             dev = ifcfg[len('ifcfg-'):]
169             path = "%s/ifcfg-%s" % (sysconfig,dev)
170             if not files_only:
171                 logger.verbose("net:InitInterfaces removing %s %s"%(dev,path))
172                 os.system("/sbin/ifdown %s" % dev)
173             deletedSomething=True
174             os.unlink(path)
175
176     # wait a bit for the one or more ifdowns to have taken effect
177     if deletedSomething:
178         time.sleep(2)
179
180     # Process ifcg-$dev changes / additions
181     newdevs = []
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)
189         
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))
194
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('=')
201                 key=key.strip()
202                 key=key.upper()
203                 val=val.strip()
204                 f.write('%s="%s"\n' % (key,val))
205         f.close()
206
207         # compare whether two files are the same
208         def comparefiles(a,b):
209             try:
210                 logger.verbose("net:InitInterfaces comparing %s with %s" % (a,b))
211                 if not os.path.exists(a): return False
212                 fb = open(a)
213                 buf_a = fb.read()
214                 fb.close()
215
216                 if not os.path.exists(b): return False
217                 fb = open(b)
218                 buf_b = fb.read()
219                 fb.close()
220
221                 return buf_a == buf_b
222             except IOError, e:
223                 return False
224
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)
230             os.chmod(path,0644)
231             newdevs.append(dev)
232             
233         elif not comparefiles(tmpnam,path):
234             logger.verbose('net:InitInterfaces Configuration change for %s' % dev)
235             if not files_only:
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
240                 time.sleep(2)
241
242             logger.log('replacing configuration for %s' % dev)
243             # replace ifcfg-$dev configuration file
244             os.rename(tmpnam,path)
245             os.chmod(path,0644)
246             newdevs.append(dev)
247         else:
248             # tmpnam & path are identical
249             os.unlink(tmpnam)
250
251     for dev in newdevs:
252         cfgvariables = {}
253         fb = file("%s/ifcfg-%s"%(sysconfig,dev),"r")
254         for line in fb.readlines():
255             parts = line.split()
256             if parts[0][0]=="#":continue
257             if parts[0].find('='):
258                 name,value = parts[0].split('=')
259                 # clean up name & value
260                 name = name.strip()
261                 value = value.strip()
262                 value = value.strip("'")
263                 value = value.strip('"')
264                 cfgvariables[name]=value
265         fb.close()
266
267         def getvar(name):
268             if name in cfgvariables:
269                 value=cfgvariables[name]
270                 value = value.lower()
271                 return value
272             return ''
273
274         # skip over device configs with ONBOOT=no
275         if getvar("ONBOOT") == 'no': continue
276
277         # don't bring up slave devices, the network scripts will
278         # handle those correctly
279         if getvar("SLAVE") == 'yes': continue
280
281         if not files_only:
282             logger.verbose('net:InitInterfaces bringing up %s' % dev)
283             os.system("/sbin/ifup %s" % dev)
284
285 if __name__ == "__main__":
286     import optparse
287     import sys
288
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",
294                       dest="files_only")
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]
299         sys.exit(1)
300
301     node = shell.GetNodes({'node_id': [int(args[0])]})
302     networks = shell.GetInterfaces({'interface_id': node[0]['interface_ids']})
303
304     data = {'hostname': node[0]['hostname'], 'networks': networks}
305     class logger:
306         def __init__(self, verbose):
307             self.verbosity = verbose
308         def log(self, msg, loglevel=2):
309             if self.verbosity:
310                 print msg
311         def verbose(self, msg):
312             self.log(msg, 1)
313     l = logger(options.verbose)
314     InitInterfaces(l, shell, data, options.root, options.files_only)