<commit_before># Copyright 2016 ZTE Corporation.
#
# 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
import uuid
from threading import Thread
from lcm.ns.const import OWNER_TYPE

from lcm.ns.vnfs.const import VNF_STATUS, NFVO_VNF_INST_TIMEOUT_SECOND, INST_TYPE, INST_TYPE_NAME
from lcm.ns.vnfs.wait_job import wait_job_finish
from lcm.pub.database.models import NfPackageModel, NfInstModel, NSInstModel, VmInstModel, VNFFGInstModel, VLInstModel
from lcm.pub.exceptions import NSLCMException
from lcm.pub.msapi.extsys import get_vnfm_by_id
from lcm.pub.msapi.resmgr import create_vnf, create_vnf_creation_info
from lcm.pub.msapi.vnfmdriver import send_nf_init_request
from lcm.pub.utils.jobutil import JOB_MODEL_STATUS, JobUtil, JOB_TYPE
from lcm.pub.utils.share_lock import do_biz_with_share_lock
from lcm.pub.utils.timeutil import now_time
from lcm.pub.utils.values import ignore_case_get

logger = logging.getLogger(__name__)


def prepare_create_params():
    nf_inst_id = str(uuid.uuid4())
    NfInstModel(nfinstid=nf_inst_id, status=VNF_STATUS.INSTANTIATING, create_time=now_time(),
                lastuptime=now_time()).save()
    job_id = JobUtil.create_job(INST_TYPE_NAME.VNF, JOB_TYPE.CREATE_VNF, nf_inst_id)
    JobUtil.add_job_status(job_id, 0, 'create vnf record in database.', 0)
    return nf_inst_id, job_id


class CreateVnfs(Thread):
    def __init__(self, data, nf_inst_id, job_id):
        super(CreateVnfs, self).__init__()
        self.data = data
        self.nf_inst_id = nf_inst_id
        self.job_id = job_id
        self.ns_inst_id = ''
        self.vnf_id = ''
        self.vnfd_id = ''
        self.ns_inst_name = ''
        self.nsd_model = ''
        self.vnfd_model = ''
        self.vnf_inst_name = ''
        self.vnfm_inst_id = ''
        self.inputs = ''
        self.nf_package_info = ''
        self.vnfm_nf_inst_id = ''
        self.vnfm_job_id = ''
        self.vnfm_inst_name = ''
        self.vim_id = ''

    def run(self):
        try:
            self.get_params()
            self.check_nf_name_exist()
            self.get_vnfd_id()
            self.check_nf_package_valid()
            self.send_nf_init_request_to_vnfm()
            self.send_get_vnfm_request_to_extsys()
            self.send_create_vnf_request_to_resmgr()
            self.wait_vnfm_job_finish()
            self.write_vnf_creation_info()
            self.save_info_to_db()
        except NSLCMException as e:
            self.vnf_inst_failed_handle(e.message)
        except Exception:
            logger.error(traceback.format_exc())
            self.vnf_inst_failed_handle('unexpected exception')

    def get_params(self):
        self.ns_inst_id = self.data['ns_instance_id']
        vnf_index = int(float(self.data['vnf_index'])) - 1
        additional_vnf_info = self.data['additional_param_for_vnf'][vnf_index]
        self.vnf_id = ignore_case_get(additional_vnf_info, 'vnfProfileId')
        additional_param = ignore_case_get(additional_vnf_info, 'additionalParam')
        self.vnfm_inst_id = ignore_case_get(additional_param, 'vnfmInstanceId')
        para = ignore_case_get(additional_param, 'inputs')
        self.inputs = json.loads(para) if isinstance(para, (str, unicode)) else para
        self.vim_id = ignore_case_get(additional_param, 'vimId')
        self.vnfd_id = ignore_case_get(additional_param, 'vnfdId')

    def check_nf_name_exist(self):
        is_exist = NfInstModel.objects.filter(nf_name=self.vnf_inst_name).exists()
        if is_exist:
            logger.error('The name of NF instance already exists.')
            raise NSLCMException('The name of NF instance already exists.')

    def get_vnfd_id(self):
        if self.vnfd_id:
            logger.debug("need not get vnfd_id")
            self.nsd_model={'vnfs': [], 'vls': [], 'vnffgs': []}
            self.vnf_inst_name = self.vnfd_id + str(uuid.uuid4())
            self.vnf_inst_name = self.vnf_inst_name[:30]
            return
        ns_inst_info = NSInstModel.objects.get(id=self.ns_inst_id)
        self.ns_inst_name = ns_inst_info.name
        self.nsd_model = json.loads(ns_inst_info.nsd_model)
        for vnf_info in self.nsd_model['vnfs']:
            if self.vnf_id == vnf_info['vnf_id']:
                self.vnfd_id = vnf_info['properties']['id']
                if 'name' not in vnf_info['properties']:
                    self.vnf_inst_name = self.vnfd_id + str(uuid.uuid4())
                else:
                    self.vnf_inst_name = vnf_info['properties']['name'] + str(uuid.uuid4())
                return
        logger.error('Can not found vnf in nsd model')
        raise NSLCMException('Can not found vnf in nsd model')

    def check_nf_package_valid(self):
        nf_package_info = NfPackageModel.objects.filter(vnfdid=self.vnfd_id)
        if not nf_package_info:
            logger.info('NF package not exist.')
            raise NSLCMException('NF package not exist.')
        self.nf_package_info = nf_package_info[0]
        self.vnfd_model = json.loads(self.nf_package_info.vnfdmodel)

    def get_virtual_link_info(self, vnf_id):
        virtual_link_list, ext_virtual_link = [], []
        for vnf_info in self.nsd_model['vnfs']:
            if vnf_info['vnf_id'] != vnf_id:
                continue
            for network_info in vnf_info['networks']:
                vl_instance = VLInstModel.objects.get(
                    vldid=network_info['vl_id'], 
                    ownertype=OWNER_TYPE.NS,<commit_msg>Modify vnf inst name set logic<commit_after># Copyright 2016 ZTE Corporation.
#
# 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
import uuid
from threading import Thread
from lcm.ns.const import OWNER_TYPE

from lcm.ns.vnfs.const import VNF_STATUS, NFVO_VNF_INST_TIMEOUT_SECOND, INST_TYPE, INST_TYPE_NAME
from lcm.ns.vnfs.wait_job import wait_job_finish
from lcm.pub.database.models import NfPackageModel, NfInstModel, NSInstModel, VmInstModel, VNFFGInstModel, VLInstModel
from lcm.pub.exceptions import NSLCMException
from lcm.pub.msapi.extsys import get_vnfm_by_id
from lcm.pub.msapi.resmgr import create_vnf, create_vnf_creation_info
from lcm.pub.msapi.vnfmdriver import send_nf_init_request
from lcm.pub.utils.jobutil import JOB_MODEL_STATUS, JobUtil, JOB_TYPE
from lcm.pub.utils.share_lock import do_biz_with_share_lock
from lcm.pub.utils.timeutil import now_time
from lcm.pub.utils.values import ignore_case_get

logger = logging.getLogger(__name__)


def prepare_create_params():
    nf_inst_id = str(uuid.uuid4())
    NfInstModel(nfinstid=nf_inst_id, status=VNF_STATUS.INSTANTIATING, create_time=now_time(),
                lastuptime=now_time()).save()
    job_id = JobUtil.create_job(INST_TYPE_NAME.VNF, JOB_TYPE.CREATE_VNF, nf_inst_id)
    JobUtil.add_job_status(job_id, 0, 'create vnf record in database.', 0)
    return nf_inst_id, job_id


class CreateVnfs(Thread):
    def __init__(self, data, nf_inst_id, job_id):
        super(CreateVnfs, self).__init__()
        self.data = data
        self.nf_inst_id = nf_inst_id
        self.job_id = job_id
        self.ns_inst_id = ''
        self.vnf_id = ''
        self.vnfd_id = ''
        self.ns_inst_name = ''
        self.nsd_model = ''
        self.vnfd_model = ''
        self.vnf_inst_name = ''
        self.vnfm_inst_id = ''
        self.inputs = ''
        self.nf_package_info = ''
        self.vnfm_nf_inst_id = ''
        self.vnfm_job_id = ''
        self.vnfm_inst_name = ''
        self.vim_id = ''

    def run(self):
        try:
            self.get_params()
            self.check_nf_name_exist()
            self.get_vnfd_id()
            self.check_nf_package_valid()
            self.send_nf_init_request_to_vnfm()
            self.send_get_vnfm_request_to_extsys()
            self.send_create_vnf_request_to_resmgr()
            self.wait_vnfm_job_finish()
            self.write_vnf_creation_info()
            self.save_info_to_db()
        except NSLCMException as e:
            self.vnf_inst_failed_handle(e.message)
        except Exception:
            logger.error(traceback.format_exc())
            self.vnf_inst_failed_handle('unexpected exception')

    def get_params(self):
        self.ns_inst_id = self.data['ns_instance_id']
        vnf_index = int(float(self.data['vnf_index'])) - 1
        additional_vnf_info = self.data['additional_param_for_vnf'][vnf_index]
        self.vnf_id = ignore_case_get(additional_vnf_info, 'vnfProfileId')
        additional_param = ignore_case_get(additional_vnf_info, 'additionalParam')
        self.vnfm_inst_id = ignore_case_get(additional_param, 'vnfmInstanceId')
        para = ignore_case_get(additional_param, 'inputs')
        self.inputs = json.loads(para) if isinstance(para, (str, unicode)) else para
        self.vim_id = ignore_case_get(additional_param, 'vimId')
        self.vnfd_id = ignore_case_get(additional_param, 'vnfdId')

    def check_nf_name_exist(self):
        is_exist = NfInstModel.objects.filter(nf_name=self.vnf_inst_name).exists()
        if is_exist:
            logger.error('The name of NF instance already exists.')
            raise NSLCMException('The name of NF instance already exists.')

    def get_vnfd_id(self):
        if self.vnfd_id:
            logger.debug("need not get vnfd_id")
            self.nsd_model={'vnfs': [], 'vls': [], 'vnffgs': []}
            self.vnf_inst_name = self.vnfd_id + str(uuid.uuid4())
            self.vnf_inst_name = self.vnf_inst_name[:30]
            return
        ns_inst_info = NSInstModel.objects.get(id=self.ns_inst_id)
        self.ns_inst_name = ns_inst_info.name
        self.nsd_model = json.loads(ns_inst_info.nsd_model)
        for vnf_info in self.nsd_model['vnfs']:
            if self.vnf_id == vnf_info['vnf_id']:
                self.vnfd_id = vnf_info['properties']['id']
                if 'name' not in vnf_info['properties']:
                    self.vnf_inst_name = self.vnfd_id + str(uuid.uuid4())
                else:
                    self.vnf_inst_name = vnf_info['properties']['name'] + str(uuid.uuid4())
                self.vnf_inst_name = self.vnf_inst_name[:30]
                return
        logger.error('Can not found vnf in nsd model')
        raise NSLCMException('Can not found vnf in nsd model')

    def check_nf_package_valid(self):
        nf_package_info = NfPackageModel.objects.filter(vnfdid=self.vnfd_id)
        if not nf_package_info:
            logger.info('NF package not exist.')
            raise NSLCMException('NF package not exist.')
        self.nf_package_info = nf_package_info[0]
        self.vnfd_model = json.loads(self.nf_package_info.vnfdmodel)

    def get_virtual_link_info(self, vnf_id):
        virtual_link_list, ext_virtual_link = [], []
        for vnf_info in self.nsd_model['vnfs']:
            if vnf_info['vnf_id'] != vnf_id:
                continue
            for network_info in vnf_info['networks']:
                vl_instance = VLInstModel.objects.get(
                    vldid=network_info['vl_id'], 
                    ownertype=OWNER_TYPE.NS,
{'fraction_non_alphanumeric': 0.09472640105802611, 'fraction_numerical': 0.003141015043808894, 'mean_word_length': 2.8841091492776885, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '219833', 'n_tokens_mistral': 4140, 'n_tokens_neox': 3985, 'n_words': 782}