Skip to content

Commit bc554b1

Browse files
authored
Merge pull request #215 from hpe-container-platform-community/cli_k8sworker
issue with k8s worker get()
2 parents 4d31480 + 55031b7 commit bc554b1

File tree

4 files changed

+141
-57
lines changed

4 files changed

+141
-57
lines changed

Dockerfile

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,14 @@ RUN sudo apt-get update \
66
&& sudo apt-get install -y software-properties-common \
77
&& sudo add-apt-repository -y ppa:deadsnakes/ppa \
88
&& sudo apt-get update \
9-
&& sudo apt-get install -y python3.5 python3.6 python3.7 python3.8 python3.9 tox python3-sphinx vim
9+
&& sudo apt-get install -y python3.5 python3.6 python3.7 python3.8 python3.9 tox python3-sphinx python-pip python3-pip python3.9-distutils vim
1010

11-
RUN pip install -U pylint pytest mock nose flake8-docstrings flake8-per-file-ignores==0.8.1 \
12-
&& pip3 install -U pylint pytest mock nose black flake8-docstrings flake8-per-file-ignores==0.8.1 \
13-
&& pip install -r /tmp/requirements.txt \
14-
&& pip3 install -r /tmp/requirements.txt
11+
# FIXME: Python 3.9 returns errors with pip
12+
RUN echo "Installing python modules" \
13+
&& for v in 2 3 3.5 3.6 3.7 3.8; do python${v} -m pip install -U pylint pytest mock nose flake8-docstrings flake8-per-file-ignores==0.8.1; done \
14+
&& for v in 3 3.5 3.6 3.7 3.8; do python${v} -m pip install -U black; done \
15+
&& sudo ln -s /home/theia/.local/bin//black /bin/ \
16+
&& for v in 2 3 3.5 3.6 3.7 3.8; do python${v} -m pip install -r /tmp/requirements.txt; done
1517

1618
RUN echo 'PATH=$PATH:/home/theia/.local/bin/' >> /home/theia/.bashrc
1719

bin/cli.py

Lines changed: 22 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,7 @@
101101
def intercept_exception(wrapped, instance, args, kwargs):
102102
"""Handle Exceptions.""" # noqa: D202
103103

104-
def _handle_unknown_exception(ex):
104+
def _unknown_exception_handler(ex):
105105
"""Handle unknown exceptions."""
106106
if _log.level == 10: # "DEBUG"
107107
print(
@@ -125,7 +125,7 @@ def _handle_unknown_exception(ex):
125125
print(ae, file=sys.stderr)
126126
sys.exit(1)
127127
except APIUnknownException as ue:
128-
_handle_unknown_exception(ue)
128+
_unknown_exception_handler(ue)
129129
except (
130130
APIException,
131131
APIItemNotFoundException,
@@ -136,7 +136,7 @@ def _handle_unknown_exception(ex):
136136
print(e.message, file=sys.stderr)
137137
sys.exit(1)
138138
except Exception as ex:
139-
_handle_unknown_exception(ex)
139+
_unknown_exception_handler(ex)
140140

141141

142142
@intercept_exception
@@ -181,17 +181,17 @@ def get(self, id, output="yaml", params=None):
181181
self.client, self.client_module_name
182182
)
183183
response = self.client_module_property.get(id=id, params=params)
184+
json_data = response.json
184185

185186
if output == "json":
186-
print(json.dumps(response.json))
187+
print(json.dumps(json_data))
187188
elif output == "json-pp":
188-
print(json.dumps(response.json, indent=4, sort_keys=True,))
189+
print(json.dumps(json_data, indent=4, sort_keys=True,))
189190
else:
191+
190192
print(
191193
yaml.dump(
192-
yaml.load(
193-
json.dumps(response.json), Loader=yaml.FullLoader,
194-
)
194+
yaml.load(json.dumps(json_data), Loader=yaml.FullLoader,)
195195
)
196196
)
197197

@@ -679,7 +679,7 @@ def create_with_ssh_key(
679679
) and wait_for_operation_secs == 0:
680680
print(
681681
(
682-
"if setting disks 'wait-for-operation-secs' parameter"
682+
"If setting disks, 'wait-for-operation-secs' parameter"
683683
" must be greater than zero (recommended 600 seconds)"
684684
),
685685
file=sys.stderr,
@@ -693,10 +693,22 @@ def create_with_ssh_key(
693693
if wait_for_operation_secs > 0:
694694
self.wait_for_status(
695695
id=worker_id,
696-
status=["storage_pending"],
696+
status=["storage_pending", "error"],
697697
timeout_secs=wait_for_operation_secs,
698698
)
699699

700+
if get_client().k8s_worker.get(id=worker_id).status == "error":
701+
print(
702+
(
703+
"Create request has errored. "
704+
"Check status message with `hpecp k8sworker get {}".format(
705+
id
706+
)
707+
),
708+
file=sys.stderr,
709+
)
710+
sys.exit(1)
711+
700712
if ephemeral_disks is not None or persistent_disks is not None:
701713
self.set_storage(
702714
id=worker_id,

hpecp/k8s_worker.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -145,17 +145,18 @@ def create_with_ssh_key(self, ip, ssh_key_data, tags=[]):
145145
url="/api/v2/worker/k8shost/",
146146
http_method="post",
147147
data=data,
148-
description="worker/create_with_ssh_key",
148+
description="K8sWorkerController/create_with_ssh_key",
149149
)
150150
return CaseInsensitiveDict(response.headers)["location"]
151151

152-
def get(self, id, setup_log=False):
152+
def get(self, id, params=None, setup_log=False):
153153

154-
if setup_log is True:
155-
params = {"setup_log": "true"}
156-
else:
154+
if params is None:
157155
params = {}
158156

157+
if setup_log is True:
158+
params["setup_log"] = "true"
159+
159160
return super(K8sWorkerController, self).get(id, params)
160161

161162
def set_storage(self, worker_id, ephemeral_disks=[], persistent_disks=[]):

tests/library/k8s_worker_test.py

Lines changed: 106 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,21 @@
11
from unittest import TestCase
22
import requests
3-
from mock import patch
3+
from mock import patch, MagicMock
4+
import sys
5+
import os
6+
import json
47

58
from hpecp import ContainerPlatformClient
6-
from hpecp.k8s_worker import K8sWorkerController, WorkerK8sStatus
9+
from hpecp.k8s_worker import K8sWorkerController, WorkerK8sStatus, WorkerK8s
710
from hpecp.exceptions import APIItemConflictException, APIItemNotFoundException
811
from .base_test import session_mock_response, BaseTestCase
912
import tempfile
1013

14+
try:
15+
from imp import reload
16+
except Exception:
17+
from importlib import reload
18+
1119

1220
class MockResponse:
1321
def __init__(
@@ -389,26 +397,57 @@ def test_with_only_ssh_key_content_provided(
389397
is passed to the library method 'create_with_ssh_key()'.
390398
"""
391399

392-
with patch.object(
393-
K8sWorkerController,
394-
"create_with_ssh_key",
395-
return_value="/api/v2/worker/k8shost/1",
396-
) as mock_create_with_ssh_key:
397-
try:
398-
hpecp_cli = self.cli.CLI()
399-
hpecp_cli.k8sworker.create_with_ssh_key(
400-
ip="127.0.0.1", ssh_key="test_ssh_key",
401-
)
402-
except Exception:
403-
self.fail("Unexpected exception.")
400+
def mock_k8s_worker_get(*args, **kwargs):
401+
worker = WorkerK8s(
402+
{
403+
"status": "bundle",
404+
"approved_worker_pubkey": [],
405+
"tags": [],
406+
"hostname": "",
407+
"ipaddr": "10.1.0.186",
408+
"setup_log": (
409+
"/var/log/bluedata/install/"
410+
"k8shost_setup_10.1.0.186-"
411+
"2020-4-26-18-49-10"
412+
),
413+
"_links": {"self": {"href": "/api/v2/worker/k8shost/5"}},
414+
}
415+
)
416+
return worker
417+
418+
def mock_create_with_ssh_key(*args, **kwargs):
419+
return "/api/v2/worker/k8shost/5"
420+
421+
def mock_get_client():
422+
client = ContainerPlatformClient(
423+
username="",
424+
password="",
425+
api_host="",
426+
api_port=9090,
427+
use_ssl=True,
428+
verify_ssl=True,
429+
warn_ssl=True,
430+
)
431+
client.session_id = "ABC"
432+
client.k8s_worker.get = mock_k8s_worker_get
433+
client.k8s_worker.create_with_ssh_key = mock_create_with_ssh_key
434+
return client
404435

405-
mock_create_with_ssh_key.assert_called_once_with(
406-
ip="127.0.0.1", ssh_key_data="test_ssh_key", tags=[],
407-
)
436+
# support debugging if this test fails
437+
with patch.dict("os.environ", {"LOG_LEVEL": "DEBUG"}):
438+
hpecp_cli = self.cli.CLI()
439+
440+
# manually patch methods due to json serialization error
441+
# when using Mock or MagicMock
442+
self.cli.get_client = mock_get_client
443+
444+
hpecp_cli.k8sworker.create_with_ssh_key(
445+
ip="127.0.0.1", ssh_key="test_ssh_key",
446+
)
408447

409448
stdout = self.out.getvalue().strip()
410449

411-
self.assertEqual(stdout, "/api/v2/worker/k8shost/1")
450+
self.assertEqual(stdout, "/api/v2/worker/k8shost/5")
412451

413452
@patch("requests.post", side_effect=mocked_requests_post)
414453
@patch("hpecp.k8s_worker")
@@ -506,34 +545,64 @@ def test_with_only_ssh_key_content_provided_raises_general_exception(
506545
"Expected: `{}`, Actual: `{}`".format(expected_err, stderr),
507546
)
508547

509-
@patch("requests.post", side_effect=mocked_requests_post)
510-
@patch("hpecp.k8s_worker")
511-
def test_with_only_ssh_key_file_provided(self, mock_post, mock_k8sworker):
548+
@patch("requests.post", side_effect=mocked_requests_post) # Login response
549+
def test_with_only_ssh_key_file_provided(self, mock_login_response):
512550

513551
ssh_key_file = tempfile.NamedTemporaryFile(delete=True, mode="w")
514552
ssh_key_file.write("test_ssh_key_file_data")
515553
ssh_key_file.flush()
516554

517-
with patch.object(
518-
K8sWorkerController,
519-
"create_with_ssh_key",
520-
return_value="/api/v2/worker/k8shost/1",
521-
) as mock_create_with_ssh_key:
522-
try:
523-
hpecp_cli = self.cli.CLI()
524-
hpecp_cli.k8sworker.create_with_ssh_key(
525-
ip="127.0.0.1", ssh_key_file=ssh_key_file.name,
526-
)
527-
except Exception as e:
528-
self.fail("Unexpected exception. {}".format(e))
555+
def mock_k8s_worker_get(*args, **kwargs):
556+
worker = WorkerK8s(
557+
{
558+
"status": "bundle",
559+
"approved_worker_pubkey": [],
560+
"tags": [],
561+
"hostname": "",
562+
"ipaddr": "10.1.0.186",
563+
"setup_log": (
564+
"/var/log/bluedata/install/"
565+
"k8shost_setup_10.1.0.186-"
566+
"2020-4-26-18-49-10"
567+
),
568+
"_links": {"self": {"href": "/api/v2/worker/k8shost/5"}},
569+
}
570+
)
571+
return worker
572+
573+
def mock_create_with_ssh_key(*args, **kwargs):
574+
return "/api/v2/worker/k8shost/5"
575+
576+
def mock_get_client():
577+
client = ContainerPlatformClient(
578+
username="",
579+
password="",
580+
api_host="",
581+
api_port=9090,
582+
use_ssl=True,
583+
verify_ssl=True,
584+
warn_ssl=True,
585+
)
586+
client.session_id = "ABC"
587+
client.k8s_worker.get = mock_k8s_worker_get
588+
client.k8s_worker.create_with_ssh_key = mock_create_with_ssh_key
589+
return client
529590

530-
mock_create_with_ssh_key.assert_called_once_with(
531-
ip="127.0.0.1", ssh_key_data="test_ssh_key_file_data", tags=[],
532-
)
591+
# support debugging if this test fails
592+
with patch.dict("os.environ", {"LOG_LEVEL": "DEBUG"}):
593+
hpecp_cli = self.cli.CLI()
594+
595+
# manually patch methods due to json serialization error
596+
# when using Mock or MagicMock
597+
self.cli.get_client = mock_get_client
598+
599+
hpecp_cli.k8sworker.create_with_ssh_key(
600+
ip="127.0.0.1", ssh_key_file=ssh_key_file.name
601+
)
533602

534603
stdout = self.out.getvalue().strip()
535604

536-
self.assertEqual(stdout, "/api/v2/worker/k8shost/1")
605+
self.assertEqual(stdout, "/api/v2/worker/k8shost/5")
537606

538607
ssh_key_file.close()
539608

0 commit comments

Comments
 (0)