1 """vsys configurator. Maintains ACLs and script pipes inside vservers based on slice attributes."""
9 VSYSCONF="/etc/vsys.conf"
13 logger.log("vsys: plugin starting up...")
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."""
18 if 'slivers' not in data:
19 logger.log_missing_data("vsys.GetSlivers",'slivers')
22 # Touch ACLs and create dict of available
24 for script in touchAcls(): scripts[script] = []
25 # slices that need to be written to the conf
28 # Parse attributes and update dict of scripts
29 if 'slivers' not in data:
30 logger.log_missing_data("vsys.GetSlivers",'slivers')
32 for sliver in data['slivers']:
33 for attribute in sliver['attributes']:
34 if attribute['tagname'] == 'vsys':
35 if sliver['name'] not in slices:
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'])
43 _restart = writeConf(slices, parseConf()) or _restart
45 if writeAcls(scripts, parseAcls()) or _restart:
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"])
54 logger.log("vsys: restarting vsys service through /etc/init.d/vsys")
55 logger.log_call(["/etc/init.d/vsys", "restart", ])
57 def createVsysDir(sliver):
58 '''Create /vsys directory in slice. Update vsys conf file.'''
60 os.mkdir("/vservers/%s/vsys" % sliver)
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.'''
72 for (root, dirs, files) in os.walk(VSYSBKEND):
74 # ingore scripts that start with local_
75 if file.startswith("local_"): continue
76 if file.endswith(".acl"):
77 acls.append(file.replace(".acl", ""))
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")
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
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():
99 if (len(oldslivers) != len(currentscripts[acl])) or \
100 (len(set(oldslivers) - set(currentscripts[acl])) != 0):
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)
107 logger.log("vsys: #:)# Warning,Not a valid Vsys script,%s"%acl)
113 '''Parse the frontend script acls. Return {script: [slices]} in conf.'''
114 # make a dict of what slices are in what acls.
116 for (root, dirs, files) in os.walk(VSYSBKEND):
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())
125 # return what scripts are configured for which slices.
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})
148 '''Parse the vsys conf and return list of slices in conf.'''
153 for line in f.readlines():
154 (path, slice) = line.split()
155 slicesinconf.append(slice)
157 except: logger.log_exc("vsys: failed parseConf")
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):
169 trashVsysHandleInSliver (sliver)
171 logger.log("vsys.removeSliverFromConf: no need to remove %s"%sliver)
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)
179 retcod=subprocess.call([ 'rm', '-rf' , slice_vsys_area])
180 logger.log ("vsys.trashVsysHandleInSliver: Removed %s (retcod=%s)"%(slice_vsys_area,retcod))