]> kaliko git repositories - mpd-sima.git/blob - sima/launch.py
Add new database replacement code.
[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 # 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 %s (%s)', 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     cfg_mgmt = ConfMan(sopt.options)
84     config = cfg_mgmt.config
85     # set logger
86     logger = logging.getLogger('sima')
87     logfile = config.get('log', 'logfile', fallback=None)
88     verbosity = config.get('log', 'verbosity')
89     set_logger(verbosity, logfile)
90     logger.debug('Command line say: %s', sopt.options)
91
92     # Create database if not present
93     db_file = config.get('sima', 'db_file')
94     if not isfile(db_file):
95         logger.debug('Creating database in "%s"', db_file)
96         SimaDB(db_path=db_file).create_db()
97     # Migration from v0.17.0
98     dbinfo = SimaDB(db_path=db_file).get_info()
99     if not dbinfo:  # v0.17.0 → v0.18+ migration
100         logger.warning('Backing up database!')
101         rename(db_file, db_file + '-old-version-backup')
102         logger.info('Creating an new database in "%s"', db_file)
103         SimaDB(db_path=db_file).create_db()
104
105     if sopt.options.get('command'):
106         cmd = sopt.options.get('command')
107         if cmd == "generate-config":
108             config.write(sys.stdout, space_around_delimiters=True)
109             sys.exit(0)
110         logger.info('Running "%s" and exit' % cmd)
111         if cmd == "config-test":
112             logger.info('Config location: "%s"', cfg_mgmt.conf_file)
113             from .utils.configtest import config_test
114             config_test(config)
115             sys.exit(0)
116         if cmd == "create-db":
117             if not isfile(db_file):
118                 logger.info('Creating database in "%s"', db_file)
119                 SimaDB(db_path=db_file).create_db()
120             else:
121                 logger.info('Database already there, not overwriting %s', db_file)
122             logger.info('Done, bye...')
123             sys.exit(0)
124         if cmd == "purge-history":
125             db_file = config.get('sima', 'db_file')
126             if not isfile(db_file):
127                 logger.warning('No db found: %s', db_file)
128                 sys.exit(1)
129             SimaDB(db_path=db_file).purge_history(duration=0)
130             sys.exit(0)
131
132     logger.info('Starting (%s)...', info.__version__)
133     sima = core.Sima(config)
134
135     # required core plugins
136     core_plugins = [History, MpdOptions, Uniq]
137     if config.getboolean('sima', 'mopidy_compat'):
138         logger.warning('Running with mopidy compat. mode!')
139         core_plugins = [History, MpdOptions]
140         config['sima']['musicbrainzid'] = 'False'
141     for cplgn in core_plugins:
142         logger.debug('Register core %(name)s (%(doc)s)', cplgn.info())
143         sima.register_core_plugin(cplgn)
144     logger.debug('core loaded, prioriy: %s', ' > '.join(map(str, sima.core_plugins)))
145
146     #  Loading internal plugins
147     load_plugins(sima, 'internal')
148     #  Loading contrib plugins
149     load_plugins(sima, 'contrib')
150     logger.info('plugins loaded, prioriy: %s', ' > '.join(map(str, sima.plugins)))
151
152     # Run as a daemon
153     if config.getboolean('daemon', 'daemon'):
154         if restart:
155             sima.run()
156         else:
157             logger.info('Daemonize process...')
158             sima.start()
159
160     try:
161         sima.foreground()
162     except KeyboardInterrupt:
163         logger.info('Caught KeyboardInterrupt, stopping')
164         sys.exit(0)
165
166
167 def run(sopt, restart=False):
168     """
169     Handles SigHup exception
170     Catches Unhandled exception
171     """
172     # pylint: disable=broad-except
173     logger = logging.getLogger('sima')
174     try:
175         start(sopt, restart)
176     except SigHup:  # SigHup inherit from Exception
177         run(sopt, True)
178     except MPDSimaException as err:
179         logger.error(err)
180         sys.exit(2)
181     except Exception:  # Unhandled exception
182         exception_log()
183
184 # Script starts here
185 def main():
186     """Entry point"""
187     nfo = dict({'version': info.__version__,
188                 'prog': 'sima'})
189     # StartOpt gathers options from command line call (in StartOpt().options)
190     sopt = StartOpt(nfo)
191     run(sopt)
192
193
194 if __name__ == '__main__':
195     main()
196
197 # VIM MODLINE
198 # vim: ai ts=4 sw=4 sts=4 expandtab