Skip to content

Commit 0847df8

Browse files
committed
[WIP] implementation for /exec using websocket
Fixes kubernetes-client#58
1 parent 1d3cd13 commit 0847df8

File tree

6 files changed

+151
-13
lines changed

6 files changed

+151
-13
lines changed

kubernetes/client/api_client.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
from __future__ import absolute_import
2222

2323
from . import models
24+
from . import ws_client
2425
from .rest import RESTClientObject
2526
from .rest import ApiException
2627

@@ -343,6 +344,13 @@ def request(self, method, url, query_params=None, headers=None,
343344
"""
344345
Makes the HTTP request using RESTClient.
345346
"""
347+
if url.endswith('/exec') and method == "GET":
348+
return ws_client.GET(self.config,
349+
url,
350+
query_params=query_params,
351+
_request_timeout=_request_timeout,
352+
headers=headers)
353+
346354
if method == "GET":
347355
return self.rest_client.GET(url,
348356
query_params=query_params,

kubernetes/client/apis/core_v1_api.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1007,7 +1007,7 @@ def connect_get_namespaced_pod_exec_with_http_info(self, name, namespace, **kwar
10071007
auth_settings=auth_settings,
10081008
callback=params.get('callback'),
10091009
_return_http_data_only=params.get('_return_http_data_only'),
1010-
_preload_content=params.get('_preload_content', True),
1010+
_preload_content=params.get('_preload_content', False),
10111011
_request_timeout=params.get('_request_timeout'),
10121012
collection_formats=collection_formats)
10131013

kubernetes/client/ws_client.py

Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
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+
from .configuration import configuration
14+
from .rest import ApiException
15+
16+
import websocket
17+
import six
18+
import ssl
19+
from six.moves.urllib.parse import urlencode
20+
from six.moves.urllib.parse import quote_plus
21+
22+
23+
class WSClient:
24+
def __init__(self, configuration, url):
25+
self.messages = []
26+
self.errors = []
27+
websocket.enableTrace(False)
28+
self.ws = websocket.WebSocketApp(url,
29+
on_message=self.on_message,
30+
on_error=self.on_error,
31+
on_close=self.on_close,
32+
header=[])
33+
self.ws.on_open = self.on_open
34+
sslopt = None
35+
if url.startswith('wss://'):
36+
sslopt = {"cert_reqs": ssl.CERT_NONE}
37+
self.ws.run_forever(sslopt=sslopt)
38+
39+
def on_message(self, ws, message):
40+
if message[0] == '\x01':
41+
message = message[1:]
42+
if message:
43+
if six.PY3 and isinstance(message, six.binary_type):
44+
message = message.decode('utf-8')
45+
self.messages.append(message)
46+
47+
def on_error(self, ws, error):
48+
self.errors.append(error)
49+
50+
def on_close(self, ws):
51+
pass
52+
53+
def on_open(self, ws):
54+
pass
55+
56+
57+
def GET(configuration, url, query_params, _request_timeout, headers):
58+
# switch protocols from http to websocket
59+
url = url.replace('http://', 'ws://')
60+
url = url.replace('https://', 'wss://')
61+
62+
# patch extra /
63+
url = url.replace('//api', '/api')
64+
65+
# Extract the command from the list of tuples
66+
commands = None
67+
for key, value in query_params:
68+
if key == 'command':
69+
commands = value
70+
break
71+
72+
# drop command from query_params as we will be processing it separately
73+
query_params = [(key, value) for key, value in query_params if
74+
key != 'command']
75+
76+
# if we still have query params then encode them
77+
if query_params:
78+
url += '?' + urlencode(query_params)
79+
80+
# tack on the actual command to execute at the end
81+
if isinstance(commands, list):
82+
for command in commands:
83+
url += "&command=%s&" % quote_plus(command)
84+
else:
85+
url += '&command=' + quote_plus(commands)
86+
87+
client = WSClient(configuration, url)
88+
if client.errors:
89+
raise ApiException(
90+
status=0,
91+
reason='\n'.join([str(error) for error in client.errors])
92+
)
93+
return '\n'.join(client.messages)

kubernetes/e2e_test/test_client.py

Lines changed: 46 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
# License for the specific language governing permissions and limitations
1313
# under the License.
1414

15+
import time
1516
import unittest
1617
import uuid
1718

@@ -27,22 +28,57 @@ def test_pod_apis(self):
2728
client = api_client.ApiClient('http://127.0.0.1:8080/')
2829
api = core_v1_api.CoreV1Api(client)
2930

30-
name = 'test-' + str(uuid.uuid4())
31-
pod_manifest = {'apiVersion': 'v1',
32-
'kind': 'Pod',
33-
'metadata': {'color': 'blue', 'name': name},
34-
'spec': {'containers': [{'image': 'dockerfile/redis',
35-
'name': 'redis'}]}}
31+
name = 'busybox-test-' + str(uuid.uuid4())
32+
pod_manifest = {
33+
'apiVersion': 'v1',
34+
'kind': 'Pod',
35+
'metadata': {
36+
'name': name
37+
},
38+
'spec': {
39+
'containers': [{
40+
'image': 'busybox',
41+
'name': 'sleep',
42+
"args": [
43+
"/bin/sh",
44+
"-c",
45+
"while true;do date;sleep 5; done"
46+
]
47+
}]
48+
}
49+
}
3650

3751
resp = api.create_namespaced_pod(body=pod_manifest,
3852
namespace='default')
3953
self.assertEqual(name, resp.metadata.name)
4054
self.assertTrue(resp.status.phase)
4155

42-
resp = api.read_namespaced_pod(name=name,
43-
namespace='default')
44-
self.assertEqual(name, resp.metadata.name)
45-
self.assertTrue(resp.status.phase)
56+
while True:
57+
resp = api.read_namespaced_pod(name=name,
58+
namespace='default')
59+
self.assertEqual(name, resp.metadata.name)
60+
self.assertTrue(resp.status.phase)
61+
print(">>>> pod status : %r" % resp.status.phase)
62+
if resp.status.phase != 'Pending':
63+
break
64+
else:
65+
time.sleep(1)
66+
67+
# exec_command = 'uptime'
68+
# resp = api.connect_get_namespaced_pod_exec(name, 'default',
69+
# command=exec_command,
70+
# stderr=False, stdin=False,
71+
# stdout=True, tty=False)
72+
# print('EXEC response : %s' % resp)
73+
74+
exec_command = ['/bin/sh',
75+
'-c',
76+
'for i in $(seq 1 3); do date; sleep 1; done']
77+
resp = api.connect_get_namespaced_pod_exec(name, 'default',
78+
command=exec_command,
79+
stderr=False, stdin=False,
80+
stdout=True, tty=False)
81+
print('EXEC response : %s' % resp)
4682

4783
number_of_pods = len(api.list_pod_for_all_namespaces().items)
4884
self.assertTrue(number_of_pods > 0)

requirements.txt

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
certifi >= 14.05.14
2-
six == 1.8.0
2+
six>=1.9.0
33
python_dateutil >= 2.5.3
44
setuptools >= 21.0.0
55
urllib3 >= 1.19.1
66
pyyaml >= 3.12
77
oauth2client >= 4.0.0
88
ipaddress >= 1.0.17
9-
9+
websocket-client>=0.32.0

tox.ini

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ passenv = TOXENV CI TRAVIS TRAVIS_*
66
usedevelop = True
77
install_command = pip install -U {opts} {packages}
88
deps = -r{toxinidir}/test-requirements.txt
9+
-r{toxinidir}/requirements.txt
910
commands =
1011
python -V
1112
nosetests []

0 commit comments

Comments
 (0)