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