true-level-replication 0.10.4__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
replication/server.py ADDED
@@ -0,0 +1,839 @@
1
+ # ##### BEGIN GPL LICENSE BLOCK #####
2
+ #
3
+ # This program is free software: you can redistribute it and/or modify
4
+ # it under the terms of the GNU General Public License as published by
5
+ # the Free Software Foundation, either version 3 of the License, or
6
+ # (at your option) any later version.
7
+ #
8
+ # This program is distributed in the hope that it will be useful,
9
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
10
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
+ # GNU General Public License for more details.
12
+ #
13
+ # You should have received a copy of the GNU General Public License
14
+ # along with this program. If not, see <https://www.gnu.org/licenses/>.
15
+ #
16
+ # ##### END GPL LICENSE BLOCK #####
17
+
18
+ import argparse
19
+ import cmd
20
+ import logging
21
+ import os
22
+ import sys
23
+ from pathlib import Path
24
+ import traceback
25
+
26
+ # REFACTOR: remove this in favor of a better env setup
27
+ replication_lib = Path(os.path.dirname(os.path.realpath(__file__)))
28
+
29
+
30
+ sys.path.insert(0, str(replication_lib.parent))
31
+
32
+ import copy
33
+ import logging
34
+
35
+ import os
36
+ import queue
37
+ import sys
38
+ import threading
39
+ import time
40
+ from pathlib import Path
41
+
42
+ from replication import __version__
43
+ from replication.constants import (
44
+ CLIENT_PING_FREQUENCY,
45
+ CONNECTION_TIMEOUT,
46
+ RP_COMMON,
47
+ STATE_ACTIVE,
48
+ STATE_DATA_PENDING,
49
+ STATE_INITIAL,
50
+ STATE_LOBBY,
51
+ STATE_SRV_SYNC,
52
+ STATE_WAITING,
53
+ UP,
54
+ )
55
+ from replication.objects import (
56
+ ReplicationObject,
57
+ Auth,
58
+ Delete,
59
+ Disconnect,
60
+ Kick,
61
+ Right,
62
+ ServerSnapshot,
63
+ Snapshot,
64
+ UpdateClientsState,
65
+ UpdateUserMetadata,
66
+ RequestServerInfo,
67
+ )
68
+
69
+ from replication.repository import Repository
70
+ from replication.utils import current_milli_time
71
+ from replication import net
72
+
73
+
74
+ class ServerNetService(threading.Thread):
75
+ def __init__(self):
76
+
77
+ # Threading
78
+ threading.Thread.__init__(self)
79
+ self.name = "command"
80
+ self._exit_event = threading.Event()
81
+
82
+ # Networking
83
+ self._repository = Repository(bare=True)
84
+ self._command = None
85
+ self._data = None
86
+ self._state = 0
87
+ self.clients = {}
88
+ self._ttl = None
89
+ # kick() can be called from any thread (ServerShell's cmdloop
90
+ # thread, in the CLI shell case) but Router/_Connection are only
91
+ # safe to touch from ServerNetService's own thread - queue the
92
+ # request and act on it from inside run().
93
+ self._kick_queue = queue.Queue()
94
+ # identity -> (auth_status, queued_at) for clients that passed auth
95
+ # but whose DATA channel hasn't registered with the server yet.
96
+ self._pending_auth = {}
97
+
98
+ def listen(
99
+ self,
100
+ port=5560,
101
+ server_password=None,
102
+ admin_password="admin",
103
+ attached=False,
104
+ timeout=CONNECTION_TIMEOUT,
105
+ ):
106
+ self._server_password = server_password
107
+ self._admin_password = admin_password
108
+ self._port = port
109
+ self._attached = attached
110
+ self._connection_timeout = timeout
111
+
112
+ # Single public port shared by all 3 roles - connections are
113
+ # dispatched to the right subsystem by role tag at handshake time.
114
+ self._listener = net.Listener(port)
115
+ self._command_queue = queue.Queue()
116
+ data_queue = queue.Queue()
117
+ ttl_queue = queue.Queue()
118
+ self._listener.register_role(net.ROLE_COMMAND, self._command_queue)
119
+ self._listener.register_role(net.ROLE_DATA, data_queue)
120
+ self._listener.register_role(net.ROLE_TTL, ttl_queue)
121
+ self._listener.start()
122
+
123
+ self._command = net.Router()
124
+
125
+ # TTL communication - two one-way queues rather than one shared
126
+ # queue (see ServerTTL for why: a single Queue would let ServerTTL's
127
+ # own drain loop race with us to consume its own notifications).
128
+ self._ttl_notify_queue = queue.Queue() # ServerTTL -> us: STATE / LOST
129
+ self._ttl_watch_queue = queue.Queue() # us -> ServerTTL: STOP_WATCHING
130
+
131
+ self._ttl = ServerTTL(
132
+ ttl_queue, self._ttl_notify_queue, self._ttl_watch_queue, timeout=timeout
133
+ )
134
+
135
+ # Data handling
136
+ self._data = ServerData(
137
+ data_queue, repository=self._repository, clients_state=self.clients
138
+ )
139
+
140
+ self._client_snapshot_size = 0
141
+ self._client_snapshot_progress = 0
142
+
143
+ self.start()
144
+
145
+ def _drain_new_connections(self):
146
+ try:
147
+ while True:
148
+ identity, sock = self._command_queue.get_nowait()
149
+ self._command.add_connection(identity, sock)
150
+ except queue.Empty:
151
+ pass
152
+
153
+ def disconnect_client(self, client, reason):
154
+ leaving_client = self.clients.get(client)
155
+ if leaving_client:
156
+ client_id = leaving_client.get("id")
157
+ locked_nodes = [
158
+ n.uuid for n in self._repository.graph.values() if n.owner == client_id
159
+ ]
160
+
161
+ if locked_nodes:
162
+ reset_right = Right(
163
+ owner="server", data={"uuid": locked_nodes, "owner": RP_COMMON}
164
+ )
165
+
166
+ logging.debug(f"Changing node {locked_nodes} rights to COMMON")
167
+
168
+ for cli in list(self.clients.keys()):
169
+ if cli != client:
170
+ self._repository.push(self._command, reset_right, identity=cli)
171
+ reset_right.execute(self._repository.object_store)
172
+
173
+ del self.clients[client]
174
+ logging.info(f"{client_id} disconnected from the server [{reason}]")
175
+
176
+ def _update_clients_states(self):
177
+ user_dict = {}
178
+ for user, user_data in self.clients.items():
179
+ user_dict[user_data["id"]] = user_data
180
+
181
+ clients_states = UpdateClientsState(owner="server", data=user_dict)
182
+
183
+ # Push it to every clients
184
+ chunks = clients_states.as_raw_chunks()
185
+ for client_uid in list(self.clients):
186
+ self._command.send(client_uid, chunks)
187
+
188
+ def _login_client(
189
+ self, auth_type, uid, id, server_password, admin_password, version
190
+ ):
191
+ """Register a client on the server
192
+
193
+ return:
194
+ FAILED
195
+ LOBBY
196
+ RUNNING
197
+ """
198
+ logging.debug(f"Processing logging request from {id}")
199
+ for cli in self.clients.values():
200
+ if id == cli["id"]:
201
+ logging.debug("client logged in")
202
+ return "FAILED: client already logged in"
203
+
204
+ if auth_type == "ADMIN" and admin_password != self._admin_password:
205
+ return "FAILED: wrong admin password"
206
+
207
+ if str(server_password) != self._server_password:
208
+ return "FAILED: wrong server password"
209
+
210
+ if version != __version__:
211
+ return f"FAILED: wrong client version ({version} != {__version__})"
212
+
213
+ logging.info(f"{id} logged in.")
214
+
215
+ self.clients[uid] = {
216
+ "id": id,
217
+ "admin": auth_type == "ADMIN",
218
+ "latency": 999,
219
+ # Not STATE_LOBBY yet - ServerData excludes STATE_DATA_PENDING
220
+ # clients from broadcast until their data channel registers (see
221
+ # the pending-auth resolution block in run()), otherwise a live
222
+ # update could land and silently drop before they're reachable.
223
+ "status": STATE_DATA_PENDING,
224
+ "metadata": {},
225
+ }
226
+ if self._state in [STATE_WAITING, STATE_SRV_SYNC]:
227
+ return "LOBBY"
228
+ else:
229
+ return "RUNNING"
230
+
231
+ def kick(self, user):
232
+ """kick the given user - safe to call from any thread, the actual
233
+ disconnect happens on this service's own thread in run() (see
234
+ _kick_queue).
235
+
236
+ :arg user: username of the kicked client
237
+ :type user: str
238
+ """
239
+ self._kick_queue.put(user)
240
+
241
+ def _do_kick(self, user):
242
+ for k, v in list(self.clients.items()):
243
+ if v["id"] == user:
244
+ disconnect = Disconnect(
245
+ owner="server",
246
+ data={
247
+ "reason": "kicked by admin",
248
+ },
249
+ )
250
+ self._repository.push(self._command, disconnect, identity=k)
251
+
252
+ self._ttl_watch_queue.put(("STOP_WATCHING", k))
253
+ self.disconnect_client(k, "kicked")
254
+
255
+ logging.warning(f"{user} kicked from the session.")
256
+ return
257
+
258
+ logging.error(f"Can't kick {user}, user not found.")
259
+
260
+ def send_client_snapshot_init(self, client):
261
+ catalog = [str(k) for k in self._repository.object_store.keys()]
262
+ snapshot_state = Snapshot(
263
+ owner="server", data={"STATE": "INIT", "CATALOG": catalog}
264
+ )
265
+ logging.info(f"{self.clients[client]['id']} - Snapshot : Pushing nodes catalog")
266
+ self._repository.push(self._command, snapshot_state, identity=client)
267
+
268
+ def handle_client_snapshot(self, command):
269
+ """Handle client snapshot commands"""
270
+
271
+ snapshot_state = command.data.get("STATE")
272
+ snapshot_client = self.clients.get(command.sender)
273
+
274
+ if snapshot_client:
275
+ if snapshot_state == "REQUEST_INIT":
276
+ self.send_client_snapshot_init(command.sender)
277
+ elif snapshot_state == "GET":
278
+ node = self._repository.graph.get(command.data["ID"])
279
+
280
+ if node:
281
+ logging.debug(
282
+ f"{snapshot_client['id']} - Snapshot : pushing node {node.uuid}"
283
+ )
284
+ else:
285
+ logging.debug(
286
+ f"{snapshot_client['id']} - Snapshot : node {command.data['ID']} no longer exist, skipping it."
287
+ )
288
+
289
+ node_data = node.as_raw_chunks() if node else b"removed"
290
+ snapshot_cmd = Snapshot(
291
+ owner="server", data={"STATE": "SET", "DATA": node_data}
292
+ )
293
+ self._repository.push(
294
+ self._command, snapshot_cmd, identity=command.sender
295
+ )
296
+ elif snapshot_state == "DONE":
297
+ # Set client ready
298
+ logging.info(f"{snapshot_client['id']} - Snapshot : done.")
299
+ self.clients[command.sender]["status"] = STATE_ACTIVE
300
+ self._update_clients_states()
301
+ else:
302
+ logging.error(f"Snapshot cancelled {command.sender} (client disconnected)")
303
+
304
+ def handle_server_repository_init(self, command):
305
+ cli_snapshot_state = command.data.get("STATE")
306
+ cli_snapshot_lenght = command.data.get("SIZE")
307
+ cli_snapshot_dict = command.data.get("NODES")
308
+ cli_snapshot_data = command.data.get("DATA")
309
+
310
+ if cli_snapshot_state == "INIT":
311
+ if self._state == STATE_SRV_SYNC: # REJECT
312
+ snapshot_status = "REJECTED"
313
+ if self._state == STATE_WAITING:
314
+ snapshot_status = "ACCEPTED"
315
+ self._client_snapshot_size = cli_snapshot_lenght
316
+ self._client_snapshot_dict = cli_snapshot_dict
317
+
318
+ snapshot_cmd = ServerSnapshot(
319
+ owner="server", data={"STATE": snapshot_status}
320
+ )
321
+ self._repository.push(self._command, snapshot_cmd, identity=command.sender)
322
+ self._state = STATE_SRV_SYNC
323
+
324
+ if cli_snapshot_state == "SET":
325
+ node = ReplicationObject.from_raw_chunks(cli_snapshot_data)
326
+ node.state = UP
327
+
328
+ self._repository.do_commit(node)
329
+
330
+ self._client_snapshot_progress += 1
331
+ logging.debug(
332
+ f"Receiving snapshot {self._client_snapshot_progress}/{self._client_snapshot_size}"
333
+ )
334
+ self._client_snapshot_dict.remove(node.uuid)
335
+ if len(self._client_snapshot_dict) == 0:
336
+ # Launch snapshot for other waiting clients
337
+ snapshot_cmd = ServerSnapshot(owner="server", data={"STATE": "DONE"})
338
+
339
+ self._repository.push(
340
+ self._command, snapshot_cmd, identity=command.sender
341
+ )
342
+
343
+ for client in list(self.clients.keys()):
344
+ if client != command.sender:
345
+ self.send_client_snapshot_init(client)
346
+
347
+ self._state = STATE_ACTIVE
348
+
349
+ if cli_snapshot_state == "END":
350
+ self.clients[command.sender]["status"] = STATE_ACTIVE
351
+ self._update_clients_states()
352
+ logging.info("Done")
353
+
354
+ def run(self):
355
+ logging.info(f"Listening on {self._port}.")
356
+
357
+ self._state = STATE_WAITING
358
+
359
+ while not self._exit_event.is_set():
360
+ self._drain_new_connections()
361
+ self._command.poll(1)
362
+
363
+ try:
364
+ while True:
365
+ self._do_kick(self._kick_queue.get_nowait())
366
+ except queue.Empty:
367
+ pass
368
+
369
+ # COMMAND HANDLING
370
+ try:
371
+ result = self._repository.fetch(self._command)
372
+ except Exception as e:
373
+ logging.error(
374
+ f"Corrupted command frame received, skipping it. Cause:{e}"
375
+ )
376
+ traceback.print_exc()
377
+ result = None
378
+
379
+ if result is not None:
380
+ identity, command = result
381
+ command.sender = identity
382
+
383
+ # AUHTENTIFICATION
384
+ if isinstance(command, Auth):
385
+ auth_type = command.data.get("AUTH_TYPE")
386
+ auth_origin = command.sender
387
+ auth_id = command.data.get("AUTH_ID")
388
+ auth_s_pass = command.data.get("S_PWD", None)
389
+ auth_a_pass = command.data.get("A_PWD", None)
390
+ client_version = command.data.get("VERSION")
391
+
392
+ auth_status = self._login_client(
393
+ auth_type,
394
+ auth_origin,
395
+ auth_id,
396
+ auth_s_pass,
397
+ auth_a_pass,
398
+ client_version,
399
+ )
400
+
401
+ if auth_status in ("LOBBY", "RUNNING"):
402
+ # Hold the reply until the data channel registers -
403
+ # see the pending-auth resolution block below.
404
+ self._pending_auth[auth_origin] = (
405
+ auth_status,
406
+ current_milli_time(),
407
+ )
408
+ else:
409
+ auth_response = Auth(owner="server", data=auth_status)
410
+ self._repository.push(
411
+ self._command, auth_response, identity=command.sender
412
+ )
413
+ self._update_clients_states()
414
+
415
+ # SERVER-> CLIENT SNAPSHOT
416
+ if isinstance(command, Snapshot):
417
+ self.handle_client_snapshot(command)
418
+
419
+ # CLIENT-> SERVER SNAPSHOT
420
+ if isinstance(command, ServerSnapshot):
421
+ self.handle_server_repository_init(command)
422
+
423
+ # CLIENT METADATA
424
+ if isinstance(command, UpdateUserMetadata):
425
+ user = self.clients.get(command.sender)
426
+
427
+ if user:
428
+ try:
429
+ user["metadata"].update(command.data)
430
+ except Exception as e:
431
+ logging.error(e)
432
+ traceback.print_exc()
433
+ else:
434
+ for client_uid in list(self.clients):
435
+ if client_uid != command.sender:
436
+ self._repository.push(
437
+ self._command, command, identity=client_uid
438
+ )
439
+
440
+ # KICK
441
+ if isinstance(command, Kick):
442
+ self.kick(command.data["user"])
443
+
444
+ if isinstance(command, RequestServerInfo):
445
+ server_info = RequestServerInfo(
446
+ owner="server",
447
+ data={
448
+ "private": True if self._server_password else False,
449
+ "version": __version__,
450
+ },
451
+ )
452
+ self._repository.push(
453
+ self._command, server_info, identity=command.sender
454
+ )
455
+
456
+ # OTHERS
457
+ if type(command) in [Delete, Right]:
458
+ try:
459
+ command.execute(self._repository.object_store)
460
+ except Exception as e:
461
+ logging.error(e)
462
+ traceback.print_exc()
463
+ else:
464
+ chunks = command.as_raw_chunks()
465
+ for client_uid in list(self.clients):
466
+ self._command.send(client_uid, chunks)
467
+
468
+ # PENDING AUTH RESOLUTION - a client that authenticated is held
469
+ # out of self.clients' STATE_LOBBY (and thus out of ServerData's
470
+ # broadcast) until its DATA channel has actually registered, so
471
+ # a live update landing in between can't silently drop for it.
472
+ if self._pending_auth:
473
+ now = current_milli_time()
474
+ connected = self._data.identities
475
+ for auth_origin, (auth_status, queued_at) in list(
476
+ self._pending_auth.items()
477
+ ):
478
+ client = self.clients.get(auth_origin)
479
+ if client is None:
480
+ del self._pending_auth[auth_origin]
481
+ continue
482
+
483
+ if auth_origin in connected:
484
+ client["status"] = STATE_LOBBY
485
+ auth_response = Auth(owner="server", data=auth_status)
486
+ self._repository.push(
487
+ self._command, auth_response, identity=auth_origin
488
+ )
489
+ self._update_clients_states()
490
+ del self._pending_auth[auth_origin]
491
+ elif now - queued_at > self._connection_timeout:
492
+ logging.warning(
493
+ f"{client['id']} authenticated but its data channel never "
494
+ "connected in time, rejecting."
495
+ )
496
+ auth_response = Auth(
497
+ owner="server", data="FAILED: data channel timeout"
498
+ )
499
+ self._repository.push(
500
+ self._command, auth_response, identity=auth_origin
501
+ )
502
+ self.disconnect_client(auth_origin, "data channel timeout")
503
+ del self._pending_auth[auth_origin]
504
+
505
+ # TTL HANDLING
506
+ try:
507
+ while True:
508
+ notification = self._ttl_notify_queue.get_nowait()
509
+
510
+ if notification[0] == "STATE":
511
+ clients_states = notification[1]
512
+
513
+ # Prepare update
514
+ for id, state in clients_states.items():
515
+ cli = self.clients.get(id)
516
+ if cli:
517
+ cli.update(state)
518
+ else:
519
+ self._ttl_watch_queue.put(("STOP_WATCHING", id))
520
+
521
+ self._update_clients_states()
522
+
523
+ if notification[0] == "LOST":
524
+ self.disconnect_client(notification[1], "connection closed")
525
+ except queue.Empty:
526
+ pass
527
+
528
+ while self._ttl._state != STATE_INITIAL:
529
+ time.sleep(1)
530
+
531
+ self._data.stop()
532
+ self._data.join(timeout=2.0)
533
+ self._command.close()
534
+ self._listener.stop()
535
+
536
+ def stop(self):
537
+ self._ttl.stop()
538
+ self._data.stop()
539
+ self._exit_event.set()
540
+ self._state = 0
541
+
542
+
543
+ class ServerData(threading.Thread):
544
+ def __init__(self, connection_queue, repository=None, clients_state=None):
545
+ threading.Thread.__init__(self)
546
+ self.name = "data"
547
+ self.daemon = False
548
+ self._exit_event = threading.Event()
549
+ self._repository = repository
550
+ self._connection_queue = connection_queue
551
+
552
+ # Update all clients - connections are handed in by the shared
553
+ # net.Listener (ROLE_DATA) rather than binding our own port.
554
+ self._data = net.Router()
555
+ self.clients = clients_state
556
+
557
+ self.start()
558
+
559
+ @property
560
+ def identities(self):
561
+ return self._data.identities
562
+
563
+ def _drain_new_connections(self):
564
+ try:
565
+ while True:
566
+ identity, sock = self._connection_queue.get_nowait()
567
+ self._data.add_connection(identity, sock)
568
+ except queue.Empty:
569
+ pass
570
+
571
+ def run(self):
572
+ while not self._exit_event.is_set():
573
+ self._drain_new_connections()
574
+ self._data.poll(1)
575
+
576
+ try:
577
+ result = self._repository.fetch(self._data)
578
+ except Exception as e:
579
+ logging.error(f"Corrupted data frame received, skipping it. Cause:{e}")
580
+ traceback.print_exc()
581
+ continue
582
+
583
+ if result is None:
584
+ continue
585
+
586
+ identity, update = result
587
+ self._repository.do_commit(update)
588
+
589
+ # Serialize once and reuse the same chunks for every recipient -
590
+ # as_raw_chunks() re-pickles the payload on every call, so doing
591
+ # it inside the fan-out loop below cost one redundant
592
+ # serialization per connected client instead of one total.
593
+ chunks = update.as_raw_chunks()
594
+
595
+ # Update all ready clients - skip clients still in
596
+ # STATE_DATA_PENDING, whose data channel hasn't registered yet
597
+ # (ServerNetService holds their auth reply until it has).
598
+ for client_uid, client_data in list(self.clients.items()):
599
+ if (
600
+ client_uid != identity
601
+ and client_data.get("status") != STATE_DATA_PENDING
602
+ ):
603
+ if not self._data.send(client_uid, chunks):
604
+ logging.debug(
605
+ f"Broadcast to {client_uid!r} dropped (no live data connection)."
606
+ )
607
+
608
+ self._data.close()
609
+
610
+ def stop(self):
611
+ self._exit_event.set()
612
+
613
+
614
+ class ServerTTL(threading.Thread):
615
+ def __init__(
616
+ self, connection_queue, notify_queue, watch_queue, timeout=CONNECTION_TIMEOUT
617
+ ):
618
+ # Threading
619
+ threading.Thread.__init__(self)
620
+ self.name = "ttl"
621
+ self.daemon = False
622
+ self._exit_event = threading.Event()
623
+
624
+ # Networking - connection_queue is fed by the shared net.Listener
625
+ # (ROLE_TTL). Replaces the old inproc zmq pipe with two one-way
626
+ # queues rather than one shared queue: a single Queue has no notion
627
+ # of sender, so ServerTTL's own STOP_WATCHING-drain loop would
628
+ # otherwise race with ServerNetService to consume ServerTTL's own
629
+ # just-put STATE/LOST notifications.
630
+ self._connection_queue = connection_queue
631
+ self._notify_queue = notify_queue # ServerTTL -> ServerNetService: STATE / LOST
632
+ self._watch_queue = watch_queue # ServerNetService -> ServerTTL: STOP_WATCHING
633
+ self._heartbeat = net.Router()
634
+
635
+ self._timeout = timeout
636
+ self._state = STATE_INITIAL
637
+ self._clients_state = {}
638
+
639
+ self.start()
640
+
641
+ def _drain_new_connections(self):
642
+ try:
643
+ while True:
644
+ identity, sock = self._connection_queue.get_nowait()
645
+ self._heartbeat.add_connection(identity, sock)
646
+ except queue.Empty:
647
+ pass
648
+
649
+ def run(self):
650
+ self._state = STATE_ACTIVE
651
+ last_update_time = current_milli_time()
652
+ while not self._exit_event.is_set():
653
+ self._drain_new_connections()
654
+ self._heartbeat.poll(1)
655
+ current_time = current_milli_time()
656
+
657
+ message = self._heartbeat.recv()
658
+ if message is not None:
659
+ identity, chunks = message
660
+ frame = chunks[0] if chunks else b""
661
+
662
+ if frame == b"INIT":
663
+ self._clients_state[identity] = {}
664
+ self._clients_state[identity]["latency"] = 999
665
+ self._clients_state[identity]["last_received_update"] = current_time
666
+ self._clients_state[identity]["last_sent_update"] = current_time
667
+ self._heartbeat.send(identity, [b"PING"])
668
+
669
+ client = self._clients_state.get(identity)
670
+
671
+ if client is not None:
672
+ client["last_received_update"] = current_time
673
+
674
+ try:
675
+ while True:
676
+ notification = self._watch_queue.get_nowait()
677
+ if notification[0] == "STOP_WATCHING":
678
+ self.stop_monitor(notification[1])
679
+ except queue.Empty:
680
+ pass
681
+
682
+ if current_time - last_update_time > 1000:
683
+ last_update_time = current_time
684
+ client_to_remove = []
685
+
686
+ # Check clients status
687
+ for client, client_data in self._clients_state.items():
688
+ client_data["latency"] = abs(
689
+ (client_data["last_received_update"])
690
+ - (client_data["last_sent_update"])
691
+ )
692
+
693
+ if client_data["latency"] > self._timeout:
694
+ client_to_remove.append(client)
695
+ self._notify_queue.put(("LOST", client))
696
+
697
+ for client in client_to_remove:
698
+ self.stop_monitor(client)
699
+
700
+ state_update = {
701
+ cli: {"latency": val["latency"]}
702
+ for cli, val in self._clients_state.items()
703
+ }
704
+ self._notify_queue.put(("STATE", state_update))
705
+
706
+ for cli_key, cli_data in self._clients_state.items():
707
+ if (
708
+ current_time - cli_data["last_received_update"]
709
+ ) > CLIENT_PING_FREQUENCY and current_time - cli_data[
710
+ "last_sent_update"
711
+ ] > CLIENT_PING_FREQUENCY:
712
+
713
+ self._heartbeat.send(cli_key, [b"PING"])
714
+ cli_data["last_sent_update"] = current_time
715
+
716
+ self._heartbeat.close()
717
+ self._state = STATE_INITIAL
718
+
719
+ def stop_monitor(self, client):
720
+ if client in self._clients_state:
721
+ logging.debug(f"Removing client {client} from watchlist")
722
+ del self._clients_state[client]
723
+
724
+ @property
725
+ def state(self):
726
+ return self._state
727
+
728
+ @property
729
+ def clients_state(self):
730
+ return copy.copy(self._clients_state)
731
+
732
+ def stop(self):
733
+ self._exit_event.set()
734
+
735
+
736
+ class ServerShell(cmd.Cmd):
737
+ intro = (
738
+ "Welcome the replication server shell.\n Type help or ? to list commands.\n"
739
+ )
740
+ prompt = ">> "
741
+ file = None
742
+
743
+ def __init__(
744
+ self,
745
+ port=5555,
746
+ timeout=CONNECTION_TIMEOUT,
747
+ server_password=None,
748
+ admin_password=None,
749
+ attached=False,
750
+ ):
751
+
752
+ cmd.Cmd.__init__(self)
753
+ self._net = ServerNetService()
754
+
755
+ self._net.listen(
756
+ port=port,
757
+ server_password=server_password,
758
+ admin_password=admin_password,
759
+ attached=attached,
760
+ timeout=timeout,
761
+ )
762
+
763
+ def do_users(self, args):
764
+ """Print online users"""
765
+ print(f"{len(self._net.clients)} user online")
766
+ for cli_id, cli_data in self._net.clients.items():
767
+ role = "admin" if cli_data["admin"] else ""
768
+ print(f"{cli_data['id']}({role}) - {cli_data['latency']} ms")
769
+
770
+ def do_kick(self, args):
771
+ """Kick the target user"""
772
+ self._net.kick(args)
773
+
774
+ def do_exit(self, args):
775
+ """Exit the server"""
776
+ self._net.stop()
777
+ return -1
778
+
779
+ def do_EOF(self, args):
780
+ print("*** EOF")
781
+ return True
782
+
783
+
784
+ def cli():
785
+ parser = argparse.ArgumentParser()
786
+ parser.add_argument("-p", "--port", default=5560, help="port to listen")
787
+ parser.add_argument("-l", "--log-level", default="INFO", help="set logging level ")
788
+ parser.add_argument(
789
+ "-lf", "--log-file", default="multi_user_server.log", help="set log file output"
790
+ )
791
+ parser.add_argument(
792
+ "-t",
793
+ "--timeout",
794
+ default=CONNECTION_TIMEOUT,
795
+ help="connection timeout in millisecond",
796
+ )
797
+ parser.add_argument(
798
+ "-apwd", "--admin-password", default="admin", help="session admin password"
799
+ )
800
+ parser.add_argument(
801
+ "-spwd", "--server-password", default=None, help="session server password"
802
+ )
803
+
804
+ parser.add_argument(
805
+ "--attached", help="server attached to a blender instance", action="store_true"
806
+ )
807
+
808
+ args = parser.parse_args()
809
+
810
+ formatter = logging.Formatter(
811
+ fmt="%(asctime)s SERVER %(levelname)-8s %(message)s", datefmt="%H:%M:%S"
812
+ )
813
+
814
+ logging.basicConfig(level=logging._nameToLevel[args.log_level])
815
+ logger = logging.getLogger()
816
+ handler = logging.FileHandler(args.log_file, mode="w")
817
+ logger.addHandler(handler)
818
+
819
+ for handler in logger.handlers:
820
+ if isinstance(handler, logging.NullHandler):
821
+ continue
822
+
823
+ handler.setFormatter(formatter)
824
+
825
+ shell = ServerShell(
826
+ port=int(args.port),
827
+ timeout=int(args.timeout),
828
+ server_password=str(args.server_password),
829
+ admin_password=str(args.admin_password),
830
+ attached=bool(args.attached),
831
+ )
832
+ try:
833
+ shell.cmdloop()
834
+ except KeyboardInterrupt:
835
+ shell.do_exit(None)
836
+
837
+
838
+ if __name__ == "__main__":
839
+ cli()