multi-user/net_components.py

363 lines
11 KiB
Python
Raw Normal View History

2019-03-25 14:56:09 +01:00
import collections
import logging
import threading
2019-04-04 18:02:51 +02:00
from uuid import uuid4
import binascii
import os
from random import randint
2019-02-11 15:48:07 +01:00
import time
2019-03-15 17:37:02 +01:00
from enum import Enum
try:
from .libs import umsgpack, zmq
except:
from libs import umsgpack, zmq
logger = logging.getLogger(__name__)
2019-03-14 17:04:41 +01:00
logging.basicConfig(level=logging.DEBUG)
2019-03-25 14:56:09 +01:00
CONNECT_TIMEOUT = 2
2019-03-15 16:50:59 +01:00
WAITING_TIME = 0.001
2019-04-08 12:53:14 +02:00
SERVER_MAX = 1
2019-02-22 16:46:35 +01:00
2019-04-08 17:01:02 +02:00
stop = False
2019-04-08 12:53:14 +02:00
def zpipe(ctx):
"""build inproc pipe for talking to threads
2019-03-25 14:56:09 +01:00
2019-04-08 12:53:14 +02:00
mimic pipe used in czmq zthread_fork.
Returns a pair of PAIRs connected via inproc
"""
a = ctx.socket(zmq.PAIR)
b = ctx.socket(zmq.PAIR)
a.linger = b.linger = 0
a.hwm = b.hwm = 1
iface = "inproc://%s" % binascii.hexlify(os.urandom(8))
a.bind(iface)
b.connect(iface)
return a, b
2019-04-08 12:53:14 +02:00
class State(Enum):
INITIAL = 1
SYNCING = 2
ACTIVE = 3
2019-03-15 17:37:02 +01:00
2019-02-13 11:55:18 +01:00
class RCFMessage(object):
"""
Message is formatted on wire as 2 frames:
frame 0: key (0MQ string) // property path
2019-02-14 15:30:35 +01:00
frame 1: id (0MQ string) // property path
frame 2: mtype (0MQ string) // property path
frame 3: body (blob) // Could be any data
"""
key = None # key (string)
id = None # User (string)
mtype = None # data mtype (string)
body = None # data blob
2019-04-04 18:02:51 +02:00
uuid = None
def __init__(self, key=None, uuid=None, id=None, mtype=None, body=None):
2019-04-04 18:02:51 +02:00
if uuid is None:
uuid = uuid4().bytes
self.key = key
2019-04-04 18:02:51 +02:00
self.uuid = uuid
self.mtype = mtype
self.body = body
2019-02-14 15:30:35 +01:00
self.id = id
2019-03-25 14:56:09 +01:00
def store(self, dikt):
"""Store me in a dict if I have anything to store"""
# this currently erasing old value
if self.key is not None:
2019-02-22 16:46:35 +01:00
dikt[self.key] = self
2019-03-28 15:02:21 +01:00
# elif self.key in dikt:
# del dikt[self.key]
def send(self, socket):
"""Send key-value message to socket; any empty frames are sent as such."""
2019-02-22 16:46:35 +01:00
key = ''.encode() if self.key is None else self.key.encode()
mtype = ''.encode() if self.mtype is None else self.mtype.encode()
body = ''.encode() if self.body is None else umsgpack.packb(self.body)
2019-03-06 14:01:33 +01:00
id = ''.encode() if self.id is None else self.id
2019-02-22 16:46:35 +01:00
try:
socket.send_multipart([key, id, mtype, body])
2019-02-22 16:46:35 +01:00
except:
logger.info("Fail to send {} {}".format(key,id))
@classmethod
def recv(cls, socket):
"""Reads key-value message from socket, returns new kvmsg instance."""
key, id, mtype, body = socket.recv_multipart(zmq.DONTWAIT)
key = key.decode() if key else None
id = id if id else None
mtype = mtype.decode() if body else None
body = umsgpack.unpackb(body) if body else None
return cls(key=key, id=id, mtype=mtype, body=body)
def dump(self):
if self.body is None:
size = 0
data = 'NULL'
else:
size = len(self.body)
data = repr(self.body)
print("[key:{key}][size:{size}][mtype:{mtype}] {data}".format(
key=self.key,
size=size,
mtype=self.mtype,
data=data,
))
class RCFClient(object):
ctx = None
pipe = None
agent = None
def __init__(self):
self.ctx = zmq.Context()
self.pipe, peer = zpipe(self.ctx)
self.agent = threading.Thread(
target=rcf_client_agent, args=(self.ctx, peer))
self.agent.daemon = True
self.agent.start()
def connect(self, address, port):
self.pipe.send_multipart([b"CONNECT", (address.encode() if isinstance(
address, str) else address), b'%d' % port])
def set(self, key, value):
"""Set new value in distributed hash table
2019-04-08 18:21:48 +02:00
Sends [SET][key][value] to the agent
"""
self.pipe.send_multipart([b"SET", umsgpack.packb(key), umsgpack.packb(value)])
2019-04-08 12:53:14 +02:00
2019-04-08 18:21:48 +02:00
def get(self, key):
"""Lookup value in distributed hash table
Sends [GET][key] to the agent and waits for a value response
If there is no clone available, will eventually return None.
"""
self.pipe.send_multipart([b"GET", umsgpack.packb(key)])
try:
reply = self.pipe.recv_multipart()
except KeyboardInterrupt:
return
else:
return umsgpack.unpackb(reply[0])
2019-04-08 17:01:02 +02:00
def exit(self):
if self.agent.is_alive():
global stop
stop = True
2019-03-25 14:56:09 +01:00
2019-04-08 12:53:14 +02:00
class RCFServer(object):
address = None # Server address
port = None # Server port
snapshot = None # Snapshot socket
subscriber = None # Incoming updates
def __init__(self, ctx, address, port,id):
2019-04-08 12:53:14 +02:00
self.address = address
self.port = port
self.snapshot = ctx.socket(zmq.DEALER)
self.snapshot.linger = 0
self.snapshot.connect("tcp://{}:{}".format(address.decode(), port))
self.snapshot.setsockopt(zmq.IDENTITY, id)
2019-04-08 12:53:14 +02:00
self.subscriber = ctx.socket(zmq.SUB)
self.subscriber.setsockopt_string(zmq.SUBSCRIBE, '')
self.subscriber.connect("tcp://{}:{}".format(address.decode(), port+1))
2019-04-08 12:53:14 +02:00
self.subscriber.linger = 0
print("connected on tcp://{}:{}".format(address.decode(), port))
2019-04-08 12:53:14 +02:00
class RCFClientAgent(object):
ctx = None
2019-04-08 12:53:14 +02:00
pipe = None
property_map = None
publisher = None
id = None
state = State.INITIAL
server = None
def __init__(self, ctx, pipe):
self.ctx = ctx
self.pipe = pipe
2019-04-08 18:21:48 +02:00
self.property_map = {}
self.id = b"test"
2019-04-08 12:53:14 +02:00
self.state = State.INITIAL
self.server = None
self.publisher = self.ctx.socket(zmq.PUSH) # push update socket
2019-04-08 12:53:14 +02:00
self.publisher.setsockopt(zmq.IDENTITY, self.id)
self.publisher.setsockopt(zmq.SNDHWM, 60)
self.publisher.linger = 0
def control_message(self):
2019-04-08 12:53:14 +02:00
msg = self.pipe.recv_multipart()
command = msg.pop(0)
if command == b"CONNECT":
address = msg.pop(0)
port = int(msg.pop(0))
if self.server is None:
self.server = RCFServer(self.ctx, address, port, self.id)
self.publisher.connect("tcp://{}:{}".format(address.decode(), port+2))
2019-04-08 12:53:14 +02:00
else:
logger.error("E: too many servers (max. %i)", SERVER_MAX)
elif command == b"SET":
key,value = msg
2019-04-08 12:53:14 +02:00
# Send key-value pair on to server
rcfmsg = RCFMessage(key=umsgpack.unpackb(key),id=self.id ,mtype="",body=umsgpack.unpackb(value))
rcfmsg.store(self.property_map)
rcfmsg.send(self.publisher)
2019-04-08 18:21:48 +02:00
elif command == b"GET":
key = umsgpack.unpackb(msg[0])
value = self.property_map.get(key)
self.pipe.send(umsgpack.packb(value.body) if value else b'')
2019-03-25 14:56:09 +01:00
def rcf_client_agent(ctx, pipe):
agent = RCFClientAgent(ctx, pipe)
2019-04-08 12:53:14 +02:00
server = None
2019-04-08 17:01:02 +02:00
global stop
while True:
if stop:
break
# logger.info("asdasd")
2019-04-08 12:53:14 +02:00
poller = zmq.Poller()
poller.register(agent.pipe, zmq.POLLIN)
server_socket = None
2019-04-08 17:01:02 +02:00
2019-04-08 12:53:14 +02:00
if agent.state == State.INITIAL:
server = agent.server
if agent.server:
logger.info("I: waiting for server at %s:%d...",
server.address, server.port)
2019-04-08 12:53:14 +02:00
server.snapshot.send(b"SNAPSHOT_REQUEST")
agent.state = State.SYNCING
server_socket = server.snapshot
2019-04-08 12:53:14 +02:00
elif agent.state == State.SYNCING:
server_socket = server.snapshot
2019-04-08 12:53:14 +02:00
elif agent.state == State.ACTIVE:
server_socket = server.subscriber
if server_socket:
poller.register(server_socket, zmq.POLLIN)
try:
2019-04-08 17:01:02 +02:00
items = dict(poller.poll(1))
2019-04-08 12:53:14 +02:00
except:
pass
2019-04-08 12:53:14 +02:00
if agent.pipe in items:
agent.control_message()
elif server_socket in items:
rcfmsg = RCFMessage.recv(server_socket)
if agent.state == State.SYNCING:
# Store snapshot
if rcfmsg.key == "SNAPSHOT_END":
logger.info("snapshot complete")
agent.state = State.ACTIVE
else:
rcfmsg.store(agent.property_map)
elif agent.state == State.ACTIVE:
if rcfmsg.id != agent.id:
rcfmsg.store(agent.property_map)
action = "update" if rcfmsg.body else "delete"
logging.info("I: received from {}:{},{} {}".format(server.address,rcfmsg.body.id, server.port, action))
else:
logger.info("IDLE")
2019-04-08 17:01:02 +02:00
logger.info("exit thread")
stop = False
# else: else
# agent.state = State.INITIAL
2019-04-08 12:53:14 +02:00
class RCFServerAgent():
def __init__(self, context=zmq.Context.instance(), id="admin"):
2019-02-11 16:25:08 +01:00
self.context = context
2019-02-11 16:25:08 +01:00
self.pub_sock = None
self.request_sock = None
self.collector_sock = None
2019-02-11 16:25:08 +01:00
self.poller = None
self.property_map = {}
2019-02-11 16:25:08 +01:00
self.id = id
self.bind_ports()
# Main client loop registration
self.tick()
2019-02-11 16:25:08 +01:00
logger.info("{} client initialized".format(id))
def bind_ports(self):
# Update all clients
self.pub_sock = self.context.socket(zmq.PUB)
self.pub_sock.setsockopt(zmq.SNDHWM, 60)
self.pub_sock.bind("tcp://*:5556")
2019-02-11 15:48:07 +01:00
time.sleep(0.2)
# Update request
self.request_sock = self.context.socket(zmq.ROUTER)
2019-02-22 16:46:35 +01:00
self.request_sock.setsockopt(zmq.IDENTITY, b'SERVER')
self.request_sock.setsockopt(zmq.RCVHWM, 60)
self.request_sock.bind("tcp://*:5555")
# Update collector
self.collector_sock = self.context.socket(zmq.PULL)
self.collector_sock.setsockopt(zmq.RCVHWM, 60)
self.collector_sock.bind("tcp://*:5557")
2019-02-11 15:48:07 +01:00
2019-02-11 16:25:08 +01:00
# poller for socket aggregation
self.poller = zmq.Poller()
self.poller.register(self.request_sock, zmq.POLLIN)
self.poller.register(self.collector_sock, zmq.POLLIN)
2019-02-11 16:25:08 +01:00
2019-04-08 12:53:14 +02:00
def tick(self):
2019-02-11 16:25:08 +01:00
logger.info("{} server launched".format(id))
2019-02-11 15:48:07 +01:00
while True:
2019-03-25 14:56:09 +01:00
# Non blocking poller
socks = dict(self.poller.poll(1000))
2019-02-11 16:25:08 +01:00
# Snapshot system for late join (Server - Client)
if self.request_sock in socks:
2019-02-22 16:46:35 +01:00
msg = self.request_sock.recv_multipart(zmq.DONTWAIT)
2019-03-06 14:01:33 +01:00
identity = msg[0]
request = msg[1]
print("asdasd")
if request == b"SNAPSHOT_REQUEST":
pass
else:
logger.info("Bad snapshot request")
break
2019-03-06 14:01:33 +01:00
for k, v in self.property_map.items():
logger.info(
"Sending {} snapshot to {}".format(k, identity))
self.request_sock.send(identity, zmq.SNDMORE)
v.send(self.request_sock)
2019-03-06 14:01:33 +01:00
msg_end_snapshot = RCFMessage(key="SNAPSHOT_END", id=identity)
self.request_sock.send(identity, zmq.SNDMORE)
msg_end_snapshot.send(self.request_sock)
2019-02-22 16:46:35 +01:00
logger.info("done")
# Regular update routing (Clients / Client)
elif self.collector_sock in socks:
msg = RCFMessage.recv(self.collector_sock)
# Update all clients
2019-02-22 16:46:35 +01:00
msg.store(self.property_map)
msg.send(self.pub_sock)