diff options
-rw-r--r-- | lcm/lcm/nf/biz/grant_vnf.py | 17 | ||||
-rw-r--r-- | lcm/lcm/nf/biz/operate_vnf.py | 103 | ||||
-rw-r--r-- | lcm/lcm/nf/const.py | 3 | ||||
-rw-r--r-- | lcm/lcm/nf/serializers/operate_vnf_req.py | 36 | ||||
-rw-r--r-- | lcm/lcm/nf/serializers/response.py | 23 | ||||
-rw-r--r-- | lcm/lcm/nf/tests/test_operate_vnf.py | 242 | ||||
-rw-r--r-- | lcm/lcm/nf/urls.py | 2 | ||||
-rw-r--r-- | lcm/lcm/nf/views/operate_vnf_view.py | 88 | ||||
-rw-r--r-- | lcm/lcm/pub/database/models.py | 1 | ||||
-rw-r--r-- | lcm/lcm/pub/exceptions.py | 8 | ||||
-rw-r--r-- | lcm/lcm/pub/vimapi/adaptor.py | 45 | ||||
-rw-r--r-- | lcm/lcm/pub/vimapi/api.py | 5 |
12 files changed, 569 insertions, 4 deletions
diff --git a/lcm/lcm/nf/biz/grant_vnf.py b/lcm/lcm/nf/biz/grant_vnf.py index 1997e0c0..fe3cb530 100644 --- a/lcm/lcm/nf/biz/grant_vnf.py +++ b/lcm/lcm/nf/biz/grant_vnf.py @@ -18,16 +18,14 @@ import logging from lcm.pub.database.models import NfInstModel from lcm.pub.msapi.gvnfmdriver import apply_grant_to_nfvo from lcm.pub.utils.values import ignore_case_get +from lcm.nf.const import GRANT_TYPE logger = logging.getLogger(__name__) def grant_resource(data, nf_inst_id, job_id, grant_type, vdus): logger.info("Grant resource begin") - if grant_type == "Terminate": - lifecycleOperration = "Terminate" - elif grant_type == "Instantiate": - lifecycleOperration = "Instantiate" + lifecycleOperration = grant_type content_args = { 'vnfInstanceId': nf_inst_id, @@ -35,6 +33,7 @@ def grant_resource(data, nf_inst_id, job_id, grant_type, vdus): 'lifecycleOperation': lifecycleOperration, 'vnfLcmOpOccId': job_id, 'addResources': [], + 'updateResources': [], 'removeResources': [], 'placementConstraints': [], 'additionalParams': {} @@ -62,6 +61,16 @@ def grant_resource(data, nf_inst_id, job_id, grant_type, vdus): content_args['addResources'].append(res_def) res_index += 1 content_args['additionalParams']['vimid'] = vim_id + elif grant_type == GRANT_TYPE.OPERATE: + res_index = 1 + for vdu in vdus: + res_def = { + 'type': 'VDU', + 'resDefId': str(res_index), + 'resDesId': vdu.resouceid} + content_args['updateResources'].append(res_def) + res_index += 1 + content_args['additionalParams']['vimid'] = vdus[0].vimid vnfInsts = NfInstModel.objects.filter(nfinstid=nf_inst_id) content_args['additionalParams']['vnfmid'] = vnfInsts[0].vnfminstid diff --git a/lcm/lcm/nf/biz/operate_vnf.py b/lcm/lcm/nf/biz/operate_vnf.py new file mode 100644 index 00000000..5f6499d6 --- /dev/null +++ b/lcm/lcm/nf/biz/operate_vnf.py @@ -0,0 +1,103 @@ +# Copyright (C) 2018 Verizon. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import json +import logging +import traceback +from threading import Thread + +from lcm.pub.database.models import NfInstModel, VmInstModel +from lcm.pub.exceptions import NFLCMException +from lcm.pub.msapi.gvnfmdriver import notify_lcm_to_nfvo, prepare_notification_data +from lcm.pub.utils.jobutil import JobUtil +from lcm.pub.utils.timeutil import now_time +from lcm.pub.utils.values import ignore_case_get +from lcm.pub.vimapi import adaptor +from lcm.nf.biz.grant_vnf import grant_resource +from lcm.nf.const import VNF_STATUS, RESOURCE_MAP, GRANT_TYPE + +logger = logging.getLogger(__name__) + + +class OperateVnf(Thread): + def __init__(self, data, nf_inst_id, job_id): + super(OperateVnf, self).__init__() + self.data = data + self.nf_inst_id = nf_inst_id + self.job_id = job_id + self.grant_type = GRANT_TYPE.OPERATE + self.changeStateTo = ignore_case_get(self.data, "changeStateTo") + self.stopType = ignore_case_get(self.data, "stopType") + self.gracefulStopTimeout = ignore_case_get(self.data, "gracefulStopTimeout") + self.inst_resource = {'vm': []} + + def run(self): + try: + self.apply_grant() + self.query_inst_resource() + self.operate_resource() + JobUtil.add_job_status(self.job_id, 100, "Operate Vnf success.") + NfInstModel.objects.filter(nfinstid=self.nf_inst_id).update(status='INSTANTIATED', lastuptime=now_time(), operationState=self.changeStateTo) + self.lcm_notify() + except NFLCMException as e: + self.vnf_operate_failed_handle(e.message) + except Exception as e: + logger.error(e.message) + self.vnf_operate_failed_handle(traceback.format_exc()) + + def apply_grant(self): + vdus = VmInstModel.objects.filter(instid=self.nf_inst_id, is_predefined=1) + apply_result = grant_resource(data=self.data, nf_inst_id=self.nf_inst_id, job_id=self.job_id, + grant_type=self.grant_type, vdus=vdus) + logger.info("Grant resource, response: %s" % apply_result) + JobUtil.add_job_status(self.job_id, 20, 'Nf Operate grant_resource finish') + + def query_inst_resource(self): + logger.info('Query resource begin') + # Querying only vm resources now + resource_type = "Vm" + resource_table = globals().get(resource_type + 'InstModel') + resource_insts = resource_table.objects.filter(instid=self.nf_inst_id) + for resource_inst in resource_insts: + if not resource_inst.resouceid: + continue + self.inst_resource[RESOURCE_MAP.get(resource_type)].append(self.get_resource(resource_inst)) + logger.info('Query resource end, resource=%s' % self.inst_resource) + + def get_resource(self, resource): + return { + "vim_id": resource.vimid, + "tenant_id": resource.tenant, + "id": resource.resouceid + } + + def operate_resource(self): + logger.info('Operate resource begin') + adaptor.operate_vim_res(self.inst_resource, self.changeStateTo, self.stopType, self.gracefulStopTimeout, self.do_notify_op) + logger.info('Operate resource complete') + + def lcm_notify(self): + notification_content = prepare_notification_data(self.nf_inst_id, self.job_id, "MODIFIED") + logger.info('Notify request data = %s' % notification_content) + resp = notify_lcm_to_nfvo(json.dumps(notification_content)) + logger.info('Lcm notify end, response %s' % resp) + + def vnf_operate_failed_handle(self, error_msg): + logger.error('VNF Operation failed, detail message: %s' % error_msg) + NfInstModel.objects.filter(nfinstid=self.nf_inst_id).update(status=VNF_STATUS.FAILED, lastuptime=now_time()) + JobUtil.add_job_status(self.job_id, 255, error_msg) + + def do_notify_op(self, status, resid): + logger.error('VNF resource %s updated to: %s' % (resid, status)) + VmInstModel.objects.filter(instid=self.nf_inst_id, resouceid=resid).update(operationalstate=status) diff --git a/lcm/lcm/nf/const.py b/lcm/lcm/nf/const.py index ecbc80fd..37205c5a 100644 --- a/lcm/lcm/nf/const.py +++ b/lcm/lcm/nf/const.py @@ -15,6 +15,9 @@ import json from lcm.pub.utils.jobutil import enum +HEAL_ACTION_TYPE = enum(START="vmCreate", RESTART="vmReset") +ACTION_TYPE = enum(START=1, STOP=2, REBOOT=3) +GRANT_TYPE = enum(INSTANTIATE="Instantiate", TERMINATE="Terminate", HEAL_CREATE="Heal Create", HEAL_RESTART="Heal Restart", OPERATE="Operate") VNF_STATUS = enum(NULL='null', INSTANTIATING="instantiating", INACTIVE='inactive', ACTIVE="active", FAILED="failed", TERMINATING="terminating", SCALING="scaling", OPERATING="operating", UPDATING="updating", HEALING="healing") diff --git a/lcm/lcm/nf/serializers/operate_vnf_req.py b/lcm/lcm/nf/serializers/operate_vnf_req.py new file mode 100644 index 00000000..b40e7000 --- /dev/null +++ b/lcm/lcm/nf/serializers/operate_vnf_req.py @@ -0,0 +1,36 @@ +# Copyright (C) 2018 Verizon. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from rest_framework import serializers + + +class OperateVnfRequestSerializer(serializers.Serializer): + changeStateTo = serializers.ChoiceField( + help_text="The desired operational state (i.e. started or stopped) to change the VNF to.", + choices=["STARTED", "STOPPED"], + required=True) + stopType = serializers.ChoiceField( + help_text="It signals whether forceful or graceful stop is requested.", + choices=["FORCEFUL", "GRACEFUL"], + required=False) + gracefulStopTimeout = serializers.IntegerField( + help_text="The time interval to wait for the VNF to be taken out of service during graceful stop.", + required=False) + additionalParams = serializers.DictField( + help_text="Additional input parameters for the operate process, \ + specific to the VNF being operated, \ + as declared in the VNFD as part of OperateVnfOpConfig.", + child=serializers.CharField(help_text="KeyValue Pairs", allow_blank=True), + required=False, + allow_null=True) diff --git a/lcm/lcm/nf/serializers/response.py b/lcm/lcm/nf/serializers/response.py new file mode 100644 index 00000000..81f5ed54 --- /dev/null +++ b/lcm/lcm/nf/serializers/response.py @@ -0,0 +1,23 @@ +# Copyright (C) 2018 Verizon. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from rest_framework import serializers + + +class ProblemDetailsSerializer(serializers.Serializer): + type = serializers.CharField(help_text="Type", required=False, allow_null=True) + title = serializers.CharField(help_text="Title", required=False, allow_null=True) + status = serializers.IntegerField(help_text="Status", required=True) + detail = serializers.CharField(help_text="Detail", required=True, allow_null=True) + instance = serializers.CharField(help_text="Instance", required=False, allow_null=True) diff --git a/lcm/lcm/nf/tests/test_operate_vnf.py b/lcm/lcm/nf/tests/test_operate_vnf.py new file mode 100644 index 00000000..2071472c --- /dev/null +++ b/lcm/lcm/nf/tests/test_operate_vnf.py @@ -0,0 +1,242 @@ +# Copyright (C) 2018 Verizon. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import json
+
+import mock
+from django.test import TestCase, Client
+from rest_framework import status
+
+from lcm.nf.biz.operate_vnf import OperateVnf
+from lcm.pub.database.models import NfInstModel, JobStatusModel, VmInstModel
+from lcm.pub.utils import restcall
+from lcm.pub.utils.jobutil import JobUtil
+from lcm.pub.utils.timeutil import now_time
+from lcm.pub.vimapi import api
+
+
+class TestNFOperate(TestCase):
+ def setUp(self):
+ self.client = Client()
+
+ def tearDown(self):
+ VmInstModel.objects.all().delete()
+
+ def assert_job_result(self, job_id, job_progress, job_detail):
+ jobs = JobStatusModel.objects.filter(jobid=job_id,
+ progress=job_progress,
+ descp=job_detail)
+ self.assertEqual(1, len(jobs))
+
+ def test_operate_vnf_not_found(self):
+ req_data = {
+ "changeStateTo": "STARTED"
+ }
+ response = self.client.post("/api/vnflcm/v1/vnf_instances/12/operate", data=req_data, format='json')
+ self.failUnlessEqual(status.HTTP_404_NOT_FOUND, response.status_code)
+
+ def test_operate_vnf_conflict(self):
+ req_data = {
+ "changeStateTo": "STARTED"
+ }
+ NfInstModel(nfinstid='12', nf_name='VNF1', status='NOT_INSTANTIATED').save()
+ response = self.client.post("/api/vnflcm/v1/vnf_instances/12/operate", data=req_data, format='json')
+ self.failUnlessEqual(status.HTTP_409_CONFLICT, response.status_code)
+ NfInstModel(nfinstid='12', nf_name='VNF1', status='NOT_INSTANTIATED').delete()
+
+ @mock.patch.object(OperateVnf, 'run')
+ def test_operate_vnf_success(self, mock_run):
+ req_data = {
+ "changeStateTo": "STARTED"
+ }
+ NfInstModel(nfinstid='12', nf_name='VNF1', status='INSTANTIATED').save()
+ response = self.client.post("/api/vnflcm/v1/vnf_instances/12/operate", data=req_data, format='json')
+ mock_run.re.return_value = None
+ self.failUnlessEqual(status.HTTP_202_ACCEPTED, response.status_code)
+ NfInstModel(nfinstid='12', nf_name='VNF1', status='INSTANTIATED').delete()
+
+ @mock.patch.object(restcall, 'call_req')
+ @mock.patch.object(api, 'call')
+ def test_operate_vnf_success_start(self, mock_call, mock_call_req):
+ NfInstModel.objects.create(nfinstid='1111',
+ nf_name='2222',
+ vnfminstid='1',
+ package_id='todo',
+ version='',
+ vendor='',
+ netype='',
+ vnfd_model='',
+ status='INSTANTIATED',
+ nf_desc='',
+ vnfdid='',
+ vnfSoftwareVersion='',
+ vnfConfigurableProperties='todo',
+ localizationLanguage='EN_US',
+ create_time=now_time())
+
+ VmInstModel.objects.create(vmid="1",
+ vimid="1",
+ resouceid="11",
+ insttype=0,
+ instid="1111",
+ vmname="test_01",
+ is_predefined=1,
+ operationalstate=1)
+ t1_apply_grant_result = [0, json.JSONEncoder().encode(''), '200']
+ t2_lcm_notify_result = [0, json.JSONEncoder().encode(''), '200']
+ t3_action_vm_start_result = [0, json.JSONEncoder().encode(''), '202']
+ mock_call_req.side_effect = [t1_apply_grant_result, t2_lcm_notify_result, t3_action_vm_start_result]
+ mock_call.return_value = None
+ req_data = {
+ "changeStateTo": "STARTED"
+ }
+ self.nf_inst_id = '1111'
+ self.job_id = JobUtil.create_job('NF', 'OPERATE', self.nf_inst_id)
+ JobUtil.add_job_status(self.job_id, 0, "OPERATE_VNF_READY")
+ OperateVnf(req_data, nf_inst_id=self.nf_inst_id, job_id=self.job_id).run()
+ vm = VmInstModel.objects.filter(vmid="1", vimid="1", resouceid="11")
+ self.assertEqual("ACTIVE", vm[0].operationalstate)
+ self.assert_job_result(self.job_id, 100, "Operate Vnf success.")
+
+ @mock.patch.object(restcall, 'call_req')
+ @mock.patch.object(api, 'call')
+ def test_operate_vnf_success_stop(self, mock_call, mock_call_req):
+ NfInstModel.objects.create(nfinstid='1111',
+ nf_name='2222',
+ vnfminstid='1',
+ package_id='todo',
+ version='',
+ vendor='',
+ netype='',
+ vnfd_model='',
+ status='INSTANTIATED',
+ nf_desc='',
+ vnfdid='',
+ vnfSoftwareVersion='',
+ vnfConfigurableProperties='todo',
+ localizationLanguage='EN_US',
+ create_time=now_time())
+
+ VmInstModel.objects.create(vmid="1",
+ vimid="1",
+ resouceid="11",
+ insttype=0,
+ instid="1111",
+ vmname="test_01",
+ is_predefined=1,
+ operationalstate=1)
+ t1_apply_grant_result = [0, json.JSONEncoder().encode(''), '200']
+ t2_lcm_notify_result = [0, json.JSONEncoder().encode(''), '200']
+ t3_action_vm_stop_result = [0, json.JSONEncoder().encode(''), '202']
+ mock_call_req.side_effect = [t1_apply_grant_result, t2_lcm_notify_result, t3_action_vm_stop_result]
+ mock_call.return_value = None
+ req_data = {
+ "changeStateTo": "STOPPED"
+ }
+ self.nf_inst_id = '1111'
+ self.job_id = JobUtil.create_job('NF', 'OPERATE', self.nf_inst_id)
+ JobUtil.add_job_status(self.job_id, 0, "OPERATE_VNF_READY")
+ OperateVnf(req_data, nf_inst_id=self.nf_inst_id, job_id=self.job_id).run()
+ vm = VmInstModel.objects.filter(vmid="1", vimid="1", resouceid="11")
+ self.assertEqual("INACTIVE", vm[0].operationalstate)
+ self.assert_job_result(self.job_id, 100, "Operate Vnf success.")
+
+ @mock.patch.object(restcall, 'call_req')
+ @mock.patch.object(api, 'call')
+ def test_operate_vnf_success_stop_graceful(self, mock_call, mock_call_req):
+ NfInstModel.objects.create(nfinstid='1111',
+ nf_name='2222',
+ vnfminstid='1',
+ package_id='todo',
+ version='',
+ vendor='',
+ netype='',
+ vnfd_model='',
+ status='INSTANTIATED',
+ nf_desc='',
+ vnfdid='',
+ vnfSoftwareVersion='',
+ vnfConfigurableProperties='todo',
+ localizationLanguage='EN_US',
+ create_time=now_time())
+
+ VmInstModel.objects.create(vmid="1",
+ vimid="1",
+ resouceid="11",
+ insttype=0,
+ instid="1111",
+ vmname="test_01",
+ is_predefined=1,
+ operationalstate=1)
+ t1_apply_grant_result = [0, json.JSONEncoder().encode(''), '200']
+ t2_lcm_notify_result = [0, json.JSONEncoder().encode(''), '200']
+ t3_action_vm_stop_result = [0, json.JSONEncoder().encode(''), '202']
+ mock_call_req.side_effect = [t1_apply_grant_result, t2_lcm_notify_result, t3_action_vm_stop_result]
+ mock_call.return_value = None
+ req_data = {
+ "changeStateTo": "STOPPED",
+ "stopType": "GRACEFUL",
+ "gracefulStopTimeout": 2
+ }
+ self.nf_inst_id = '1111'
+ self.job_id = JobUtil.create_job('NF', 'OPERATE', self.nf_inst_id)
+ JobUtil.add_job_status(self.job_id, 0, "OPERATE_VNF_READY")
+ OperateVnf(req_data, nf_inst_id=self.nf_inst_id, job_id=self.job_id).run()
+ vm = VmInstModel.objects.filter(vmid="1", vimid="1", resouceid="11")
+ self.assertEqual("INACTIVE", vm[0].operationalstate)
+ self.assert_job_result(self.job_id, 100, "Operate Vnf success.")
+
+ @mock.patch.object(restcall, 'call_req')
+ @mock.patch.object(api, 'call')
+ def test_operate_vnf_success_stop_forceful(self, mock_call, mock_call_req):
+ NfInstModel.objects.create(nfinstid='1111',
+ nf_name='2222',
+ vnfminstid='1',
+ package_id='todo',
+ version='',
+ vendor='',
+ netype='',
+ vnfd_model='',
+ status='INSTANTIATED',
+ nf_desc='',
+ vnfdid='',
+ vnfSoftwareVersion='',
+ vnfConfigurableProperties='todo',
+ localizationLanguage='EN_US',
+ create_time=now_time())
+
+ VmInstModel.objects.create(vmid="1",
+ vimid="1",
+ resouceid="11",
+ insttype=0,
+ instid="1111",
+ vmname="test_01",
+ is_predefined=1,
+ operationalstate=1)
+ t1_apply_grant_result = [0, json.JSONEncoder().encode(''), '200']
+ t2_lcm_notify_result = [0, json.JSONEncoder().encode(''), '200']
+ t3_action_vm_stop_result = [0, json.JSONEncoder().encode(''), '202']
+ mock_call_req.side_effect = [t1_apply_grant_result, t2_lcm_notify_result, t3_action_vm_stop_result]
+ mock_call.return_value = None
+ req_data = {
+ "changeStateTo": "STOPPED",
+ "stopType": "FORCEFUL",
+ }
+ self.nf_inst_id = '1111'
+ self.job_id = JobUtil.create_job('NF', 'OPERATE', self.nf_inst_id)
+ JobUtil.add_job_status(self.job_id, 0, "OPERATE_VNF_READY")
+ OperateVnf(req_data, nf_inst_id=self.nf_inst_id, job_id=self.job_id).run()
+ vm = VmInstModel.objects.filter(vmid="1", vimid="1", resouceid="11")
+ self.assertEqual("INACTIVE", vm[0].operationalstate)
+ self.assert_job_result(self.job_id, 100, "Operate Vnf success.")
diff --git a/lcm/lcm/nf/urls.py b/lcm/lcm/nf/urls.py index b7625339..b73cb02e 100644 --- a/lcm/lcm/nf/urls.py +++ b/lcm/lcm/nf/urls.py @@ -18,6 +18,7 @@ from lcm.nf.views.curd_vnf_views import DeleteVnfAndQueryVnf, CreateVnfAndQueryV from lcm.nf.views.instantiate_vnf_view import InstantiateVnfView from lcm.nf.views.terminate_vnf_view import TerminateVnfView from lcm.nf.views.subscriptions_view import SubscriptionsView +from lcm.nf.views.operate_vnf_view import OperateVnfView urlpatterns = [ url(r'^api/vnflcm/v1/subscriptions$', SubscriptionsView.as_view()), @@ -25,4 +26,5 @@ urlpatterns = [ url(r'^api/vnflcm/v1/vnf_instances/(?P<instanceid>[0-9a-zA-Z_-]+)/instantiate$', InstantiateVnfView.as_view()), url(r'^api/vnflcm/v1/vnf_instances/(?P<instanceid>[0-9a-zA-Z_-]+)$', DeleteVnfAndQueryVnf.as_view()), url(r'^api/vnflcm/v1/vnf_instances/(?P<instanceid>[0-9a-zA-Z_-]+)/terminate$', TerminateVnfView.as_view()), + url(r'^api/vnflcm/v1/vnf_instances/(?P<instanceid>[0-9a-zA-Z_-]+)/operate$', OperateVnfView.as_view()), ] diff --git a/lcm/lcm/nf/views/operate_vnf_view.py b/lcm/lcm/nf/views/operate_vnf_view.py new file mode 100644 index 00000000..947e983e --- /dev/null +++ b/lcm/lcm/nf/views/operate_vnf_view.py @@ -0,0 +1,88 @@ +# Copyright (C) 2018 Verizon. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import logging
+import traceback
+
+from drf_yasg.utils import swagger_auto_schema
+from rest_framework import status
+from rest_framework.response import Response
+from rest_framework.views import APIView
+
+from lcm.nf.biz.operate_vnf import OperateVnf
+from lcm.nf.serializers.operate_vnf_req import OperateVnfRequestSerializer
+from lcm.nf.serializers.response import ProblemDetailsSerializer
+from lcm.pub.exceptions import NFLCMException, NFLCMExceptionNotFound, NFLCMExceptionConflict
+from lcm.pub.utils.jobutil import JobUtil
+from lcm.pub.database.models import NfInstModel
+from lcm.nf.const import VNF_STATUS
+
+logger = logging.getLogger(__name__)
+
+
+class OperateVnfView(APIView):
+ @swagger_auto_schema(
+ request_body=OperateVnfRequestSerializer(),
+ responses={
+ status.HTTP_202_ACCEPTED: "Success",
+ status.HTTP_404_NOT_FOUND: ProblemDetailsSerializer(),
+ status.HTTP_409_CONFLICT: ProblemDetailsSerializer(),
+ status.HTTP_500_INTERNAL_SERVER_ERROR: "Internal error"
+ }
+ )
+ def post(self, request, instanceid):
+ logger.debug("OperateVnf--post::> %s" % request.data)
+ try:
+ operate_vnf_request_serializer = OperateVnfRequestSerializer(data=request.data)
+ if not operate_vnf_request_serializer.is_valid():
+ raise NFLCMException(operate_vnf_request_serializer.errors)
+
+ job_id = JobUtil.create_job('NF', 'OPERATE', instanceid)
+ JobUtil.add_job_status(job_id, 0, "OPERATE_VNF_READY")
+ self.operate_pre_check(instanceid, job_id)
+ OperateVnf(operate_vnf_request_serializer.data, instanceid, job_id).start()
+ response = Response(data=None, status=status.HTTP_202_ACCEPTED)
+ response["Location"] = "/vnf_lc_ops/%s" % job_id
+ return response
+ except NFLCMExceptionNotFound as e:
+ probDetail = ProblemDetailsSerializer(data={"status": 404, "detail": "VNF Instance not found"})
+ resp_isvalid = probDetail.is_valid()
+ if not resp_isvalid:
+ raise NFLCMException(probDetail.errors)
+ return Response(data=probDetail.data, status=status.HTTP_404_NOT_FOUND)
+ except NFLCMExceptionConflict as e:
+ probDetail = ProblemDetailsSerializer(data={"status": 409, "detail": "VNF Instance not in Instantiated State"})
+ resp_isvalid = probDetail.is_valid()
+ if not resp_isvalid:
+ raise NFLCMException(probDetail.errors)
+ return Response(data=probDetail.data, status=status.HTTP_409_CONFLICT)
+ except NFLCMException as e:
+ logger.error(e.message)
+ return Response(data={'error': '%s' % e.message}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
+ except Exception as e:
+ logger.error(e.message)
+ logger.error(traceback.format_exc())
+ return Response(data={'error': 'unexpected exception'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
+
+ def operate_pre_check(self, nfInstId, jobId):
+ vnf_insts = NfInstModel.objects.filter(nfinstid=nfInstId)
+ if not vnf_insts.exists():
+ raise NFLCMExceptionNotFound("VNF nf_inst_id does not exist.")
+
+ if vnf_insts[0].status != 'INSTANTIATED':
+ raise NFLCMExceptionConflict("VNF instantiationState is not INSTANTIATED.")
+ NfInstModel.objects.filter(nfinstid=nfInstId).update(status=VNF_STATUS.OPERATING)
+
+ JobUtil.add_job_status(jobId, 15, 'Nf operating pre-check finish')
+ logger.info("Nf operating pre-check finish")
diff --git a/lcm/lcm/pub/database/models.py b/lcm/lcm/pub/database/models.py index 4f4fc9f2..57de616f 100644 --- a/lcm/lcm/pub/database/models.py +++ b/lcm/lcm/pub/database/models.py @@ -39,6 +39,7 @@ class NfInstModel(models.Model): vnfSoftwareVersion = models.CharField(db_column='VNFSOFTWAREVER', max_length=200, blank=True, null=True) vnfConfigurableProperties = models.TextField(db_column='VNFCONFIGURABLEPROPERTIES', max_length=20000, blank=True, null=True) localizationLanguage = models.CharField(db_column='LOCALIZATIONLANGUAGE', max_length=255, null=True) + operationState = models.CharField(db_column='OPERATIONSTATE', max_length=255, null=True) class JobModel(models.Model): diff --git a/lcm/lcm/pub/exceptions.py b/lcm/lcm/pub/exceptions.py index 274c0d06..5ff9bc42 100644 --- a/lcm/lcm/pub/exceptions.py +++ b/lcm/lcm/pub/exceptions.py @@ -15,3 +15,11 @@ class NFLCMException(Exception): pass + + +class NFLCMExceptionNotFound(Exception): + pass + + +class NFLCMExceptionConflict(Exception): + pass diff --git a/lcm/lcm/pub/vimapi/adaptor.py b/lcm/lcm/pub/vimapi/adaptor.py index 9ca3e8de..8ebddab0 100644 --- a/lcm/lcm/pub/vimapi/adaptor.py +++ b/lcm/lcm/pub/vimapi/adaptor.py @@ -20,6 +20,7 @@ from lcm.pub.utils.values import ignore_case_get, set_opt_val from lcm.pub.msapi.aai import get_flavor_info from . import api from .exceptions import VimException +from lcm.nf.const import ACTION_TYPE logger = logging.getLogger(__name__) @@ -65,6 +66,50 @@ def get_res_id(res_cache, res_type, key): return res_cache[res_type][key] +def action_vm(action_type, server, vimId, tenantId): + param = {} + if action_type == ACTION_TYPE.START: + param = { + "os-start": None, + } + elif action_type == ACTION_TYPE.STOP: + param = { + "os-stop": None, + } + elif action_type == ACTION_TYPE.REBOOT: + param = { + "reboot": {} + } + if server["status"] == "ACTIVE": + param["reboot"]["type"] = "SOFT" + else: + param["reboot"]["type"] = "HARD" + res_id = server["id"] + api.action_vm(vimId, tenantId, res_id, param) + + +# TODO Have to check if the resources should be started and stopped in some order. +def operate_vim_res(data, changeStateTo, stopType, gracefulStopTimeout, do_notify_op): + for res in ignore_case_get(data, "vm"): + try: + if changeStateTo == "STARTED": + action_vm(ACTION_TYPE.START, res, res["vim_id"], res["tenant_id"]) + do_notify_op("ACTIVE", res["id"]) + elif changeStateTo == "STOPPED": + if stopType == "GRACEFUL": + if gracefulStopTimeout > 60: + gracefulStopTimeout = 60 + time.sleep(gracefulStopTimeout) + action_vm(ACTION_TYPE.STOP, res, res["vim_id"], res["tenant_id"]) + # TODO check if the we should poll getvm to get the status or the action_vm api + # successful return should suffice to mark vm as Active/Inactive + do_notify_op("INACTIVE", res["id"]) + except VimException as e: + # TODO Have to update database appropriately on failure + logger.error("Failed to Heal %s(%s)", RES_VM, res["res_id"]) + logger.error("%s:%s", e.http_code, e.message) + + def create_vim_res(data, do_notify): vim_cache, res_cache = {}, {} for vol in ignore_case_get(data, "volume_storages"): diff --git a/lcm/lcm/pub/vimapi/api.py b/lcm/lcm/pub/vimapi/api.py index 0090d66f..2ceb82d0 100644 --- a/lcm/lcm/pub/vimapi/api.py +++ b/lcm/lcm/pub/vimapi/api.py @@ -145,6 +145,11 @@ def get_vm(vim_id, tenant_id, vm_id): def list_vm(vim_id, tenant_id): return call(vim_id, tenant_id, "servers", "GET") + +# Used to start/stop/restart a vm +def action_vm(vim_id, tenant_id, vm_id, data): + return call(vim_id, tenant_id, "servers/%s/action" % vm_id, "POST", data) + ###################################################################### |