source: trunk/ws_client.py

Last change on this file was 9ec2259, checked in by Jean-Paul Calderone <exarkun@…>, at 2019-03-21T19:00:02Z

move to different url

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