Exemplo n.º 1
0
    def keep_connected(self):
        """Keep reconnecting to the controller"""
        while not self.exiting:
            host, port = self.resolve_endpoint(self.controller_endpoint)
            log.info('connecting', host=host, port=port)
            if self.enable_tls:
                try:
                    # Check that key_file and cert_file is provided and
                    # the files exist
                    if self.key_file is None or             \
                       self.cert_file is None or            \
                       not os.path.isfile(self.key_file) or \
                       not os.path.isfile(self.cert_file):
                        raise Exception('key_file "{}" or cert_file "{}"'
                                        ' is not found'.format(
                                            self.key_file, self.cert_file))
                    with open(self.key_file) as keyFile:
                        with open(self.cert_file) as certFile:
                            clientCert = ssl.PrivateCertificate.loadPEM(
                                keyFile.read() + certFile.read())

                    ctx = clientCert.options()
                    self.connector = reactor.connectSSL(host, port, self, ctx)
                    log.info('tls-enabled')

                except Exception as e:
                    log.exception('failed-to-connect', reason=e)
            else:
                self.connector = reactor.connectTCP(host, port, self)
                log.info('tls-disabled')

            self.d_disconnected = Deferred()
            yield self.d_disconnected
            log.debug('reconnect', after_delay=self.retry_interval)
            yield asleep(self.retry_interval)
Exemplo n.º 2
0
    def test_in_sync_with_ont_g_values(self):
        self.setup_one_of_each()
        self.assertEqual(len(self.omci_agent.device_ids()), 1)

        version = 'abcDEF'
        tm_opt = 2
        onu_survival = 123

        def stuff_db(_results):
            self._stuff_database([(OntG.class_id, 0, {
                'version': version,
                'traffic_management_options': tm_opt,
                'ont_survival_time': onu_survival
            })])

        def do_my_tests(_results):
            config = self.onu_device.configuration

            # On no Class ID for requested property, None should be
            # returned
            self.assertEqual(config.version, version)
            self.assertEqual(config.traffic_management_option, tm_opt)
            self.assertEqual(config.onu_survival_time, onu_survival)

        # No capabilities available until started
        self.assertIsNone(self.onu_device.configuration)

        # Yield context so that MIB Database callLater runs.
        self.onu_device.start()
        d = asleep(0.2)
        d.addCallbacks(stuff_db, self.not_called)
        d.addCallbacks(do_my_tests, self.not_called)
        return d
    def edit_config(self, config, target='running', default_operation='merge',
                    test_option=None, error_option=None):
        """
        Loads all or part of the specified config to the target configuration datastore with the ability to lock
        the datastore during the edit.

        :param config is the configuration, which must be rooted in the config element. It can be specified
                      either as a string or an Element.format="xml"
        :param target is the name of the configuration datastore being edited
        :param default_operation if specified must be one of { 'merge', 'replace', or 'none' }
        :param test_option if specified must be one of { 'test_then_set', 'set' }
        :param error_option if specified must be one of { 'stop-on-error', 'continue-on-error', 'rollback-on-error' }
                            The 'rollback-on-error' error_option depends on the :rollback-on-error capability.

        :return: (defeered) for RpcReply
        """
        try:
            yield asleep(random.uniform(0.1, 2.0))  # Simulate NETCONF request delay

        except Exception as e:
            log.exception('edit_config', e=e)
            raise

        # TODO: Customize if needed...
        xml = _dummy_xml
        returnValue(RPCReply(xml))
Exemplo n.º 4
0
    def test_in_sync_with_uni_g_values(self):
        self.setup_one_of_each()
        self.assertEqual(len(self.omci_agent.device_ids()), 1)

        entity_id = 0x4321
        mgmt_cap = 0

        def stuff_db(_results):
            self._stuff_database([(UniG.class_id, entity_id, {
                'management_capability': mgmt_cap
            })])

        def do_my_tests(_results):
            config = self.onu_device.configuration

            unig = config.uni_g_entities
            self.assertTrue(isinstance(unig, dict))
            self.assertEqual(len(unig), 1)

            self.assertEqual(unig[entity_id]['entity-id'], entity_id)
            self.assertEqual(unig[entity_id]['management-capability'],
                             mgmt_cap)

        # No capabilities available until started
        self.assertIsNone(self.onu_device.configuration)

        # Yield context so that MIB Database callLater runs.
        self.onu_device.start()
        d = asleep(0.2)
        d.addCallbacks(stuff_db, self.not_called)
        d.addCallbacks(do_my_tests, self.not_called)
        return d
Exemplo n.º 5
0
    def monitor_logical_devices(self):
        log.debug('start-monitor-logical-devices')

        while self.running:
            log.info('monitoring-logical-devices')

            # should change to a gRPC streaming call
            # see https://jira.opencord.org/browse/CORD-821

            try:
                if self.channel is not None and self.grpc_client is not None and \
                                self.subscription is not None:
                    # get current list from Voltha
                    devices = yield \
                        self.get_list_of_logical_devices_from_voltha()

                    # update agent list and mapping tables as needed
                    self.refresh_agent_connections(devices)
                else:
                    log.info('vcore-communication-unavailable')

                # wait before next poll
                yield asleep(self.devices_refresh_interval)

            except _Rendezvous, e:
                log.error('vcore-communication-failure',
                          exception=repr(e),
                          status=e.code())

            except Exception as e:
                log.exception('unexpected-vcore-communication-failure',
                              exception=repr(e))
Exemplo n.º 6
0
 def _backoff(self, msg):
     wait_time = RETRY_BACKOFF[min(self.retries, len(RETRY_BACKOFF) - 1)]
     self.retry_time += wait_time
     self.retries += 1
     log.error(msg, next_retry_in_secs=wait_time,
               total_delay_in_secs = self.retry_time,
               retries=self.retries)
     return asleep(wait_time)
Exemplo n.º 7
0
    def upload_mib(self, number_of_commands):
        ########################################
        # Begin MIB Upload
        seq_no = None

        for seq_no in xrange(number_of_commands):
            max_tries = MibResyncTask.max_mib_upload_next_retries

            for retries in xrange(0, max_tries):
                try:
                    self.strobe_watchdog()
                    response = yield self._device.omci_cc.send_mib_upload_next(
                        seq_no)

                    omci_msg = response.fields['omci_message'].fields
                    class_id = omci_msg['object_entity_class']
                    entity_id = omci_msg['object_entity_id']

                    # Filter out the 'mib_data_sync' from the database. We save that at
                    # the device level and do not want it showing up during a re-sync
                    # during data comparison
                    from binascii import hexlify
                    if class_id == OntData.class_id:
                        break

                    # The T&W ONU reports an ME with class ID 0 but only on audit. Perhaps others do as well.
                    if class_id == 0 or class_id > 0xFFFF:
                        self.log.warn('invalid-class-id', class_id=class_id)
                        break

                    attributes = {
                        k: v
                        for k, v in omci_msg['object_data'].items()
                    }

                    # Save to the database
                    self._db_active.set(self.device_id, class_id, entity_id,
                                        attributes)
                    break

                except TimeoutError:
                    self.log.warn('mib-resync-timeout',
                                  seq_no=seq_no,
                                  number_of_commands=number_of_commands)

                    if retries < max_tries - 1:
                        self.strobe_watchdog()
                        yield asleep(MibResyncTask.mib_upload_next_delay)
                    else:
                        raise

                except Exception as e:
                    self.log.exception('resync',
                                       e=e,
                                       seq_no=seq_no,
                                       number_of_commands=number_of_commands)

        returnValue(seq_no + 1)  # seq_no is zero based.
 def close(self):
     """
     Close the connection to the NETCONF server
     :return:  (deferred) Deferred request
     """
     yield asleep(random.uniform(0.1, 0.5))   # Simulate NETCONF request delay
     self._connected = False
     self._locked = {}
     returnValue(True)
    def check_that_t1_t2_running_and_last_is_not(self, results):
        from pyvoltha.common.utils.asleep import asleep
        yield asleep(0.1)

        self.assertEqual(self.runner.pending_tasks, 1)
        self.assertEqual(self.runner.running_tasks, 2)
        self.assertEqual(self.runner.successful_tasks_completed, 1)

        returnValue(results)
    def rpc(self, rpc_string):
        """
        Custom RPC request
        :param rpc_string: (string) RPC request
        :return: (defeered) for GetReply
        """
        yield asleep(random.uniform(0.1, 2.0))   # Simulate NETCONF request delay

        # TODO: Customize if needed...
        xml = _dummy_xml
        returnValue(RPCReply(xml))
    def get(self, payload):
        """
        Get the requested data from the server

        :param payload: Payload/filter
        :return: (defeered) for GetReply
        """
        yield asleep(random.uniform(0.1, 3.0))   # Simulate NETCONF request delay

        # TODO: Customize if needed...
        xml = _dummy_xml
        returnValue(RPCReply(xml))
    def add_gem_ctp_pm_me(self):
        config = self._device.configuration
        gem_ctps = config.gem_ctp_entities
        self.log.debug('gem-ctp-entities', gem_ctps=gem_ctps)

        if gem_ctps is not None:
            for entity_id in six.iterkeys(gem_ctps):
                self.add_pm_me(GemPortNetworkCtpMonitoringHistoryData.class_id,
                               entity_id)
        else:
            yield asleep(0.3)
            self.add_gem_ctp_pm_me()
    def get_config(self, source='running'):
        """
        Get the configuration from the specified source

        :param source: (string) Configuration source, 'running', 'candidate', ...
        :return: (deferred) Deferred request that wraps the GetReply class
        """
        yield asleep(random.uniform(0.1, 4.0))   # Simulate NETCONF request delay

        # TODO: Customize if needed...
        xml = _dummy_xml
        returnValue(RPCReply(xml))
Exemplo n.º 14
0
    def test_in_sync_with_ont_2g_values(self):
        self.setup_one_of_each()
        self.assertEqual(len(self.omci_agent.device_ids()), 1)

        equip_id = 'br-549'
        omcc_ver = OMCCVersion.G_988_2012
        vend_code = 0x1234
        queues = 64
        scheds = 8
        gem_ports = 24
        uptime = 12345
        conn_capp = 0x00aa
        qos_flex = 0x001b
        queue_scale = 1

        def stuff_db(_results):
            self._stuff_database([(Ont2G.class_id, 0, {
                'equipment_id': equip_id,
                'omcc_version': omcc_ver.value,
                'vendor_product_code': vend_code,
                'total_priority_queue_number': queues,
                'total_traffic_scheduler_number': scheds,
                'total_gem_port_id_number': gem_ports,
                'sys_uptime': uptime,
                'connectivity_capability': conn_capp,
                'qos_configuration_flexibility': qos_flex,
                'priority_queue_scale_factor': queue_scale
            })])

        def do_my_tests(_results):
            config = self.onu_device.configuration

            self.assertEqual(config.equipment_id, equip_id)
            self.assertEqual(config.omcc_version, omcc_ver)
            self.assertEqual(config.vendor_product_code, vend_code)
            self.assertEqual(config.total_priority_queues, queues)
            self.assertEqual(config.total_traffic_schedulers, scheds)
            self.assertEqual(config.total_gem_ports, gem_ports)
            self.assertEqual(config.uptime, uptime)
            self.assertEqual(config.connectivity_capability, conn_capp)
            self.assertEqual(config.qos_configuration_flexibility, qos_flex)
            self.assertEqual(config.priority_queue_scale_factor, queue_scale)

        # No capabilities available until started
        self.assertIsNone(self.onu_device.configuration)

        # Yield context so that MIB Database callLater runs.
        self.onu_device.start()
        d = asleep(0.2)
        d.addCallbacks(stuff_db, self.not_called)
        d.addCallbacks(do_my_tests, self.not_called)
        return d
    def fix_onu_only_save_to_db(self, undecodable, onu_created, onu_db):
        """
        In ONU database and needs to be saved to OLT/OpenOMCI database.

        Note that some, perhaps all, of these instances could be ONU create
        in response to the OLT creating some other ME instance. So treat
        the Database operation as a create.
        """
        successes = 0
        failures = 0

        for cid, eid in undecodable + onu_created:
            if self.deferred.called:        # Check if task canceled
                break
            try:
                # If in current MIB, had an audit issue or other MIB operation
                # put it into the database, declare it a failure so we audit again
                try:
                    olt_entry = self._sync_sm.query_mib(class_id=cid, instance_id=eid)

                except KeyError:        # Common for ONU created MEs during audit
                    olt_entry = None

                if olt_entry is not None and len(olt_entry):
                    self.log.debug('onu-only-in-current', cid=cid, eid=eid)
                    failures += 1     # Mark as failure so we audit again

                elif cid not in onu_db:
                    self.log.warn('onu-only-not-in-audit', cid=cid, eid=eid)
                    failures += 1

                else:
                    entry = onu_db[cid][eid]
                    self.strobe_watchdog()
                    self._sync_sm.mib_set(cid, eid, entry[ATTRIBUTES_KEY])
                    successes += 1

                    # If we do nothing but DB updates for ALOT of MEs, we are
                    # blocking other async twisted tasks, be kind and pause
                    self._db_updates += 1

                    if self._db_updates >= MibReconcileTask.max_sequential_db_updates:
                        self._db_updates = 0
                        self._local_deferred = yield asleep(MibReconcileTask.db_update_pause)

            except Exception as e:
                self.log.warn('onu-only-error', e=e)
                failures += 1

        returnValue((successes, failures))
    def connect(self, connect_timeout=None):
        """
        Connect to the NETCONF server
          o To disable attempting publickey authentication altogether, call with
            allow_agent and look_for_keys as False.`

          o hostkey_verify enables hostkey verification from ~/.ssh/known_hosts

        :return: (deferred) Deferred request
        """
        yield asleep(random.uniform(0.1, 5.0))   # Simulate NETCONF request delay
        self._connected = True
        self._locked = {}
        returnValue(True)
Exemplo n.º 17
0
    def snapshot_mib(self):
        """
        Snapshot the MIB on the ONU and create a copy of our local MIB database

        :return: (pair) (db_copy, number_of_commands)
        """
        db_copy = None
        number_of_commands = None

        try:
            max_tries = MibResyncTask.max_db_copy_retries - 1

            for retries in xrange(0, max_tries + 1):
                # Send MIB Upload so ONU snapshots its MIB
                try:
                    self.strobe_watchdog()
                    number_of_commands = yield self.send_mib_upload()

                    if number_of_commands is None:
                        if retries >= max_tries:
                            db_copy = None
                            break

                except (TimeoutError, ValueError) as e:
                    self.log.warn('timeout-or-value-error', e=e)
                    if retries >= max_tries:
                        raise

                    self.strobe_watchdog()
                    yield asleep(MibResyncTask.db_copy_retry_delay)
                    continue

                # Get a snapshot of the local MIB database
                db_copy = self._device.query_mib()
                # if we made it this far, no need to keep trying
                break

        except Exception as e:
            self.log.exception('mib-resync', e=e)
            raise

        # Handle initial failures

        if db_copy is None or number_of_commands is None:
            raise MibCopyException(
                'Failed to snapshot MIB copy after {} retries'.format(
                    MibResyncTask.max_db_copy_retries))

        returnValue((db_copy, number_of_commands))
Exemplo n.º 18
0
    def get_vcore_subscription(self):
        log.debug('start-get-vcore-subscription')

        while self.running and self.subscription is None:
            try:
                # If a subscription is not yet assigned then establish new GRPC connection
                # ... otherwise keep using existing connection details
                if self.subscription is None:
                    self._assign_grpc_attributes()

                # Send subscription request to register the current ofagent instance
                container_name = self.instance_id
                if self.grpc_client is None:
                    self.grpc_client = GrpcClient(self, self.channel,
                                                  self.grpc_timeout,
                                                  self.core_binding_key,
                                                  self.core_transaction_key)
                subscription = yield self.grpc_client.subscribe(
                    OfAgentSubscriber(ofagent_id=container_name))

                # If the subscriber id matches the current instance
                # ... then the subscription has succeeded
                if subscription is not None and subscription.ofagent_id == container_name:
                    if self.subscription is None:
                        # Keep details on the current GRPC session and subscription
                        log.debug('subscription-with-vcore-successful',
                                  subscription=subscription)
                        self.subscription = subscription
                        self.grpc_client.start()

                    # Sleep a bit in between each subscribe
                    yield asleep(self.subscription_refresh_interval)

                    # Move on to next subscribe request
                    continue

                # The subscription did not succeed, reset and move on
                else:
                    log.info('subscription-with-vcore-unavailable',
                             subscription=subscription)

            except _Rendezvous, e:
                log.error('subscription-with-vcore-terminated',
                          exception=e,
                          status=e.code())

            except Exception as e:
                log.exception('unexpected-subscription-termination-with-vcore',
                              e=e)
Exemplo n.º 19
0
    def snapshot_alarm(self):
        """
        Snapshot the ALARM on the ONU and create a copy of our local ALARM database

        :return: (pair) (command_sequence_number)
        """
        olt_db_copy = None
        command_sequence_number = None

        try:
            max_tries = AlarmResyncTask.max_retries - 1

            for retries in range(0, max_tries + 1):
                # Send ALARM Upload so ONU snapshots its ALARM
                try:
                    command_sequence_number = yield self.send_alarm_upload()
                    self.strobe_watchdog()

                    if command_sequence_number is None:
                        if retries >= max_tries:
                            olt_db_copy = None
                            break

                except TimeoutError as e:
                    self.log.warn('timeout', e=e)
                    if retries >= max_tries:
                        raise

                    self.strobe_watchdog()
                    yield asleep(AlarmResyncTask.retry_delay)
                    continue

                # Get a snapshot of the local MIB database
                olt_db_copy = self._device.query_alarm_table()
                # if we made it this far, no need to keep trying
                break

        except Exception as e:
            self.log.exception('alarm-resync', e=e)
            raise

        # Handle initial failures

        if olt_db_copy is None or command_sequence_number is None:
            raise AlarmCopyException(
                'Failed to snapshot ALARM copy after {} retries'.format(
                    AlarmResyncTask.max_retries))

        returnValue((olt_db_copy, command_sequence_number))
    def lock(self, source, lock_timeout):
        """
        Lock the configuration system
        :param source: is the name of the configuration datastore accessed
        :param lock_timeout: timeout in seconds for holding the lock
        :return: (defeered) for RpcReply
        """
        expire_time = time.time() + lock_timeout

        if source not in self._locked:
            self._locked[source] = None

        while self._locked[source] is not None:
            # Watch for lock timeout
            if time.time() >= self._locked[source]:
                self._locked[source] = None
                break
            yield asleep(0.1)

        if time.time() < expire_time:
            yield asleep(random.uniform(0.1, 0.5))   # Simulate NETCONF request delay
            self._locked[source] = expire_time

        returnValue(RPCReply(_dummy_xml) if expire_time > time.time() else RPCError('TODO'))
    def unlock(self, source):
        """
        Get the requested data from the server
        :param rpc_string: RPC request
        :param source: is the name of the configuration datastore accessed
        :return: (defeered) for RpcReply
        """
        if source not in self._locked:
            self._locked[source] = None

        if self._locked[source] is not None:
            yield asleep(random.uniform(0.1, 0.5))   # Simulate NETCONF request delay

        self._locked[source] = None
        returnValue(RPCReply(_dummy_xml))
Exemplo n.º 22
0
    def perform_task(self):
        """
        Get the 'mib_data_sync' attribute of the ONU
        """
        try:
            if self._delay > 0:
                yield asleep(self._delay)

            if self._success:
                self.deferred.callback(self._value)

            self.deferred.errback(failure.Failure(self._value))

        except Exception as e:
            self.deferred.errback(failure.Failure(e))
    def test_in_sync_with_circuitpack_values(self):
        self.setup_one_of_each()
        self.assertEqual(len(self.omci_agent.device_ids()), 1)

        cp_entity = 0x100
        num_ports = 1
        serial_num = 'ABCD01234'
        cp_version = '1234ABCD'
        vendor_id = 'AB-9876'
        tconts = 2
        pqueues = 64
        sched_count = 8

        def stuff_db(_results):
            self._stuff_database([
                (CircuitPack.class_id, cp_entity, {'number_of_ports': num_ports,
                                                   'serial_number': serial_num,
                                                   'version': cp_version,
                                                   'vendor_id': vendor_id,
                                                   'total_tcont_buffer_number': tconts,
                                                   'total_priority_queue_number': pqueues,
                                                   'total_traffic_scheduler_number': sched_count,
                                                   })])

        def do_my_tests(_results):
            config = self.onu_device.configuration

            circuitpack = config.circuitpack_entities
            self.assertTrue(isinstance(circuitpack, dict))
            self.assertEqual(len(circuitpack), 1)
            self.assertEqual(circuitpack[cp_entity]['entity-id'], cp_entity)
            self.assertEqual(circuitpack[cp_entity]['number-of-ports'], num_ports)
            self.assertEqual(circuitpack[cp_entity]['serial-number'], serial_num)
            self.assertEqual(circuitpack[cp_entity]['version'], cp_version)
            self.assertEqual(circuitpack[cp_entity]['vendor-id'], vendor_id)
            self.assertEqual(circuitpack[cp_entity]['total-tcont-count'], tconts)
            self.assertEqual(circuitpack[cp_entity]['total-priority-queue-count'], pqueues)
            self.assertEqual(circuitpack[cp_entity]['total-traffic-sched-count'], sched_count)

        # No capabilities available until started
        self.assertIsNone(self.onu_device.configuration)

        # Yield context so that MIB Database callLater runs.
        self.onu_device.start()
        d = asleep(0.2)
        d.addCallbacks(stuff_db, self.not_called)
        d.addCallbacks(do_my_tests, self.not_called)
        return d
Exemplo n.º 24
0
    def upload_alarm(self, command_sequence_number):
        ########################################
        # Begin ALARM Upload
        seq_no = None

        for seq_no in range(command_sequence_number):
            max_tries = AlarmResyncTask.max_alarm_upload_next_retries

            for retries in range(0, max_tries):
                try:
                    response = yield self._device.omci_cc.send_get_all_alarm_next(
                        seq_no)
                    self.strobe_watchdog()

                    omci_msg = response.fields['omci_message'].fields
                    alarm_class_id = omci_msg['alarmed_entity_class']
                    alarm_entity_id = omci_msg['alarmed_entity_id']

                    alarm_bit_map = omci_msg['alarm_bit_map']
                    attributes = {
                        AlarmDbExternal.ALARM_BITMAP_KEY: alarm_bit_map
                    }

                    # Save to the database
                    self._db_active.set(self.device_id, alarm_class_id,
                                        alarm_entity_id, attributes)
                    break

                except TimeoutError:
                    self.log.warn(
                        'alarm-resync-timeout',
                        seq_no=seq_no,
                        command_sequence_number=command_sequence_number)

                    if retries < max_tries - 1:
                        yield asleep(AlarmResyncTask.alarm_upload_next_delay)
                        self.strobe_watchdog()
                    else:
                        raise

                except Exception as e:
                    self.log.exception(
                        'resync',
                        e=e,
                        seq_no=seq_no,
                        command_sequence_number=command_sequence_number)

        returnValue(seq_no + 1)  # seq_no is zero based and alarm table.
Exemplo n.º 25
0
    def reboot(self):
        self.log.info('rebooting', device_id=self.device_id)

        # Update the connect status to UNREACHABLE
        yield self.core_proxy.device_state_update(
            self.device_id, connect_status=ConnectStatus.UNREACHABLE)

        # Sleep 10 secs, simulating a reboot
        # TODO: send alert and clear alert after the reboot
        yield asleep(10)

        # Change the connection status back to REACHABLE.  With a
        # real ONU the connection state must be the actual state
        yield self.core_proxy.device_state_update(
            self.device_id, connect_status=ConnectStatus.REACHABLE)

        self.log.info('rebooted', device_id=self.device_id)
Exemplo n.º 26
0
    def test_in_sync_with_software_values(self):
        self.setup_one_of_each()
        self.assertEqual(len(self.omci_agent.device_ids()), 1)

        sw_entity = 0x200
        sw_version = 'Beta-0.0.2'
        sw_hash = md5("just_a_test").hexdigest()
        prod_code = 'MySoftware'
        sw_active = True
        sw_committed = True
        sw_valid = True

        def stuff_db(_results):
            self._stuff_database([(SoftwareImage.class_id, sw_entity, {
                'version': sw_version,
                'is_committed': sw_committed,
                'is_active': sw_active,
                'is_valid': sw_valid,
                'product_code': prod_code,
                'image_hash': sw_hash,
            })])

        def do_my_tests(_results):
            config = self.onu_device.configuration

            images = config.software_images
            self.assertTrue(isinstance(images, list))
            self.assertEqual(len(images), 1)
            self.assertEqual(
                images[0].name,
                'running-revision' if sw_active else 'candidate-revision')
            self.assertEqual(images[0].version, sw_version)
            self.assertEqual(images[0].is_active, 1 if sw_active else 0)
            self.assertEqual(images[0].is_committed, 1 if sw_committed else 0)
            self.assertEqual(images[0].is_valid, 1 if sw_valid else 0)
            self.assertEqual(images[0].hash, sw_hash)

        # No capabilities available until started
        self.assertIsNone(self.onu_device.configuration)

        # Yield context so that MIB Database callLater runs.
        self.onu_device.start()
        d = asleep(0.2)
        d.addCallbacks(stuff_db, self.not_called)
        d.addCallbacks(do_my_tests, self.not_called)
        return d
Exemplo n.º 27
0
    def test_mib_query_ok_if_dev_started(self):
        self.setup_one_of_each()

        onu_device = self.agent.add_device(DEFAULT_ONU_DEVICE_ID,
                                           self.adapter_agent)
        self.assertIsNotNone(onu_device)
        self.assertEqual(len(self.agent.device_ids()), 1)
        self.assertEqual(self.agent.get_device(DEFAULT_ONU_DEVICE_ID),
                         onu_device)

        def not_called(_reason):
            onu_device.stop()
            assert False, 'Should never be called'

        def check_status(_results):
            # Device started. Query will succeed but nothing should be populated
            # but the most basic items

            results = onu_device.query_mib()
            self.assertTrue(isinstance(results, dict))
            self.assertEqual(results.get(DEVICE_ID_KEY), DEFAULT_ONU_DEVICE_ID)

            self.assertIsNotNone(results.get(VERSION_KEY))
            self.assertIsNotNone(results.get(CREATED_KEY))
            self.assertIsNone(
                results.get(MODIFIED_KEY))  # Created! but not yet modified

            self.assertEqual(results.get(MDS_KEY), 0)
            self.assertIsNone(results.get(LAST_SYNC_KEY))

            self.assertIsNone(results.get(CLASS_ID_KEY))

            # Stopping still allows a query.  Note you just delete a device
            # to clean up any associated databases
            onu_device.stop()
            results = onu_device.query_mib()
            self.assertTrue(isinstance(results, dict))

        # Yield context so that MIB Database callLater runs. This is a waiting
        # Async task from when the OpenOMCIAgent was started. But also start the
        # device so that it's queued async state machines can run as well
        onu_device.start()
        d = asleep(0.2)
        d.addCallbacks(check_status, not_called)

        return d
Exemplo n.º 28
0
    def test_in_sync_with_cardholder_values(self):
        self.setup_one_of_each()
        self.assertEqual(len(self.omci_agent.device_ids()), 1)

        ch_entity = 0x102
        unit_type = 255
        clie_code = 'abc123'
        prot_ptr = 0

        def stuff_db(_results):
            self._stuff_database([(Cardholder.class_id, ch_entity, {
                'actual_plugin_unit_type': unit_type,
                'actual_equipment_id': clie_code,
                'protection_profile_pointer': prot_ptr,
            })])

        def do_my_tests(_results):
            config = self.onu_device.configuration

            cardholder = config.cardholder_entities
            self.assertTrue(isinstance(cardholder, dict))
            self.assertEqual(len(cardholder), 1)
            self.assertEqual(cardholder[ch_entity]['entity-id'], ch_entity)
            self.assertEqual(cardholder[ch_entity]['is-single-piece'],
                             ch_entity >= 256)
            self.assertEqual(cardholder[ch_entity]['slot-number'],
                             ch_entity & 0xFF)
            self.assertEqual(cardholder[ch_entity]['actual-plug-in-type'],
                             unit_type)
            self.assertEqual(cardholder[ch_entity]['actual-equipment-id'],
                             clie_code)
            self.assertEqual(cardholder[ch_entity]['protection-profile-ptr'],
                             prot_ptr)

        # No capabilities available until started
        self.assertIsNone(self.onu_device.configuration)

        # Yield context so that MIB Database callLater runs.
        self.onu_device.start()
        d = asleep(0.2)
        d.addCallbacks(stuff_db, self.not_called)
        d.addCallbacks(do_my_tests, self.not_called)
        return d
Exemplo n.º 29
0
    def test_defaults(self):
        self.setup_one_of_each()
        self.assertEqual(len(self.omci_agent.device_ids()), 1)

        @raises(AssertionError)
        def do_my_tests(_results):
            config = self.onu_device.configuration
            # Should raise assertion if never been synchronized
            config.version

        # No capabilities available until started
        self.assertIsNone(self.onu_device.configuration)

        # Yield context so that MIB Database callLater runs. This is a waiting
        # Async task from when the OpenOMCIAgent was started. But also start the
        # device so that it's queued async state machines can run as well
        self.onu_device.start()
        d = asleep(0.2)
        d.addCallbacks(do_my_tests, self.not_called)
        return d
Exemplo n.º 30
0
 def _register_with_core(self, retries):
     while 1:
         try:
             resp = yield self.core_proxy.register(
                 self.adapter.adapter_descriptor(),
                 self.adapter.device_types())
             if resp:
                 self.log.info('registered-with-core',
                               coreId=resp.instance_id)
             returnValue(resp)
         except TimeOutError as e:
             self.log.warn("timeout-when-registering-with-core", e=e)
             if retries == 0:
                 self.log.exception("no-more-retries", e=e)
                 raise
             else:
                 retries = retries if retries < 0 else retries - 1
                 yield asleep(defs['retry_interval'])
         except Exception as e:
             self.log.exception("failed-registration", e=e)
             raise