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/>.
20 from ipsilon.util.page import Page
21 from ipsilon.util.page import admin_protect
22 from ipsilon.util.endpoint import allow_iframe
23 from ipsilon.util import config as pconfig
26 ADMIN_STATUS_OK = "success"
27 ADMIN_STATUS_ERROR = "danger"
28 ADMIN_STATUS_WARN = "warning"
31 class AdminError(Exception):
32 def __init__(self, message):
33 super(AdminError, self).__init__(message)
34 self.message = message
37 return str(self.message)
40 class AdminPage(Page):
42 def __init__(self, *args, **kwargs):
43 super(AdminPage, self).__init__(*args, **kwargs)
44 self.auth_protect = True
47 class AdminPluginConfig(AdminPage):
49 def __init__(self, po, site, parent):
50 super(AdminPluginConfig, self).__init__(site, form=True)
52 self.title = '%s plugin' % po.name
53 self.url = '%s/%s' % (parent.url, po.name)
54 self.facility = parent.facility
56 self.back = parent.url
58 def root_with_msg(self, message=None, message_type=None):
59 return self._template('admin/option_config.html', title=self.title,
60 menu=self.menu, action=self.url, back=self.back,
61 message=message, message_type=message_type,
62 name='admin_%s_%s_form' % (self.facility,
64 config=self._po.get_config_obj())
67 def GET(self, *args, **kwargs):
68 return self.root_with_msg()
71 def POST(self, *args, **kwargs):
73 if self._po.is_readonly:
74 return self.root_with_msg(
75 message="Configuration is marked Read-Only",
76 message_type=ADMIN_STATUS_WARN)
78 message = "Nothing was modified."
80 new_db_values = dict()
82 conf = self._po.get_config_obj()
84 for name, option in conf.iteritems():
87 if isinstance(option, pconfig.List):
88 value = [x.strip() for x in value.split('\n')]
89 elif isinstance(option, pconfig.Condition):
92 if isinstance(option, pconfig.Condition):
94 elif isinstance(option, pconfig.Choice):
96 for a in option.get_allowed():
97 aname = '%s_%s' % (name, a)
100 elif isinstance(option, pconfig.MappingList):
101 value = get_mapping_list_value(name,
106 elif isinstance(option, pconfig.ComplexList):
107 value = get_complex_list_value(name,
115 if value != option.get_value():
116 cherrypy.log.error("Storing [%s]: %s = %s" %
117 (self._po.name, name, value),
118 severity=logging.DEBUG)
119 option.set_value(value)
120 new_db_values[name] = option.export_value()
122 if len(new_db_values) != 0:
123 # First we try to save in the database
125 self._po.save_plugin_config(new_db_values)
126 message = "New configuration saved."
127 message_type = ADMIN_STATUS_OK
128 except Exception as e: # pylint: disable=broad-except
129 self.error('Failed to save data: %s' % e)
130 message = "Failed to save data!"
131 message_type = ADMIN_STATUS_ERROR
133 # Then refresh the actual objects
134 self._po.refresh_plugin_config()
136 return self.root_with_msg(message=message,
137 message_type=message_type)
140 class AdminPluginsOrder(AdminPage):
142 def __init__(self, site, parent, facility):
143 super(AdminPluginsOrder, self).__init__(site, form=True)
145 self.facility = facility
146 self.url = '%s/order' % parent.url
150 def GET(self, *args, **kwargs):
151 return self.parent.root_with_msg()
154 def POST(self, *args, **kwargs):
156 if self._site[self.facility].is_readonly:
157 return self.parent.root_with_msg(
158 message="Configuration is marked Read-Only",
159 message_type=ADMIN_STATUS_WARN)
161 message = "Nothing was modified."
162 message_type = "info"
164 cur_enabled = self._site[self.facility].enabled
166 if 'order' in kwargs:
167 order = kwargs['order'].split(',')
173 if val not in cur_enabled:
174 error = "Invalid plugin name: %s" % val
175 raise ValueError(error)
176 new_order.append(val)
177 if len(new_order) < len(cur_enabled):
178 for val in cur_enabled:
179 if val not in new_order:
180 new_order.append(val)
182 self.parent.save_enabled_plugins(new_order)
184 # When all is saved update also live config. The
185 # live config is the ordered list of plugin names.
186 self._site[self.facility].refresh_enabled()
188 message = "New configuration saved."
189 message_type = ADMIN_STATUS_OK
192 self.debug('%s -> %s' % (cur_enabled, new_order))
193 for i in range(0, len(cur_enabled)):
194 if cur_enabled[i] != new_order[i]:
195 changed[cur_enabled[i]] = 'reordered'
197 except ValueError, e:
199 message_type = ADMIN_STATUS_ERROR
201 except Exception as e: # pylint: disable=broad-except
202 self.error('Failed to save data: %s' % e)
203 message = "Failed to save data!"
204 message_type = ADMIN_STATUS_ERROR
206 return self.parent.root_with_msg(message=message,
207 message_type=message_type,
211 class AdminPlugins(AdminPage):
212 def __init__(self, name, site, parent, facility, ordered=True):
213 super(AdminPlugins, self).__init__(site)
214 self._master = parent
216 self.title = '%s plugins' % name
217 self.url = '%s/%s' % (parent.url, name)
218 self.facility = facility
219 self.template = 'admin/plugins.html'
221 parent.add_subtree(name, self)
223 if self._site[facility] is None:
226 for plugin in self._site[facility].available:
227 cherrypy.log.error('Admin info plugin: %s' % plugin,
228 severity=logging.DEBUG)
229 obj = self._site[facility].available[plugin]
230 page = AdminPluginConfig(obj, self._site, self)
231 if hasattr(obj, 'admin'):
232 obj.admin.mount(page)
233 self.add_subtree(plugin, page)
236 self.order = AdminPluginsOrder(self._site, self, facility)
238 def save_enabled_plugins(self, names):
239 self._site[self.facility].save_enabled(names)
241 def root_with_msg(self, message=None, message_type=None, changed=None):
242 plugins = self._site[self.facility]
247 targs = {'title': self.title,
248 'menu': self._master.menu,
250 'message_type': message_type,
251 'available': plugins.available,
252 'enabled': plugins.enabled,
257 targs['order_name'] = '%s_order_form' % self.name
258 targs['order_action'] = self.order.url
260 return self._template(self.template, **targs)
262 def root(self, *args, **kwargs):
263 return self.root_with_msg()
265 def _get_plugin_obj(self, plugin):
266 plugins = self._site[self.facility]
267 if plugins.is_readonly:
268 msg = "Configuration is marked Read-Only"
269 raise AdminError(msg)
270 if plugin not in plugins.available:
271 msg = "Unknown plugin %s" % plugin
272 raise AdminError(msg)
273 obj = plugins.available[plugin]
275 msg = "Plugin Configuration is marked Read-Only"
276 raise AdminError(msg)
280 def enable(self, plugin):
283 obj = self._get_plugin_obj(plugin)
284 except AdminError, e:
285 return self.root_with_msg(str(e), ADMIN_STATUS_WARN)
286 if not obj.is_enabled:
289 except Exception as e: # pylint: disable=broad-except
290 return self.root_with_msg(str(e), ADMIN_STATUS_WARN)
291 obj.save_enabled_state()
292 msg = "Plugin %s enabled" % obj.name
293 return self.root_with_msg(msg, ADMIN_STATUS_OK,
294 changed={obj.name: 'enabled'})
295 enable.public_function = True
298 def disable(self, plugin):
301 obj = self._get_plugin_obj(plugin)
302 except AdminError, e:
303 return self.root_with_msg(str(e), ADMIN_STATUS_WARN)
307 except Exception as e: # pylint: disable=broad-except
308 return self.root_with_msg(str(e), ADMIN_STATUS_WARN)
309 obj.save_enabled_state()
310 msg = "Plugin %s disabled" % obj.name
311 return self.root_with_msg(msg, ADMIN_STATUS_OK,
312 changed={obj.name: 'disabled'})
313 disable.public_function = True
316 class Admin(AdminPage):
318 def __init__(self, site, mount):
319 super(Admin, self).__init__(site)
322 self.url = '%s/%s' % (self.basepath, mount)
325 def root(self, *args, **kwargs):
326 return self._template('admin/index.html',
327 title='Configuration',
331 def add_subtree(self, name, page):
332 self.__dict__[name] = page
333 self.menu.append(page)
335 def del_subtree(self, name):
336 self.menu.remove(self.__dict__[name])
337 del self.__dict__[name]
339 def get_menu_urls(self):
341 for item in self.menu:
342 name = getattr(item, 'name', None)
344 urls['%s_url' % name] = cherrypy.url('/%s/%s' % (self.mount,
351 cherrypy.response.headers.update({'Content-Type': 'image/svg+xml'})
352 urls = self.get_menu_urls()
353 return str(self._template('admin/ipsilon-scheme.svg', **urls))
354 scheme.public_function = True
357 def get_complex_list_value(name, old_value, **kwargs):
360 for key, val in kwargs.iteritems():
361 if not key.startswith(name):
364 if len(n) == 0 or n[0] != ' ':
367 index, field = n[1:].split('-')
370 if field == 'delete':
371 delete.append(int(index))
372 elif field == 'name':
373 change[int(index)] = val
375 if len(delete) == 0 and len(change) == 0:
380 # remove unwanted changes
385 # perform requested changes
386 for index, val in change.iteritems():
387 val_list = val.split('/')
390 stripped.append(v.strip())
391 if len(stripped) == 1:
392 stripped = stripped[0]
393 if len(value) <= index:
394 value.extend([None]*(index + 1 - len(value)))
395 value[index] = stripped
397 if len(value[index]) == 0:
400 # the previous loop may add 'None' entries
401 # if any still exists mark them to be deleted
402 for i in xrange(0, len(value)):
406 # remove duplicates and set in reverse order
407 delete = list(set(delete))
408 delete.sort(reverse=True)
419 def get_mapping_list_value(name, old_value, **kwargs):
422 for key, val in kwargs.iteritems():
423 if not key.startswith(name):
426 if len(n) == 0 or n[0] != ' ':
429 index, field = n[1:].split('-')
432 if field == 'delete':
433 delete.append(int(index))
438 change[i][field] = val
440 if len(delete) == 0 and len(change) == 0:
445 # remove unwanted changes
450 # perform requested changes
451 for index, fields in change.iteritems():
452 for k in 'from', 'to':
455 val_list = val.split('/')
458 stripped.append(v.strip())
459 if len(stripped) == 1:
460 stripped = stripped[0]
461 if len(value) <= index:
462 value.extend([None]*(index + 1 - len(value)))
463 if value[index] is None:
464 value[index] = [None, None]
469 value[index][i] = stripped
471 # eliminate incomplete/incorrect entries
472 if value[index] is not None:
473 if ((len(value[index]) != 2 or
474 value[index][0] is None or
475 len(value[index][0]) == 0 or
476 value[index][1] is None or
477 len(value[index][1]) == 0)):
480 # the previous loop may add 'None' entries
481 # if any still exists mark them to be deleted
482 for i in xrange(0, len(value)):
486 # remove duplicates and set in reverse order
487 delete = list(set(delete))
488 delete.sort(reverse=True)