main.py 1.99 KB
Newer Older
1 2 3 4 5 6 7 8
#
# Copyright (C) 2013 Stefano Sanfilippo
# Copyright (C) 2013 BITS development team
#
# This file is part of bitsd, which is released under the terms of
# GNU GPLv3. See COPYING at top level for more information.
#

9 10 11 12
"""
BITSd entry point and unix signal handlers.
"""

13
# MUST be the first import, DO NOT REMOVE
14 15
import bitsd.properties

16
import bitsd.server as server
17
import bitsd.listener as listener
JackV's avatar
JackV committed
18
import bitsd.mqtt_listener as mqtt_listener
19
import bitsd.persistence as persistence
Stefano Sanfilippo's avatar
Stefano Sanfilippo committed
20

21 22
from bitsd.common import LOG

Stefano Sanfilippo's avatar
Stefano Sanfilippo committed
23
from tornado.options import parse_command_line
24
from tornado.options import parse_config_file, options
25
from tornado.log import enable_pretty_logging
Stefano Sanfilippo's avatar
Stefano Sanfilippo committed
26

27
import tornado.ioloop
28

29 30
import signal
import time
31
import sys
32
import logging
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52

# Signal code adapted from https://gist.github.com/kachayev/1387470

def sig_handler(sig, frame):
    """Catch signal and init callback.

    Reference:
    http://codemehanika.org/blog/2011-10-28-graceful-stop-tornado.html
    """
    LOG.warning('Caught signal: %s', sig)
    tornado.ioloop.IOLoop.instance().add_callback(shutdown)


def shutdown():
    """Stop server and add callback to stop i/o loop."""
    io_loop = tornado.ioloop.IOLoop.instance()
    LOG.info('Shutting down in 2 seconds')
    io_loop.add_timeout(time.time() + 2, io_loop.stop)


53
def main():
54
    """Entry point for bitsd."""
Stefano Sanfilippo's avatar
Stefano Sanfilippo committed
55 56 57 58 59
    enable_pretty_logging()

    try:
        parse_config_file('/etc/bitsd.conf')
    except IOError:
60
        LOG.warning('Config file not found, using defaults and command line.')
Stefano Sanfilippo's avatar
Stefano Sanfilippo committed
61

62 63 64 65 66
    try:
        parse_command_line()
    except tornado.options.Error as error:
        sys.stderr.write('{}\n'.format(error))
        sys.exit(0)
67

68
    persistence.start()
69
    server.start()
JackV's avatar
JackV committed
70
    #listener.start()
JackV's avatar
JackV committed
71
    mqtt_listener.start()
72

73 74 75 76
    # Add signal handlers...
    signal.signal(signal.SIGTERM, sig_handler)
    signal.signal(signal.SIGINT, sig_handler)

77
    if not options.log_requests:
78
        logging.getLogger("tornado.access").setLevel(logging.WARNING)
79

80
    tornado.ioloop.IOLoop.instance().start()