Example #1
0
def main():
    import getpass
    from tornado import options
    from tornado.log import enable_pretty_logging

    options.define("xmpp", default=None, help="XMPP Account", metavar="XMPP")
    options.define("qq", default=None, type=int, help="QQ Account",
                   metavar="QQ")
    options.define("debug", type=bool, default=False, help="Show debug info")
    options.define("control", default=None, help="XMPP Control Account",
                   metavar="CONTROL")
    options.parse_command_line()

    xmpp = options.options.xmpp
    qq = options.options.qq
    control = options.options.control
    debug = options.options.debug
    if not xmpp or not qq or not control:
        options.print_help()
        return

    xmpp_pwd = getpass.getpass(u"Enter XMPP Password: "******"Enter QQ Password: ")

    enable_pretty_logging()
    client = MagpieClient(qq, qq_pwd, xmpp, xmpp_pwd, control, debug)
    client.run()
Example #2
0
def main():
    # Parse options
    tornado.options.parse_command_line()
    if len(sys.argv) > 1 and sys.argv[1] == "help":
        options.print_help()
        exit()
    tornado.options.parse_config_file(options.configfile)

    # Configure logging
    # We cannot use logging.basicConfig because tornado has
    # set up loggers when parsing options
    logging_config(options.access_log, options.debug_log, options.info_log,
                   options.warn_log, options.err_log, options.log_level)

    tokens = options.tokens.split(",")
    token_auth.init(tokens)

    # Set up application
    app = tornado.web.Application(handlers=[(r"/", EchoHandler)])
    http_server = tornado.httpserver.HTTPServer(app)
    http_server.listen(options.port)

    pidfile = options.pidfile
    ensure_dir(os.path.dirname(pidfile))
    pidfp = open(pidfile, "w")
    pidfp.write(str(os.getpid()))
    pidfp.close()

    logger.info("Starting tornado server on port {}...".format(options.port))

    tornado.ioloop.IOLoop.instance().start()
Example #3
0
def main():
    define("config_dir")
    define("listen", default="0.0.0.0:80", multiple=True)

    if "--help" in sys.argv or "-h" in sys.argv:
        print_help()
        return

    parse_command_line(final=False)

    options.run_parse_callbacks()  # same as final=True

    application = tornado.web.Application(routes,
                                          debug=bool(os.getenv("DEBUG")))
    server = tornado.httpserver.HTTPServer(application)
    for addr in options.listen:
        port = 80
        address = addr
        try:
            address, port = addr.rsplit(':', 1)
            port = int(port)
        except ValueError:
            pass
        server.listen(port, address=address)
    tornado.ioloop.IOLoop.instance().start()
Example #4
0
def main():
    logs_to_stream = tornado.options.parse_command_line()
    logging.getLogger().setLevel(getattr(logging, options.logging.upper()))

    if logs_to_stream:
        # parse_command_line gives options if they're at the end
        # of the line. For example lumberjack log1 log2 --logging=debug
        # gives ['log1', 'log2', '--logging=debug'].
        lumberbuffers, lodge = setup_global_models(
            [l for l in logs_to_stream if not l.startswith('--')]
            )
    else:
        sys.stderr.write("Didn't specify any files to stream\n")
        options.print_help()
        sys.exit(1)
            
    routes = (
        ( r'/', MainHandler, 
          dict(lodge=lodge) ),
        ( r'/lodge/?', LodgeHandler, 
          dict(lodge=lodge) ),
        ( r'/([\w.\.%]+)/?', LumberHandler, 
          dict(cache=lumberbuffers) ),
        ( r'/([\w.\.%]+)/socket.*', LumberSocket, 
          dict(cache=lumberbuffers) ),
        ( r'/([\w.\.]+)/([\w.\.%]+)/?', ProxyHandler ),
        ( r'/([\w.\.]+)/([\w.\.%]+)/socket.*', ProxySocket )
        )

    app_settings = dict(
        static_path=os.path.join(os.path.dirname(__file__), 'static'),
        template_path=os.path.join(os.path.dirname(__file__), 'templates'),
        debug=(options.logging.lower() == 'debug')
        )

    app = tornado.web.Application( routes, **app_settings )
    
    app.listen(options.listenport)

    ioloop = tornado.ioloop.IOLoop.instance()

    try:
        ioloop.start()
    except KeyboardInterrupt:
        log.info('Keyboard interrupt. Shutting down...')
Example #5
0
def main():  # pragma: no cover
    try:
        command_line_config = CommandLineConfig()
        command_line_config.parse_config()
        file_config = FileConfig()

        if command_line_config.config_file:
            file_config.parse_config(command_line_config.config_file)

        environment_config = EnvironmentConfig()
        environment_config.parse_config()

    except Exception as e:
        print_help()
        print("Error: {}".format(e))
        sys.exit(1)

    app = Application(command_line_config, file_config, environment_config)
    app.start()
Example #6
0
def main():    # pragma: no cover
    try:
        command_line_config = CommandLineConfig()
        command_line_config.parse_config()
        file_config = FileConfig()

        if command_line_config.config_file:
            file_config.parse_config(command_line_config.config_file)

        environment_config = EnvironmentConfig()
        environment_config.parse_config()

    except Exception as e:
        print_help()
        print("Error: {}".format(e))
        sys.exit(1)

    app = Application(command_line_config, file_config, environment_config)
    app.start()
Example #7
0
 def _RunOTPCommand():
   with util.ExceptionBarrier(_OnException):
     if options.options.otp_mode == "get":
       print GetOTP(options.options.user)
     elif options.options.otp_mode == "verify":
       print VerifyOTP(options.options.user, options.options.otp)
     elif options.options.otp_mode == "new_secret":
       CreateUserSecret(options.options.user)
     elif options.options.otp_mode == "display_secret":
       DisplayUserSecret(options.options.user)
     elif options.options.otp_mode == "set_pwd":
       SetPassword(options.options.user)
     elif options.options.otp_mode == "verify_pwd":
       VerifyPasswordCLI(options.options.user)
     elif options.options.otp_mode == "random":
       CreateRandomBytes(options.options.bytes)
     elif options.options.otp_mode == "randomb64":
       CreateRandomBytes(options.options.bytes, True)
     else:
       logging.error("unrecognized mode {0}", options.options.otp_mode)
       options.print_help()
     io_loop.stop()
Example #8
0
 def _RunOTPCommand():
     with util.ExceptionBarrier(_OnException):
         if options.options.otp_mode == "get":
             print GetOTP(options.options.user)
         elif options.options.otp_mode == "verify":
             print VerifyOTP(options.options.user, options.options.otp)
         elif options.options.otp_mode == "new_secret":
             CreateUserSecret(options.options.user)
         elif options.options.otp_mode == "display_secret":
             DisplayUserSecret(options.options.user)
         elif options.options.otp_mode == "set_pwd":
             SetPassword(options.options.user)
         elif options.options.otp_mode == "verify_pwd":
             VerifyPasswordCLI(options.options.user)
         elif options.options.otp_mode == "random":
             CreateRandomBytes(options.options.bytes)
         elif options.options.otp_mode == "randomb64":
             CreateRandomBytes(options.options.bytes, True)
         else:
             logging.error("unrecognized mode {0}",
                           options.options.otp_mode)
             options.print_help()
         io_loop.stop()
Example #9
0
def main():
    define("config_dir")
    define("listen", default="0.0.0.0:80", multiple=True)

    if "--help" in sys.argv or "-h" in sys.argv:
        print_help()
        return

    parse_command_line(final=False)

    options.run_parse_callbacks()  # same as final=True

    application = tornado.web.Application(routes, debug=bool(os.getenv("DEBUG")))
    server = tornado.httpserver.HTTPServer(application)
    for addr in options.listen:
        port = 80
        address = addr
        try:
            address, port = addr.rsplit(':', 1)
            port = int(port)
        except ValueError:
            pass
        server.listen(port, address=address)
    tornado.ioloop.IOLoop.instance().start()
Example #10
0
def run():
    options.parse_command_line()

    options_dict = options.as_dict()

    if not options_dict.get('config', None):
        if os.path.isfile(DEFAULT_CONFIG_PATH):
            options_dict['config'] = DEFAULT_CONFIG_PATH
        else:
            LOGGER.error("Config file is required.")
            print_help()
            sys.exit(1)

    reactor = Reactor(**options_dict)

    stop = lambda *args: reactor.stop()
    reinit = lambda *args: reactor.reinit()

    signal.signal(signal.SIGTERM, stop)
    signal.signal(signal.SIGINT, stop)
    if hasattr(signal, 'SIGHUP'):
        signal.signal(signal.SIGHUP, reinit)

    reactor.start()
Example #11
0
def run():
    options.parse_command_line()

    options_dict = options.as_dict()

    if not options_dict.get('config', None):
        if os.path.isfile(DEFAULT_CONFIG_PATH):
            options_dict['config'] = DEFAULT_CONFIG_PATH
        else:
            LOGGER.error("Config file is required.")
            print_help()
            sys.exit(1)

    reactor = Reactor(**options_dict)

    stop = lambda *args: reactor.stop()
    reinit = lambda *args: reactor.reinit()

    signal.signal(signal.SIGTERM, stop)
    signal.signal(signal.SIGINT, stop)
    if hasattr(signal, 'SIGHUP'):
        signal.signal(signal.SIGHUP, reinit)

    reactor.start()
Example #12
0
def checker():
    import json
    import logging
    import re

    define("tenderloin_address", default="127.0.0.1", group="check_tl",
           help="Tenderloin address")
    define("tenderloin_port", default=50000, group="check_tl",
           help="Tenderloin port")
    define("plugin", group="check_tl", help="Tenderloin plugin to check")
    define("metric", group="check_tl", help="metric to check")
    define("warn", default=None, metavar="VALUE", group="check_tl",
           help="Warning if [not,beyond] VALUE")
    define("crit", default=None, metavar="VALUE", group="check_tl",
           help="Critical if [not,beyond] VALUE")
    define("over", default=False, group="check_tl",
           help="Over specified warning or critical threshold")
    define("under", default=False, group="check_tl",
           help="Under specified warning or critical threshold")
    define("match", multiple=True, group="check_tl",
           help="Critical if metric does not match value specified")

    parse_command_line()

    # hackety-hack to turn off logging
    logging.getLogger().setLevel(logging.FATAL)
    real_warning = coerce_float(options.warn)
    real_critical = coerce_float(options.crit)

    if not any([getattr(options, option) for option in ("warn", "crit", "match")]):
        print "ERROR: You must specify either --warn and --crit or --match values\n"
        print_help()
        sys.exit(NAGIOS_STATUSES["UNKNOWN"])

    if not any([getattr(options, option) for option in ("over", "under", "match")]):
        print "ERROR: You must specify how to interpret the metric with --over or --under or --match\n"
        print_help()
        sys.exit(NAGIOS_STATUSES["UNKNOWN"])

    if not all([getattr(options, option) for option in ("metric", "plugin")]):
        print "ERROR: You must specify both the plugin and metric to check\n"
        print_help()
        sys.exit(NAGIOS_STATUSES["UNKNOWN"])

    if getattr(options, "over") and real_warning > real_critical:
        print "ERROR: warning is over critical!\n"
        print_help()
        sys.exit(NAGIOS_STATUSES["UNKNOWN"])
    elif getattr(options, "under") and real_warning < real_critical:
        print "ERROR: warning is under critical!\n"
        print_help()
        sys.exit(NAGIOS_STATUSES["UNKNOWN"])

    tl = Tenderloin(options.tenderloin_address, options.tenderloin_port)
    output = tl.get_data(options.plugin)
    check_output = {}

    try:
        p = re.compile(options.metric)
        for mn, mv in output.items():
            if p.match(mn):
                check_output[mn] = dict(OK=[], WARNING=[], CRITICAL=[])
                mval = coerce_float(output[mn])
                output_string = "%s [warn=%s|crit=%s|recvd=%s]" %\
                                (mn, real_warning, real_critical, mval)

                if options.match:
                    for mx in options.match:
                        p2 = re.compile(mx)
                        if p2.match(str(mval)):
                            check_status = "OK"
                            break
                        else:
                            check_status = "CRITICAL"
                elif options.over:
                    if mval > real_critical:
                        check_status = "CRITICAL"
                    elif real_critical and mval > real_warning:
                        check_status = "WARNING"
                    else:
                        check_status = "OK"
                elif options.under:
                    if mval < real_critical:
                        check_status = "CRITICAL"
                    elif real_warning and mval < real_warning:
                        check_status = "WARNING"
                    else:
                        check_status = "OK"

                check_output[mn][check_status].append(
                    nagios_output(check_status,
                                  mn,
                                  mval,
                                  real_warning,
                                  real_critical))
    except KeyError:
        print "UNKNOWN: Metric doesn't exist: %s" % options.metric
        sys.exit(NAGIOS_STATUSES["UNKNOWN"])

    if not check_output:
        print "UNKNOWN: Metric doesn't exist: %s" % options.metric
        sys.exit(NAGIOS_STATUSES["UNKNOWN"])

    critical_statuses = sum([x for x in [v["CRITICAL"] for k, v in check_output.items()] if x], [])
    warning_statuses = sum([x for x in [v["WARNING"] for k, v in check_output.items()] if x], [])
    ok_statuses = sum([x for x in [v["OK"] for k, v in check_output.items()] if x], [])

    if critical_statuses:
        print "\n".join([st for st in critical_statuses])
        sys.exit(NAGIOS_STATUSES["CRITICAL"])
    elif warning_statuses:
        print "\n".join([st for st in warning_statuses])
        sys.exit(NAGIOS_STATUSES["WARNING"])
    else:
        print "\n".join([st for st in ok_statuses])
        sys.exit(NAGIOS_STATUSES["OK"])
Example #13
0
    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
'''

from tornado.options import define, options, parse_command_line, print_help
from server.game_server import run_server

define("run", help="run the server on the specified http port")
define("board_x_size", default="1000")
define("board_y_size", default="1000")
define("network_latency",
       default="0.100",
       help="The network latency in seconds.")
define(
    "game_tick",
    default="0.25",
    help=
    "The virtual simulation time in seconds, between two consecutive robot commands."
)

parse_command_line()

if not options.run:
    # TODO print license
    print_help()
else:
    run_server(options.run, int(float(options.board_x_size)),
               int(float(options.board_y_size)),
               float(options.network_latency), float(options.game_tick))
from tornado import autoreload
from os import environ

from core.boterator import Boterator


if __name__ == '__main__':
    define('token', type=str, help='TelegramBot\'s token', default=environ.get('TG_TOKEN'))
    define('db', type=str, help='DB connection DSN', default=environ.get('DB', "dbname=boterator user=boterator host=localhost port=5432"))
    define('burlesque', type=str, help='Burlesque address', default=environ.get('BURLESQUE', 'http://127.0.0.1:4401'))
    define('debug', type=bool, default=False)

    parse_command_line()

    if not options.token:
        print_help()
        exit(1)

    ioloop = IOLoop.instance()

    db = Pool(dsn=options.db, size=1, max_size=10, auto_shrink=True, ioloop=IOLoop.current())
    ioloop.run_sync(db.connect)

    if options.debug:
        autoreload.start()

    bm = Boterator(options.token, db, Burlesque(options.burlesque))
    try:
        ioloop.run_sync(bm.start)
    except Exception as e:
        if not isinstance(e, KeyboardInterrupt):