afc8ca7e345bd3f9e822cd9201975be68f60ea85
[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 = "env KUBECONFIG=./tmp/helm_cluster_id/.kube/config /usr/bin/helm repo update"
83 repo_add_command = (
84 "env KUBECONFIG=./tmp/helm_cluster_id/.kube/config /usr/bin/helm repo add {} {}"
85 ).format(repo_name, repo_url)
86 calls = self.helm_conn._local_async_exec.call_args_list
87 call0_kargs = calls[0][1]
88 self.assertEqual(
89 call0_kargs.get("command"),
90 repo_update_command,
91 "Invalid repo update command: {}".format(call0_kargs.get("command")),
92 )
93 self.assertEqual(
94 call0_kargs.get("env"),
95 self.env,
96 "Invalid env for update command: {}".format(call0_kargs.get("env")),
97 )
98 call1_kargs = calls[1][1]
99 self.assertEqual(
100 call1_kargs.get("command"),
101 repo_add_command,
102 "Invalid repo add command: {}".format(call1_kargs.get("command")),
103 )
104 self.assertEqual(
105 call1_kargs.get("env"),
106 self.env,
107 "Invalid env for add command: {}".format(call1_kargs.get("env")),
108 )
109
110 @asynctest.fail_on(active_handles=True)
111 async def test_repo_list(self):
112 self.helm_conn._local_async_exec = asynctest.CoroutineMock(return_value=("", 0))
113
114 await self.helm_conn.repo_list(self.cluster_uuid)
115
116 self.helm_conn.fs.sync.assert_called_once_with(from_path=self.cluster_id)
117 self.helm_conn.fs.reverse_sync.assert_called_once_with(
118 from_path=self.cluster_id
119 )
120 command = "env KUBECONFIG=./tmp/helm_cluster_id/.kube/config /usr/bin/helm repo list --output yaml"
121 self.helm_conn._local_async_exec.assert_called_with(
122 command=command, env=self.env, raise_exception_on_error=False
123 )
124
125 @asynctest.fail_on(active_handles=True)
126 async def test_repo_remove(self):
127 self.helm_conn._local_async_exec = asynctest.CoroutineMock(return_value=("", 0))
128 repo_name = "bitnami"
129 await self.helm_conn.repo_remove(self.cluster_uuid, repo_name)
130
131 self.helm_conn.fs.sync.assert_called_once_with(from_path=self.cluster_id)
132 self.helm_conn.fs.reverse_sync.assert_called_once_with(
133 from_path=self.cluster_id
134 )
135 command = "env KUBECONFIG=./tmp/helm_cluster_id/.kube/config /usr/bin/helm repo remove {}".format(
136 repo_name
137 )
138 self.helm_conn._local_async_exec.assert_called_once_with(
139 command=command, env=self.env, raise_exception_on_error=True
140 )
141
142 @asynctest.fail_on(active_handles=True)
143 async def test_install(self):
144 kdu_model = "stable/openldap:1.2.2"
145 kdu_instance = "stable-openldap-0005399828"
146 db_dict = {}
147 self.helm_conn._local_async_exec = asynctest.CoroutineMock(return_value=("", 0))
148 self.helm_conn._status_kdu = asynctest.CoroutineMock(return_value=None)
149 self.helm_conn._store_status = asynctest.CoroutineMock()
150 self.helm_conn.generate_kdu_instance_name = Mock(return_value=kdu_instance)
151
152 await self.helm_conn.install(
153 self.cluster_uuid,
154 kdu_model,
155 kdu_instance,
156 atomic=True,
157 namespace=self.namespace,
158 db_dict=db_dict,
159 )
160
161 self.helm_conn.fs.sync.assert_called_once_with(from_path=self.cluster_id)
162 self.helm_conn.fs.reverse_sync.assert_called_once_with(
163 from_path=self.cluster_id
164 )
165 self.helm_conn._store_status.assert_called_with(
166 cluster_id=self.cluster_id,
167 kdu_instance=kdu_instance,
168 namespace=self.namespace,
169 db_dict=db_dict,
170 operation="install",
171 run_once=True,
172 check_every=0,
173 )
174 command = (
175 "env KUBECONFIG=./tmp/helm_cluster_id/.kube/config /usr/bin/helm install "
176 "--atomic --output yaml --timeout 300 "
177 "--name=stable-openldap-0005399828 --namespace testk8s stable/openldap "
178 "--version 1.2.2"
179 )
180 self.helm_conn._local_async_exec.assert_called_once_with(
181 command=command, env=self.env, raise_exception_on_error=False
182 )
183
184 @asynctest.fail_on(active_handles=True)
185 async def test_upgrade(self):
186 kdu_model = "stable/openldap:1.2.3"
187 kdu_instance = "stable-openldap-0005399828"
188 db_dict = {}
189 instance_info = {
190 "chart": "openldap-1.2.2",
191 "name": kdu_instance,
192 "namespace": self.namespace,
193 "revision": 1,
194 "status": "DEPLOYED",
195 }
196 self.helm_conn._local_async_exec = asynctest.CoroutineMock(return_value=("", 0))
197 self.helm_conn._store_status = asynctest.CoroutineMock()
198 self.helm_conn.get_instance_info = asynctest.CoroutineMock(
199 return_value=instance_info
200 )
201
202 await self.helm_conn.upgrade(
203 self.cluster_uuid, kdu_instance, kdu_model, atomic=True, db_dict=db_dict
204 )
205 self.helm_conn.fs.sync.assert_called_with(from_path=self.cluster_id)
206 self.helm_conn.fs.reverse_sync.assert_called_once_with(
207 from_path=self.cluster_id
208 )
209 self.helm_conn._store_status.assert_called_with(
210 cluster_id=self.cluster_id,
211 kdu_instance=kdu_instance,
212 namespace=self.namespace,
213 db_dict=db_dict,
214 operation="upgrade",
215 run_once=True,
216 check_every=0,
217 )
218 command = (
219 "env KUBECONFIG=./tmp/helm_cluster_id/.kube/config /usr/bin/helm upgrade "
220 "--atomic --output yaml --timeout 300 stable-openldap-0005399828 stable/openldap --version 1.2.3"
221 )
222 self.helm_conn._local_async_exec.assert_called_once_with(
223 command=command, env=self.env, raise_exception_on_error=False
224 )
225
226 @asynctest.fail_on(active_handles=True)
227 async def test_rollback(self):
228 kdu_instance = "stable-openldap-0005399828"
229 db_dict = {}
230 instance_info = {
231 "chart": "openldap-1.2.3",
232 "name": kdu_instance,
233 "namespace": self.namespace,
234 "revision": 2,
235 "status": "DEPLOYED",
236 }
237 self.helm_conn._local_async_exec = asynctest.CoroutineMock(return_value=("", 0))
238 self.helm_conn._store_status = asynctest.CoroutineMock()
239 self.helm_conn.get_instance_info = asynctest.CoroutineMock(
240 return_value=instance_info
241 )
242
243 await self.helm_conn.rollback(
244 self.cluster_uuid, kdu_instance=kdu_instance, revision=1, db_dict=db_dict
245 )
246 self.helm_conn.fs.sync.assert_called_with(from_path=self.cluster_id)
247 self.helm_conn.fs.reverse_sync.assert_called_once_with(
248 from_path=self.cluster_id
249 )
250 self.helm_conn._store_status.assert_called_with(
251 cluster_id=self.cluster_id,
252 kdu_instance=kdu_instance,
253 namespace=self.namespace,
254 db_dict=db_dict,
255 operation="rollback",
256 run_once=True,
257 check_every=0,
258 )
259 command = (
260 "env KUBECONFIG=./tmp/helm_cluster_id/.kube/config "
261 "/usr/bin/helm rollback stable-openldap-0005399828 1 --wait"
262 )
263 self.helm_conn._local_async_exec.assert_called_once_with(
264 command=command, env=self.env, raise_exception_on_error=False
265 )
266
267 @asynctest.fail_on(active_handles=True)
268 async def test_uninstall(self):
269 kdu_instance = "stable-openldap-0005399828"
270 instance_info = {
271 "chart": "openldap-1.2.2",
272 "name": kdu_instance,
273 "namespace": self.namespace,
274 "revision": 3,
275 "status": "DEPLOYED",
276 }
277 self.helm_conn._local_async_exec = asynctest.CoroutineMock(return_value=("", 0))
278 self.helm_conn._store_status = asynctest.CoroutineMock()
279 self.helm_conn.get_instance_info = asynctest.CoroutineMock(
280 return_value=instance_info
281 )
282
283 await self.helm_conn.uninstall(self.cluster_uuid, kdu_instance)
284 self.helm_conn.fs.sync.assert_called_with(from_path=self.cluster_id)
285 self.helm_conn.fs.reverse_sync.assert_called_once_with(
286 from_path=self.cluster_id
287 )
288 command = "env KUBECONFIG=./tmp/helm_cluster_id/.kube/config /usr/bin/helm delete --purge {}".format(
289 kdu_instance
290 )
291 self.helm_conn._local_async_exec.assert_called_once_with(
292 command=command, env=self.env, raise_exception_on_error=True
293 )
294
295 @asynctest.fail_on(active_handles=True)
296 async def test_get_services(self):
297 kdu_instance = "test_services_1"
298 service = {"name": "testservice", "type": "LoadBalancer"}
299 self.helm_conn._local_async_exec_pipe = asynctest.CoroutineMock(
300 return_value=("", 0)
301 )
302 self.helm_conn._parse_services = Mock(return_value=["testservice"])
303 self.helm_conn._get_service = asynctest.CoroutineMock(return_value=service)
304
305 services = await self.helm_conn.get_services(
306 self.cluster_uuid, kdu_instance, self.namespace
307 )
308 self.helm_conn.fs.sync.assert_called_once_with(from_path=self.cluster_id)
309 self.helm_conn.fs.reverse_sync.assert_called_once_with(
310 from_path=self.cluster_id
311 )
312 self.helm_conn._parse_services.assert_called_once()
313 command1 = "env KUBECONFIG=./tmp/helm_cluster_id/.kube/config /usr/bin/helm get manifest {} ".format(
314 kdu_instance
315 )
316 command2 = "/usr/bin/kubectl get --namespace={} -f -".format(self.namespace)
317 self.helm_conn._local_async_exec_pipe.assert_called_once_with(
318 command1, command2, env=self.env, raise_exception_on_error=True
319 )
320 self.assertEqual(
321 services, [service], "Invalid service returned from get_service"
322 )
323
324 @asynctest.fail_on(active_handles=True)
325 async def test_get_service(self):
326 service_name = "service1"
327
328 self.helm_conn._local_async_exec = asynctest.CoroutineMock(return_value=("", 0))
329 await self.helm_conn.get_service(
330 self.cluster_uuid, service_name, self.namespace
331 )
332
333 self.helm_conn.fs.sync.assert_called_once_with(from_path=self.cluster_id)
334 self.helm_conn.fs.reverse_sync.assert_called_once_with(
335 from_path=self.cluster_id
336 )
337 command = (
338 "/usr/bin/kubectl --kubeconfig=./tmp/helm_cluster_id/.kube/config "
339 "--namespace=testk8s get service service1 -o=yaml"
340 )
341 self.helm_conn._local_async_exec.assert_called_once_with(
342 command=command, env=self.env, raise_exception_on_error=True
343 )
344
345 @asynctest.fail_on(active_handles=True)
346 async def test_inspect_kdu(self):
347 self.helm_conn._local_async_exec = asynctest.CoroutineMock(return_value=("", 0))
348
349 kdu_model = "stable/openldap:1.2.4"
350 repo_url = "https://kubernetes-charts.storage.googleapis.com/"
351 await self.helm_conn.inspect_kdu(kdu_model, repo_url)
352
353 command = (
354 "/usr/bin/helm inspect openldap --repo "
355 "https://kubernetes-charts.storage.googleapis.com/ "
356 "--version 1.2.4"
357 )
358 self.helm_conn._local_async_exec.assert_called_with(
359 command=command, encode_utf8=True
360 )
361
362 @asynctest.fail_on(active_handles=True)
363 async def test_help_kdu(self):
364 self.helm_conn._local_async_exec = asynctest.CoroutineMock(return_value=("", 0))
365
366 kdu_model = "stable/openldap:1.2.4"
367 repo_url = "https://kubernetes-charts.storage.googleapis.com/"
368 await self.helm_conn.help_kdu(kdu_model, repo_url)
369
370 command = (
371 "/usr/bin/helm inspect readme openldap --repo "
372 "https://kubernetes-charts.storage.googleapis.com/ "
373 "--version 1.2.4"
374 )
375 self.helm_conn._local_async_exec.assert_called_with(
376 command=command, encode_utf8=True
377 )
378
379 @asynctest.fail_on(active_handles=True)
380 async def test_values_kdu(self):
381 self.helm_conn._local_async_exec = asynctest.CoroutineMock(return_value=("", 0))
382
383 kdu_model = "stable/openldap:1.2.4"
384 repo_url = "https://kubernetes-charts.storage.googleapis.com/"
385 await self.helm_conn.values_kdu(kdu_model, repo_url)
386
387 command = (
388 "/usr/bin/helm inspect values openldap --repo "
389 "https://kubernetes-charts.storage.googleapis.com/ "
390 "--version 1.2.4"
391 )
392 self.helm_conn._local_async_exec.assert_called_with(
393 command=command, encode_utf8=True
394 )
395
396 @asynctest.fail_on(active_handles=True)
397 async def test_instances_list(self):
398 self.helm_conn._local_async_exec = asynctest.CoroutineMock(return_value=("", 0))
399
400 await self.helm_conn.instances_list(self.cluster_uuid)
401 self.helm_conn.fs.sync.assert_called_once_with(from_path=self.cluster_id)
402 self.helm_conn.fs.reverse_sync.assert_called_once_with(
403 from_path=self.cluster_id
404 )
405 command = "/usr/bin/helm list --output yaml"
406 self.helm_conn._local_async_exec.assert_called_once_with(
407 command=command, env=self.env, raise_exception_on_error=True
408 )
409
410 @asynctest.fail_on(active_handles=True)
411 async def test_status_kdu(self):
412 kdu_instance = "stable-openldap-0005399828"
413 self.helm_conn._local_async_exec = asynctest.CoroutineMock(return_value=("", 0))
414
415 await self.helm_conn._status_kdu(
416 self.cluster_id, kdu_instance, self.namespace, return_text=True
417 )
418 command = (
419 "env KUBECONFIG=./tmp/helm_cluster_id/.kube/config /usr/bin/helm status {} --output yaml"
420 ).format(kdu_instance)
421 self.helm_conn._local_async_exec.assert_called_once_with(
422 command=command,
423 env=self.env,
424 raise_exception_on_error=True,
425 show_error_log=False,
426 )
427
428 @asynctest.fail_on(active_handles=True)
429 async def test_store_status(self):
430 kdu_instance = "stable-openldap-0005399828"
431 db_dict = {}
432 status = {
433 "info": {
434 "description": "Install complete",
435 "status": {
436 "code": "1",
437 "notes": "The openldap helm chart has been installed",
438 },
439 }
440 }
441 self.helm_conn._status_kdu = asynctest.CoroutineMock(return_value=status)
442 self.helm_conn.write_app_status_to_db = asynctest.CoroutineMock(
443 return_value=status
444 )
445
446 await self.helm_conn._store_status(
447 cluster_id=self.cluster_id,
448 kdu_instance=kdu_instance,
449 namespace=self.namespace,
450 db_dict=db_dict,
451 operation="install",
452 run_once=True,
453 check_every=0,
454 )
455 self.helm_conn._status_kdu.assert_called_once_with(
456 cluster_id=self.cluster_id,
457 kdu_instance=kdu_instance,
458 namespace=self.namespace,
459 return_text=False,
460 )
461 self.helm_conn.write_app_status_to_db.assert_called_once_with(
462 db_dict=db_dict,
463 status="Install complete",
464 detailed_status=str(status),
465 operation="install",
466 )
467
468 @asynctest.fail_on(active_handles=True)
469 async def test_reset_uninstall_false(self):
470 self.helm_conn._uninstall_sw = asynctest.CoroutineMock()
471
472 await self.helm_conn.reset(self.cluster_uuid, force=False, uninstall_sw=False)
473 self.helm_conn.fs.sync.assert_called_once_with(from_path=self.cluster_id)
474 self.helm_conn.fs.file_delete.assert_called_once_with(
475 self.cluster_id, ignore_non_exist=True
476 )
477 self.helm_conn._uninstall_sw.assert_not_called()
478
479 @asynctest.fail_on(active_handles=True)
480 async def test_reset_uninstall(self):
481 kdu_instance = "stable-openldap-0021099429"
482 instances = [
483 {
484 "app_version": "2.4.48",
485 "chart": "openldap-1.2.3",
486 "name": kdu_instance,
487 "namespace": self.namespace,
488 "revision": "1",
489 "status": "deployed",
490 "updated": "2020-10-30 11:11:20.376744191 +0000 UTC",
491 }
492 ]
493 self.helm_conn._uninstall_sw = asynctest.CoroutineMock()
494 self.helm_conn.instances_list = asynctest.CoroutineMock(return_value=instances)
495 self.helm_conn.uninstall = asynctest.CoroutineMock()
496
497 await self.helm_conn.reset(self.cluster_uuid, force=True, uninstall_sw=True)
498 self.helm_conn.fs.sync.assert_called_once_with(from_path=self.cluster_id)
499 self.helm_conn.fs.file_delete.assert_called_once_with(
500 self.cluster_id, ignore_non_exist=True
501 )
502 self.helm_conn.instances_list.assert_called_once_with(
503 cluster_uuid=self.cluster_uuid
504 )
505 self.helm_conn.uninstall.assert_called_once_with(
506 cluster_uuid=self.cluster_uuid, kdu_instance=kdu_instance
507 )
508 self.helm_conn._uninstall_sw.assert_called_once_with(
509 self.cluster_id, self.namespace
510 )
511
512 @asynctest.fail_on(active_handles=True)
513 async def test_uninstall_sw_namespace(self):
514 self.helm_conn._local_async_exec = asynctest.CoroutineMock(return_value=("", 0))
515
516 await self.helm_conn._uninstall_sw(self.cluster_id, self.namespace)
517 calls = self.helm_conn._local_async_exec.call_args_list
518 self.assertEqual(
519 len(calls), 3, "To uninstall should have executed three commands"
520 )
521 call0_kargs = calls[0][1]
522 command_0 = "/usr/bin/helm --kubeconfig={} --home={} reset".format(
523 self.kube_config, self.helm_home
524 )
525 self.assertEqual(
526 call0_kargs,
527 {"command": command_0, "raise_exception_on_error": True, "env": self.env},
528 "Invalid args for first call to local_exec",
529 )
530 call1_kargs = calls[1][1]
531 command_1 = (
532 "/usr/bin/kubectl --kubeconfig={} delete "
533 "clusterrolebinding.rbac.authorization.k8s.io/osm-tiller-cluster-rule".format(
534 self.kube_config
535 )
536 )
537 self.assertEqual(
538 call1_kargs,
539 {"command": command_1, "raise_exception_on_error": False, "env": self.env},
540 "Invalid args for second call to local_exec",
541 )
542 call2_kargs = calls[2][1]
543 command_2 = (
544 "/usr/bin/kubectl --kubeconfig={} --namespace kube-system delete "
545 "serviceaccount/{}".format(self.kube_config, self.service_account)
546 )
547 self.assertEqual(
548 call2_kargs,
549 {"command": command_2, "raise_exception_on_error": False, "env": self.env},
550 "Invalid args for third call to local_exec",
551 )