Feature 7184 New generation RO
[osm/LCM.git] / osm_lcm / tests / test_ns.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
19 import asynctest # pip3 install asynctest --user
20 import asyncio
21 import yaml
22 from os import getenv
23 from osm_lcm import ns
24 from osm_common.dbmemory import DbMemory
25 from osm_common.msgkafka import MsgKafka
26 from osm_common.fslocal import FsLocal
27 from osm_lcm.lcm_utils import TaskRegistry
28 from osm_lcm.ROclient import ROClient
29 from uuid import uuid4
30 # from asynctest.mock import patch
31
32 from osm_lcm.tests import test_db_descriptors as descriptors
33
34 __author__ = "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
35
36 """ Perform unittests using asynctest of osm_lcm.ns module
37 It allows, if some testing ENV are supplied, testing without mocking some external libraries for debugging:
38 OSMLCMTEST_NS_PUBKEY: public ssh-key returned by N2VC to inject to VMs
39 OSMLCMTEST_NS_NAME: change name of NS
40 OSMLCMTEST_PACKAGES_PATH: path where the vnf-packages are stored (de-compressed), each one on a 'vnfd_id' folder
41 OSMLCMTEST_NS_IPADDRESS: IP address where emulated VMs are reached. Comma separate list
42 OSMLCMTEST_RO_VIMID: VIM id of RO target vim IP. Obtain it with openmano datcenter-list on RO container
43 OSMLCMTEST_VCA_NOMOCK: Do no mock the VCA, N2VC library, for debugging it
44 OSMLCMTEST_RO_NOMOCK: Do no mock the ROClient library, for debugging it
45 OSMLCMTEST_DB_NOMOCK: Do no mock the database library, for debugging it
46 OSMLCMTEST_FS_NOMOCK: Do no mock the File Storage library, for debugging it
47 OSMLCMTEST_LOGGING_NOMOCK: Do no mock the logging
48 OSMLCM_VCA_XXX: configuration of N2VC
49 OSMLCM_RO_XXX: configuration of RO
50 """
51
52 lcm_config = {
53 "timeout": {},
54 "VCA": { # TODO replace with os.get_env to get other configurations
55 "host": getenv("OSMLCM_VCA_HOST", "vca"),
56 "port": getenv("OSMLCM_VCA_PORT", 17070),
57 "user": getenv("OSMLCM_VCA_USER", "admin"),
58 "secret": getenv("OSMLCM_VCA_SECRET", "vca"),
59 "public_key": getenv("OSMLCM_VCA_PUBKEY", None),
60 'ca_cert': getenv("OSMLCM_VCA_CACERT", None)
61 },
62 "ro_config": {
63 "uri": "http://{}:{}/openmano".format(getenv("OSMLCM_RO_HOST", "ro"),
64 getenv("OSMLCM_RO_PORT", "9090")),
65 "tenant": getenv("OSMLCM_RO_TENANT", "osm"),
66 "logger_name": "lcm.ROclient",
67 "loglevel": "DEBUG",
68 }
69 }
70
71
72 class TestMyNS(asynctest.TestCase):
73
74 async def _n2vc_DeployCharms(self, model_name, application_name, vnfd, charm_path, params={}, machine_spec={},
75 callback=None, *callback_args):
76 if callback:
77 for status, message in (("maintenance", "installing sofwware"), ("active", "Ready!")):
78 # call callback after some time
79 asyncio.sleep(5, loop=self.loop)
80 callback(model_name, application_name, status, message, *callback_args)
81
82 @staticmethod
83 def _n2vc_FormatApplicationName(*args):
84 num_calls = 0
85 while True:
86 yield "app_name-{}".format(num_calls)
87 num_calls += 1
88
89 def _n2vc_CreateExecutionEnvironment(self, namespace, reuse_ee_id, db_dict):
90 k_list = namespace.split(".")
91 ee_id = k_list[1] + "."
92 if len(k_list) >= 2:
93 for k in k_list[2:4]:
94 ee_id += k[:8]
95 else:
96 ee_id += "_NS_"
97 return ee_id, {}
98
99 def _ro_show(self, *args, **kwargs):
100 if kwargs.get("delete"):
101 ro_ns_desc = yaml.load(descriptors.ro_delete_action_text, Loader=yaml.Loader)
102 while True:
103 yield ro_ns_desc
104
105 ro_ns_desc = yaml.load(descriptors.ro_ns_text, Loader=yaml.Loader)
106
107 # if ip address provided, replace descriptor
108 ip_addresses = getenv("OSMLCMTEST_NS_IPADDRESS", "")
109 if ip_addresses:
110 ip_addresses_list = ip_addresses.split(",")
111 for vnf in ro_ns_desc["vnfs"]:
112 if not ip_addresses_list:
113 break
114 vnf["ip_address"] = ip_addresses_list[0]
115 for vm in vnf["vms"]:
116 if not ip_addresses_list:
117 break
118 vm["ip_address"] = ip_addresses_list.pop(0)
119
120 while True:
121 yield ro_ns_desc
122 for net in ro_ns_desc["nets"]:
123 if net["status"] != "ACTIVE":
124 net["status"] = "ACTIVE"
125 break
126 else:
127 for vnf in ro_ns_desc["vnfs"]:
128 for vm in vnf["vms"]:
129 if vm["status"] != "ACTIVE":
130 vm["status"] = "ACTIVE"
131 break
132
133 def _ro_create(self, *args, **kwargs):
134 while True:
135 yield {"uuid": str(uuid4())}
136
137 def _return_uuid(self, *args, **kwargs):
138 return str(uuid4())
139
140 async def setUp(self):
141
142 # Mock DB
143 if not getenv("OSMLCMTEST_DB_NOMOCK"):
144 self.db = DbMemory()
145 self.db.create_list("vnfds", yaml.load(descriptors.db_vnfds_text, Loader=yaml.Loader))
146 self.db.create_list("nsds", yaml.load(descriptors.db_nsds_text, Loader=yaml.Loader))
147 self.db.create_list("nsrs", yaml.load(descriptors.db_nsrs_text, Loader=yaml.Loader))
148 self.db.create_list("vim_accounts", yaml.load(descriptors.db_vim_accounts_text, Loader=yaml.Loader))
149 self.db.create_list("k8sclusters", yaml.load(descriptors.db_k8sclusters_text, Loader=yaml.Loader))
150 self.db.create_list("nslcmops", yaml.load(descriptors.db_nslcmops_text, Loader=yaml.Loader))
151 self.db.create_list("vnfrs", yaml.load(descriptors.db_vnfrs_text, Loader=yaml.Loader))
152 self.db_vim_accounts = yaml.load(descriptors.db_vim_accounts_text, Loader=yaml.Loader)
153
154 # Mock kafka
155 self.msg = asynctest.Mock(MsgKafka())
156
157 # Mock filesystem
158 if not getenv("OSMLCMTEST_FS_NOMOCK"):
159 self.fs = asynctest.Mock(FsLocal())
160 self.fs.get_params.return_value = {"path": getenv("OSMLCMTEST_PACKAGES_PATH", "./test/temp/packages")}
161 self.fs.file_open = asynctest.mock_open()
162 # self.fs.file_open.return_value.__enter__.return_value = asynctest.MagicMock() # called on a python "with"
163 # self.fs.file_open.return_value.__enter__.return_value.read.return_value = "" # empty file
164
165 # Mock TaskRegistry
166 self.lcm_tasks = asynctest.Mock(TaskRegistry())
167 self.lcm_tasks.lock_HA.return_value = True
168 self.lcm_tasks.waitfor_related_HA.return_value = None
169 self.lcm_tasks.lookfor_related.return_value = ("", [])
170
171 # Mock VCA - K8s
172 if not getenv("OSMLCMTEST_VCA_K8s_NOMOCK"):
173 ns.K8sJujuConnector = asynctest.MagicMock(ns.K8sJujuConnector)
174 ns.K8sHelmConnector = asynctest.MagicMock(ns.K8sHelmConnector)
175
176 if not getenv("OSMLCMTEST_VCA_NOMOCK"):
177 ns.N2VCJujuConnector = asynctest.MagicMock(ns.N2VCJujuConnector)
178
179 # Create NsLCM class
180 self.my_ns = ns.NsLcm(self.db, self.msg, self.fs, self.lcm_tasks, lcm_config, self.loop)
181 self.my_ns._wait_dependent_n2vc = asynctest.CoroutineMock()
182
183 # Mock logging
184 if not getenv("OSMLCMTEST_LOGGING_NOMOCK"):
185 self.my_ns.logger = asynctest.Mock(self.my_ns.logger)
186
187 # Mock VCA - N2VC
188 if not getenv("OSMLCMTEST_VCA_NOMOCK"):
189 pub_key = getenv("OSMLCMTEST_NS_PUBKEY", "ssh-rsa test-pub-key t@osm.com")
190 # self.my_ns.n2vc = asynctest.Mock(N2VC())
191 self.my_ns.n2vc.GetPublicKey.return_value = getenv("OSMLCM_VCA_PUBKEY", "public_key")
192 # allow several versions of n2vc
193 self.my_ns.n2vc.FormatApplicationName = asynctest.Mock(side_effect=self._n2vc_FormatApplicationName())
194 self.my_ns.n2vc.DeployCharms = asynctest.CoroutineMock(side_effect=self._n2vc_DeployCharms)
195 self.my_ns.n2vc.create_execution_environment = asynctest.CoroutineMock(
196 side_effect=self._n2vc_CreateExecutionEnvironment)
197 self.my_ns.n2vc.install_configuration_sw = asynctest.CoroutineMock(return_value=pub_key)
198 self.my_ns.n2vc.get_ee_ssh_public__key = asynctest.CoroutineMock(return_value=pub_key)
199 self.my_ns.n2vc.exec_primitive = asynctest.CoroutineMock(side_effect=self._return_uuid)
200 self.my_ns.n2vc.GetPrimitiveStatus = asynctest.CoroutineMock(return_value="completed")
201 self.my_ns.n2vc.GetPrimitiveOutput = asynctest.CoroutineMock(return_value={"result": "ok",
202 "pubkey": pub_key})
203 self.my_ns.n2vc.delete_execution_environment = asynctest.CoroutineMock(return_value=None)
204 self.my_ns.n2vc.get_public_key = asynctest.CoroutineMock(
205 return_value=getenv("OSMLCM_VCA_PUBKEY", "public_key"))
206 self.my_ns.n2vc.delete_namespace = asynctest.CoroutineMock(return_value=None)
207
208 # Mock RO
209 if not getenv("OSMLCMTEST_RO_NOMOCK"):
210 # self.my_ns.RO = asynctest.Mock(ROclient.ROClient(self.loop, **lcm_config["ro_config"]))
211 # TODO first time should be empty list, following should return a dict
212 self.my_ns.RO.get_list = asynctest.CoroutineMock(self.my_ns.RO.get_list, return_value=[])
213 self.my_ns.RO.create = asynctest.CoroutineMock(self.my_ns.RO.create, side_effect=self._ro_create())
214 self.my_ns.RO.show = asynctest.CoroutineMock(self.my_ns.RO.show, side_effect=self._ro_show())
215 self.my_ns.RO.create_action = asynctest.CoroutineMock(self.my_ns.RO.create_action,
216 return_value={"vm-id": {"vim_result": 200,
217 "description": "done"}})
218 self.my_ns.RO.delete = asynctest.CoroutineMock(self.my_ns.RO.delete, return_value={"action_id": "del"})
219 # self.my_ns.wait_vm_up_insert_key_ro = asynctest.CoroutineMock(return_value="ip-address")
220
221 @asynctest.fail_on(active_handles=True) # all async tasks must be completed
222 async def test_instantiate(self):
223 self.db.set_one = asynctest.Mock()
224 nsr_id = descriptors.test_ids["TEST-A"]["ns"]
225 nslcmop_id = descriptors.test_ids["TEST-A"]["instantiate"]
226 # print("Test instantiate started")
227
228 # delete deployed information of database
229 if not getenv("OSMLCMTEST_DB_NOMOCK"):
230 if self.db.get_list("nsrs")[0]["_admin"].get("deployed"):
231 del self.db.get_list("nsrs")[0]["_admin"]["deployed"]
232 for db_vnfr in self.db.get_list("vnfrs"):
233 db_vnfr.pop("ip_address", None)
234 for db_vdur in db_vnfr["vdur"]:
235 db_vdur.pop("ip_address", None)
236 db_vdur.pop("mac_address", None)
237 if getenv("OSMLCMTEST_RO_VIMID"):
238 self.db.get_list("vim_accounts")[0]["_admin"]["deployed"]["RO"] = getenv("OSMLCMTEST_RO_VIMID")
239 if getenv("OSMLCMTEST_RO_VIMID"):
240 self.db.get_list("nsrs")[0]["_admin"]["deployed"]["RO"] = getenv("OSMLCMTEST_RO_VIMID")
241
242 await self.my_ns.instantiate(nsr_id, nslcmop_id)
243
244 # print("instantiate_result: {}".format(self.db.get_one("nslcmops",
245 # {"_id": nslcmop_id}).get("detailed-status")))
246
247 self.msg.aiowrite.assert_called_once_with("ns", "instantiated",
248 {"nsr_id": nsr_id, "nslcmop_id": nslcmop_id,
249 "operationState": "COMPLETED"},
250 loop=self.loop)
251 self.lcm_tasks.lock_HA.assert_called_once_with('ns', 'nslcmops', nslcmop_id)
252 if not getenv("OSMLCMTEST_LOGGING_NOMOCK"):
253 self.assertTrue(self.my_ns.logger.debug.called, "Debug method not called")
254 self.my_ns.logger.error.assert_not_called()
255 self.my_ns.logger.exception().assert_not_called()
256
257 if not getenv("OSMLCMTEST_DB_NOMOCK"):
258 self.assertTrue(self.db.set_one.called, "db.set_one not called")
259
260 # TODO add more checks of called methods
261 # TODO add a terminate
262
263 def test_ns_params_2_RO(self):
264 vims = self.db.get_list("vim_accounts")
265 vim_id = vims[0]["_id"]
266 ro_vim_id = vims[0]["_admin"]["deployed"]["RO"]
267 vim_id2 = vims[1]["_id"]
268 ro_vim_id2 = vims[1]["_admin"]["deployed"]["RO"]
269
270 ns_params = {"vimAccountId": vim_id}
271 mgmt_interface = {"cp": "cp"}
272 vdu = [{"id": "vdu_id", "interface": [{"external-connection-point-ref": "cp"}]}]
273 vnfd_dict = {
274 "1": {"vdu": vdu, "mgmt-interface": mgmt_interface},
275 "2": {"vdu": vdu, "mgmt-interface": mgmt_interface, "vnf-configuration": None},
276 "3": {"vdu": vdu, "mgmt-interface": mgmt_interface, "vnf-configuration": {"config-access": None}},
277 "4": {"vdu": vdu, "mgmt-interface": mgmt_interface,
278 "vnf-configuration": {"config-access": {"ssh-access": None}}},
279 "5": {"vdu": vdu, "mgmt-interface": mgmt_interface,
280 "vnf-configuration": {"config-access": {"ssh-access": {"required": True, "default_user": "U"}}}},
281 }
282 nsd = {"constituent-vnfd": []}
283 db_vnfrs = {}
284 for k in vnfd_dict.keys():
285 nsd["constituent-vnfd"].append({"vnfd-id-ref": k, "member-vnf-index": "member " + k})
286 db_vnfrs["member " + k] = {"vim-account-id": vim_id2 if k == "1" else vim_id}
287
288 n2vc_key_list = ["key"]
289 ro_ns_params = self.my_ns._ns_params_2_RO(ns_params, nsd, vnfd_dict, db_vnfrs, n2vc_key_list)
290 ro_params_expected = {'wim_account': None, "datacenter": ro_vim_id,
291 "vnfs": {
292 "member 5": {"vdus": {"vdu_id": {"mgmt_keys": n2vc_key_list}}},
293 "member 1": {"datacenter": ro_vim_id2}
294 }}
295 self.assertEqual(ro_ns_params, ro_params_expected)
296
297 # Test scale() and related methods
298 @asynctest.fail_on(active_handles=True) # all async tasks must be completed
299 async def test_scale(self):
300 # print("Test scale started")
301
302 # TODO: Add more higher-lever tests here, for example:
303 # scale-out/scale-in operations with success/error result
304
305 # Test scale() with missing 'scaleVnfData', should return operationState = 'FAILED'
306 nsr_id = descriptors.test_ids["TEST-A"]["ns"]
307 nslcmop_id = descriptors.test_ids["TEST-A"]["instantiate"]
308 await self.my_ns.scale(nsr_id, nslcmop_id)
309 expected_value = 'FAILED'
310 return_value = self.db.get_one("nslcmops", {"_id": nslcmop_id}).get("operationState")
311 self.assertEqual(return_value, expected_value)
312 # print("scale_result: {}".format(self.db.get_one("nslcmops", {"_id": nslcmop_id}).get("detailed-status")))
313
314 # Test _retry_or_skip_suboperation()
315 # Expected result:
316 # - if a suboperation's 'operationState' is marked as 'COMPLETED', SUBOPERATION_STATUS_SKIP is expected
317 # - if marked as anything but 'COMPLETED', the suboperation index is expected
318 def test_scale_retry_or_skip_suboperation(self):
319 # Load an alternative 'nslcmops' YAML for this test
320 nslcmop_id = descriptors.test_ids["TEST-A"]["instantiate"]
321 db_nslcmop = self.db.get_one('nslcmops', {"_id": nslcmop_id})
322 op_index = 2
323 # Test when 'operationState' is 'COMPLETED'
324 db_nslcmop['_admin']['operations'][op_index]['operationState'] = 'COMPLETED'
325 return_value = self.my_ns._retry_or_skip_suboperation(db_nslcmop, op_index)
326 expected_value = self.my_ns.SUBOPERATION_STATUS_SKIP
327 self.assertEqual(return_value, expected_value)
328 # Test when 'operationState' is not 'COMPLETED'
329 db_nslcmop['_admin']['operations'][op_index]['operationState'] = None
330 return_value = self.my_ns._retry_or_skip_suboperation(db_nslcmop, op_index)
331 expected_value = op_index
332 self.assertEqual(return_value, expected_value)
333
334 # Test _find_suboperation()
335 # Expected result: index of the found sub-operation, or SUBOPERATION_STATUS_NOT_FOUND if not found
336 def test_scale_find_suboperation(self):
337 # Load an alternative 'nslcmops' YAML for this test
338 nslcmop_id = descriptors.test_ids["TEST-A"]["instantiate"]
339 db_nslcmop = self.db.get_one('nslcmops', {"_id": nslcmop_id})
340 # Find this sub-operation
341 op_index = 2
342 vnf_index = db_nslcmop['_admin']['operations'][op_index]['member_vnf_index']
343 primitive = db_nslcmop['_admin']['operations'][op_index]['primitive']
344 primitive_params = db_nslcmop['_admin']['operations'][op_index]['primitive_params']
345 match = {
346 'member_vnf_index': vnf_index,
347 'primitive': primitive,
348 'primitive_params': primitive_params,
349 }
350 found_op_index = self.my_ns._find_suboperation(db_nslcmop, match)
351 self.assertEqual(found_op_index, op_index)
352 # Test with not-matching params
353 match = {
354 'member_vnf_index': vnf_index,
355 'primitive': '',
356 'primitive_params': primitive_params,
357 }
358 found_op_index = self.my_ns._find_suboperation(db_nslcmop, match)
359 self.assertEqual(found_op_index, self.my_ns.SUBOPERATION_STATUS_NOT_FOUND)
360 # Test with None
361 match = None
362 found_op_index = self.my_ns._find_suboperation(db_nslcmop, match)
363 self.assertEqual(found_op_index, self.my_ns.SUBOPERATION_STATUS_NOT_FOUND)
364
365 # Test _update_suboperation_status()
366 def test_scale_update_suboperation_status(self):
367 self.db.set_one = asynctest.Mock()
368 nslcmop_id = descriptors.test_ids["TEST-A"]["instantiate"]
369 db_nslcmop = self.db.get_one('nslcmops', {"_id": nslcmop_id})
370 op_index = 0
371 # Force the initial values to be distinct from the updated ones
372 q_filter = {"_id": db_nslcmop["_id"]}
373 # Test to change 'operationState' and 'detailed-status'
374 operationState = 'COMPLETED'
375 detailed_status = 'Done'
376 expected_update_dict = {'_admin.operations.0.operationState': operationState,
377 '_admin.operations.0.detailed-status': detailed_status,
378 }
379 self.my_ns._update_suboperation_status(db_nslcmop, op_index, operationState, detailed_status)
380 self.db.set_one.assert_called_once_with("nslcmops", q_filter=q_filter, update_dict=expected_update_dict,
381 fail_on_empty=False)
382
383 def test_scale_add_suboperation(self):
384 nslcmop_id = descriptors.test_ids["TEST-A"]["instantiate"]
385 db_nslcmop = self.db.get_one('nslcmops', {"_id": nslcmop_id})
386 vnf_index = '1'
387 num_ops_before = len(db_nslcmop.get('_admin', {}).get('operations', [])) - 1
388 vdu_id = None
389 vdu_count_index = None
390 vdu_name = None
391 primitive = 'touch'
392 mapped_primitive_params = {'parameter':
393 [{'data-type': 'STRING',
394 'name': 'filename',
395 'default-value': '<touch_filename2>'}],
396 'name': 'touch'}
397 operationState = 'PROCESSING'
398 detailed_status = 'In progress'
399 operationType = 'PRE-SCALE'
400 # Add a 'pre-scale' suboperation
401 op_index_after = self.my_ns._add_suboperation(db_nslcmop, vnf_index, vdu_id, vdu_count_index,
402 vdu_name, primitive, mapped_primitive_params,
403 operationState, detailed_status, operationType)
404 self.assertEqual(op_index_after, num_ops_before + 1)
405
406 # Delete all suboperations and add the same operation again
407 del db_nslcmop['_admin']['operations']
408 op_index_zero = self.my_ns._add_suboperation(db_nslcmop, vnf_index, vdu_id, vdu_count_index,
409 vdu_name, primitive, mapped_primitive_params,
410 operationState, detailed_status, operationType)
411 self.assertEqual(op_index_zero, 0)
412
413 # Add a 'RO' suboperation
414 RO_nsr_id = '1234567890'
415 RO_scaling_info = [{'type': 'create', 'count': 1, 'member-vnf-index': '1', 'osm_vdu_id': 'dataVM'}]
416 op_index = self.my_ns._add_suboperation(db_nslcmop, vnf_index, vdu_id, vdu_count_index,
417 vdu_name, primitive, mapped_primitive_params,
418 operationState, detailed_status, operationType,
419 RO_nsr_id, RO_scaling_info)
420 db_RO_nsr_id = db_nslcmop['_admin']['operations'][op_index]['RO_nsr_id']
421 self.assertEqual(op_index, 1)
422 self.assertEqual(RO_nsr_id, db_RO_nsr_id)
423
424 # Try to add an invalid suboperation, should return SUBOPERATION_STATUS_NOT_FOUND
425 op_index_invalid = self.my_ns._add_suboperation(None, None, None, None, None,
426 None, None, None,
427 None, None, None)
428 self.assertEqual(op_index_invalid, self.my_ns.SUBOPERATION_STATUS_NOT_FOUND)
429
430 # Test _check_or_add_scale_suboperation() and _check_or_add_scale_suboperation_RO()
431 # check the possible return values:
432 # - SUBOPERATION_STATUS_NEW: This is a new sub-operation
433 # - op_index (non-negative number): This is an existing sub-operation, operationState != 'COMPLETED'
434 # - SUBOPERATION_STATUS_SKIP: This is an existing sub-operation, operationState == 'COMPLETED'
435 def test_scale_check_or_add_scale_suboperation(self):
436 nslcmop_id = descriptors.test_ids["TEST-A"]["instantiate"]
437 db_nslcmop = self.db.get_one('nslcmops', {"_id": nslcmop_id})
438 operationType = 'PRE-SCALE'
439 vnf_index = '1'
440 primitive = 'touch'
441 primitive_params = {'parameter':
442 [{'data-type': 'STRING',
443 'name': 'filename',
444 'default-value': '<touch_filename2>'}],
445 'name': 'touch'}
446
447 # Delete all sub-operations to be sure this is a new sub-operation
448 del db_nslcmop['_admin']['operations']
449
450 # Add a new sub-operation
451 # For new sub-operations, operationState is set to 'PROCESSING' by default
452 op_index_new = self.my_ns._check_or_add_scale_suboperation(
453 db_nslcmop, vnf_index, primitive, primitive_params, operationType)
454 self.assertEqual(op_index_new, self.my_ns.SUBOPERATION_STATUS_NEW)
455
456 # Use the same parameters again to match the already added sub-operation
457 # which has status 'PROCESSING' (!= 'COMPLETED') by default
458 # The expected return value is a non-negative number
459 op_index_existing = self.my_ns._check_or_add_scale_suboperation(
460 db_nslcmop, vnf_index, primitive, primitive_params, operationType)
461 self.assertTrue(op_index_existing >= 0)
462
463 # Change operationState 'manually' for this sub-operation
464 db_nslcmop['_admin']['operations'][op_index_existing]['operationState'] = 'COMPLETED'
465 # Then use the same parameters again to match the already added sub-operation,
466 # which now has status 'COMPLETED'
467 # The expected return value is SUBOPERATION_STATUS_SKIP
468 op_index_skip = self.my_ns._check_or_add_scale_suboperation(
469 db_nslcmop, vnf_index, primitive, primitive_params, operationType)
470 self.assertEqual(op_index_skip, self.my_ns.SUBOPERATION_STATUS_SKIP)
471
472 # RO sub-operation test:
473 # Repeat tests for the very similar _check_or_add_scale_suboperation_RO(),
474 RO_nsr_id = '1234567890'
475 RO_scaling_info = [{'type': 'create', 'count': 1, 'member-vnf-index': '1', 'osm_vdu_id': 'dataVM'}]
476 op_index_new_RO = self.my_ns._check_or_add_scale_suboperation(
477 db_nslcmop, vnf_index, None, None, 'SCALE-RO', RO_nsr_id, RO_scaling_info)
478 self.assertEqual(op_index_new_RO, self.my_ns.SUBOPERATION_STATUS_NEW)
479
480 # Use the same parameters again to match the already added RO sub-operation
481 op_index_existing_RO = self.my_ns._check_or_add_scale_suboperation(
482 db_nslcmop, vnf_index, None, None, 'SCALE-RO', RO_nsr_id, RO_scaling_info)
483 self.assertTrue(op_index_existing_RO >= 0)
484
485 # Change operationState 'manually' for this RO sub-operation
486 db_nslcmop['_admin']['operations'][op_index_existing_RO]['operationState'] = 'COMPLETED'
487 # Then use the same parameters again to match the already added sub-operation,
488 # which now has status 'COMPLETED'
489 # The expected return value is SUBOPERATION_STATUS_SKIP
490 op_index_skip_RO = self.my_ns._check_or_add_scale_suboperation(
491 db_nslcmop, vnf_index, None, None, 'SCALE-RO', RO_nsr_id, RO_scaling_info)
492 self.assertEqual(op_index_skip_RO, self.my_ns.SUBOPERATION_STATUS_SKIP)
493
494 async def test_deploy_kdus(self):
495 nsr_id = descriptors.test_ids["TEST-KDU"]["ns"]
496 nslcmop_id = descriptors.test_ids["TEST-KDU"]["instantiate"]
497 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
498 db_vnfr = self.db.get_one("vnfrs", {"nsr-id-ref": nsr_id, "member-vnf-index-ref": "multikdu"})
499 db_vnfrs = {"multikdu": db_vnfr}
500 db_vnfd = self.db.get_one("vnfds", {"_id": db_vnfr["vnfd-id"]})
501 db_vnfds = {db_vnfd["_id"]: db_vnfd}
502 task_register = {}
503 logging_text = "KDU"
504 self.my_ns.k8sclusterhelm.install = asynctest.CoroutineMock(return_value="k8s_id")
505 self.my_ns.k8sclusterhelm.synchronize_repos = asynctest.CoroutineMock(return_value=("", ""))
506 await self.my_ns.deploy_kdus(logging_text, nsr_id, nslcmop_id, db_vnfrs, db_vnfds, task_register)
507 await asyncio.wait(list(task_register.keys()), timeout=100)
508 db_nsr = self.db.get_list("nsrs")[1]
509 self.assertIn("K8s", db_nsr["_admin"]["deployed"], "K8s entry not created at '_admin.deployed'")
510 self.assertIsInstance(db_nsr["_admin"]["deployed"]["K8s"], list, "K8s entry is not of type list")
511 self.assertEqual(len(db_nsr["_admin"]["deployed"]["K8s"]), 2, "K8s entry is not of type list")
512 k8s_instace_info = {"kdu-instance": "k8s_id", "k8scluster-uuid": "73d96432-d692-40d2-8440-e0c73aee209c",
513 "k8scluster-type": "helm-chart",
514 "kdu-name": "ldap", "kdu-model": "stable/openldap:1.2.1",
515 "member-vnf-index": "multikdu", "namespace": None}
516
517 self.assertEqual(db_nsr["_admin"]["deployed"]["K8s"][0], k8s_instace_info)
518 k8s_instace_info["kdu-name"] = "mongo"
519 k8s_instace_info["kdu-model"] = "stable/mongodb"
520 self.assertEqual(db_nsr["_admin"]["deployed"]["K8s"][1], k8s_instace_info)
521
522 async def test_instantiate_pdu(self):
523 nsr_id = descriptors.test_ids["TEST-A"]["ns"]
524 nslcmop_id = descriptors.test_ids["TEST-A"]["instantiate"]
525 # Modify vnfd/vnfr to change KDU for PDU. Adding keys that NBI will already set
526 self.db.set_one("vnfrs", {"nsr-id-ref": nsr_id, "member-vnf-index-ref": "1"},
527 update_dict={"ip-address": "10.205.1.46",
528 "vdur.0.pdu-id": "53e1ec21-2464-451e-a8dc-6e311d45b2c8",
529 "vdur.0.pdu-type": "PDU-TYPE-1",
530 "vdur.0.ip-address": "10.205.1.46",
531 },
532 unset={"vdur.status": None})
533 self.db.set_one("vnfrs", {"nsr-id-ref": nsr_id, "member-vnf-index-ref": "2"},
534 update_dict={"ip-address": "10.205.1.47",
535 "vdur.0.pdu-id": "53e1ec21-2464-451e-a8dc-6e311d45b2c8",
536 "vdur.0.pdu-type": "PDU-TYPE-1",
537 "vdur.0.ip-address": "10.205.1.47",
538 },
539 unset={"vdur.status": None})
540
541 await self.my_ns.instantiate(nsr_id, nslcmop_id)
542 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
543 self.assertEqual(db_nsr.get("nsState"), "READY", str(db_nsr.get("errorDescription ")))
544 self.assertEqual(db_nsr.get("currentOperation"), "IDLE", "currentOperation different than 'IDLE'")
545 self.assertEqual(db_nsr.get("currentOperationID"), None, "currentOperationID different than None")
546 self.assertEqual(db_nsr.get("errorDescription "), None, "errorDescription different than None")
547 self.assertEqual(db_nsr.get("errorDetail"), None, "errorDetail different than None")
548
549 @asynctest.fail_on(active_handles=True) # all async tasks must be completed
550 async def test_terminate_without_configuration(self):
551 nsr_id = descriptors.test_ids["TEST-A"]["ns"]
552 nslcmop_id = descriptors.test_ids["TEST-A"]["terminate"]
553 # set instantiation task as completed
554 self.db.set_list("nslcmops", {"nsInstanceId": nsr_id, "_id.ne": nslcmop_id},
555 update_dict={"operationState": "COMPLETED"})
556 self.my_ns.RO.show = asynctest.CoroutineMock(ROClient.show, side_effect=self._ro_show(delete=nslcmop_id))
557 self.db.set_one("nsrs", {"_id": nsr_id},
558 update_dict={"_admin.deployed.VCA.0": None, "_admin.deployed.VCA.1": None})
559
560 await self.my_ns.terminate(nsr_id, nslcmop_id)
561 db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
562 self.assertEqual(db_nslcmop.get("operationState"), 'COMPLETED', db_nslcmop.get("detailed-status"))
563 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
564 self.assertEqual(db_nsr.get("nsState"), "NOT_INSTANTIATED", str(db_nsr.get("errorDescription ")))
565 self.assertEqual(db_nsr["_admin"].get("nsState"), "NOT_INSTANTIATED", str(db_nsr.get("errorDescription ")))
566 self.assertEqual(db_nsr.get("currentOperation"), "IDLE", "currentOperation different than 'IDLE'")
567 self.assertEqual(db_nsr.get("currentOperationID"), None, "currentOperationID different than None")
568 self.assertEqual(db_nsr.get("errorDescription "), None, "errorDescription different than None")
569 self.assertEqual(db_nsr.get("errorDetail"), None, "errorDetail different than None")
570
571 @asynctest.fail_on(active_handles=True) # all async tasks must be completed
572 async def test_terminate_primitive(self):
573 nsr_id = descriptors.test_ids["TEST-A"]["ns"]
574 nslcmop_id = descriptors.test_ids["TEST-A"]["terminate"]
575 self.my_ns.RO.show = asynctest.CoroutineMock(ROClient.show, side_effect=self._ro_show(delete=nslcmop_id))
576 # set instantiation task as completed
577 self.db.set_list("nslcmops", {"nsInstanceId": nsr_id, "_id.ne": nslcmop_id},
578 update_dict={"operationState": "COMPLETED"})
579
580 # modify vnfd descriptor to include terminate_primitive
581 terminate_primitive = [{
582 "name": "touch",
583 "parameter": [{"name": "filename", "value": "terminate_filename"}],
584 "seq": '1'
585 }]
586 db_vnfr = self.db.get_one("vnfrs", {"nsr-id-ref": nsr_id, "member-vnf-index-ref": "1"})
587 self.db.set_one("vnfds", {"_id": db_vnfr["vnfd-id"]},
588 {"vnf-configuration.terminate-config-primitive": terminate_primitive})
589
590 await self.my_ns.terminate(nsr_id, nslcmop_id)
591 db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
592 self.assertEqual(db_nslcmop.get("operationState"), 'COMPLETED', db_nslcmop.get("detailed-status"))
593 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
594 self.assertEqual(db_nsr.get("nsState"), "NOT_INSTANTIATED", str(db_nsr.get("errorDescription ")))
595 self.assertEqual(db_nsr["_admin"].get("nsState"), "NOT_INSTANTIATED", str(db_nsr.get("errorDescription ")))
596 self.assertEqual(db_nsr.get("currentOperation"), "IDLE", "currentOperation different than 'IDLE'")
597 self.assertEqual(db_nsr.get("currentOperationID"), None, "currentOperationID different than None")
598 self.assertEqual(db_nsr.get("errorDescription "), None, "errorDescription different than None")
599 self.assertEqual(db_nsr.get("errorDetail"), None, "errorDetail different than None")
600
601
602 if __name__ == '__main__':
603 asynctest.main()