Make dhclient persistent, so transient network failures don't make nodes unreachable.
[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             inter['PERSISTENT_DHCLIENT'] = "yes"
60             if network['hostname']:
61                 inter['DHCP_HOSTNAME'] = network['hostname']
62             else:
63                 inter['DHCP_HOSTNAME'] = hostname 
64             if not network['is_primary']:
65                 inter['DHCLIENTARGS'] = "-R subnet-mask"
66
67         if len(network['interface_tag_ids']) > 0:
68             try:
69                 settings = plc.GetInterfaceTags({'interface_tag_id':
70                                                  network['interface_tag_ids']})
71             except:
72                 logger.log("net:InitInterfaces FATAL: failed call GetInterfaceTags({'interface_tag_id':{%s})"% \
73                            network['interface_tag_ids'])
74                 failedToGetSettings = True
75                 continue # on to the next network
76
77             for setting in settings:
78                 # to explicitly set interface name
79                 settingname = setting['name'].upper()
80                 if settingname in ('IFNAME','ALIAS','CFGOPTIONS','DRIVER'):
81                     inter[settingname]=setting['value']
82                 else:
83                     logger.log("net:InitInterfaces WARNING: ignored setting named %s"%setting['name'])
84
85         # support aliases to interfaces either by name or HWADDR
86         if 'ALIAS' in inter:
87             if 'HWADDR' in inter:
88                 hwaddr = inter['HWADDR'].lower()
89                 del inter['HWADDR']
90                 if hwaddr in macs:
91                     hwifname = macs[hwaddr]
92                     if ('IFNAME' in inter) and inter['IFNAME'] <> hwifname:
93                         logger.log("net:InitInterfaces WARNING: alias ifname (%s) and hwaddr ifname (%s) do not match"%\
94                                        (inter['IFNAME'],hwifname))
95                         inter['IFNAME'] = hwifname
96                 else:
97                     logger.log('net:InitInterfaces WARNING: mac addr %s for alias not found' %(hwaddr,alias))
98
99             if 'IFNAME' in inter:
100                 # stupid RH /etc/sysconfig/network-scripts/ifup-aliases:new_interface()
101                 # checks if the "$DEVNUM" only consists of '^[0-9A-Za-z_]*$'. Need to make
102                 # our aliases compliant.
103                 parts = inter['ALIAS'].split('_')
104                 isValid=True
105                 for part in parts:
106                     isValid=isValid and part.isalnum()
107
108                 if isValid:
109                     interfaces["%s:%s" % (inter['IFNAME'],inter['ALIAS'])] = inter 
110                 else:
111                     logger.log("net:InitInterfaces WARNING: interface alias (%s) not a valid string for RH ifup-aliases"% inter['ALIAS'])
112             else:
113                 logger.log("net:InitInterfaces WARNING: interface alias (%s) not matched to an interface"% inter['ALIAS'])
114             interface -= 1
115         else:
116             if ('IFNAME' not in inter) and not orig_ifname:
117                 ifname="eth%d" % (interface-1)
118                 # should check if $ifname is an eth already defines
119                 if os.path.exists("%s/ifcfg-%s"%(sysconfig,ifname)):
120                     logger.log("net:InitInterfaces WARNING: possibly blowing away %s configuration"%ifname)
121             else:
122                 if ('IFNAME' not in inter) and orig_ifname:
123                     ifname = orig_ifname
124                 else:
125                     ifname = inter['IFNAME']
126                 interface -= 1
127             interfaces[ifname] = inter
128                 
129     m = modprobe.Modprobe()
130     try:
131         m.input("%s/etc/modprobe.conf" % root, program)
132     except:
133         pass
134     for (dev, inter) in interfaces.iteritems():
135         # get the driver string "moduleName option1=a option2=b"
136         driver=inter.get('DRIVER','')
137         if driver <> '':
138             driver=driver.split()
139             kernelmodule=driver[0]
140             m.aliasset(dev,kernelmodule)
141             options=" ".join(driver[1:])
142             if options <> '':
143                 m.optionsset(dev,options)
144     m.output("%s/etc/modprobe.conf" % root)
145
146     # clean up after any ifcfg-$dev script that's no longer listed as
147     # part of the NodeNetworks associated with this node
148
149     # list all network-scripts
150     files = os.listdir(sysconfig)
151
152     # filter out the ifcfg-* files
153     ifcfgs=[]
154     for f in files:
155         if f.find("ifcfg-") == 0:
156             ifcfgs.append(f)
157
158     # remove loopback (lo) from ifcfgs list
159     lo = "ifcfg-lo"
160     if lo in ifcfgs: ifcfgs.remove(lo)
161
162     # remove known devices from icfgs list
163     for (dev, inter) in interfaces.iteritems():
164         ifcfg = 'ifcfg-'+dev
165         if ifcfg in ifcfgs: ifcfgs.remove(ifcfg)
166
167     # delete the remaining ifcfgs from 
168     deletedSomething = False
169
170     if not failedToGetSettings:
171         for ifcfg in ifcfgs:
172             dev = ifcfg[len('ifcfg-'):]
173             path = "%s/ifcfg-%s" % (sysconfig,dev)
174             if not files_only:
175                 logger.verbose("net:InitInterfaces removing %s %s"%(dev,path))
176                 os.system("/sbin/ifdown %s" % dev)
177             deletedSomething=True
178             os.unlink(path)
179
180     # wait a bit for the one or more ifdowns to have taken effect
181     if deletedSomething:
182         time.sleep(2)
183
184     # Process ifcg-$dev changes / additions
185     newdevs = []
186     for (dev, inter) in interfaces.iteritems():
187         (fd, tmpnam) = tempfile.mkstemp(dir=sysconfig)
188         f = os.fdopen(fd, "w")
189         f.write("# Autogenerated by NodeManager/net.py.... do not edit!\n")
190         if 'DRIVER' in inter:
191             f.write("# using %s driver for device %s\n" % (inter['DRIVER'],dev))
192         f.write('DEVICE="%s"\n' % dev)
193         
194         # print the configuration values
195         for (key, val) in inter.iteritems():
196             if key not in ('IFNAME','ALIAS','CFGOPTIONS','DRIVER'):
197                 f.write('%s="%s"\n' % (key, val))
198
199         # print the configuration specific option values (if any)
200         if 'CFGOPTIONS' in inter:
201             cfgoptions = inter['CFGOPTIONS']
202             f.write('#CFGOPTIONS are %s\n' % cfgoptions)
203             for cfgoption in cfgoptions.split():
204                 key,val = cfgoption.split('=')
205                 key=key.strip()
206                 key=key.upper()
207                 val=val.strip()
208                 f.write('%s="%s"\n' % (key,val))
209         f.close()
210
211         # compare whether two files are the same
212         def comparefiles(a,b):
213             try:
214                 logger.verbose("net:InitInterfaces comparing %s with %s" % (a,b))
215                 if not os.path.exists(a): return False
216                 fb = open(a)
217                 buf_a = fb.read()
218                 fb.close()
219
220                 if not os.path.exists(b): return False
221                 fb = open(b)
222                 buf_b = fb.read()
223                 fb.close()
224
225                 return buf_a == buf_b
226             except IOError, e:
227                 return False
228
229         path = "%s/ifcfg-%s" % (sysconfig,dev)
230         if not os.path.exists(path):
231             logger.verbose('net:InitInterfaces adding configuration for %s' % dev)
232             # add ifcfg-$dev configuration file
233             os.rename(tmpnam,path)
234             os.chmod(path,0644)
235             newdevs.append(dev)
236             
237         elif not comparefiles(tmpnam,path):
238             logger.verbose('net:InitInterfaces Configuration change for %s' % dev)
239             if not files_only:
240                 logger.verbose('net:InitInterfaces ifdown %s' % dev)
241                 # invoke ifdown for the old configuration
242                 os.system("/sbin/ifdown %s" % dev)
243                 # wait a few secs for ifdown to complete
244                 time.sleep(2)
245
246             logger.log('replacing configuration for %s' % dev)
247             # replace ifcfg-$dev configuration file
248             os.rename(tmpnam,path)
249             os.chmod(path,0644)
250             newdevs.append(dev)
251         else:
252             # tmpnam & path are identical
253             os.unlink(tmpnam)
254
255     for dev in newdevs:
256         cfgvariables = {}
257         fb = file("%s/ifcfg-%s"%(sysconfig,dev),"r")
258         for line in fb.readlines():
259             parts = line.split()
260             if parts[0][0]=="#":continue
261             if parts[0].find('='):
262                 name,value = parts[0].split('=')
263                 # clean up name & value
264                 name = name.strip()
265                 value = value.strip()
266                 value = value.strip("'")
267                 value = value.strip('"')
268                 cfgvariables[name]=value
269         fb.close()
270
271         def getvar(name):
272             if name in cfgvariables:
273                 value=cfgvariables[name]
274                 value = value.lower()
275                 return value
276             return ''
277
278         # skip over device configs with ONBOOT=no
279         if getvar("ONBOOT") == 'no': continue
280
281         # don't bring up slave devices, the network scripts will
282         # handle those correctly
283         if getvar("SLAVE") == 'yes': continue
284
285         if not files_only:
286             logger.verbose('net:InitInterfaces bringing up %s' % dev)
287             os.system("/sbin/ifup %s" % dev)
288
289 if __name__ == "__main__":
290     import optparse
291     import sys
292
293     parser = optparse.OptionParser(usage="plnet [-v] [-f] [-p <program>] -r root node_id")
294     parser.add_option("-v", "--verbose", action="store_true", dest="verbose")
295     parser.add_option("-r", "--root", action="store", type="string",
296                       dest="root", default=None)
297     parser.add_option("-f", "--files-only", action="store_true",
298                       dest="files_only")
299     parser.add_option("-p", "--program", action="store", type="string",
300                       dest="program", default="plnet")
301     (options, args) = parser.parse_args()
302     if len(args) != 1 or options.root is None:
303         print >>sys.stderr, "Missing root or node_id"
304         parser.print_help()
305         sys.exit(1)
306
307     node = shell.GetNodes({'node_id': [int(args[0])]})
308     networks = shell.GetInterfaces({'interface_id': node[0]['interface_ids']})
309
310     data = {'hostname': node[0]['hostname'], 'networks': networks}
311     class logger:
312         def __init__(self, verbose):
313             self.verbosity = verbose
314         def log(self, msg, loglevel=2):
315             if self.verbosity:
316                 print msg
317         def verbose(self, msg):
318             self.log(msg, 1)
319     l = logger(options.verbose)
320     InitInterfaces(l, shell, data, options.root, options.files_only)