Esempio n. 1
0
def run():
    global g_mp3chunker
    server = None

    configfile = 'default.cfg'
    daemon = False
    kill   = False
    try:
        opts, args = getopt.getopt(sys.argv[1:], 'dhc:k:', ['daemon', 'help', 'config=', 'kill='])

        for opt, arg in opts:
            if opt in ('-h', '--help'):
                usage()
                sys.exit(0)
            if opt in ('-c', '--config'):
                configfile = arg 
            if opt in ('-d', '--daemon'):
                daemon = True
            if opt in ('-k', '--kill'):
                kill = True
                pidfile = arg

    except getopt.GetoptError:
        usage()
        sys.exit(2)

    if kill:
        retcode = killpid(pidfile)
        sys.exit(retcode)
    
    if not os.path.isfile(configfile):
        print >> sys.stderr, "Config file %s does not exist!" % (configfile)
        usage()
        sys.exit(1)

    if daemon:
        util.daemonize('.')

    start(configfile)
Esempio n. 2
0
async def fetch_ticker():
    logging.basicConfig(filename=fetch_ticker.log_file, level=logging.INFO)
    session = fetch_ticker.session
    while True:
        try:
            responses = []
            for coin in coins.coins:
                responses.append(await session.get('https://www.okex.com/api/v1/ticker.do?symbol=%s_btc' % coin))
            prices = []
            for response in responses:
                jdata = response.json()
                url = response.url
                code = url.split('?')[1].split('=')[1].split('_')[0]
                price = float(jdata['ticker']['last'])
                prices.append({'code': code, 'price': price})
                util.write_values(code, price)
            prices = sorted(prices, key=lambda x: x['price'])
            write_to_aggs(prices[-6:-1][::-1], 'bts_price_top5')
            write_to_aggs(prices[:5], 'bts_price_bottom5')
        except Exception as e:
            logging.error(e)
            logging.error(traceback.format_exc())
        time.sleep(45)

if __name__ == '__main__':
    args = parse_args()
    util.daemonize(fetch_ticker,
                   os.path.join(os.getcwd(), 'pid_ticker.txt'),
                   os.path.join(os.getcwd(), 'log_ticker.txt'),
                   args.debug)
Esempio n. 3
0
import logging
import signal

from tornado import ioloop
from tornado.web import Application
import tornado.httpserver

from tcp_server import CtrlServer, MyTCPServer
from zmq_server import zmq_server
import conf
from conn import Conn
import util

if __name__ == "__main__":
    if conf.DAEMONIZE:
        util.daemonize()
    util.init_logging("log/gate_server.log", colorfy=True)

    handlers = [
        (r'/', Conn),
        (r'/snappy/', Conn, dict(compress="snappy", binary=True,
                                 conn_tag='SP')),
        (r'/msgpack-snappy-skip/', Conn,
         dict(msgpack=True,
              compress="snappy",
              skip_size=512,
              binary=True,
              conn_tag='MP-SP-skip')),
        (r'/msgpack-lz4-skip/', Conn,
         dict(msgpack=True,
              compress="lz4",
Esempio n. 4
0
def main(argv):
	ret = int(0)

	pid_file_path      = f'{argv[2]}_pid.text'
	cmd_pipe_file_path = f'{argv[2]}_pipecmd'
	log_file           = f'{argv[2]}_log.text'

	pid = daemonize(argv[1])

	f = open(pid_file_path, 'w+')
	f.write(f"{pid}\n{cmd_pipe_file_path}\n{log_file}\n{argv[1]}\n{argv[3]}\n")
	f.close()

	signal(SIGILL , sigHandler)
	signal(SIGTRAP, sigHandler)
	signal(SIGINT , sigHandler)
	signal(SIGHUP , sigHandler)
	signal(SIGTERM, sigHandler)
	signal(SIGSEGV, sigHandler)

	logging.basicConfig(handlers = [ RotatingFileHandler(log_file, maxBytes = int(argv[10]), backupCount = int(argv[11])) ],
	                    level    = logging.INFO,
	                    format   = '%(asctime)s - %(levelname)s - %(message)s',
	                    datefmt  = '%Y%m%d%H%M%S')

	'''
 	except IOError:
 		sys.stderr.write(f"Creating log file failed: {e.errno} - {e.strerror}\n")
 		sys.exit(1)

 	try:
 		CMD_PIPE_FILE = open(CMD_PIPE_FILE_PATH, "r")

 	except IOError:
 		sys.stderr.write(f"Opeing cmd pipe file failed: {e.errno} - {e.strerror}\n")
  		sys.exit(1)

 	ret = runBot(logFile, BINANCE_PAIR, binance_apiKey, binance_sekKey)
	'''

	bot1 = bot()

	try:
		bot1.loadCfg(pid                 = pid,
		             botId               = argv[2],
		             binance_apikey      = getenv('BINANCE_APIKEY', 'NOTDEF_APIKEY'),
		             binance_sekkey      = getenv('BINANCE_SEKKEY', 'NOTDEF_APIKEY'),
		             work_path           = argv[1],
		             pid_file_path       = pid_file_path,
		             cmd_pipe_file_path  = cmd_pipe_file_path,
		             binance_pair        = argv[3],
		             fast_ema            = int(argv[4]),
		             fast_ema_offset     = int(argv[5]),
		             slow_ema            = int(argv[6]),
		             slow_ema_offset     = int(argv[7]),
		             time_sample         = argv[8],
		             notification        = argv[9],
		             max_timeout_to_exit = int(argv[12]),
		             retry_timeout       = int(argv[13]) )

	except Expcepton as e:
		endBot(1, f"BOT Exeption: initialization error: {e}")

	try:
		ret = bot1.connectBinance()
		if ret != 0:
			endBot(ret, f"BOT connect Biance status return ERROR: [{ret}]")

		ret = bot1.walletStatus()
		if ret != 0:
			endBot(ret, f"BOT wallet status return ERROR: [{ret}]")

		ret = bot1.loadData()
		if ret != 0:
			endBot(ret, f"BOT load data return ERROR: [{ret}]")

		ret = bot1.start()
		if ret != 0:
			endBot(ret, f"BOT start return ERROR: [{ret}]")

	except Exception as e:
		endBot(ret, f"BOT EXCEPTION! Exit: {e}")

#	CMD_PIPE_FILE.close()
	endBot(ret, f"BOT return: [{ret}]")
Esempio n. 5
0
	return app.myBird.tick()


@app.route('/spawn')
def spawn():
	return app.myBird.spawn()

@app.route('/die')
def die():
	logging.info("Bye.")
	reactor.stop()
	return "Bye"
	# return app.myBird.die()
		
logging.debug("I was called like this: %s" % (sys.argv))

if os.environ.get('MOMMA_BIRD'):
	logging.debug("I'm a BABY!")
	logging.info("ENV says momma is %s" % os.environ.get('MOMMA_BIRD'))
	util.daemonize()
	app.myBird.momma = os.environ.get('MOMMA_BIRD')


resource = WSGIResource(reactor, reactor.getThreadPool(), app)
site = Site(resource)
restartListener(app.myBird.port)
gossiploop = task.LoopingCall(gossip)
tickloop = task.LoopingCall(tick)
gossiploop.start(CONFIG['gossip_interval'])
tickloop.start(CONFIG['tick_interval'])
reactor.run()
Esempio n. 6
0
def start(port=443, daemonize=True, http_redirect_port=None):
    if port < 1024 and not os.getuid() == 0:
        print('Port %s requires root permissions.' % port, file=sys.stderr)
        sys.exit(1)

    util.setup_logging('log/web.txt')

    if http_redirect_port is not None:
        logging.info('Redirecting http://:%s to https://:%s',
                     http_redirect_port, port)
        tornado.web.Application([(r'/.well-known/acme-challenge/(.+)',
                                  CertbotHandler),
                                 (r'/.*', HttpRedirectHandler, {
                                     'https_port': port
                                 })]).listen(http_redirect_port)

    logic = donationswap.Donationswap('app-config.json')

    def args(kv=None):
        result = {
            'logic': logic,
        }
        if kv:
            result.update(kv)
        return result

    application = tornado.web.Application(
        [
            (r'/', TemplateHandler, args({'page_name': 'index.html'})),
            (r'/contact/?', TemplateHandler, args(
                {'page_name': 'contact.html'})),
            (r'/howto/?', TemplateHandler, args({'page_name': 'howto.html'})),
            (r'/start/?', TemplateHandler, args({'page_name': 'start.html'})),
            (r'/charities/?', TemplateHandler,
             args({'page_name': 'charities.html'})),
            (r'/match/?', TemplateHandler, args({'page_name': 'match.html'})),
            (r'/offer/?', TemplateHandler, args({'page_name': 'offer.html'})),
            (r'/ajax/(.+)', AjaxHandler, args()),
            (r'/special-secret-admin/(.+)', AdminHandler, args()),
            (r'/housekeeping/?', HousekeepingHandler, args()),
        ],
        cookie_secret=logic.get_cookie_key(),
        static_path=os.path.join(os.path.dirname(__file__), 'static'),
    )

    if os.path.exists(
            '/etc/letsencrypt/live/donationswap.eahub.org/privkey.pem'):
        ssl_context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
        ssl_context.load_cert_chain(
            '/etc/letsencrypt/live/donationswap.eahub.org/fullchain.pem',
            '/etc/letsencrypt/live/donationswap.eahub.org/privkey.pem')
    else:
        logging.warning(
            'SSL Certificate not found. Traffic will NOT be encrypted.')
        ssl_context = None

    logging.info('Starting webserver.')

    server = tornado.httpserver.HTTPServer(application,
                                           ssl_options=ssl_context)

    server.listen(port)

    if daemonize:
        util.daemonize('/var/run/webserver-%s.pid' % port)

    if os.geteuid() == 0:  # we don't need root privileges any more
        util.drop_privileges()

    tornado.ioloop.IOLoop.current().start()
Esempio n. 7
0
                prices = []
                for response in responses:
                    jdata = response.json()[
                        0]  # Becasue it returns an array of arrays
                    url = response.url
                    code = url.split('?')[1].split('&')[0].split('=')[1].split(
                        '_')[0]
                    open_ = float(jdata[1])
                    close_ = float(jdata[4])
                    pct_chg = (close_ -
                               open_) / open_ * 100.0  # all day trading...
                    prices.append({
                        'code': code,
                        'open': open_,
                        'close': close_,
                        'pct_chg': pct_chg
                    })
                prices = sorted(prices, key=lambda x: x['pct_chg'])
                write_to_aggs(prices[-6:-1][::-1], 'bts_change_%s_top5' % k)
                write_to_aggs(prices[:5], 'bts_change_%s_bottom5' % k)
        except Exception as e:
            logging.error(e)
            logging.error(traceback.format_exc())
        time.sleep(60)


if __name__ == '__main__':
    args = parse_args()
    util.daemonize(fetch_kline, os.path.join(os.getcwd(), 'pid_kline.txt'),
                   os.path.join(os.getcwd(), 'log_kline.txt'), args.debug)