-
Notifications
You must be signed in to change notification settings - Fork 2
/
client.py
executable file
·85 lines (68 loc) · 2 KB
/
client.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#!/usr/bin/env python
# encoding: utf-8
import os
import sys
import signal
import time
from libs import daemon
import node
from config import config
import click
@click.group()
@click.option('-c', "--conf", default='config/config.json', help="Set config file")
@click.pass_context
def cli(ctx, conf):
ctx.ensure_object(dict)
cfg = config.read_cfg(conf)
ctx.obj['cfg'] = cfg
ctx.obj['pid'] = cfg['global']['pid']
@cli.command()
@click.pass_context
def start(ctx):
# auto fetch boot nodes
ctx.obj['cfg'] = config.auto_insert_boot_nodes(ctx.obj['cfg'])
# find out latest image tag
ctx.obj['cfg'] = config.check_image_latest_version(ctx.obj['cfg'])
start_daemon(ctx.obj['pid'], ctx.obj['cfg'])
@cli.command()
@click.pass_context
def stop(ctx):
stop_daemon(ctx.obj['pid'])
def sigterm_handler(signum, frame):
print('try to stop %s' % glue.pid)
sys.stdout.flush()
os.kill(glue.pid, signal.SIGTERM)
glue.join()
raise SystemExit(1)
def start_daemon(_pid, _cfg):
global glue
signal.signal(signal.SIGTERM, sigterm_handler)
if not os.getenv("DOCKER_MODE") == "True":
try:
daemon.daemonize(_pid)
except RuntimeError as e:
print(e, file=sys.stderr)
raise SystemExit(1)
glue = node.Monitor(_cfg)
glue.daemon = True
glue.start()
while True:
if not glue.is_alive():
print('%d: 服务进程丢失,重启进程' % time.time())
glue = node.Monitor(_cfg)
glue.daemon = True
glue.start()
print('%d: new pid=%d' % (time.time(), glue.pid))
sys.stdout.flush()
time.sleep(_cfg['global']['monitor_interval'])
def stop_daemon(_pid):
if os.path.exists(_pid):
with open(_pid) as _f:
os.kill(int(_f.read()), signal.SIGTERM)
print("Stop success")
else:
print('Not running', file=sys.stderr)
if __name__ == '__main__':
cli(obj={})
cli.add_command(start)
cli.add_command(stop)