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