addresses one bug that failed to create ifcfg-eth0 for mlab boot images.
[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 import errno
9
10 import sioc
11 import modprobe
12
13 global version
14 version = 4.3
15
16 def InitInterfaces(logger, plc, data, root="", files_only=False, program="NodeManager"):
17     global version
18
19     sysconfig = "%s/etc/sysconfig/network-scripts" % root
20     try:
21         os.makedirs(sysconfig)
22     except OSError, e:
23         if e.errno != errno.EEXIST:
24             raise e
25
26     # query running network interfaces
27     devs = sioc.gifconf()
28     ips = dict(zip(devs.values(), devs.keys()))
29     macs = {}
30     for dev in devs:
31         macs[sioc.gifhwaddr(dev).lower()] = dev
32
33     # assume data['networks'] contains this node's NodeNetworks
34     interfaces = {}
35     interface = 1
36     hostname = data.get('hostname',socket.gethostname())
37     gateway = None
38     networks = data['networks']
39     failedToGetSettings = False
40
41     # NOTE: GetInterfaces/NodeNetworks does not necessarily order the interfaces
42     # returned.  Because 'interface'is decremented as each interface is processed,
43     # by the time is_primary=True (primary) interface is reached, the device
44     # "eth%s" % interface, is not eth0.  But, something like eth-4, or eth-12.
45     # This code sorts the interfaces, implicitly placing the primary (first created)
46     # interface first.  There is a lot of room for improvement to how this
47     # script handles interfaces and how it chooses the primary interface.
48     def compare_by (fieldname):
49         def compare_two_dicts (a, b):
50             return cmp(a[fieldname], b[fieldname])
51         return compare_two_dicts
52     if version == 4.3:
53         networks.sort( compare_by('interface_id') )
54     else:
55         networks.sort( compare_by('nodenetwork_id') )
56
57     for network in networks:
58         logger.verbose('net:InitInterfaces interface %d: %s'%(interface,network))
59         logger.verbose('net:InitInterfaces macs = %s' % macs)
60         logger.verbose('net:InitInterfaces ips = %s' % ips)
61         # Get interface name preferably from MAC address, falling back
62         # on IP address.
63         hwaddr=network['mac']
64         if hwaddr <> None: hwaddr=hwaddr.lower()
65         if hwaddr in macs:
66             orig_ifname = macs[hwaddr]
67         elif network['ip'] in ips:
68             orig_ifname = ips[network['ip']]
69         else:
70             orig_ifname = None
71
72         if orig_ifname:
73                 logger.verbose('net:InitInterfaces orig_ifname = %s' % orig_ifname)
74         
75         inter = {}
76         inter['ONBOOT']='yes'
77         inter['USERCTL']='no'
78         if network['mac']:
79             inter['HWADDR'] = network['mac']
80         if network['is_primary']:
81             inter['PRIMARY']='yes'
82
83         if network['method'] == "static":
84             inter['BOOTPROTO'] = "static"
85             inter['IPADDR'] = network['ip']
86             inter['NETMASK'] = network['netmask']
87             inter['DNS1'] = network['dns1']
88             inter['DNS2'] = network['dns2']
89             if network['is_primary']:
90                 gateway = network['gateway']
91
92         elif network['method'] == "dhcp":
93             inter['BOOTPROTO'] = "dhcp"
94             inter['PERSISTENT_DHCLIENT'] = "yes"
95             if network['hostname']:
96                 inter['DHCP_HOSTNAME'] = network['hostname']
97             else:
98                 inter['DHCP_HOSTNAME'] = hostname 
99             if not network['is_primary']:
100                 inter['DHCLIENTARGS'] = "-R subnet-mask"
101
102         try:
103             plc.GetInterfaceTags()
104             version = 4.3
105         except AttributeError:
106             version = 4.2
107
108         if version == 4.3:
109             interface_tag_ids = "interface_tag_ids"
110             interface_tag_id = "interface_tag_id"
111         else:
112             interface_tag_ids = "nodenetwork_setting_ids"
113             interface_tag_id = "nodenetwork_setting_id"
114
115         if len(network[interface_tag_ids]) > 0:
116             try:
117                 if version == 4.3:
118                     settings = plc.GetInterfaceTags({interface_tag_id:network[interface_tag_ids]})
119                 else:
120                     settings = plc.GetNodeNetworkSettings({interface_tag_id:network[interface_tag_ids]})
121             except:
122                 logger.log("net:InitInterfaces FATAL: failed call GetInterfaceTags({'interface_tag_id':{%s})"% \
123                            network['interface_tag_ids'])
124                 failedToGetSettings = True
125                 continue # on to the next network
126
127             for setting in settings:
128                 # to explicitly set interface name
129                 name_key = "name"
130                 if version == 4.3:
131                     name_key = "tagname"
132                     
133                 settingname = setting[name_key].upper()
134                 if settingname in ('IFNAME','ALIAS','CFGOPTIONS','DRIVER'):
135                     inter[settingname]=setting['value']
136                 # wireless settings
137                 elif settingname in \
138                         [  "MODE", "ESSID", "NW", "FREQ", "CHANNEL", "SENS", "RATE",
139                            "KEY", "KEY1", "KEY2", "KEY3", "KEY4", "SECURITYMODE", 
140                            "IWCONFIG", "IWPRIV" ] :
141                     inter [settingname] = setting['value']
142                     inter ['TYPE']='Wireless'
143                 else:
144                     logger.log("net:InitInterfaces WARNING: ignored setting named %s"%setting[name_key])
145
146         # support aliases to interfaces either by name or HWADDR
147         if 'ALIAS' in inter:
148             if 'HWADDR' in inter:
149                 hwaddr = inter['HWADDR'].lower()
150                 del inter['HWADDR']
151                 if hwaddr in macs:
152                     hwifname = macs[hwaddr]
153                     if ('IFNAME' in inter) and inter['IFNAME'] <> hwifname:
154                         logger.log("net:InitInterfaces WARNING: alias ifname (%s) and hwaddr ifname (%s) do not match"%\
155                                        (inter['IFNAME'],hwifname))
156                         inter['IFNAME'] = hwifname
157                 else:
158                     logger.log('net:InitInterfaces WARNING: mac addr %s for alias not found' %(hwaddr,alias))
159
160             if 'IFNAME' in inter:
161                 # stupid RH /etc/sysconfig/network-scripts/ifup-aliases:new_interface()
162                 # checks if the "$DEVNUM" only consists of '^[0-9A-Za-z_]*$'. Need to make
163                 # our aliases compliant.
164                 parts = inter['ALIAS'].split('_')
165                 isValid=True
166                 for part in parts:
167                     isValid=isValid and part.isalnum()
168
169                 if isValid:
170                     interfaces["%s:%s" % (inter['IFNAME'],inter['ALIAS'])] = inter 
171                 else:
172                     logger.log("net:InitInterfaces WARNING: interface alias (%s) not a valid string for RH ifup-aliases"% inter['ALIAS'])
173             else:
174                 logger.log("net:InitInterfaces WARNING: interface alias (%s) not matched to an interface"% inter['ALIAS'])
175             interface -= 1
176         else:
177             if ('IFNAME' not in inter) and not orig_ifname:
178                 ifname="eth%d" % (interface-1)
179                 # should check if $ifname is an eth already defines
180                 if os.path.exists("%s/ifcfg-%s"%(sysconfig,ifname)):
181                     logger.log("net:InitInterfaces WARNING: possibly blowing away %s configuration"%ifname)
182             else:
183                 if ('IFNAME' not in inter) and orig_ifname:
184                     ifname = orig_ifname
185                 else:
186                     ifname = inter['IFNAME']
187                 interface -= 1
188             interfaces[ifname] = inter
189                 
190     m = modprobe.Modprobe()
191     try:
192         m.input("%s/etc/modprobe.conf" % root)
193     except:
194         pass
195     for (dev, inter) in interfaces.iteritems():
196         # get the driver string "moduleName option1=a option2=b"
197         driver=inter.get('DRIVER','')
198         if driver <> '':
199             driver=driver.split()
200             kernelmodule=driver[0]
201             m.aliasset(dev,kernelmodule)
202             options=" ".join(driver[1:])
203             if options <> '':
204                 m.optionsset(dev,options)
205     m.output("%s/etc/modprobe.conf" % root, program)
206
207     # clean up after any ifcfg-$dev script that's no longer listed as
208     # part of the NodeNetworks associated with this node
209
210     # list all network-scripts
211     files = os.listdir(sysconfig)
212
213     # filter out the ifcfg-* files
214     ifcfgs=[]
215     for f in files:
216         if f.find("ifcfg-") == 0:
217             ifcfgs.append(f)
218
219     # remove loopback (lo) from ifcfgs list
220     lo = "ifcfg-lo"
221     if lo in ifcfgs: ifcfgs.remove(lo)
222
223     # remove known devices from icfgs list
224     for (dev, inter) in interfaces.iteritems():
225         ifcfg = 'ifcfg-'+dev
226         if ifcfg in ifcfgs: ifcfgs.remove(ifcfg)
227
228     # delete the remaining ifcfgs from 
229     deletedSomething = False
230
231     if not failedToGetSettings:
232         for ifcfg in ifcfgs:
233             dev = ifcfg[len('ifcfg-'):]
234             path = "%s/ifcfg-%s" % (sysconfig,dev)
235             if not files_only:
236                 logger.verbose("net:InitInterfaces removing %s %s"%(dev,path))
237                 os.system("/sbin/ifdown %s" % dev)
238             deletedSomething=True
239             os.unlink(path)
240
241     # wait a bit for the one or more ifdowns to have taken effect
242     if deletedSomething:
243         time.sleep(2)
244
245     # Write network configuration file
246     networkconf = file("%s/etc/sysconfig/network" % root, "w")
247     networkconf.write("NETWORKING=yes\nHOSTNAME=%s\n" % hostname)
248     if gateway is not None:
249         networkconf.write("GATEWAY=%s\n" % gateway)
250     networkconf.close()
251
252     # Process ifcfg-$dev changes / additions
253     newdevs = []
254     for (dev, inter) in interfaces.iteritems():
255         (fd, tmpnam) = tempfile.mkstemp(dir=sysconfig)
256         f = os.fdopen(fd, "w")
257         f.write("# Autogenerated by pyplnet... do not edit!\n")
258         if 'DRIVER' in inter:
259             f.write("# using %s driver for device %s\n" % (inter['DRIVER'],dev))
260         f.write('DEVICE=%s\n' % dev)
261         
262         # print the configuration values
263         for (key, val) in inter.iteritems():
264             if key not in ('IFNAME','ALIAS','CFGOPTIONS','DRIVER'):
265                 f.write('%s=%s\n' % (key, val))
266
267         # print the configuration specific option values (if any)
268         if 'CFGOPTIONS' in inter:
269             cfgoptions = inter['CFGOPTIONS']
270             f.write('#CFGOPTIONS are %s\n' % cfgoptions)
271             for cfgoption in cfgoptions.split():
272                 key,val = cfgoption.split('=')
273                 key=key.strip()
274                 key=key.upper()
275                 val=val.strip()
276                 f.write('%s="%s"\n' % (key,val))
277         f.close()
278
279         # compare whether two files are the same
280         def comparefiles(a,b):
281             try:
282                 logger.verbose("net:InitInterfaces comparing %s with %s" % (a,b))
283                 if not os.path.exists(a): return False
284                 fb = open(a)
285                 buf_a = fb.read()
286                 fb.close()
287
288                 if not os.path.exists(b): return False
289                 fb = open(b)
290                 buf_b = fb.read()
291                 fb.close()
292
293                 return buf_a == buf_b
294             except IOError, e:
295                 return False
296
297         path = "%s/ifcfg-%s" % (sysconfig,dev)
298         if not os.path.exists(path):
299             logger.verbose('net:InitInterfaces adding configuration for %s' % dev)
300             # add ifcfg-$dev configuration file
301             os.rename(tmpnam,path)
302             os.chmod(path,0644)
303             newdevs.append(dev)
304             
305         elif not comparefiles(tmpnam,path):
306             logger.verbose('net:InitInterfaces Configuration change for %s' % dev)
307             if not files_only:
308                 logger.verbose('net:InitInterfaces ifdown %s' % dev)
309                 # invoke ifdown for the old configuration
310                 os.system("/sbin/ifdown %s" % dev)
311                 # wait a few secs for ifdown to complete
312                 time.sleep(2)
313
314             logger.log('replacing configuration for %s' % dev)
315             # replace ifcfg-$dev configuration file
316             os.rename(tmpnam,path)
317             os.chmod(path,0644)
318             newdevs.append(dev)
319         else:
320             # tmpnam & path are identical
321             os.unlink(tmpnam)
322
323     for dev in newdevs:
324         cfgvariables = {}
325         fb = file("%s/ifcfg-%s"%(sysconfig,dev),"r")
326         for line in fb.readlines():
327             parts = line.split()
328             if parts[0][0]=="#":continue
329             if parts[0].find('='):
330                 name,value = parts[0].split('=')
331                 # clean up name & value
332                 name = name.strip()
333                 value = value.strip()
334                 value = value.strip("'")
335                 value = value.strip('"')
336                 cfgvariables[name]=value
337         fb.close()
338
339         def getvar(name):
340             if name in cfgvariables:
341                 value=cfgvariables[name]
342                 value = value.lower()
343                 return value
344             return ''
345
346         # skip over device configs with ONBOOT=no
347         if getvar("ONBOOT") == 'no': continue
348
349         # don't bring up slave devices, the network scripts will
350         # handle those correctly
351         if getvar("SLAVE") == 'yes': continue
352
353         if not files_only:
354             logger.verbose('net:InitInterfaces bringing up %s' % dev)
355             os.system("/sbin/ifup %s" % dev)
356
357 if __name__ == "__main__":
358     import optparse
359     import sys
360
361     parser = optparse.OptionParser(usage="plnet [-v] [-f] [-p <program>] -r root node_id")
362     parser.add_option("-v", "--verbose", action="store_true", dest="verbose")
363     parser.add_option("-r", "--root", action="store", type="string",
364                       dest="root", default=None)
365     parser.add_option("-f", "--files-only", action="store_true",
366                       dest="files_only")
367     parser.add_option("-p", "--program", action="store", type="string",
368                       dest="program", default="plnet")
369     (options, args) = parser.parse_args()
370     if len(args) != 1 or options.root is None:
371         print >>sys.stderr, "Missing root or node_id"
372         parser.print_help()
373         sys.exit(1)
374
375     node = shell.GetNodes({'node_id': [int(args[0])]})
376     try:
377         networks = shell.GetInterfaces({'interface_id': node[0]['interface_ids']})
378     except AttributeError:
379         networks = shell.GetNodeNetworks({'nodenetwork_id':node[0]['nodenetwork_ids']})
380         version = 4.2
381
382
383     data = {'hostname': node[0]['hostname'], 'networks': networks}
384     class logger:
385         def __init__(self, verbose):
386             self.verbosity = verbose
387         def log(self, msg, loglevel=2):
388             if self.verbosity:
389                 print msg
390         def verbose(self, msg):
391             self.log(msg, 1)
392     l = logger(options.verbose)
393     InitInterfaces(l, shell, data, options.root, options.files_only)