multi-user/replication_client.py

279 lines
8.3 KiB
Python
Raw Normal View History

2019-07-05 18:07:16 +02:00
import threading
import logging
import zmq
import time
2019-07-18 16:38:13 +02:00
from replication import ReplicatedDatablock, RepCommand
2019-07-05 18:07:16 +02:00
logging.basicConfig(level=logging.DEBUG)
2019-07-18 16:38:13 +02:00
logger = logging.getLogger(__name__)
2019-07-05 18:07:16 +02:00
2019-07-08 20:05:12 +02:00
STATE_INITIAL = 0
STATE_SYNCING = 1
STATE_ACTIVE = 2
2019-07-05 18:07:16 +02:00
class Client(object):
2019-07-18 18:15:01 +02:00
def __init__(self,factory=None, id='default'):
2019-07-07 12:22:45 +02:00
assert(factory)
2019-07-18 16:38:13 +02:00
self._rep_store = {}
self._net_client = ClientNetService(
store_reference=self._rep_store,
2019-07-18 18:15:01 +02:00
factory=factory,
id=id)
2019-07-07 12:22:45 +02:00
self._factory = factory
2019-07-05 18:07:16 +02:00
def connect(self,address="127.0.0.1",port=5560):
self._net_client.connect(address=address,port=port)
2019-07-05 18:47:40 +02:00
2019-07-07 12:22:45 +02:00
def disconnect(self):
2019-07-18 16:38:13 +02:00
self._net_client.stop()
@property
2019-07-18 16:38:13 +02:00
def state(self):
return self._net_client.state
2019-07-06 12:52:15 +02:00
def register(self, object):
2019-07-07 12:22:45 +02:00
"""
Register a new item for replication
"""
assert(object)
2019-07-08 20:05:12 +02:00
new_item = self._factory.construct_from_dcc(object)(owner="client", data=object)
2019-07-05 18:47:40 +02:00
if new_item:
2019-07-18 16:38:13 +02:00
logger.info("Registering {} on {}".format(object,new_item.uuid))
new_item.store(self._rep_store)
2019-07-18 16:38:13 +02:00
logger.info("Pushing changes...")
new_item.push(self._net_client.publish)
return new_item.uuid
2019-07-18 16:38:13 +02:00
else:
raise TypeError("Type not supported")
2019-07-07 12:22:45 +02:00
2019-07-08 20:05:12 +02:00
def pull(self,object=None):
2019-07-07 12:22:45 +02:00
pass
2019-07-08 20:05:12 +02:00
2019-07-07 12:22:45 +02:00
def unregister(self,object):
pass
2019-07-18 16:38:13 +02:00
2019-07-05 18:07:16 +02:00
class ClientNetService(threading.Thread):
2019-07-18 18:15:01 +02:00
def __init__(self,store_reference=None, factory=None,id="default"):
2019-07-18 16:38:13 +02:00
2019-07-05 18:07:16 +02:00
# Threading
threading.Thread.__init__(self)
2019-07-07 12:22:45 +02:00
self.name = "ClientNetLink"
2019-07-05 18:07:16 +02:00
self.daemon = True
2019-07-18 16:38:13 +02:00
self._exit_event = threading.Event()
self._factory = factory
self._store_reference = store_reference
2019-07-18 18:15:01 +02:00
self._id = id
2019-07-18 16:38:13 +02:00
assert(self._factory)
2019-07-05 18:07:16 +02:00
# Networking
self.context = zmq.Context.instance()
self.state = STATE_INITIAL
2019-07-05 18:07:16 +02:00
def connect(self,address='127.0.0.1', port=5560):
if self.state == STATE_INITIAL:
logger.debug("connecting on {}:{}".format(address,port))
self.snapshot = self.context.socket(zmq.DEALER)
self.snapshot.setsockopt(zmq.IDENTITY, self._id.encode())
self.snapshot.connect("tcp://{}:{}".format(address, port))
self.subscriber = self.context.socket(zmq.SUB)
self.subscriber.setsockopt_string(zmq.SUBSCRIBE, '')
self.subscriber.connect("tcp://{}:{}".format(address, port+1))
self.subscriber.linger = 0
2019-07-05 18:07:16 +02:00
self.publish = self.context.socket(zmq.PUSH)
self.publish.connect("tcp://{}:{}".format(address, port+2))
2019-07-05 18:07:16 +02:00
self.start()
2019-07-05 18:07:16 +02:00
def run(self):
2019-07-18 18:15:01 +02:00
logger.info("{} online".format(self._id))
2019-07-05 18:07:16 +02:00
poller = zmq.Poller()
poller.register(self.snapshot, zmq.POLLIN)
poller.register(self.subscriber, zmq.POLLIN)
poller.register(self.publish, zmq.POLLOUT)
2019-07-18 16:38:13 +02:00
while not self._exit_event.is_set():
"""NET OUT
Given the net state we do something:
SYNCING : Ask for snapshots
ACTIVE : Do nothing
"""
if self.state == STATE_INITIAL:
2019-07-18 18:15:01 +02:00
logger.debug('{} : request snapshot'.format(self._id))
2019-07-18 16:38:13 +02:00
self.snapshot.send(b"SNAPSHOT_REQUEST")
self.state = STATE_SYNCING
"""NET IN
Given the net state we do something:
SYNCING : Ask for snapshots
ACTIVE : Do nothing
"""
2019-07-18 18:15:01 +02:00
items = dict(poller.poll(10))
2019-07-18 16:38:13 +02:00
if self.snapshot in items:
if self.state == STATE_SYNCING:
datablock = ReplicatedDatablock.pull(self.snapshot, self._factory)
2019-07-18 18:15:01 +02:00
if datablock.buffer == 'SNAPSHOT_END':
self.state = STATE_ACTIVE
logger.debug('{} : snapshot done'.format(self._id))
2019-07-05 18:47:40 +02:00
2019-07-18 16:38:13 +02:00
# We receive updates from the server !
if self.subscriber in items:
if self.state == STATE_ACTIVE:
2019-07-18 18:15:01 +02:00
logger.debug("{} : Receiving changes from server".format(self._id))
2019-07-18 16:38:13 +02:00
datablock = ReplicatedDatablock.pull(self.subscriber, self._factory)
datablock.store(self._store_reference)
2019-07-05 18:07:16 +02:00
if not items:
2019-07-18 16:38:13 +02:00
logger.error("No request ")
2019-07-05 18:07:16 +02:00
self.snapshot.close()
self.subscriber.close()
self.publish.close()
self._exit_event.clear()
2019-07-05 21:17:37 +02:00
2019-07-18 16:38:13 +02:00
def setup(self,id="Client"):
pass
2019-07-05 21:17:37 +02:00
2019-07-05 18:07:16 +02:00
def stop(self):
2019-07-18 16:38:13 +02:00
self._exit_event.set()
2019-07-05 18:07:16 +02:00
#Wait the end of the run
while self._exit_event.is_set():
time.sleep(.1)
2019-07-07 12:22:45 +02:00
2019-07-05 18:47:40 +02:00
self.state = 0
class Server():
def __init__(self,config=None, factory=None):
self._rep_store = {}
self._net = ServerNetService(store_reference=self._rep_store, factory=factory)
2019-07-05 18:47:40 +02:00
def serve(self,port=5560):
self._net.listen(port=port)
2019-07-05 18:47:40 +02:00
def state(self):
return self._net.state
2019-07-05 18:47:40 +02:00
def stop(self):
self._net.stop()
2019-07-05 18:47:40 +02:00
class ServerNetService(threading.Thread):
def __init__(self,store_reference=None, factory=None):
2019-07-05 18:47:40 +02:00
# Threading
threading.Thread.__init__(self)
2019-07-07 12:22:45 +02:00
self.name = "ServerNetLink"
2019-07-05 18:47:40 +02:00
self.daemon = True
2019-07-18 16:38:13 +02:00
self._exit_event = threading.Event()
# Networking
self._rep_store = store_reference
2019-07-05 18:47:40 +02:00
self.context = zmq.Context.instance()
2019-07-07 12:22:45 +02:00
self.snapshot = None
self.publisher = None
self.pull = None
2019-07-05 18:47:40 +02:00
self.state = 0
self.factory = factory
2019-07-19 11:42:08 +02:00
self.clients = []
2019-07-05 18:47:40 +02:00
def listen(self, port=5560):
2019-07-07 12:22:45 +02:00
try:
# Update request
self.snapshot = self.context.socket(zmq.ROUTER)
self.snapshot.setsockopt(zmq.IDENTITY, b'SERVER')
self.snapshot.setsockopt(zmq.RCVHWM, 60)
self.snapshot.bind("tcp://*:{}".format(port))
2019-07-07 12:22:45 +02:00
# Update all clients
self.publisher = self.context.socket(zmq.PUB)
2019-07-19 11:42:08 +02:00
# self.publisher.setsockopt(zmq.IDENTITY,b'SERVER')
2019-07-07 12:22:45 +02:00
self.publisher.setsockopt(zmq.SNDHWM, 60)
self.publisher.bind("tcp://*:{}".format(port+1))
2019-07-07 12:22:45 +02:00
time.sleep(0.2)
# Update collector
self.pull = self.context.socket(zmq.PULL)
self.pull.setsockopt(zmq.RCVHWM, 60)
self.pull.bind("tcp://*:{}".format(port+2))
self.start()
2019-07-07 12:22:45 +02:00
except zmq.error.ZMQError:
2019-07-18 16:38:13 +02:00
logger.error("Address already in use, change net config")
2019-07-07 12:22:45 +02:00
2019-07-05 18:47:40 +02:00
def run(self):
2019-07-18 16:38:13 +02:00
logger.debug("Server is online")
2019-07-05 18:47:40 +02:00
poller = zmq.Poller()
poller.register(self.snapshot, zmq.POLLIN)
poller.register(self.pull, zmq.POLLIN)
2019-07-08 20:05:12 +02:00
self.state = STATE_ACTIVE
2019-07-05 18:47:40 +02:00
2019-07-18 16:38:13 +02:00
while not self._exit_event.is_set():
2019-07-08 20:05:12 +02:00
# Non blocking poller
socks = dict(poller.poll(1))
2019-07-08 20:05:12 +02:00
# Snapshot system for late join (Server - Client)
2019-07-18 16:38:13 +02:00
if self.snapshot in socks:
msg = self.snapshot.recv_multipart(zmq.DONTWAIT)
identity = msg[0]
request = msg[1]
if request == b"SNAPSHOT_REQUEST":
2019-07-19 11:42:08 +02:00
# Sending snapshots
2019-07-19 11:46:43 +02:00
for key, item in self._rep_store.items():
2019-07-19 11:42:08 +02:00
self.snapshot.send(identity, zmq.SNDMORE)
item.push(self.snapshot)
# Snapshot end
2019-07-18 16:38:13 +02:00
self.snapshot.send(identity, zmq.SNDMORE)
2019-07-19 11:42:08 +02:00
RepCommand(owner='server',data='SNAPSHOT_END').push(self.snapshot)
2019-07-18 16:38:13 +02:00
2019-07-08 20:05:12 +02:00
# Regular update routing (Clients / Client)
if self.pull in socks:
2019-07-18 16:38:13 +02:00
logger.debug("Receiving changes from client")
datablock = ReplicatedDatablock.pull(self.pull, self.factory)
2019-07-19 11:20:22 +02:00
2019-07-18 16:38:13 +02:00
datablock.store(self._rep_store)
# Update all clients
datablock.push(self.publisher)
2019-07-07 12:22:45 +02:00
self.snapshot.close()
self.pull.close()
self.publisher.close()
self._exit_event.clear()
def stop(self):
self._exit_event.set()
#Wait the end of the run
while self._exit_event.is_set():
time.sleep(.1)
2019-07-07 12:22:45 +02:00
self.state = 0