1 # Copyright (C) 2018 Verizon. All Rights Reserved.
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
7 # http://www.apache.org/licenses/LICENSE-2.0
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.
19 from threading import Thread
21 from lcm.pub.database.models import NfInstModel
22 from lcm.pub.database.models import VmInstModel
23 from lcm.pub.database.models import VNFCInstModel
24 from lcm.pub.exceptions import NFLCMException
25 from lcm.pub.utils.jobutil import JobUtil
26 from lcm.pub.utils.timeutil import now_time
27 from lcm.pub.utils.notificationsutil import NotificationsUtil
28 from lcm.pub.utils.values import ignore_case_get
29 from lcm.pub.vimapi import adaptor
30 from lcm.nf.biz.grant_vnf import grant_resource
31 from lcm.nf.const import RESOURCE_MAP
32 from lcm.nf.const import GRANT_TYPE
33 from lcm.nf.const import OPERATION_STATE_TYPE
34 from lcm.nf.const import LCM_NOTIFICATION_STATUS
35 from lcm.nf.const import CHANGE_TYPE
36 from lcm.nf.const import OPERATION_TYPE
37 from lcm.nf.const import OPERATION_TASK
38 from .operate_vnf_lcm_op_occ import VnfLcmOpOcc
40 logger = logging.getLogger(__name__)
43 class OperateVnf(Thread):
44 def __init__(self, data, nf_inst_id, job_id):
45 super(OperateVnf, self).__init__()
47 self.nf_inst_id = nf_inst_id
49 self.grant_type = GRANT_TYPE.OPERATE
50 self.changeStateTo = ignore_case_get(self.data, "changeStateTo")
51 self.stopType = ignore_case_get(self.data, "stopType")
52 self.gracefulStopTimeout = ignore_case_get(self.data, "gracefulStopTimeout")
53 self.inst_resource = {'vm': []}
54 self.lcm_op_occ = VnfLcmOpOcc(
55 vnf_inst_id=nf_inst_id,
57 operation=OPERATION_TYPE.OPERATE,
58 task=OPERATION_TASK.OPERATE
63 self.lcm_op_occ.notify_lcm(OPERATION_STATE_TYPE.STARTING)
65 self.query_inst_resource()
66 self.lcm_op_occ.notify_lcm(OPERATION_STATE_TYPE.PROCESSING)
67 self.operate_resource()
68 JobUtil.add_job_status(self.job_id, 100, "Operate Vnf success.")
69 NfInstModel.objects.filter(nfinstid=self.nf_inst_id).update(
70 status='INSTANTIATED',
74 LCM_NOTIFICATION_STATUS.RESULT,
75 OPERATION_STATE_TYPE.COMPLETED
77 except NFLCMException as e:
78 self.vnf_operate_failed_handle(e.args[0])
79 except Exception as e:
80 logger.error(e.args[0])
81 logger.error(traceback.format_exc())
82 self.vnf_operate_failed_handle(e.args[0])
84 def apply_grant(self):
85 vdus = VmInstModel.objects.filter(instid=self.nf_inst_id)
86 apply_result = grant_resource(data=self.data,
87 nf_inst_id=self.nf_inst_id,
89 grant_type=self.grant_type,
91 logger.info("Grant resource, response: %s" % apply_result)
92 JobUtil.add_job_status(self.job_id, 20, 'Nf Operate grant_resource finish')
94 def query_inst_resource(self):
95 logger.info('Query resource begin')
96 # Querying only vm resources now
98 resource_table = globals().get(resource_type + 'InstModel')
99 resource_insts = resource_table.objects.filter(instid=self.nf_inst_id)
100 for resource_inst in resource_insts:
101 if not resource_inst.resourceid:
103 self.inst_resource[RESOURCE_MAP.get(resource_type)].append(self.get_resource(resource_inst))
104 logger.info('Query resource end, resource=%s' % self.inst_resource)
106 def get_resource(self, resource):
108 "vim_id": resource.vimid,
109 "tenant_id": resource.tenant,
110 "id": resource.resourceid
113 def operate_resource(self):
114 logger.info('Operate resource begin')
115 adaptor.operate_vim_res(self.inst_resource,
118 self.gracefulStopTimeout,
120 logger.info('Operate resource complete')
122 def lcm_notify(self, status, opState, err=None):
123 notification_content = self.prepareNotificationData(status, opState, err)
124 logger.info('Notify data = %s' % notification_content)
125 NotificationsUtil().send_notification(notification_content)
126 logger.info('Notify end')
128 def vnf_operate_failed_handle(self, error_msg):
129 logger.error('VNF Operation failed, detail message: %s' % error_msg)
130 NfInstModel.objects.filter(nfinstid=self.nf_inst_id).update(
131 # status=VNF_STATUS.FAILED,
132 lastuptime=now_time()
134 self.lcm_op_occ.notify_lcm(OPERATION_STATE_TYPE.FAILED, error_msg)
135 JobUtil.add_job_status(self.job_id, 255, error_msg)
137 def do_notify_op(self, status, resid):
138 logger.error('VNF resource %s updated to: %s' % (resid, status))
140 def prepareNotificationData(self, status, opState, err=None):
142 if status == LCM_NOTIFICATION_STATUS.RESULT and opState == OPERATION_STATE_TYPE.COMPLETED:
143 vnfcs = VNFCInstModel.objects.filter(instid=self.nf_inst_id)
147 vm = VmInstModel.objects.filter(vmid=vnfc.vmid)
150 'vimConnectionId': vm[0].vimid,
151 'resourceId': vm[0].resourceid,
152 'vimLevelResourceType': 'vm'
154 affected_vnfcs.append({
155 'id': vnfc.vnfcinstanceid,
157 'changeType': CHANGE_TYPE.MODIFIED,
158 'computeResource': vm_resource
160 notification_content = {
161 "id": str(uuid.uuid4()),
162 "notificationType": "VnfLcmOperationOccurrenceNotification",
163 "subscriptionId": "",
164 "timeStamp": now_time(),
165 "notificationStatus": status,
166 "operationState": opState,
167 "vnfInstanceId": self.nf_inst_id,
168 "operation": OPERATION_TYPE.OPERATE,
169 "isAutomaticInvocation": "false",
170 "vnfLcmOpOccId": self.job_id,
171 "affectedVnfcs": affected_vnfcs,
172 "affectedVirtualLinks": [],
173 "affectedVirtualStorages": [],
175 "changedExtConnectivity": [],
176 "_links": {"vnfInstance": {"href": ""},
177 "subscription": {"href": ""},
178 "vnfLcmOpOcc": {"href": ""}}
180 if opState in (OPERATION_STATE_TYPE.FAILED, OPERATION_STATE_TYPE.FAILED_TEMP):
181 notification_content["error"] = {"status": 500, "detail": err}
182 notification_content["_links"]["vnfInstance"]["href"] = "/vnf_instances/%s" % self.nf_inst_id
183 notification_content["_links"]["vnfLcmOpOcc"]["href"] = "/vnf_lc_ops/%s" % self.job_id
184 return notification_content