Skip to content

Commit cfd34ef

Browse files
authored
Merge pull request #120 from dims/support-exec-calls
Implementation for /exec using websocket
2 parents 192b67c + 066bba1 commit cfd34ef

File tree

5 files changed

+165
-12
lines changed

5 files changed

+165
-12
lines changed

kubernetes/client/api_client.py

Lines changed: 10 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,15 @@ def request(self, method, url, query_params=None, headers=None,
343344
"""
344345
Makes the HTTP request using RESTClient.
345346
"""
347+
# FIXME(dims) : We need a better way to figure out which
348+
# calls end up using web sockets
349+
if url.endswith('/exec') and method == "GET":
350+
return ws_client.GET(self.config,
351+
url,
352+
query_params=query_params,
353+
_request_timeout=_request_timeout,
354+
headers=headers)
355+
346356
if method == "GET":
347357
return self.rest_client.GET(url,
348358
query_params=query_params,

kubernetes/client/ws_client.py

Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,114 @@
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 .rest import ApiException
14+
15+
import certifi
16+
import collections
17+
import websocket
18+
import six
19+
import ssl
20+
from six.moves.urllib.parse import urlencode
21+
from six.moves.urllib.parse import quote_plus
22+
23+
24+
class WSClient:
25+
def __init__(self, configuration, url, headers):
26+
self.messages = []
27+
self.errors = []
28+
websocket.enableTrace(False)
29+
header = None
30+
31+
# We just need to pass the Authorization, ignore all the other
32+
# http headers we get from the generated code
33+
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
42+
43+
if url.startswith('wss://') and configuration.verify_ssl:
44+
ssl_opts = {
45+
'cert_reqs': ssl.CERT_REQUIRED,
46+
'keyfile': configuration.key_file,
47+
'certfile': configuration.cert_file,
48+
'ca_certs': configuration.ssl_ca_cert or certifi.where(),
49+
}
50+
if configuration.assert_hostname is not None:
51+
ssl_opts['check_hostname'] = configuration.assert_hostname
52+
else:
53+
ssl_opts = {'cert_reqs': ssl.CERT_NONE}
54+
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)
64+
65+
def on_error(self, ws, error):
66+
self.errors.append(error)
67+
68+
def on_close(self, ws):
69+
pass
70+
71+
def on_open(self, ws):
72+
pass
73+
74+
75+
WSResponse = collections.namedtuple('WSResponse', ['data'])
76+
77+
78+
def GET(configuration, url, query_params, _request_timeout, headers):
79+
# switch protocols from http to websocket
80+
url = url.replace('http://', 'ws://')
81+
url = url.replace('https://', 'wss://')
82+
83+
# patch extra /
84+
url = url.replace('//api', '/api')
85+
86+
# Extract the command from the list of tuples
87+
commands = None
88+
for key, value in query_params:
89+
if key == 'command':
90+
commands = value
91+
break
92+
93+
# drop command from query_params as we will be processing it separately
94+
query_params = [(key, value) for key, value in query_params if
95+
key != 'command']
96+
97+
# if we still have query params then encode them
98+
if query_params:
99+
url += '?' + urlencode(query_params)
100+
101+
# tack on the actual command to execute at the end
102+
if isinstance(commands, list):
103+
for command in commands:
104+
url += "&command=%s&" % quote_plus(command)
105+
else:
106+
url += '&command=' + quote_plus(commands)
107+
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))

kubernetes/e2e_test/test_client.py

Lines changed: 38 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

@@ -34,22 +35,49 @@ def test_pod_apis(self):
3435
client = api_client.ApiClient(self.API_URL, config=self.config)
3536
api = core_v1_api.CoreV1Api(client)
3637

37-
name = 'test-' + str(uuid.uuid4())
38-
pod_manifest = {'apiVersion': 'v1',
39-
'kind': 'Pod',
40-
'metadata': {'color': 'blue', 'name': name},
41-
'spec': {'containers': [{'image': 'dockerfile/redis',
42-
'name': 'redis'}]}}
38+
name = 'busybox-test-' + str(uuid.uuid4())
39+
pod_manifest = {
40+
'apiVersion': 'v1',
41+
'kind': 'Pod',
42+
'metadata': {
43+
'name': name
44+
},
45+
'spec': {
46+
'containers': [{
47+
'image': 'busybox',
48+
'name': 'sleep',
49+
"args": [
50+
"/bin/sh",
51+
"-c",
52+
"while true;do date;sleep 5; done"
53+
]
54+
}]
55+
}
56+
}
4357

4458
resp = api.create_namespaced_pod(body=pod_manifest,
4559
namespace='default')
4660
self.assertEqual(name, resp.metadata.name)
4761
self.assertTrue(resp.status.phase)
4862

49-
resp = api.read_namespaced_pod(name=name,
50-
namespace='default')
51-
self.assertEqual(name, resp.metadata.name)
52-
self.assertTrue(resp.status.phase)
63+
while True:
64+
resp = api.read_namespaced_pod(name=name,
65+
namespace='default')
66+
self.assertEqual(name, resp.metadata.name)
67+
self.assertTrue(resp.status.phase)
68+
if resp.status.phase != 'Pending':
69+
break
70+
time.sleep(1)
71+
72+
exec_command = ['/bin/sh',
73+
'-c',
74+
'for i in $(seq 1 3); do date; sleep 1; done']
75+
resp = api.connect_get_namespaced_pod_exec(name, 'default',
76+
command=exec_command,
77+
stderr=False, stdin=False,
78+
stdout=True, tty=False)
79+
print('EXEC response : %s' % resp)
80+
self.assertEqual(3, len(resp.splitlines()))
5381

5482
number_of_pods = len(api.list_pod_for_all_namespaces().items)
5583
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)