]> kaliko git repositories - mpd-sima.git/blob - sima/launch.py
Add a PluginConfException
[mpd-sima.git] / sima / launch.py
1 # -*- coding: utf-8 -*-
2 # Copyright (c) 2013, 2014, 2015 kaliko <kaliko@azylum.org>
3 #
4 #  This file is part of sima
5 #
6 #  sima is free software: you can redistribute it and/or modify
7 #  it under the terms of the GNU General Public License as published by
8 #  the Free Software Foundation, either version 3 of the License, or
9 #  (at your option) any later version.
10 #
11 #  sima is distributed in the hope that it will be useful,
12 #  but WITHOUT ANY WARRANTY; without even the implied warranty of
13 #  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 #  GNU General Public License for more details.
15 #
16 #  You should have received a copy of the GNU General Public License
17 #  along with sima.  If not, see <http://www.gnu.org/licenses/>.
18 #
19 #
20 """Sima
21 """
22
23 # standard library import
24 import logging
25 import sys
26
27 from importlib import __import__ as sima_import
28 from os.path import isfile
29 ##
30
31 # third parties components
32 ##
33
34 # local import
35 from . import core, info
36 from .lib.logger import set_logger
37 from .lib.simadb import SimaDB
38 from .utils.config import ConfMan
39 from .utils.startopt import StartOpt
40 from .utils.utils import exception_log, SigHup, PluginConfException
41 # core plugins
42 from .plugins.core.history import History
43 from .plugins.core.mpdoptions import MpdOptions
44 from .plugins.core.uniq import Uniq
45 ##
46
47
48 def load_plugins(sima, source):
49     """Handles internal/external plugins
50         sima:   sima.core.Sima instance
51         source: ['internal', 'contrib']
52     """
53     if not sima.config.get('sima', source):
54         return
55     logger = logging.getLogger('sima')
56     # TODO: Sanity check for "sima.config.get('sima', source)" ?
57     for plugin in sima.config.get('sima', source).split(','):
58         plugin = plugin.strip(' \n')
59         module = 'sima.plugins.{0}.{1}'.format(source, plugin.lower())
60         try:
61             mod_obj = sima_import(module, fromlist=[plugin])
62         except ImportError as err:
63             logger.error('Failed to load "{}" plugin\'s module: '.format(plugin) +
64                          '{0} ({1})'.format(module, err))
65             sima.shutdown()
66             sys.exit(1)
67         try:
68             plugin_obj = getattr(mod_obj, plugin)
69         except AttributeError as err:
70             logger.error('Failed to load plugin %s (%s)', plugin, err)
71             sima.shutdown()
72             sys.exit(1)
73         logger.info('Loading {0} plugin: {name} ({doc})'.format(
74             source, **plugin_obj.info()))
75         try:
76             sima.register_plugin(plugin_obj)
77         except PluginConfException as err:
78             logger.error(err)
79             sys.exit(2)
80
81
82 def start(sopt, restart=False):
83     """starts application
84     """
85     # loads configuration
86     config = ConfMan(sopt.options).config
87     # set logger
88     logger = logging.getLogger('sima')
89     logfile = config.get('log', 'logfile', fallback=None)
90     verbosity = config.get('log', 'verbosity')
91     set_logger(verbosity, logfile)
92     logger.debug('Command line say: %s', sopt.options)
93     # Create Database
94     db_file = config.get('sima', 'db_file')
95     if (sopt.options.get('create_db', None)
96             or not isfile(db_file)):
97         logger.info('Creating database in "%s"', db_file)
98         open(db_file, 'a').close()
99         SimaDB(db_path=db_file).create_db()
100         if sopt.options.get('create_db', None):
101             logger.info('Done, bye...')
102             sys.exit(0)
103
104     if sopt.options.get('generate_config'):
105         config.write(sys.stdout, space_around_delimiters=True)
106         sys.exit(0)
107
108     logger.info('Starting (%s)...', info.__version__)
109     sima = core.Sima(config)
110
111     # required core plugins
112     core_plugins = [History, MpdOptions, Uniq]
113     if config.getboolean('sima', 'mopidy_compat'):
114         logger.warning('Running with mopidy compat. mode!')
115         core_plugins = [History, MpdOptions]
116         config['sima']['musicbrainzid'] = 'False'
117     for cplgn in core_plugins:
118         logger.debug('Register core %(name)s (%(doc)s)', cplgn.info())
119         sima.register_core_plugin(cplgn)
120     logger.debug('core loaded, prioriy: %s', ' > '.join(map(str, sima.core_plugins)))
121
122     #  Loading internal plugins
123     load_plugins(sima, 'internal')
124     #  Loading contrib plugins
125     load_plugins(sima, 'contrib')
126     logger.info('plugins loaded, prioriy: %s', ' > '.join(map(str, sima.plugins)))
127
128     # Run as a daemon
129     if config.getboolean('daemon', 'daemon'):
130         if restart:
131             sima.run()
132         else:
133             logger.info('Daemonize process...')
134             sima.start()
135
136     try:
137         sima.foreground()
138     except KeyboardInterrupt:
139         logger.info('Caught KeyboardInterrupt, stopping')
140         sys.exit(0)
141
142
143 def run(sopt, restart=False):
144     """
145     Handles SigHup exception
146     Catches Unhandled exception
147     """
148     # pylint: disable=broad-except
149     try:
150         start(sopt, restart)
151     except SigHup:  # SigHup inherit from Exception
152         run(sopt, True)
153     except Exception:  # Unhandled exception
154         exception_log()
155
156 # Script starts here
157 def main():
158     """Entry point"""
159     nfo = dict({'version': info.__version__,
160                 'prog': 'sima'})
161     # StartOpt gathers options from command line call (in StartOpt().options)
162     sopt = StartOpt(nfo)
163     run(sopt)
164
165
166 if __name__ == '__main__':
167     main()
168
169 # VIM MODLINE
170 # vim: ai ts=4 sw=4 sts=4 expandtab