3410: Add replication attributes (and rules about updating them) to model and docs.
[arvados.git] / sdk / python / arvados / events.py
1 import arvados
2 import config
3 import errors
4
5 import logging
6 import json
7 import threading
8 import time
9 import os
10 import re
11 import ssl
12 from ws4py.client.threadedclient import WebSocketClient
13
14 _logger = logging.getLogger('arvados.events')
15
16 class EventClient(WebSocketClient):
17     def __init__(self, url, filters, on_event):
18         # Prefer system's CA certificates (if available)
19         ssl_options = {}
20         certs_path = '/etc/ssl/certs/ca-certificates.crt'
21         if os.path.exists(certs_path):
22             ssl_options['ca_certs'] = certs_path
23         if config.flag_is_true('ARVADOS_API_HOST_INSECURE'):
24             ssl_options['cert_reqs'] = ssl.CERT_NONE
25         else:
26             ssl_options['cert_reqs'] = ssl.CERT_REQUIRED
27
28         # Warning: If the host part of url resolves to both IPv6 and
29         # IPv4 addresses (common with "localhost"), only one of them
30         # will be attempted -- and it might not be the right one. See
31         # ws4py's WebSocketBaseClient.__init__.
32         super(EventClient, self).__init__(url, ssl_options=ssl_options)
33         self.filters = filters
34         self.on_event = on_event
35
36     def opened(self):
37         self.subscribe(self.filters)
38
39     def received_message(self, m):
40         self.on_event(json.loads(str(m)))
41
42     def close_connection(self):
43         try:
44             self.sock.shutdown(socket.SHUT_RDWR)
45             self.sock.close()
46         except:
47             pass
48
49     def subscribe(self, filters, last_log_id=None):
50         m = {"method": "subscribe", "filters": filters}
51         if last_log_id is not None:
52             m["last_log_id"] = last_log_id
53         self.send(json.dumps(m))
54
55     def unsubscribe(self, filters):
56         self.send(json.dumps({"method": "unsubscribe", "filters": filters}))
57
58 class PollClient(threading.Thread):
59     def __init__(self, api, filters, on_event, poll_time):
60         super(PollClient, self).__init__()
61         self.api = api
62         if filters:
63             self.filters = [filters]
64         else:
65             self.filters = [[]]
66         self.on_event = on_event
67         self.poll_time = poll_time
68         self.stop = threading.Event()
69
70     def run(self):
71         self.id = 0
72         for f in self.filters:
73             items = self.api.logs().list(limit=1, order="id desc", filters=f).execute()['items']
74             if items:
75                 if items[0]['id'] > self.id:
76                     self.id = items[0]['id']
77
78         self.on_event({'status': 200})
79
80         while not self.stop.isSet():
81             max_id = self.id
82             for f in self.filters:
83                 items = self.api.logs().list(order="id asc", filters=f+[["id", ">", str(self.id)]]).execute()['items']
84                 for i in items:
85                     if i['id'] > max_id:
86                         max_id = i['id']
87                     self.on_event(i)
88             self.id = max_id
89             self.stop.wait(self.poll_time)
90
91     def run_forever(self):
92         # Have to poll here, otherwise KeyboardInterrupt will never get processed.
93         while not self.stop.is_set():
94             self.stop.wait(1)
95
96     def close(self):
97         self.stop.set()
98         try:
99             self.join()
100         except RuntimeError:
101             # "join() raises a RuntimeError if an attempt is made to join the
102             # current thread as that would cause a deadlock. It is also an
103             # error to join() a thread before it has been started and attempts
104             # to do so raises the same exception."
105             pass
106
107     def subscribe(self, filters):
108         self.on_event({'status': 200})
109         self.filters.append(filters)
110
111     def unsubscribe(self, filters):
112         del self.filters[self.filters.index(filters)]
113
114
115 def _subscribe_websocket(api, filters, on_event):
116     endpoint = api._rootDesc.get('websocketUrl', None)
117     if not endpoint:
118         raise errors.FeatureNotEnabledError(
119             "Server does not advertise a websocket endpoint")
120     uri_with_token = "{}?api_token={}".format(endpoint, api.api_token)
121     client = EventClient(uri_with_token, filters, on_event)
122     ok = False
123     try:
124         client.connect()
125         ok = True
126         return client
127     finally:
128         if not ok:
129             client.close_connection()
130
131 def subscribe(api, filters, on_event, poll_fallback=15):
132     '''
133     api: a client object retrieved from arvados.api(). The caller should not use this client object for anything else after calling subscribe().
134     filters: Initial subscription filters.
135     on_event: The callback when a message is received.
136     poll_fallback: If websockets are not available, fall back to polling every N seconds.  If poll_fallback=False, this will return None if websockets are not available.
137     '''
138     if not poll_fallback:
139         return _subscribe_websocket(api, filters, on_event)
140
141     try:
142         return _subscribe_websocket(api, filters, on_event)
143     except Exception as e:
144         _logger.warn("Falling back to polling after websocket error: %s" % e)
145     p = PollClient(api, filters, on_event, poll_fallback)
146     p.start()
147     return p