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