b836dc5ddc41b23547488f762e15c0b9db4298fb
[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():
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         try:
92             if (len(oldslivers) != len(currentscripts[acl])) or \
93             (len(set(oldslivers) - set(currentscripts[acl])) != 0):
94                 _restartvsys = True
95                 logger.log("vsys: Updating %s.acl w/ slices %s" % (acl, currentscripts[acl]))
96                 f = open("%s/%s.acl" % (VSYSBKEND, acl), "w")
97                 for slice in currentscripts[acl]: f.write("%s\n" % slice)
98                 f.close()
99         except KeyError:
100             logger.log("vsys: #:)# Warning,Not a valid Vsys script,%s"%acl)
101     # Trigger a restart
102     return _restartvsys
103
104
105 def parseAcls():
106     '''Parse the frontend script acls.  Return {script: [slices]} in conf.'''
107     # make a dict of what slices are in what acls.
108     scriptacls = {}
109     for (root, dirs, files) in os.walk(VSYSBKEND):
110         for file in files:
111             if file.endswith(".acl") and not file.startswith("local_"):
112                 f = open(root+"/"+file,"r+")
113                 scriptname = file.replace(".acl", "")
114                 scriptacls[scriptname] = []
115                 for slice in f.readlines():
116                     scriptacls[scriptname].append(slice.rstrip())
117                 f.close()
118     # return what scripts are configured for which slices.
119     return scriptacls
120
121
122 def writeConf(slivers, oldslivers):
123     # Check if this is needed
124     # The assumption here is if lengths are the same,
125     # and the non intersection of both arrays has length 0,
126     # then the arrays are identical.
127     if (len(slivers) != len(oldslivers)) or \
128     (len(set(oldslivers) - set(slivers)) != 0):
129         logger.log("vsys:  Updating %s" % VSYSCONF)
130         f = open(VSYSCONF,"w")
131         for sliver in slivers:
132             f.write("/vservers/%(name)s/vsys %(name)s\n" % {"name": sliver})
133         f.truncate()
134         f.close()
135         return True
136     else:
137         return False
138
139
140 def parseConf():
141     '''Parse the vsys conf and return list of slices in conf.'''
142     scriptacls = {}
143     slicesinconf = []
144     try:
145         f = open(VSYSCONF)
146         for line in f.readlines():
147             (path, slice) = line.split()
148             slicesinconf.append(slice)
149         f.close()
150     except: logger.log_exc("vsys: failed parseConf")
151     return slicesinconf