-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLibPeerUnixServer.py
More file actions
345 lines (240 loc) · 11.6 KB
/
LibPeerUnixServer.py
File metadata and controls
345 lines (240 loc) · 11.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
from LibMedium.Medium.Listener.Application import Application
from LibMedium.Util.Defer import Defer
from LibPeerUnix.Server import LibPeerUnixServerBase
import LibPeerUnix.Exceptions
import LibPeerUnix.Models
from LibPeerUnix.Utilities import LabelCollection, PeerCollection, TransmitItem
from LibPeer.Discoverers import Discoverer
from LibPeer.Discoverers.Samband import Samband
from LibPeer.Discoverers.AMPP import AMPP
from LibPeer.Networks import Network
from LibPeer.Networks.Ipv4 import Ipv4
from LibPeer.Muxer import Muxer
from LibPeer.Transports import Transport
from LibPeer.Transports.EDP import EDP
from LibPeer.Transports.DSTP import DSTP
from LibPeer.Formats.BinaryAddress import BinaryAddress
from LibPeer.Logging import log
import threading
import time
import queue
class LibPeerUnixServer(LibPeerUnixServerBase):
def run(self):
# This is called when the daemon is ready to communicate. Do your background tasks in here.
# Communication is managed in a different thread, so feel free to place your infinate loop here.
# A set of application connections can be found at 'self.applications'.
# All your events are available to fire off at any time using 'self.event_name(*params)'.
# To fire an event to a single application instance, pass in the application as the last
# paramater in the event call, eg. 'self.event_name(param1, param2, application)'
# Setup networks (TODO needs system config)
self.networks = [
Ipv4({"address": "0.0.0.0", "port": 3000}),
]
for network in self.networks:
network.go_up()
# Setup muxer (TODO needs system config)
self.muxer = Muxer(self.networks)
# Setup transports (TODO needs system config)
self.transports = [
EDP(self.muxer, {}),
DSTP(self.muxer, {})
]
self.transport_map = {}
for transport in self.transports:
transport.incoming.subscribe(lambda info, transport=transport: self.data_received(info, transport.identifier))
self.transport_map[transport.identifier] = transport
# Setup discoverers (TODO needs system config)
self.discoverers = [
# Samband(self.networks),
AMPP(self.networks),
]
for discoverer in self.discoverers:
# Create an administrative distance multiplier
distance_mul = 2
# 2 For every other discoverer, 1 for Samband (local)
if(type(discoverer) == Samband):
distance_mul = 1
discoverer.discovered.subscribe(lambda p: self.peer_discovered(p, 1))
# Setup priority map (TODO needs system config)
self.namespace_priorities = {
}
# Setup maps
self.app_namespace = {}
self.namespace_app = {}
self.application_labels = {}
self.applications_advertised = set()
self.discoveries = {}
self.tx_queue = queue.PriorityQueue()
# Runs forever
self.transmitter()
def ensure_bound(self, application: Application):
if(application not in self.app_namespace):
raise LibPeerUnix.Exceptions.UnboundError("That method cannot be called before bind(nameapce) is called.")
def peer_discovered(self, info, distance_mul: int):
# Get address
peer: BinaryAddress = info[0]
# Determine administrative distance
distance = info[1] * distance_mul
# Change AD to 0 if this is the local machine
for discoverer in self.discoverers:
if(peer in discoverer.get_addresses()):
distance = 0
break
# Get the PeerCollection for this namespace
collection: PeerCollection = self.discoveries[peer.application]
# Tell it of our find, and get the model to notify the application with
model = collection.found_peer(peer, distance).get_model()
# Notify the relevent application
app = self.namespace_app[peer.application]
self.new_peer(model, app)
def data_received(self, info, transport):
# Unpack the tuple
data: bytes = info[0]
channel: bytes = info[1]
address: BinaryAddress = info[2]
# Ignore if we aren't running the application
if(address.application not in self.namespace_app):
return
# Get the application
app = self.namespace_app[address.application]
# Convert the address
label = b""
if(address.label):
label = address.label
model_address = LibPeerUnix.Models.Address(address.network_type, address.network_address, address.network_port, label)
# Create the message
model_message = LibPeerUnix.Models.Message(model_address, data, channel, transport)
# Send to the app
self.receive(model_message, app)
def advertiser(self, app: Application, discoverer: Discoverer):
# Get the application's namespace
namespace = self.app_namespace[app]
while(app in self.applications_advertised):
# Get peer's address
addresses = discoverer.get_addresses()
# Get the label lock
with self.application_labels[app].lock:
# Loop over each address
for address in addresses:
# Give the address application information
address.application = namespace
# Loop over each label
for label in self.application_labels[app].labels:
# Add label info to the address
address.label = label
# Advertise with the label info
discoverer.advertise(address)
# Get ready to store time to wait after advertising
wait = 0
# Now advertise the application with no label
for address in addresses:
# Clear the label
address.label = None
# Advertise
wait = discoverer.advertise(address)
# Wait before advertising again
time.sleep(wait)
# Below are all the method calls you will need to handle.
def available_discoverers(self, caller: Application) -> list:
return [d.__class__.__name__ for d in self.discoverers]
def available_networks(self, caller: Application) -> list:
return [LibPeerUnix.Models.Network(n.identifier, n.__class__.__name__, n.up) for n in self.networks]
def available_transports(self, caller: Application) -> list:
return [LibPeerUnix.Models.Transport(t.identifier, t.__class__.__name__) for t in self.transports]
def bind(self, caller: Application, application: bytes):
# Make sure no other application is currently bound
if(application in self.namespace_app):
raise LibPeerUnix.Exceptions.NamespaceOccupiedError("Can not bind to the namespace '%s' as it is already in use" % application.decode("utf-8"))
# Set the namespace's app to be the caller
self.namespace_app[application] = caller
# Now set the application's namespace
self.app_namespace[caller] = application
# Give the application a label collection
self.application_labels[caller] = LabelCollection()
# Create a new collection for our discoveries dict
self.discoveries[application] = PeerCollection()
# Start listening for data addressed to this namespace
self.muxer.add_application(application)
# Start listening for advertisments with this namespace
for discoverer in self.discoverers:
discoverer.add_application(application)
def set_discoverable(self, caller: Application, discoverable: bool):
# Make sure the application has bound to a namespace
self.ensure_bound(caller)
if(caller in self.applications_advertised and not discoverable):
self.applications_advertised.remove(caller)
else:
# Add the app to the advertised list
self.applications_advertised.add(caller)
# Create an advertiser thread for each discoverer
for discoverer in self.discoverers:
threading.Thread(target=self.advertiser, args=(caller, discoverer)).start()
def add_label(self, caller: Application, label: bytes):
# Make sure the application has bound to a namespace
self.ensure_bound(caller)
# Add the label
self.application_labels[caller].add_label(label)
def remove_label(self, caller: Application, label: bytes):
# Make sure the application has bound to a namespace
self.ensure_bound(caller)
# Remove the label
self.application_labels[caller].remove_label(label)
def clear_labels(self, caller: Application):
# Make sure the application has bound to a namespace
self.ensure_bound(caller)
# Clear the labes
self.application_labels[caller].clear_labels()
def get_peers(self, caller: Application) -> list:
# Make sure the application has bound to a namespace
self.ensure_bound(caller)
# Get all peers under the namespace
return self.discoveries[self.app_namespace[caller]].get_peer_models()
def get_labelled_peers(self, caller: Application, label: bytes) -> list:
# Make sure the application has bound to a namespace
self.ensure_bound(caller)
# Get all peers under the namespace with a label
return self.discoveries[self.app_namespace[caller]].get_peer_models_with_label(label)
def send(self, caller: Application, message: LibPeerUnix.Models.Message):
# Make sure the application has bound to a namespace
self.ensure_bound(caller)
# Get the transport to send the message with
transport: Transport = self.transport_map[message.transport]
# Create the BinaryAddress to send the message with
address = BinaryAddress(message.address.protocol, message.address.address, message.address.port, self.app_namespace[caller])
# Defer the result until the sending has completed
defer = Defer()
# Get the namespace priority (out of 10, default 5)
priority = 5
if(address.application in self.namespace_priorities):
priority = self.namespace_priorities[address.application]
# Create the TransmitItem
item = TransmitItem(transport, message.payload, message.channel, address, defer, priority)
# Add the item to the queue
self.tx_queue.put(item)
# Return the defered result
return defer
def close(self, caller: Application):
# Make sure the application has bound to a namespace
self.ensure_bound(caller)
# Get the namespace of the caller
namespace = self.app_namespace[caller]
# Notify muxer
self.muxer.remove_application(namespace)
# Stop discovering
for discoverer in self.discoverers:
discoverer.add_application(namespace)
# Remove dict entries
del self.application_labels[caller]
del self.discoveries[namespace]
del self.namespace_app[namespace]
# Remove namespace last
del self.app_namespace[caller]
def transmitter(self):
# TODO add proper shutdown
while True:
# Queue of TransmitItems
self.tx_queue.get().execute()
# If you run this module, it will run your daemon class above
if __name__ == '__main__':
log.settings(True, 0)
daemon = LibPeerUnixServer()