clean up the code that removes a slice from vsys's scope before its rootfs gets deleted
[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 import tools
6
7 VSYSCONF="/etc/vsys.conf"
8 VSYSBKEND="/vsys"
9
10 def start():
11     logger.log("vsys: plugin starting up...")
12
13 def GetSlivers(data, config=None, plc=None):
14     """For each sliver with the vsys attribute, set the script ACL, create the vsys directory in the slice, and restart vsys."""
15
16     if 'slivers' not in data:
17         logger.log_missing_data("vsys.GetSlivers",'slivers')
18         return
19
20     # Touch ACLs and create dict of available
21     scripts = {}
22     for script in touchAcls(): scripts[script] = []
23     # slices that need to be written to the conf
24     slices = []
25     _restart = False
26     # Parse attributes and update dict of scripts
27     if 'slivers' not in data:
28         logger.log_missing_data("vsys.GetSlivers",'slivers')
29         return
30     for sliver in data['slivers']:
31         for attribute in sliver['attributes']:
32             if attribute['tagname'] == 'vsys':
33                 if sliver['name'] not in slices:
34                     # add to conf
35                     slices.append(sliver['name'])
36                     _restart = createVsysDir(sliver['name']) or _restart
37                 if attribute['value'] in scripts.keys():
38                     scripts[attribute['value']].append(sliver['name'])
39
40     # Write the conf
41     _restart = writeConf(slices, parseConf()) or _restart
42     # Write out the ACLs
43     if writeAcls(scripts, parseAcls()) or _restart:
44         restartService()
45
46 # check for systemctl, use it if present
47 def restartService ():
48     if tools.has_systemctl():
49         logger.log("vsys: restarting vsys service through systemctl")
50         logger.log_call(["systemctl", "restart", "vsys"])
51     else:
52         logger.log("vsys: restarting vsys service through /etc/init.d/vsys")
53         logger.log_call(["/etc/init.d/vsys", "restart", ])
54
55 def createVsysDir(sliver):
56     '''Create /vsys directory in slice.  Update vsys conf file.'''
57     try:
58         os.mkdir("/vservers/%s/vsys" % sliver)
59         return True
60     except OSError:
61         return False
62
63
64 def touchAcls():
65     '''Creates empty acl files for scripts.
66     To be ran in case of new scripts that appear in the backend.
67     Returns list of available scripts.'''
68     acls = []
69     scripts = []
70     for (root, dirs, files) in os.walk(VSYSBKEND):
71         for file in files:
72             # ingore scripts that start with local_
73             if file.startswith("local_"): continue
74             if file.endswith(".acl"):
75                 acls.append(file.replace(".acl", ""))
76             else:
77                 scripts.append(file)
78     for new in (set(scripts) - set(acls)):
79         logger.log("vsys: Found new script %s.  Writing empty acl." % new)
80         f = open("%s/%s.acl" %(VSYSBKEND, new), "w")
81         f.write("\n")
82         f.close()
83
84     return scripts
85
86
87 def writeAcls(currentscripts, oldscripts):
88     '''Creates .acl files for script in the script repo.'''
89     # Check each oldscript entry to see if we need to modify
90     _restartvsys = False
91     # for iteritems along dict(oldscripts), if length of values
92     # not the same as length of values of new scripts,
93     # and length of non intersection along new scripts is not 0,
94     # then dicts are different.
95     for (acl, oldslivers) in oldscripts.iteritems():
96         try:
97             if (len(oldslivers) != len(currentscripts[acl])) or \
98             (len(set(oldslivers) - set(currentscripts[acl])) != 0):
99                 _restartvsys = True
100                 logger.log("vsys: Updating %s.acl w/ slices %s" % (acl, currentscripts[acl]))
101                 f = open("%s/%s.acl" % (VSYSBKEND, acl), "w")
102                 for slice in currentscripts[acl]: f.write("%s\n" % slice)
103                 f.close()
104         except KeyError:
105             logger.log("vsys: #:)# Warning,Not a valid Vsys script,%s"%acl)
106     # Trigger a restart
107     return _restartvsys
108
109
110 def parseAcls():
111     '''Parse the frontend script acls.  Return {script: [slices]} in conf.'''
112     # make a dict of what slices are in what acls.
113     scriptacls = {}
114     for (root, dirs, files) in os.walk(VSYSBKEND):
115         for file in files:
116             if file.endswith(".acl") and not file.startswith("local_"):
117                 f = open(root+"/"+file,"r+")
118                 scriptname = file.replace(".acl", "")
119                 scriptacls[scriptname] = []
120                 for slice in f.readlines():
121                     scriptacls[scriptname].append(slice.rstrip())
122                 f.close()
123     # return what scripts are configured for which slices.
124     return scriptacls
125
126
127 def writeConf(slivers, oldslivers):
128     # Check if this is needed
129     # The assumption here is if lengths are the same,
130     # and the non intersection of both arrays has length 0,
131     # then the arrays are identical.
132     if (len(slivers) != len(oldslivers)) or \
133     (len(set(oldslivers) - set(slivers)) != 0):
134         logger.log("vsys:  Updating %s" % VSYSCONF)
135         f = open(VSYSCONF,"w")
136         for sliver in slivers:
137             f.write("/vservers/%(name)s/vsys %(name)s\n" % {"name": sliver})
138         f.truncate()
139         f.close()
140         return True
141     else:
142         return False
143
144
145 def parseConf():
146     '''Parse the vsys conf and return list of slices in conf.'''
147     scriptacls = {}
148     slicesinconf = []
149     try:
150         f = open(VSYSCONF)
151         for line in f.readlines():
152             (path, slice) = line.split()
153             slicesinconf.append(slice)
154         f.close()
155     except: logger.log_exc("vsys: failed parseConf")
156     return slicesinconf
157
158
159 # before shutting down slivers, it is safe to first remove them from vsys's scope
160 # so that we are sure that no dangling open file remains
161 # this will also restart vsys if needed
162 def removeSliverFromVsys (sliver):
163     current_slivers=parseConf()
164     new_slivers= [ s for s in current_slivers if s != sliver ]
165     if writeConf (current_slivers, new_slivers):
166         trashSliverVsys (sliver)
167         restartService()
168     else:
169         logger.log("vsys.removeSliverFromConf: no need to remove %s"%sliver)
170
171
172 def trashSliverVsys (sliver):
173     slice_vsys_area = "/vservers/%s/vsys"%sliver
174     if not os.path.exists(slice_vsys_area):
175         logger.log("vsys.trashSliverVsys: no action needed, %s not found"%slice_vsys_area)
176         return
177     ret=subprocess.call([ 'rm', '-rf' , slice_vsys_area])
178     logger.log ("vsys.trashSliverVsys: Removed %s (retcod=%s)"%(slice_vsys_area,retcod))