summaryrefslogtreecommitdiffstats
path: root/ipsilon/util/plugin.py
blob: 1035ca82e71a152d72286e9daf59bc6f426e667d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
# Copyright (C) 2013  Simo Sorce <simo@redhat.com>
#
# see file 'COPYING' for use and warranty information
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import os
import imp
import cherrypy
import inspect
from ipsilon.util.config import Config
from ipsilon.util.data import AdminStore
from ipsilon.util.log import Log


class Plugins(object):

    def __init__(self):
        self._providers_tree = None

    def _load_class(self, tree, class_type, file_name, *pargs):
        cherrypy.log.error('Check module %s for class %s' % (file_name,
                                                             class_type))
        name, ext = os.path.splitext(os.path.split(file_name)[-1])
        try:
            if ext.lower() == '.py':
                mod = imp.load_source(name, file_name)
            # elif ext.lower() == '.pyc':
            #    mod = imp.load_compiled(name, file_name)
            else:
                return
        except Exception, e:  # pylint: disable=broad-except
            cherrypy.log.error('Failed to load "%s" module: [%s]' % (name, e))
            return

        if hasattr(mod, class_type):
            instance = getattr(mod, class_type)(*pargs)
            public_name = getattr(instance, 'name', name)
            tree[public_name] = instance
            cherrypy.log.error('Added module %s as %s' % (name, public_name))

    def _load_classes(self, tree, path, class_type, *pargs):
        files = None
        try:
            files = os.listdir(path)
        except Exception, e:  # pylint: disable=broad-except
            cherrypy.log.error('No modules in %s: [%s]' % (path, e))
            return

        for name in files:
            filename = os.path.join(path, name)
            self._load_class(tree, class_type, filename, *pargs)

    def get_plugins(self, path, class_type, *pargs):
        plugins = dict()
        self._load_classes(plugins, path, class_type, *pargs)
        return plugins


class PluginLoader(Log):

    def __init__(self, baseobj, facility, plugin_type):
        self._pathname, _ = os.path.split(inspect.getfile(baseobj))
        self.facility = facility
        self._plugin_type = plugin_type
        self.available = dict()
        self.enabled = list()
        self.__data = None

    # Defer initialization or instantiating the store will fail at load
    # time when used with Installer plugins as the cherrypy config context
    # is created after all Installer plugins are loaded.
    @property
    def _data(self):
        if not self.__data:
            self.__data = AdminStore()
        return self.__data

    @property
    def is_readonly(self):
        return self._data.is_readonly

    def get_plugins(self):
        p = Plugins()
        return p.get_plugins(self._pathname, self._plugin_type, self)

    def refresh_enabled(self):
        config = self._data.load_options(self.facility, name='global')
        self.enabled = []
        if config:
            if 'enabled' in config:
                self.enabled = config['enabled'].split(',')

    def get_plugin_data(self):
        self.available = self.get_plugins()
        self.refresh_enabled()

    def save_enabled(self, enabled):
        if enabled:
            self._data.save_options(self.facility, 'global',
                                    {'enabled': ','.join(enabled)})
        else:
            self._data.delete_options(self.facility, 'global',
                                      {'enabled': '*'})
        self.debug('Plugin enabled state saved: %s' % enabled)
        self.refresh_enabled()


class PluginInstaller(PluginLoader):
    def __init__(self, baseobj, facility):
        super(PluginInstaller, self).__init__(baseobj, facility, 'Installer')


class PluginObject(Log):

    def __init__(self, plugins):
        self.name = None
        self._config = None
        self._data = AdminStore()
        self._plugins = plugins
        self.is_enabled = False

    @property
    def is_readonly(self):
        return self._data.is_readonly

    def on_enable(self):
        return

    def on_disable(self):
        return

    def save_enabled_state(self):
        enabled = []
        self._plugins.refresh_enabled()
        enabled.extend(self._plugins.enabled)
        if self.is_enabled:
            if self.name not in enabled:
                enabled.append(self.name)
        else:
            if self.name in enabled:
                enabled.remove(self.name)
        self._plugins.save_enabled(enabled)

    def enable(self):
        if self.is_enabled:
            return

        self.refresh_plugin_config()
        self.on_enable()
        self.is_enabled = True
        self.debug('Plugin enabled: %s' % self.name)

    def disable(self):
        if not self.is_enabled:
            return

        self.on_disable()

        self.is_enabled = False
        self.debug('Plugin disabled: %s' % self.name)

    def import_config(self, config):
        self._config = config

    def export_config(self):
        return self._config

    def get_plugin_config(self):
        return self._data.load_options(self._plugins.facility, self.name)

    def refresh_plugin_config(self):
        config = self.get_plugin_config()
        if config:
            try:
                self.import_config(config)
            except Exception, e:  # pylint: disable=broad-except
                self.error('Failed to refresh config for %s (%s)' %
                           (self.name, e))

    def save_plugin_config(self, config=None):
        if config is None:
            config = self.export_config()

        self._data.save_options(self._plugins.facility, self.name, config)

    def get_data(self, idval=None, name=None, value=None):
        return self._data.get_data(self.name, idval=idval, name=name,
                                   value=value)

    def save_data(self, data):
        self._data.save_data(self.name, data)

    def new_datum(self, datum):
        self._data.new_datum(self.name, datum)

    def del_datum(self, idval):
        self._data.del_datum(self.name, idval)

    def wipe_config_values(self):
        self._data.delete_options(self._plugins.facility, self.name, None)

    def wipe_data(self):
        self._data.wipe_data(self.name)


class PluginConfig(Log):

    def __init__(self):
        self._config = None

    def new_config(self, name, *config_args):
        self._config = Config(name, *config_args)

    def get_config_obj(self):
        if self._config is None:
            raise AttributeError('Config not initialized')
        return self._config

    def import_config(self, config):
        if not self._config:
            raise AttributeError('Config not initialized, cannot import')

        for key, value in config.iteritems():
            if key in self._config:
                self._config[key].import_value(str(value))

    def export_config(self):
        config = dict()
        for name, option in self._config.iteritems():
            config[name] = option.export_value()
        return config

    def get_config_value(self, name):
        if not self._config:
            raise AttributeError('Config not initialized')
        return self._config[name].get_value()

    def set_config_value(self, name, value):
        if not self._config:
            raise AttributeError('Config not initialized')
        return self._config[name].set_value(value)