|
1 | 1 | from __future__ import absolute_import
|
2 | 2 |
|
3 | 3 | import json
|
| 4 | +import logging |
4 | 5 |
|
5 | 6 | import websocket
|
6 | 7 |
|
7 | 8 | import dockercloud
|
8 | 9 | from .base import StreamingAPI
|
9 | 10 | from .exceptions import AuthError
|
10 | 11 |
|
| 12 | +logger = logging.getLogger("python-dockercloud") |
| 13 | + |
11 | 14 |
|
12 | 15 | class Events(StreamingAPI):
|
13 | 16 | def __init__(self):
|
14 | 17 | endpoint = "events"
|
15 | 18 | url = "/".join([dockercloud.stream_host.rstrip("/"), "api", "audit", self._api_version, endpoint.lstrip("/")])
|
| 19 | + self.invaid_auth_headers = set() |
| 20 | + self.auth_error = "" |
16 | 21 | super(self.__class__, self).__init__(url)
|
17 | 22 |
|
18 | 23 | def _on_message(self, ws, message):
|
| 24 | + logger.info("Websocket Message: %s" % message) |
19 | 25 | try:
|
20 | 26 | event = json.loads(message)
|
21 | 27 | except ValueError:
|
22 | 28 | return
|
23 |
| - |
24 |
| - if event.get("type") == "error" and event.get("data", {}).get("errorMessage") == "UNAUTHORIZED": |
25 |
| - self.auth_error = True |
26 |
| - raise AuthError("Not authorized") |
27 | 29 | if event.get("type") == "auth":
|
28 | 30 | return
|
29 | 31 |
|
30 | 32 | if self.message_handler:
|
31 | 33 | self.message_handler(message)
|
32 | 34 |
|
| 35 | + def _on_error(self, ws, e): |
| 36 | + if isinstance(e, websocket._exceptions.WebSocketBadStatusException) and getattr(e, "status_code") == 401: |
| 37 | + self.auth_error = "Not Authorized" |
| 38 | + self.invaid_auth_headers.add(str(dockercloud.auth.get_auth_header())) |
| 39 | + |
| 40 | + super(self.__class__, self)._on_error(ws, e) |
| 41 | + |
33 | 42 | def run_forever(self, *args, **kwargs):
|
34 | 43 | while True:
|
35 |
| - if self.auth_error: |
36 |
| - raise AuthError("Not authorized") |
| 44 | + if str(dockercloud.auth.get_auth_header()) in self.invaid_auth_headers: |
| 45 | + raise AuthError(self.auth_error) |
37 | 46 | ws = websocket.WebSocketApp(self.url, header=self.header,
|
38 | 47 | on_open=self._on_open,
|
39 | 48 | on_message=self._on_message,
|
|
0 commit comments