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()
145 def POST(self, *args, **kwargs):
147 if self._site[self.facility].is_readonly:
148 return self.parent.root_with_msg(
149 message="Configuration is marked Read-Only",
150 message_type=ADMIN_STATUS_WARN)
152 message = "Nothing was modified."
153 message_type = "info"
155 cur_enabled = self._site[self.facility].enabled
157 if 'order' in kwargs:
158 order = kwargs['order'].split(',')
164 if val not in cur_enabled:
165 error = "Invalid plugin name: %s" % val
166 raise ValueError(error)
167 new_order.append(val)
168 if len(new_order) < len(cur_enabled):
169 for val in cur_enabled:
170 if val not in new_order:
171 new_order.append(val)
173 self.parent.save_enabled_plugins(new_order)
175 # When all is saved update also live config. The
176 # live config is the ordered list of plugin names.
177 self._site[self.facility].refresh_enabled()
179 message = "New configuration saved."
180 message_type = ADMIN_STATUS_OK
183 self.debug('%s -> %s' % (cur_enabled, new_order))
184 for i in range(0, len(cur_enabled)):
185 if cur_enabled[i] != new_order[i]:
186 changed[cur_enabled[i]] = 'reordered'
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,
201 class AdminPlugins(AdminPage):
202 def __init__(self, name, site, parent, facility, ordered=True):
203 super(AdminPlugins, self).__init__(site)
204 self._master = parent
206 self.title = '%s plugins' % name
207 self.url = '%s/%s' % (parent.url, name)
208 self.facility = facility
209 self.template = 'admin/plugins.html'
211 parent.add_subtree(name, self)
213 for plugin in self._site[facility].available:
214 cherrypy.log.error('Admin info plugin: %s' % plugin)
215 obj = self._site[facility].available[plugin]
216 page = AdminPluginConfig(obj, self._site, self)
217 if hasattr(obj, 'admin'):
218 obj.admin.mount(page)
219 self.add_subtree(plugin, page)
222 self.order = AdminPluginsOrder(self._site, self, facility)
224 def save_enabled_plugins(self, names):
225 self._site[self.facility].save_enabled(names)
227 def root_with_msg(self, message=None, message_type=None, changed=None):
228 plugins = self._site[self.facility]
233 targs = {'title': self.title,
234 'menu': self._master.menu,
236 'message_type': message_type,
237 'available': plugins.available,
238 'enabled': plugins.enabled,
243 targs['order_name'] = '%s_order_form' % self.name
244 targs['order_action'] = self.order.url
246 # pylint: disable=star-args
247 return self._template(self.template, **targs)
249 def root(self, *args, **kwargs):
250 return self.root_with_msg()
252 def _get_plugin_obj(self, plugin):
253 plugins = self._site[self.facility]
254 if plugins.is_readonly:
255 msg = "Configuration is marked Read-Only"
256 raise AdminError(msg)
257 if plugin not in plugins.available:
258 msg = "Unknown plugin %s" % plugin
259 raise AdminError(msg)
260 obj = plugins.available[plugin]
262 msg = "Plugin Configuration is marked Read-Only"
263 raise AdminError(msg)
267 def enable(self, plugin):
270 obj = self._get_plugin_obj(plugin)
271 except AdminError, e:
272 return self.root_with_msg(str(e), ADMIN_STATUS_WARN)
273 if not obj.is_enabled:
275 obj.save_enabled_state()
276 msg = "Plugin %s enabled" % obj.name
277 return self.root_with_msg(msg, ADMIN_STATUS_OK,
278 changed={obj.name: 'enabled'})
279 enable.public_function = True
282 def disable(self, plugin):
285 obj = self._get_plugin_obj(plugin)
286 except AdminError, e:
287 return self.root_with_msg(str(e), ADMIN_STATUS_WARN)
290 obj.save_enabled_state()
291 msg = "Plugin %s disabled" % obj.name
292 return self.root_with_msg(msg, ADMIN_STATUS_OK,
293 changed={obj.name: 'disabled'})
294 disable.public_function = True
297 class Admin(AdminPage):
299 def __init__(self, site, mount):
300 super(Admin, self).__init__(site)
303 self.url = '%s/%s' % (self.basepath, mount)
306 def root(self, *args, **kwargs):
307 return self._template('admin/index.html',
308 title='Configuration',
312 def add_subtree(self, name, page):
313 self.__dict__[name] = page
314 self.menu.append(page)
316 def del_subtree(self, name):
317 self.menu.remove(self.__dict__[name])
318 del self.__dict__[name]
320 def get_menu_urls(self):
322 for item in self.menu:
323 name = getattr(item, 'name', None)
325 urls['%s_url' % name] = cherrypy.url('/%s/%s' % (self.mount,
331 cherrypy.response.headers.update({'Content-Type': 'image/svg+xml'})
332 urls = self.get_menu_urls()
333 # pylint: disable=star-args
334 return self._template('admin/ipsilon-scheme.svg', **urls)
335 scheme.public_function = True