Add operate api to GVNFM 93/64193/3
authorShobana Jothi <shobana.jothi@verizon.com>
Tue, 28 Aug 2018 12:10:10 +0000 (17:40 +0530)
committerShobana Jothi <shobana.jothi@verizon.com>
Tue, 4 Sep 2018 10:37:38 +0000 (16:07 +0530)
Change-Id: I35e3b52b76beff7f014759cec7217e5e5315c985
Signed-off-by: Shobana Jothi<shobana.jothi@verizon.com>
Issue-ID: VFC-996

12 files changed:
lcm/lcm/nf/biz/grant_vnf.py
lcm/lcm/nf/biz/operate_vnf.py [new file with mode: 0644]
lcm/lcm/nf/const.py
lcm/lcm/nf/serializers/operate_vnf_req.py [new file with mode: 0644]
lcm/lcm/nf/serializers/response.py [new file with mode: 0644]
lcm/lcm/nf/tests/test_operate_vnf.py [new file with mode: 0644]
lcm/lcm/nf/urls.py
lcm/lcm/nf/views/operate_vnf_view.py [new file with mode: 0644]
lcm/lcm/pub/database/models.py
lcm/lcm/pub/exceptions.py
lcm/lcm/pub/vimapi/adaptor.py
lcm/lcm/pub/vimapi/api.py

index 1997e0c..fe3cb53 100644 (file)
@@ -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 (file)
index 0000000..5f6499d
--- /dev/null
@@ -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)
index ecbc80f..37205c5 100644 (file)
@@ -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 (file)
index 0000000..b40e700
--- /dev/null
@@ -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 (file)
index 0000000..81f5ed5
--- /dev/null
@@ -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 (file)
index 0000000..2071472
--- /dev/null
@@ -0,0 +1,242 @@
+# Copyright (C) 2018 Verizon. All Rights Reserved.\r
+#\r
+# Licensed under the Apache License, Version 2.0 (the "License");\r
+# you may not use this file except in compliance with the License.\r
+# You may obtain a copy of the License at\r
+#\r
+#       http://www.apache.org/licenses/LICENSE-2.0\r
+#\r
+# Unless required by applicable law or agreed to in writing, software\r
+# distributed under the License is distributed on an "AS IS" BASIS,\r
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+# See the License for the specific language governing permissions and\r
+# limitations under the License.\r
+\r
+import json\r
+\r
+import mock\r
+from django.test import TestCase, Client\r
+from rest_framework import status\r
+\r
+from lcm.nf.biz.operate_vnf import OperateVnf\r
+from lcm.pub.database.models import NfInstModel, JobStatusModel, VmInstModel\r
+from lcm.pub.utils import restcall\r
+from lcm.pub.utils.jobutil import JobUtil\r
+from lcm.pub.utils.timeutil import now_time\r
+from lcm.pub.vimapi import api\r
+\r
+\r
+class TestNFOperate(TestCase):\r
+    def setUp(self):\r
+        self.client = Client()\r
+\r
+    def tearDown(self):\r
+        VmInstModel.objects.all().delete()\r
+\r
+    def assert_job_result(self, job_id, job_progress, job_detail):\r
+        jobs = JobStatusModel.objects.filter(jobid=job_id,\r
+                                             progress=job_progress,\r
+                                             descp=job_detail)\r
+        self.assertEqual(1, len(jobs))\r
+\r
+    def test_operate_vnf_not_found(self):\r
+        req_data = {\r
+            "changeStateTo": "STARTED"\r
+        }\r
+        response = self.client.post("/api/vnflcm/v1/vnf_instances/12/operate", data=req_data, format='json')\r
+        self.failUnlessEqual(status.HTTP_404_NOT_FOUND, response.status_code)\r
+\r
+    def test_operate_vnf_conflict(self):\r
+        req_data = {\r
+            "changeStateTo": "STARTED"\r
+        }\r
+        NfInstModel(nfinstid='12', nf_name='VNF1', status='NOT_INSTANTIATED').save()\r
+        response = self.client.post("/api/vnflcm/v1/vnf_instances/12/operate", data=req_data, format='json')\r
+        self.failUnlessEqual(status.HTTP_409_CONFLICT, response.status_code)\r
+        NfInstModel(nfinstid='12', nf_name='VNF1', status='NOT_INSTANTIATED').delete()\r
+\r
+    @mock.patch.object(OperateVnf, 'run')\r
+    def test_operate_vnf_success(self, mock_run):\r
+        req_data = {\r
+            "changeStateTo": "STARTED"\r
+        }\r
+        NfInstModel(nfinstid='12', nf_name='VNF1', status='INSTANTIATED').save()\r
+        response = self.client.post("/api/vnflcm/v1/vnf_instances/12/operate", data=req_data, format='json')\r
+        mock_run.re.return_value = None\r
+        self.failUnlessEqual(status.HTTP_202_ACCEPTED, response.status_code)\r
+        NfInstModel(nfinstid='12', nf_name='VNF1', status='INSTANTIATED').delete()\r
+\r
+    @mock.patch.object(restcall, 'call_req')\r
+    @mock.patch.object(api, 'call')\r
+    def test_operate_vnf_success_start(self, mock_call, mock_call_req):\r
+        NfInstModel.objects.create(nfinstid='1111',\r
+                                   nf_name='2222',\r
+                                   vnfminstid='1',\r
+                                   package_id='todo',\r
+                                   version='',\r
+                                   vendor='',\r
+                                   netype='',\r
+                                   vnfd_model='',\r
+                                   status='INSTANTIATED',\r
+                                   nf_desc='',\r
+                                   vnfdid='',\r
+                                   vnfSoftwareVersion='',\r
+                                   vnfConfigurableProperties='todo',\r
+                                   localizationLanguage='EN_US',\r
+                                   create_time=now_time())\r
+\r
+        VmInstModel.objects.create(vmid="1",\r
+                                   vimid="1",\r
+                                   resouceid="11",\r
+                                   insttype=0,\r
+                                   instid="1111",\r
+                                   vmname="test_01",\r
+                                   is_predefined=1,\r
+                                   operationalstate=1)\r
+        t1_apply_grant_result = [0, json.JSONEncoder().encode(''), '200']\r
+        t2_lcm_notify_result = [0, json.JSONEncoder().encode(''), '200']\r
+        t3_action_vm_start_result = [0, json.JSONEncoder().encode(''), '202']\r
+        mock_call_req.side_effect = [t1_apply_grant_result, t2_lcm_notify_result, t3_action_vm_start_result]\r
+        mock_call.return_value = None\r
+        req_data = {\r
+            "changeStateTo": "STARTED"\r
+        }\r
+        self.nf_inst_id = '1111'\r
+        self.job_id = JobUtil.create_job('NF', 'OPERATE', self.nf_inst_id)\r
+        JobUtil.add_job_status(self.job_id, 0, "OPERATE_VNF_READY")\r
+        OperateVnf(req_data, nf_inst_id=self.nf_inst_id, job_id=self.job_id).run()\r
+        vm = VmInstModel.objects.filter(vmid="1", vimid="1", resouceid="11")\r
+        self.assertEqual("ACTIVE", vm[0].operationalstate)\r
+        self.assert_job_result(self.job_id, 100, "Operate Vnf success.")\r
+\r
+    @mock.patch.object(restcall, 'call_req')\r
+    @mock.patch.object(api, 'call')\r
+    def test_operate_vnf_success_stop(self, mock_call, mock_call_req):\r
+        NfInstModel.objects.create(nfinstid='1111',\r
+                                   nf_name='2222',\r
+                                   vnfminstid='1',\r
+                                   package_id='todo',\r
+                                   version='',\r
+                                   vendor='',\r
+                                   netype='',\r
+                                   vnfd_model='',\r
+                                   status='INSTANTIATED',\r
+                                   nf_desc='',\r
+                                   vnfdid='',\r
+                                   vnfSoftwareVersion='',\r
+                                   vnfConfigurableProperties='todo',\r
+                                   localizationLanguage='EN_US',\r
+                                   create_time=now_time())\r
+\r
+        VmInstModel.objects.create(vmid="1",\r
+                                   vimid="1",\r
+                                   resouceid="11",\r
+                                   insttype=0,\r
+                                   instid="1111",\r
+                                   vmname="test_01",\r
+                                   is_predefined=1,\r
+                                   operationalstate=1)\r
+        t1_apply_grant_result = [0, json.JSONEncoder().encode(''), '200']\r
+        t2_lcm_notify_result = [0, json.JSONEncoder().encode(''), '200']\r
+        t3_action_vm_stop_result = [0, json.JSONEncoder().encode(''), '202']\r
+        mock_call_req.side_effect = [t1_apply_grant_result, t2_lcm_notify_result, t3_action_vm_stop_result]\r
+        mock_call.return_value = None\r
+        req_data = {\r
+            "changeStateTo": "STOPPED"\r
+        }\r
+        self.nf_inst_id = '1111'\r
+        self.job_id = JobUtil.create_job('NF', 'OPERATE', self.nf_inst_id)\r
+        JobUtil.add_job_status(self.job_id, 0, "OPERATE_VNF_READY")\r
+        OperateVnf(req_data, nf_inst_id=self.nf_inst_id, job_id=self.job_id).run()\r
+        vm = VmInstModel.objects.filter(vmid="1", vimid="1", resouceid="11")\r
+        self.assertEqual("INACTIVE", vm[0].operationalstate)\r
+        self.assert_job_result(self.job_id, 100, "Operate Vnf success.")\r
+\r
+    @mock.patch.object(restcall, 'call_req')\r
+    @mock.patch.object(api, 'call')\r
+    def test_operate_vnf_success_stop_graceful(self, mock_call, mock_call_req):\r
+        NfInstModel.objects.create(nfinstid='1111',\r
+                                   nf_name='2222',\r
+                                   vnfminstid='1',\r
+                                   package_id='todo',\r
+                                   version='',\r
+                                   vendor='',\r
+                                   netype='',\r
+                                   vnfd_model='',\r
+                                   status='INSTANTIATED',\r
+                                   nf_desc='',\r
+                                   vnfdid='',\r
+                                   vnfSoftwareVersion='',\r
+                                   vnfConfigurableProperties='todo',\r
+                                   localizationLanguage='EN_US',\r
+                                   create_time=now_time())\r
+\r
+        VmInstModel.objects.create(vmid="1",\r
+                                   vimid="1",\r
+                                   resouceid="11",\r
+                                   insttype=0,\r
+                                   instid="1111",\r
+                                   vmname="test_01",\r
+                                   is_predefined=1,\r
+                                   operationalstate=1)\r
+        t1_apply_grant_result = [0, json.JSONEncoder().encode(''), '200']\r
+        t2_lcm_notify_result = [0, json.JSONEncoder().encode(''), '200']\r
+        t3_action_vm_stop_result = [0, json.JSONEncoder().encode(''), '202']\r
+        mock_call_req.side_effect = [t1_apply_grant_result, t2_lcm_notify_result, t3_action_vm_stop_result]\r
+        mock_call.return_value = None\r
+        req_data = {\r
+            "changeStateTo": "STOPPED",\r
+            "stopType": "GRACEFUL",\r
+            "gracefulStopTimeout": 2\r
+        }\r
+        self.nf_inst_id = '1111'\r
+        self.job_id = JobUtil.create_job('NF', 'OPERATE', self.nf_inst_id)\r
+        JobUtil.add_job_status(self.job_id, 0, "OPERATE_VNF_READY")\r
+        OperateVnf(req_data, nf_inst_id=self.nf_inst_id, job_id=self.job_id).run()\r
+        vm = VmInstModel.objects.filter(vmid="1", vimid="1", resouceid="11")\r
+        self.assertEqual("INACTIVE", vm[0].operationalstate)\r
+        self.assert_job_result(self.job_id, 100, "Operate Vnf success.")\r
+\r
+    @mock.patch.object(restcall, 'call_req')\r
+    @mock.patch.object(api, 'call')\r
+    def test_operate_vnf_success_stop_forceful(self, mock_call, mock_call_req):\r
+        NfInstModel.objects.create(nfinstid='1111',\r
+                                   nf_name='2222',\r
+                                   vnfminstid='1',\r
+                                   package_id='todo',\r
+                                   version='',\r
+                                   vendor='',\r
+                                   netype='',\r
+                                   vnfd_model='',\r
+                                   status='INSTANTIATED',\r
+                                   nf_desc='',\r
+                                   vnfdid='',\r
+                                   vnfSoftwareVersion='',\r
+                                   vnfConfigurableProperties='todo',\r
+                                   localizationLanguage='EN_US',\r
+                                   create_time=now_time())\r
+\r
+        VmInstModel.objects.create(vmid="1",\r
+                                   vimid="1",\r
+                                   resouceid="11",\r
+                                   insttype=0,\r
+                                   instid="1111",\r
+                                   vmname="test_01",\r
+                                   is_predefined=1,\r
+                                   operationalstate=1)\r
+        t1_apply_grant_result = [0, json.JSONEncoder().encode(''), '200']\r
+        t2_lcm_notify_result = [0, json.JSONEncoder().encode(''), '200']\r
+        t3_action_vm_stop_result = [0, json.JSONEncoder().encode(''), '202']\r
+        mock_call_req.side_effect = [t1_apply_grant_result, t2_lcm_notify_result, t3_action_vm_stop_result]\r
+        mock_call.return_value = None\r
+        req_data = {\r
+            "changeStateTo": "STOPPED",\r
+            "stopType": "FORCEFUL",\r
+        }\r
+        self.nf_inst_id = '1111'\r
+        self.job_id = JobUtil.create_job('NF', 'OPERATE', self.nf_inst_id)\r
+        JobUtil.add_job_status(self.job_id, 0, "OPERATE_VNF_READY")\r
+        OperateVnf(req_data, nf_inst_id=self.nf_inst_id, job_id=self.job_id).run()\r
+        vm = VmInstModel.objects.filter(vmid="1", vimid="1", resouceid="11")\r
+        self.assertEqual("INACTIVE", vm[0].operationalstate)\r
+        self.assert_job_result(self.job_id, 100, "Operate Vnf success.")\r
index b762533..b73cb02 100644 (file)
@@ -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 (file)
index 0000000..947e983
--- /dev/null
@@ -0,0 +1,88 @@
+# Copyright (C) 2018 Verizon. All Rights Reserved.\r
+#\r
+# Licensed under the Apache License, Version 2.0 (the "License");\r
+# you may not use this file except in compliance with the License.\r
+# You may obtain a copy of the License at\r
+#\r
+#       http://www.apache.org/licenses/LICENSE-2.0\r
+#\r
+# Unless required by applicable law or agreed to in writing, software\r
+# distributed under the License is distributed on an "AS IS" BASIS,\r
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+# See the License for the specific language governing permissions and\r
+# limitations under the License.\r
+\r
+import logging\r
+import traceback\r
+\r
+from drf_yasg.utils import swagger_auto_schema\r
+from rest_framework import status\r
+from rest_framework.response import Response\r
+from rest_framework.views import APIView\r
+\r
+from lcm.nf.biz.operate_vnf import OperateVnf\r
+from lcm.nf.serializers.operate_vnf_req import OperateVnfRequestSerializer\r
+from lcm.nf.serializers.response import ProblemDetailsSerializer\r
+from lcm.pub.exceptions import NFLCMException, NFLCMExceptionNotFound, NFLCMExceptionConflict\r
+from lcm.pub.utils.jobutil import JobUtil\r
+from lcm.pub.database.models import NfInstModel\r
+from lcm.nf.const import VNF_STATUS\r
+\r
+logger = logging.getLogger(__name__)\r
+\r
+\r
+class OperateVnfView(APIView):\r
+    @swagger_auto_schema(\r
+        request_body=OperateVnfRequestSerializer(),\r
+        responses={\r
+            status.HTTP_202_ACCEPTED: "Success",\r
+            status.HTTP_404_NOT_FOUND: ProblemDetailsSerializer(),\r
+            status.HTTP_409_CONFLICT: ProblemDetailsSerializer(),\r
+            status.HTTP_500_INTERNAL_SERVER_ERROR: "Internal error"\r
+        }\r
+    )\r
+    def post(self, request, instanceid):\r
+        logger.debug("OperateVnf--post::> %s" % request.data)\r
+        try:\r
+            operate_vnf_request_serializer = OperateVnfRequestSerializer(data=request.data)\r
+            if not operate_vnf_request_serializer.is_valid():\r
+                raise NFLCMException(operate_vnf_request_serializer.errors)\r
+\r
+            job_id = JobUtil.create_job('NF', 'OPERATE', instanceid)\r
+            JobUtil.add_job_status(job_id, 0, "OPERATE_VNF_READY")\r
+            self.operate_pre_check(instanceid, job_id)\r
+            OperateVnf(operate_vnf_request_serializer.data, instanceid, job_id).start()\r
+            response = Response(data=None, status=status.HTTP_202_ACCEPTED)\r
+            response["Location"] = "/vnf_lc_ops/%s" % job_id\r
+            return response\r
+        except NFLCMExceptionNotFound as e:\r
+            probDetail = ProblemDetailsSerializer(data={"status": 404, "detail": "VNF Instance not found"})\r
+            resp_isvalid = probDetail.is_valid()\r
+            if not resp_isvalid:\r
+                raise NFLCMException(probDetail.errors)\r
+            return Response(data=probDetail.data, status=status.HTTP_404_NOT_FOUND)\r
+        except NFLCMExceptionConflict as e:\r
+            probDetail = ProblemDetailsSerializer(data={"status": 409, "detail": "VNF Instance not in Instantiated State"})\r
+            resp_isvalid = probDetail.is_valid()\r
+            if not resp_isvalid:\r
+                raise NFLCMException(probDetail.errors)\r
+            return Response(data=probDetail.data, status=status.HTTP_409_CONFLICT)\r
+        except NFLCMException as e:\r
+            logger.error(e.message)\r
+            return Response(data={'error': '%s' % e.message}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)\r
+        except Exception as e:\r
+            logger.error(e.message)\r
+            logger.error(traceback.format_exc())\r
+            return Response(data={'error': 'unexpected exception'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)\r
+\r
+    def operate_pre_check(self, nfInstId, jobId):\r
+        vnf_insts = NfInstModel.objects.filter(nfinstid=nfInstId)\r
+        if not vnf_insts.exists():\r
+            raise NFLCMExceptionNotFound("VNF nf_inst_id does not exist.")\r
+\r
+        if vnf_insts[0].status != 'INSTANTIATED':\r
+            raise NFLCMExceptionConflict("VNF instantiationState is not INSTANTIATED.")\r
+        NfInstModel.objects.filter(nfinstid=nfInstId).update(status=VNF_STATUS.OPERATING)\r
+\r
+        JobUtil.add_job_status(jobId, 15, 'Nf operating pre-check finish')\r
+        logger.info("Nf operating pre-check finish")\r
index 4f4fc9f..57de616 100644 (file)
@@ -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):
index 274c0d0..5ff9bc4 100644 (file)
 
 class NFLCMException(Exception):
     pass
+
+
+class NFLCMExceptionNotFound(Exception):
+    pass
+
+
+class NFLCMExceptionConflict(Exception):
+    pass
index 9ca3e8d..8ebddab 100644 (file)
@@ -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"):
index 0090d66..2ceb82d 100644 (file)
@@ -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)
+
 ######################################################################