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