fix vnf status update error
[vfc/gvnfm/vnflcm.git] / lcm / lcm / nf / biz / operate_vnf.py
1 # Copyright (C) 2018 Verizon. All Rights Reserved.
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 json
16 import logging
17 import traceback
18 import uuid
19 from threading import Thread
20
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
39
40 logger = logging.getLogger(__name__)
41
42
43 class OperateVnf(Thread):
44     def __init__(self, data, nf_inst_id, job_id):
45         super(OperateVnf, self).__init__()
46         self.data = data
47         self.nf_inst_id = nf_inst_id
48         self.job_id = job_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,
56             lcm_op_id=job_id,
57             operation=OPERATION_TYPE.OPERATE,
58             task=OPERATION_TASK.OPERATE
59         )
60
61     def run(self):
62         try:
63             self.lcm_op_occ.notify_lcm(OPERATION_STATE_TYPE.STARTING)
64             self.apply_grant()
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',
71                 lastuptime=now_time()
72             )
73             self.lcm_notify(
74                 LCM_NOTIFICATION_STATUS.RESULT,
75                 OPERATION_STATE_TYPE.COMPLETED
76             )
77         except NFLCMException as e:
78             self.vnf_operate_failed_handle(e.message)
79         except Exception as e:
80             logger.error(e.message)
81             logger.error(traceback.format_exc())
82             self.vnf_operate_failed_handle(e.message)
83
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,
88                                       job_id=self.job_id,
89                                       grant_type=self.grant_type,
90                                       vdus=vdus)
91         logger.info("Grant resource, response: %s" % apply_result)
92         JobUtil.add_job_status(self.job_id, 20, 'Nf Operate grant_resource finish')
93
94     def query_inst_resource(self):
95         logger.info('Query resource begin')
96         # Querying only vm resources now
97         resource_type = "Vm"
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:
102                 continue
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)
105
106     def get_resource(self, resource):
107         return {
108             "vim_id": resource.vimid,
109             "tenant_id": resource.tenant,
110             "id": resource.resourceid
111         }
112
113     def operate_resource(self):
114         logger.info('Operate resource begin')
115         adaptor.operate_vim_res(self.inst_resource,
116                                 self.changeStateTo,
117                                 self.stopType,
118                                 self.gracefulStopTimeout,
119                                 self.do_notify_op)
120         logger.info('Operate resource complete')
121
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')
127
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()
133         )
134         self.lcm_op_occ.notify_lcm(OPERATION_STATE_TYPE.FAILED, error_msg)
135         JobUtil.add_job_status(self.job_id, 255, error_msg)
136
137     def do_notify_op(self, status, resid):
138         logger.error('VNF resource %s updated to: %s' % (resid, status))
139
140     def prepareNotificationData(self, status, opState, err=None):
141         affected_vnfcs = []
142         if status == LCM_NOTIFICATION_STATUS.RESULT and opState == OPERATION_STATE_TYPE.COMPLETED:
143             vnfcs = VNFCInstModel.objects.filter(instid=self.nf_inst_id)
144             for vnfc in vnfcs:
145                 vm_resource = {}
146                 if vnfc.vmid:
147                     vm = VmInstModel.objects.filter(vmid=vnfc.vmid)
148                     if vm:
149                         vm_resource = {
150                             'vimConnectionId': vm[0].vimid,
151                             'resourceId': vm[0].resourceid,
152                             'vimLevelResourceType': 'vm'
153                         }
154                 affected_vnfcs.append({
155                     'id': vnfc.vnfcinstanceid,
156                     'vduId': vnfc.vduid,
157                     'changeType': CHANGE_TYPE.MODIFIED,
158                     'computeResource': vm_resource
159                 })
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": [],
174             "changedInfo": {},
175             "changedExtConnectivity": [],
176             "_links": {"vnfInstance": {"href": ""},
177                        "subscription": {"href": ""},
178                        "vnfLcmOpOcc": {"href": ""}}
179         }
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