1c01adaf86bdf4575d6586936a08c5f2b6da4452
[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 from threading import Thread
19
20 from lcm.pub.database.models import NfInstModel, VmInstModel
21 from lcm.pub.exceptions import NFLCMException
22 from lcm.pub.msapi.gvnfmdriver import prepare_notification_data
23 # from lcm.pub.msapi.gvnfmdriver import notify_lcm_to_nfvo
24 from lcm.pub.utils.jobutil import JobUtil
25 from lcm.pub.utils.timeutil import now_time
26 from lcm.pub.utils.notificationsutil import NotificationsUtil
27 from lcm.pub.utils.values import ignore_case_get
28 from lcm.pub.vimapi import adaptor
29 from lcm.nf.biz.grant_vnf import grant_resource
30 from lcm.nf.const import VNF_STATUS, RESOURCE_MAP, CHANGE_TYPE, GRANT_TYPE, OPERATION_TYPE
31
32 logger = logging.getLogger(__name__)
33
34
35 class OperateVnf(Thread):
36     def __init__(self, data, nf_inst_id, job_id):
37         super(OperateVnf, self).__init__()
38         self.data = data
39         self.nf_inst_id = nf_inst_id
40         self.job_id = job_id
41         self.grant_type = GRANT_TYPE.OPERATE
42         self.changeStateTo = ignore_case_get(self.data, "changeStateTo")
43         self.stopType = ignore_case_get(self.data, "stopType")
44         self.gracefulStopTimeout = ignore_case_get(self.data, "gracefulStopTimeout")
45         self.inst_resource = {'vm': []}
46
47     def run(self):
48         try:
49             self.apply_grant()
50             self.query_inst_resource()
51             self.operate_resource()
52             JobUtil.add_job_status(self.job_id, 100, "Operate Vnf success.")
53             NfInstModel.objects.filter(nfinstid=self.nf_inst_id).update(status='INSTANTIATED', lastuptime=now_time(), operationState=self.changeStateTo)
54             self.lcm_notify()
55         except NFLCMException as e:
56             self.vnf_operate_failed_handle(e.message)
57         except Exception as e:
58             logger.error(e.message)
59             self.vnf_operate_failed_handle(traceback.format_exc())
60
61     def apply_grant(self):
62         vdus = VmInstModel.objects.filter(instid=self.nf_inst_id, is_predefined=1)
63         apply_result = grant_resource(data=self.data, nf_inst_id=self.nf_inst_id, job_id=self.job_id,
64                                       grant_type=self.grant_type, vdus=vdus)
65         logger.info("Grant resource, response: %s" % apply_result)
66         JobUtil.add_job_status(self.job_id, 20, 'Nf Operate grant_resource finish')
67
68     def query_inst_resource(self):
69         logger.info('Query resource begin')
70         # Querying only vm resources now
71         resource_type = "Vm"
72         resource_table = globals().get(resource_type + 'InstModel')
73         resource_insts = resource_table.objects.filter(instid=self.nf_inst_id)
74         for resource_inst in resource_insts:
75             if not resource_inst.resourceid:
76                 continue
77             self.inst_resource[RESOURCE_MAP.get(resource_type)].append(self.get_resource(resource_inst))
78         logger.info('Query resource end, resource=%s' % self.inst_resource)
79
80     def get_resource(self, resource):
81         return {
82             "vim_id": resource.vimid,
83             "tenant_id": resource.tenant,
84             "id": resource.resourceid
85         }
86
87     def operate_resource(self):
88         logger.info('Operate resource begin')
89         adaptor.operate_vim_res(self.inst_resource, self.changeStateTo, self.stopType, self.gracefulStopTimeout, self.do_notify_op)
90         logger.info('Operate resource complete')
91
92     def lcm_notify(self):
93         notification_content = prepare_notification_data(self.nf_inst_id, self.job_id, CHANGE_TYPE.MODIFIED, OPERATION_TYPE.OPERATE)
94         logger.info('Notify request data = %s' % notification_content)
95         # resp = notify_lcm_to_nfvo(json.dumps(notification_content))
96         # logger.info('Lcm notify end, response %s' % resp)
97         NotificationsUtil().send_notification(notification_content)
98
99     def vnf_operate_failed_handle(self, error_msg):
100         logger.error('VNF Operation failed, detail message: %s' % error_msg)
101         NfInstModel.objects.filter(nfinstid=self.nf_inst_id).update(status=VNF_STATUS.FAILED, lastuptime=now_time())
102         JobUtil.add_job_status(self.job_id, 255, error_msg)
103
104     def do_notify_op(self, status, resid):
105         logger.error('VNF resource %s updated to: %s' % (resid, status))
106         VmInstModel.objects.filter(instid=self.nf_inst_id, resourceid=resid).update(operationalstate=status)