Added code to reduce duplicate entries in /etc/vsys.conf; this will help play
[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                 if sliver['name'] not in slices:
31                     # add to conf
32                     slices.append(sliver['name'])
33                     # As the name implies, when we find an attribute, we
34                     createVsysDir(sliver['name'])
35                 # add it to our list of slivers that need vsys
36                 if attribute['value'] in scripts.keys():
37                     scripts[attribute['value']].append(sliver['name'])
38  
39     # Write the conf
40     writeConf(slices, parseConf())
41     # Write out the ACLs
42     if writeAcls(scripts, parseAcls()): 
43         logger.log("vsys: restarting vsys service")
44         os.system("/etc/init.d/vsys restart")
45
46
47 def createVsysDir(sliver):
48     '''Create /vsys directory in slice.  Update vsys conf file.'''
49     try: os.makedirs("/vservers/%s/vsys" % sliver)
50     except OSError: pass
51
52
53 def touchAcls():
54     '''Creates empty acl files for scripts.  
55     To be ran in case of new scripts that appear in the backend.
56     Returns list of available scripts.'''
57     acls = []
58     scripts = []
59     for (root, dirs, files) in os.walk(VSYSBKEND):
60         for file in files:
61             if file.endswith(".acl"):
62                 acls.append(file.rstrip(".acl"))
63             else:
64                 scripts.append(file)
65     for new in (Set(scripts) - Set(acls)):
66         logger.log("vsys: Found new script %s.  Writing empty acl." % new)
67         f = open("%s/%s.acl" %(VSYSBKEND, new), "w")
68         f.write("\n")
69         f.close()
70     
71     return scripts
72
73
74 def writeAcls(currentscripts, oldscripts):
75     '''Creates .acl files for script in the script repo.'''
76     # Check each oldscript entry to see if we need to modify
77     _restartvsys = False
78     # for iteritems along dict(oldscripts), if length of values
79     # not the same as length of values of new scripts,
80     # and length of non intersection along new scripts is not 0,
81     # then dicts are different.
82     for (acl, oldslivers) in oldscripts.iteritems():
83         if (len(oldslivers) != len(currentscripts[acl])) or \
84         (len(Set(oldslivers) - Set(currentscripts[acl])) != 0):
85             _restartvsys = True
86             logger.log("vsys: Updating %s.acl w/ slices %s" % (acl, currentscripts[acl]))
87             f = open("%s/%s.acl" % (VSYSBKEND, acl), "w")
88             for slice in currentscripts[acl]: f.write("%s\n" % slice)
89             f.close()
90     # Trigger a restart
91     return _restartvsys
92
93
94 def parseAcls():
95     '''Parse the frontend script acls.  Return {script: [slices]} in conf.'''
96     # make a dict of what slices are in what acls.
97     scriptacls = {}
98     for (root, dirs, files) in os.walk(VSYSBKEND):
99         for file in files:
100             if file.endswith(".acl"):
101                 f = open(root+"/"+file,"r+")
102                 scriptname = file.rstrip(".acl")
103                 scriptacls[scriptname] = []
104                 for slice in f.readlines():  
105                     scriptacls[scriptname].append(slice.rstrip())
106                 f.close()
107     # return what scripts are configured for which slices.
108     return scriptacls
109
110
111 def writeConf(slivers, oldslivers):
112     # Check if this is needed
113     # The assumption here is if lengths are the same,
114     # and the non intersection of both arrays has length 0,
115     # then the arrays are identical.
116     if (len(slivers) != len(oldslivers)) or \
117     (len(Set(oldslivers) - Set(slivers)) != 0):
118         logger.log("vsys:  Updating %s" % VSYSCONF)
119         f = open(VSYSCONF,"w")
120         for sliver in slivers:
121             f.write("/vservers/%(name)s/vsys %(name)s\n" % {"name": sliver})
122         f.truncate()
123         f.close()
124
125
126 def parseConf():
127     '''Parse the vsys conf and return list of slices in conf.'''
128     scriptacls = {}
129     slicesinconf = []
130     try: 
131         f = open(VSYSCONF)
132         for line in f.readlines():
133             (path, slice) = line.split()
134             slicesinconf.append(slice)
135         f.close()
136     except: logger.log_exc()
137     return slicesinconf
138
139