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