another bugfix
[nodemanager.git] / plugins / vsys.py
1 """vsys configurator.  Maintains ACLs and script pipes inside vservers based on slice attributes."""
2
3 import os
4 import subprocess
5
6 import logger
7 import tools
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         restartService()
47
48 # check for systemctl, use it if present
49 def restartService ():
50     if tools.has_systemctl():
51         logger.log("vsys: restarting vsys service through systemctl")
52         logger.log_call(["systemctl", "restart", "vsys"])
53     else:
54         logger.log("vsys: restarting vsys service through /etc/init.d/vsys")
55         logger.log_call(["/etc/init.d/vsys", "restart", ])
56
57 def createVsysDir(sliver):
58     '''Create /vsys directory in slice.  Update vsys conf file.'''
59     try:
60         os.mkdir("/vservers/%s/vsys" % sliver)
61         return True
62     except OSError:
63         return False
64
65
66 def touchAcls():
67     '''Creates empty acl files for scripts.
68     To be ran in case of new scripts that appear in the backend.
69     Returns list of available scripts.'''
70     acls = []
71     scripts = []
72     for (root, dirs, files) in os.walk(VSYSBKEND):
73         for file in files:
74             # ingore scripts that start with local_
75             if file.startswith("local_"): continue
76             if file.endswith(".acl"):
77                 acls.append(file.replace(".acl", ""))
78             else:
79                 scripts.append(file)
80     for new in (set(scripts) - set(acls)):
81         logger.log("vsys: Found new script %s.  Writing empty acl." % new)
82         f = open("%s/%s.acl" %(VSYSBKEND, new), "w")
83         f.write("\n")
84         f.close()
85
86     return scripts
87
88
89 def writeAcls(currentscripts, oldscripts):
90     '''Creates .acl files for script in the script repo.'''
91     # Check each oldscript entry to see if we need to modify
92     _restartvsys = False
93     # for iteritems along dict(oldscripts), if length of values
94     # not the same as length of values of new scripts,
95     # and length of non intersection along new scripts is not 0,
96     # then dicts are different.
97     for (acl, oldslivers) in oldscripts.iteritems():
98         try:
99             if (len(oldslivers) != len(currentscripts[acl])) or \
100             (len(set(oldslivers) - set(currentscripts[acl])) != 0):
101                 _restartvsys = True
102                 logger.log("vsys: Updating %s.acl w/ slices %s" % (acl, currentscripts[acl]))
103                 f = open("%s/%s.acl" % (VSYSBKEND, acl), "w")
104                 for slice in currentscripts[acl]: f.write("%s\n" % slice)
105                 f.close()
106         except KeyError:
107             logger.log("vsys: #:)# Warning,Not a valid Vsys script,%s"%acl)
108     # Trigger a restart
109     return _restartvsys
110
111
112 def parseAcls():
113     '''Parse the frontend script acls.  Return {script: [slices]} in conf.'''
114     # make a dict of what slices are in what acls.
115     scriptacls = {}
116     for (root, dirs, files) in os.walk(VSYSBKEND):
117         for file in files:
118             if file.endswith(".acl") and not file.startswith("local_"):
119                 f = open(root+"/"+file,"r+")
120                 scriptname = file.replace(".acl", "")
121                 scriptacls[scriptname] = []
122                 for slice in f.readlines():
123                     scriptacls[scriptname].append(slice.rstrip())
124                 f.close()
125     # return what scripts are configured for which slices.
126     return scriptacls
127
128
129 def writeConf(slivers, oldslivers):
130     # Check if this is needed
131     # The assumption here is if lengths are the same,
132     # and the non intersection of both arrays has length 0,
133     # then the arrays are identical.
134     if (len(slivers) != len(oldslivers)) or \
135     (len(set(oldslivers) - set(slivers)) != 0):
136         logger.log("vsys:  Updating %s" % VSYSCONF)
137         f = open(VSYSCONF,"w")
138         for sliver in slivers:
139             f.write("/vservers/%(name)s/vsys %(name)s\n" % {"name": sliver})
140         f.truncate()
141         f.close()
142         return True
143     else:
144         return False
145
146
147 def parseConf():
148     '''Parse the vsys conf and return list of slices in conf.'''
149     scriptacls = {}
150     slicesinconf = []
151     try:
152         f = open(VSYSCONF)
153         for line in f.readlines():
154             (path, slice) = line.split()
155             slicesinconf.append(slice)
156         f.close()
157     except: logger.log_exc("vsys: failed parseConf")
158     return slicesinconf
159
160
161 # before shutting down slivers, it is safe to first remove them from vsys's scope
162 # so that we are sure that no dangling open file remains
163 # this will also restart vsys if needed
164 def removeSliverFromVsys (sliver):
165     current_slivers=parseConf()
166     new_slivers= [ s for s in current_slivers if s != sliver ]
167     if writeConf (current_slivers, new_slivers):
168         restartService()
169         trashVsysHandleInSliver (sliver)
170     else:
171         logger.log("vsys.removeSliverFromConf: no need to remove %s"%sliver)
172
173
174 def trashVsysHandleInSliver (sliver):
175     slice_vsys_area = "/vservers/%s/vsys"%sliver
176     if not os.path.exists(slice_vsys_area):
177         logger.log("vsys.trashVsysHandleInSliver: no action needed, %s not found"%slice_vsys_area)
178         return
179     retcod=subprocess.call([ 'rm', '-rf' , slice_vsys_area])
180     logger.log ("vsys.trashVsysHandleInSliver: Removed %s (retcod=%s)"%(slice_vsys_area,retcod))