Beispiel #1
0
    def post(self, request, job_id):
        job_result_ok = {'result': 'ok'}

        logger.debug("Enter JobView:post, %s, %s ", job_id, request.data)
        jobs = JobUtil.query_job_status(job_id)
        if len(jobs) > 0 and jobs[-1].errcode == '255':
            return Response(data=job_result_ok)

        request_serializer = PostJobRequestSerializer(data=request.data)
        validataion_error = self.handleValidatonError(request_serializer, True)
        if validataion_error:
            return validataion_error

        requestData = request_serializer.data
        progress = ignore_case_get(requestData, "progress")
        desc = ignore_case_get(requestData, "desc", '%s' % progress)
        errcode = '0' if ignore_case_get(
            requestData, 'errcode') in ('true', 'active') else '255'
        logger.debug("errcode=%s", errcode)
        JobUtil.add_job_status(job_id, progress, desc, error_code=errcode)

        response_serializer = PostJobResponseResultSerializer(
            data=job_result_ok)
        validataion_error = self.handleValidatonError(response_serializer,
                                                      False)
        if validataion_error:
            return validataion_error

        return Response(data=response_serializer.data,
                        status=status.HTTP_202_ACCEPTED)
def pnf_model_parser(request, *args, **kwargs):
    csar_id = ignore_case_get(request.data, "csarId")
    inputs = ignore_case_get(request.data, "inputs")
    logger.debug("Enter %s, csar_id=%s, inputs=%s", fun_name(), csar_id,
                 inputs)
    ret = PnfDescriptor().parse_pnfd(csar_id, inputs)
    logger.info("Leave %s, Return value is %s", fun_name(), ret)
    if ret[0] != 0:
        return Response(data={'error': ret[1]},
                        status=status.HTTP_500_INTERNAL_SERVER_ERROR)
    response = validate_data(ret[1], ParseModelResponseSerializer)
    return Response(data=response.data, status=status.HTTP_202_ACCEPTED)
Beispiel #3
0
 def create(self, data):
     logger.debug("Start Create Subscription... ")
     self.filter = ignore_case_get(data, "filter", {})
     self.callback_uri = ignore_case_get(data, "callbackUri")
     self.authentication = ignore_case_get(data, "authentication", {})
     self.subscription_id = str(uuid.uuid4())
     self.check_callbackuri_connection()
     self.check_valid_auth_info()
     self.check_filter_types()
     self.check_valid()
     self.save_db()
     subscription = \
         NsdmSubscriptionModel.objects.get(
             subscriptionid=self.subscription_id)
     return self.fill_resp_data(subscription)
Beispiel #4
0
 def __init__(self, data):
     self.data = data
     self.filter = ignore_case_get(self.data, "filter", {})
     self.callback_uri = ignore_case_get(self.data, "callbackUri")
     self.authentication = ignore_case_get(self.data, "authentication", {})
     self.notification_types = ignore_case_get(self.filter, "notificationTypes", [])
     self.operation_states = ignore_case_get(self.filter, "operationalState", [])
     self.usage_states = ignore_case_get(self.filter, "usageState", [])
     self.vnfd_id = ignore_case_get(self.filter, "vnfdId", [])
     self.vnf_pkg_id = ignore_case_get(self.filter, "vnfPkgId", [])
     self.vnf_products_from_provider = \
         ignore_case_get(self.filter, "vnfProductsFromProviders", [])
    def upload_vnf_pkg_from_uri(self):
        logger.info("Start to upload VNF packge(%s) from URI..." %
                    self.vnf_pkg_id)
        vnf_pkg = VnfPackageModel.objects.filter(vnfPackageId=self.vnf_pkg_id)
        if vnf_pkg[0].onboardingState != const.PKG_STATUS.CREATED:
            logger.error("VNF package(%s) is not CREATED" % self.vnf_pkg_id)
            raise CatalogException("VNF package (%s) is not created" %
                                   self.vnf_pkg_id)
        vnf_pkg.update(onboardingState=const.PKG_STATUS.UPLOADING)
        send_notification(self.vnf_pkg_id,
                          const.PKG_NOTIFICATION_TYPE.ONBOARDING,
                          const.PKG_CHANGE_TYPE.OP_STATE_CHANGE)

        uri = ignore_case_get(self.data, "addressInformation")
        response = urllib.request.urlopen(uri)

        local_file_dir = os.path.join(CATALOG_ROOT_PATH, self.vnf_pkg_id)
        self.upload_file_name = os.path.join(local_file_dir,
                                             os.path.basename(uri))
        if not os.path.exists(local_file_dir):
            fileutil.make_dirs(local_file_dir)
        with open(self.upload_file_name, "wt") as local_file:
            local_file.write(response.read())
        response.close()
        logger.info('VNF packge(%s) has been uploaded.' % self.vnf_pkg_id)
Beispiel #6
0
def nspackages_rc(request, *args, **kwargs):
    logger.debug("Enter %s, method is %s", fun_name(), request.method)
    ret, normal_status, response_serializer, validation_error = None, None, None, None

    if request.method == 'GET':
        # Gets ns package list
        ret = sdc_ns_package.ns_get_csars()
        normal_status = status.HTTP_200_OK

        if ret[0] == 0:
            response_serializer = NsPackagesSerializer(data=ret[1])
            validation_error = handleValidatonError(response_serializer, False)
            if validation_error:
                return validation_error
    elif request.method == 'POST':
        # Distributes the package accroding to the given csarId
        request_serializer = NsPackageDistributeRequestSerializer(
            data=request.data)
        validation_error = handleValidatonError(request_serializer, True)
        if validation_error:
            return validation_error

        csar_id = ignore_case_get(request.data, "csarId")
        logger.debug("csar_id is %s", csar_id)
        ret = sdc_ns_package.ns_on_distribute(csar_id)
        normal_status = status.HTTP_202_ACCEPTED

    logger.debug("Leave %s, Return value is %s", fun_name(), ret)
    if ret[0] != 0:
        return Response(data={'error': ret[1]},
                        status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    return Response(data=ret[1], status=normal_status)
 def create(self, data, csar_id=None):
     """
     Create a Service package
     :param data:
     :param csar_id:
     :return:
     """
     logger.info('Start to create a ServiceD...')
     user_defined_data = ignore_case_get(data, 'userDefinedData', {})
     data = {
         'id': csar_id if csar_id else str(uuid.uuid4()),
         'servicedOnboardingState': PKG_STATUS.CREATED,
         'servicedOperationalState': PKG_STATUS.DISABLED,
         'servicedUsageState': PKG_STATUS.NOT_IN_USE,
         'userDefinedData': user_defined_data,
         '_links': None  # TODO
     }
     ServicePackageModel.objects.create(
         servicePackageId=data['id'],
         onboardingState=data['servicedOnboardingState'],
         operationalState=data['servicedOperationalState'],
         usageState=data['servicedUsageState'],
         userDefinedData=json.dumps(user_defined_data))
     logger.info('A ServiceD(%s) has been created.' % data['id'])
     return data
Beispiel #8
0
def nf_rd_csar(request, *args, **kwargs):
    csar_id = ignore_case_get(kwargs, "csarId")
    logger.info("Enter %s, method is %s, csar_id is %s", fun_name(),
                request.method, csar_id)
    ret, normal_status, response_serializer, validation_error = None, None, None, None

    if request.method == 'GET':
        ret = sdc_vnf_package.nf_get_csar(csar_id)
        normal_status = status.HTTP_200_OK
        response_serializer = NfPackageSerializer(data=ret[1])

    elif request.method == 'DELETE':
        job_id = str(uuid.uuid4())
        sdc_vnf_package.NfPkgDeleteThread(csar_id, job_id).start()
        ret = [0, {"jobId": job_id}]
        normal_status = status.HTTP_202_ACCEPTED
        response_serializer = PostJobResponseSerializer(data=ret[1])

    logger.info("Leave %s, Return value is %s", fun_name(), ret)
    if ret[0] != 0:
        return Response(data={'error': ret[1]},
                        status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    validation_error = handleValidatonError(response_serializer, False)
    if validation_error:
        return validation_error

    return Response(data=response_serializer.data, status=normal_status)
Beispiel #9
0
def service_rd_csar(request, *args, **kwargs):
    csar_id = ignore_case_get(kwargs, "csarId")
    logger.info("Enter %s, method is %s, csar_id is %s", fun_name(),
                request.method, csar_id)

    if request.method == 'GET':
        try:
            ret = ServicePackage().get_csar(csar_id)
            response_serializer = ServicePackageSerializer(data=ret)
            validation_error = handleValidatonError(response_serializer, False)
            if validation_error:
                return validation_error
            return Response(data=ret, status=status.HTTP_200_OK)
        except PackageNotFoundException as e:
            error_status = status.HTTP_404_NOT_FOUND
            return Response(data=fmt_error_rsp(e.args[0], error_status),
                            status=error_status)
        except Exception as e:
            error_status = status.HTTP_500_INTERNAL_SERVER_ERROR
            return Response(data=fmt_error_rsp(e.args[0], error_status),
                            status=error_status)

    elif request.method == 'DELETE':
        try:
            ServicePackage().delete_csar(csar_id)
            return Response(status=status.HTTP_204_NO_CONTENT)
        except PackageNotFoundException as e:
            error_status = status.HTTP_404_NOT_FOUND
            return Response(data=fmt_error_rsp(e.args[0], error_status),
                            status=error_status)
        except Exception as e:
            error_status = status.HTTP_500_INTERNAL_SERVER_ERROR
            return Response(data=fmt_error_rsp(e.args[0], error_status),
                            status=error_status)
Beispiel #10
0
def model_parser(request, *args, **kwargs):
    csar_id = ignore_case_get(request.data, "csarId")
    package_type = ignore_case_get(request.data, "packageType")
    inputs = ignore_case_get(request.data, "inputs")
    logger.debug("Enter %s, csar_id=%s, package_type=%s, inputs=%s",
                 fun_name(), csar_id, package_type, inputs)

    if package_type.lower().__eq__("service"):
        try:
            ret = ServicePackage().parse_serviced(csar_id, inputs)
            response_serializer = ParseModelResponseSerializer(data=ret)
            validation_error = handleValidatonError(response_serializer, False)
            if validation_error:
                return validation_error
            return Response(data=response_serializer.data,
                            status=status.HTTP_202_ACCEPTED)
        except PackageNotFoundException as e:
            error_status = status.HTTP_404_NOT_FOUND
            return Response(data=fmt_error_rsp(e.args[0], error_status),
                            status=error_status)
        except Exception as e:
            error_status = status.HTTP_500_INTERNAL_SERVER_ERROR
            return Response(data=fmt_error_rsp(e.args[0], error_status),
                            status=error_status)
    elif package_type.lower().__eq__("ns"):
        ret = sdc_ns_package.parse_nsd(csar_id, inputs)
    elif package_type.lower().__eq__("vnf"):
        ret = sdc_vnf_package.parse_vnfd(csar_id, inputs)
    elif package_type.lower().__eq__("pnf"):
        ret = PnfDescriptor().parse_pnfd(csar_id, inputs)
    else:
        error_status = status.HTTP_400_BAD_REQUEST
        error_message = "Invalid package type, it should be one of [VNF, PNF, NS, Service]"
        return Response(data=fmt_error_rsp(error_message, error_status),
                        status=error_status)

    if ret[0] != 0:
        return Response(data={'error': ret[1]},
                        status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    response_serializer = ParseModelResponseSerializer(data=ret[1])
    validation_error = handleValidatonError(response_serializer, False)
    if validation_error:
        return validation_error

    return Response(data=response_serializer.data,
                    status=status.HTTP_202_ACCEPTED)
def process_notification(msg):
    logger.info('Receive a callback notification, nb of resources: %s',
                len(msg['resources']))
    try:
        ns = sdc.get_asset(sdc.ASSETTYPE_SERVICES, msg['serviceUUID'])
        # check if the related resources exist
        resources = ns.get('resources', None)
        job_array = []
        resource_threads = []
        if resources:
            for resource in resources:
                if (resource['resoucreType']
                        == 'VF') and not VnfPackageModel.objects.filter(
                            vnfPackageId=resource['resourceUUID']):
                    logger.debug("VF [%s] is not distributed.",
                                 resource['resourceUUID'])
                    # raise CatalogException("VF (%s) is not distributed." % resource['resourceUUID'])
                    logger.info("VF [%s] begin to distribute.",
                                resource['resourceUUID'])
                    csar_id = resource['resourceUUID']
                    vim_ids = ignore_case_get(resource, "vimIds")
                    lab_vim_id = ignore_case_get(resource, "labVimId")
                    job_id = str(uuid.uuid4())
                    job_array.append(job_id)
                    resource_threads.append(
                        sdc_vnf_package.NfDistributeThread(
                            csar_id, vim_ids, lab_vim_id, job_id))
                    # sdc_vnf_package.NfDistributeThread(csar_id, vim_ids, lab_vim_id, job_id).start()
                else:
                    logger.debug("resource [%s] has been distributed",
                                 resource['resourceUUID'])
        for resource_thread in resource_threads:
            resource_thread.start()
        for resource_thread in resource_threads:
            resource_thread.join()
        for jobID in job_array:
            job_status = JobUtil.query_job_status(jobID)
            if job_status[0].status == 'error':
                raise CatalogException("VF resource fail to distributed.")
        csar_id = msg['serviceUUID']
        sdc_ns_package.ns_on_distribute(csar_id)
        logger.debug("Csar package [%s] has been destributed successfully",
                     csar_id)
    except CatalogException as e:
        logger.error("Failed to download the resource")
        logger.error(str(e))
Beispiel #12
0
def vnf_model_parser(request, *args, **kwargs):
    csar_id = ignore_case_get(request.data, "csarId")
    inputs = ignore_case_get(request.data, "inputs")
    logger.debug("Enter %s, csar_id=%s, inputs=%s", fun_name(), csar_id,
                 inputs)
    ret = sdc_vnf_package.parse_vnfd(csar_id, inputs)
    logger.info("Leave %s, Return value is %s", fun_name(), ret)
    if ret[0] != 0:
        return Response(data={'error': ret[1]},
                        status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    response_serializer = ParseModelResponseSerializer(data=ret[1])
    validation_error = handleValidatonError(response_serializer, False)
    if validation_error:
        return validation_error

    return Response(data=response_serializer.data,
                    status=status.HTTP_202_ACCEPTED)
Beispiel #13
0
    def get(self, request, job_id):
        response_id = ignore_case_get(request.META, 'responseId')
        ret = GetJobInfoService(job_id, response_id).do_biz()
        response_serializer = GetJobResponseSerializer(data=ret)
        validataion_error = self.handleValidatonError(response_serializer,
                                                      False)
        if validataion_error:
            return validataion_error

        return Response(data=response_serializer.data,
                        status=status.HTTP_200_OK)
Beispiel #14
0
def nfpackages_rc(request, *args, **kwargs):
    logger.debug("Enter %s%s, method is %s", fun_name(), request.data,
                 request.method)
    ret, normal_status, response_serializer, validation_error = None, None, None, None
    if request.method == 'GET':
        ret = sdc_vnf_package.nf_get_csars()
        normal_status = status.HTTP_200_OK
        response_serializer = NfPackagesSerializer(data=ret[1])
    elif request.method == 'POST':
        request_serivalizer = NfPackageDistributeRequestSerializer(
            data=request.data)
        validation_error = handleValidatonError(request_serivalizer, True)
        if validation_error:
            return validation_error

        csar_id = ignore_case_get(request_serivalizer.data, "csarId")
        vim_ids = ignore_case_get(request_serivalizer.data, "vimIds")
        lab_vim_id = ignore_case_get(request_serivalizer.data, "labVimId")
        job_id = str(uuid.uuid4())
        sdc_vnf_package.NfDistributeThread(csar_id, vim_ids, lab_vim_id,
                                           job_id).start()
        ret = [0, {"jobId": job_id}]
        normal_status = status.HTTP_202_ACCEPTED

        response_serializer = PostJobResponseSerializer(data=ret[1])
    logger.debug("Leave %s, Return value is %s", fun_name(), ret)

    if ret[0] != 0:
        return Response(data={'error': ret[1]},
                        status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    validation_error = handleValidatonError(response_serializer, False)
    if validation_error:
        return validation_error

    return Response(data=response_serializer.data, status=normal_status)
Beispiel #15
0
def ns_rd_csar(request, *args, **kwargs):
    csar_id = ignore_case_get(kwargs, "csarId")
    logger.info("Enter %s, method is %s, csar_id is %s", fun_name(),
                request.method, csar_id)
    ret, normal_status, response_serializer, validation_error = None, None, None, None
    if request.method == 'GET':
        ret = sdc_ns_package.ns_get_csar(csar_id)
        normal_status = status.HTTP_200_OK
        if ret[0] == 0:
            response_serializer = NsPackageSerializer(data=ret[1])
            validation_error = handleValidatonError(response_serializer, False)
            if validation_error:
                return validation_error
    elif request.method == 'DELETE':
        ret = sdc_ns_package.ns_delete_csar(csar_id)
        normal_status = status.HTTP_200_OK
    logger.info("Leave %s, Return value is %s", fun_name(), ret)
    if ret[0] != 0:
        return Response(data={'error': ret[1]},
                        status=status.HTTP_500_INTERNAL_SERVER_ERROR)
    return Response(data=ret[1], status=normal_status)
Beispiel #16
0
 def create(self, data):
     """
     Create a PNF package
     :param data:
     :return:
     """
     logger.info('Start to create a PNFD...')
     user_defined_data = ignore_case_get(data, 'userDefinedData', {})
     data = {
         'id': str(uuid.uuid4()),
         'pnfdOnboardingState': PKG_STATUS.CREATED,
         'pnfdUsageState': PKG_STATUS.NOT_IN_USE,
         'userDefinedData': user_defined_data,
         '_links': None  # TODO
     }
     PnfPackageModel.objects.create(
         pnfPackageId=data['id'],
         onboardingState=data['pnfdOnboardingState'],
         usageState=data['pnfdUsageState'],
         userDefinedData=json.dumps(user_defined_data)
     )
     logger.info('A PNFD(%s) has been created.' % data['id'])
     return data
 def create_vnf_pkg(self, data):
     """
     Create a VNF package
     :param data: user defined data
     :return: VNF package info
     """
     user_defined_data = ignore_case_get(data, "userDefinedData", {})
     vnf_pkg_id = str(uuid.uuid4())
     VnfPackageModel.objects.create(
         vnfPackageId=vnf_pkg_id,
         onboardingState=const.PKG_STATUS.CREATED,
         operationalState=const.PKG_STATUS.DISABLED,
         usageState=const.PKG_STATUS.NOT_IN_USE,
         userDefinedData=json.dumps(user_defined_data))
     data = {
         "id": vnf_pkg_id,
         "onboardingState": const.PKG_STATUS.CREATED,
         "operationalState": const.PKG_STATUS.DISABLED,
         "usageState": const.PKG_STATUS.NOT_IN_USE,
         "userDefinedData": user_defined_data,
         "_links": None
     }
     return data
Beispiel #18
0
def servicepackages_rc(request, *args, **kwargs):
    logger.debug("Enter %s, method is %s", fun_name(), request.method)

    if request.method == 'GET':
        # Gets service package list
        try:
            csar_list = ServicePackage().get_csars()
            response_serializer = ServicePackagesSerializer(data=csar_list)
            validation_error = handleValidatonError(response_serializer, False)
            if validation_error:
                return validation_error
            return Response(data=csar_list, status=status.HTTP_200_OK)
        except Exception as e:
            error_status = status.HTTP_500_INTERNAL_SERVER_ERROR
            return Response(data=fmt_error_rsp(e.args[0], error_status),
                            status=error_status)
    elif request.method == 'POST':
        # Distributes the package according to the given csarId
        request_serializer = ServicePackageDistributeRequestSerializer(
            data=request.data)
        validation_error = handleValidatonError(request_serializer, True)
        if validation_error:
            return validation_error

        csar_id = ignore_case_get(request.data, "csarId")
        logger.debug("csar_id is %s", csar_id)
        try:
            ServicePackage().on_distribute(csar_id)
            return Response(status=status.HTTP_202_ACCEPTED)
        except PackageHasExistsException as e:
            error_status = status.HTTP_400_BAD_REQUEST
            return Response(data=fmt_error_rsp(e.args[0], error_status),
                            status=error_status)
        except Exception as e:
            error_status = status.HTTP_500_INTERNAL_SERVER_ERROR
            return Response(data=fmt_error_rsp(e.args[0], error_status),
                            status=error_status)