]> kaliko git repositories - mpd-sima.git/blob - launch
Allow choosing internal plugins from config file
[mpd-sima.git] / launch
1 #!/usr/bin/env python3
2 # -*- coding: utf-8 -*-
3 """Sima
4 """
5
6 # standart library import
7 import logging
8 import sys
9
10 from importlib import __import__
11 from os.path import isfile
12 ##
13
14 # third parties components
15 ##
16
17 # local import
18 from sima import core
19 from sima.lib.logger import set_logger
20 from sima.lib.simadb import SimaDB
21 from sima.utils.config import ConfMan
22 from sima.utils.startopt import StartOpt
23 from sima.utils.utils import exception_log
24 ##
25
26
27 def load_plugins(sima, source):
28     """Handles internal/external plugins
29         sima:   sima.core.Sima instance
30         source: ['internal', 'contrib']
31     """
32     if not sima.config.get('sima', source ):
33         return
34     logger = logging.getLogger('sima')
35     for plugin in sima.config.get('sima', source).split(','):
36         plugin = plugin.strip(' \n')
37         module = 'sima.plugins.{0}.{1}'.format(source, plugin.lower())
38         try:
39             mod_obj = __import__(module, fromlist=[plugin])
40         except ImportError as err:
41             logger.error('Failed to load plugin\'s module: {0} ({1})'.format(module, err))
42             sima.shutdown()
43         try:
44             plugin_obj = getattr(mod_obj, plugin)
45         except AttributeError as err:
46             logger.error('Failed to load plugin {0} ({1})'.format(plugin, err))
47             sima.shutdown()
48         logger.info('Loading {0} plugin: {name} ({doc})'.format(source, **plugin_obj.info()))
49         sima.register_plugin(plugin_obj)
50
51
52 def main():
53     """Entry point, deal w/ CLI and starts application
54     """
55     info = dict({'version': core.__version__,
56                  'prog': 'sima'})
57     # StartOpt gathers options from command line call (in StartOpt().options)
58     sopt = StartOpt(info)
59     # set logger
60     verbosity = sopt.options.get('verbosity', 'warning')
61     logfile = sopt.options.get('logfile', None)
62     cli_loglevel = getattr(logging, verbosity.upper())
63     set_logger(level=verbosity, logfile=logfile)
64     logger = logging.getLogger('sima')
65     logger.setLevel(cli_loglevel)
66     # loads configuration
67     config = ConfMan(logger, sopt.options).config
68     logger.setLevel(getattr(logging,
69                     config.get('log', 'verbosity').upper()))  # pylint: disable=E1103
70
71     logger.debug('Command line say: {0}'.format(sopt.options))
72     # Create Database
73     db_file = config.get('sima', 'db_file')
74     if (sopt.options.get('create_db', None)
75        or not isfile(db_file)):
76         logger.info('Creating database in "{}"'.format(db_file))
77         open(db_file, 'a').close()
78         SimaDB(db_path=db_file).create_db()
79         if sopt.options.get('create_db', None):
80             logger.info('Done, bye...')
81             sys.exit(0)
82
83     logger.info('Starting...')
84     sima = core.Sima(config)
85
86     #  Loading internal plugins
87     load_plugins(sima, 'internal')
88
89     #  Loading contrib plugins
90     load_plugins(sima, 'contrib')
91
92     # Run as a daemon
93     if config.getboolean('daemon', 'daemon'):
94         sima.start()
95
96     try:
97         sima.foreground()
98     except KeyboardInterrupt:
99         logger.info('Caught KeyboardInterrupt, stopping')
100         #sima.shutdown()
101
102
103 def run():
104     """Catching broad exception
105     """
106     # pylint: disable=broad-except
107     try:
108         main()
109     except Exception:
110         exception_log()
111
112 # Script starts here
113 if __name__ == '__main__':
114     run()
115
116 # VIM MODLINE
117 # vim: ai ts=4 sw=4 sts=4 expandtab