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 if self._site[facility] is None:
224 for plugin in self._site[facility].available:
225 cherrypy.log.error('Admin info plugin: %s' % plugin)
226 obj = self._site[facility].available[plugin]
227 page = AdminPluginConfig(obj, self._site, self)
228 if hasattr(obj, 'admin'):
229 obj.admin.mount(page)
230 self.add_subtree(plugin, page)
233 self.order = AdminPluginsOrder(self._site, self, facility)
235 def save_enabled_plugins(self, names):
236 self._site[self.facility].save_enabled(names)
238 def root_with_msg(self, message=None, message_type=None, changed=None):
239 plugins = self._site[self.facility]
244 targs = {'title': self.title,
245 'menu': self._master.menu,
247 'message_type': message_type,
248 'available': plugins.available,
249 'enabled': plugins.enabled,
254 targs['order_name'] = '%s_order_form' % self.name
255 targs['order_action'] = self.order.url
257 # pylint: disable=star-args
258 return self._template(self.template, **targs)
260 def root(self, *args, **kwargs):
261 return self.root_with_msg()
263 def _get_plugin_obj(self, plugin):
264 plugins = self._site[self.facility]
265 if plugins.is_readonly:
266 msg = "Configuration is marked Read-Only"
267 raise AdminError(msg)
268 if plugin not in plugins.available:
269 msg = "Unknown plugin %s" % plugin
270 raise AdminError(msg)
271 obj = plugins.available[plugin]
273 msg = "Plugin Configuration is marked Read-Only"
274 raise AdminError(msg)
278 def enable(self, plugin):
281 obj = self._get_plugin_obj(plugin)
282 except AdminError, e:
283 return self.root_with_msg(str(e), ADMIN_STATUS_WARN)
284 if not obj.is_enabled:
286 obj.save_enabled_state()
287 msg = "Plugin %s enabled" % obj.name
288 return self.root_with_msg(msg, ADMIN_STATUS_OK,
289 changed={obj.name: 'enabled'})
290 enable.public_function = True
293 def disable(self, plugin):
296 obj = self._get_plugin_obj(plugin)
297 except AdminError, e:
298 return self.root_with_msg(str(e), ADMIN_STATUS_WARN)
301 obj.save_enabled_state()
302 msg = "Plugin %s disabled" % obj.name
303 return self.root_with_msg(msg, ADMIN_STATUS_OK,
304 changed={obj.name: 'disabled'})
305 disable.public_function = True
308 class Admin(AdminPage):
310 def __init__(self, site, mount):
311 super(Admin, self).__init__(site)
314 self.url = '%s/%s' % (self.basepath, mount)
317 def root(self, *args, **kwargs):
318 return self._template('admin/index.html',
319 title='Configuration',
323 def add_subtree(self, name, page):
324 self.__dict__[name] = page
325 self.menu.append(page)
327 def del_subtree(self, name):
328 self.menu.remove(self.__dict__[name])
329 del self.__dict__[name]
331 def get_menu_urls(self):
333 for item in self.menu:
334 name = getattr(item, 'name', None)
336 urls['%s_url' % name] = cherrypy.url('/%s/%s' % (self.mount,
343 cherrypy.response.headers.update({'Content-Type': 'image/svg+xml'})
344 urls = self.get_menu_urls()
345 # pylint: disable=star-args
346 return str(self._template('admin/ipsilon-scheme.svg', **urls))
347 scheme.public_function = True
350 def get_complex_list_value(name, old_value, **kwargs):
353 for key, val in kwargs.iteritems():
354 if not key.startswith(name):
357 if len(n) == 0 or n[0] != ' ':
360 index, field = n[1:].split('-')
363 if field == 'delete':
364 delete.append(int(index))
365 elif field == 'name':
366 change[int(index)] = val
368 if len(delete) == 0 and len(change) == 0:
373 # remove unwanted changes
378 # perform requested changes
379 for index, val in change.iteritems():
380 val_list = val.split('/')
383 stripped.append(v.strip())
384 if len(stripped) == 1:
385 stripped = stripped[0]
386 if len(value) <= index:
387 value.extend([None]*(index + 1 - len(value)))
388 value[index] = stripped
390 if len(value[index]) == 0:
393 # the previous loop may add 'None' entries
394 # if any still exists mark them to be deleted
395 for i in xrange(0, len(value)):
399 # remove duplicates and set in reverse order
400 delete = list(set(delete))
401 delete.sort(reverse=True)
412 def get_mapping_list_value(name, old_value, **kwargs):
415 for key, val in kwargs.iteritems():
416 if not key.startswith(name):
419 if len(n) == 0 or n[0] != ' ':
422 index, field = n[1:].split('-')
425 if field == 'delete':
426 delete.append(int(index))
431 change[i][field] = val
433 if len(delete) == 0 and len(change) == 0:
438 # remove unwanted changes
443 # perform requested changes
444 for index, fields in change.iteritems():
445 for k in 'from', 'to':
448 val_list = val.split('/')
451 stripped.append(v.strip())
452 if len(stripped) == 1:
453 stripped = stripped[0]
454 if len(value) <= index:
455 value.extend([None]*(index + 1 - len(value)))
456 if value[index] is None:
457 value[index] = [None, None]
462 value[index][i] = stripped
464 # eliminate incomplete/incorrect entries
465 if value[index] is not None:
466 if ((len(value[index]) != 2 or
467 value[index][0] is None or
468 len(value[index][0]) == 0 or
469 value[index][1] is None or
470 len(value[index][1]) == 0)):
473 # the previous loop may add 'None' entries
474 # if any still exists mark them to be deleted
475 for i in xrange(0, len(value)):
479 # remove duplicates and set in reverse order
480 delete = list(set(delete))
481 delete.sort(reverse=True)