6cda0af0fb077aeddca5e84d46fb9e8e53b1f95c
[vfc/gvnfm/vnflcm.git] / lcm / lcm / pub / vimapi / adaptor.py
1 # Copyright 2017 ZTE Corporation.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 #         http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 import logging
16 import time
17 import json
18 import os
19 import base64
20
21 from lcm.pub.utils.values import ignore_case_get, set_opt_val
22 from . import api
23 from .exceptions import VimException
24 from lcm.pub.exceptions import NFLCMException
25 from lcm.nf.const import ACTION_TYPE, HEAL_ACTION_TYPE
26
27 logger = logging.getLogger(__name__)
28
29 ERR_CODE = "500"
30 RES_EXIST, RES_NEW = 0, 1
31 IP_V4, IP_V6 = 4, 6
32 BOOT_FROM_VOLUME, BOOT_FROM_IMAGE = 1, 2
33
34 RES_VOLUME = "volume"
35 RES_NETWORK = "network"
36 RES_SUBNET = "subnet"
37 RES_PORT = "port"
38 RES_FLAVOR = "flavor"
39 RES_VM = "vm"
40 NOT_PREDEFINED = 1
41
42
43 def get_tenant_id(vim_cache, vim_id, tenant_name):
44     if vim_id not in vim_cache:
45         tenants = api.list_tenant(vim_id)
46         vim_cache[vim_id] = {}
47         for tenant in tenants["tenants"]:
48             id, name = tenant["id"], tenant["name"]
49             vim_cache[vim_id][name] = id
50     if tenant_name not in vim_cache[vim_id]:
51         raise VimException("Tenant(%s) not found in vim(%s)" % (tenant_name, vim_id), ERR_CODE)
52     return vim_cache[vim_id][tenant_name]
53
54
55 def set_res_cache(res_cache, res_type, key, val):
56     if res_type not in res_cache:
57         res_cache[res_type] = {}
58     if key in res_cache[res_type]:
59         raise VimException("Duplicate key(%s) of %s" % (key, res_type), ERR_CODE)
60     res_cache[res_type][key] = val
61
62
63 def get_res_id(res_cache, res_type, key):
64     if res_type not in res_cache:
65         raise VimException("%s not found in cache" % res_type, ERR_CODE)
66     if key not in res_cache[res_type]:
67         raise VimException("%s(%s) not found in cache" % (res_type, key), ERR_CODE)
68     return res_cache[res_type][key]
69
70
71 def action_vm(action_type, server, vimId, tenantId):
72     param = {}
73     if action_type == ACTION_TYPE.START:
74         param = {
75             "os-start": None,
76         }
77     elif action_type == ACTION_TYPE.STOP:
78         param = {
79             "os-stop": None,
80         }
81     elif action_type == ACTION_TYPE.REBOOT:
82         param = {
83             "reboot": {}
84         }
85         if server["status"] == "ACTIVE":
86             param["reboot"]["type"] = "SOFT"
87         else:
88             param["reboot"]["type"] = "HARD"
89     res_id = server["id"]
90     logger.debug("%s,%s,%s,%s", vimId, tenantId, res_id, param)
91     api.action_vm(vimId, tenantId, res_id, param)
92
93
94 # TODO Have to check if the resources should be started and stopped in some order.
95 def operate_vim_res(data, changeStateTo, stopType, gracefulStopTimeout, do_notify_op):
96     for res in ignore_case_get(data, "vm"):
97         try:
98             if changeStateTo == "STARTED":
99                 action_vm(ACTION_TYPE.START, res, res["vim_id"], res["tenant_id"])
100                 do_notify_op("ACTIVE", res["id"])
101             elif changeStateTo == "STOPPED":
102                 if stopType == "GRACEFUL":
103                     if gracefulStopTimeout > 60:
104                         gracefulStopTimeout = 60
105                     time.sleep(gracefulStopTimeout)
106                 action_vm(ACTION_TYPE.STOP, res, res["vim_id"], res["tenant_id"])
107                 do_notify_op("INACTIVE", res["id"])
108         except VimException as e:
109             logger.error("Failed to Operate %s(%s)", RES_VM, res["res_id"])
110             logger.error("%s:%s", e.http_code, e.args[0])
111             raise NFLCMException("Failed to Operate %s(%s)", RES_VM, res["res_id"])
112
113
114 def heal_vim_res(vdus, vnfd_info, do_notify, data, vim_cache, res_cache):
115     try:
116         vimid = data["vimid"]
117         tenant = data["tenant"]
118         actionType = data["action"]
119         resid = ''
120         if actionType == HEAL_ACTION_TYPE.START:
121             resid = vdus[0]["vdu_id"]
122             create_vm(vim_cache, res_cache, vnfd_info, vdus[0], do_notify, RES_VM)
123         elif actionType == HEAL_ACTION_TYPE.RESTART:
124             resid = vdus[0].resourceid
125             logger.debug("Start restart vm(%s)", resid)
126             vm_info = api.get_vm(vimid, tenant, vdus[0].resourceid)
127             logger.debug("vminfo=%s", vm_info)
128             action_vm(ACTION_TYPE.REBOOT, vm_info, vimid, tenant)
129     except VimException as e:
130         logger.error("Failed to Heal %s(%s)", RES_VM, resid)
131         logger.error("%s:%s", e.http_code, e.args[0])
132         raise NFLCMException("Failed to Heal %s(%s)" % (RES_VM, resid))
133
134
135 def create_vim_res(data, do_notify, vim_cache={}, res_cache={}):
136     for vol in ignore_case_get(data, "volume_storages"):
137         create_volume(vim_cache, res_cache, vol, do_notify, RES_VOLUME)
138     for network in ignore_case_get(data, "vls"):
139         create_network(vim_cache, res_cache, network, do_notify, RES_NETWORK)
140     for subnet in ignore_case_get(data, "vls"):
141         create_subnet(vim_cache, res_cache, subnet, do_notify, RES_SUBNET)
142     for port in ignore_case_get(data, "cps"):
143         create_port(vim_cache, res_cache, data, port, do_notify, RES_PORT)
144     for vdu in ignore_case_get(data, "vdus"):
145         if vdu["type"] == "tosca.nodes.nfv.Vdu.Compute":
146             create_flavor(vim_cache, res_cache, data, vdu, do_notify, RES_FLAVOR)
147     for vdu in ignore_case_get(data, "vdus"):
148         if vdu["type"] == "tosca.nodes.nfv.Vdu.Compute":
149             create_vm(vim_cache, res_cache, data, vdu, do_notify, RES_VM)
150
151
152 def delete_vim_res(data, do_notify):
153     res_types = [RES_VM, RES_FLAVOR, RES_PORT, RES_SUBNET, RES_NETWORK, RES_VOLUME]
154     res_del_funs = [api.delete_vm, api.delete_flavor, api.delete_port,
155                     api.delete_subnet, api.delete_network, api.delete_volume]
156     for res_type, res_del_fun in zip(res_types, res_del_funs):
157         for res in ignore_case_get(data, res_type):
158             try:
159                 if NOT_PREDEFINED == res["is_predefined"]:
160                     res_del_fun(res["vim_id"], res["tenant_id"], res["res_id"])
161             except VimException as e:
162                 logger.error("Failed to delete %s(%s)", res_type, res["res_id"])
163                 logger.error("%s:%s", e.http_code, e.args[0])
164             do_notify(res_type, res["res_id"])
165
166
167 def create_volume(vim_cache, res_cache, vol, do_notify, res_type):
168     location_info = vol["properties"]["location_info"]
169     param = {
170         "name": vol["properties"]["volume_name"] if vol["properties"].get("volume_name", None) else vol["volume_storage_id"],
171         "volumeSize": int(ignore_case_get(vol["properties"], "size_of_storage", "0").replace('GB', '').replace('"', '').strip())
172     }
173     set_opt_val(param, "imageName", ignore_case_get(vol, "image_file"))
174     set_opt_val(param, "volumeType", ignore_case_get(vol["properties"], "type_of_storage"))
175     set_opt_val(param, "availabilityZone", ignore_case_get(location_info, "availability_zone"))
176     vim_id, tenant_name = location_info["vimid"], location_info["tenant"]
177     tenant_id = get_tenant_id(vim_cache, vim_id, tenant_name)
178     ret = api.create_volume(vim_id, tenant_id, param)
179     ret["nodeId"] = vol["volume_storage_id"]
180     do_notify(res_type, ret)
181     vol_id, vol_name = ret["id"], ret["name"]
182     set_res_cache(res_cache, res_type, vol["volume_storage_id"], vol_id)
183     retry_count, max_retry_count = 0, 300
184     while retry_count < max_retry_count:
185         vol_info = api.get_volume(vim_id, tenant_id, vol_id)
186         if vol_info["status"].upper() == "AVAILABLE":
187             logger.debug("Volume(%s) is available", vol_id)
188             return
189         time.sleep(2)
190         retry_count = retry_count + 1
191     raise VimException("Failed to create Volume(%s): Timeout." % vol_name, ERR_CODE)
192
193
194 def create_network(vim_cache, res_cache, network, do_notify, res_type):
195     location_info = network["properties"]["location_info"]
196     vl_profile = network["properties"]["vl_profile"]
197     param = {
198         "name": vl_profile["networkName"],
199         "shared": False,
200         "networkType": ignore_case_get(vl_profile, "networkType"),
201         "physicalNetwork": ignore_case_get(vl_profile, "physicalNetwork")
202     }
203     set_opt_val(param, "vlanTransparent", ignore_case_get(vl_profile, "vlanTransparent"))
204     set_opt_val(param, "segmentationId", int(ignore_case_get(vl_profile, "segmentationId", "0")))
205     set_opt_val(param, "routerExternal", ignore_case_get(network, "route_external"))
206     vim_id, tenant_name = location_info["vimid"], location_info["tenant"]
207     tenant_id = get_tenant_id(vim_cache, vim_id, tenant_name)
208     ret = api.create_network(vim_id, tenant_id, param)
209     ret["nodeId"] = network["vl_id"]
210     do_notify(res_type, ret)
211     set_res_cache(res_cache, res_type, network["vl_id"], ret["id"])
212
213
214 def create_subnet(vim_cache, res_cache, subnet, do_notify, res_type):
215     location_info = subnet["properties"]["location_info"]
216     network_id = get_res_id(res_cache, RES_NETWORK, subnet["vl_id"])
217     vl_profile = subnet["properties"]["vl_profile"]
218     layer_protocol = ignore_case_get(subnet["properties"]["connectivity_type"], "layer_protocol")
219     param = {
220         "networkId": network_id,
221         "name": vl_profile["networkName"] + "_subnet",
222         "cidr": ignore_case_get(vl_profile, "cidr"),
223         "ipVersion": IP_V4 if(layer_protocol == 'ipv4') else (IP_V6 if(layer_protocol == 'ipv6') else None)
224     }
225     set_opt_val(param, "enableDhcp", ignore_case_get(vl_profile, "dhcpEnabled"))
226     set_opt_val(param, "gatewayIp", ignore_case_get(vl_profile, "gatewayIp"))
227     set_opt_val(param, "dnsNameservers", ignore_case_get(subnet["properties"], "dns_nameservers"))
228     allocation_pool = {}
229     set_opt_val(allocation_pool, "start", ignore_case_get(vl_profile, "startIp"))
230     set_opt_val(allocation_pool, "end", ignore_case_get(vl_profile, "endIp"))
231     if allocation_pool:
232         param["allocationPools"] = [allocation_pool]
233     set_opt_val(param, "hostRoutes", ignore_case_get(subnet["properties"], "host_routes"))
234     vim_id, tenant_name = location_info["vimid"], location_info["tenant"]
235     tenant_id = get_tenant_id(vim_cache, vim_id, tenant_name)
236     ret = api.create_subnet(vim_id, tenant_id, param)
237     do_notify(res_type, ret)
238     set_res_cache(res_cache, res_type, subnet["vl_id"], ret["id"])
239
240
241 def create_port(vim_cache, res_cache, data, port, do_notify, res_type):
242     location_info = None
243     port_ref_vdu_id = ignore_case_get(port, "vdu_id")
244     for vdu in ignore_case_get(data, "vdus"):
245         if vdu["vdu_id"] == port_ref_vdu_id:
246             location_info = vdu["properties"]["location_info"]
247             if port["cp_id"] not in vdu["cps"]:
248                 vdu["cps"].append(port["cp_id"])
249             break
250     if not location_info:
251         err_msg = "vdu_id(%s) for cp(%s) is not defined."
252         raise VimException(err_msg % (port_ref_vdu_id, port["cp_id"]), ERR_CODE)
253     network_id = ignore_case_get(port, "networkId")
254     subnet_id = ignore_case_get(port, "subnetId")
255
256     if not network_id:
257         if port["vl_id"] == "":
258             return
259         network_id = get_res_id(res_cache, RES_NETWORK, port["vl_id"])
260         subnet_id = get_res_id(res_cache, RES_SUBNET, port["vl_id"])
261     param = {
262         "networkId": network_id,
263         "name": port["cp_id"]
264     }
265     set_opt_val(param, "subnetId", subnet_id)
266     set_opt_val(param, "macAddress", ignore_case_get(port["properties"], "mac_address"))
267     ip_address = []
268     logger.debug("port['properties']:%s" % port["properties"])
269     for one_protocol_data in port["properties"]["protocol_data"]:
270         l3_address_data = one_protocol_data["address_data"]["l3_address_data"]  # l3 is not 13
271         fixed_ip_address = ignore_case_get(l3_address_data, "fixed_ip_address")
272         ip_address.extend(fixed_ip_address)
273     for one_virtual_network_interface in port["properties"].get("virtual_network_interface_requirements", []):
274         network_interface_requirements = one_virtual_network_interface["network_interface_requirements"]
275         interfaceTypeString = ignore_case_get(network_interface_requirements, "interfaceType")
276         interfaceType = ""
277         if interfaceTypeString != "":
278             interfaceType = json.loads(interfaceTypeString)["configurationValue"]
279         vnic_type = ignore_case_get(port["properties"], "vnic_type")
280         if vnic_type == "":
281             if interfaceType == "SR-IOV":
282                 set_opt_val(param, "vnicType", "direct")
283         else:
284             set_opt_val(param, "vnicType", vnic_type)
285
286     set_opt_val(param, "ip", ",".join(ip_address))
287     set_opt_val(param, "securityGroups", "")   # TODO
288     vim_id, tenant_name = location_info["vimid"], location_info["tenant"]
289     tenant_id = get_tenant_id(vim_cache, vim_id, tenant_name)
290     ret = api.create_port(vim_id, tenant_id, param)
291     ret["nodeId"] = port["cp_id"]
292     do_notify(res_type, ret)
293     set_res_cache(res_cache, res_type, port["cp_id"], ret["id"])
294
295
296 def create_flavor(vim_cache, res_cache, data, flavor, do_notify, res_type):
297     location_info = flavor["properties"]["location_info"]
298     vim_id, tenant_name = location_info["vimid"], location_info["tenant"]
299     virtual_compute = flavor["virtual_compute"]
300     virtual_storages = ignore_case_get(flavor, "virtual_storages")
301     virtual_cpu = ignore_case_get(virtual_compute, "virtual_cpu")
302     virtual_memory = ignore_case_get(virtual_compute, "virtual_memory")
303     param = {
304         "name": "Flavor_%s" % flavor["vdu_id"],
305         "vcpu": int(ignore_case_get(virtual_cpu, "num_virtual_cpu")),
306         "memory": int(ignore_case_get(virtual_memory, "virtual_mem_size").replace('MB', '').strip()),
307         "isPublic": True
308     }
309
310     # Get flavor id from OOF
311     vdu_id = ignore_case_get(flavor, "vdu_id", "")
312     flavor_id = ""
313     for one_vdu in location_info["vduInfo"]:
314         if one_vdu["vduName"] == vdu_id:
315             flavor_id = ignore_case_get(one_vdu, "flavorId", "")
316             break
317
318     # Add check if OOF return flavor id has value
319     # If value is not None, we use it.
320     # If value is None, we will create flavor again.
321     if flavor_id:
322         set_res_cache(res_cache, res_type, flavor["vdu_id"], flavor_id)
323     else:
324         if virtual_storages:
325             for virtual_storage in virtual_storages:
326                 vs_id = virtual_storage["virtual_storage_id"]
327                 for vs in data["volume_storages"]:
328                     if vs["volume_storage_id"] == vs_id:
329                         disk_type = ignore_case_get(vs["properties"], "type_of_storage")
330                         size_of_storage = ignore_case_get(vs["properties"], "size_of_storage")
331                         disk_size = int(size_of_storage.replace('GB', '').replace('"', '').strip())
332                         if disk_type == "root":
333                             param["disk"] = disk_size
334                         elif disk_type == "ephemeral":
335                             param["ephemeral"] = disk_size
336                         elif disk_type == "swap":
337                             param["swap"] = disk_size
338         else:
339             virtual_storages = ignore_case_get(virtual_compute, "virtual_storages")
340             size_of_storage = ignore_case_get(virtual_storages[0], "size_of_storage")
341             disk_size = int(size_of_storage.replace('GB', '').replace('"', '').strip())
342             param["disk"] = disk_size
343
344         tenant_id = get_tenant_id(vim_cache, vim_id, tenant_name)
345         logger.debug("param:%s" % param)
346         ret = api.create_flavor(vim_id, tenant_id, param)
347         logger.debug("hhb ret:%s" % ret)
348         do_notify(res_type, ret)
349         set_res_cache(res_cache, res_type, flavor["vdu_id"], ret["id"])
350
351
352 def create_vm(vim_cache, res_cache, data, vm, do_notify, res_type):
353     location_info = vm["properties"]["location_info"]
354     vim_id, tenant_name = location_info["vimid"], location_info["tenant"]
355     tenant_id = get_tenant_id(vim_cache, vim_id, tenant_name)
356     param = {
357         "name": vm["properties"].get("name", "undefined"),
358         "flavorId": get_res_id(res_cache, RES_FLAVOR, vm["vdu_id"]),
359         "boot": {},
360         "nicArray": [],
361         "contextArray": [],
362         "volumeArray": []
363     }
364     # set boot param
365     if "artifacts" in vm and vm["artifacts"]:
366         param["boot"]["type"] = BOOT_FROM_IMAGE
367         img_name = ""
368         for artifact in vm["artifacts"]:
369             if artifact["artifact_name"] == "sw_image":
370                 # TODO: after DM define
371                 img_name = os.path.basename(artifact["file"])
372                 break
373         if not img_name:
374             raise VimException("Undefined image(%s)" % vm["artifacts"], ERR_CODE)
375         images = api.list_image(vim_id, tenant_id)
376         for image in images["images"]:
377             if img_name == image["name"]:
378                 param["boot"]["imageId"] = image["id"]
379                 break
380         if "imageId" not in param["boot"]:
381             raise VimException("Undefined artifacts image(%s)" % vm["artifacts"], ERR_CODE)
382     elif vm["virtual_storages"]:
383         param["boot"]["type"] = BOOT_FROM_VOLUME
384         vol_id = vm["virtual_storages"][0]["virtual_storage_id"]
385         param["boot"]["volumeId"] = get_res_id(res_cache, RES_VOLUME, vol_id)
386     else:
387         raise VimException("No image and volume defined", ERR_CODE)
388
389     for cp_id in ignore_case_get(vm, "cps"):
390         param["nicArray"].append({
391             "portId": get_res_id(res_cache, RES_PORT, cp_id)
392         })
393     param["contextArray"] = ignore_case_get(vm["properties"], "inject_files")
394     logger.debug("contextArray:%s", param["contextArray"])
395     for vol_data in ignore_case_get(vm, "volume_storages"):
396         vol_id = vol_data["volume_storage_id"]
397         param["volumeArray"].append({
398             "volumeId": get_res_id(res_cache, RES_VOLUME, vol_id)
399         })
400
401     user_data = base64.b64encode(bytes(ignore_case_get(vm["properties"], "user_data"), "utf-8")).decode("utf-8")
402     set_opt_val(param, "availabilityZone", ignore_case_get(location_info, "availability_zone"))
403     set_opt_val(param, "userdata", user_data)
404     set_opt_val(param, "metadata", ignore_case_get(vm["properties"], "meta_data"))
405     set_opt_val(param, "securityGroups", "")   # TODO List of names of security group
406     set_opt_val(param, "serverGroup", "")      # TODO the ServerGroup for anti-affinity and affinity
407
408     ret = api.create_vm(vim_id, tenant_id, param)
409     ret["ports"] = [nic.get("portId") for nic in param["nicArray"]]
410     ret["vimId"] = vim_id
411     ret["tenantId"] = tenant_id
412     do_notify(res_type, ret)
413     vm_id = ret["id"]
414     if ignore_case_get(ret, "name"):
415         vm_name = vm["properties"].get("name", "undefined")
416         logger.debug("vm_name:%s" % vm_name)
417     opt_vm_status = "Timeout"
418     retry_count, max_retry_count = 0, 100
419     while retry_count < max_retry_count:
420         vm_info = api.get_vm(vim_id, tenant_id, vm_id)
421         if vm_info["status"].upper() == "ACTIVE":
422             logger.debug("Vm(%s) is active", vm_id)
423             return
424         if vm_info["status"].upper() == "ERROR":
425             opt_vm_status = vm_info["status"]
426             break
427         time.sleep(2)
428         retry_count = retry_count + 1
429     raise VimException("Failed to create Vm(%s): %s." % (vm_name, opt_vm_status), ERR_CODE)
430
431
432 def list_port_of_vm(vim_cache, res_cache, data, port, do_notify, res_type):
433     location_info = None
434     vm_id = ignore_case_get(port, "vm_id")
435     port_ref_vdu_id = ignore_case_get(port, "vdu_id")
436     for vdu in ignore_case_get(data, "vdus"):
437         if vdu["vdu_id"] == port_ref_vdu_id:
438             location_info = vdu["properties"]["location_info"]
439             if port["cp_id"] not in vdu["cps"]:
440                 vdu["cps"].append(port["cp_id"])
441             break
442     if not location_info:
443         err_msg = "vdu_id(%s) for cp(%s) is not defined."
444         raise VimException(err_msg % (port_ref_vdu_id, port["cp_id"]), ERR_CODE)
445
446     vim_id, tenant_name = location_info["vimid"], location_info["tenant"]
447     tenant_id = get_tenant_id(vim_cache, vim_id, tenant_name)
448     ret = api.list_vm_port(vim_id, tenant_id, vm_id)
449     ret["nodeId"] = port["cp_id"]
450     do_notify(res_type, ret)
451     set_res_cache(res_cache, res_type, port["cp_id"], ret["id"])
452
453     return ret
454
455
456 def get_port_of_vm(vim_cache, res_cache, data, port, do_notify, res_type):
457     location_info = None
458     vm_id = ignore_case_get(port, "vm_id")
459     port_id = ignore_case_get(port, "cp_id")
460     port_ref_vdu_id = ignore_case_get(port, "vdu_id")
461     for vdu in ignore_case_get(data, "vdus"):
462         if vdu["vdu_id"] == port_ref_vdu_id:
463             location_info = vdu["properties"]["location_info"]
464             if port["cp_id"] not in vdu["cps"]:
465                 vdu["cps"].append(port["cp_id"])
466             break
467     if not location_info:
468         err_msg = "vdu_id(%s) for cp(%s) is not defined."
469         raise VimException(err_msg % (port_ref_vdu_id, port["cp_id"]), ERR_CODE)
470
471     vim_id, tenant_name = location_info["vimid"], location_info["tenant"]
472     tenant_id = get_tenant_id(vim_cache, vim_id, tenant_name)
473     ret = api.get_vm_port(vim_id, tenant_id, vm_id, port_id)
474     ret["nodeId"] = port["cp_id"]
475     do_notify(res_type, ret)
476     set_res_cache(res_cache, res_type, port["cp_id"], ret["id"])
477
478     return ret
479
480
481 def create_port_of_vm(vim_cache, res_cache, data, port, do_notify, res_type):
482     location_info = None
483     vm_id = ignore_case_get(port, "vm_id")
484     port_id = ignore_case_get(port, "port_id")
485     port_ref_vdu_id = ignore_case_get(port, "vdu_id")
486     for vdu in ignore_case_get(data, "vdus"):
487         if vdu["vdu_id"] == port_ref_vdu_id:
488             location_info = vdu["properties"]["location_info"]
489             if port["cp_id"] not in vdu["cps"]:
490                 vdu["cps"].append(port["cp_id"])
491             break
492     if not location_info:
493         err_msg = "vdu_id(%s) for cp(%s) is not defined."
494         raise VimException(err_msg % (port_ref_vdu_id, port["cp_id"]), ERR_CODE)
495     network_id = ignore_case_get(port, "networkId")
496     # subnet_id = ignore_case_get(port, "subnetId")
497     if not network_id:
498         network_id = get_res_id(res_cache, RES_NETWORK, port["vl_id"])
499     #    subnet_id = get_res_id(res_cache, RES_SUBNET, port["vl_id"])
500     # param = {
501     #     "networkId": network_id,
502     #     "name": port["cp_id"]
503     # }
504     # set_opt_val(param, "subnetId", subnet_id)
505     # set_opt_val(param, "macAddress", ignore_case_get(port["properties"], "mac_address"))
506     # ip_address = []
507     # for one_protocol_data in port["properties"]["protocol_data"]:
508     #     l3_address_data = one_protocol_data["address_data"]["l3_address_data"]  # l3 is not 13
509     #     fixed_ip_address = ignore_case_get(l3_address_data, "fixed_ip_address")
510     #     ip_address.extend(fixed_ip_address)
511     # for one_virtual_network_interface in port["properties"].get("virtual_network_interface_requirements", []):
512     #     interfaceTypeString = one_virtual_network_interface["network_interface_requirements"]["interfaceType"]
513     #     interfaceType = json.loads(interfaceTypeString)["configurationValue"]
514     #     vnic_type = ignore_case_get(port["properties"], "vnic_type")
515     #     if vnic_type == "":
516     #         if interfaceType == "SR-IOV":
517     #             set_opt_val(param, "vnicType", "direct")
518     #     else:
519     #         set_opt_val(param, "vnicType", vnic_type)
520     #
521     # set_opt_val(param, "ip", ",".join(ip_address))
522     # set_opt_val(param, "securityGroups", "")  # TODO
523     vim_id, tenant_name = location_info["vimid"], location_info["tenant"]
524     tenant_id = get_tenant_id(vim_cache, vim_id, tenant_name)
525
526     # ip_address = ignore_case_get(ignore_case_get(port, "properties"), "ip_address")
527     param = {
528         "interfaceAttachment": {
529             "port_id": port_id
530         }
531     }
532     ret = api.create_vm_port(vim_id, tenant_id, vm_id, param)
533     ret["nodeId"] = port["cp_id"]
534     do_notify("create", res_type, ret)
535
536
537 def delete_port_of_vm(vim_cache, res_cache, data, port, do_notify, res_type):
538     location_info = None
539     vm_id = ignore_case_get(port, "vm_id")
540     port_id = ignore_case_get(port, "cp_id")
541     port_ref_vdu_id = ignore_case_get(port, "vdu_id")
542     for vdu in ignore_case_get(data, "vdus"):
543         if vdu["vdu_id"] == port_ref_vdu_id:
544             location_info = vdu["properties"]["location_info"]
545             if port["cp_id"] not in vdu["cps"]:
546                 vdu["cps"].append(port["cp_id"])
547             break
548     if not location_info:
549         err_msg = "vdu_id(%s) for cp(%s) is not defined."
550         raise VimException(err_msg % (port_ref_vdu_id, port["cp_id"]), ERR_CODE)
551
552     vim_id, tenant_name = location_info["vimid"], location_info["tenant"]
553     tenant_id = get_tenant_id(vim_cache, vim_id, tenant_name)
554     ret = api.delete_vm_port(vim_id, tenant_id, vm_id, port_id)
555     ret["nodeId"] = port["cp_id"]
556     do_notify("delete", res_type, port_id)
557     set_res_cache(res_cache, res_type, port["cp_id"], ret["id"])