3 # Copyright (C) 2014 Simo Sorce <simo@redhat.com>
5 # see file 'COPYING' for use and warranty information
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.
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.
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/>.
21 from ipsilon.util.page import Page
22 from ipsilon.util.page import admin_protect
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.default_headers.update({
45 'Cache-Control': 'no-cache, must-revalidate',
47 'Expires': 'Thu, 01 Dec 1994 16:00:00 GMT',
49 self.auth_protect = True
52 class AdminPluginConfig(AdminPage):
54 def __init__(self, po, site, parent):
55 super(AdminPluginConfig, self).__init__(site, form=True)
57 self.title = '%s plugin' % po.name
58 self.url = '%s/%s' % (parent.url, po.name)
59 self.facility = parent.facility
61 self.back = parent.url
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,
69 config=self._po.get_config_obj())
72 def GET(self, *args, **kwargs):
73 return self.root_with_msg()
76 def POST(self, *args, **kwargs):
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)
83 message = "Nothing was modified."
85 new_db_values = dict()
87 conf = self._po.get_config_obj()
89 for name, option in conf.iteritems():
92 if isinstance(option, pconfig.List):
93 value = [x.strip() for x in value.split('\n')]
94 elif isinstance(option, pconfig.Condition):
97 if isinstance(option, pconfig.Condition):
99 elif isinstance(option, pconfig.Choice):
101 for a in option.get_allowed():
102 aname = '%s_%s' % (name, a)
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()
114 if len(new_db_values) != 0:
115 # First we try to save in the database
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
124 # Then refresh the actual objects
125 self._po.refresh_plugin_config()
127 return self.root_with_msg(message=message,
128 message_type=message_type)
131 class AdminPluginsOrder(AdminPage):
133 def __init__(self, site, parent, facility):
134 super(AdminPluginsOrder, self).__init__(site, form=True)
136 self.facility = facility
137 self.url = '%s/order' % parent.url
141 def GET(self, *args, **kwargs):
142 return self.parent.root_with_msg()
144 def _get_enabled_list(self):
146 for p in self._site[self.facility].available.values():
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"
161 cur_enabled = self._get_enabled_list()
163 if 'order' in kwargs:
164 order = kwargs['order'].split(',')
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)
179 self.parent.save_enabled_plugins(new_order)
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()
185 message = "New configuration saved."
186 message_type = ADMIN_STATUS_OK
188 except ValueError, e:
190 message_type = ADMIN_STATUS_ERROR
192 except Exception, e: # pylint: disable=broad-except
193 message = "Failed to save data!"
194 message_type = ADMIN_STATUS_ERROR
196 return self.parent.root_with_msg(message=message,
197 message_type=message_type)
200 class AdminPlugins(AdminPage):
201 def __init__(self, name, site, parent, facility, ordered=True):
202 super(AdminPlugins, self).__init__(site)
203 self._master = parent
205 self.title = '%s plugins' % name
206 self.url = '%s/%s' % (parent.url, name)
207 self.facility = facility
208 self.template = 'admin/plugins.html'
210 parent.add_subtree(name, self)
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)
221 self.order = AdminPluginsOrder(self._site, self, facility)
223 def save_enabled_plugins(self, names):
224 self._site[self.facility].save_enabled(names)
226 def root_with_msg(self, message=None, message_type=None):
227 plugins = self._site[self.facility]
229 targs = {'title': self.title,
230 'menu': self._master.menu,
232 'message_type': message_type,
233 'available': plugins.available,
234 'enabled': plugins.enabled,
238 targs['order_name'] = '%s_order_form' % self.name
239 targs['order_action'] = self.order.url
241 # pylint: disable=star-args
242 return self._template(self.template, **targs)
244 def root(self, *args, **kwargs):
245 return self.root_with_msg()
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]
257 msg = "Plugin Configuration is marked Read-Only"
258 raise AdminError(msg)
262 def enable(self, plugin):
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:
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
276 def disable(self, plugin):
279 obj = self._get_plugin_obj(plugin)
280 except AdminError, e:
281 return self.root_with_msg(str(e), ADMIN_STATUS_WARN)
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
290 class Admin(AdminPage):
292 def __init__(self, site, mount):
293 super(Admin, self).__init__(site)
296 self.url = '%s/%s' % (self.basepath, mount)
299 def root(self, *args, **kwargs):
300 return self._template('admin/index.html',
301 title='Configuration',
305 def add_subtree(self, name, page):
306 self.__dict__[name] = page
307 self.menu.append(page)
309 def del_subtree(self, name):
310 self.menu.remove(self.__dict__[name])
311 del self.__dict__[name]
313 def get_menu_urls(self):
315 for item in self.menu:
316 name = getattr(item, 'name', None)
318 urls['%s_url' % name] = cherrypy.url('/%s/%s' % (self.mount,
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