source: trunk/ws_client.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.1 KB
Line 
1
2import sys
3import json
4
5from twisted.internet.error import ConnectError
6from twisted.internet.task import react
7from twisted.internet.defer import inlineCallbacks, Deferred
8from twisted.internet.endpoints import HostnameEndpoint
9
10from autobahn.twisted.websocket import (
11    WebSocketClientProtocol,
12    WebSocketClientFactory,
13)
14
15from allmydata.client import read_config
16
17
18class TahoeLogProtocol(WebSocketClientProtocol):
19    """
20    """
21
22    def onOpen(self):
23        self.factory.on_open.callback(self)
24
25    def onMessage(self, payload, isBinary):
26        if False:
27            log_data = json.loads(payload.decode('utf8'))
28            print("eliot message:")
29            for k, v in log_data.items():
30                print("  {}: {}".format(k, v))
31        else:
32            print(payload)
33            sys.stdout.flush()
34
35    def onClose(self, *args):
36        if not self.factory.on_open.called:
37            self.factory.on_open.errback(
38                RuntimeError("Failed: {}".format(args))
39            )
40        self.factory.on_close.callback(self)
41
42
43@inlineCallbacks
44def main(reactor):
45
46    from twisted.python import log
47    log.startLogging(sys.stdout)
48
49    tahoe_dir = "testgrid/alice"
50    cfg = read_config(tahoe_dir, "portnum")
51
52    token = cfg.get_private_config("api_auth_token").strip()
53    webport = cfg.get_config("node", "web.port")
54    if webport.startswith("tcp:"):
55        port = webport.split(':')[1]
56    else:
57        port = webport
58
59    factory = WebSocketClientFactory(
60        url=u"ws://127.0.0.1:{}/private/logs/v1".format(port),
61        headers={
62            "Authorization": "tahoe-lafs {}".format(token),
63        }
64    )
65    factory.on_open = Deferred()
66    factory.on_close = Deferred()
67
68    factory.protocol = TahoeLogProtocol
69
70    endpoint = HostnameEndpoint(reactor, "127.0.0.1", int(port))
71    try:
72        port = yield endpoint.connect(factory)
73    except ConnectError as e:
74        print("Connection failed: {}".format(e))
75        return
76
77    print("port: {}".format(port))
78    yield factory.on_open
79    print("opened")
80    yield factory.on_close
81    print("closed")
82
83
84
85if __name__ == '__main__':
86    react(main)
Note: See TracBrowser for help on using the repository browser.