Debian Codegraph @

etcd3gw/watch.py

raw symbols SCIP
1 # Licensed under the Apache License, Version 2.0 (the "License"); you may
2 # not use this file except in compliance with the License. You may obtain
3 # a copy of the License at
4 #
5 # http://www.apache.org/licenses/LICENSE-2.0
6 #
7 # Unless required by applicable law or agreed to in writing, software
8 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
9 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
10 # License for the specific language governing permissions and limitations
11 # under the License.
12
13 import json
14 import socket
15
16 from etcd3gw.utils import _decode
17 from etcd3gw.utils import _encode
18 from etcd3gw.utils import _get_threadpool_executor
19
20
21 def _watch(resp, callback):
22 for line in resp.iter_content(chunk_size=None, decode_unicode=False):
23 decoded_line = line.decode('utf-8')
24 # Skip a possible empty line (only "\n")
25 # https://bugs.launchpad.net/python-etcd3gw/+bug/2072492
26 if not decoded_line.strip():
27 continue
28 payload = json.loads(decoded_line)
29 if 'created' in payload['result']:
30 if payload['result']['created']:
31 continue
32 else:
33 raise Exception('Unable to create watch')
34 if 'events' in payload['result']:
35 for event in payload['result']['events']:
36 event['kv']['key'] = _decode(event['kv']['key'])
37 if 'value' in event['kv']:
38 event['kv']['value'] = _decode(event['kv']['value'])
39 callback(event)
40
41
42 class Watcher:
43
44 KW_ARGS = ['start_revision', 'progress_notify', 'filters', 'prev_kv']
45 KW_ENCODED_ARGS = ['range_end']
46
47 def __init__(self, client, key, callback, **kwargs):
48 create_watch = {
49 'key': _encode(key)
50 }
51
52 for arg in kwargs:
53 if arg in self.KW_ARGS:
54 create_watch[arg] = kwargs[arg]
55 elif arg in self.KW_ENCODED_ARGS:
56 create_watch[arg] = _encode(kwargs[arg])
57
58 create_request = {
59 "create_request": create_watch
60 }
61 self._response = client.session.post(client.get_url('/watch'),
62 json=create_request,
63 stream=True)
64
65 clazz = _get_threadpool_executor()
66 self._executor = clazz(max_workers=2)
67 self._executor.submit(_watch, self._response, callback)
68
69 def stop(self):
70 try:
71 s = socket.fromfd(self._response.raw._fp.fileno(),
72 socket.AF_INET,
73 socket.SOCK_STREAM)
74 s.shutdown(socket.SHUT_RDWR)
75 s.close()
76 except Exception:
77 pass
78 self._response.connection.close()
79 self._executor.shutdown(wait=False)