Skip to content

Commit d1d2507

Browse files
committed
Improvements on ws_client. Now the client can returns an object to interact with websocket server and reach each channel separately
1 parent 1635150 commit d1d2507

File tree

5 files changed

+253
-47
lines changed

5 files changed

+253
-47
lines changed

examples/exec.py

Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
import time
2+
3+
from kubernetes import config
4+
from kubernetes.client import configuration
5+
from kubernetes.client.apis import core_v1_api
6+
from kubernetes.client.rest import ApiException
7+
8+
config.load_kube_config()
9+
configuration.assert_hostname = False
10+
api = core_v1_api.CoreV1Api()
11+
name = 'busybox-test'
12+
13+
resp = None
14+
try:
15+
resp = api.read_namespaced_pod(name=name,
16+
namespace='default')
17+
except ApiException as e:
18+
if e.status != 404:
19+
print("Unknown error: %s" % e)
20+
exit(1)
21+
22+
if not resp:
23+
print("Pod %s does not exits. Creating it..." % name)
24+
pod_manifest = {
25+
'apiVersion': 'v1',
26+
'kind': 'Pod',
27+
'metadata': {
28+
'name': name
29+
},
30+
'spec': {
31+
'containers': [{
32+
'image': 'busybox',
33+
'name': 'sleep',
34+
"args": [
35+
"/bin/sh",
36+
"-c",
37+
"while true;do date;sleep 5; done"
38+
]
39+
}]
40+
}
41+
}
42+
resp = api.create_namespaced_pod(body=pod_manifest,
43+
namespace='default')
44+
while True:
45+
resp = api.read_namespaced_pod(name=name,
46+
namespace='default')
47+
if resp.status.phase != 'Pending':
48+
break
49+
time.sleep(1)
50+
print("Done.")
51+
52+
53+
# calling exec and wait for response.
54+
exec_command = [
55+
'/bin/sh',
56+
'-c',
57+
'echo This message goes to stderr >&2; echo This message goes to stdout']
58+
resp = api.connect_get_namespaced_pod_exec(name, 'default',
59+
command=exec_command,
60+
stderr=True, stdin=False,
61+
stdout=True, tty=False)
62+
print("Response: " + resp)
63+
64+
# Calling exec interactively.
65+
exec_command = ['/bin/sh']
66+
resp = api.connect_get_namespaced_pod_exec(name, 'default',
67+
command=exec_command,
68+
stderr=True, stdin=True,
69+
stdout=True, tty=False,
70+
71+
_preload_content=False)
72+
commands = [
73+
"echo test1",
74+
"echo \"This message goes to stderr\" >&2",
75+
]
76+
while resp.is_open():
77+
resp.update(timeout=1)
78+
if resp.peek_stdout():
79+
print("STDOUT: %s" % resp.read_stdout())
80+
if resp.peek_stderr():
81+
print("STDERR: %s" % resp.read_stderr())
82+
if commands:
83+
c = commands.pop(0)
84+
print("Running command... %s\n" % c)
85+
resp.write_stdin(c + "\n")
86+
else:
87+
break
88+
89+
resp.write_stdin("date\n")
90+
sdate = resp.readline_stdout(timeout=3)
91+
print("Server date command returns: %s" % sdate)
92+
resp.write_stdin("whoami\n")
93+
user = resp.readline_stdout(timeout=3)
94+
print("Server user is: %s" % user)

kubernetes/client/api_client.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -351,6 +351,7 @@ def request(self, method, url, query_params=None, headers=None,
351351
url,
352352
query_params=query_params,
353353
_request_timeout=_request_timeout,
354+
_preload_content=_preload_content,
354355
headers=headers)
355356

356357
if method == "GET":

kubernetes/client/ws_client.py

Lines changed: 126 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -12,33 +12,33 @@
1212

1313
from .rest import ApiException
1414

15+
import select
1516
import certifi
17+
import time
1618
import collections
17-
import websocket
19+
from websocket import WebSocket, ABNF, enableTrace
1820
import six
1921
import ssl
2022
from six.moves.urllib.parse import urlencode
2123
from six.moves.urllib.parse import quote_plus
2224

25+
STDIN_CHANNEL = 0
26+
STDOUT_CHANNEL = 1
27+
STDERR_CHANNEL = 2
28+
2329

2430
class WSClient:
2531
def __init__(self, configuration, url, headers):
26-
self.messages = []
27-
self.errors = []
28-
websocket.enableTrace(False)
29-
header = None
32+
enableTrace(False)
33+
header = []
34+
self._connected = False
35+
self._channels = {}
36+
self._all = ""
3037

3138
# We just need to pass the Authorization, ignore all the other
3239
# http headers we get from the generated code
3340
if 'Authorization' in headers:
34-
header = "Authorization: %s" % headers['Authorization']
35-
36-
self.ws = websocket.WebSocketApp(url,
37-
on_message=self.on_message,
38-
on_error=self.on_error,
39-
on_close=self.on_close,
40-
header=[header] if header else None)
41-
self.ws.on_open = self.on_open
41+
header.append("Authorization: %s" % headers['Authorization'])
4242

4343
if url.startswith('wss://') and configuration.verify_ssl:
4444
ssl_opts = {
@@ -52,30 +52,118 @@ def __init__(self, configuration, url, headers):
5252
else:
5353
ssl_opts = {'cert_reqs': ssl.CERT_NONE}
5454

55-
self.ws.run_forever(sslopt=ssl_opts)
56-
57-
def on_message(self, ws, message):
58-
if message[0] == '\x01':
59-
message = message[1:]
60-
if message:
61-
if six.PY3 and isinstance(message, six.binary_type):
62-
message = message.decode('utf-8')
63-
self.messages.append(message)
55+
self.sock = WebSocket(sslopt=ssl_opts, skip_utf8_validation=False)
56+
self.sock.connect(url, header=header)
57+
self._connected = True
6458

65-
def on_error(self, ws, error):
66-
self.errors.append(error)
59+
def peek_channel(self, channel, timeout=0):
60+
self.update(timeout=timeout)
61+
if channel in self._channels:
62+
return self._channels[channel]
63+
return ""
6764

68-
def on_close(self, ws):
69-
pass
70-
71-
def on_open(self, ws):
72-
pass
65+
def read_channel(self, channel, timeout=0):
66+
if channel not in self._channels:
67+
ret = self.peek_channel(channel, timeout)
68+
else:
69+
ret = self._channels[channel]
70+
if channel in self._channels:
71+
del self._channels[channel]
72+
return ret
73+
74+
def readline_channel(self, channel, timeout=None):
75+
if timeout is None:
76+
timeout = float("inf")
77+
start = time.time()
78+
while self.is_open() and time.time() - start < timeout:
79+
if channel in self._channels:
80+
data = self._channels[channel]
81+
if "\n" in data:
82+
index = data.find("\n")
83+
ret = data[:index]
84+
data = data[index+1:]
85+
if data:
86+
self._channels[channel] = data
87+
else:
88+
del self._channels[channel]
89+
return ret
90+
self.update(timeout=(timeout - time.time() + start))
91+
92+
def write_channel(self, channel, data):
93+
self.sock.send(chr(channel) + data)
94+
95+
def peek_stdout(self, timeout=0):
96+
return self.peek_channel(STDOUT_CHANNEL, timeout=timeout)
97+
98+
def read_stdout(self, timeout=None):
99+
return self.read_channel(STDOUT_CHANNEL, timeout=timeout)
100+
101+
def readline_stdout(self, timeout=None):
102+
return self.readline_channel(STDOUT_CHANNEL, timeout=timeout)
103+
104+
def peek_stderr(self, timeout=0):
105+
return self.peek_channel(STDERR_CHANNEL, timeout=timeout)
106+
107+
def read_stderr(self, timeout=None):
108+
return self.read_channel(STDERR_CHANNEL, timeout=timeout)
109+
110+
def readline_stderr(self, timeout=None):
111+
return self.readline_channel(STDERR_CHANNEL, timeout=timeout)
112+
113+
def read_all(self):
114+
out = self._all
115+
self._all = ""
116+
self._channels = {}
117+
return out
118+
119+
def is_open(self):
120+
return self._connected
121+
122+
def write_stdin(self, data):
123+
self.write_channel(STDIN_CHANNEL, data)
124+
125+
def update(self, timeout=0):
126+
if not self.is_open():
127+
return
128+
if not self.sock.connected:
129+
self._connected = False
130+
return
131+
r, _, _ = select.select(
132+
(self.sock.sock, ), (), (), timeout)
133+
if r:
134+
op_code, frame = self.sock.recv_data_frame(True)
135+
if op_code == ABNF.OPCODE_CLOSE:
136+
self._connected = False
137+
return
138+
elif op_code == ABNF.OPCODE_BINARY or op_code == ABNF.OPCODE_TEXT:
139+
data = frame.data
140+
if six.PY3:
141+
data = data.decode("utf-8")
142+
self._all += data
143+
if len(data) > 1:
144+
channel = ord(data[0])
145+
data = data[1:]
146+
if data:
147+
if channel not in self._channels:
148+
self._channels[channel] = data
149+
else:
150+
self._channels[channel] += data
151+
152+
def run_forever(self, timeout=None):
153+
if timeout:
154+
start = time.time()
155+
while self.is_open() and time.time() - start < timeout:
156+
self.update(timeout=(timeout - time.time() + start))
157+
else:
158+
while self.is_open():
159+
self.update(timeout=None)
73160

74161

75162
WSResponse = collections.namedtuple('WSResponse', ['data'])
76163

77164

78-
def GET(configuration, url, query_params, _request_timeout, headers):
165+
def GET(configuration, url, query_params, _request_timeout, _preload_content,
166+
headers):
79167
# switch protocols from http to websocket
80168
url = url.replace('http://', 'ws://')
81169
url = url.replace('https://', 'wss://')
@@ -105,10 +193,11 @@ def GET(configuration, url, query_params, _request_timeout, headers):
105193
else:
106194
url += '&command=' + quote_plus(commands)
107195

108-
client = WSClient(configuration, url, headers)
109-
if client.errors:
110-
raise ApiException(
111-
status=0,
112-
reason='\n'.join([str(error) for error in client.errors])
113-
)
114-
return WSResponse('%s' % ''.join(client.messages))
196+
try:
197+
client = WSClient(configuration, url, headers)
198+
if not _preload_content:
199+
return client
200+
client.run_forever(timeout=_request_timeout)
201+
return WSResponse('%s' % ''.join(client.read_all()))
202+
except (Exception, KeyboardInterrupt, SystemExit) as e:
203+
raise ApiException(status=0, reason=str(e))

kubernetes/e2e_test/base.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,4 +42,5 @@ def get_e2e_configuration():
4242
if config.host is None:
4343
raise unittest.SkipTest('Unable to find a running Kubernetes instance')
4444
print('Running test against : %s' % config.host)
45+
config.assert_hostname = False
4546
return config

0 commit comments

Comments
 (0)