Add api adaptor for vnf pkg download
[vfc/nfvo/driver/vnfm/svnfm.git] / zte / vmanager / driver / interfaces / views.py
index 0866301..7376d4d 100644 (file)
@@ -18,18 +18,22 @@ import logging
 import os
 import traceback
 
+from drf_yasg import openapi
 from drf_yasg.utils import swagger_auto_schema
 from rest_framework import status
-from rest_framework.decorators import api_view
 from rest_framework.response import Response
 from rest_framework.views import APIView
+from django.http import StreamingHttpResponse
 
 from driver.interfaces.serializers import HealReqSerializer, InstScaleHealRespSerializer, ScaleReqSerializer, \
-    NotifyReqSerializer
+    NotifyReqSerializer, GrantRespSerializer, GrantReqSerializer, JobQueryRespSerializer, TerminateVnfRequestSerializer, \
+    InstantiateVnfRequestSerializer, QueryVnfResponseSerializer
 from driver.pub.config.config import VNF_FTP
 from driver.pub.utils import restcall
 from driver.pub.utils.restcall import req_by_msb
 
+CHUNK_SIZE = 1024 * 8
+
 logger = logging.getLogger(__name__)
 
 
@@ -41,6 +45,25 @@ def load_json_file(file_name):
     return json_data
 
 
+def read(file_path, start, end):
+    fp = open(file_path, 'rb')
+    fp.seek(start)
+    pos = start
+    while pos + CHUNK_SIZE < end:
+        yield fp.read(CHUNK_SIZE)
+        pos = fp.tell()
+    yield fp.read(end - pos)
+
+
+def parse_file_range(file_path, file_range):
+    start, end = 0, os.path.getsize(file_path)
+    if file_range:
+        [start, end] = file_range.split('-')
+        start, end = start.strip(), end.strip()
+        start, end = int(start), int(end)
+    return start, end
+
+
 def fun_name():
     return "=================%s==================" % inspect.stack()[1][3]
 
@@ -58,14 +81,6 @@ def ignorcase_get(args, key):
     return ""
 
 
-def mapping_conv(keyword_map, rest_return):
-    resp_data = {}
-    for param in keyword_map:
-        if keyword_map[param]:
-            resp_data[keyword_map[param]] = ignorcase_get(rest_return, param)
-    return resp_data
-
-
 # Query vnfm_info from nslcm
 def get_vnfminfo_from_nslcm(vnfmid):
     ret = req_by_msb("api/nslcm/v1/vnfms/%s" % vnfmid, "GET")
@@ -84,231 +99,306 @@ def vnfpackage_get(csarid):
     return ret
 
 
-@api_view(http_method_names=['POST'])
-def instantiate_vnf(request, *args, **kwargs):
-    try:
-        logger.debug("[%s] request.data=%s", fun_name(), request.data)
-        vnfm_id = ignorcase_get(kwargs, "vnfmid")
-        ret = get_vnfminfo_from_nslcm(vnfm_id)
-        if ret[0] != 0:
-            return Response(data={'error': ret[1]}, status=ret[2])
-        vnfm_info = json.JSONDecoder().decode(ret[1])
-        logger.debug("[%s] vnfm_info=%s", fun_name(), vnfm_info)
-        vnf_package_id = ignorcase_get(request.data, "vnfPackageId")
-        ret = vnfd_get(vnf_package_id)
-        if ret[0] != 0:
-            return Response(data={'error': ret[1]}, status=ret[2])
-        vnfd_info = json.JSONDecoder().decode(ret[1])
-        logger.debug("[%s] vnfd_info=%s", fun_name(), vnfd_info)
-        csar_id = ignorcase_get(vnfd_info, "csarId")
-        ret = vnfpackage_get(csar_id)
-        if ret[0] != 0:
-            return Response(data={'error': ret[1]}, status=ret[2])
-        vnf_package_info = json.JSONDecoder().decode(ret[1])
-        packageInfo = ignorcase_get(vnf_package_info, "packageInfo")
-        logger.debug("[%s] packageInfo=%s", fun_name(), packageInfo)
-        data = {}
-        data["NFVOID"] = 1
-        data["VNFMID"] = vnfm_id
-        vnfdModel = json.loads(ignorcase_get(packageInfo, "vnfdModel"))
-        metadata = ignorcase_get(vnfdModel, "metadata")
-        vnfd_name = ignorcase_get(metadata, "name")
-        # TODO  convert sdc vnf package to vnf vender package
-        inputs = []
-        if "SPGW" in vnfd_name.upper():
-            data["VNFD"] = VNF_FTP + "SPGW"
-            inputs = load_json_file("SPGW" + "_inputs.json")
-        elif "MME" in vnfd_name.upper():
-            data["VNFD"] = VNF_FTP + "MME"
-            inputs = load_json_file("MME" + "_inputs.json")
-        else:
-            data["VNFD"] = ignorcase_get(packageInfo, "downloadUri")
-
-        data["VNFURL"] = data["VNFD"]
-
-        data["extension"] = {}
-        for name, value in ignorcase_get(ignorcase_get(request.data, "additionalParam"), "inputs").items():
-            inputs.append({"name": name, "value": value})
-
-        data["extension"]["inputs"] = json.dumps(inputs)
-        additionalParam = ignorcase_get(request.data, "additionalParam")
-        data["extension"]["extVirtualLinks"] = ignorcase_get(additionalParam, "extVirtualLinks")
-        data["extension"]["vnfinstancename"] = ignorcase_get(request.data, "vnfInstanceName")
-        data["extension"]["vnfid"] = data["VNFD"]
-        data["extension"]["multivim"] = 0
-        logger.debug("[%s] call_req data=%s", fun_name(), data)
-
-        ret = restcall.call_req(
-            base_url=ignorcase_get(vnfm_info, "url"),
-            user=ignorcase_get(vnfm_info, "userName"),
-            passwd=ignorcase_get(vnfm_info, "password"),
-            auth_type=restcall.rest_no_auth,
-            resource="v1/vnfs",
-            method='post',
-            content=json.JSONEncoder().encode(data))
-
-        logger.debug("[%s] call_req ret=%s", fun_name(), ret)
-        if ret[0] != 0:
-            return Response(data={'error': ret[1]}, status=ret[2])
-        resp = json.JSONDecoder().decode(ret[1])
-        resp_data = {
-            "vnfInstanceId": ignorcase_get(resp, "VNFInstanceID"),
-            "jobId": ignorcase_get(resp, "JobId")
+class InstantiateVnf(APIView):
+    @swagger_auto_schema(
+        request_body=InstantiateVnfRequestSerializer(),
+        responses={
+            status.HTTP_200_OK: InstScaleHealRespSerializer(),
+            status.HTTP_500_INTERNAL_SERVER_ERROR: "Internal error"
         }
-        logger.info("[%s]resp_data=%s", fun_name(), resp_data)
-    except Exception as e:
-        logger.error("Error occurred when instantiating VNF")
-        raise e
-    return Response(data=resp_data, status=ret[2])
-
-
-@api_view(http_method_names=['POST'])
-def terminate_vnf(request, *args, **kwargs):
-    try:
-        logger.debug("[%s] request.data=%s", fun_name(), request.data)
-        vnfm_id = ignorcase_get(kwargs, "vnfmid")
-        ret = get_vnfminfo_from_nslcm(vnfm_id)
-        if ret[0] != 0:
-            return Response(data={'error': ret[1]}, status=ret[2])
-        vnfm_info = json.JSONDecoder().decode(ret[1])
-        logger.debug("[%s] vnfm_info=%s", fun_name(), vnfm_info)
-        ret = restcall.call_req(
-            base_url=ignorcase_get(vnfm_info, "url"),
-            user=ignorcase_get(vnfm_info, "userName"),
-            passwd=ignorcase_get(vnfm_info, "password"),
-            auth_type=restcall.rest_no_auth,
-            resource="v1/vnfs/%s" % (ignorcase_get(kwargs, "vnfInstanceID")),
-            method='delete',
-            content=json.JSONEncoder().encode(request.data))
-        if ret[0] != 0:
-            return Response(data={'error': ret[1]}, status=ret[2])
-        resp = json.JSONDecoder().decode(ret[1])
-        resp_data = {
-            "vnfInstanceId": ignorcase_get(resp, "VNFInstanceID"),
-            "jobId": ignorcase_get(resp, "JobId")
+    )
+    def post(self, request, vnfmid):
+        try:
+            logger.debug("[%s] request.data=%s", fun_name(), request.data)
+            instantiateVnfRequestSerializer = InstantiateVnfRequestSerializer(data=request.data)
+            if not instantiateVnfRequestSerializer.is_valid():
+                raise Exception(instantiateVnfRequestSerializer.errors)
+
+            ret = get_vnfminfo_from_nslcm(vnfmid)
+            if ret[0] != 0:
+                raise Exception(ret[1])
+
+            vnfm_info = json.JSONDecoder().decode(ret[1])
+            logger.debug("[%s] vnfm_info=%s", fun_name(), vnfm_info)
+            vnf_package_id = ignorcase_get(instantiateVnfRequestSerializer.data, "vnfPackageId")
+            ret = vnfd_get(vnf_package_id)
+            if ret[0] != 0:
+                raise Exception(ret[1])
+
+            vnfd_info = json.JSONDecoder().decode(ret[1])
+            logger.debug("[%s] vnfd_info=%s", fun_name(), vnfd_info)
+            csar_id = ignorcase_get(vnfd_info, "csarId")
+            ret = vnfpackage_get(csar_id)
+            if ret[0] != 0:
+                raise Exception(ret[1])
+
+            vnf_package_info = json.JSONDecoder().decode(ret[1])
+            packageInfo = ignorcase_get(vnf_package_info, "packageInfo")
+            logger.debug("[%s] packageInfo=%s", fun_name(), packageInfo)
+            data = {
+                "NFVOID": 1,
+                "VNFMID": vnfmid,
+                "extension": {},
+            }
+            vnfdModel = json.loads(ignorcase_get(packageInfo, "vnfdModel"))
+            metadata = ignorcase_get(vnfdModel, "metadata")
+            vnfd_name = ignorcase_get(metadata, "name")
+            # TODO  convert sdc vnf package to vnf vender package
+            inputs = []
+            if "SPGW" in vnfd_name.upper():
+                data["VNFD"] = VNF_FTP + "SPGW"
+                inputs = load_json_file("SPGW" + "_inputs.json")
+            elif "MME" in vnfd_name.upper():
+                data["VNFD"] = VNF_FTP + "MME"
+                inputs = load_json_file("MME" + "_inputs.json")
+            else:
+                data["VNFD"] = ignorcase_get(packageInfo, "downloadUri")
+
+            data["VNFURL"] = data["VNFD"]
+
+            additionalParam = ignorcase_get(instantiateVnfRequestSerializer.data, "additionalParam")
+            for name, value in ignorcase_get(additionalParam, "inputs").items():
+                inputs.append({"name": name, "value": value})
+
+            data["extension"]["inputs"] = json.dumps(inputs)
+            data["extension"]["extVirtualLinks"] = ignorcase_get(additionalParam, "extVirtualLinks")
+            data["extension"]["vnfinstancename"] = ignorcase_get(instantiateVnfRequestSerializer.data, "vnfInstanceName")
+            data["extension"]["vnfid"] = data["VNFD"]
+            data["extension"]["multivim"] = 0
+            logger.debug("[%s] call_req data=%s", fun_name(), data)
+
+            ret = restcall.call_req(
+                base_url=ignorcase_get(vnfm_info, "url"),
+                user=ignorcase_get(vnfm_info, "userName"),
+                passwd=ignorcase_get(vnfm_info, "password"),
+                auth_type=restcall.rest_no_auth,
+                resource="v1/vnfs",
+                method='post',
+                content=json.JSONEncoder().encode(data))
+
+            logger.debug("[%s] call_req ret=%s", fun_name(), ret)
+            if ret[0] != 0:
+                raise Exception(ret[1])
+
+            resp = json.JSONDecoder().decode(ret[1])
+            resp_data = {
+                "vnfInstanceId": ignorcase_get(resp, "VNFInstanceID"),
+                "jobId": ignorcase_get(resp, "JobId")
+            }
+            logger.debug("[%s]resp_data=%s", fun_name(), resp_data)
+            instRespSerializer = InstScaleHealRespSerializer(data=resp_data)
+            if not instRespSerializer.is_valid():
+                raise Exception(instRespSerializer.errors)
+
+            logger.debug("[%s] instRespSerializer.data=%s", fun_name(), instRespSerializer.data)
+            return Response(data=instRespSerializer.data, status=status.HTTP_200_OK)
+        except Exception as e:
+            logger.error("Error occurred when instantiating VNF,error:%s", e.message)
+            logger.error(traceback.format_exc())
+            return Response(data={'error': 'InstantiateVnf expection'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
+
+
+class TerminateVnf(APIView):
+    @swagger_auto_schema(
+        request_body=TerminateVnfRequestSerializer(),
+        responses={
+            status.HTTP_200_OK: InstScaleHealRespSerializer(),
+            status.HTTP_500_INTERNAL_SERVER_ERROR: "Internal error"
+        }
+    )
+    def post(self, request, vnfmid, vnfInstanceId):
+        try:
+            logger.debug("[%s] request.data=%s", fun_name(), request.data)
+            terminate_vnf_request_serializer = TerminateVnfRequestSerializer(data=request.data)
+            if not terminate_vnf_request_serializer.is_valid():
+                raise Exception(terminate_vnf_request_serializer.errors)
+
+            ret = get_vnfminfo_from_nslcm(vnfmid)
+            if ret[0] != 0:
+                raise Exception(ret[1])
+
+            vnfm_info = json.JSONDecoder().decode(ret[1])
+            logger.debug("[%s] vnfm_info=%s", fun_name(), vnfm_info)
+            ret = restcall.call_req(
+                base_url=ignorcase_get(vnfm_info, "url"),
+                user=ignorcase_get(vnfm_info, "userName"),
+                passwd=ignorcase_get(vnfm_info, "password"),
+                auth_type=restcall.rest_no_auth,
+                resource="v1/vnfs/%s" % vnfInstanceId,
+                method='delete',
+                content=json.JSONEncoder().encode(terminate_vnf_request_serializer.data))
+            if ret[0] != 0:
+                raise Exception(ret[1])
+
+            resp = json.JSONDecoder().decode(ret[1])
+            resp_data = {
+                "vnfInstanceId": ignorcase_get(resp, "VNFInstanceID"),
+                "jobId": ignorcase_get(resp, "JobId")
+            }
+            logger.debug("[%s]resp_data=%s", fun_name(), resp_data)
+            terminateRespSerializer = InstScaleHealRespSerializer(data=resp_data)
+            if not terminateRespSerializer.is_valid():
+                raise Exception(terminateRespSerializer.errors)
+            return Response(data=terminateRespSerializer.data, status=status.HTTP_200_OK)
+        except Exception as e:
+            logger.error("Error occurred when terminating VNF,error: %s", e.message)
+            logger.error(traceback.format_exc())
+            return Response(data={'error': 'TerminateVnf expection'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
+
+
+class QueryVnf(APIView):
+    @swagger_auto_schema(
+        responses={
+            status.HTTP_200_OK: QueryVnfResponseSerializer(),
+            status.HTTP_500_INTERNAL_SERVER_ERROR: "Internal error"
         }
-        logger.debug("[%s]resp_data=%s", fun_name(), resp_data)
-    except Exception as e:
-        logger.error("Error occurred when terminating VNF")
-        raise e
-    return Response(data=resp_data, status=ret[2])
-
-
-@api_view(http_method_names=['GET'])
-def query_vnf(request, *args, **kwargs):
-    try:
-        logger.debug("[%s] request.data=%s", fun_name(), request.data)
-        vnfm_id = ignorcase_get(kwargs, "vnfmid")
-        ret = get_vnfminfo_from_nslcm(vnfm_id)
-        if ret[0] != 0:
-            return Response(data={'error': ret[1]}, status=ret[2])
-        vnfm_info = json.JSONDecoder().decode(ret[1])
-        logger.debug("[%s] vnfm_info=%s", fun_name(), vnfm_info)
-        ret = restcall.call_req(
-            base_url=ignorcase_get(vnfm_info, "url"),
-            user=ignorcase_get(vnfm_info, "userName"),
-            passwd=ignorcase_get(vnfm_info, "password"),
-            auth_type=restcall.rest_no_auth,
-            resource="v1/vnfs/%s" % (ignorcase_get(kwargs, "vnfInstanceID")),
-            method='get',
-            content=json.JSONEncoder().encode({}))
-        if ret[0] != 0:
-            return Response(data={'error': ret[1]}, status=ret[2])
-        resp = json.JSONDecoder().decode(ret[1])
-        vnf_status = ignorcase_get(resp, "vnfinstancestatus")
-        resp_data = {"vnfInfo": {"vnfStatus": vnf_status}}
-        logger.debug("[%s]resp_data=%s", fun_name(), resp_data)
-    except Exception as e:
-        logger.error("Error occurred when querying VNF information.")
-        raise e
-    return Response(data=resp_data, status=ret[2])
-
-
-@api_view(http_method_names=['GET'])
-def operation_status(request, *args, **kwargs):
-    data = {}
-    try:
-        logger.debug("[%s] request.data=%s", fun_name(), request.data)
-        vnfm_id = ignorcase_get(kwargs, "vnfmid")
-        ret = get_vnfminfo_from_nslcm(vnfm_id)
-        if ret[0] != 0:
-            return Response(data={'error': ret[1]}, status=ret[2])
-        vnfm_info = json.JSONDecoder().decode(ret[1])
-        logger.debug("[%s] vnfm_info=%s", fun_name(), vnfm_info)
-        operation_status_url = '/v1/jobs/{jobId}?NFVOID={nfvoId}&VNFMID={vnfmId}&ResponseID={responseId}'
-        ret = restcall.call_req(
-            base_url=ignorcase_get(vnfm_info, 'url'),
-            user=ignorcase_get(vnfm_info, 'userName'),
-            passwd=ignorcase_get(vnfm_info, 'password'),
-            auth_type=restcall.rest_no_auth,
-            resource=operation_status_url.format(jobId=ignorcase_get(kwargs, 'jobid'), nfvoId=1,
-                                                 vnfmId=ignorcase_get(kwargs, 'vnfmid'),
-                                                 responseId=ignorcase_get(request.GET, 'responseId')),
-            method='get',
-            content=json.JSONEncoder().encode(data))
-
-        if ret[0] != 0:
-            return Response(data={'error': ret[1]}, status=ret[2])
-        resp_data = json.JSONDecoder().decode(ret[1])
-        logger.info("[%s]resp_data=%s", fun_name(), resp_data)
-    except Exception as e:
-        logger.error("Error occurred when getting operation status information.")
-        raise e
-    return Response(data=resp_data, status=ret[2])
-
-
-@api_view(http_method_names=['PUT'])
-def grantvnf(request, *args, **kwargs):
-    logger.info("=====grantvnf=====")
-    try:
-        logger.info("req_data = %s", request.data)
-        grant_vnf_param_map = {
-            "VNFMID": "",
-            "NFVOID": "",
-            "VIMID": "",
-            "ExVIMIDList": "",
-            "ExVIMID": "",
-            "Tenant": "",
-            "VNFInstanceID": "vnfInstanceId",
-            "OperationRight": "",
-            "VMList": "",
-            "VMFlavor": "",
-            "VMNumber": ""
+    )
+    def get(self, request, vnfmid, vnfInstanceId):
+        try:
+            logger.debug("[%s] request.data=%s", fun_name(), request.data)
+            ret = get_vnfminfo_from_nslcm(vnfmid)
+            if ret[0] != 0:
+                raise Exception(ret[1])
+
+            vnfm_info = json.JSONDecoder().decode(ret[1])
+            logger.debug("[%s] vnfm_info=%s", fun_name(), vnfm_info)
+            ret = restcall.call_req(
+                base_url=ignorcase_get(vnfm_info, "url"),
+                user=ignorcase_get(vnfm_info, "userName"),
+                passwd=ignorcase_get(vnfm_info, "password"),
+                auth_type=restcall.rest_no_auth,
+                resource="v1/vnfs/%s" % vnfInstanceId,
+                method='get',
+                content=json.JSONEncoder().encode({}))
+            if ret[0] != 0:
+                raise Exception(ret[1])
+
+            resp = json.JSONDecoder().decode(ret[1])
+            vnf_status = ignorcase_get(resp, "vnfinstancestatus")
+            resp_data = {"vnfInfo": {"vnfStatus": vnf_status}}
+            logger.debug("[%s]resp_data=%s", fun_name(), resp_data)
+            queryVnfResponseSerializer = QueryVnfResponseSerializer(data=resp_data)
+            if not queryVnfResponseSerializer.is_valid():
+                raise Exception(queryVnfResponseSerializer.errors)
+            return Response(data=queryVnfResponseSerializer.data, status=status.HTTP_200_OK)
+        except Exception as e:
+            logger.error("Error occurred when querying VNF information,error:%s", e.message)
+            logger.error(traceback.format_exc())
+            return Response(data={'error': 'QueryVnf expection'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
+
+
+class JobView(APIView):
+    @swagger_auto_schema(
+        manual_parameters=[
+            openapi.Parameter('responseId',
+                              openapi.IN_QUERY,
+                              "responseId",
+                              type=openapi.TYPE_INTEGER
+                              ),
+        ],
+        responses={
+            status.HTTP_200_OK: JobQueryRespSerializer(),
+            status.HTTP_500_INTERNAL_SERVER_ERROR: "Internal error"
         }
-        data = mapping_conv(grant_vnf_param_map, request.data)
-        data["vnfDescriptorId"] = ""
-        if ignorcase_get(request.data, "operationright") == 0:
-            data["lifecycleOperation"] = "Instantiate"
-            data["addresource"] = []
-            for vm in ignorcase_get(request.data, "vmlist"):
-                for i in range(int(ignorcase_get(vm, "vmnumber"))):
-                    data["addresource"].append(
-                        {
-                            "type": "vdu",
-                            "resourceDefinitionId": i,
-                            "vdu": ignorcase_get(vm, "vmflavor"),
-                            "vimid": ignorcase_get(vm, "vimid"),
-                            "tenant": ignorcase_get(vm, "tenant")})
-
-        data["additionalparam"] = {}
-        data["additionalparam"]["vnfmid"] = ignorcase_get(request.data, "vnfmid")
-        data["additionalparam"]["vimid"] = ignorcase_get(request.data, "vimid")
-        data["additionalparam"]["tenant"] = ignorcase_get(request.data, "tenant")
-
-        ret = req_by_msb('api/nslcm/v1/ns/grantvnf', "POST", content=json.JSONEncoder().encode(data))
-        logger.info("ret = %s", ret)
-        if ret[0] != 0:
-            return Response(data={'error': ret[1]}, status=ret[2])
-        resp = json.JSONDecoder().decode(ret[1])
-        resp_data = {
-            'vimid': ignorcase_get(resp['vim'], 'vimid'),
-            'tenant': ignorcase_get(ignorcase_get(resp['vim'], 'accessinfo'), 'tenant')
+    )
+    def get(self, request, vnfmid, jobid):
+        try:
+            logger.debug("[%s] request.data=%s", fun_name(), request.data)
+            ret = get_vnfminfo_from_nslcm(vnfmid)
+            if ret[0] != 0:
+                raise Exception(ret[1])
+
+            vnfm_info = json.JSONDecoder().decode(ret[1])
+            logger.debug("[%s] vnfm_info=%s", fun_name(), vnfm_info)
+            operation_status_url = '/v1/jobs/{jobId}?NFVOID={nfvoId}&VNFMID={vnfmId}&ResponseID={responseId}'
+            responseId = ignorcase_get(request.GET, 'responseId')
+            query_url = operation_status_url.format(jobId=jobid, nfvoId=1, vnfmId=vnfmid, responseId=responseId)
+            ret = restcall.call_req(
+                base_url=ignorcase_get(vnfm_info, 'url'),
+                user=ignorcase_get(vnfm_info, 'userName'),
+                passwd=ignorcase_get(vnfm_info, 'password'),
+                auth_type=restcall.rest_no_auth,
+                resource=query_url,
+                method='get',
+                content={})
+
+            if ret[0] != 0:
+                raise Exception(ret[1])
+
+            resp_data = json.JSONDecoder().decode(ret[1])
+            logger.debug("[%s]resp_data=%s", fun_name(), resp_data)
+            jobQueryRespSerializer = JobQueryRespSerializer(data=resp_data)
+            if not jobQueryRespSerializer.is_valid():
+                raise Exception(jobQueryRespSerializer.errors)
+
+            return Response(data=jobQueryRespSerializer.data, status=status.HTTP_200_OK)
+        except Exception as e:
+            logger.error("Error occurred when getting operation status information,error:%s", e.message)
+            logger.error(traceback.format_exc())
+            return Response(data={'error': 'QueryJob expection'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
+
+
+class GrantVnf(APIView):
+    @swagger_auto_schema(
+        request_body=GrantReqSerializer(),
+        responses={
+            status.HTTP_201_CREATED: GrantRespSerializer(),
+            status.HTTP_500_INTERNAL_SERVER_ERROR: 'Internal error'
         }
-        logger.info("[%s]resp_data=%s", fun_name(), resp_data)
-    except Exception as e:
-        logger.error("Error occurred in Grant VNF.")
-        raise e
-    return Response(data=resp_data, status=ret[2])
+    )
+    def put(self, request):
+        logger.debug("=====GrantVnf=====")
+        try:
+            logger.debug("request.data = %s", request.data)
+            grantReqSerializer = GrantReqSerializer(data=request.data)
+            if not grantReqSerializer.is_valid():
+                raise Exception(grantReqSerializer.errors)
+
+            logger.debug("grantReqSerializer.data = %s", grantReqSerializer.data)
+            req_data = {
+                "vnfInstanceId": ignorcase_get(grantReqSerializer.data, "vnfistanceid"),
+                "vnfDescriptorId": "",
+                "addresource": [],
+                "additionalparam": {
+                    "vnfmid": ignorcase_get(grantReqSerializer.data, "vnfmid"),
+                    "vimid": ignorcase_get(grantReqSerializer.data, "vimid"),
+                    "tenant": ignorcase_get(grantReqSerializer.data, "tenant")
+                }
+            }
+            if ignorcase_get(grantReqSerializer.data, "operationright") == 0:
+                req_data["lifecycleOperation"] = "Instantiate"
+                for vm in ignorcase_get(grantReqSerializer.data, "vmlist"):
+                    for i in range(int(ignorcase_get(vm, "VMNumber"))):
+                        req_data["addresource"].append(
+                            {
+                                "type": "vdu",
+                                "resourceDefinitionId": i,
+                                "vdu": ignorcase_get(vm, "VMFlavor"),
+                                "vimid": ignorcase_get(vm, "vimid"),
+                                "tenant": ignorcase_get(vm, "tenant")})
+
+            logger.debug("req_data=%s", req_data)
+            ret = req_by_msb('api/nslcm/v1/ns/grantvnf', "POST", content=json.JSONEncoder().encode(req_data))
+            logger.info("ret = %s", ret)
+            if ret[0] != 0:
+                raise Exception(ret[1])
+
+            resp = json.JSONDecoder().decode(ret[1])
+            resp_data = {
+                'vimid': ignorcase_get(resp['vim'], 'vimid'),
+                'tenant': ignorcase_get(ignorcase_get(resp['vim'], 'accessinfo'), 'tenant')
+            }
+            logger.debug("[%s]resp_data=%s", fun_name(), resp_data)
+            grantRespSerializer = GrantRespSerializer(data=resp_data)
+            if not grantRespSerializer.is_valid():
+                raise Exception(grantRespSerializer.errors)
+
+            logger.debug("grantRespSerializer.data=%s", grantRespSerializer.data)
+            return Response(data=grantRespSerializer.data, status=status.HTTP_201_CREATED)
+        except Exception as e:
+            logger.error("Error occurred in Grant VNF, error: %s", e.message)
+            logger.error(traceback.format_exc())
+            return Response(data={'error': 'Grant expection'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
 
 
 class Notify(APIView):
@@ -321,33 +411,24 @@ class Notify(APIView):
     )
     def post(self, request):
         try:
-            logger.info("[%s]req_data = %s", fun_name(), request.data)
+            logger.debug("[%s]request.data = %s", fun_name(), request.data)
             notifyReqSerializer = NotifyReqSerializer(data=request.data)
             if not notifyReqSerializer.is_valid():
                 raise Exception(notifyReqSerializer.errors)
 
-            notify_param_map = {
-                "NFVOID": "",
-                "VNFMID": "VNFMID",
-                "VIMID": "vimid",
-                "VNFInstanceID": "vnfInstanceId",
-                "TimeStamp": "",
-                "EventType": "operation",
-                "VMList": "",
-                "VMFlavor": "",
-                "VMNumber": "",
-                "VMIDlist": "",
-                "VMUUID": ""
+            logger.debug("[%s]notifyReqSerializer.data = %s", fun_name(), notifyReqSerializer.data)
+            req_data = {
+                "status": "result",
+                "vnfInstanceId": ignorcase_get(notifyReqSerializer.data, "vnfinstanceid"),
+                "vnfmId": ignorcase_get(notifyReqSerializer.data, "vnfmid"),
+                "vimId": ignorcase_get(notifyReqSerializer.data, "vimid"),
+                "operation": ignorcase_get(notifyReqSerializer.data, "EventType"),
+                "jobId": "notMust",
+                "affectedVl": [],
+                "affectedCp": [],
+                "affectedVirtualStorage": [],
+                "affectedVnfc": [],
             }
-            data = mapping_conv(notify_param_map, notifyReqSerializer.data)
-            logger.info("[%s]data = %s", fun_name(), data)
-
-            data["status"] = "result"
-            data["jobId"] = "notMust"
-            data["affectedVnfc"] = []
-            data["affectedVl"] = []
-            data["affectedVirtualStorage"] = []
-            data["affectedCp"] = []
 
             extension = ignorcase_get(notifyReqSerializer.data, "extension")
             openo_notification = ignorcase_get(extension, "openo_notification")
@@ -362,10 +443,10 @@ class Notify(APIView):
                 affectedcps = ignorcase_get(ignorcase_get(notifyReqSerializer.data, "extension"), "affectedcp")
                 vnfdmodule = ignorcase_get(ignorcase_get(notifyReqSerializer.data, "extension"), "vnfdmodule")
 
-            data["vnfdmodule"] = vnfdmodule
+            req_data["vnfdmodule"] = vnfdmodule
 
             for affectedvnfc in affectedvnfcs:
-                data["affectedVnfc"].append({
+                req_data["affectedVnfc"].append({
                     "vnfcInstanceId": ignorcase_get(affectedvnfc, "vnfcInstanceId"),
                     "vduId": ignorcase_get(affectedvnfc, "vduId"),
                     "changeType": ignorcase_get(affectedvnfc, "changeType"),
@@ -375,7 +456,7 @@ class Notify(APIView):
                 })
 
             for affectedvl in affectedvls:
-                data["affectedVl"].append({
+                req_data["affectedVl"].append({
                     "vlInstanceId": ignorcase_get(affectedvl, "virtualLinkInstanceId"),
                     "changeType": ignorcase_get(affectedvl, "changeType"),
                     "vimId": ignorcase_get(ignorcase_get(affectedvl, "networkResource"), "vimId"),
@@ -388,22 +469,24 @@ class Notify(APIView):
                 })
 
             for affectedcp in affectedcps:
-                data["affectedCp"].append(affectedcp)
+                req_data["affectedCp"].append(affectedcp)
 
-            notify_url = 'api/nslcm/v1/ns/{vnfmid}/vnfs/{vnfInstanceId}/Notify'
-            ret = req_by_msb(notify_url.format(vnfmid=ignorcase_get(data, 'VNFMID'),
-                                               vnfInstanceId=ignorcase_get(data, 'vnfinstanceid')),
-                             "POST", content=json.JSONEncoder().encode(data))
+            vnfmid = ignorcase_get(req_data, 'vnfmId')
+            vnfInstanceId = ignorcase_get(req_data, 'vnfinstanceid')
+            notify_url = 'api/nslcm/v1/ns/%s/vnfs/%s/Notify' % (vnfmid, vnfInstanceId)
+            logger.debug("notify_url = %s", notify_url)
+            logger.debug("req_data = %s", req_data)
+            ret = req_by_msb(notify_url, "POST", content=json.JSONEncoder().encode(req_data))
 
-            logger.info("[%s]data = %s", fun_name(), ret)
+            logger.debug("[%s]data = %s", fun_name(), ret)
             if ret[0] != 0:
                 raise Exception(ret[1])
 
-            return Response(data=None, status=ret[2])
+            return Response(data=None, status=status.HTTP_200_OK)
         except Exception as e:
             logger.error("Error occurred in LCM notification,error: %s", e.message)
             logger.error(traceback.format_exc())
-            return Response(data={'error': 'notify expection'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
+            return Response(data={'error': 'Notify expection'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
 
 
 class Scale(APIView):
@@ -415,10 +498,10 @@ class Scale(APIView):
         }
     )
     def post(self, request, vnfmid, vnfInstanceId):
-        logger.info("====scale_vnf===")
+        logger.debug("====scale_vnf===")
         try:
-            logger.info("request.data = %s", request.data)
-            logger.info("requested_url = %s", request.get_full_path())
+            logger.debug("request.data = %s", request.data)
+            logger.debug("requested_url = %s", request.get_full_path())
             scaleReqSerializer = ScaleReqSerializer(data=request.data)
             if not scaleReqSerializer.is_valid():
                 raise Exception(scaleReqSerializer.errors)
@@ -435,11 +518,14 @@ class Scale(APIView):
                 'vnfmid': vnfmid,
                 'nfvoid': 1,
                 'scaletype': '0' if scale_type == 'SCALE_OUT' else '1',
-                'vmlist': [{'VMNumber': number_of_steps, 'VMFlavor': aspect_id}],
+                'vmlist': [{
+                    'VMNumber': number_of_steps,
+                    'VMFlavor': aspect_id
+                }],
                 'extension': ''
             }
 
-            logger.info("data = %s", data)
+            logger.debug("data = %s", data)
             ret = restcall.call_req(
                 base_url=ignorcase_get(vnfm_info, "url"),
                 user=ignorcase_get(vnfm_info, "userName"),
@@ -448,21 +534,20 @@ class Scale(APIView):
                 resource='/v1/vnfs/{vnfInstanceID}/scale'.format(vnfInstanceID=vnfInstanceId),
                 method='put',  # POST
                 content=json.JSONEncoder().encode(data))
-            logger.info("ret=%s", ret)
+            logger.debug("ret=%s", ret)
             if ret[0] != 0:
                 raise Exception('scale error')
 
-            resp_data = json.JSONDecoder().decode(ret[1])
-            logger.info("resp_data=%s", resp_data)
-            scaleRespSerializer = InstScaleHealRespSerializer(data=resp_data)
+            scaleRespSerializer = InstScaleHealRespSerializer(data=json.JSONDecoder().decode(ret[1]))
             if not scaleRespSerializer.is_valid():
                 raise Exception(scaleRespSerializer.errors)
 
+            logger.debug("scaleRespSerializer.data=%s", scaleRespSerializer.data)
             return Response(data=scaleRespSerializer.data, status=status.HTTP_202_ACCEPTED)
         except Exception as e:
             logger.error("Error occurred when scaling VNF,error:%s", e.message)
             logger.error(traceback.format_exc())
-            return Response(data={'error': 'scale expection'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
+            return Response(data={'error': 'Scale expection'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
 
 
 class Heal(APIView):
@@ -474,31 +559,34 @@ class Heal(APIView):
         }
     )
     def post(self, request, vnfmid, vnfInstanceId):
-        logger.info("====heal_vnf===")
+        logger.debug("====heal_vnf===")
         try:
-            logger.info("request.data = %s", request.data)
-            logger.info("requested_url = %s", request.get_full_path())
+            logger.debug("request.data = %s", request.data)
+            logger.debug("requested_url = %s", request.get_full_path())
             healReqSerializer = HealReqSerializer(data=request.data)
             if not healReqSerializer.is_valid():
                 raise Exception(healReqSerializer.errors)
 
+            logger.debug("healReqSerializer.data = %s", healReqSerializer.data)
+            logger.debug("vnfmid = %s", vnfmid)
             ret = get_vnfminfo_from_nslcm(vnfmid)
             if ret[0] != 0:
                 raise Exception(ret[1])
 
             vnfm_info = json.JSONDecoder().decode(ret[1])
-            data = {}
-            data['action'] = ignorcase_get(healReqSerializer.data, 'action')
+            req_data = {
+                "action": ignorcase_get(healReqSerializer.data, 'action'),
+                "lifecycleoperation": "operate",
+                "isgrace": "force",
+                "affectedvm": [],
+            }
             affectedvm = ignorcase_get(healReqSerializer.data, 'affectedvm')
-            data['affectedvm'] = []
             if isinstance(affectedvm, list):
-                data['affectedvm'] = affectedvm
+                req_data['affectedvm'] = affectedvm
             else:
-                data['affectedvm'].append(affectedvm)
-            data['lifecycleoperation'] = 'operate'
-            data['isgrace'] = 'force'
+                req_data['affectedvm'].append(affectedvm)
 
-            logger.info("data = %s", data)
+            logger.debug("req_data = %s", req_data)
             ret = restcall.call_req(
                 base_url=ignorcase_get(vnfm_info, "url"),
                 user=ignorcase_get(vnfm_info, "userName"),
@@ -506,21 +594,21 @@ class Heal(APIView):
                 auth_type=restcall.rest_no_auth,
                 resource='/api/v1/nf_m_i/nfs/{vnfInstanceID}/vms/operation'.format(vnfInstanceID=vnfInstanceId),
                 method='post',
-                content=json.JSONEncoder().encode(data))
-            logger.info("ret=%s", ret)
+                content=json.JSONEncoder().encode(req_data))
+            logger.debug("ret=%s", ret)
             if ret[0] != 0:
                 raise Exception('heal error')
-            resp_data = json.JSONDecoder().decode(ret[1])
-            logger.info("resp_data=%s", resp_data)
-            healRespSerializer = InstScaleHealRespSerializer(data=resp_data)
+
+            healRespSerializer = InstScaleHealRespSerializer(data=json.JSONDecoder().decode(ret[1]))
             if not healRespSerializer.is_valid():
                 raise Exception(healRespSerializer.errors)
 
+            logger.debug("healRespSerializer.data=%s", healRespSerializer.data)
             return Response(data=healRespSerializer.data, status=status.HTTP_202_ACCEPTED)
         except Exception as e:
             logger.error("Error occurred when healing VNF,error:%s", e.message)
             logger.error(traceback.format_exc())
-            return Response(data={'error': 'heal expection'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
+            return Response(data={'error': 'Heal expection'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
 
 
 def get_vdus(nf_model, aspect_id):
@@ -545,6 +633,66 @@ def get_vdus(nf_model, aspect_id):
     return members
 
 
-@api_view(http_method_names=['GET'])
-def samples(request, *args, **kwargs):
-    return Response(data={"status": "ok"})
+class SampleList(APIView):
+    @swagger_auto_schema(
+        responses={
+            status.HTTP_200_OK: 'Successfully'})
+    def get(self, request):
+        logger.debug("get")
+        return Response({"status": "active"})
+
+
+class Subscribe(APIView):
+    def get(self, request):
+        logger.debug("====Subscribe get====")
+        resp_data = {
+            "subscriptions": [{
+                "subscribeid": "cdbddb00-452c-11e9-91e8-acc860114657",
+                "filter": [{
+                    "vendor": "ZTE",
+                    "type": "vCPE",
+                }],
+                "notificationuri": " https://127.0.0.1:80/v2/vnfm/vnfds/notification",
+            }]
+        }
+        return Response(data=resp_data, status=status.HTTP_200_OK)
+
+    def post(self, request):
+        logger.debug("====Subscribe post====")
+        resp_data = {"subscribeid": "cdbddb00-452c-11e9-91e8-acc860114657"}
+        return Response(data=resp_data, status=status.HTTP_201_CREATED)
+
+
+class SubscribeDetail(APIView):
+    def delete(self, request, subscribeId):
+        logger.debug("====SubscribeDetail delete %s====", subscribeId)
+        return Response(status=status.HTTP_204_NO_CONTENT)
+
+
+class VnfPkgs(APIView):
+    def get(self, request):
+        logger.debug("====VnfPkgs get====")
+        resp_data = {
+            "data": [{
+                "packageid": "924fc980-4530-11e9-ae68-acc860114657",
+                "vendor": "ZTE",
+                "type": "vCPE",
+                "vnfdfile": "MRP6600_FS_SRIOV_4NIC_200W.zip",
+                "imagefiles": ["MRP6600_FS_SRIOV_MRPISU_IMGV500R008C20SPC030T.tar"],
+                "swfiles": ["MRP6600_SRV_V500R008C20SPC030T.tar"],
+                "description": "This is a service for vCPE.",
+            }]
+        }
+        return Response(data=resp_data, status=status.HTTP_200_OK)
+
+
+class VnfPkg(APIView):
+    def get(self, request, packageId, fileName):
+        logger.debug("====VnfPkg get====%s, %s", packageId, fileName)
+        file_range = request.META.get('RANGE')
+        logger.debug('file_range: %s' % file_range)
+        # TODO: get filepath
+        local_file_path = fileName
+        start, end = parse_file_range(local_file_path, file_range)
+        file_iterator = read(local_file_path, start, end)
+        return StreamingHttpResponse(file_iterator, status=status.HTTP_200_OK)