source: trunk/src/allmydata/web/logs.py

Last change on this file was b856238, checked in by Alexandre Detiste <alexandre.detiste@…>, at 2024-02-15T15:53:34Z

remove old Python2 future statements

  • Property mode set to 100644
File size: 2.0 KB
Line 
1"""
2Ported to Python 3.
3"""
4
5from autobahn.twisted.resource import WebSocketResource
6from autobahn.twisted.websocket import (
7    WebSocketServerFactory,
8    WebSocketServerProtocol,
9)
10import eliot
11
12from twisted.web.resource import (
13    Resource,
14)
15
16from allmydata.util import jsonbytes as json
17
18
19class TokenAuthenticatedWebSocketServerProtocol(WebSocketServerProtocol):
20    """
21    A WebSocket protocol that looks for an `Authorization:` header
22    with a `tahoe-lafs` scheme and a token matching our private config
23    for `api_auth_token`.
24    """
25
26    def onConnect(self, req):
27        """
28        WebSocket callback
29        """
30        # we don't care what WebSocket sub-protocol is
31        # negotiated, nor do we need to send headers to the
32        # client, so we ask Autobahn to just allow this
33        # connection with the defaults. We could return a
34        # (headers, protocol) pair here instead if required.
35        return None
36
37    def _received_eliot_log(self, message):
38        """
39        While this WebSocket connection is open, this function is
40        registered as an eliot destination
41        """
42        # probably want a try/except around here? what do we do if
43        # transmission fails or anything else bad happens?
44        encoded = json.dumps_bytes(message, any_bytes=True)
45        self.sendMessage(encoded)
46
47    def onOpen(self):
48        """
49        WebSocket callback
50        """
51        eliot.add_destination(self._received_eliot_log)
52
53    def onClose(self, wasClean, code, reason):
54        """
55        WebSocket callback
56        """
57        try:
58            eliot.remove_destination(self._received_eliot_log)
59        except ValueError:
60            pass
61
62
63def create_log_streaming_resource():
64    factory = WebSocketServerFactory()
65    factory.protocol = TokenAuthenticatedWebSocketServerProtocol
66    return WebSocketResource(factory)
67
68
69def create_log_resources():
70    logs = Resource()
71    logs.putChild(b"v1", create_log_streaming_resource())
72    return logs
Note: See TracBrowser for help on using the repository browser.