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