]> kaliko git repositories - mpd-sima.git/blob - sima/launch.py
Releasing 0.17.0
[mpd-sima.git] / sima / launch.py
1 # -*- coding: utf-8 -*-
2 # Copyright (c) 2013, 2014, 2015, 2020,2021 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, MPDSimaException
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         sima.register_plugin(plugin_obj)
76
77
78 def start(sopt, restart=False):
79     """starts application
80     """
81     # loads configuration
82     cfg_mgmt = ConfMan(sopt.options)
83     config = cfg_mgmt.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
91     if sopt.options.get('command'):
92         cmd = sopt.options.get('command')
93         if cmd == "generate-config":
94             config.write(sys.stdout, space_around_delimiters=True)
95             sys.exit(0)
96         logger.info('Running "%s" and exit' % cmd)
97         if cmd == "config-test":
98             logger.info('Config location: "%s"', cfg_mgmt.conf_file)
99             from .utils.configtest import config_test
100             config_test(config)
101             sys.exit(0)
102         if cmd == "create-db":
103             db_file = config.get('sima', 'db_file')
104             if not isfile(db_file):
105                 logger.info('Creating database in "%s"', db_file)
106                 open(db_file, 'a').close()
107                 SimaDB(db_path=db_file).create_db()
108                 if sopt.options.get('create_db', None):
109                     logger.info('Done, bye...')
110             else:
111                 logger.info('Database already there, not overwriting %s', db_file)
112             sys.exit(0)
113         if cmd == "purge-history":
114             db_file = config.get('sima', 'db_file')
115             if not isfile(db_file):
116                 logger.warning('No db found: %s', db_file)
117                 sys.exit(1)
118             SimaDB(db_path=db_file).purge_history(duration=0)
119             sys.exit(0)
120
121
122     # TODO: To remove eventually in next major realese v0.18
123     # Create Database
124     db_file = config.get('sima', 'db_file')
125     if (sopt.options.get('create_db', None)
126             or not isfile(db_file)):
127         logger.info('Creating database in "%s"', db_file)
128         open(db_file, 'a').close()
129         SimaDB(db_path=db_file).create_db()
130         if sopt.options.get('create_db', None):
131             logger.info('Done, bye...')
132         sys.exit(0)
133
134     # TODO: To remove eventually in next major realese v0.18
135     if sopt.options.get('generate_config'):
136         config.write(sys.stdout, space_around_delimiters=True)
137         sys.exit(0)
138
139     logger.info('Starting (%s)...', info.__version__)
140     sima = core.Sima(config)
141
142     # required core plugins
143     core_plugins = [History, MpdOptions, Uniq]
144     if config.getboolean('sima', 'mopidy_compat'):
145         logger.warning('Running with mopidy compat. mode!')
146         core_plugins = [History, MpdOptions]
147         config['sima']['musicbrainzid'] = 'False'
148     for cplgn in core_plugins:
149         logger.debug('Register core %(name)s (%(doc)s)', cplgn.info())
150         sima.register_core_plugin(cplgn)
151     logger.debug('core loaded, prioriy: %s', ' > '.join(map(str, sima.core_plugins)))
152
153     #  Loading internal plugins
154     load_plugins(sima, 'internal')
155     #  Loading contrib plugins
156     load_plugins(sima, 'contrib')
157     logger.info('plugins loaded, prioriy: %s', ' > '.join(map(str, sima.plugins)))
158
159     # Run as a daemon
160     if config.getboolean('daemon', 'daemon'):
161         if restart:
162             sima.run()
163         else:
164             logger.info('Daemonize process...')
165             sima.start()
166
167     try:
168         sima.foreground()
169     except KeyboardInterrupt:
170         logger.info('Caught KeyboardInterrupt, stopping')
171         sys.exit(0)
172
173
174 def run(sopt, restart=False):
175     """
176     Handles SigHup exception
177     Catches Unhandled exception
178     """
179     # pylint: disable=broad-except
180     logger = logging.getLogger('sima')
181     try:
182         start(sopt, restart)
183     except SigHup:  # SigHup inherit from Exception
184         run(sopt, True)
185     except MPDSimaException as err:
186         logger.error(err)
187         sys.exit(2)
188     except Exception:  # Unhandled exception
189         exception_log()
190
191 # Script starts here
192 def main():
193     """Entry point"""
194     nfo = dict({'version': info.__version__,
195                 'prog': 'sima'})
196     # StartOpt gathers options from command line call (in StartOpt().options)
197     sopt = StartOpt(nfo)
198     run(sopt)
199
200
201 if __name__ == '__main__':
202     main()
203
204 # VIM MODLINE
205 # vim: ai ts=4 sw=4 sts=4 expandtab