Merge the login and info plugins configurations
[cascardo/ipsilon.git] / ipsilon / admin / common.py
1 # Copyright (C) 2014  Simo Sorce <simo@redhat.com>
2 #
3 # see file 'COPYING' for use and warranty information
4 #
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.
9 #
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.
14 #
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/>.
17
18 import cherrypy
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
23
24
25 ADMIN_STATUS_OK = "success"
26 ADMIN_STATUS_ERROR = "danger"
27 ADMIN_STATUS_WARN = "warning"
28
29
30 class AdminError(Exception):
31     def __init__(self, message):
32         super(AdminError, self).__init__(message)
33         self.message = message
34
35     def __str__(self):
36         return str(self.message)
37
38
39 class AdminPage(Page):
40
41     def __init__(self, *args, **kwargs):
42         super(AdminPage, self).__init__(*args, **kwargs)
43         self.auth_protect = True
44
45
46 class AdminPluginConfig(AdminPage):
47
48     def __init__(self, po, site, parent):
49         super(AdminPluginConfig, self).__init__(site, form=True)
50         self._po = po
51         self.title = '%s plugin' % po.name
52         self.url = '%s/%s' % (parent.url, po.name)
53         self.facility = parent.facility
54         self.menu = [parent]
55         self.back = parent.url
56
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,
62                                                          self._po.name),
63                               config=self._po.get_config_obj())
64
65     @admin_protect
66     def GET(self, *args, **kwargs):
67         return self.root_with_msg()
68
69     @admin_protect
70     def POST(self, *args, **kwargs):
71
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)
76
77         message = "Nothing was modified."
78         message_type = "info"
79         new_db_values = dict()
80
81         conf = self._po.get_config_obj()
82
83         for name, option in conf.iteritems():
84             if name in kwargs:
85                 value = kwargs[name]
86                 if isinstance(option, pconfig.List):
87                     value = [x.strip() for x in value.split('\n')]
88                 elif isinstance(option, pconfig.Condition):
89                     value = True
90             else:
91                 if isinstance(option, pconfig.Condition):
92                     value = False
93                 elif isinstance(option, pconfig.Choice):
94                     value = list()
95                     for a in option.get_allowed():
96                         aname = '%s_%s' % (name, a)
97                         if aname in kwargs:
98                             value.append(a)
99                 elif type(option) is pconfig.ComplexList:
100                     value = get_complex_list_value(name,
101                                                    option.get_value(),
102                                                    **kwargs)
103                     if value is None:
104                         continue
105                 elif type(option) is pconfig.MappingList:
106                     value = get_mapping_list_value(name,
107                                                    option.get_value(),
108                                                    **kwargs)
109                     if value is None:
110                         continue
111                 else:
112                     continue
113
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()
119
120         if len(new_db_values) != 0:
121             # First we try to save in the database
122             try:
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
130
131             # Then refresh the actual objects
132             self._po.refresh_plugin_config()
133
134         return self.root_with_msg(message=message,
135                                   message_type=message_type)
136
137
138 class AdminPluginsOrder(AdminPage):
139
140     def __init__(self, site, parent, facility):
141         super(AdminPluginsOrder, self).__init__(site, form=True)
142         self.parent = parent
143         self.facility = facility
144         self.url = '%s/order' % parent.url
145         self.menu = [parent]
146
147     @admin_protect
148     def GET(self, *args, **kwargs):
149         return self.parent.root_with_msg()
150
151     @admin_protect
152     def POST(self, *args, **kwargs):
153
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)
158
159         message = "Nothing was modified."
160         message_type = "info"
161         changed = None
162         cur_enabled = self._site[self.facility].enabled
163
164         if 'order' in kwargs:
165             order = kwargs['order'].split(',')
166             if len(order) != 0:
167                 new_order = []
168                 try:
169                     for v in order:
170                         val = v.strip()
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)
179
180                     self.parent.save_enabled_plugins(new_order)
181
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()
185
186                     message = "New configuration saved."
187                     message_type = ADMIN_STATUS_OK
188
189                     changed = dict()
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'
194
195                 except ValueError, e:
196                     message = str(e)
197                     message_type = ADMIN_STATUS_ERROR
198
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
203
204         return self.parent.root_with_msg(message=message,
205                                          message_type=message_type,
206                                          changed=changed)
207
208
209 class AdminPlugins(AdminPage):
210     def __init__(self, name, site, parent, facility, ordered=True):
211         super(AdminPlugins, self).__init__(site)
212         self._master = parent
213         self.name = name
214         self.title = '%s plugins' % name
215         self.url = '%s/%s' % (parent.url, name)
216         self.facility = facility
217         self.template = 'admin/plugins.html'
218         self.order = None
219         parent.add_subtree(name, self)
220
221         if self._site[facility] is None:
222             return
223
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)
231
232         if ordered:
233             self.order = AdminPluginsOrder(self._site, self, facility)
234
235     def save_enabled_plugins(self, names):
236         self._site[self.facility].save_enabled(names)
237
238     def root_with_msg(self, message=None, message_type=None, changed=None):
239         plugins = self._site[self.facility]
240
241         if changed is None:
242             changed = dict()
243
244         targs = {'title': self.title,
245                  'menu': self._master.menu,
246                  'message': message,
247                  'message_type': message_type,
248                  'available': plugins.available,
249                  'enabled': plugins.enabled,
250                  'changed': changed,
251                  'baseurl': self.url,
252                  'newurl': self.url}
253         if self.order:
254             targs['order_name'] = '%s_order_form' % self.name
255             targs['order_action'] = self.order.url
256
257         # pylint: disable=star-args
258         return self._template(self.template, **targs)
259
260     def root(self, *args, **kwargs):
261         return self.root_with_msg()
262
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]
272         if obj.is_readonly:
273             msg = "Plugin Configuration is marked Read-Only"
274             raise AdminError(msg)
275         return obj
276
277     @admin_protect
278     def enable(self, plugin):
279         msg = None
280         try:
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:
285             obj.enable()
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
291
292     @admin_protect
293     def disable(self, plugin):
294         msg = None
295         try:
296             obj = self._get_plugin_obj(plugin)
297         except AdminError, e:
298             return self.root_with_msg(str(e), ADMIN_STATUS_WARN)
299         if obj.is_enabled:
300             obj.disable()
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
306
307
308 class Admin(AdminPage):
309
310     def __init__(self, site, mount):
311         super(Admin, self).__init__(site)
312         self.title = 'Home'
313         self.mount = mount
314         self.url = '%s/%s' % (self.basepath, mount)
315         self.menu = [self]
316
317     def root(self, *args, **kwargs):
318         return self._template('admin/index.html',
319                               title='Configuration',
320                               baseurl=self.url,
321                               menu=self.menu)
322
323     def add_subtree(self, name, page):
324         self.__dict__[name] = page
325         self.menu.append(page)
326
327     def del_subtree(self, name):
328         self.menu.remove(self.__dict__[name])
329         del self.__dict__[name]
330
331     def get_menu_urls(self):
332         urls = dict()
333         for item in self.menu:
334             name = getattr(item, 'name', None)
335             if name:
336                 urls['%s_url' % name] = cherrypy.url('/%s/%s' % (self.mount,
337                                                                  name))
338         return urls
339
340     @admin_protect
341     @allow_iframe
342     def scheme(self):
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
348
349
350 def get_complex_list_value(name, old_value, **kwargs):
351     delete = list()
352     change = dict()
353     for key, val in kwargs.iteritems():
354         if not key.startswith(name):
355             continue
356         n = key[len(name):]
357         if len(n) == 0 or n[0] != ' ':
358             continue
359         try:
360             index, field = n[1:].split('-')
361         except ValueError:
362             continue
363         if field == 'delete':
364             delete.append(int(index))
365         elif field == 'name':
366             change[int(index)] = val
367
368     if len(delete) == 0 and len(change) == 0:
369         return None
370
371     value = old_value
372
373     # remove unwanted changes
374     for i in delete:
375         if i in change:
376             del change[i]
377
378     # perform requested changes
379     for index, val in change.iteritems():
380         val_list = val.split('/')
381         stripped = list()
382         for v in val_list:
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
389
390         if len(value[index]) == 0:
391             value[index] = None
392
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)):
396         if value[i] is None:
397             delete.append(i)
398
399     # remove duplicates and set in reverse order
400     delete = list(set(delete))
401     delete.sort(reverse=True)
402
403     for i in delete:
404         if len(value) > i:
405             del value[i]
406
407     if len(value) == 0:
408         value = None
409     return value
410
411
412 def get_mapping_list_value(name, old_value, **kwargs):
413     delete = list()
414     change = dict()
415     for key, val in kwargs.iteritems():
416         if not key.startswith(name):
417             continue
418         n = key[len(name):]
419         if len(n) == 0 or n[0] != ' ':
420             continue
421         try:
422             index, field = n[1:].split('-')
423         except ValueError:
424             continue
425         if field == 'delete':
426             delete.append(int(index))
427         else:
428             i = int(index)
429             if i not in change:
430                 change[i] = dict()
431             change[i][field] = val
432
433     if len(delete) == 0 and len(change) == 0:
434         return None
435
436     value = old_value
437
438     # remove unwanted changes
439     for i in delete:
440         if i in change:
441             del change[i]
442
443     # perform requested changes
444     for index, fields in change.iteritems():
445         for k in 'from', 'to':
446             if k in fields:
447                 val = fields[k]
448                 val_list = val.split('/')
449                 stripped = list()
450                 for v in val_list:
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]
458                 if k == 'from':
459                     i = 0
460                 else:
461                     i = 1
462                 value[index][i] = stripped
463
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)):
471                 value[index] = None
472
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)):
476         if value[i] is None:
477             delete.append(i)
478
479     # remove duplicates and set in reverse order
480     delete = list(set(delete))
481     delete.sort(reverse=True)
482
483     for i in delete:
484         if len(value) > i:
485             del value[i]
486
487     if len(value) == 0:
488         value = None
489     return value