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