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.plugin import PluginObject
24 from ipsilon.util import config as pconfig
27 class AdminPage(Page):
29 def __init__(self, *args, **kwargs):
30 super(AdminPage, self).__init__(*args, **kwargs)
31 self.default_headers.update({
32 'Cache-Control': 'no-cache, must-revalidate',
34 'Expires': 'Thu, 01 Dec 1994 16:00:00 GMT',
36 self.auth_protect = True
39 class AdminPluginConfig(AdminPage):
41 def __init__(self, po, site, parent):
42 super(AdminPluginConfig, self).__init__(site, form=True)
44 self.title = '%s plugin' % po.name
45 self.url = '%s/%s' % (parent.url, po.name)
46 self.facility = parent.facility
48 self.back = parent.url
50 def root_with_msg(self, message=None, message_type=None):
51 return self._template('admin/plugin_config.html', title=self.title,
52 menu=self.menu, action=self.url, back=self.back,
53 message=message, message_type=message_type,
54 name='admin_%s_%s_form' % (self.facility,
56 config=self._po.get_config_obj())
59 def GET(self, *args, **kwargs):
60 return self.root_with_msg()
63 def POST(self, *args, **kwargs):
65 message = "Nothing was modified."
67 new_db_values = dict()
69 conf = self._po.get_config_obj()
71 for name, option in conf.iteritems():
74 if isinstance(option, pconfig.List):
75 value = [x.strip() for x in value.split('\n')]
76 elif isinstance(option, pconfig.Condition):
79 if isinstance(option, pconfig.Condition):
81 elif isinstance(option, pconfig.Choice):
83 for a in option.get_allowed():
84 aname = '%s_%s' % (name, a)
90 if value != option.get_value():
91 cherrypy.log.error("Storing [%s]: %s = %s" %
92 (self._po.name, name, value))
93 option.set_value(value)
94 new_db_values[name] = option.export_value()
96 if len(new_db_values) != 0:
97 # First we try to save in the database
99 self._po.save_plugin_config(self.facility, new_db_values)
100 message = "New configuration saved."
101 message_type = "success"
102 except Exception: # pylint: disable=broad-except
103 message = "Failed to save data!"
104 message_type = "error"
106 # Then refresh the actual objects
107 self._po.refresh_plugin_config(self.facility)
109 return self.root_with_msg(message=message,
110 message_type=message_type)
113 class AdminPluginsOrder(AdminPage):
115 def __init__(self, site, parent, facility):
116 super(AdminPluginsOrder, self).__init__(site, form=True)
118 self.facility = facility
119 self.url = '%s/order' % parent.url
123 def GET(self, *args, **kwargs):
124 return self.parent.root_with_msg()
126 def _get_enabled_by_name(self):
128 for p in self._site[self.facility]['available'].values():
134 def POST(self, *args, **kwargs):
135 message = "Nothing was modified."
136 message_type = "info"
137 by_name = self._get_enabled_by_name()
139 if 'order' in kwargs:
140 order = kwargs['order'].split(',')
147 if val not in by_name:
148 error = "Invalid plugin name: %s" % val
149 raise ValueError(error)
150 new_names.append(val)
151 new_plugins.append(by_name[val])
152 if len(new_names) < len(by_name):
154 if val not in new_names:
155 new_names.append(val)
156 new_plugins.append(by_name[val])
158 self.parent.save_enabled_plugins(new_names)
159 self.parent.reorder_plugins(new_names)
161 # When all is saved update also live config. The
162 # live config is a list of the actual plugin
164 self._site[self.facility]['enabled'] = new_plugins
166 message = "New configuration saved."
167 message_type = "success"
169 except ValueError, e:
171 message_type = "error"
173 except Exception, e: # pylint: disable=broad-except
174 message = "Failed to save data!"
175 message_type = "error"
177 return self.parent.root_with_msg(message=message,
178 message_type=message_type)
181 class AdminPlugins(AdminPage):
182 def __init__(self, name, site, parent, facility, ordered=True):
183 super(AdminPlugins, self).__init__(site)
184 self._master = parent
186 self.title = '%s plugins' % name
187 self.url = '%s/%s' % (parent.url, name)
188 self.facility = facility
189 self.template = 'admin/plugins.html'
191 parent.add_subtree(name, self)
193 for plugin in self._site[facility]['available']:
194 cherrypy.log.error('Admin info plugin: %s' % plugin)
195 obj = self._site[facility]['available'][plugin]
196 page = AdminPluginConfig(obj, self._site, self)
197 if hasattr(obj, 'admin'):
198 obj.admin.mount(page)
199 self.add_subtree(plugin, page)
202 self.order = AdminPluginsOrder(self._site, self, facility)
204 def save_enabled_plugins(self, names):
208 globalconf['order'] = ','.join(names)
209 po.import_config(globalconf)
210 po.save_plugin_config(self.facility)
212 def reorder_plugins(self, names):
215 def root_with_msg(self, message=None, message_type=None):
216 plugins = self._site[self.facility]
219 for plugin in plugins['enabled']:
220 if plugin.is_enabled:
221 enabled.append(plugin.name)
223 for _, plugin in plugins['available'].iteritems():
224 if plugin.is_enabled:
225 enabled.append(plugin.name)
227 targs = {'title': self.title,
228 'menu': self._master.menu,
230 'message_type': message_type,
231 'available': plugins['available'],
235 targs['order_name'] = '%s_order_form' % self.name
236 targs['order_action'] = self.order.url
238 # pylint: disable=star-args
239 return self._template(self.template, **targs)
241 def root(self, *args, **kwargs):
242 return self.root_with_msg()
245 def enable(self, plugin):
247 plugins = self._site[self.facility]
248 if plugin not in plugins['available']:
249 msg = "Unknown plugin %s" % plugin
250 return self.root_with_msg(msg, "error")
251 obj = plugins['available'][plugin]
252 if not obj.is_enabled:
253 obj.enable(self._site)
255 enabled = list(x.name for x in plugins['enabled'])
256 self.save_enabled_plugins(enabled)
257 msg = "Plugin %s enabled" % obj.name
258 return self.root_with_msg(msg, "success")
259 enable.public_function = True
262 def disable(self, plugin):
264 plugins = self._site[self.facility]
265 if plugin not in plugins['available']:
266 msg = "Unknown plugin %s" % plugin
267 return self.root_with_msg(msg, "error")
268 obj = plugins['available'][plugin]
270 obj.disable(self._site)
272 enabled = list(x.name for x in plugins['enabled'])
273 self.save_enabled_plugins(enabled)
274 msg = "Plugin %s disabled" % obj.name
275 return self.root_with_msg(msg, "success")
276 disable.public_function = True
279 class Admin(AdminPage):
281 def __init__(self, site, mount):
282 super(Admin, self).__init__(site)
285 self.url = '%s/%s' % (self.basepath, mount)
288 def root(self, *args, **kwargs):
289 return self._template('admin/index.html',
290 title='Configuration',
294 def add_subtree(self, name, page):
295 self.__dict__[name] = page
296 self.menu.append(page)
298 def del_subtree(self, name):
299 self.menu.remove(self.__dict__[name])
300 del self.__dict__[name]
302 def get_menu_urls(self):
304 for item in self.menu:
305 name = getattr(item, 'name', None)
307 urls['%s_url' % name] = cherrypy.url('/%s/%s' % (self.mount,
313 cherrypy.response.headers.update({'Content-Type': 'image/svg+xml'})
314 urls = self.get_menu_urls()
315 # pylint: disable=star-args
316 return self._template('admin/ipsilon-scheme.svg', **urls)
317 scheme.public_function = True