remove svn keywords
[nodemanager.git] / plugins / vsys.py
1 """vsys configurator.  Maintains ACLs and script pipes inside vservers based on slice attributes."""
2
3 import logger
4 import os
5
6 VSYSCONF="/etc/vsys.conf"
7 VSYSBKEND="/vsys"
8
9 def start():
10     logger.log("vsys: plugin starting up...")
11
12 def GetSlivers(data, config=None, plc=None):
13     """For each sliver with the vsys attribute, set the script ACL, create the vsys directory in the slice, and restart vsys."""
14
15     if 'slivers' not in data:
16         logger.log_missing_data("vsys.GetSlivers",'slivers')
17         return
18
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     if 'slivers' not in data:
27         logger.log_missing_data("vsys.GetSlivers",'slivers')
28         return
29     for sliver in data['slivers']:
30         for attribute in sliver['attributes']:
31             if attribute['tagname'] == 'vsys':
32                 if sliver['name'] not in slices:
33                     # add to conf
34                     slices.append(sliver['name'])
35                     _restart = createVsysDir(sliver['name']) or _restart
36                 if attribute['value'] in scripts.keys():
37                     scripts[attribute['value']].append(sliver['name'])
38
39     # Write the conf
40     _restart = writeConf(slices, parseConf()) or _restart
41     # Write out the ACLs
42     if writeAcls(scripts, parseAcls()) or _restart:
43         logger.log("vsys: restarting vsys service")
44         logger.log_call(["/etc/init.d/vsys", "restart", ])
45
46
47 def createVsysDir(sliver):
48     '''Create /vsys directory in slice.  Update vsys conf file.'''
49     try:
50         os.mkdir("/vservers/%s/vsys" % sliver)
51         return True
52     except OSError:
53         return False
54
55
56 def touchAcls():
57     '''Creates empty acl files for scripts.
58     To be ran in case of new scripts that appear in the backend.
59     Returns list of available scripts.'''
60     acls = []
61     scripts = []
62     for (root, dirs, files) in os.walk(VSYSBKEND):
63         for file in files:
64             # ingore scripts that start with local_
65             if file.startswith("local_"): continue
66             if file.endswith(".acl"):
67                 acls.append(file.replace(".acl", ""))
68             else:
69                 scripts.append(file)
70     for new in (set(scripts) - set(acls)):
71         logger.log("vsys: Found new script %s.  Writing empty acl." % new)
72         f = open("%s/%s.acl" %(VSYSBKEND, new), "w")
73         f.write("\n")
74         f.close()
75
76     return scripts
77
78
79 def writeAcls(currentscripts, oldscripts):
80     '''Creates .acl files for script in the script repo.'''
81     # Check each oldscript entry to see if we need to modify
82     _restartvsys = False
83     # for iteritems along dict(oldscripts), if length of values
84     # not the same as length of values of new scripts,
85     # and length of non intersection along new scripts is not 0,
86     # then dicts are different.
87     for (acl, oldslivers) in oldscripts.iteritems():
88         try:
89             if (len(oldslivers) != len(currentscripts[acl])) or \
90             (len(set(oldslivers) - set(currentscripts[acl])) != 0):
91                 _restartvsys = True
92                 logger.log("vsys: Updating %s.acl w/ slices %s" % (acl, currentscripts[acl]))
93                 f = open("%s/%s.acl" % (VSYSBKEND, acl), "w")
94                 for slice in currentscripts[acl]: f.write("%s\n" % slice)
95                 f.close()
96         except KeyError:
97             logger.log("vsys: #:)# Warning,Not a valid Vsys script,%s"%acl)
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