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.
@@ -0,0 +1,18 @@
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
+ __version__ = "0.10.4"
@@ -0,0 +1,66 @@
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 os
19
+ from pathlib import Path
20
+
21
+ # Constant values
22
+
23
+ # Datablock
24
+ ADDED = 0
25
+ COMMITED = 1
26
+ PUSHED = 2
27
+ FETCHED = 3
28
+ UP = 4
29
+ MODIFIED = 5
30
+ ERROR = 6
31
+
32
+
33
+ # networking
34
+ STATE_INITIAL = 0
35
+ CONNECTING = 9
36
+ STATE_WAITING = 6
37
+ STATE_CONFIG = 4
38
+ STATE_SYNCING = 1
39
+ STATE_SRV_SYNC = 7
40
+ STATE_ACTIVE = 2
41
+ STATE_QUITTING = 8
42
+ STATE_ERROR = 3
43
+ STATE_AUTH = 5
44
+ STATE_LOBBY = 10
45
+ # Client authed on the command channel but its data channel hasn't
46
+ # registered with the server yet - excluded from ServerData's broadcast
47
+ # until it flips to STATE_LOBBY, so a live update can't silently drop for a
48
+ # client that isn't reachable on the data channel yet.
49
+ STATE_DATA_PENDING = 11
50
+
51
+ # rights
52
+ RP_COMMON = "COMMON"
53
+
54
+ # Differential methodology
55
+ DIFF_BINARY = 0
56
+ DIFF_JSON = 1
57
+
58
+ # Default values
59
+ CONNECTION_TIMEOUT = 2000
60
+ CLIENT_PING_FREQUENCY = 1000
61
+
62
+ HEAD = "HEAD"
63
+
64
+ ROOT_PATH = Path(os.path.dirname(os.path.realpath(__file__)))
65
+ TTL_SCRIPT_PATH = os.path.join(ROOT_PATH, "ttl.py")
66
+ SERVER_SCRIPT_PATH = os.path.join(ROOT_PATH, "server.py")
@@ -0,0 +1,58 @@
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
+
19
+ class NonAuthorizedOperationError(Exception):
20
+ """Right authorization exception"""
21
+
22
+ pass
23
+
24
+
25
+ class ContextError(Exception):
26
+ """Context execution error"""
27
+
28
+ pass
29
+
30
+
31
+ class UnsupportedTypeError(Warning):
32
+ """Type not supported error"""
33
+
34
+ pass
35
+
36
+
37
+ class StateError(Exception):
38
+ """State error"""
39
+
40
+ pass
41
+
42
+
43
+ class ServiceNetworkError(Exception):
44
+ """Service networking error"""
45
+
46
+ pass
47
+
48
+
49
+ class NetworkFrameError(Exception):
50
+ """Networking frame error"""
51
+
52
+ pass
53
+
54
+
55
+ class DataError(Exception):
56
+ """Networking frame error"""
57
+
58
+ pass
@@ -0,0 +1,506 @@
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 logging
19
+ import os
20
+ import queue
21
+ import subprocess
22
+ import sys
23
+ import traceback
24
+ import os
25
+ import queue
26
+ import sys
27
+
28
+ from replication import __version__
29
+
30
+ from .constants import (
31
+ FETCHED,
32
+ SERVER_SCRIPT_PATH,
33
+ STATE_ACTIVE,
34
+ STATE_AUTH,
35
+ STATE_INITIAL,
36
+ CONNECTING,
37
+ STATE_LOBBY,
38
+ STATE_SRV_SYNC,
39
+ STATE_SYNCING,
40
+ UP,
41
+ TTL_SCRIPT_PATH,
42
+ STATE_QUITTING,
43
+ )
44
+ from .exception import StateError
45
+ from .repository import Repository
46
+ from .objects import (
47
+ ReplicationObject,
48
+ Auth,
49
+ Delete,
50
+ Disconnect,
51
+ Right,
52
+ ServerSnapshot,
53
+ Snapshot,
54
+ UpdateClientsState,
55
+ UpdateUserMetadata,
56
+ )
57
+ from .utils import current_milli_time
58
+ from . import porcelain
59
+
60
+ this = sys.modules[__name__]
61
+
62
+
63
+ class Session(object):
64
+ def __init__(self):
65
+ self.repository = None
66
+ self.callbacks = {}
67
+ self._state = STATE_INITIAL
68
+ self._state_progress = {"current": -1, "total": -1}
69
+ self._server = None
70
+
71
+ # Networking
72
+ self._state = STATE_INITIAL
73
+ self._srv_snapshot_size = 0
74
+ self._srv_snapshot_progress = 0
75
+
76
+ def register(self, name):
77
+ def func_wrapper(func):
78
+ self.callbacks[name] = func
79
+ return func
80
+
81
+ return func_wrapper
82
+
83
+ def call_registered(self, name=None, **kwargs):
84
+ func = self.callbacks.get(name, None)
85
+ if func is None:
86
+ logging.info("No function registered against - " + str(name))
87
+ return None
88
+ return func(**kwargs)
89
+
90
+ def connect(
91
+ self,
92
+ repository: Repository = None,
93
+ remote: str = "origin",
94
+ timeout=1000,
95
+ server_password=None,
96
+ admin_password=None,
97
+ subprocess_python_args=[],
98
+ ):
99
+ """Connect to a session
100
+
101
+ :param id: user name
102
+ :type id: string
103
+ :param address: host ip address
104
+ :type address: string
105
+ :param port: host port
106
+ :type port: int
107
+ """
108
+ self.repository = repository
109
+ self.remote = repository.remotes.get(remote)
110
+ self._data_protocol = repository.rdp
111
+
112
+ self._id = repository.username
113
+ # uuid needed to avoid reconnexion problems on router sockets
114
+ self._connection_timeout = timeout
115
+ self._state = CONNECTING
116
+
117
+ auth_type = "ADMIN" if admin_password else "CLIENT"
118
+ auth_request = Auth(
119
+ owner=self._id,
120
+ data={
121
+ "AUTH_TYPE": auth_type,
122
+ "AUTH_ID": self._id,
123
+ "S_PWD": server_password,
124
+ "A_PWD": admin_password,
125
+ "VERSION": __version__,
126
+ },
127
+ )
128
+ self.repository.push(self.remote.command, auth_request)
129
+
130
+ self._state = STATE_AUTH
131
+ self._connection_start_time = current_milli_time()
132
+ self._ttl = subprocess.Popen(
133
+ [
134
+ sys.executable,
135
+ *subprocess_python_args,
136
+ TTL_SCRIPT_PATH,
137
+ "-p",
138
+ str(self.remote.port),
139
+ "-d",
140
+ self.remote.address,
141
+ "-i",
142
+ str(self.remote.uuid),
143
+ "-t",
144
+ str(timeout),
145
+ ]
146
+ )
147
+
148
+ def host(
149
+ self,
150
+ id="Default",
151
+ repository: Repository = None,
152
+ remote="origin",
153
+ timeout=5000,
154
+ server_password=None,
155
+ admin_password=None,
156
+ cache_directory="",
157
+ server_log_level="INFO",
158
+ subprocess_python_args=[],
159
+ ):
160
+ """Host a session
161
+
162
+ :param id: user name
163
+ :type id: string
164
+ :param address: host ip address
165
+ :type address: strings
166
+ :param port: host port
167
+ :type port: int
168
+ """
169
+ active_remote = repository.remotes.get(remote)
170
+ # Create a server and serve
171
+ self._server = subprocess.Popen(
172
+ [
173
+ sys.executable,
174
+ *subprocess_python_args,
175
+ SERVER_SCRIPT_PATH,
176
+ "-p",
177
+ str(active_remote.port),
178
+ "-t",
179
+ str(timeout),
180
+ "-spwd",
181
+ str(server_password),
182
+ "-apwd",
183
+ str(admin_password),
184
+ "--attached",
185
+ "--log-level",
186
+ server_log_level,
187
+ "--log-file",
188
+ os.path.join(cache_directory, "multiuser_server.log"),
189
+ ]
190
+ )
191
+
192
+ self.connect(
193
+ repository=repository,
194
+ remote=remote,
195
+ timeout=timeout,
196
+ admin_password=admin_password,
197
+ server_password=server_password,
198
+ )
199
+
200
+ def init(self):
201
+ """Init the repository data
202
+
203
+ commit and push initial graph to the server
204
+ """
205
+ if len(self.repository.object_store) == 0:
206
+ logging.error("Add some data first")
207
+ return
208
+
209
+ self.request_server_repository_init()
210
+
211
+ def disconnect(self, reason: str = "None"):
212
+ """Disconnect from session"""
213
+ self._state = STATE_QUITTING
214
+ self.remote.command.close()
215
+ self.remote.data.close()
216
+ logging.info(f"Exiting session, reason {reason}")
217
+ if self.is_connection_alive():
218
+ self._ttl.kill()
219
+ if self._server:
220
+ self._server.kill()
221
+ self.call_registered("on_exit", reason=reason)
222
+
223
+ self._state = STATE_INITIAL
224
+
225
+ # NETWORKING
226
+ def is_connection_alive(self):
227
+ return self._ttl.poll() is None
228
+
229
+ def _assert_state(self, state):
230
+ if self._state not in state:
231
+ raise StateError("Client in wrong state")
232
+
233
+ def request_snapshot_init(self):
234
+ """Ask to the server for repository init."""
235
+
236
+ logging.info("Snapshot: request init")
237
+
238
+ self._snapshot_progress = 0
239
+ self._snapshot_total = 0
240
+
241
+ snapshot_request = Snapshot(owner=self._id, data={"STATE": "REQUEST_INIT"})
242
+
243
+ self.repository.push(self.remote.command, snapshot_request)
244
+
245
+ def request_server_repository_init(self):
246
+ """Ask to the server for repository init.
247
+
248
+ :param command: incoming command
249
+ :type command: Auth
250
+ """
251
+ logging.info("Request server init")
252
+
253
+ self._srv_snapshot_size = len(self.repository.object_store)
254
+ keys = [k for k, v in self.repository.object_store.items()]
255
+ assert self._srv_snapshot_size > 0
256
+
257
+ snapshot_cmd = ServerSnapshot(
258
+ owner="server",
259
+ data={"STATE": "INIT", "SIZE": self._srv_snapshot_size, "NODES": keys},
260
+ )
261
+ self.repository.push(self.remote.command, snapshot_cmd)
262
+
263
+ self._state = STATE_SRV_SYNC
264
+
265
+ def handle_authentification(self, command):
266
+ """Manage client authentification
267
+
268
+ :param command: incoming command
269
+ :type command: Auth
270
+ """
271
+ self._assert_state([STATE_AUTH])
272
+
273
+ connection_status = command.data
274
+
275
+ if "LOBBY" in connection_status:
276
+ self._state = STATE_LOBBY
277
+ if self._server:
278
+ self.request_server_repository_init()
279
+ if "RUNNING" in connection_status:
280
+ self._state = STATE_LOBBY
281
+ self.request_snapshot_init()
282
+ if "FAILED" in connection_status:
283
+ self.disconnect(
284
+ reason=f"Failed to connect, authentification refused [{connection_status}]"
285
+ )
286
+
287
+ def handle_client_snapshot(self, command):
288
+ """Manage incoming snapshot commands
289
+
290
+ :param command: incoming command
291
+ :type command: Snapshot
292
+ """
293
+ self._assert_state([STATE_SYNCING, STATE_LOBBY])
294
+
295
+ snapshot_state = command.data["STATE"]
296
+ snapshot_data = command.data.get("DATA")
297
+ if snapshot_state == "INIT":
298
+ logging.info("client init")
299
+ self._snapshot_progress = 0
300
+ self._snapshot_catalog = command.data.get("CATALOG")
301
+ self._snapshot_total = len(self._snapshot_catalog)
302
+ self._snapshot_late_updates = queue.Queue()
303
+
304
+ self._state_progress = {
305
+ "current": self._snapshot_progress,
306
+ "total": self._snapshot_total,
307
+ }
308
+
309
+ self._current_snapshot = self._snapshot_catalog.pop()
310
+ self.get_snapshot(self._current_snapshot)
311
+
312
+ self._state = STATE_SYNCING
313
+ elif snapshot_state == "SET":
314
+ if snapshot_data == b"removed":
315
+ logging.info(
316
+ f"Snapshot : node {self._current_snapshot} removed, skipping it."
317
+ )
318
+ else:
319
+ node = ReplicationObject.from_raw_chunks(snapshot_data)
320
+ node.state = FETCHED
321
+
322
+ if node.uuid != self._current_snapshot:
323
+ logging.error("Snapshot : wrong node received, skipping it")
324
+ return
325
+
326
+ self.repository.do_commit(node)
327
+
328
+ self._snapshot_progress += 1
329
+ self._state_progress = {
330
+ "current": self._snapshot_progress,
331
+ "total": self._snapshot_total,
332
+ }
333
+
334
+ if not self._snapshot_catalog:
335
+ # Apply late updates
336
+ logging.info(
337
+ f"Snapshot : Applying {self._snapshot_late_updates.qsize()} late updates."
338
+ )
339
+ while not self._snapshot_late_updates.empty():
340
+ late_update = self._snapshot_late_updates.get()
341
+ self.repository.do_commit(late_update)
342
+
343
+ snapshot_request = Snapshot(owner=self._id, data={"STATE": "DONE"})
344
+ self.repository.push(self.remote.command, snapshot_request)
345
+ logging.info("Snapshot : done.")
346
+ self._state = STATE_ACTIVE
347
+ self.call_registered("on_connection")
348
+ else:
349
+ self._current_snapshot = self._snapshot_catalog.pop()
350
+ self.get_snapshot(self._current_snapshot)
351
+
352
+ def handle_server_repository_init(self, command):
353
+ """Manage server initialization commands
354
+
355
+ :param command: incoming command
356
+ :type command: ServerSnapshot
357
+ """
358
+ self._assert_state([STATE_SRV_SYNC])
359
+
360
+ cli_snapshot_state = command.data.get("STATE")
361
+
362
+ if cli_snapshot_state == "ACCEPTED":
363
+ for index, node in enumerate(self.repository.object_store.values()):
364
+ porcelain.commit(self.repository, node.uuid)
365
+ node.state = UP
366
+ snapshot_cmd = ServerSnapshot(
367
+ owner="server", data={"STATE": "SET", "DATA": node.as_raw_chunks()}
368
+ )
369
+
370
+ self.repository.push(self.remote.command, snapshot_cmd)
371
+ self._state_progress = {
372
+ "current": index,
373
+ "total": len(self.repository.object_store),
374
+ }
375
+
376
+ snapshot_cmd = ServerSnapshot(owner="server", data={"STATE": "END"})
377
+ self.repository.push(self.remote.command, snapshot_cmd)
378
+ elif cli_snapshot_state == "DONE":
379
+ self._state = STATE_ACTIVE
380
+ self.call_registered("on_connection")
381
+ elif cli_snapshot_state == "REJECTED":
382
+ logging.error("client snapshot refused by the server.")
383
+ self._state = STATE_LOBBY
384
+
385
+ def get_snapshot(self, id):
386
+ """Ask a specific snapshot to the server
387
+
388
+ :param id: uuid of the data
389
+ :type id: str
390
+ """
391
+ logging.debug(f"Snapshot : request node {id}")
392
+ snapshot_request = Snapshot(owner=self._id, data={"STATE": "GET", "ID": id})
393
+
394
+ self.repository.push(self.remote.command, snapshot_request)
395
+
396
+ def listen(self, timeout: int = 0):
397
+ """Non-blocking network listening
398
+
399
+ :param timeout: network packet waiting time in millisecond
400
+ :type timeout: int
401
+ """
402
+ if self._state in [STATE_INITIAL, STATE_QUITTING]:
403
+ return
404
+
405
+ if not self.is_connection_alive():
406
+ self.disconnect(reason="Server lost")
407
+ return
408
+
409
+ # Servicing both dealers here also flushes/reads them - fetch()
410
+ # below is non-blocking and returns None if nothing complete has
411
+ # arrived yet, which can happen even right after poll() (a socket
412
+ # can be readable with only a partial frame buffered so far).
413
+ self.remote.poller.poll(timeout)
414
+
415
+ # COMMANDS I/O
416
+ try:
417
+ command_result = self.repository.fetch(self.remote.command)
418
+ except Exception as e:
419
+ logging.error(f"Corrupted frame received, skipping it. Cause:{e}")
420
+ traceback.print_exc()
421
+ command_result = None
422
+
423
+ if command_result is not None:
424
+ identity, command = command_result
425
+ # AUTHENTIFICATION
426
+ if isinstance(command, Auth):
427
+ self.handle_authentification(command)
428
+
429
+ # DISCONNECT CONFIRMATION
430
+ if isinstance(command, Disconnect):
431
+ reason = command.data.get("reason", "None")
432
+ self.disconnect(reason=reason)
433
+
434
+ # CLIENTS INFO UPDATE
435
+ if isinstance(command, UpdateClientsState):
436
+ self.repository.remote.online_users = command.data
437
+
438
+ if isinstance(command, UpdateUserMetadata):
439
+ user = self.repository.remote.online_users.get(command.owner)
440
+ user["metadata"].update(command.data)
441
+
442
+ # SERVER-->CLIENT SNAPSHOT
443
+ if isinstance(command, Snapshot):
444
+ self.handle_client_snapshot(command)
445
+
446
+ # CLIENT -> SERVER SNAPSHOT
447
+ if isinstance(command, ServerSnapshot):
448
+ self.handle_server_repository_init(command)
449
+
450
+ # GRAPH OPERATION (DELETE, CHANGE_RIGHT)
451
+ if type(command) in [Delete, Right]:
452
+ command.execute(self.repository.object_store)
453
+
454
+ # DATA IN
455
+ try:
456
+ data_result = self.repository.fetch(self.remote.data)
457
+ except Exception as e:
458
+ logging.error(f"Corrupted frame received, skipping it. Cause:{e}")
459
+ traceback.print_exc()
460
+ data_result = None
461
+
462
+ if data_result is not None:
463
+ identity, update = data_result
464
+ # Client snapshot
465
+ if self._state == STATE_SYNCING:
466
+ # If the snapshot is expected in the snapshot catalog we store
467
+ logging.info("Snapshot: Adding an update for the late one...")
468
+ self._snapshot_late_updates.put(update)
469
+
470
+ # Store received updates
471
+ if self._state == STATE_ACTIVE:
472
+ self.repository.do_commit(update)
473
+ # TODO: remove with stateless refactor
474
+ node_id = getattr(update, "uuid", getattr(update, "node_id", None))
475
+ node = self.repository.graph.get(node_id)
476
+ node.state = FETCHED
477
+ # Various timeout checks
478
+ # auth
479
+ if self._state == STATE_AUTH:
480
+ if (
481
+ current_milli_time() - self._connection_start_time
482
+ ) > self._connection_timeout:
483
+ self.disconnect(reason="Connection failed, server not found")
484
+
485
+ @property
486
+ def state(self):
487
+ """Get active session state
488
+
489
+ :return: session state
490
+ """
491
+ return self._state
492
+
493
+ @property
494
+ def state_progress(self):
495
+ """Get active session state
496
+
497
+ :return: session state
498
+ """
499
+ return self._state_progress
500
+
501
+ @property
502
+ def online_users(self):
503
+ return self.repository.remote.online_users
504
+
505
+
506
+ this.session = Session()