]> kaliko git repositories - mpd-sima.git/blob - sima/launch.py
Use client2client to detect other instance
[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.simadb import SimaDB
38 from .utils.config import ConfMan
39 from .utils.startopt import StartOpt
40 from .utils.utils import exception_log, SigHup
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     for plugin in sima.config.get('sima', source).split(','):
57         plugin = plugin.strip(' \n')
58         module = 'sima.plugins.{0}.{1}'.format(source, plugin.lower())
59         try:
60             mod_obj = __import__(module, fromlist=[plugin])
61         except ImportError as err:
62             logger.error('Failed to load plugin\'s module: ' +
63                          '{0} ({1})'.format(module, err))
64             sima.shutdown()
65             sys.exit(1)
66         try:
67             plugin_obj = getattr(mod_obj, plugin)
68         except AttributeError as err:
69             logger.error('Failed to load plugin {0} ({1})'.format(plugin, err))
70             sima.shutdown()
71             sys.exit(1)
72         logger.info('Loading {0} plugin: {name} ({doc})'.format(
73                              source, **plugin_obj.info()))
74         sima.register_plugin(plugin_obj)
75
76
77 def start(sopt, restart=False):
78     """starts application
79     """
80     # set logger
81     verbosity = sopt.options.get('verbosity', 'warning')
82     logfile = sopt.options.get('logfile', None)
83     set_logger(verbosity, logfile)
84     # loads configuration
85     config = ConfMan(sopt.options).config
86     logfile = config.get('log', 'logfile')
87     verbosity = config.get('log', 'verbosity')
88     set_logger(verbosity, logfile)
89     logger = logging.getLogger('sima')
90     logger.debug('Command line say: {0}'.format(sopt.options))
91     # Create Database
92     db_file = config.get('sima', 'db_file')
93     if (sopt.options.get('create_db', None)
94        or not isfile(db_file)):
95         logger.info('Creating database in "{}"'.format(db_file))
96         open(db_file, 'a').close()
97         SimaDB(db_path=db_file).create_db()
98         if sopt.options.get('create_db', None):
99             logger.info('Done, bye...')
100             sys.exit(0)
101
102     logger.info('Starting...')
103     sima = core.Sima(config)
104
105     # required core plugins
106     core_plugins = [History, MpdOptions, Uniq]
107     for cplgn in core_plugins:
108         logger.debug('Register core {name} ({doc})'.format(**cplgn.info()))
109         sima.register_plugin(cplgn)
110
111     #  Loading internal plugins
112     load_plugins(sima, 'internal')
113
114     #  Loading contrib plugins
115     load_plugins(sima, 'contrib')
116     # Run as a daemon
117     if config.getboolean('daemon', 'daemon'):
118         if restart:
119             sima.run()
120         else:
121             logger.info('Daemonize process...')
122             sima.start()
123
124     try:
125         sima.foreground()
126     except KeyboardInterrupt:
127         logger.info('Caught KeyboardInterrupt, stopping')
128         sys.exit(0)
129
130
131 def run(sopt, restart=False):
132     """
133     Handles SigHup exception
134     Catches Unhandled exception
135     """
136     # pylint: disable=broad-except
137     try:
138         start(sopt, restart)
139     except SigHup:  # SigHup inherit from Exception
140         run(sopt, True)
141     except Exception:  # Unhandled exception
142         exception_log()
143
144 # Script starts here
145 def main():
146     """Entry point"""
147     nfo = dict({'version': info.__version__,
148                  'prog': 'sima'})
149     # StartOpt gathers options from command line call (in StartOpt().options)
150     sopt = StartOpt(nfo)
151     run(sopt)
152
153
154 if __name__ == '__main__':
155     main()
156
157 # VIM MODLINE
158 # vim: ai ts=4 sw=4 sts=4 expandtab