Fix bug 1448: minor fix in JujuModelWatcher.wait_for_model
[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(return_value=("", 0))
45 cluster_dir = self.fs.path + self.cluster_id
46 self.kube_config = self.fs.path + self.cluster_id + "/.kube/config"
47 self.helm_home = self.fs.path + self.cluster_id + "/.helm"
48 self.env = {
49 "HELM_HOME": "{}/.helm".format(cluster_dir),
50 "KUBECONFIG": "{}/.kube/config".format(cluster_dir)
51 }
52 self.helm_conn = K8sHelmConnector(self.fs, self.db,
53 log=self.logger)
54 self.logger.debug("Set up executed")
55
56 @asynctest.fail_on(active_handles=True)
57 async def test_init_env(self):
58 # TODO
59 pass
60
61 @asynctest.fail_on(active_handles=True)
62 async def test_repo_add(self):
63 repo_name = "bitnami"
64 repo_url = "https://charts.bitnami.com/bitnami"
65 self.helm_conn._local_async_exec = asynctest.CoroutineMock(return_value=("", 0))
66
67 await self.helm_conn.repo_add(self.cluster_uuid, repo_name, repo_url)
68
69 self.helm_conn.fs.sync.assert_called_once_with(from_path=self.cluster_id)
70 self.helm_conn.fs.reverse_sync.assert_called_once_with(from_path=self.cluster_id)
71 self.assertEqual(self.helm_conn._local_async_exec.call_count, 2,
72 "local_async_exec expected 2 calls, called {}".format(
73 self.helm_conn._local_async_exec.call_count))
74
75 repo_update_command = "/usr/bin/helm repo update"
76 repo_add_command = "/usr/bin/helm repo add {} {}".format(repo_name, repo_url)
77 calls = self.helm_conn._local_async_exec.call_args_list
78 call0_kargs = calls[0][1]
79 self.assertEqual(call0_kargs.get("command"), repo_update_command,
80 "Invalid repo update command: {}".format(call0_kargs.get("command")))
81 self.assertEqual(call0_kargs.get("env"), self.env,
82 "Invalid env for update command: {}".format(call0_kargs.get("env")))
83 call1_kargs = calls[1][1]
84 self.assertEqual(call1_kargs.get("command"), repo_add_command,
85 "Invalid repo add command: {}".format(call1_kargs.get("command")))
86 self.assertEqual(call1_kargs.get("env"), self.env,
87 "Invalid env for add command: {}".format(call1_kargs.get("env")))
88
89 @asynctest.fail_on(active_handles=True)
90 async def test_repo_list(self):
91 self.helm_conn._local_async_exec = asynctest.CoroutineMock(return_value=("", 0))
92
93 await self.helm_conn.repo_list(self.cluster_uuid)
94
95 self.helm_conn.fs.sync.assert_called_once_with(from_path=self.cluster_id)
96 self.helm_conn.fs.reverse_sync.assert_called_once_with(from_path=self.cluster_id)
97 command = "/usr/bin/helm repo list --output yaml"
98 self.helm_conn._local_async_exec.assert_called_with(command=command, env=self.env,
99 raise_exception_on_error=False)
100
101 @asynctest.fail_on(active_handles=True)
102 async def test_repo_remove(self):
103 self.helm_conn._local_async_exec = asynctest.CoroutineMock(return_value=("", 0))
104 repo_name = "bitnami"
105 await self.helm_conn.repo_remove(self.cluster_uuid, repo_name)
106
107 self.helm_conn.fs.sync.assert_called_once_with(from_path=self.cluster_id)
108 self.helm_conn.fs.reverse_sync.assert_called_once_with(from_path=self.cluster_id)
109 command = "/usr/bin/helm repo remove {}".format(repo_name)
110 self.helm_conn._local_async_exec.assert_called_once_with(command=command, env=self.env,
111 raise_exception_on_error=True)
112
113 @asynctest.fail_on(active_handles=True)
114 async def test_install(self):
115 kdu_model = "stable/openldap:1.2.2"
116 kdu_instance = "stable-openldap-0005399828"
117 db_dict = {}
118 self.helm_conn._local_async_exec = asynctest.CoroutineMock(return_value=("", 0))
119 self.helm_conn._status_kdu = asynctest.CoroutineMock(return_value=None)
120 self.helm_conn._store_status = asynctest.CoroutineMock()
121 self.helm_conn.generate_kdu_instance_name = Mock(return_value=kdu_instance)
122
123 await self.helm_conn.install(
124 self.cluster_uuid,
125 kdu_model,
126 kdu_instance,
127 atomic=True,
128 namespace=self.namespace,
129 db_dict=db_dict
130 )
131
132 self.helm_conn.fs.sync.assert_called_once_with(from_path=self.cluster_id)
133 self.helm_conn.fs.reverse_sync.assert_called_once_with(from_path=self.cluster_id)
134 self.helm_conn._store_status.assert_called_with(cluster_id=self.cluster_id,
135 kdu_instance=kdu_instance,
136 namespace=self.namespace,
137 db_dict=db_dict,
138 operation="install",
139 run_once=True,
140 check_every=0)
141 command = "/usr/bin/helm install --atomic --output yaml --timeout 300 " \
142 "--name=stable-openldap-0005399828 --namespace testk8s stable/openldap " \
143 "--version 1.2.2"
144 self.helm_conn._local_async_exec.assert_called_once_with(command=command,
145 env=self.env,
146 raise_exception_on_error=False)
147
148 @asynctest.fail_on(active_handles=True)
149 async def test_upgrade(self):
150 kdu_model = "stable/openldap:1.2.3"
151 kdu_instance = "stable-openldap-0005399828"
152 db_dict = {}
153 instance_info = {
154 "chart": "openldap-1.2.2",
155 "name": kdu_instance,
156 "namespace": self.namespace,
157 "revision": 1,
158 "status": "DEPLOYED"
159 }
160 self.helm_conn._local_async_exec = asynctest.CoroutineMock(return_value=("", 0))
161 self.helm_conn._store_status = asynctest.CoroutineMock()
162 self.helm_conn.get_instance_info = asynctest.CoroutineMock(return_value=instance_info)
163
164 await self.helm_conn.upgrade(self.cluster_uuid,
165 kdu_instance,
166 kdu_model,
167 atomic=True,
168 db_dict=db_dict)
169 self.helm_conn.fs.sync.assert_called_once_with(from_path=self.cluster_id)
170 self.helm_conn.fs.reverse_sync.assert_called_once_with(from_path=self.cluster_id)
171 self.helm_conn._store_status.assert_called_with(cluster_id=self.cluster_id,
172 kdu_instance=kdu_instance,
173 namespace=self.namespace,
174 db_dict=db_dict,
175 operation="upgrade",
176 run_once=True,
177 check_every=0)
178 command = "/usr/bin/helm upgrade --atomic --output yaml --timeout 300 " \
179 "stable-openldap-0005399828 stable/openldap --version 1.2.3"
180 self.helm_conn._local_async_exec.assert_called_once_with(command=command,
181 env=self.env,
182 raise_exception_on_error=False)
183
184 @asynctest.fail_on(active_handles=True)
185 async def test_rollback(self):
186 kdu_instance = "stable-openldap-0005399828"
187 db_dict = {}
188 instance_info = {
189 "chart": "openldap-1.2.3",
190 "name": kdu_instance,
191 "namespace": self.namespace,
192 "revision": 2,
193 "status": "DEPLOYED"
194 }
195 self.helm_conn._local_async_exec = asynctest.CoroutineMock(return_value=("", 0))
196 self.helm_conn._store_status = asynctest.CoroutineMock()
197 self.helm_conn.get_instance_info = asynctest.CoroutineMock(return_value=instance_info)
198
199 await self.helm_conn.rollback(self.cluster_uuid,
200 kdu_instance=kdu_instance,
201 revision=1,
202 db_dict=db_dict)
203 self.helm_conn.fs.sync.assert_called_once_with(from_path=self.cluster_id)
204 self.helm_conn.fs.reverse_sync.assert_called_once_with(from_path=self.cluster_id)
205 self.helm_conn._store_status.assert_called_with(cluster_id=self.cluster_id,
206 kdu_instance=kdu_instance,
207 namespace=self.namespace,
208 db_dict=db_dict,
209 operation="rollback",
210 run_once=True,
211 check_every=0)
212 command = "/usr/bin/helm rollback stable-openldap-0005399828 1 --wait"
213 self.helm_conn._local_async_exec.assert_called_once_with(command=command,
214 env=self.env,
215 raise_exception_on_error=False)
216
217 @asynctest.fail_on(active_handles=True)
218 async def test_uninstall(self):
219 kdu_instance = "stable-openldap-0005399828"
220 instance_info = {
221 "chart": "openldap-1.2.2",
222 "name": kdu_instance,
223 "namespace": self.namespace,
224 "revision": 3,
225 "status": "DEPLOYED"
226 }
227 self.helm_conn._local_async_exec = asynctest.CoroutineMock(return_value=("", 0))
228 self.helm_conn._store_status = asynctest.CoroutineMock()
229 self.helm_conn.get_instance_info = asynctest.CoroutineMock(return_value=instance_info)
230
231 await self.helm_conn.uninstall(self.cluster_uuid, kdu_instance)
232 self.helm_conn.fs.sync.assert_called_once_with(from_path=self.cluster_id)
233 self.helm_conn.fs.reverse_sync.assert_called_once_with(from_path=self.cluster_id)
234 command = "/usr/bin/helm delete --purge {}".format(kdu_instance)
235 self.helm_conn._local_async_exec.assert_called_once_with(command=command,
236 env=self.env,
237 raise_exception_on_error=True)
238
239 @asynctest.fail_on(active_handles=True)
240 async def test_get_services(self):
241 kdu_instance = "test_services_1"
242 service = {
243 "name": "testservice",
244 "type": "LoadBalancer"
245 }
246 self.helm_conn._local_async_exec_pipe = asynctest.CoroutineMock(return_value=("", 0))
247 self.helm_conn._parse_services = Mock(return_value=["testservice"])
248 self.helm_conn._get_service = asynctest.CoroutineMock(return_value=service)
249
250 services = await self.helm_conn.get_services(self.cluster_uuid, kdu_instance,
251 self.namespace)
252 self.helm_conn.fs.sync.assert_called_once_with(from_path=self.cluster_id)
253 self.helm_conn.fs.reverse_sync.assert_called_once_with(from_path=self.cluster_id)
254 self.helm_conn._parse_services.assert_called_once()
255 command1 = "/usr/bin/helm get manifest {} ".format(kdu_instance)
256 command2 = "/usr/bin/kubectl get --namespace={} -f -".format(self.namespace)
257 self.helm_conn._local_async_exec_pipe.assert_called_once_with(command1, command2,
258 env=self.env,
259 raise_exception_on_error=True)
260 self.assertEqual(services, [service], "Invalid service returned from get_service")
261
262 @asynctest.fail_on(active_handles=True)
263 async def test_get_service(self):
264 service_name = "service1"
265
266 self.helm_conn._local_async_exec = asynctest.CoroutineMock(return_value=("", 0))
267 await self.helm_conn.get_service(self.cluster_uuid, service_name, self.namespace)
268
269 self.helm_conn.fs.sync.assert_called_once_with(from_path=self.cluster_id)
270 self.helm_conn.fs.reverse_sync.assert_called_once_with(from_path=self.cluster_id)
271 command = "/usr/bin/kubectl --kubeconfig=./tmp/helm_cluster_id/.kube/config " \
272 "--namespace=testk8s get service service1 -o=yaml"
273 self.helm_conn._local_async_exec.assert_called_once_with(command=command,
274 env=self.env,
275 raise_exception_on_error=True)
276
277 @asynctest.fail_on(active_handles=True)
278 async def test_inspect_kdu(self):
279 self.helm_conn._local_async_exec = asynctest.CoroutineMock(return_value=("", 0))
280
281 kdu_model = "stable/openldap:1.2.4"
282 repo_url = "https://kubernetes-charts.storage.googleapis.com/"
283 await self.helm_conn.inspect_kdu(kdu_model, repo_url)
284
285 command = "/usr/bin/helm inspect openldap --repo " \
286 "https://kubernetes-charts.storage.googleapis.com/ " \
287 "--version 1.2.4"
288 self.helm_conn._local_async_exec.assert_called_with(command=command, encode_utf8=True)
289
290 @asynctest.fail_on(active_handles=True)
291 async def test_help_kdu(self):
292 self.helm_conn._local_async_exec = asynctest.CoroutineMock(return_value=("", 0))
293
294 kdu_model = "stable/openldap:1.2.4"
295 repo_url = "https://kubernetes-charts.storage.googleapis.com/"
296 await self.helm_conn.help_kdu(kdu_model, repo_url)
297
298 command = "/usr/bin/helm inspect readme openldap --repo " \
299 "https://kubernetes-charts.storage.googleapis.com/ " \
300 "--version 1.2.4"
301 self.helm_conn._local_async_exec.assert_called_with(command=command, encode_utf8=True)
302
303 @asynctest.fail_on(active_handles=True)
304 async def test_values_kdu(self):
305 self.helm_conn._local_async_exec = asynctest.CoroutineMock(return_value=("", 0))
306
307 kdu_model = "stable/openldap:1.2.4"
308 repo_url = "https://kubernetes-charts.storage.googleapis.com/"
309 await self.helm_conn.values_kdu(kdu_model, repo_url)
310
311 command = "/usr/bin/helm inspect values openldap --repo " \
312 "https://kubernetes-charts.storage.googleapis.com/ " \
313 "--version 1.2.4"
314 self.helm_conn._local_async_exec.assert_called_with(command=command, encode_utf8=True)
315
316 @asynctest.fail_on(active_handles=True)
317 async def test_instances_list(self):
318 self.helm_conn._local_async_exec = asynctest.CoroutineMock(return_value=("", 0))
319
320 await self.helm_conn.instances_list(self.cluster_uuid)
321 self.helm_conn.fs.sync.assert_called_once_with(from_path=self.cluster_id)
322 self.helm_conn.fs.reverse_sync.assert_called_once_with(from_path=self.cluster_id)
323 command = "/usr/bin/helm list --output yaml"
324 self.helm_conn._local_async_exec.assert_called_once_with(command=command,
325 env=self.env,
326 raise_exception_on_error=True)
327
328 @asynctest.fail_on(active_handles=True)
329 async def test_status_kdu(self):
330 kdu_instance = "stable-openldap-0005399828"
331 self.helm_conn._local_async_exec = asynctest.CoroutineMock(return_value=("", 0))
332
333 await self.helm_conn._status_kdu(self.cluster_id, kdu_instance,
334 self.namespace, return_text=True)
335 command = "/usr/bin/helm status {} --output yaml".format(kdu_instance)
336 self.helm_conn._local_async_exec.assert_called_once_with(command=command,
337 env=self.env,
338 raise_exception_on_error=True,
339 show_error_log=False)
340
341 @asynctest.fail_on(active_handles=True)
342 async def test_store_status(self):
343 kdu_instance = "stable-openldap-0005399828"
344 db_dict = {}
345 status = {
346 "info": {
347 "description": "Install complete",
348 "status": {
349 "code": "1",
350 "notes": "The openldap helm chart has been installed"
351 }
352 }
353 }
354 self.helm_conn._status_kdu = asynctest.CoroutineMock(return_value=status)
355 self.helm_conn.write_app_status_to_db = asynctest.CoroutineMock(return_value=status)
356
357 await self.helm_conn._store_status(cluster_id=self.cluster_id,
358 kdu_instance=kdu_instance,
359 namespace=self.namespace,
360 db_dict=db_dict,
361 operation="install",
362 run_once=True,
363 check_every=0)
364 self.helm_conn._status_kdu.assert_called_once_with(cluster_id=self.cluster_id,
365 kdu_instance=kdu_instance,
366 namespace=self.namespace,
367 return_text=False)
368 self.helm_conn.write_app_status_to_db.assert_called_once_with(db_dict=db_dict,
369 status="Install complete",
370 detailed_status=str(status),
371 operation="install")
372
373 @asynctest.fail_on(active_handles=True)
374 async def test_reset_uninstall_false(self):
375 self.helm_conn._uninstall_sw = asynctest.CoroutineMock()
376
377 await self.helm_conn.reset(self.cluster_uuid, force=False, uninstall_sw=False)
378 self.helm_conn.fs.sync.assert_called_once_with(from_path=self.cluster_id)
379 self.helm_conn.fs.file_delete.assert_called_once_with(self.cluster_id,
380 ignore_non_exist=True)
381 self.helm_conn._uninstall_sw.assert_not_called()
382
383 @asynctest.fail_on(active_handles=True)
384 async def test_reset_uninstall(self):
385 kdu_instance = 'stable-openldap-0021099429'
386 instances = [
387 {
388 'app_version': '2.4.48',
389 'chart': 'openldap-1.2.3',
390 'name': kdu_instance,
391 'namespace': self.namespace,
392 'revision': '1',
393 'status': 'deployed',
394 'updated': '2020-10-30 11:11:20.376744191 +0000 UTC'
395 }
396 ]
397 self.helm_conn._uninstall_sw = asynctest.CoroutineMock()
398 self.helm_conn.instances_list = asynctest.CoroutineMock(return_value=instances)
399 self.helm_conn.uninstall = asynctest.CoroutineMock()
400
401 await self.helm_conn.reset(self.cluster_uuid, force=True, uninstall_sw=True)
402 self.helm_conn.fs.sync.assert_called_once_with(from_path=self.cluster_id)
403 self.helm_conn.fs.file_delete.assert_called_once_with(self.cluster_id,
404 ignore_non_exist=True)
405 self.helm_conn.instances_list.assert_called_once_with(cluster_uuid=self.cluster_uuid)
406 self.helm_conn.uninstall.assert_called_once_with(cluster_uuid=self.cluster_uuid,
407 kdu_instance=kdu_instance)
408 self.helm_conn._uninstall_sw.assert_called_once_with(self.cluster_id, self.namespace)
409
410 @asynctest.fail_on(active_handles=True)
411 async def test_uninstall_sw_namespace(self):
412 self.helm_conn._local_async_exec = asynctest.CoroutineMock(return_value=("", 0))
413
414 await self.helm_conn._uninstall_sw(self.cluster_id, self.namespace)
415 calls = self.helm_conn._local_async_exec.call_args_list
416 self.assertEqual(len(calls), 3, "To uninstall should have executed three commands")
417 call0_kargs = calls[0][1]
418 command_0 = "/usr/bin/helm --kubeconfig={} --home={} reset".format(self.kube_config,
419 self.helm_home)
420 self.assertEqual(call0_kargs,
421 {"command": command_0,
422 "raise_exception_on_error": True,
423 "env": self.env}, "Invalid args for first call to local_exec")
424 call1_kargs = calls[1][1]
425 command_1 = "/usr/bin/kubectl --kubeconfig={} delete " \
426 "clusterrolebinding.rbac.authorization.k8s.io/osm-tiller-cluster-rule".\
427 format(self.kube_config)
428 self.assertEqual(call1_kargs,
429 {"command": command_1,
430 "raise_exception_on_error": False,
431 "env": self.env}, "Invalid args for second call to local_exec")
432 call2_kargs = calls[2][1]
433 command_2 = "/usr/bin/kubectl --kubeconfig={} --namespace kube-system delete " \
434 "serviceaccount/{}".\
435 format(self.kube_config, self.service_account)
436 self.assertEqual(call2_kargs,
437 {"command": command_2,
438 "raise_exception_on_error": False,
439 "env": self.env}, "Invalid args for third call to local_exec")