Fix bug 2036
[osm/N2VC.git] / n2vc / tests / unit / test_k8s_helm_conn.py
1 ##
2 # Licensed under the Apache License, Version 2.0 (the "License"); you may
3 # not use this file except in compliance with the License. You may obtain
4 # a copy of the License at
5 #
6 # http://www.apache.org/licenses/LICENSE-2.0
7 #
8 # Unless required by applicable law or agreed to in writing, software
9 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
10 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
11 # License for the specific language governing permissions and limitations
12 # under the License.
13 #
14 # For those usages not covered by the Apache License, Version 2.0 please
15 # contact: alfonso.tiernosepulveda@telefonica.com
16 ##
17
18 import asynctest
19 import logging
20
21 from asynctest.mock import Mock
22 from osm_common.dbmemory import DbMemory
23 from osm_common.fslocal import FsLocal
24 from n2vc.k8s_helm_conn import K8sHelmConnector
25
26 __author__ = "Isabel Lloret <illoret@indra.es>"
27
28
29 class TestK8sHelmConn(asynctest.TestCase):
30 logging.basicConfig(level=logging.DEBUG)
31 logger = logging.getLogger(__name__)
32 logger.setLevel(logging.DEBUG)
33
34 async def setUp(self):
35 self.db = Mock(DbMemory())
36 self.fs = asynctest.Mock(FsLocal())
37 self.fs.path = "./tmp/"
38 self.namespace = "testk8s"
39 self.service_account = "osm"
40 self.cluster_id = "helm_cluster_id"
41 self.cluster_uuid = "{}:{}".format(self.namespace, self.cluster_id)
42 # pass fake kubectl and helm commands to make sure it does not call actual commands
43 K8sHelmConnector._check_file_exists = asynctest.Mock(return_value=True)
44 K8sHelmConnector._local_async_exec = asynctest.CoroutineMock(
45 return_value=(0, "")
46 )
47 cluster_dir = self.fs.path + self.cluster_id
48 self.kube_config = self.fs.path + self.cluster_id + "/.kube/config"
49 self.helm_home = self.fs.path + self.cluster_id + "/.helm"
50 self.env = {
51 "HELM_HOME": "{}/.helm".format(cluster_dir),
52 "KUBECONFIG": "{}/.kube/config".format(cluster_dir),
53 }
54 self.helm_conn = K8sHelmConnector(self.fs, self.db, log=self.logger)
55 self.logger.debug("Set up executed")
56
57 @asynctest.fail_on(active_handles=True)
58 async def test_init_env(self):
59 # TODO
60 pass
61
62 @asynctest.fail_on(active_handles=True)
63 async def test_repo_add(self):
64 repo_name = "bitnami"
65 repo_url = "https://charts.bitnami.com/bitnami"
66 self.helm_conn._local_async_exec = asynctest.CoroutineMock(return_value=("", 0))
67
68 await self.helm_conn.repo_add(self.cluster_uuid, repo_name, repo_url)
69
70 self.helm_conn.fs.sync.assert_called_once_with(from_path=self.cluster_id)
71 self.helm_conn.fs.reverse_sync.assert_called_once_with(
72 from_path=self.cluster_id
73 )
74 self.assertEqual(
75 self.helm_conn._local_async_exec.call_count,
76 2,
77 "local_async_exec expected 2 calls, called {}".format(
78 self.helm_conn._local_async_exec.call_count
79 ),
80 )
81
82 repo_update_command = (
83 "env KUBECONFIG=./tmp/helm_cluster_id/.kube/config /usr/bin/helm repo update {}"
84 ).format(repo_name)
85 repo_add_command = (
86 "env KUBECONFIG=./tmp/helm_cluster_id/.kube/config /usr/bin/helm repo add {} {}"
87 ).format(repo_name, repo_url)
88 calls = self.helm_conn._local_async_exec.call_args_list
89 call0_kargs = calls[0][1]
90 self.assertEqual(
91 call0_kargs.get("command"),
92 repo_add_command,
93 "Invalid repo add command: {}".format(call0_kargs.get("command")),
94 )
95 self.assertEqual(
96 call0_kargs.get("env"),
97 self.env,
98 "Invalid env for add command: {}".format(call0_kargs.get("env")),
99 )
100 call1_kargs = calls[1][1]
101 self.assertEqual(
102 call1_kargs.get("command"),
103 repo_update_command,
104 "Invalid repo update command: {}".format(call1_kargs.get("command")),
105 )
106 self.assertEqual(
107 call1_kargs.get("env"),
108 self.env,
109 "Invalid env for update command: {}".format(call1_kargs.get("env")),
110 )
111
112 @asynctest.fail_on(active_handles=True)
113 async def test_repo_list(self):
114 self.helm_conn._local_async_exec = asynctest.CoroutineMock(return_value=("", 0))
115
116 await self.helm_conn.repo_list(self.cluster_uuid)
117
118 self.helm_conn.fs.sync.assert_called_once_with(from_path=self.cluster_id)
119 self.helm_conn.fs.reverse_sync.assert_called_once_with(
120 from_path=self.cluster_id
121 )
122 command = "env KUBECONFIG=./tmp/helm_cluster_id/.kube/config /usr/bin/helm repo list --output yaml"
123 self.helm_conn._local_async_exec.assert_called_with(
124 command=command, env=self.env, raise_exception_on_error=False
125 )
126
127 @asynctest.fail_on(active_handles=True)
128 async def test_repo_remove(self):
129 self.helm_conn._local_async_exec = asynctest.CoroutineMock(return_value=("", 0))
130 repo_name = "bitnami"
131 await self.helm_conn.repo_remove(self.cluster_uuid, repo_name)
132
133 self.helm_conn.fs.sync.assert_called_once_with(from_path=self.cluster_id)
134 self.helm_conn.fs.reverse_sync.assert_called_once_with(
135 from_path=self.cluster_id
136 )
137 command = "env KUBECONFIG=./tmp/helm_cluster_id/.kube/config /usr/bin/helm repo remove {}".format(
138 repo_name
139 )
140 self.helm_conn._local_async_exec.assert_called_once_with(
141 command=command, env=self.env, raise_exception_on_error=True
142 )
143
144 @asynctest.fail_on(active_handles=True)
145 async def test_install(self):
146 kdu_model = "stable/openldap:1.2.2"
147 kdu_instance = "stable-openldap-0005399828"
148 db_dict = {}
149 self.helm_conn._local_async_exec = asynctest.CoroutineMock(return_value=("", 0))
150 self.helm_conn._status_kdu = asynctest.CoroutineMock(return_value=None)
151 self.helm_conn._store_status = asynctest.CoroutineMock()
152 self.helm_conn.generate_kdu_instance_name = Mock(return_value=kdu_instance)
153
154 await self.helm_conn.install(
155 self.cluster_uuid,
156 kdu_model,
157 kdu_instance,
158 atomic=True,
159 namespace=self.namespace,
160 db_dict=db_dict,
161 )
162
163 self.helm_conn.fs.sync.assert_has_calls(
164 [
165 asynctest.call(from_path=self.cluster_id),
166 asynctest.call(from_path=self.cluster_id),
167 ]
168 )
169 self.helm_conn.fs.reverse_sync.assert_has_calls(
170 [
171 asynctest.call(from_path=self.cluster_id),
172 asynctest.call(from_path=self.cluster_id),
173 ]
174 )
175 self.helm_conn._store_status.assert_called_with(
176 cluster_id=self.cluster_id,
177 kdu_instance=kdu_instance,
178 namespace=self.namespace,
179 db_dict=db_dict,
180 operation="install",
181 )
182 command = (
183 "env KUBECONFIG=./tmp/helm_cluster_id/.kube/config /usr/bin/helm install "
184 "--atomic --output yaml --timeout 300 "
185 "--name=stable-openldap-0005399828 --namespace testk8s stable/openldap "
186 "--version 1.2.2"
187 )
188 self.helm_conn._local_async_exec.assert_called_with(
189 command=command, env=self.env, raise_exception_on_error=False
190 )
191
192 @asynctest.fail_on(active_handles=True)
193 async def test_upgrade(self):
194 kdu_model = "stable/openldap:1.2.3"
195 kdu_instance = "stable-openldap-0005399828"
196 db_dict = {}
197 instance_info = {
198 "chart": "openldap-1.2.2",
199 "name": kdu_instance,
200 "namespace": self.namespace,
201 "revision": 1,
202 "status": "DEPLOYED",
203 }
204 self.helm_conn._local_async_exec = asynctest.CoroutineMock(return_value=("", 0))
205 self.helm_conn._store_status = asynctest.CoroutineMock()
206 self.helm_conn.get_instance_info = asynctest.CoroutineMock(
207 return_value=instance_info
208 )
209
210 await self.helm_conn.upgrade(
211 self.cluster_uuid, kdu_instance, kdu_model, atomic=True, db_dict=db_dict
212 )
213 self.helm_conn.fs.sync.assert_called_with(from_path=self.cluster_id)
214 self.helm_conn.fs.reverse_sync.assert_has_calls(
215 [
216 asynctest.call(from_path=self.cluster_id),
217 asynctest.call(from_path=self.cluster_id),
218 ]
219 )
220 self.helm_conn._store_status.assert_called_with(
221 cluster_id=self.cluster_id,
222 kdu_instance=kdu_instance,
223 namespace=self.namespace,
224 db_dict=db_dict,
225 operation="upgrade",
226 )
227 command = (
228 "env KUBECONFIG=./tmp/helm_cluster_id/.kube/config /usr/bin/helm upgrade "
229 "--atomic --output yaml --timeout 300 stable-openldap-0005399828 stable/openldap --version 1.2.3"
230 )
231 self.helm_conn._local_async_exec.assert_called_with(
232 command=command, env=self.env, raise_exception_on_error=False
233 )
234
235 @asynctest.fail_on(active_handles=True)
236 async def test_rollback(self):
237 kdu_instance = "stable-openldap-0005399828"
238 db_dict = {}
239 instance_info = {
240 "chart": "openldap-1.2.3",
241 "name": kdu_instance,
242 "namespace": self.namespace,
243 "revision": 2,
244 "status": "DEPLOYED",
245 }
246 self.helm_conn._local_async_exec = asynctest.CoroutineMock(return_value=("", 0))
247 self.helm_conn._store_status = asynctest.CoroutineMock()
248 self.helm_conn.get_instance_info = asynctest.CoroutineMock(
249 return_value=instance_info
250 )
251
252 await self.helm_conn.rollback(
253 self.cluster_uuid, kdu_instance=kdu_instance, revision=1, db_dict=db_dict
254 )
255 self.helm_conn.fs.sync.assert_called_with(from_path=self.cluster_id)
256 self.helm_conn.fs.reverse_sync.assert_called_once_with(
257 from_path=self.cluster_id
258 )
259 self.helm_conn._store_status.assert_called_with(
260 cluster_id=self.cluster_id,
261 kdu_instance=kdu_instance,
262 namespace=self.namespace,
263 db_dict=db_dict,
264 operation="rollback",
265 )
266 command = (
267 "env KUBECONFIG=./tmp/helm_cluster_id/.kube/config "
268 "/usr/bin/helm rollback stable-openldap-0005399828 1 --wait"
269 )
270 self.helm_conn._local_async_exec.assert_called_once_with(
271 command=command, env=self.env, raise_exception_on_error=False
272 )
273
274 @asynctest.fail_on(active_handles=True)
275 async def test_uninstall(self):
276 kdu_instance = "stable-openldap-0005399828"
277 instance_info = {
278 "chart": "openldap-1.2.2",
279 "name": kdu_instance,
280 "namespace": self.namespace,
281 "revision": 3,
282 "status": "DEPLOYED",
283 }
284 self.helm_conn._local_async_exec = asynctest.CoroutineMock(return_value=("", 0))
285 self.helm_conn._store_status = asynctest.CoroutineMock()
286 self.helm_conn.get_instance_info = asynctest.CoroutineMock(
287 return_value=instance_info
288 )
289
290 await self.helm_conn.uninstall(self.cluster_uuid, kdu_instance)
291 self.helm_conn.fs.sync.assert_called_with(from_path=self.cluster_id)
292 self.helm_conn.fs.reverse_sync.assert_called_once_with(
293 from_path=self.cluster_id
294 )
295 command = "env KUBECONFIG=./tmp/helm_cluster_id/.kube/config /usr/bin/helm delete --purge {}".format(
296 kdu_instance
297 )
298 self.helm_conn._local_async_exec.assert_called_once_with(
299 command=command, env=self.env, raise_exception_on_error=True
300 )
301
302 @asynctest.fail_on(active_handles=True)
303 async def test_get_services(self):
304 kdu_instance = "test_services_1"
305 service = {"name": "testservice", "type": "LoadBalancer"}
306 self.helm_conn._local_async_exec_pipe = asynctest.CoroutineMock(
307 return_value=("", 0)
308 )
309 self.helm_conn._parse_services = Mock(return_value=["testservice"])
310 self.helm_conn._get_service = asynctest.CoroutineMock(return_value=service)
311
312 services = await self.helm_conn.get_services(
313 self.cluster_uuid, kdu_instance, self.namespace
314 )
315 self.helm_conn.fs.sync.assert_called_once_with(from_path=self.cluster_id)
316 self.helm_conn.fs.reverse_sync.assert_called_once_with(
317 from_path=self.cluster_id
318 )
319 self.helm_conn._parse_services.assert_called_once()
320 command1 = "env KUBECONFIG=./tmp/helm_cluster_id/.kube/config /usr/bin/helm get manifest {} ".format(
321 kdu_instance
322 )
323 command2 = "/usr/bin/kubectl get --namespace={} -f -".format(self.namespace)
324 self.helm_conn._local_async_exec_pipe.assert_called_once_with(
325 command1, command2, env=self.env, raise_exception_on_error=True
326 )
327 self.assertEqual(
328 services, [service], "Invalid service returned from get_service"
329 )
330
331 @asynctest.fail_on(active_handles=True)
332 async def test_get_service(self):
333 service_name = "service1"
334
335 self.helm_conn._local_async_exec = asynctest.CoroutineMock(return_value=("", 0))
336 await self.helm_conn.get_service(
337 self.cluster_uuid, service_name, self.namespace
338 )
339
340 self.helm_conn.fs.sync.assert_called_once_with(from_path=self.cluster_id)
341 self.helm_conn.fs.reverse_sync.assert_called_once_with(
342 from_path=self.cluster_id
343 )
344 command = (
345 "/usr/bin/kubectl --kubeconfig=./tmp/helm_cluster_id/.kube/config "
346 "--namespace=testk8s get service service1 -o=yaml"
347 )
348 self.helm_conn._local_async_exec.assert_called_once_with(
349 command=command, env=self.env, raise_exception_on_error=True
350 )
351
352 @asynctest.fail_on(active_handles=True)
353 async def test_inspect_kdu(self):
354 self.helm_conn._local_async_exec = asynctest.CoroutineMock(return_value=("", 0))
355
356 kdu_model = "stable/openldap:1.2.4"
357 repo_url = "https://kubernetes-charts.storage.googleapis.com/"
358 await self.helm_conn.inspect_kdu(kdu_model, repo_url)
359
360 command = (
361 "/usr/bin/helm inspect openldap --repo "
362 "https://kubernetes-charts.storage.googleapis.com/ "
363 "--version 1.2.4"
364 )
365 self.helm_conn._local_async_exec.assert_called_with(
366 command=command, encode_utf8=True
367 )
368
369 @asynctest.fail_on(active_handles=True)
370 async def test_help_kdu(self):
371 self.helm_conn._local_async_exec = asynctest.CoroutineMock(return_value=("", 0))
372
373 kdu_model = "stable/openldap:1.2.4"
374 repo_url = "https://kubernetes-charts.storage.googleapis.com/"
375 await self.helm_conn.help_kdu(kdu_model, repo_url)
376
377 command = (
378 "/usr/bin/helm inspect readme openldap --repo "
379 "https://kubernetes-charts.storage.googleapis.com/ "
380 "--version 1.2.4"
381 )
382 self.helm_conn._local_async_exec.assert_called_with(
383 command=command, encode_utf8=True
384 )
385
386 @asynctest.fail_on(active_handles=True)
387 async def test_values_kdu(self):
388 self.helm_conn._local_async_exec = asynctest.CoroutineMock(return_value=("", 0))
389
390 kdu_model = "stable/openldap:1.2.4"
391 repo_url = "https://kubernetes-charts.storage.googleapis.com/"
392 await self.helm_conn.values_kdu(kdu_model, repo_url)
393
394 command = (
395 "/usr/bin/helm inspect values openldap --repo "
396 "https://kubernetes-charts.storage.googleapis.com/ "
397 "--version 1.2.4"
398 )
399 self.helm_conn._local_async_exec.assert_called_with(
400 command=command, encode_utf8=True
401 )
402
403 @asynctest.fail_on(active_handles=True)
404 async def test_instances_list(self):
405 self.helm_conn._local_async_exec = asynctest.CoroutineMock(return_value=("", 0))
406
407 await self.helm_conn.instances_list(self.cluster_uuid)
408 self.helm_conn.fs.sync.assert_called_once_with(from_path=self.cluster_id)
409 self.helm_conn.fs.reverse_sync.assert_called_once_with(
410 from_path=self.cluster_id
411 )
412 command = "/usr/bin/helm list --output yaml"
413 self.helm_conn._local_async_exec.assert_called_once_with(
414 command=command, env=self.env, raise_exception_on_error=True
415 )
416
417 @asynctest.fail_on(active_handles=True)
418 async def test_status_kdu(self):
419 kdu_instance = "stable-openldap-0005399828"
420 self.helm_conn._local_async_exec = asynctest.CoroutineMock(return_value=("", 0))
421
422 await self.helm_conn._status_kdu(
423 self.cluster_id, kdu_instance, self.namespace, yaml_format=True
424 )
425 command = (
426 "env KUBECONFIG=./tmp/helm_cluster_id/.kube/config /usr/bin/helm status {} --output yaml"
427 ).format(kdu_instance)
428 self.helm_conn._local_async_exec.assert_called_once_with(
429 command=command,
430 env=self.env,
431 raise_exception_on_error=True,
432 show_error_log=False,
433 )
434
435 @asynctest.fail_on(active_handles=True)
436 async def test_store_status(self):
437 kdu_instance = "stable-openldap-0005399828"
438 db_dict = {}
439 status = {
440 "info": {
441 "description": "Install complete",
442 "status": {
443 "code": "1",
444 "notes": "The openldap helm chart has been installed",
445 },
446 }
447 }
448 self.helm_conn._status_kdu = asynctest.CoroutineMock(return_value=status)
449 self.helm_conn.write_app_status_to_db = asynctest.CoroutineMock(
450 return_value=status
451 )
452
453 await self.helm_conn._store_status(
454 cluster_id=self.cluster_id,
455 kdu_instance=kdu_instance,
456 namespace=self.namespace,
457 db_dict=db_dict,
458 operation="install",
459 )
460 self.helm_conn._status_kdu.assert_called_once_with(
461 cluster_id=self.cluster_id,
462 kdu_instance=kdu_instance,
463 namespace=self.namespace,
464 yaml_format=False,
465 )
466 self.helm_conn.write_app_status_to_db.assert_called_once_with(
467 db_dict=db_dict,
468 status="Install complete",
469 detailed_status=str(status),
470 operation="install",
471 )
472
473 @asynctest.fail_on(active_handles=True)
474 async def test_reset_uninstall_false(self):
475 self.helm_conn._uninstall_sw = asynctest.CoroutineMock()
476
477 await self.helm_conn.reset(self.cluster_uuid, force=False, uninstall_sw=False)
478 self.helm_conn.fs.sync.assert_called_once_with(from_path=self.cluster_id)
479 self.helm_conn.fs.file_delete.assert_called_once_with(
480 self.cluster_id, ignore_non_exist=True
481 )
482 self.helm_conn._uninstall_sw.assert_not_called()
483
484 @asynctest.fail_on(active_handles=True)
485 async def test_reset_uninstall(self):
486 kdu_instance = "stable-openldap-0021099429"
487 instances = [
488 {
489 "app_version": "2.4.48",
490 "chart": "openldap-1.2.3",
491 "name": kdu_instance,
492 "namespace": self.namespace,
493 "revision": "1",
494 "status": "deployed",
495 "updated": "2020-10-30 11:11:20.376744191 +0000 UTC",
496 }
497 ]
498 self.helm_conn._uninstall_sw = asynctest.CoroutineMock()
499 self.helm_conn.instances_list = asynctest.CoroutineMock(return_value=instances)
500 self.helm_conn.uninstall = asynctest.CoroutineMock()
501
502 await self.helm_conn.reset(self.cluster_uuid, force=True, uninstall_sw=True)
503 self.helm_conn.fs.sync.assert_called_once_with(from_path=self.cluster_id)
504 self.helm_conn.fs.file_delete.assert_called_once_with(
505 self.cluster_id, ignore_non_exist=True
506 )
507 self.helm_conn.instances_list.assert_called_once_with(
508 cluster_uuid=self.cluster_uuid
509 )
510 self.helm_conn.uninstall.assert_called_once_with(
511 cluster_uuid=self.cluster_uuid, kdu_instance=kdu_instance
512 )
513 self.helm_conn._uninstall_sw.assert_called_once_with(
514 self.cluster_id, self.namespace
515 )
516
517 @asynctest.fail_on(active_handles=True)
518 async def test_uninstall_sw_namespace(self):
519 self.helm_conn._local_async_exec = asynctest.CoroutineMock(return_value=("", 0))
520
521 await self.helm_conn._uninstall_sw(self.cluster_id, self.namespace)
522 calls = self.helm_conn._local_async_exec.call_args_list
523 self.assertEqual(
524 len(calls), 3, "To uninstall should have executed three commands"
525 )
526 call0_kargs = calls[0][1]
527 command_0 = "/usr/bin/helm --kubeconfig={} --home={} reset".format(
528 self.kube_config, self.helm_home
529 )
530 self.assertEqual(
531 call0_kargs,
532 {"command": command_0, "raise_exception_on_error": True, "env": self.env},
533 "Invalid args for first call to local_exec",
534 )
535 call1_kargs = calls[1][1]
536 command_1 = (
537 "/usr/bin/kubectl --kubeconfig={} delete "
538 "clusterrolebinding.rbac.authorization.k8s.io/osm-tiller-cluster-rule".format(
539 self.kube_config
540 )
541 )
542 self.assertEqual(
543 call1_kargs,
544 {"command": command_1, "raise_exception_on_error": False, "env": self.env},
545 "Invalid args for second call to local_exec",
546 )
547 call2_kargs = calls[2][1]
548 command_2 = (
549 "/usr/bin/kubectl --kubeconfig={} --namespace kube-system delete "
550 "serviceaccount/{}".format(self.kube_config, self.service_account)
551 )
552 self.assertEqual(
553 call2_kargs,
554 {"command": command_2, "raise_exception_on_error": False, "env": self.env},
555 "Invalid args for third call to local_exec",
556 )