Don't whine about comments in modprobe.conf.
[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, program="NodeManager"):
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     try:
130         m.input("%s/etc/modprobe.conf" % root, program)
131     except:
132         pass
133     for (dev, inter) in interfaces.iteritems():
134         # get the driver string "moduleName option1=a option2=b"
135         driver=inter.get('DRIVER','')
136         if driver <> '':
137             driver=driver.split()
138             kernelmodule=driver[0]
139             m.aliasset(dev,kernelmodule)
140             options=" ".join(driver[1:])
141             if options <> '':
142                 m.optionsset(dev,options)
143     m.output("%s/etc/modprobe.conf" % root)
144
145     # clean up after any ifcfg-$dev script that's no longer listed as
146     # part of the NodeNetworks associated with this node
147
148     # list all network-scripts
149     files = os.listdir(sysconfig)
150
151     # filter out the ifcfg-* files
152     ifcfgs=[]
153     for f in files:
154         if f.find("ifcfg-") == 0:
155             ifcfgs.append(f)
156
157     # remove loopback (lo) from ifcfgs list
158     lo = "ifcfg-lo"
159     if lo in ifcfgs: ifcfgs.remove(lo)
160
161     # remove known devices from icfgs list
162     for (dev, inter) in interfaces.iteritems():
163         ifcfg = 'ifcfg-'+dev
164         if ifcfg in ifcfgs: ifcfgs.remove(ifcfg)
165
166     # delete the remaining ifcfgs from 
167     deletedSomething = False
168
169     if not failedToGetSettings:
170         for ifcfg in ifcfgs:
171             dev = ifcfg[len('ifcfg-'):]
172             path = "%s/ifcfg-%s" % (sysconfig,dev)
173             if not files_only:
174                 logger.verbose("net:InitInterfaces removing %s %s"%(dev,path))
175                 os.system("/sbin/ifdown %s" % dev)
176             deletedSomething=True
177             os.unlink(path)
178
179     # wait a bit for the one or more ifdowns to have taken effect
180     if deletedSomething:
181         time.sleep(2)
182
183     # Process ifcg-$dev changes / additions
184     newdevs = []
185     for (dev, inter) in interfaces.iteritems():
186         (fd, tmpnam) = tempfile.mkstemp(dir=sysconfig)
187         f = os.fdopen(fd, "w")
188         f.write("# Autogenerated by NodeManager/net.py.... do not edit!\n")
189         if 'DRIVER' in inter:
190             f.write("# using %s driver for device %s\n" % (inter['DRIVER'],dev))
191         f.write('DEVICE="%s"\n' % dev)
192         
193         # print the configuration values
194         for (key, val) in inter.iteritems():
195             if key not in ('IFNAME','ALIAS','CFGOPTIONS','DRIVER'):
196                 f.write('%s="%s"\n' % (key, val))
197
198         # print the configuration specific option values (if any)
199         if 'CFGOPTIONS' in inter:
200             cfgoptions = inter['CFGOPTIONS']
201             f.write('#CFGOPTIONS are %s\n' % cfgoptions)
202             for cfgoption in cfgoptions.split():
203                 key,val = cfgoption.split('=')
204                 key=key.strip()
205                 key=key.upper()
206                 val=val.strip()
207                 f.write('%s="%s"\n' % (key,val))
208         f.close()
209
210         # compare whether two files are the same
211         def comparefiles(a,b):
212             try:
213                 logger.verbose("net:InitInterfaces comparing %s with %s" % (a,b))
214                 if not os.path.exists(a): return False
215                 fb = open(a)
216                 buf_a = fb.read()
217                 fb.close()
218
219                 if not os.path.exists(b): return False
220                 fb = open(b)
221                 buf_b = fb.read()
222                 fb.close()
223
224                 return buf_a == buf_b
225             except IOError, e:
226                 return False
227
228         path = "%s/ifcfg-%s" % (sysconfig,dev)
229         if not os.path.exists(path):
230             logger.verbose('net:InitInterfaces adding configuration for %s' % dev)
231             # add ifcfg-$dev configuration file
232             os.rename(tmpnam,path)
233             os.chmod(path,0644)
234             newdevs.append(dev)
235             
236         elif not comparefiles(tmpnam,path):
237             logger.verbose('net:InitInterfaces Configuration change for %s' % dev)
238             if not files_only:
239                 logger.verbose('net:InitInterfaces ifdown %s' % dev)
240                 # invoke ifdown for the old configuration
241                 os.system("/sbin/ifdown %s" % dev)
242                 # wait a few secs for ifdown to complete
243                 time.sleep(2)
244
245             logger.log('replacing configuration for %s' % dev)
246             # replace ifcfg-$dev configuration file
247             os.rename(tmpnam,path)
248             os.chmod(path,0644)
249             newdevs.append(dev)
250         else:
251             # tmpnam & path are identical
252             os.unlink(tmpnam)
253
254     for dev in newdevs:
255         cfgvariables = {}
256         fb = file("%s/ifcfg-%s"%(sysconfig,dev),"r")
257         for line in fb.readlines():
258             parts = line.split()
259             if parts[0][0]=="#":continue
260             if parts[0].find('='):
261                 name,value = parts[0].split('=')
262                 # clean up name & value
263                 name = name.strip()
264                 value = value.strip()
265                 value = value.strip("'")
266                 value = value.strip('"')
267                 cfgvariables[name]=value
268         fb.close()
269
270         def getvar(name):
271             if name in cfgvariables:
272                 value=cfgvariables[name]
273                 value = value.lower()
274                 return value
275             return ''
276
277         # skip over device configs with ONBOOT=no
278         if getvar("ONBOOT") == 'no': continue
279
280         # don't bring up slave devices, the network scripts will
281         # handle those correctly
282         if getvar("SLAVE") == 'yes': continue
283
284         if not files_only:
285             logger.verbose('net:InitInterfaces bringing up %s' % dev)
286             os.system("/sbin/ifup %s" % dev)
287
288 if __name__ == "__main__":
289     import optparse
290     import sys
291
292     parser = optparse.OptionParser(usage="plnet [-v] [-f] [-p <program>] -r root node_id")
293     parser.add_option("-v", "--verbose", action="store_true", dest="verbose")
294     parser.add_option("-r", "--root", action="store", type="string",
295                       dest="root", default=None)
296     parser.add_option("-f", "--files-only", action="store_true",
297                       dest="files_only")
298     parser.add_option("-p", "--program", action="store", type="string",
299                       dest="program", default="plnet")
300     (options, args) = parser.parse_args()
301     if len(args) != 1 or options.root is None:
302         print >>sys.stderr, "Missing root or node_id"
303         parser.print_help()
304         sys.exit(1)
305
306     node = shell.GetNodes({'node_id': [int(args[0])]})
307     networks = shell.GetInterfaces({'interface_id': node[0]['interface_ids']})
308
309     data = {'hostname': node[0]['hostname'], 'networks': networks}
310     class logger:
311         def __init__(self, verbose):
312             self.verbosity = verbose
313         def log(self, msg, loglevel=2):
314             if self.verbosity:
315                 print msg
316         def verbose(self, msg):
317             self.log(msg, 1)
318     l = logger(options.verbose)
319     InitInterfaces(l, shell, data, options.root, options.files_only)