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