Use indirection to report error strings
[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 import config as pconfig
24
25
26 ADMIN_STATUS_OK = "success"
27 ADMIN_STATUS_ERROR = "danger"
28 ADMIN_STATUS_WARN = "warning"
29
30
31 class AdminError(Exception):
32     def __init__(self, message):
33         super(AdminError, self).__init__(message)
34         self.message = message
35
36     def __str__(self):
37         return str(self.message)
38
39
40 class AdminPage(Page):
41
42     def __init__(self, *args, **kwargs):
43         super(AdminPage, self).__init__(*args, **kwargs)
44         self.default_headers.update({
45             'Cache-Control': 'no-cache, must-revalidate',
46             'Pragma': 'no-cache',
47             'Expires': 'Thu, 01 Dec 1994 16:00:00 GMT',
48         })
49         self.auth_protect = True
50
51
52 class AdminPluginConfig(AdminPage):
53
54     def __init__(self, po, site, parent):
55         super(AdminPluginConfig, self).__init__(site, form=True)
56         self._po = po
57         self.title = '%s plugin' % po.name
58         self.url = '%s/%s' % (parent.url, po.name)
59         self.facility = parent.facility
60         self.menu = [parent]
61         self.back = parent.url
62
63     def root_with_msg(self, message=None, message_type=None):
64         return self._template('admin/plugin_config.html', title=self.title,
65                               menu=self.menu, action=self.url, back=self.back,
66                               message=message, message_type=message_type,
67                               name='admin_%s_%s_form' % (self.facility,
68                                                          self._po.name),
69                               config=self._po.get_config_obj())
70
71     @admin_protect
72     def GET(self, *args, **kwargs):
73         return self.root_with_msg()
74
75     @admin_protect
76     def POST(self, *args, **kwargs):
77
78         if self._po.is_readonly:
79             return self.root_with_msg(
80                 message="Configuration is marked Read-Only",
81                 message_type=ADMIN_STATUS_WARN)
82
83         message = "Nothing was modified."
84         message_type = "info"
85         new_db_values = dict()
86
87         conf = self._po.get_config_obj()
88
89         for name, option in conf.iteritems():
90             if name in kwargs:
91                 value = kwargs[name]
92                 if isinstance(option, pconfig.List):
93                     value = [x.strip() for x in value.split('\n')]
94                 elif isinstance(option, pconfig.Condition):
95                     value = True
96             else:
97                 if isinstance(option, pconfig.Condition):
98                     value = False
99                 elif isinstance(option, pconfig.Choice):
100                     value = list()
101                     for a in option.get_allowed():
102                         aname = '%s_%s' % (name, a)
103                         if aname in kwargs:
104                             value.append(a)
105                 else:
106                     continue
107
108             if value != option.get_value():
109                 cherrypy.log.error("Storing [%s]: %s = %s" %
110                                    (self._po.name, name, value))
111             option.set_value(value)
112             new_db_values[name] = option.export_value()
113
114         if len(new_db_values) != 0:
115             # First we try to save in the database
116             try:
117                 self._po.save_plugin_config(new_db_values)
118                 message = "New configuration saved."
119                 message_type = ADMIN_STATUS_OK
120             except Exception:  # pylint: disable=broad-except
121                 message = "Failed to save data!"
122                 message_type = ADMIN_STATUS_ERROR
123
124             # Then refresh the actual objects
125             self._po.refresh_plugin_config()
126
127         return self.root_with_msg(message=message,
128                                   message_type=message_type)
129
130
131 class AdminPluginsOrder(AdminPage):
132
133     def __init__(self, site, parent, facility):
134         super(AdminPluginsOrder, self).__init__(site, form=True)
135         self.parent = parent
136         self.facility = facility
137         self.url = '%s/order' % parent.url
138         self.menu = [parent]
139
140     @admin_protect
141     def GET(self, *args, **kwargs):
142         return self.parent.root_with_msg()
143
144     def _get_enabled_list(self):
145         cur = list()
146         for p in self._site[self.facility].available.values():
147             if p.is_enabled:
148                 cur.append(p.name)
149         return cur
150
151     @admin_protect
152     def POST(self, *args, **kwargs):
153
154         if self._site[self.facility].is_readonly:
155             return self.parent.root_with_msg(
156                 message="Configuration is marked Read-Only",
157                 message_type=ADMIN_STATUS_WARN)
158
159         message = "Nothing was modified."
160         message_type = "info"
161         cur_enabled = self._get_enabled_list()
162
163         if 'order' in kwargs:
164             order = kwargs['order'].split(',')
165             if len(order) != 0:
166                 new_order = []
167                 try:
168                     for v in order:
169                         val = v.strip()
170                         if val not in cur_enabled:
171                             error = "Invalid plugin name: %s" % val
172                             raise ValueError(error)
173                         new_order.append(val)
174                     if len(new_order) < len(cur_enabled):
175                         for val in cur_enabled:
176                             if val not in new_order:
177                                 new_order.append(val)
178
179                     self.parent.save_enabled_plugins(new_order)
180
181                     # When all is saved update also live config. The
182                     # live config is the ordered list of plugin names.
183                     self._site[self.facility].refresh_enabled()
184
185                     message = "New configuration saved."
186                     message_type = ADMIN_STATUS_OK
187
188                 except ValueError, e:
189                     message = str(e)
190                     message_type = ADMIN_STATUS_ERROR
191
192                 except Exception, e:  # pylint: disable=broad-except
193                     message = "Failed to save data!"
194                     message_type = ADMIN_STATUS_ERROR
195
196         return self.parent.root_with_msg(message=message,
197                                          message_type=message_type)
198
199
200 class AdminPlugins(AdminPage):
201     def __init__(self, name, site, parent, facility, ordered=True):
202         super(AdminPlugins, self).__init__(site)
203         self._master = parent
204         self.name = name
205         self.title = '%s plugins' % name
206         self.url = '%s/%s' % (parent.url, name)
207         self.facility = facility
208         self.template = 'admin/plugins.html'
209         self.order = None
210         parent.add_subtree(name, self)
211
212         for plugin in self._site[facility].available:
213             cherrypy.log.error('Admin info plugin: %s' % plugin)
214             obj = self._site[facility].available[plugin]
215             page = AdminPluginConfig(obj, self._site, self)
216             if hasattr(obj, 'admin'):
217                 obj.admin.mount(page)
218             self.add_subtree(plugin, page)
219
220         if ordered:
221             self.order = AdminPluginsOrder(self._site, self, facility)
222
223     def save_enabled_plugins(self, names):
224         self._site[self.facility].save_enabled(names)
225
226     def root_with_msg(self, message=None, message_type=None):
227         plugins = self._site[self.facility]
228
229         targs = {'title': self.title,
230                  'menu': self._master.menu,
231                  'message': message,
232                  'message_type': message_type,
233                  'available': plugins.available,
234                  'enabled': plugins.enabled,
235                  'baseurl': self.url,
236                  'newurl': self.url}
237         if self.order:
238             targs['order_name'] = '%s_order_form' % self.name
239             targs['order_action'] = self.order.url
240
241         # pylint: disable=star-args
242         return self._template(self.template, **targs)
243
244     def root(self, *args, **kwargs):
245         return self.root_with_msg()
246
247     def _get_plugin_obj(self, plugin):
248         plugins = self._site[self.facility]
249         if plugins.is_readonly:
250             msg = "Configuration is marked Read-Only"
251             raise AdminError(msg)
252         if plugin not in plugins.available:
253             msg = "Unknown plugin %s" % plugin
254             raise AdminError(msg)
255         obj = plugins.available[plugin]
256         if obj.is_readonly:
257             msg = "Plugin Configuration is marked Read-Only"
258             raise AdminError(msg)
259         return obj
260
261     @admin_protect
262     def enable(self, plugin):
263         msg = None
264         try:
265             obj = self._get_plugin_obj(plugin)
266         except AdminError, e:
267             return self.root_with_msg(str(e), ADMIN_STATUS_WARN)
268         if not obj.is_enabled:
269             obj.enable()
270             obj.save_enabled_state()
271             msg = "Plugin %s enabled" % obj.name
272         return self.root_with_msg(msg, ADMIN_STATUS_OK)
273     enable.public_function = True
274
275     @admin_protect
276     def disable(self, plugin):
277         msg = None
278         try:
279             obj = self._get_plugin_obj(plugin)
280         except AdminError, e:
281             return self.root_with_msg(str(e), ADMIN_STATUS_WARN)
282         if obj.is_enabled:
283             obj.disable()
284             obj.save_enabled_state()
285             msg = "Plugin %s disabled" % obj.name
286         return self.root_with_msg(msg, ADMIN_STATUS_OK)
287     disable.public_function = True
288
289
290 class Admin(AdminPage):
291
292     def __init__(self, site, mount):
293         super(Admin, self).__init__(site)
294         self.title = 'Home'
295         self.mount = mount
296         self.url = '%s/%s' % (self.basepath, mount)
297         self.menu = [self]
298
299     def root(self, *args, **kwargs):
300         return self._template('admin/index.html',
301                               title='Configuration',
302                               baseurl=self.url,
303                               menu=self.menu)
304
305     def add_subtree(self, name, page):
306         self.__dict__[name] = page
307         self.menu.append(page)
308
309     def del_subtree(self, name):
310         self.menu.remove(self.__dict__[name])
311         del self.__dict__[name]
312
313     def get_menu_urls(self):
314         urls = dict()
315         for item in self.menu:
316             name = getattr(item, 'name', None)
317             if name:
318                 urls['%s_url' % name] = cherrypy.url('/%s/%s' % (self.mount,
319                                                                  name))
320         return urls
321
322     @admin_protect
323     def scheme(self):
324         cherrypy.response.headers.update({'Content-Type': 'image/svg+xml'})
325         urls = self.get_menu_urls()
326         # pylint: disable=star-args
327         return self._template('admin/ipsilon-scheme.svg', **urls)
328     scheme.public_function = True