Cleaned up bugs. Now works as advertised.
[nodemanager.git] / vsys.py
1 # $Id$
2 # $URL$
3
4 """vsys configurator.  Maintains ACLs and script pipes inside vservers based on slice attributes."""
5
6 import logger
7 import os
8 from sets import Set
9
10 VSYSCONF="/etc/vsys.conf"
11 VSYSBKEND="/vsys"
12
13 def start(options, config):
14     pass
15
16
17 def GetSlivers(data):
18     """For each sliver with the vsys attribute, set the script ACL, create the vsys directory in the slice, and restart vsys."""
19     # Touch ACLs and create dict of available
20     # XXX ...Sigh...  fromkeys will use an immutable 
21     #scripts = dict.fromkeys(touchAcls(),[])A
22     scripts = {}
23     for script in touchAcls(): scripts[script] = []
24     # slices that need to be written to the conf
25     slices = []
26     # Parse attributes and update dict of scripts
27     for sliver in data['slivers']:
28         for attribute in sliver['attributes']:
29             if attribute['name'] == 'vsys':
30                 # add to conf
31                 slices.append(sliver['name'])
32                 # As the name implies, when we find an attribute, we
33                 createVsysDir(sliver['name'])
34                 # add it to our list of slivers that need vsys
35                 if attribute['value'] in scripts.keys():
36                     scripts[attribute['value']].append(sliver['name'])
37  
38     # Write the conf
39     writeConf(slices, parseConf())
40     # Write out the ACLs
41     if writeAcls(scripts, parseAcls()): 
42         logger.log("vsys: restarting vsys service")
43         os.system("/etc/init.d/vsys restart")
44
45
46 def createVsysDir(sliver):
47     '''Create /vsys directory in slice.  Update vsys conf file.'''
48     try: os.makedirs("/vservers/%s/vsys" % sliver)
49     except OSError: pass
50
51
52 def touchAcls():
53     '''Creates empty acl files for scripts.  
54     To be ran in case of new scripts that appear in the backend.
55     Returns list of available scripts.'''
56     acls = []
57     scripts = []
58     for (root, dirs, files) in os.walk(VSYSBKEND):
59         for file in files:
60             if file.endswith(".acl"):
61                 acls.append(file.rstrip(".acl"))
62             else:
63                 scripts.append(file)
64     for new in (Set(scripts) - Set(acls)):
65         logger.log("vsys: Found new script %s.  Writing empty acl." % new)
66         f = open("%s/%s.acl" %(VSYSBKEND, new), "w")
67         f.write("\n")
68         f.close()
69     
70     return scripts
71
72
73 def writeAcls(currentscripts, oldscripts):
74     '''Creates .acl files for script in the script repo.'''
75     # Check each oldscript entry to see if we need to modify
76     _restartvsys = False
77     # for iteritems along dict(oldscripts), if length of values
78     # not the same as length of values of new scripts,
79     # and length of non intersection along new scripts is not 0,
80     # then dicts are different.
81     for (acl, oldslivers) in oldscripts.iteritems():
82         if (len(oldslivers) != len(currentscripts[acl])) or \
83         (len(Set(oldslivers) - Set(currentscripts[acl])) != 0):
84             _restartvsys = True
85             logger.log("vsys: Updating %s.acl w/ slices %s" % (acl, currentscripts[acl]))
86             f = open("%s/%s.acl" % (VSYSBKEND, acl), "w")
87             for slice in currentscripts[acl]: f.write("%s\n" % slice)
88             f.close()
89     # Trigger a restart
90     return _restartvsys
91
92
93 def parseAcls():
94     '''Parse the frontend script acls.  Return {script: [slices]} in conf.'''
95     # make a dict of what slices are in what acls.
96     scriptacls = {}
97     for (root, dirs, files) in os.walk(VSYSBKEND):
98         for file in files:
99             if file.endswith(".acl"):
100                 f = open(root+"/"+file,"r+")
101                 scriptname = file.rstrip(".acl")
102                 scriptacls[scriptname] = []
103                 for slice in f.readlines():  
104                     scriptacls[scriptname].append(slice.rstrip())
105                 f.close()
106     # return what scripts are configured for which slices.
107     return scriptacls
108
109
110 def writeConf(slivers, oldslivers):
111     # Check if this is needed
112     # The assumption here is if lengths are the same,
113     # and the non intersection of both arrays has length 0,
114     # then the arrays are identical.
115     if (len(slivers) != len(oldslivers)) or \
116     (len(Set(oldslivers) - Set(slivers)) != 0):
117         logger.log("vsys:  Updating %s" % VSYSCONF)
118         f = open(VSYSCONF,"w")
119         for sliver in slivers:
120             f.write("/vservers/%(name)s/vsys %(name)s\n" % {"name": sliver})
121         f.truncate()
122         f.close()
123
124
125 def parseConf():
126     '''Parse the vsys conf and return list of slices in conf.'''
127     scriptacls = {}
128     slicesinconf = []
129     try: 
130         f = open(VSYSCONF)
131         for line in f.readlines():
132             (path, slice) = line.split()
133             slicesinconf.append(slice)
134         f.close()
135     except: logger.log_exc()
136     return slicesinconf
137
138