X-Git-Url: http://average.org/gitweb/?a=blobdiff_plain;f=gps303%2Fcollector.py;h=be1bdeccc609c35b85bea167ceda15fed65bb6b9;hb=3dea189c7bb47f02db07b52fdcda53fdb986fd2b;hp=7ffa7526cbce36f3ff98d4d88570b97ee8c84e94;hpb=8be4295a5027349ebbf5242d131c5a942181f7a6;p=loctrkd.git diff --git a/gps303/collector.py b/gps303/collector.py index 7ffa752..be1bdec 100644 --- a/gps303/collector.py +++ b/gps303/collector.py @@ -1,36 +1,27 @@ """ TCP server that communicates with terminals """ -from getopt import getopt -from logging import getLogger, StreamHandler, DEBUG, INFO -from logging.handlers import SysLogHandler -from socket import socket, AF_INET, SOCK_STREAM, SOL_SOCKET, SO_REUSEADDR +from logging import getLogger +from socket import socket, AF_INET6, SOCK_STREAM, SOL_SOCKET, SO_REUSEADDR from time import time -import sys +from struct import pack import zmq -from .config import readconfig -from .gps303proto import handle_packet, make_response, LOGIN, set_config - -CONF = "/etc/gps303.conf" +from . import common +from .gps303proto import ( + HIBERNATION, + LOGIN, + inline_response, + parse_message, + proto_of_message, +) +from .zmsg import Bcast, Resp log = getLogger("gps303/collector") -class Bcast: - """Zmq message to broadcast what was received from the terminal""" - def __init__(self, imei, msg): - self.as_bytes = imei.encode() + msg.encode() - - -class Resp: - """Zmq message received from a third party to send to the terminal""" - def __init__(self, msg): - self.imei = msg[:16].decode() - self.payload = msg[16:] - - class Client: """Connected socket to the terminal plus buffer and metadata""" + def __init__(self, sock, addr): self.sock = sock self.addr = addr @@ -44,16 +35,23 @@ class Client: self.imei = None def recv(self): - """ Read from the socket and parse complete messages """ + """Read from the socket and parse complete messages""" try: segment = self.sock.recv(4096) except OSError: - log.warning("Reading from fd %d (IMEI %s): %s", - self.sock.fileno(), self.imei, e) + log.warning( + "Reading from fd %d (IMEI %s): %s", + self.sock.fileno(), + self.imei, + e, + ) return None if not segment: # Terminal has closed connection - log.info("EOF reading from fd %d (IMEI %s)", - self.sock.fileno(), self.imei) + log.info( + "EOF reading from fd %d (IMEI %s)", + self.sock.fileno(), + self.imei, + ) return None when = time() self.buffer += segment @@ -63,28 +61,38 @@ class Client: if framestart == -1: # No frames, return whatever we have break if framestart > 0: # Should not happen, report - log.warning("Undecodable data \"%s\" from fd %d (IMEI %s)", - self.buffer[:framestart].hex(), self.sock.fileno(), self.imei) + log.warning( + 'Undecodable data "%s" from fd %d (IMEI %s)', + self.buffer[:framestart].hex(), + self.sock.fileno(), + self.imei, + ) self.buffer = self.buffer[framestart:] # At this point, buffer starts with a packet frameend = self.buffer.find(b"\r\n", 4) if frameend == -1: # Incomplete frame, return what we have break - msg = parse_message(self.buffer[:frameend]) - self.buffer = self.buffer[frameend+2:] - if isinstance(msg, LOGIN): - self.imei = msg.imei - log.info("LOGIN from fd %d: IMEI %s", - self.sock.fileno(), self.imei) - msgs.append(msg) + packet = self.buffer[2:frameend] + self.buffer = self.buffer[frameend + 2 :] + if proto_of_message(packet) == LOGIN.PROTO: + self.imei = parse_message(packet).imei + log.info( + "LOGIN from fd %d (IMEI %s)", self.sock.fileno(), self.imei + ) + msgs.append((when, self.addr, packet)) return msgs def send(self, buffer): try: self.sock.send(b"xx" + buffer + b"\r\n") except OSError as e: - log.error("Sending to fd %d (IMEI %s): %s", - self.sock.fileno, self.imei, e) + log.error( + "Sending to fd %d (IMEI %s): %s", + self.sock.fileno, + self.imei, + e, + ) + class Clients: def __init__(self): @@ -97,7 +105,7 @@ class Clients: return fd def stop(self, fd): - clnt = by_fd[fd] + clnt = self.by_fd[fd] log.info("Stop serving fd %d (IMEI %s)", clnt.sock.fileno(), clnt.imei) clnt.close() if clnt.imei: @@ -105,27 +113,29 @@ class Clients: del self.by_fd[fd] def recv(self, fd): - clnt = by_fd[fd] + clnt = self.by_fd[fd] msgs = clnt.recv() + if msgs is None: + return None result = [] - for msg in msgs: - if isinstance(msg, LOGIN): + for when, peeraddr, packet in msgs: + if proto_of_message(packet) == LOGIN.PROTO: # Could do blindly... self.by_imei[clnt.imei] = clnt - result.append(clnt.imei, msg) + result.append((clnt.imei, when, peeraddr, packet)) return result def response(self, resp): if resp.imei in self.by_imei: - self.by_imei[resp.imei].send(resp.payload) + self.by_imei[resp.imei].send(resp.packet) -def runserver(opts, conf): +def runserver(conf): zctx = zmq.Context() zpub = zctx.socket(zmq.PUB) zpub.bind(conf.get("collector", "publishurl")) zsub = zctx.socket(zmq.SUB) zsub.connect(conf.get("collector", "listenurl")) - tcpl = socket(AF_INET, SOCK_STREAM) + tcpl = socket(AF_INET6, SOCK_STREAM) tcpl.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) tcpl.bind(("", conf.getint("collector", "port"))) tcpl.listen(5) @@ -149,35 +159,51 @@ def runserver(opts, conf): except zmq.Again: break elif sk == tcpfd: - clntsock, clntaddr = ctlsock.accept() + clntsock, clntaddr = tcpl.accept() topoll.append((clntsock, clntaddr)) else: - imei, msg = clients.recv(sk) - zpub.send(Bcast(imei, msg).as_bytes) - if msg is None or isinstance(msg, HIBERNATION): - log.debug("HIBERNATION from fd %d", sk) + received = clients.recv(sk) + if received is None: + log.debug( + "Terminal gone from fd %d (IMEI %s)", sk, imei + ) tostop.append(sk) + else: + for imei, when, peeraddr, packet in received: + proto = proto_of_message(packet) + zpub.send( + Bcast( + proto=proto, + imei=imei, + when=when, + peeraddr=peeraddr, + packet=packet, + ).packed + ) + if proto == HIBERNATION.PROTO: + log.debug( + "HIBERNATION from fd %d (IMEI %s)", + sk, + imei, + ) + tostop.append(sk) + respmsg = inline_response(packet) + if respmsg is not None: + clients.response( + Resp(imei=imei, packet=respmsg) + ) # poll queue consumed, make changes now for fd in tostop: + poller.unregister(fd) clients.stop(fd) - pollset.unregister(fd) for zmsg in tosend: clients.response(zmsg) for clntsock, clntaddr in topoll: fd = clients.add(clntsock, clntaddr) - pollset.register(fd) + poller.register(fd) except KeyboardInterrupt: pass if __name__.endswith("__main__"): - opts, _ = getopt(sys.argv[1:], "c:d") - opts = dict(opts) - conf = readconfig(opts["-c"] if "-c" in opts else CONF) - if sys.stdout.isatty(): - log.addHandler(StreamHandler(sys.stderr)) - else: - log.addHandler(SysLogHandler(address="/dev/log")) - log.setLevel(DEBUG if "-d" in opts else INFO) - log.info("starting with options: %s", opts) - runserver(opts, conf) + runserver(common.init(log))