]> kaliko git repositories - mpd-sima.git/blob - sima/launch.py
1ff6c94c4b94a2d91a102fd06256d74075f39105
[mpd-sima.git] / sima / launch.py
1 # -*- coding: utf-8 -*-
2 # Copyright (c) 2013, 2014 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__
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     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 = __import__(module, fromlist=[plugin])
62         except ImportError as err:
63             logger.error('Failed to load plugin\'s module: ' +
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 {0} ({1})'.format(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     # set logger
82     verbosity = sopt.options.get('verbosity', 'warning')
83     logfile = sopt.options.get('logfile', None)
84     set_logger(verbosity, logfile)
85     # loads configuration
86     config = ConfMan(sopt.options).config
87     logfile = config.get('log', 'logfile')
88     verbosity = config.get('log', 'verbosity')
89     set_logger(verbosity, logfile)
90     logger = logging.getLogger('sima')
91     logger.debug('Command line say: {0}'.format(sopt.options))
92     # Create Database
93     db_file = config.get('sima', 'db_file')
94     if (sopt.options.get('create_db', None)
95        or not isfile(db_file)):
96         logger.info('Creating database in "{}"'.format(db_file))
97         open(db_file, 'a').close()
98         SimaDB(db_path=db_file).create_db()
99         if sopt.options.get('create_db', None):
100             logger.info('Done, bye...')
101             sys.exit(0)
102
103     logger.info('Starting...')
104     sima = core.Sima(config)
105
106     # required core plugins
107     core_plugins = [History, MpdOptions, Uniq]
108     for cplgn in core_plugins:
109         logger.debug('Register core {name} ({doc})'.format(**cplgn.info()))
110         sima.register_plugin(cplgn)
111
112     #  Loading internal plugins
113     load_plugins(sima, 'internal')
114
115     #  Loading contrib plugins
116     load_plugins(sima, 'contrib')
117
118     #  Set use of MusicBrainzIdentifier
119     if not config.getboolean('sima', 'musicbrainzid'):
120         logger.info('Disabling MusicBrainzIdentifier')
121         Meta.use_mbid = False
122
123     # Run as a daemon
124     if config.getboolean('daemon', 'daemon'):
125         if restart:
126             sima.run()
127         else:
128             logger.info('Daemonize process...')
129             sima.start()
130
131     try:
132         sima.foreground()
133     except KeyboardInterrupt:
134         logger.info('Caught KeyboardInterrupt, stopping')
135         sys.exit(0)
136
137
138 def run(sopt, restart=False):
139     """
140     Handles SigHup exception
141     Catches Unhandled exception
142     """
143     # pylint: disable=broad-except
144     try:
145         start(sopt, restart)
146     except SigHup:  # SigHup inherit from Exception
147         run(sopt, True)
148     except Exception:  # Unhandled exception
149         exception_log()
150
151 # Script starts here
152 def main():
153     """Entry point"""
154     nfo = dict({'version': info.__version__,
155                  'prog': 'sima'})
156     # StartOpt gathers options from command line call (in StartOpt().options)
157     sopt = StartOpt(nfo)
158     run(sopt)
159
160
161 if __name__ == '__main__':
162     main()
163
164 # VIM MODLINE
165 # vim: ai ts=4 sw=4 sts=4 expandtab