api: Add snowmix reconnects, make it shutdown gracefully

master
informatic 2018-08-14 22:03:01 +02:00
parent 851a2d37b1
commit 0faecacc77
2 changed files with 21 additions and 4 deletions

View File

@ -20,4 +20,6 @@ ENV LC_ALL C.UTF-8
ENV FLASK_APP apiserver.py
ENV FLASK_ENV production
CMD python3 -u apiserver.py
STOPSIGNAL SIGKILL
CMD [ "/usr/bin/python3", "-u", "apiserver.py" ]

View File

@ -28,11 +28,16 @@ def cast(l, t, kl, default=None):
return l
class SnowmixClient(object):
reconnect = True
def __init__(self, host='127.0.0.1', port=9999):
self.connect(host, port)
self.sem = threading.Semaphore()
def connect(self, host, port):
self.host = host
self.port = port
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.settimeout(1.0)
self.sock.connect((host, port))
@ -52,13 +57,23 @@ class SnowmixClient(object):
def call(self, command, expect='MSG:'):
with self.sem:
self.flush_input()
try:
self.flush_input()
self.fd.write(command + '\r\n')
self.fd.flush()
except socket.error:
if self.reconnect:
self.connect(self.host, self.port)
raise
self.fd.write(command + '\r\n')
self.fd.flush()
while True:
line = self.fd.readline()
if not line:
raise Exception('Remote host closed socket')
if expect and line.startswith(expect):
line = line[len(expect):].strip()
if not line: