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