Reuse the AdminPlugins class for the providers too
[cascardo/ipsilon.git] / ipsilon / admin / common.py
1 #!/usr/bin/python
2 #
3 # Copyright (C) 2014  Simo Sorce <simo@redhat.com>
4 #
5 # see file 'COPYING' for use and warranty information
6 #
7 # This program is free software; you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation, either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
19
20 import cherrypy
21 from ipsilon.util.page import Page
22 from ipsilon.util.page import admin_protect
23 from ipsilon.util.plugin import PluginObject
24
25
26 class AdminPage(Page):
27
28     def __init__(self, *args, **kwargs):
29         super(AdminPage, self).__init__(*args, **kwargs)
30         self.default_headers.update({
31             'Cache-Control': 'no-cache, must-revalidate',
32             'Pragma': 'no-cache',
33             'Expires': 'Thu, 01 Dec 1994 16:00:00 GMT',
34         })
35         self.auth_protect = True
36
37
38 class AdminPluginConfig(AdminPage):
39
40     def __init__(self, po, site, parent):
41         super(AdminPluginConfig, self).__init__(site, form=True)
42         self._po = po
43         self.title = '%s plugin' % po.name
44         self.url = '%s/%s' % (parent.url, po.name)
45         self.facility = parent.facility
46         self.menu = [parent]
47         self.back = parent.url
48
49         # Get the defaults
50         options = po.get_config_desc()
51         if options is None:
52             options = dict()
53
54         self.options_order = []
55         if hasattr(po, 'conf_opt_order'):
56             self.options_order = po.conf_opt_order
57
58         # append any undefined options
59         add = []
60         for k in options.keys():
61             if k not in self.options_order:
62                 add.append(k)
63         if len(add):
64             add.sort()
65             for k in add:
66                 self.options_order.append(k)
67
68     @admin_protect
69     def GET(self, *args, **kwargs):
70         return self._template('admin/plugin_config.html', title=self.title,
71                               name='admin_%s_%s_form' % (self.facility,
72                                                          self._po.name),
73                               menu=self.menu, action=self.url, back=self.back,
74                               options_order=self.options_order,
75                               plugin=self._po)
76
77     @admin_protect
78     def POST(self, *args, **kwargs):
79
80         message = "Nothing was modified."
81         message_type = "info"
82         new_values = dict()
83
84         # Get the defaults
85         options = self._po.get_config_desc()
86         if options is None:
87             options = dict()
88
89         for key, value in kwargs.iteritems():
90             if key in options:
91                 if value != self._po.get_config_value(key):
92                     cherrypy.log.error("Storing [%s]: %s = %s" %
93                                        (self._po.name, key, value))
94                     new_values[key] = value
95
96         if len(new_values) != 0:
97             # First we try to save in the database
98             try:
99                 self._po.save_plugin_config(self.facility, new_values)
100                 message = "New configuration saved."
101                 message_type = "success"
102             except Exception:  # pylint: disable=broad-except
103                 message = "Failed to save data!"
104                 message_type = "error"
105
106             # And only if it succeeds we change the live object
107             self._po.refresh_plugin_config(self.facility)
108
109         return self._template('admin/plugin_config.html', title=self.title,
110                               message=message,
111                               message_type=message_type,
112                               name='admin_%s_%s_form' % (self.facility,
113                                                          self._po.name),
114                               menu=self.menu, action=self.url,
115                               plugin=self._po)
116
117
118 class AdminPluginsOrder(AdminPage):
119
120     def __init__(self, site, parent, facility):
121         super(AdminPluginsOrder, self).__init__(site, form=True)
122         self.parent = parent
123         self.facility = facility
124         self.url = '%s/order' % parent.url
125         self.menu = [parent]
126
127     @admin_protect
128     def GET(self, *args, **kwargs):
129         return self.parent.root_with_msg()
130
131     @admin_protect
132     def POST(self, *args, **kwargs):
133         message = "Nothing was modified."
134         message_type = "info"
135         by_name = {p.name: p for p in self._site[self.facility]['enabled']}
136
137         if 'order' in kwargs:
138             order = kwargs['order'].split(',')
139             if len(order) != 0:
140                 new_names = []
141                 new_plugins = []
142                 try:
143                     for v in order:
144                         val = v.strip()
145                         if val not in by_name:
146                             error = "Invalid plugin name: %s" % val
147                             raise ValueError(error)
148                         new_names.append(val)
149                         new_plugins.append(by_name[val])
150                     if len(new_names) < len(by_name):
151                         for val in by_name:
152                             if val not in new_names:
153                                 new_names.append(val)
154                                 new_plugins.append(by_name[val])
155
156                     self.parent.save_enabled_plugins(new_names)
157                     self.parent.reorder_plugins(new_names)
158
159                     # When all is saved update also live config. The
160                     # live config is a list of the actual plugin
161                     # objects.
162                     self._site[self.facility]['enabled'] = new_plugins
163
164                     message = "New configuration saved."
165                     message_type = "success"
166
167                 except ValueError, e:
168                     message = str(e)
169                     message_type = "error"
170
171                 except Exception, e:  # pylint: disable=broad-except
172                     message = "Failed to save data!"
173                     message_type = "error"
174
175         return self.parent.root_with_msg(message=message,
176                                          message_type=message_type)
177
178
179 class AdminPlugins(AdminPage):
180     def __init__(self, name, site, parent, facility, ordered=True):
181         super(AdminPlugins, self).__init__(site)
182         self._master = parent
183         self.name = name
184         self.title = '%s plugins' % name
185         self.url = '%s/%s' % (parent.url, name)
186         self.facility = facility
187         self.template = 'admin/plugins.html'
188         self.order = None
189         parent.add_subtree(name, self)
190
191         for plugin in self._site[facility]['available']:
192             cherrypy.log.error('Admin info plugin: %s' % plugin)
193             obj = self._site[facility]['available'][plugin]
194             page = AdminPluginConfig(obj, self._site, self)
195             if hasattr(obj, 'admin'):
196                 obj.admin.mount(page)
197             self.add_subtree(plugin, page)
198
199         if ordered:
200             self.order = AdminPluginsOrder(self._site, self, facility)
201
202     def save_enabled_plugins(self, names):
203         po = PluginObject()
204         po.name = "global"
205         globalconf = dict()
206         globalconf['order'] = ','.join(names)
207         po.set_config(globalconf)
208         po.save_plugin_config(self.facility)
209
210     def reorder_plugins(self, names):
211         return
212
213     def root_with_msg(self, message=None, message_type=None):
214         plugins = self._site[self.facility]
215         enabled = []
216         if self.order:
217             for plugin in plugins['enabled']:
218                 enabled.append(plugin.name)
219         else:
220             for _, plugin in plugins['available'].iteritems():
221                 if plugin.is_enabled:
222                     enabled.append(plugin.name)
223
224         targs = {'title': self.title,
225                  'menu': self._master.menu,
226                  'message': message,
227                  'message_type': message_type,
228                  'available': plugins['available'],
229                  'enabled': enabled,
230                  'baseurl': self.url}
231         if self.order:
232             targs['order_name'] = '%s_order_form' % self.name
233             targs['order_action'] = self.order.url
234
235         # pylint: disable=star-args
236         return self._template(self.template, **targs)
237
238     def root(self, *args, **kwargs):
239         return self.root_with_msg()
240
241     @admin_protect
242     def enable(self, plugin):
243         msg = None
244         plugins = self._site[self.facility]
245         if plugin not in plugins['available']:
246             msg = "Unknown plugin %s" % plugin
247             return self.root_with_msg(msg, "error")
248         obj = plugins['available'][plugin]
249         if not obj.is_enabled:
250             obj.enable(self._site)
251             if self.order:
252                 enabled = list(x.name for x in plugins['enabled'])
253                 self.save_enabled_plugins(enabled)
254             msg = "Plugin %s enabled" % obj.name
255         return self.root_with_msg(msg, "success")
256     enable.public_function = True
257
258     @admin_protect
259     def disable(self, plugin):
260         msg = None
261         plugins = self._site[self.facility]
262         if plugin not in plugins['available']:
263             msg = "Unknown plugin %s" % plugin
264             return self.root_with_msg(msg, "error")
265         obj = plugins['available'][plugin]
266         if obj.is_enabled:
267             obj.disable(self._site)
268             if self.order:
269                 enabled = list(x.name for x in plugins['enabled'])
270                 self.save_enabled_plugins(enabled)
271             msg = "Plugin %s disabled" % obj.name
272         return self.root_with_msg(msg, "success")
273     disable.public_function = True
274
275
276 class Admin(AdminPage):
277
278     def __init__(self, site, mount):
279         super(Admin, self).__init__(site)
280         self.url = '%s/%s' % (self.basepath, mount)
281         self.menu = []
282
283     def root(self, *args, **kwargs):
284         return self._template('admin/index.html',
285                               title='Configuration',
286                               menu=self.menu)
287
288     def add_subtree(self, name, page):
289         self.__dict__[name] = page
290         self.menu.append(page)
291
292     def del_subtree(self, name):
293         self.menu.remove(self.__dict__[name])
294         del self.__dict__[name]