Ejemplo n.º 1
0
    def _set_vnf_deployment_ready(self,
                                  th,
                                  esc_name,
                                  event,
                                  is_ready,
                                  error_message=''):
        root = maagic.get_root(th)
        self.log.debug("event {}".format(event))
        key = [str(event.tenant), str(event.depname), esc_name]
        if key in root.nfvo_rel2__nfvo.vnf_info.esc.vnf_deployment_result:
            dep = root.nfvo_rel2__nfvo.vnf_info.esc.vnf_deployment_result[key]
            if is_ready:
                now = datetime.utcnow()
                dep.status.ready = now.isoformat()
            elif not is_ready and error_message == '':
                dep.status.deployed.create()
            else:
                self.log.debug("got {}".format(error_message))
                dep.status.error = error_message
        else:
            (tenant, depname, vm_group) = self._extract_vm_info(event)
            root = maagic.get_root(th)
            dep = root.nfvo_rel2__nfvo.vnf_info.esc.vnf_deployment_result.create(
                tenant, depname, esc_name)

            if event.status == "FAILURE" and error_message is not None:
                # IF we do not have a vnf_deployment_result, this event is a
                # SERVICE_ALIVE failure on an deployment initial configuration.
                # So we should setup the deployment_result at least.
                dep.status.error = error_message
            else:
                dep.status.error = "Unknown Error: Missing status message in escEvent"
Ejemplo n.º 2
0
    def cb_action(self, uinfo, name, kp, input, output, trans):

        device_serial=kp[0][0].as_pyval()

        with maapi.single_write_trans(uinfo.username, "system", db=ncs.RUNNING) as th:
            self.log.info("Onboarding ztp device: %s" % (kp))
            root = maagic.get_root(th)
            device=root.ztp[device_serial]
            ztp_template_vars = ncs.template.Variables()
            ztp_template_template = ncs.template.Template(device)
            ztp_template_vars.add('DEVICE_NAME', device_serial)
            ztp_template_vars.add('ADDRESS', device.ip)
            ztp_template_template.apply('ztp-template', ztp_template_vars)
            th.apply()

        with maapi.single_read_trans(uinfo.username, "system", db=ncs.OPERATIONAL) as th:
            root = maagic.get_root(th)
            inputs = root.devices.device[device_serial].ssh.fetch_host_keys.get_input()
            self.log.info(root.devices.device[device_serial].ssh.fetch_host_keys(inputs))
            self.log.info(root.devices.device[device_serial].sync_from())

        #send notif
        csocket = socket.socket()
        try:
            ctx = dp.init_daemon('send-notif')
            # making a control socket
            dp.connect(dx=ctx, sock=csocket, type=dp.CONTROL_SOCKET, ip='127.0.0.1', port=_ncs.PORT)
            # getting all the required hashes
            ns_hash = _ncs.str2hash("http://example.com/ztp")
            # notif_name_hash = _ncs.str2hash('service-name')
            notif_state_hash = _ncs.str2hash('state')
            notif_device_hash = _ncs.str2hash('device')
        notif_hash = _ncs.str2hash('ztp-status')
            
            # making the notification
            message = []
            message += [_ncs.TagValue(_ncs.XmlTag(ns_hash, notif_hash),
                                      _ncs.Value((notif_hash, ns_hash), _ncs.C_XMLBEGIN))]
            message += [_ncs.TagValue(ncs.XmlTag(ns_hash, notif_state_hash),
                                      _ncs.Value("ready"))]
            message += [_ncs.TagValue(ncs.XmlTag(ns_hash, notif_device_hash),
                                      _ncs.Value(device_serial))]
            message += [_ncs.TagValue(_ncs.XmlTag(ns_hash, notif_hash),
                                      _ncs.Value((notif_hash, ns_hash), _ncs.C_XMLEND))]
            # registering the stream
            livectx = dp.register_notification_stream(ctx, None, csocket, "ztp")
            # time
            now = datetime.datetime.now()
            time = _ncs.DateTime(now.year, now.month, now.day, now.hour, now.minute,
                                 now.second, now.microsecond, now.timetz().hour,
                                 now.timetz().minute)
            # sending the notification
            dp.notification_send(livectx, time, message)
            self.log.info(message)
            self.log.info("ZTP: Onboarding notification has been generated.")
Ejemplo n.º 3
0
def is_vnf_ready(tctx, tenant, deployment_name, esc):
    """Returns True if a VNF is ready.

    If the deployment has failed, a VNFError will be raised.

    Arguments:
    tctx -- a transaction context
    tenant -- Tenant name
    deployment_name -- The deployment name
    esc -- name of the ESC device
    """
    with maapi.single_read_trans(tctx.username, "system",
                                 db=ncs.OPERATIONAL) as oper_th:
        oroot = maagic.get_root(oper_th)
        vnf_deployment = oroot.nfvo_rel2__nfvo.vnf_info.esc.vnf_deployment

        if (tenant, deployment_name, esc) not in vnf_deployment:
            return False

        dep = vnf_deployment[tenant, deployment_name, esc]

        plan = dep.plan
        if plan.failed:
            raise VNFError(tenant, deployment_name, esc)

        ready_status = str(dep.plan.component['self'].state['ready'].status)
        return ready_status == 'reached'
Ejemplo n.º 4
0
    def _set_device_status_alive(self, th, esc_name, event, vnf_info, vdu):
        (tenant, depname, _) = self._extract_vm_info(event)
        if "VM_ALIVE" == event.event.type:
            vmid = event.vm_source.vmid
            hostid = event.vm_source.hostid
            hostname = event.vm_source.hostname
        elif "VM_RECOVERY_COMPLETE" == event.event.type:
            vmid = event.vm_target.vmid
            hostid = event.vm_target.hostid
            hostname = event.vm_target.hostname

        root = maagic.get_root(th)
        dep = root.nfvo_rel2__nfvo.vnf_info.esc.vnf_deployment_result[tenant,
                                                                      depname,
                                                                      esc_name]
        device_list = dep.vdu[vnf_info, vdu].vm_device
        key = [esc_name, vmid]
        dev = device_list[key]
        dev.hostid = hostid
        if hostname is not None:
            self.log.debug("Setting hostname to {}".format(hostname))
            dev.hostname = hostname
        else:
            self.log.debug("No compute hostname in escEvent {}".format(event))
        dev.status.ready = datetime.utcnow().isoformat()
Ejemplo n.º 5
0
    def _vm_undeployed(self, esc_name, event, th):
        (tenant, depname, vm_group) = self._extract_vm_info(event)

        root = maagic.get_root(th)
        esc = root.ncs__devices.device[esc_name]
        dep_res = root.nfvo_rel2__nfvo.vnf_info.esc.vnf_deployment_result[
            tenant, depname, esc_name]
        (vdu, device) = find_vdu_and_device_by_vmid(dep_res.vdu,
                                                    event.vm_source.vmid)
        self.log.debug("VM_UNDEPLOYED: VDU %s DEV %s" % (vdu, device))
        if device is not None:
            devName = device.device_name
            self.log.debug("GOT VM_UNDEPLOYED: for Device %s" % devName)
            if "FAILURE" == event.status:
                self.log.error("Received failed undeploy: %s" %
                               (event.status_message))
                self._set_device_status_error(th, esc_name, event,
                                              vdu.vnf_info, vdu.vdu,
                                              event.status_message)
                return
            del root.ncs__devices.device[devName]
            self._remove_device_lookup(esc_name, event, th, vdu.vnf_info,
                                       vdu.vdu)
        else:
            self.log.debug("GOT VM_UNDEPLOYED: for unknown device %s" %
                           str(event.vm_source.vmid))
def syncWorker(lsa_node, name, self, res):

    with ncs.maapi.single_write_trans('admin', 'VRF-REC-' + lsa_node) as t:
        root = maagic.get_root(t, shared=False)
        lsan = root.ncs__devices.device[lsa_node]

        try:
            self.log.debug(
                '     vrf reconcile lsa-node [%s] sync-from starting' %
                (lsa_node))
            syncFrom = lsan.sync_from
            inp = syncFrom.get_input()
            output = syncFrom(inp)

            if output.result == True:
                self.log.debug(
                    '    vrf reconcile lsa-node [%s] sync-from completed' %
                    (lsa_node))
            else:
                self.log.info(
                    '    vrf reconcile lsa-node [%s] sync-from Failure' %
                    (lsa_node))

        except Exception as e:
            res['status'] = 'failed'
            res['message'] = 'Exeception occurred during sync-from processing !'
            self.log.error(e)
def reconcileWorker(lsa_node, name, self, res):
    with ncs.maapi.single_write_trans('admin', 'VRF-REC-' + lsa_node) as t:
        root = maagic.get_root(t, shared=False)
        lsan = root.ncs__devices.device[lsa_node]
        res['status'] = 'success'
        self.log.debug("    starting reconcile [%s] LSA node [%s]" %
                       (name, lsa_node))
        try:
            action = lsan.config.vrf__vrf[name].oob_reconcile
            inp = action.get_input()
            opt = action(inp)
            self.log.debug(
                "     vrf[%s] LSA Node [%s] reconcile successfully completed" %
                (name, lsa_node))
            if opt.status == 'failed':
                self.log.error(
                    "     vrf[%s] LSA Node [%s] reconcile failed [%s]" %
                    (name, lsa_node, opt.error_message))
                res['status'] = 'failed'
                res['message'] = 'LSA Node [%s] failure details \n%s\n' % (
                    lsa_node, opt.error_message)

        except Exception as e:
            res['status'] = 'failed'
            res['message'] = 'vrf[%s] error during reconcile for LSA Node [%s]' % (
                name, lsa_node)
            self.log.error(e)
Ejemplo n.º 8
0
 def setup_drned_env(self, trans):
     """Build a dictionary that is supposed to be passed to `Popen` as the
     environment.
     """
     env = dict(os.environ)
     root = maagic.get_root(trans)
     drdir = root.drned_xmnr.drned_directory
     if drdir == "env":
         try:
             drdir = env['DRNED']
         except KeyError:
             raise ActionError('DrNED installation directory not set; ' +
                               'set /drned-xmnr/drned-directory or the ' +
                               'environment variable DRNED')
     elif drdir == "builtin" or drdir is None:
         drdir = os.path.join(self.dev_test_dir, 'drned')
     drdir = os.path.abspath(drdir)
     env['DRNED'] = drdir
     if 'PYTHONPATH' in env:
         env['PYTHONPATH'] += os.pathsep + drdir
     else:
         env['PYTHONPATH'] = drdir
     try:
         env['PYTHONPATH'] += os.pathsep + env['NCS_DIR'] + '/lib/pyang'
     except KeyError:
         raise ActionError('NCS_DIR not set')
     env['PYTHONUNBUFFERED'] = '1'
     path = env['PATH']
     # need to remove exec path inserted by NSO
     env['PATH'] = os.pathsep.join(ppart for ppart in path.split(os.pathsep)
                                   if 'ncs/erts' not in ppart)
     return env
Ejemplo n.º 9
0
    def _store_problems(self, trans: Transaction) -> int:
        if self.parsed_problems is None:
            return 0
        problem_count = len(self.parsed_problems)

        # clean up previously stored problems
        root = maagic.get_root(trans)
        device_xmnr_node = root.devices.device[self.dev_name].drned_xmnr
        problems_node = device_xmnr_node.parsed_problems
        problems_node.problems.delete()
        problems_node.target_log = self.target_log
        problems_node.parse_time = datetime.now()

        # and push new ones into CDB
        problem_list = problems_node.problems
        for problem in self.parsed_problems:
            problem_instance = problem_list.create(problem.line_num)
            problem_instance.phase = problem.phase
            problem_instance.test_case = problem.test_case
            if problem.time is not None:
                problem_instance.time = problem.time
            for (j, line) in enumerate(problem.lines):
                line_instance = maapi_keyless_create(
                    problem_instance.message_lines, j)
                line_instance.line = line.rstrip()
        problems_node.count = problem_count

        trans.apply()
        return problem_count
Ejemplo n.º 10
0
def is_ns_ready(tctx, ns_name):
    """Returns True if a NS is ready.

    If the deployment has failed, a NSError will be raised.

    Arguments:
    tctx -- a transaction context
    ns_name -- the name of the NS Info
    """
    with maapi.single_read_trans(tctx.username, "system",
                                 db=ncs.OPERATIONAL) as oper_th:
        oroot = maagic.get_root(oper_th)
        ns_infos = oroot.nfvo_rel2__nfvo.ns_info.esc.ns_info

        if ns_name not in ns_infos:
            return False

        nsi = ns_infos[ns_name]

        plan = nsi.plan
        if plan.failed:
            raise NSError(ns_name)

        ready_status = str(nsi.plan.component['self'].state['ready'].status)
        return ready_status == 'reached'
Ejemplo n.º 11
0
 def _handle_commit_error(self, username, context, key, error_msg):
     with maapi.single_write_trans(username, context,
                                   db=ncs.OPERATIONAL) as th:
         results = maagic.get_root(
             th).nfvo_rel2__nfvo.vnf_info.esc.vnf_deployment_result
         res = results.create(key)
         res.status.error = error_msg
         th.apply()
Ejemplo n.º 12
0
    def _handle_notif(self, esc_name, notif, th):
        self.log.info("Handling event from {}".format(esc_name))
        event = notif.data.escEvent
        event_type = event.event.type
        self.log.debug("Handling event type {}".format(event_type))
        if "VM_ALIVE" == event_type:
            self._vm_alive(esc_name, event, th)
        elif "VM_DEPLOYED" == event_type or "VM_RECOVERY_DEPLOYED" == event_type:
            self._vm_deployed(esc_name, event, th)
        elif "SERVICE_ALIVE" == event_type:
            self._service_alive(esc_name, event, th)
        elif "VM_RECOVERY_INIT" == event_type:
            self._recovery_init(esc_name, event, th)
        elif "VM_RECOVERY_COMPLETE" == event_type:
            self._vm_recovery_complete(esc_name, event, th)
        elif "VM_RECOVERY_CANCELLED" == event_type:
            self._recovery_cancelled(esc_name, event, th)
        elif "VM_UNDEPLOYED" == event_type:
            self._vm_undeployed(esc_name, event, th)
        elif "VM_RECOVERY_REBOOT" == event_type:
            self.log.info("VM_RECOVERY_REBOOT - nothing to do")
        elif "SERVICE_UNDEPLOYED" == event_type:
            self.log.info("TODO %s" % (event_type))
        elif "VM_RECOVERY_UNDEPLOYED" == event_type:
            self._vm_recovery_undeployed(esc_name, event, th)
        elif "VM_SCALE_OUT_INIT" == event_type:
            self.log.info("Scale out init")
            pass
        elif "VM_SCALE_OUT_DEPLOYED" == event_type:
            self.log.info("Scale out VM deployed")
            pass
        elif "VM_SCALE_OUT_COMPLETE" == event_type:
            self.log.info("Scale out complete")
            pass
        elif "VM_SCALE_IN_INIT" == event_type:
            self.log.info("Scale in init")
            pass
        elif "VM_SCALE_IN_COMPLETE" == event_type:
            self.log.info("Scale in complete")
            pass
        else:
            self.log.error("Can't handle %s" % (event_type))

        key = [str(event.tenant), str(event.depname), esc_name]
        try:
            # Is it enough to put the plan in error-state? Recovery-state?
            # Just do redeploy and let the plan subscriber figure out what to
            # do?
            #
            root = maagic.get_root(th)
            if key in root.nfvo_rel2__nfvo.vnf_info.esc.vnf_deployment:
                dep = root.nfvo_rel2__nfvo.vnf_info.esc.vnf_deployment[key]
                self._vnf_info_svcs_to_redeploy.add(dep._path)
        except KeyError:
            # Handles race condition when the service has been removed
            self.log.info("Could not redeploy %s.  (Has it been removed)?" %
                          (key))
Ejemplo n.º 13
0
def _scale_out_init(event, th):
    root = maagic.get_root(th)
    vm_group = _get_vm_group(root, event)

    if vm_group:
        if vm_group.vms_scaling:
            vm_group.vms_scaling = vm_group.vms_scaling + 1
        else:
            vm_group.vms_scaling = 1
Ejemplo n.º 14
0
    def _vm_recovery_complete(self, esc_name, event, th):
        # We assume the management IP hasn't changed here
        root = maagic.get_root(th)
        (tenant, depname, vm_group) = self._extract_vm_info(event)

        esc = root.ncs__devices.device[esc_name]
        esc_config = self._esc_config(esc, tenant, depname, vm_group)
        vm_properties = esc_config.extensions.extension[
            'NSO'].properties.property
        vnf_info = vm_properties['VNF-INFO-NAME'].value
        vdu = vm_properties['VDU'].value
        dep = root.nfvo_rel2__nfvo.vnf_info.esc.vnf_deployment_result[tenant,
                                                                      depname,
                                                                      esc_name]
        if "FAILURE" == event.status:
            error_message = event.status_message
            self.log.error("Received failed recovery: %s" % (error_message))
            self._set_device_status_error(th, esc_name, event, vnf_info, vdu,
                                          error_message)

            if dep.status.ready:
                del dep.status.ready

            dep.status.error = error_message
            return
        elif event.vm_source.vmid == event.vm_target.vmid:
            # Update vm device
            self.log.debug("VM_RECOVERY_COMPLETE with identical source and"
                           " target vmid:s. Assuming succesful reboot.")
            self._vm_alive(esc_name, event, th)
        else:
            # The vm_source contains the old vmid, remove that
            self._remove_device_lookup(esc_name, event, th, vnf_info, vdu)
            # Setup the new device
            self._vm_alive(esc_name, event, th)

        # Are all device ok now? Then set deployment-result to ready!
        num_devices = len(
            [1 for vdu in dep.vdu for vm_device in vdu.vm_device])
        self.log.debug("Check {} device(s) for readiness".format(num_devices))
        for vdu in dep.vdu:
            for vm_device in vdu.vm_device:
                if vm_device.status.ready:
                    continue
                elif vm_device.vmid == event.vm_target.vmid:
                    self.log.debug("Target device set to ready, skipping..")
                    continue
                else:
                    self.log.debug("{} is NOT ready".format(
                        vm_device.device_name))
                    return
        self.log.info("All devices in ready state, setting deployment ready")
        now = datetime.utcnow()
        dep.status.ready = now.isoformat()
Ejemplo n.º 15
0
 def _remove_device_lookup(self, esc_name, event, th, vnf_info, vdu):
     # Try to remove the device from the lookup table
     root = maagic.get_root(th)
     (tenant, depname, vm_group) = self._extract_vm_info(event)
     depKey = [tenant, depname, esc_name]
     if depKey not in root.nfvo_rel2__nfvo.vnf_info.esc.vnf_deployment_result:
         return
     dep = root.nfvo_rel2__nfvo.vnf_info.esc.vnf_deployment_result[depKey]
     del dep.vdu[vnf_info, vdu].vm_device[esc_name, event.vm_source.vmid]
     if not dep.vdu[vnf_info, vdu].vm_device:
         del dep.vdu[vnf_info, vdu]
Ejemplo n.º 16
0
    def find_ned_ids(self):
        ''' Find all active CLI NED Ids '''

        self.cli_neds = []
        with ncs.maapi.single_read_trans(self.username, 'Onboard') as t:

            root = maagic.get_root(t, shared=False)
            for pkg in root.ncs__packages.package:
                for comp in pkg.component:
                    if comp.ned.cli and comp.ned.cli.ned_id and "cli" in comp.ned.cli.ned_id:
                        vals = comp.ned.cli.ned_id.split(':')
                        self.cli_neds.append(vals[1])
Ejemplo n.º 17
0
 def _setup_directories(self, trans):
     root = maagic.get_root(trans)
     self.xmnr_directory = root.drned_xmnr.xmnr_directory
     self.log_filename = root.drned_xmnr.xmnr_log_file
     self.dev_test_dir = os.path.join(self.xmnr_directory, self.dev_name,
                                      'test')
     self.drned_run_directory = os.path.join(self.dev_test_dir, 'drned')
     self.states_dir = os.path.join(self.dev_test_dir, 'states')
     try:
         os.makedirs(self.states_dir)
     except OSError:
         pass
Ejemplo n.º 18
0
def _vnf_devices(th, tenant, deployment_name, esc):
    oroot = maagic.get_root(th)
    res = oroot.nfvo_rel2__nfvo.vnf_info.esc.vnf_deployment_result[
        tenant, deployment_name, esc]

    devices = {}
    for vdu in res.vdu:
        devs = []
        for dev in vdu.vm_device:
            devs.append(dev.device_name)

        devices[(str(vdu.vnf_info), str(vdu.vdu))] = devs
    return devices
Ejemplo n.º 19
0
 def _set_device_status_error(self, th, esc_name, event, vnf_info, vdu,
                              error_msg):
     (tenant, depname, _) = self._extract_vm_info(event)
     vmid = event.vm_source.vmid
     self.log.debug("Device {} recovery error '{}'".format(vmid, error_msg))
     root = maagic.get_root(th)
     dep = root.nfvo_rel2__nfvo.vnf_info.esc.vnf_deployment_result[tenant,
                                                                   depname,
                                                                   esc_name]
     device_list = dep.vdu[vnf_info, vdu].vm_device
     key = [esc_name, vmid]
     dev = device_list[key]
     dev.status.error = error_msg
Ejemplo n.º 20
0
def ns_devices(tctx, ns_name):
    """Returns a NS service's devices.

    The devices are return in map keyed (vnf-info, vdu) -> device list

    Arguments:
    tctx -- a transaction context
    ns_name -- The name of the NS Info
    """
    with maapi.single_read_trans(tctx.username, "system",
                                 db=ncs.OPERATIONAL) as oper_th:
        oroot = maagic.get_root(oper_th)
        ns_infos = oroot.nfvo_rel2__nfvo.ns_info.esc.ns_info
        nsi = ns_infos[ns_name]
        return _vnf_devices(oper_th, nsi.tenant, nsi.deployment_name, nsi.esc)
Ejemplo n.º 21
0
    def _get_device_name_from_lookup(self, th, esc_name, event, vnf_info, vdu):
        (tenant, depname, _) = self._extract_vm_info(event)
        if "VM_ALIVE" == event.event.type:
            vmid = event.vm_source.vmid
        else:
            #VM_RECOVERY_DEPLOYED or VM_RECOVERY_COMPLETE
            vmid = event.vm_target.vmid

        root = maagic.get_root(th)
        res = root.nfvo_rel2__nfvo.vnf_info.esc.vnf_deployment_result[tenant,
                                                                      depname,
                                                                      esc_name]
        device_list = res.vdu[vnf_info, vdu].vm_device
        key = [esc_name, vmid]
        return str(device_list[key].device_name)
Ejemplo n.º 22
0
    def _recovery_cancelled(self, esc_name, event, th):
        root = maagic.get_root(th)
        (tenant, depname, vm_group) = self._extract_vm_info(event)

        esc = root.ncs__devices.device[esc_name]
        esc_config = self._esc_config(esc, tenant, depname, vm_group)
        vm_properties = esc_config.extensions.extension[
            'NSO'].properties.property
        vnf_info = vm_properties['VNF-INFO-NAME'].value
        vdu = vm_properties['VDU'].value
        dep = root.nfvo_rel2__nfvo.vnf_info.esc.vnf_deployment_result[tenant,
                                                                      depname,
                                                                      esc_name]
        device_list = dep.vdu[vnf_info, vdu].vm_device
        dev = device_list[esc_name, event.vm_source.vmid]
        dev.status.ready = datetime.utcnow().isoformat()
        dep.status.ready = datetime.utcnow().isoformat()
Ejemplo n.º 23
0
    def post_iterate(self, state):
        context = 'system'

        with maapi.single_read_trans('', context) as ro_th:
            ro_root = maagic.get_root(ro_th)
            for kp in state:
                notif = maagic.get_node(ro_th, kp)
                if not notif.data.escEvent:
                    continue
                event = notif.data.escEvent
                username = _get_username(ro_root, event)
                vnfm_name = ncs.maagic.cd(notif, '../../../ncs:name')
                if (username and notif.subscription
                        == f'cisco-etsi-nfvo-{vnfm_name}'):
                    # Switch user context
                    with maapi.single_write_trans(username, context) as th:
                        self._handle_notif(notif, th)
                        th.apply()
Ejemplo n.º 24
0
def id_read(username, root, pool_name, allocation_name):
    """Returns the allocated ID or None

    Arguments:
    username -- the requesting service's transaction's user
    root -- a maagic root for the current transaction
    pool_name -- name of pool to request from
    allocation_name -- unique allocation name
    """

    # Look in the current transaction
    id_pool_l = root.ralloc__resource_pools.id_pool

    if pool_name not in id_pool_l:
        raise LookupError("ID pool %s does not exist" % (pool_name))

    id_pool = id_pool_l[pool_name]

    if allocation_name not in id_pool.allocation:
        raise LookupError("allocation %s does not exist in pool %s" %
                          (allocation_name, pool_name))

    # Now we switch from the current trans to actually see if
    # we have received the alloc
    with maapi.single_read_trans(username, "system",
                                 db=ncs.OPERATIONAL) as th:
        id_pool_l = maagic.get_root(th).ralloc__resource_pools.id_pool

        if pool_name not in id_pool_l:
            return None

        id_pool = id_pool_l[pool_name]

        if allocation_name not in id_pool.allocation:
            return None

        alloc = id_pool.allocation[allocation_name]

        if alloc.response.id:
            return alloc.response.id
        elif alloc.response.error:
            raise LookupError(alloc.response.error)
        else:
            return None
Ejemplo n.º 25
0
 def _setup_xmnr(self, trans: Transaction) -> None:
     root = maagic.get_root(trans)
     self.xmnr_directory = os.path.abspath(root.drned_xmnr.xmnr_directory)
     self.log_filename = root.drned_xmnr.xmnr_log_file
     self.cli_log_filename = root.drned_xmnr.cli_log_file
     self.dev_test_dir = os.path.join(self.xmnr_directory, self.dev_name, 'test')
     self.drned_run_directory = os.path.join(self.dev_test_dir, 'drned-skeleton')
     self.using_builtin_drned = root.drned_xmnr.drned_directory == "builtin"
     self.states_dir = os.path.join(self.dev_test_dir, 'states')
     device_node = root.devices.device[self.dev_name]
     self.device_timeout = device_node.read_timeout
     if self.device_timeout is None:
         self.device_timeout = 120
     device_xmnr_node = device_node.drned_xmnr
     self.cleanup_timeout = device_xmnr_node.cleanup_timeout
     try:
         os.makedirs(self.states_dir)
     except OSError:
         pass
Ejemplo n.º 26
0
 def __init__(self, action: 'ActionBase') -> None:
     self.uinfo = action.uinfo
     self.cli_log_file: Optional[TextIO]
     if action.cli_log_filename is not None:
         self.cli_log_file = open(action.cli_log_filename, 'a')
         self.cli_log_file.write(action.log_header())
     else:
         self.cli_log_file = None
     self.maapi = maapi.Maapi()
     self.maapi.start_user_session('admin', 'system')
     self.trans = maapi.Transaction(self.maapi, rw=_ncs.READ, db=_ncs.OPERATIONAL)
     root = maagic.get_root(self.trans)
     apoint = root.ncs_state.internal.callpoints.actionpoint[ns.actionpoint_xmnr_cli_log]
     if apoint.daemon.id is not None:
         self.cli_log_action = root.drned_xmnr.cli_log_message
         self.cli_log_params = self.cli_log_action.get_input()
         self.cli_log_params.device = action.dev_name
     else:
         self.cli_log_action = self.cli_log_params = None
Ejemplo n.º 27
0
    def _copy_device_info(self, th, esc_name, event, vnf_info, vdu):
        root = maagic.get_root(th)
        source_vmid = event.vm_source.vmid
        dest_vmid = event.vm_target.vmid
        (tenant, depname, _) = self._extract_vm_info(event)
        res = root.nfvo_rel2__nfvo.vnf_info.esc.vnf_deployment_result[tenant,
                                                                      depname,
                                                                      esc_name]
        device_list = res.vdu[vnf_info, vdu].vm_device

        old_dev = device_list[esc_name, source_vmid]
        dev = device_list.create(esc_name, dest_vmid)
        dev.index = old_dev.index
        dev.device_name = old_dev.device_name

        # if not dev.status.deployed.exists():
        if source_vmid != dest_vmid:
            # This could happen if the source and dest vmid is equal
            dev.status.deployed.create()
        return str(dev.device_name)
Ejemplo n.º 28
0
 def get_devcli_params(self, trans: Transaction) \
         -> Tuple[str, Optional[str], Optional[str], str, int]:
     root = maagic.get_root(trans)
     device_node = root.devices.device[self.dev_name]
     ip = device_node.address
     port = device_node.drned_xmnr.cli_port
     if port is None:
         port = device_node.port
     driver: Optional[str] = device_node.drned_xmnr.driver
     if driver is None:
         raise ActionError('device driver not configured, cannot continue')
     authgroup_name = device_node.authgroup
     authgroup = root.devices.authgroups.group[authgroup_name]
     locuser = self.uinfo.username
     if locuser in authgroup.umap:
         authmap = authgroup.umap[locuser]
     else:
         authmap = authgroup.default_map
     user, passwd = self.get_authgroup_info(trans, root, locuser, authmap)
     return driver, user, passwd, ip, port
Ejemplo n.º 29
0
    def cb_action(self, uinfo, name, kp, input, output, trans):
    
        device_serial = kp[0][0].as_pyval()

        with maapi.single_write_trans(uinfo.username, "system", db=ncs.RUNNING) as th:
            root = maagic.get_root(th)
            ztp = root.ztp[device_serial]
        filename = ztp.day0
        ip = ztp.ip
        hostname = ztp.hostname
        
        f = open("/opt/ncs-run/packages/ztp/day0_templates/{}".format(filename), "r")
        day0 = f.read()
        f.close()
        
        # replacing values in the template
        day0 = day0.replace("${IP}", ip)
        day0 = day0.replace("${HOSTNAME}", hostname)
        day0 = day0.replace("${SERIAL}", device_serial)
        
        output.message = day0
Ejemplo n.º 30
0
    def post_iterate(self, state):

        context = "system"

        with maapi.single_read_trans("", context) as ro_th:
            ro_root = maagic.get_root(ro_th)
            for notifInfo in state:
                notif = maagic.get_node(ro_th, notifInfo.kp)
                if not notif.data.escEvent:
                    continue
                event = notif.data.escEvent
                username = self._get_username(ro_root, notifInfo.esc, event)
                if username and notif.subscription == "tailf_nfvo":
                    # Switch user context
                    with maapi.single_write_trans(username, context) as th:
                        self._vnf_info_svcs_to_redeploy = set()
                        self._handle_notif(notifInfo.esc, notif, th)
                        th.apply()

                    if self._vnf_info_svcs_to_redeploy:
                        with maapi.single_read_trans(username, context) as th:
                            self._redeploy_services(th)