]> kaliko git repositories - mpd-sima.git/blob - sima/launch.py
Code convention clean up (pylint)
[mpd-sima.git] / sima / launch.py
1 # -*- coding: utf-8 -*-
2 # Copyright (c) 2013, 2014, 2015 Jack 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.meta import Meta
38 from .lib.simadb import SimaDB
39 from .utils.config import ConfMan
40 from .utils.startopt import StartOpt
41 from .utils.utils import exception_log, SigHup
42  # core plugins
43 from .plugins.core.history import History
44 from .plugins.core.mpdoptions import MpdOptions
45 from .plugins.core.uniq import Uniq
46 ##
47
48
49 def load_plugins(sima, source):
50     """Handles internal/external plugins
51         sima:   sima.core.Sima instance
52         source: ['internal', 'contrib']
53     """
54     if not sima.config.get('sima', source):
55         return
56     logger = logging.getLogger('sima')
57     # TODO: Sanity check for "sima.config.get('sima', source)" ?
58     for plugin in sima.config.get('sima', source).split(','):
59         plugin = plugin.strip(' \n')
60         module = 'sima.plugins.{0}.{1}'.format(source, plugin.lower())
61         try:
62             mod_obj = sima_import(module, fromlist=[plugin])
63         except ImportError as err:
64             logger.error('Failed to load "{}" plugin\'s module: '.format(plugin) +
65                          '{0} ({1})'.format(module, err))
66             sima.shutdown()
67             sys.exit(1)
68         try:
69             plugin_obj = getattr(mod_obj, plugin)
70         except AttributeError as err:
71             logger.error('Failed to load plugin {0} ({1})'.format(plugin, err))
72             sima.shutdown()
73             sys.exit(1)
74         logger.info('Loading {0} plugin: {name} ({doc})'.format(
75             source, **plugin_obj.info()))
76         sima.register_plugin(plugin_obj)
77
78
79 def start(sopt, restart=False):
80     """starts application
81     """
82     # loads configuration
83     config = ConfMan(sopt.options).config
84     # set logger
85     logger = logging.getLogger('sima')
86     logfile = config.get('log', 'logfile', fallback=None)
87     verbosity = config.get('log', 'verbosity')
88     set_logger(verbosity, logfile)
89     logger.debug('Command line say: %s', sopt.options)
90     # Create Database
91     db_file = config.get('sima', 'db_file')
92     if (sopt.options.get('create_db', None)
93             or not isfile(db_file)):
94         logger.info('Creating database in "%s"', db_file)
95         open(db_file, 'a').close()
96         SimaDB(db_path=db_file).create_db()
97         if sopt.options.get('create_db', None):
98             logger.info('Done, bye...')
99             sys.exit(0)
100
101     if sopt.options.get('generate_config'):
102         config.write(sys.stdout, space_around_delimiters=True)
103         sys.exit(0)
104
105     logger.info('Starting...')
106     sima = core.Sima(config)
107
108     # required core plugins
109     core_plugins = [History, MpdOptions, Uniq]
110     for cplgn in core_plugins:
111         logger.debug('Register core {name} ({doc})'.format(**cplgn.info()))
112         sima.register_core_plugin(cplgn)
113     logger.debug('core loaded, prioriy: {}'.format(' > '.join(map(str, sima.core_plugins))))
114
115     #  Loading internal plugins
116     load_plugins(sima, 'internal')
117
118     #  Loading contrib plugins
119     load_plugins(sima, 'contrib')
120     logger.info('plugins loaded, prioriy: {}'.format(' > '.join(map(str, sima.plugins))))
121     #  Set use of MusicBrainzIdentifier
122     if not config.getboolean('sima', 'musicbrainzid'):
123         logger.info('Disabling MusicBrainzIdentifier')
124         Meta.use_mbid = False
125
126     # Run as a daemon
127     if config.getboolean('daemon', 'daemon'):
128         if restart:
129             sima.run()
130         else:
131             logger.info('Daemonize process...')
132             sima.start()
133
134     try:
135         sima.foreground()
136     except KeyboardInterrupt:
137         logger.info('Caught KeyboardInterrupt, stopping')
138         sys.exit(0)
139
140
141 def run(sopt, restart=False):
142     """
143     Handles SigHup exception
144     Catches Unhandled exception
145     """
146     # pylint: disable=broad-except
147     try:
148         start(sopt, restart)
149     except SigHup:  # SigHup inherit from Exception
150         run(sopt, True)
151     except Exception:  # Unhandled exception
152         exception_log()
153
154 # Script starts here
155 def main():
156     """Entry point"""
157     nfo = dict({'version': info.__version__,
158                 'prog': 'sima'})
159     # StartOpt gathers options from command line call (in StartOpt().options)
160     sopt = StartOpt(nfo)
161     run(sopt)
162
163
164 if __name__ == '__main__':
165     main()
166
167 # VIM MODLINE
168 # vim: ai ts=4 sw=4 sts=4 expandtab