team-3/src/c3nav/mesh/consumers.py

260 lines
10 KiB
Python
Raw Normal View History

2022-04-15 20:02:42 +02:00
import traceback
from asgiref.sync import async_to_sync
2023-10-05 01:36:24 +02:00
from channels.generic.websocket import WebsocketConsumer, JsonWebsocketConsumer
2023-10-03 17:51:49 +02:00
from django.utils import timezone
2023-10-04 22:25:15 +02:00
from c3nav.mesh.utils import get_mesh_comm_group
from c3nav.mesh import messages
2023-10-04 15:44:54 +02:00
from c3nav.mesh.messages import MeshMessage, BROADCAST_ADDRESS
from c3nav.mesh.models import MeshNode, NodeMessage
# noinspection PyAttributeOutsideInit
class MeshConsumer(WebsocketConsumer):
def connect(self):
2022-04-15 20:57:11 +02:00
# todo: auth
self.uplink_node = None
2023-10-05 01:36:24 +02:00
self.log_text(None, "new mesh websocket connection")
self.dst_nodes = set()
self.accept()
def disconnect(self, close_code):
2023-10-05 01:36:24 +02:00
self.log_text(self.uplink_node, "mesh websocket disconnected")
if self.uplink_node is not None:
2023-10-03 17:51:49 +02:00
# leave broadcast group
async_to_sync(self.channel_layer.group_add)(get_mesh_comm_group(BROADCAST_ADDRESS), self.channel_name)
2023-10-03 17:51:49 +02:00
# remove all other destinations
self.remove_dst_nodes(self.dst_nodes)
2023-10-05 04:05:29 +02:00
def send_msg(self, msg, sender=None):
2023-10-05 02:34:42 +02:00
# print("sending", msg)
# self.log_text(msg.dst, "sending %s" % msg)
self.send(bytes_data=msg.encode())
2023-10-05 04:05:29 +02:00
async_to_sync(self.channel_layer.group_send)("mesh_msg_sent", {
"type": "mesh.msg_sent",
"timestamp": timezone.now().strftime("%d.%m.%y %H:%M:%S.%f"),
"channel": self.channel_name,
"sender": sender,
"uplink": self.uplink_node.address if self.uplink_node else None,
"recipient": msg.dst,
#"msg": msg.tojson(), # not doing this part for privacy reasons
})
2022-04-06 22:56:08 +02:00
def receive(self, text_data=None, bytes_data=None):
if bytes_data is None:
return
2022-04-15 20:02:42 +02:00
try:
2023-10-04 15:44:54 +02:00
msg = messages.MeshMessage.decode(bytes_data)
2022-04-15 20:02:42 +02:00
except Exception:
traceback.print_exc()
return
if msg.dst != messages.ROOT_ADDRESS and msg.dst != messages.PARENT_ADDRESS:
print('Received message for forwarding:', msg)
# todo: this message isn't for us, forward it
return
2023-10-05 02:34:42 +02:00
#print('Received message:', msg)
2022-04-15 20:57:11 +02:00
src_node, created = MeshNode.objects.get_or_create(address=msg.src)
if isinstance(msg, messages.MeshSigninMessage):
self.uplink_node = src_node
# log message, since we will not log it further down
self.log_received_message(src_node, msg)
# inform signed in uplink node about its layer
self.send_msg(messages.MeshLayerAnnounceMessage(
2022-04-15 20:02:42 +02:00
src=messages.ROOT_ADDRESS,
2022-04-06 17:25:46 +02:00
dst=msg.src,
layer=messages.NO_LAYER
2022-04-06 22:56:08 +02:00
))
2022-04-15 20:57:11 +02:00
2023-10-03 17:51:49 +02:00
# add signed in uplink node to broadcast group
async_to_sync(self.channel_layer.group_add)('mesh_broadcast', self.channel_name)
2022-04-15 20:57:11 +02:00
2023-10-03 17:51:49 +02:00
# kick out other consumers talking to the same uplink
async_to_sync(self.channel_layer.group_send)(get_mesh_comm_group(msg.src), {
2023-10-03 17:51:49 +02:00
"type": "mesh.uplink_consumer",
"name": self.channel_name,
})
# add this node as a destination that this uplink handles (duh)
2023-10-05 00:03:08 +02:00
self.add_dst_nodes(nodes=(src_node, ))
2022-04-15 20:57:11 +02:00
2023-10-02 22:02:25 +02:00
return
if self.uplink_node is None:
print('Expected sign-in message, but got a different one!')
self.close()
return
2023-10-02 22:02:25 +02:00
self.log_received_message(src_node, msg)
2022-04-15 20:02:42 +02:00
if isinstance(msg, messages.MeshAddDestinationsMessage):
2023-10-05 02:34:42 +02:00
self.add_dst_nodes(addresses=msg.addresses)
if isinstance(msg, messages.MeshRemoveDestinationsMessage):
2023-10-05 02:34:42 +02:00
self.remove_dst_nodes(addresses=msg.addresses)
2023-10-03 17:51:49 +02:00
def mesh_uplink_consumer(self, data):
# message handler: if we are not the given uplink, leave this group
if data["name"] != self.channel_name:
2023-10-05 01:36:24 +02:00
self.log_text(self.uplink_node, "shutting down, uplink now served by new consumer")
2023-10-03 17:51:49 +02:00
self.close()
def mesh_dst_node_uplink(self, data):
# message handler: if we are not the given uplink, leave this group
if data["uplink"] != self.uplink_node.address:
2023-10-05 01:36:24 +02:00
self.log_text(data["address"], "node now served by new consumer")
2023-10-03 17:51:49 +02:00
self.remove_dst_nodes((data["address"], ))
def mesh_send(self, data):
2023-10-05 04:05:29 +02:00
print("mesh_send", data)
self.send_msg(MeshMessage.fromjson(data["msg"]), data["sender"])
2023-10-04 15:44:54 +02:00
def log_received_message(self, src_node: MeshNode, msg: messages.MeshMessage):
2023-10-05 04:05:29 +02:00
as_json = msg.tojson()
async_to_sync(self.channel_layer.group_send)("mesh_msg_received", {
"type": "mesh.msg_received",
"timestamp": timezone.now().strftime("%d.%m.%y %H:%M:%S.%f"),
"channel": self.channel_name,
"uplink": self.uplink_node.address if self.uplink_node else None,
"msg": as_json,
})
2022-04-15 20:57:11 +02:00
NodeMessage.objects.create(
uplink_node=self.uplink_node,
src_node=src_node,
2022-04-15 20:02:42 +02:00
message_type=msg.msg_id,
2023-10-05 04:05:29 +02:00
data=as_json,
2022-04-15 20:02:42 +02:00
)
2022-04-15 20:57:11 +02:00
2023-10-05 01:36:24 +02:00
def log_text(self, address, text):
address = getattr(address, 'address', address)
async_to_sync(self.channel_layer.group_send)("mesh_log", {
"type": "mesh.log_entry",
"timestamp": timezone.now().strftime("%d.%m.%y %H:%M:%S.%f"),
"channel": self.channel_name,
"uplink": self.uplink_node.address if self.uplink_node else None,
"node": address,
"text": text,
})
2023-10-05 00:03:08 +02:00
def add_dst_nodes(self, nodes=None, addresses=None):
nodes = list(nodes) if nodes else []
addresses = set(addresses) if addresses else set()
2023-10-05 01:36:24 +02:00
node_addresses = set(node.address for node in nodes)
2023-10-05 00:03:08 +02:00
missing_addresses = addresses - set(node.address for node in nodes)
if missing_addresses:
MeshNode.objects.bulk_create(
[MeshNode(address=address) for address in missing_addresses],
ignore_conflicts=True
)
2023-10-05 01:36:24 +02:00
addresses |= node_addresses
2023-10-05 00:03:08 +02:00
addresses |= missing_addresses
for address in addresses:
2023-10-05 01:36:24 +02:00
self.log_text(address, "destination added")
# create group name for this address
group = get_mesh_comm_group(address)
# if we aren't handling this address yet, join the group
if address not in self.dst_nodes:
async_to_sync(self.channel_layer.group_add)(group, self.channel_name)
self.dst_nodes.add(address)
# tell other consumers to leave the group
async_to_sync(self.channel_layer.group_send)(group, {
2023-10-03 17:51:49 +02:00
"type": "mesh.dst_node_uplink",
"node": address,
"uplink": self.uplink_node.address
})
# tell the node to dump its current information
self.send_msg(
messages.ConfigDumpMessage(
src=messages.ROOT_ADDRESS,
dst=address,
)
)
# add the stuff to the db as well
2023-10-03 17:51:49 +02:00
MeshNode.objects.filter(address__in=addresses).update(
uplink_id=self.uplink_node.address,
last_signin=timezone.now(),
)
def remove_dst_nodes(self, addresses):
for address in tuple(addresses):
2023-10-05 01:36:24 +02:00
self.log_text(address, "destination removed")
2023-10-03 17:51:49 +02:00
# create group name for this address
group = get_mesh_comm_group(address)
2023-10-03 17:51:49 +02:00
# leave the group
if address in self.dst_nodes:
async_to_sync(self.channel_layer.group_discard)(group, self.channel_name)
self.dst_nodes.discard(address)
# add the stuff to the db as well
# todo: shouldn't do this because of race condition?
MeshNode.objects.filter(address__in=addresses, uplink_id=self.uplink_node.address).update(
uplink_id=None,
)
2022-04-15 20:57:11 +02:00
2023-10-05 01:36:24 +02:00
class MeshUIConsumer(JsonWebsocketConsumer):
def connect(self):
# todo: auth
self.accept()
2023-10-05 04:05:29 +02:00
self.msg_sent_filter = {}
self.msg_received_filter = {}
2023-10-05 01:36:24 +02:00
def receive_json(self, content, **kwargs):
if content.get("subscribe", None) == "log":
async_to_sync(self.channel_layer.group_add)("mesh_log", self.channel_name)
2023-10-05 04:05:29 +02:00
if content.get("subscribe", None) == "msg_sent":
async_to_sync(self.channel_layer.group_add)("mesh_msg_sent", self.channel_name)
self.msg_sent_filter = dict(content.get("filter", {}))
if content.get("subscribe", None) == "msg_received":
async_to_sync(self.channel_layer.group_add)("mesh_msg_sent", self.channel_name)
self.msg_received_filter = dict(content.get("filter", {}))
if "send_msg" in content:
msg_to_send = self.scope["session"].pop("mesh_msg_%s" % content["send_msg"], None)
if not msg_to_send:
return
self.scope["session"].save()
async_to_sync(self.channel_layer.group_add)("mesh_msg_sent", self.channel_name)
self.msg_sent_filter = {"sender": self.channel_name}
for recipient in msg_to_send["recipients"]:
print('send to', recipient)
MeshMessage.fromjson({
'dst': recipient,
**msg_to_send["msg_data"],
}).send(sender=self.channel_name)
2023-10-05 01:36:24 +02:00
def mesh_log_entry(self, data):
self.send_json(data)
2023-10-05 04:05:29 +02:00
def mesh_msg_sent(self, data):
print('got data', data)
for key, value in self.msg_sent_filter.items():
if isinstance(value, list):
if data.get(key, None) not in value:
return
else:
if data.get(key, None) != value:
return
self.send_json(data)
2023-10-05 01:36:24 +02:00
def disconnect(self, code):
2023-10-05 04:05:29 +02:00
async_to_sync(self.channel_layer.group_discard)("mesh_log", self.channel_name)
async_to_sync(self.channel_layer.group_discard)("mesh_msg_sent", self.channel_name)
async_to_sync(self.channel_layer.group_discard)("mesh_msg_received", self.channel_name)