]> kaliko git repositories - mpd-sima.git/blob - sima/launch.py
7117f09f733c4f4acbb2c51634391af77266d47c
[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 from os import rename
30 ##
31
32 # third parties components
33 ##
34
35 # local import
36 from . import core, info
37 from .lib.logger import set_logger
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, MPDSimaException
42 from .utils.blcli import BLCli
43 # core plugins
44 from .plugins.core.history import History
45 from .plugins.core.mpdoptions import MpdOptions
46 from .plugins.core.uniq import Uniq
47 ##
48
49
50 def load_plugins(sima, source):
51     """Handles internal/external plugins
52         sima:   sima.core.Sima instance
53         source: ['internal', 'contrib']
54     """# pylint: disable=logging-not-lazy,logging-format-interpolation
55     if not sima.config.get('sima', source):
56         return
57     logger = logging.getLogger('sima')
58     # TODO: Sanity check for "sima.config.get('sima', source)" ?
59     for plugin in sima.config.get('sima', source).split(','):
60         plugin = plugin.strip(' \n')
61         module = 'sima.plugins.{0}.{1}'.format(source, plugin.lower())
62         try:
63             mod_obj = sima_import(module, fromlist=[plugin])
64         except ImportError as err:
65             logger.error('Failed to load "{}" plugin\'s module: '.format(plugin) +
66                          '{0} ({1})'.format(module, err))
67             sima.shutdown()
68             sys.exit(1)
69         try:
70             plugin_obj = getattr(mod_obj, plugin)
71         except AttributeError as err:
72             logger.error('Failed to load plugin %s (%s)', plugin, err)
73             sima.shutdown()
74             sys.exit(1)
75         logger.info('Loading {0} plugin: {name} ({doc})'.format(
76             source, **plugin_obj.info()))
77         sima.register_plugin(plugin_obj)
78
79
80 def start(sopt, restart=False):
81     """starts application
82     """
83     # loads configuration
84     cfg_mgmt = ConfMan(sopt.options)
85     config = cfg_mgmt.config
86     # set logger
87     logger = logging.getLogger('sima')
88     logfile = config.get('log', 'logfile', fallback=None)
89     verbosity = config.get('log', 'verbosity')
90     if sopt.options.get('command'):  # disable file logging
91         set_logger(verbosity)
92     else:
93         set_logger(verbosity, logfile)
94     logger.debug('Command line say: %s', sopt.options)
95
96     # Create database if not present
97     db_file = config.get('sima', 'db_file')
98     if not isfile(db_file):
99         logger.debug('Creating database in "%s"', db_file)
100         SimaDB(db_path=db_file).create_db()
101     # Migration from v0.17.0
102     dbinfo = SimaDB(db_path=db_file).get_info()
103     if not dbinfo:  # v0.17.0 → v0.18+ migration
104         logger.warning('Backing up database!')
105         rename(db_file, db_file + '-old-version-backup')
106         logger.info('Creating an new database in "%s"', db_file)
107         SimaDB(db_path=db_file).create_db()
108
109     if sopt.options.get('command'):
110         cmd = sopt.options.get('command')
111         if cmd.startswith('bl-'):
112             BLCli(config, sopt.options)
113             sys.exit(0)
114         if cmd == "generate-config":
115             config.write(sys.stdout, space_around_delimiters=True)
116             sys.exit(0)
117         logger.info('Running "%s" and exit', cmd)
118         if cmd == "config-test":
119             logger.info('Config location: "%s"', cfg_mgmt.conf_file)
120             from .utils.configtest import config_test
121             config_test(config)
122             sys.exit(0)
123         if cmd == "create-db":
124             if not isfile(db_file):
125                 logger.info('Creating database in "%s"', db_file)
126                 SimaDB(db_path=db_file).create_db()
127             else:
128                 logger.info('Database already there, not overwriting %s', db_file)
129             logger.info('Done, bye...')
130             sys.exit(0)
131         if cmd == "purge-history":
132             db_file = config.get('sima', 'db_file')
133             if not isfile(db_file):
134                 logger.warning('No db found: %s', db_file)
135                 sys.exit(1)
136             SimaDB(db_path=db_file).purge_history(duration=0)
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',
152                  ' > '.join(map(str, sima.core_plugins)))
153
154     #  Loading internal plugins
155     load_plugins(sima, 'internal')
156     #  Loading contrib plugins
157     load_plugins(sima, 'contrib')
158     logger.info('plugins loaded, prioriy: %s', ' > '.join(map(str, sima.plugins)))
159
160     # Run as a daemon
161     if config.getboolean('daemon', 'daemon'):
162         if restart:
163             sima.run()
164         else:
165             logger.info('Daemonize process...')
166             sima.start()
167
168     try:
169         sima.foreground()
170     except KeyboardInterrupt:
171         logger.info('Caught KeyboardInterrupt, stopping')
172         sys.exit(0)
173
174
175 def run(sopt, restart=False):
176     """
177     Handles SigHup exception
178     Catches Unhandled exception
179     """
180     # pylint: disable=broad-except
181     logger = logging.getLogger('sima')
182     try:
183         start(sopt, restart)
184     except SigHup:  # SigHup inherit from Exception
185         run(sopt, True)
186     except MPDSimaException as err:
187         logger.error(err)
188         sys.exit(2)
189     except Exception:  # Unhandled exception
190         exception_log()
191
192
193 # Script starts here
194 def main():
195     """Entry point"""
196     nfo = dict({'version': info.__version__,
197                 'prog': 'mpd-sima'})
198     # StartOpt gathers options from command line call (in StartOpt().options)
199     sopt = StartOpt(nfo)
200     run(sopt)
201
202
203 if __name__ == '__main__':
204     main()
205
206 # VIM MODLINE
207 # vim: ai ts=4 sw=4 sts=4 expandtab