1 # Copyright (C) 2014 Simo Sorce <simo@redhat.com>
3 # see file 'COPYING' for use and warranty information
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
15 # You should have received a copy of the GNU General Public License
16 # along with this program. If not, see <http://www.gnu.org/licenses/>.
19 from ipsilon.util.page import Page
20 from ipsilon.util.page import admin_protect
21 from ipsilon.util.endpoint import allow_iframe
22 from ipsilon.util import config as pconfig
25 ADMIN_STATUS_OK = "success"
26 ADMIN_STATUS_ERROR = "danger"
27 ADMIN_STATUS_WARN = "warning"
30 class AdminError(Exception):
31 def __init__(self, message):
32 super(AdminError, self).__init__(message)
33 self.message = message
36 return str(self.message)
39 class AdminPage(Page):
41 def __init__(self, *args, **kwargs):
42 super(AdminPage, self).__init__(*args, **kwargs)
43 self.auth_protect = True
46 class AdminPluginConfig(AdminPage):
48 def __init__(self, po, site, parent):
49 super(AdminPluginConfig, self).__init__(site, form=True)
51 self.title = '%s plugin' % po.name
52 self.url = '%s/%s' % (parent.url, po.name)
53 self.facility = parent.facility
55 self.back = parent.url
57 def root_with_msg(self, message=None, message_type=None):
58 return self._template('admin/option_config.html', title=self.title,
59 menu=self.menu, action=self.url, back=self.back,
60 message=message, message_type=message_type,
61 name='admin_%s_%s_form' % (self.facility,
63 config=self._po.get_config_obj())
66 def GET(self, *args, **kwargs):
67 return self.root_with_msg()
70 def POST(self, *args, **kwargs):
72 if self._po.is_readonly:
73 return self.root_with_msg(
74 message="Configuration is marked Read-Only",
75 message_type=ADMIN_STATUS_WARN)
77 message = "Nothing was modified."
79 new_db_values = dict()
81 conf = self._po.get_config_obj()
83 for name, option in conf.iteritems():
86 if isinstance(option, pconfig.List):
87 value = [x.strip() for x in value.split('\n')]
88 elif isinstance(option, pconfig.Condition):
91 if isinstance(option, pconfig.Condition):
93 elif isinstance(option, pconfig.Choice):
95 for a in option.get_allowed():
96 aname = '%s_%s' % (name, a)
99 elif type(option) is pconfig.ComplexList:
100 value = get_complex_list_value(name,
105 elif type(option) is pconfig.MappingList:
106 value = get_mapping_list_value(name,
114 if value != option.get_value():
115 cherrypy.log.error("Storing [%s]: %s = %s" %
116 (self._po.name, name, value))
117 option.set_value(value)
118 new_db_values[name] = option.export_value()
120 if len(new_db_values) != 0:
121 # First we try to save in the database
123 self._po.save_plugin_config(new_db_values)
124 message = "New configuration saved."
125 message_type = ADMIN_STATUS_OK
126 except Exception as e: # pylint: disable=broad-except
127 self.error('Failed to save data: %s' % e)
128 message = "Failed to save data!"
129 message_type = ADMIN_STATUS_ERROR
131 # Then refresh the actual objects
132 self._po.refresh_plugin_config()
134 return self.root_with_msg(message=message,
135 message_type=message_type)
138 class AdminPluginsOrder(AdminPage):
140 def __init__(self, site, parent, facility):
141 super(AdminPluginsOrder, self).__init__(site, form=True)
143 self.facility = facility
144 self.url = '%s/order' % parent.url
148 def GET(self, *args, **kwargs):
149 return self.parent.root_with_msg()
152 def POST(self, *args, **kwargs):
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)
159 message = "Nothing was modified."
160 message_type = "info"
162 cur_enabled = self._site[self.facility].enabled
164 if 'order' in kwargs:
165 order = kwargs['order'].split(',')
171 if val not in cur_enabled:
172 error = "Invalid plugin name: %s" % val
173 raise ValueError(error)
174 new_order.append(val)
175 if len(new_order) < len(cur_enabled):
176 for val in cur_enabled:
177 if val not in new_order:
178 new_order.append(val)
180 self.parent.save_enabled_plugins(new_order)
182 # When all is saved update also live config. The
183 # live config is the ordered list of plugin names.
184 self._site[self.facility].refresh_enabled()
186 message = "New configuration saved."
187 message_type = ADMIN_STATUS_OK
190 self.debug('%s -> %s' % (cur_enabled, new_order))
191 for i in range(0, len(cur_enabled)):
192 if cur_enabled[i] != new_order[i]:
193 changed[cur_enabled[i]] = 'reordered'
195 except ValueError, e:
197 message_type = ADMIN_STATUS_ERROR
199 except Exception as e: # pylint: disable=broad-except
200 self.error('Failed to save data: %s' % e)
201 message = "Failed to save data!"
202 message_type = ADMIN_STATUS_ERROR
204 return self.parent.root_with_msg(message=message,
205 message_type=message_type,
209 class AdminPlugins(AdminPage):
210 def __init__(self, name, site, parent, facility, ordered=True):
211 super(AdminPlugins, self).__init__(site)
212 self._master = parent
214 self.title = '%s plugins' % name
215 self.url = '%s/%s' % (parent.url, name)
216 self.facility = facility
217 self.template = 'admin/plugins.html'
219 parent.add_subtree(name, self)
221 for plugin in self._site[facility].available:
222 cherrypy.log.error('Admin info plugin: %s' % plugin)
223 obj = self._site[facility].available[plugin]
224 page = AdminPluginConfig(obj, self._site, self)
225 if hasattr(obj, 'admin'):
226 obj.admin.mount(page)
227 self.add_subtree(plugin, page)
230 self.order = AdminPluginsOrder(self._site, self, facility)
232 def save_enabled_plugins(self, names):
233 self._site[self.facility].save_enabled(names)
235 def root_with_msg(self, message=None, message_type=None, changed=None):
236 plugins = self._site[self.facility]
241 targs = {'title': self.title,
242 'menu': self._master.menu,
244 'message_type': message_type,
245 'available': plugins.available,
246 'enabled': plugins.enabled,
251 targs['order_name'] = '%s_order_form' % self.name
252 targs['order_action'] = self.order.url
254 # pylint: disable=star-args
255 return self._template(self.template, **targs)
257 def root(self, *args, **kwargs):
258 return self.root_with_msg()
260 def _get_plugin_obj(self, plugin):
261 plugins = self._site[self.facility]
262 if plugins.is_readonly:
263 msg = "Configuration is marked Read-Only"
264 raise AdminError(msg)
265 if plugin not in plugins.available:
266 msg = "Unknown plugin %s" % plugin
267 raise AdminError(msg)
268 obj = plugins.available[plugin]
270 msg = "Plugin Configuration is marked Read-Only"
271 raise AdminError(msg)
275 def enable(self, plugin):
278 obj = self._get_plugin_obj(plugin)
279 except AdminError, e:
280 return self.root_with_msg(str(e), ADMIN_STATUS_WARN)
281 if not obj.is_enabled:
283 obj.save_enabled_state()
284 msg = "Plugin %s enabled" % obj.name
285 return self.root_with_msg(msg, ADMIN_STATUS_OK,
286 changed={obj.name: 'enabled'})
287 enable.public_function = True
290 def disable(self, plugin):
293 obj = self._get_plugin_obj(plugin)
294 except AdminError, e:
295 return self.root_with_msg(str(e), ADMIN_STATUS_WARN)
298 obj.save_enabled_state()
299 msg = "Plugin %s disabled" % obj.name
300 return self.root_with_msg(msg, ADMIN_STATUS_OK,
301 changed={obj.name: 'disabled'})
302 disable.public_function = True
305 class Admin(AdminPage):
307 def __init__(self, site, mount):
308 super(Admin, self).__init__(site)
311 self.url = '%s/%s' % (self.basepath, mount)
314 def root(self, *args, **kwargs):
315 return self._template('admin/index.html',
316 title='Configuration',
320 def add_subtree(self, name, page):
321 self.__dict__[name] = page
322 self.menu.append(page)
324 def del_subtree(self, name):
325 self.menu.remove(self.__dict__[name])
326 del self.__dict__[name]
328 def get_menu_urls(self):
330 for item in self.menu:
331 name = getattr(item, 'name', None)
333 urls['%s_url' % name] = cherrypy.url('/%s/%s' % (self.mount,
340 cherrypy.response.headers.update({'Content-Type': 'image/svg+xml'})
341 urls = self.get_menu_urls()
342 # pylint: disable=star-args
343 return str(self._template('admin/ipsilon-scheme.svg', **urls))
344 scheme.public_function = True
347 def get_complex_list_value(name, old_value, **kwargs):
350 for key, val in kwargs.iteritems():
351 if not key.startswith(name):
354 if len(n) == 0 or n[0] != ' ':
357 index, field = n[1:].split('-')
360 if field == 'delete':
361 delete.append(int(index))
362 elif field == 'name':
363 change[int(index)] = val
365 if len(delete) == 0 and len(change) == 0:
370 # remove unwanted changes
375 # perform requested changes
376 for index, val in change.iteritems():
377 val_list = val.split('/')
380 stripped.append(v.strip())
381 if len(stripped) == 1:
382 stripped = stripped[0]
383 if len(value) <= index:
384 value.extend([None]*(index + 1 - len(value)))
385 value[index] = stripped
387 if len(value[index]) == 0:
390 # the previous loop may add 'None' entries
391 # if any still exists mark them to be deleted
392 for i in xrange(0, len(value)):
396 # remove duplicates and set in reverse order
397 delete = list(set(delete))
398 delete.sort(reverse=True)
409 def get_mapping_list_value(name, old_value, **kwargs):
412 for key, val in kwargs.iteritems():
413 if not key.startswith(name):
416 if len(n) == 0 or n[0] != ' ':
419 index, field = n[1:].split('-')
422 if field == 'delete':
423 delete.append(int(index))
428 change[i][field] = val
430 if len(delete) == 0 and len(change) == 0:
435 # remove unwanted changes
440 # perform requested changes
441 for index, fields in change.iteritems():
442 for k in 'from', 'to':
445 val_list = val.split('/')
448 stripped.append(v.strip())
449 if len(stripped) == 1:
450 stripped = stripped[0]
451 if len(value) <= index:
452 value.extend([None]*(index + 1 - len(value)))
453 if value[index] is None:
454 value[index] = [None, None]
459 value[index][i] = stripped
461 # eliminate incomplete/incorrect entries
462 if value[index] is not None:
463 if ((len(value[index]) != 2 or
464 value[index][0] is None or
465 len(value[index][0]) == 0 or
466 value[index][1] is None or
467 len(value[index][1]) == 0)):
470 # the previous loop may add 'None' entries
471 # if any still exists mark them to be deleted
472 for i in xrange(0, len(value)):
476 # remove duplicates and set in reverse order
477 delete = list(set(delete))
478 delete.sort(reverse=True)