Ejemplo n.º 1
0
    def handle_packet_in(self, event):
        """Handle PacketIn Event.

        Install flows allowing communication between switch ports.

        Args:
            event (KytosPacketIn): Received Event
        """
        log.debug("PacketIn Received")

        packet_in = event.content['message']

        ethernet = Ethernet()
        ethernet.unpack(packet_in.data.value)

        # Ignore LLDP packets or packets not generated by table-miss flows
        if (ethernet.destination in settings.lldp_macs
                or packet_in.reason != PacketInReason.OFPR_NO_MATCH):
            return

        # Learn the port where the sender is connected
        in_port = packet_in.in_port.value
        switch = event.source.switch
        switch.update_mac_table(ethernet.source, in_port)

        ports = switch.where_is_mac(ethernet.destination)

        # Add a flow to the switch if the destination is known
        if ports:
            flow_mod = FlowMod()
            flow_mod.command = FlowModCommand.OFPFC_ADD
            flow_mod.match = Match()
            flow_mod.match.dl_src = ethernet.source.value
            flow_mod.match.dl_dst = ethernet.destination.value
            flow_mod.match.dl_type = ethernet.ether_type
            flow_mod.actions.append(ActionOutput(port=ports[0]))
            event_out = KytosEvent(name=('kytos/of_l2ls.messages.out.'
                                         'ofpt_flow_mod'),
                                   content={
                                       'destination': event.source,
                                       'message': flow_mod
                                   })
            self.controller.buffers.msg_out.put(event_out)

        # Send the packet to correct destination or flood it
        packet_out = PacketOut()
        packet_out.buffer_id = packet_in.buffer_id
        packet_out.in_port = packet_in.in_port
        packet_out.data = packet_in.data

        port = ports[0] if ports else Port.OFPP_FLOOD
        packet_out.actions.append(ActionOutput(port=port))
        event_out = KytosEvent(name=('kytos/of_l2ls.messages.out.'
                                     'ofpt_packet_out'),
                               content={
                                   'destination': event.source,
                                   'message': packet_out
                               })

        self.controller.buffers.msg_out.put(event_out)
Ejemplo n.º 2
0
    def handle_stats_reply(self, event):
        """Handle stats replies for v0x01 switches.

        Args:
            event (:class:`~kytos.core.events.KytosEvent):
                Event with ofpt_stats_reply in message.
        """
        switch = event.source.switch
        msg = event.content['message']
        if msg.body_type == StatsType.OFPST_FLOW:
            switch.flows = [
                Flow01.from_of_flow_stats(f, switch) for f in msg.body
            ]
            event_raw = KytosEvent(name='kytos/of_core.flow_stats.received',
                                   content={'switch': switch})
            self.controller.buffers.app.put(event_raw)
        elif msg.body_type == StatsType.OFPST_PORT:
            port_stats = [of_port_stats for of_port_stats in msg.body]
            port_stats_event = KytosEvent(name=f"kytos/of_core.port_stats",
                                          content={
                                              'switch': switch,
                                              'port_stats': port_stats
                                          })
            self.controller.buffers.app.put(port_stats_event)
        elif msg.body_type == StatsType.OFPST_DESC:
            switch.update_description(msg.body)
Ejemplo n.º 3
0
def send_packet_out(controller, switch, port, data):
    """ Just prepare the PacketOut to be used by the Tracer.

    Args:
        controller: Kytos controller
        switch: OpenFlow datapath
        port: in_port
        data: Ethernet frame
    Return:
        output_action = ActionOutput
    """
    output_action = ActionOutput()
    output_action.port = settings.OFPP_TABLE

    packet_out = PacketOut()
    packet_out.actions.append(output_action)
    packet_out.in_port = port
    packet_out.data = bytes(data)

    event_out = KytosEvent()
    event_out.name = 'kytos/of_lldp.messages.out.ofpt_packet_out'
    event_out.content = {
        'destination': switch.connection,
        'message': packet_out
    }

    log.debug('PacketOut %s sent' % event_out.content)
    controller.buffers.msg_out.put(event_out)
Ejemplo n.º 4
0
    def listen(self, switch, flows_stats):
        """Receive flow stats."""
        flow_class = FlowFactory.get_class(switch)
        for flow_stat in flows_stats:
            flow = flow_class.from_of_flow_stats(flow_stat, switch)

            # Update controller's flow
            controller_flow = switch.get_flow_by_id(flow.id)
            if controller_flow:
                controller_flow.stats = flow.stats

            # Save packet_count using kytos/kronos
            namespace = f'kytos.kronos.{switch.id}.flow_id.{flow.id}'
            content = {'namespace': namespace,
                       'value': {'packet_count': flow.stats.packet_count},
                       'callback': self._save_event_callback,
                       'timestamp': time.time()}

            event = KytosEvent(name='kytos.kronos.save', content=content)
            self._app_buffer.put(event)

            # Save byte_count using kytos/kronos
            namespace = f'kytos.kronos.{switch.id}.flow_id.{flow.id}'
            content = {'namespace': namespace,
                       'value': {'byte_count': flow.stats.byte_count},
                       'callback': self._save_event_callback,
                       'timestamp': time.time()}

            event = KytosEvent(name='kytos.kronos.save', content=content)
            self._app_buffer.put(event)
Ejemplo n.º 5
0
def clean_circuits(circuits, controller):
    """Remove sub-circuits."""
    cleaned_circuits = []
    event = KytosEvent(name='amlight/kytos_courier.slack_send')
    content = {'channel': 'tests', 'source': 'amlight/sdntrace_cp'}
    for circuit in circuits:
        sub = False
        for other in circuits:
            if circuit['circuit'] == other['circuit']:
                continue
            sub = True
            for step in circuit['circuit']:
                if step not in other['circuit']:
                    sub = False
                    break
            if sub:
                break
        if not sub:
            cleaned_circuits.append(circuit)

    for circuit in cleaned_circuits:
        has_return = False
        for other in cleaned_circuits:
            if compare_endpoints(circuit['circuit'][0],
                                 other['circuit'][-1]) \
                    and compare_endpoints(circuit['circuit'][-1],
                                          other['circuit'][0]):
                has_return = True
        if not has_return:
            content['m_body'] = \
                'Circuit %s has no way back' % circuit['circuit']
            event.content['message'] = content
            controller.buffers.app.put(event)
    return cleaned_circuits
Ejemplo n.º 6
0
def send_packet_out(controller, switch, port, data):
    """ Just prepare the PacketOut to be used by the Tracer.

    Args:
        controller: Kytos controller
        switch: OpenFlow datapath
        port: in_port
        data: Ethernet frame
    Return:
        output_action = ActionOutput
    """
    output_action = ActionOutput()
    output_action.port = settings.OFPP_TABLE

    packet_out = PacketOut()
    packet_out.actions.append(output_action)
    packet_out.in_port = port
    packet_out.data = bytes(data)

    event_out = KytosEvent()
    event_out.name = 'kytos/of_lldp.messages.out.ofpt_packet_out'
    event_out.content = {'destination': switch.connection,
                         'message': packet_out}

    log.debug('PacketOut %s sent' % event_out.content)
    controller.buffers.msg_out.put(event_out)
Ejemplo n.º 7
0
    def handle_packet_in(self, event):
        """Handle PacketIn Event.

        Install flows allowing communication between switch ports.

        Args:
            event (KytosPacketIn): Received Event
        """
        log.debug("PacketIn Received")

        packet_in = event.content['message']

        ethernet = Ethernet()
        ethernet.unpack(packet_in.data.value)

        # Ignore LLDP packets or packets not generated by table-miss flows
        if (ethernet.destination in settings.LLDP_MACS
                or packet_in.reason != PacketInReason.OFPR_NO_MATCH):
            return

        switch = event.source.switch
        version = switch.ofp_version

        # Learn the port where the sender is connected
        if version == '0x01':
            in_port = packet_in.in_port.value
        else:
            in_port = packet_in.in_port

        switch.update_mac_table(ethernet.source, in_port)

        ports = switch.where_is_mac(ethernet.destination)

        # Add a flow to the switch if the destination is known
        if ports:
            flow_mod = self._create_flow_mod(version, ethernet, ports[0])

            event_out = KytosEvent(name=('kytos/of_l2ls.messages.out.'
                                         'ofpt_flow_mod'),
                                   content={
                                       'destination': event.source,
                                       'message': flow_mod
                                   })
            self.controller.buffers.msg_out.put(event_out)

        # Send the packet to correct destination or flood it
        packet_out = self._create_packet_out(version, packet_in, ports)

        event_out = KytosEvent(name=('kytos/of_l2ls.messages.out.'
                                     'ofpt_packet_out'),
                               content={
                                   'destination': event.source,
                                   'message': packet_out
                               })

        self.controller.buffers.msg_out.put(event_out)
Ejemplo n.º 8
0
    def execute(self):
        "KytosNApp execute"

        event = KytosEvent(name='viniciusarcanjo/kyslacker.send')
        d = {
            'channel': 'of_notifications',
            'source': '{0}/{1}'.format(self.username, self.name),
            'tag': 'INFO',
            'payload': 'L2circuit X was provisioned for customer A'
        }
        event.content['message'] = d
        log.info('sending message to kyslacker...')
        self.controller.buffers.app.put(event)
Ejemplo n.º 9
0
    def handle_stats_reply(self, msg, switch):
        """Insert flows received in the switch list of flows."""
        try:
            old_flows = switch.generic_flows
        except AttributeError:
            old_flows = []
        switch.generic_flows = []
        for flow_stats in msg.body:
            flow = GenericFlow.from_flow_stats(flow_stats, switch.ofp_version)
            switch.generic_flows.append(flow)
        switch.generic_flows.sort(key=lambda f: (f.priority, f.duration_sec),
                                  reverse=True)
        if switch.generic_flows != old_flows:
            # Generate an event informing that flows have changed
            event = KytosEvent('amlight/kytos_flow_manager.flows_updated')
            event.content['switch'] = switch.dpid
            self.controller.buffers.app.put(event)

            # Generate an event to store the new set of flows
            event = KytosEvent('kytos/storehouse.create')
            event.content['callback'] = self.storehouse_callback
            event.content['namespace'] = 'flow history'
            data = {
                'switch': switch.dpid,
                'date': datetime.now(),
                'flows': [flow.to_dict() for flow in switch.generic_flows]
            }
            event.content['data'] = data
            self.controller.buffers.app.put(event)
Ejemplo n.º 10
0
    def flows_date(self, dpid):
        """Get the list of flows in a switch at an specific point in time."""

        flows_lists = []
        flows_filled = False
        try:
            date = request.args['date']
        except KeyError:
            return 'Date missing', 400
        try:
            date = datetime.strptime(date, '%Y-%m-%d')
        except ValueError:
            try:
                date = datetime.strptime(date, '%Y-%m-%d %H:%M:%S')
            except ValueError:
                return 'Bad date format', 400

        def storehouse_list(event, flows_list, error=False):
            """Receive the list of flow ids."""
            # pylint: disable=unused-argument
            nonlocal flows_lists, flows_filled
            flows_lists = flows_list
            flows_filled = True

        event = KytosEvent('kytos/storehouse.list')
        event.content['callback'] = storehouse_list
        event.content['namespace'] = 'flow_history_%s' % dpid
        self.controller.buffers.app.put(event)

        flows = None
        while not flows_filled:
            pass

        event = KytosEvent('kytos/storehouse.retrieve')
        event.content['namespace'] = 'flow_history_%s' % dpid
        for flow_list_id in flows_lists:
            flow_list = {}

            def storehouse_retrive(event, box, error=False):
                """Receive one flow."""
                # pylint: disable=unused-argument
                nonlocal flow_list
                flow_list = box.data
            event.content['box_id'] = flow_list_id
            event.content['callback'] = storehouse_retrive
            self.controller.buffers.app.put(event)
            while not flow_list:
                pass
            if flow_list['date'] <= date:
                if flows is None or flow_list['date'] > flows['date']:
                    flows = flow_list

        return jsonify(flows)
Ejemplo n.º 11
0
    def _send_specific_port_mod(self, port, interface, current_interface):
        """Dispatch port link_up/link_down events."""
        event_name = 'kytos/of_core.switch.interface.'
        event_content = {'interface': interface}

        # This should not be created because is a config state (operational)
        # if port.config.value % 2:
        #     status = 'down'
        # else:
        #     status = 'up'

        # event = KytosEvent(name=event_name+status, content=event_content)
        # self.controller.buffers.app.put(event)

        if port.state.value % 2:
            status = 'link_down'
        else:
            status = 'link_up'

        try:
            if current_interface.state % 2:
                current_status = 'link_down'
            else:
                current_status = 'link_up'
        except AttributeError:
            current_status = None

        if status != current_status:
            event = KytosEvent(name=event_name+status, content=event_content)
            self.controller.buffers.app.put(event)
Ejemplo n.º 12
0
    def _send_flow_mod(self, switch, flow_mod):
        event_name = 'kytos/flow_manager.messages.out.ofpt_flow_mod'

        content = {'destination': switch.connection, 'message': flow_mod}

        event = KytosEvent(name=event_name, content=content)
        self.controller.buffers.msg_out.put(event)
Ejemplo n.º 13
0
    def save_metadata_on_store(self, event):
        """Send to storehouse the data updated."""
        name = 'kytos.storehouse.update'
        if 'switch' in event.content:
            store = self.store_items.get('switches')
            obj = event.content.get('switch')
            namespace = 'kytos.topology.switches.metadata'
        elif 'interface' in event.content:
            store = self.store_items.get('interfaces')
            obj = event.content.get('interface')
            namespace = 'kytos.topology.iterfaces.metadata'
        elif 'link' in event.content:
            store = self.store_items.get('links')
            obj = event.content.get('link')
            namespace = 'kytos.topology.links.metadata'

        store.data[obj.id] = obj.metadata
        content = {
            'namespace': namespace,
            'box_id': store.box_id,
            'data': store.data,
            'callback': self.update_instance
        }

        event = KytosEvent(name=name, content=content)
        self.controller.buffers.app.put(event)
Ejemplo n.º 14
0
    def update_port_status(self, event):
        """Dispatch 'port.[created|modified|deleted]' event.

        Listen:
            `kytos/of_core.v0x0[14].messages.in.ofpt_port_status`

        Dispatch:
            `kytos/of_topology.switch.port.[created|modified|deleted]`:
                { switch : <switch.id>,
                  port: <port.port_no>
                  port_description: {<description of the port>}
                }

        """
        port_status = event.message
        reason = port_status.reason.value

        name = 'kytos/of_topology.switch.port.' + reason.lower()
        content = {
            'switch': event.source.id,
            'port': port_status.desc.port_no,
            'port_description': vars(port_status.desc)
        }

        event = KytosEvent(name=name, content=content)
        self.controller.buffers.app.put(event)

        msg = 'The port %s (%s) from switch %s was %s.'
        log.debug(msg, port_status.desc.port_no, event.source.id, reason)
Ejemplo n.º 15
0
    def update_port_status(self, port_status, source):
        """Dispatch 'port.*' events.

        Current events:

        created|deleted|up|down|link_up|link_down|modified

        Args:
            port_status: python openflow (pyof) PortStatus object.
            source: kytos.core.switch.Connection instance.

        Dispatch:
            `kytos/of_core.switch.port.[created|modified|deleted]`:
                {
                  switch : <switch.id>,
                  port: <port.port_no>
                  port_description: {<description of the port>}
                }

        """
        reason = port_status.reason.enum_ref(port_status.reason.value).name
        port = port_status.desc
        event_name = 'kytos/of_core.switch.interface.'

        if reason == 'OFPPR_ADD':
            status = 'created'
            interface = Interface(name=port.name.value,
                                  address=port.hw_addr.value,
                                  port_number=port.port_no.value,
                                  switch=source.switch,
                                  state=port.state.value,
                                  features=port.curr)
            source.switch.update_interface(interface)

        elif reason == 'OFPPR_MODIFY':
            status = 'modified'
            interface = Interface(name=port.name.value,
                                  address=port.hw_addr.value,
                                  port_number=port.port_no.value,
                                  switch=source.switch,
                                  state=port.state.value,
                                  features=port.curr)
            source.switch.update_interface(interface)

            self._send_specific_port_mod(port, interface)

        elif reason == 'OFPPR_DELETE':
            status = 'deleted'
            interface = source.switch.get_interface_by_port_no(
                port.port_no.value)
            source.switch.remove_interface(interface)

        event_name += status
        content = {'interface': interface}

        event = KytosEvent(name=event_name, content=content)
        self.controller.buffers.app.put(event)

        msg = 'The port %s from switch %s was %s.'
        log.debug(msg, port_status.desc.port_no, source.switch.id, status)
Ejemplo n.º 16
0
    def listen(self, switch, aggregate_stats):
        """Receive flow stats."""
        debug_msg = 'Received aggregate stats from switch {}:' \
                    ' packet_count {}, byte_count {}, flow_count {}'

        for aggregate in aggregate_stats:
            # need to choose the _id to aggregate_stats
            # this class isn't used yet.

            log.debug(debug_msg, switch.id, aggregate.packet_count.value,
                      aggregate.byte_count.value, aggregate.flow_count.value)

            # Save aggregate stats using kytos/kronos
            namespace = f'kytos.kronos.aggregated_stats.{switch.id}'
            stats_to_send = {'aggregate_id': aggregate.id,
                             'packet_count': aggregate.packet_count.value,
                             'byte_count': aggregate.byte_count.value,
                             'flow_count': aggregate.flow_count.value}

            content = {'namespace': namespace,
                       'value': stats_to_send,
                       'callback': self._save_event_callback,
                       'timestamp': time.time()}

            event = KytosEvent(name='kytos.kronos.save', content=content)
            self._app_buffer.put(event)
Ejemplo n.º 17
0
    def install_lldp_flow(self, event):
        """Install a flow to send LLDP packets to the controller.

        The proactive flow is installed whenever a switch connects.

        Args:
            event (:class:`~kytos.core.events.KytosEvent`):
                Event with new switch information.

        """
        try:
            of_version = event.content['switch'].connection.protocol.version
        except AttributeError:
            of_version = None

        flow_mod = self._build_lldp_flow_mod(of_version)

        if flow_mod:
            name = 'kytos/of_lldp.messages.out.ofpt_flow_mod'
            content = {
                'destination': event.content['switch'].connection,
                'message': flow_mod
            }

            event_out = KytosEvent(name=name, content=content)
            self.controller.buffers.msg_out.put(event_out)
Ejemplo n.º 18
0
    def update_links(self, event):
        """Dispatch 'reacheable.mac' event.

        Listen:
            `kytos/of_core.v0x0[14].messages.in.ofpt_packet_in`

        Dispatch:
            `reachable.mac`:
                { switch : <switch.id>,
                  port: <port.port_no>
                  reachable_mac: <mac_address>
                }

        """
        ethernet = Ethernet()
        ethernet.unpack(event.message.data.value)

        name = 'kytos/of_topology.reachable.mac'
        content = {
            'switch': event.source.switch.id,
            'port': event.message.in_port,
            'reachable_mac': ethernet.source
        }
        event = KytosEvent(name, content)
        self.controller.buffers.app.put(event)

        msg = 'The MAC %s is reachable from switch/port %s/%s.'
        log.debug(msg, ethernet.source, event.source.switch.id,
                  event.message.in_port)
Ejemplo n.º 19
0
def handle_features_reply(controller, event):
    """Handle OF v0x01 features_reply message events.

    This is the end of the Handshake workflow of the OpenFlow Protocol.
    Parameters:
        controller (Controller): Controller being used.
        event (KytosEvent): Event with features reply message.

    """
    connection = event.source
    features_reply = event.content['message']
    dpid = features_reply.datapath_id.value

    switch = controller.get_switch_or_create(dpid=dpid, connection=connection)

    for port in features_reply.ports:
        switch.update_or_create_interface(port.port_no.value,
                                          name=port.name.value,
                                          address=port.hw_addr.value,
                                          state=port.state.value,
                                          features=port.curr)
        port_event = KytosEvent(name='kytos/of_core.switch.port.created',
                                content={
                                    'switch': switch.id,
                                    'port': port.port_no.value,
                                    'port_description': {
                                        'alias': port.name.value,
                                        'mac': port.hw_addr.value,
                                        'state': port.state.value
                                    }
                                })
        controller.buffers.app.put(port_event)

    switch.update_features(features_reply)
    return switch
Ejemplo n.º 20
0
    def handle_features_reply(self, event):
        """Handle kytos/of_core.messages.in.ofpt_features_reply event.

        This is the end of the Handshake workflow of the OpenFlow Protocol.

        Args:
            event (KytosEvent): Event with features reply message.
        """
        connection = event.source
        version_utils = self.of_core_version_utils[connection.protocol.version]
        switch = version_utils.handle_features_reply(self.controller, event)

        if (connection.is_during_setup() and
                connection.protocol.state == 'waiting_features_reply'):
            connection.protocol.state = 'handshake_complete'
            connection.set_established_state()
            version_utils.send_desc_request(self.controller, switch)
            if settings.SEND_SET_CONFIG:
                version_utils.send_set_config(self.controller, switch)
            log.info('Connection %s, Switch %s: OPENFLOW HANDSHAKE COMPLETE',
                     connection.id, switch.dpid)
            event_raw = KytosEvent(
                name='kytos/of_core.handshake.completed',
                content={'switch': switch})
            self.controller.buffers.app.put(event_raw)
Ejemplo n.º 21
0
    def listen(self, switch, ports_stats):
        """Receive port stats."""
        debug_msg = 'Received port %s stats of switch %s: rx_bytes %s,' \
                    ' tx_bytes %s, rx_dropped %s, tx_dropped %s,' \
                    ' rx_errors %s, tx_errors %s'

        for port_stat in ports_stats:
            self._update_controller_interface(switch, port_stat)

            statistics_to_send = {'rx_bytes': port_stat.rx_bytes.value,
                                  'tx_bytes': port_stat.tx_bytes.value,
                                  'rx_dropped': port_stat.rx_dropped.value,
                                  'tx_dropped': port_stat.tx_dropped.value,
                                  'rx_errors': port_stat.rx_errors.value,
                                  'tx_errors': port_stat.tx_errors.value}

            port_no = port_stat.port_no.value

            namespace = f'kytos.kronos.{switch.id}.port_no.{port_no}'
            content = {'namespace': namespace,
                       'value': statistics_to_send,
                       'callback': self._save_event_callback,
                       'timestamp': time.time()}
            event = KytosEvent(name='kytos.kronos.save', content=content)
            self._app_buffer.put(event)

            log.debug(debug_msg, port_stat.port_no.value, switch.id,
                      port_stat.rx_bytes.value, port_stat.tx_bytes.value,
                      port_stat.rx_dropped.value, port_stat.tx_dropped.value,
                      port_stat.rx_errors.value, port_stat.tx_errors.value)
Ejemplo n.º 22
0
 def _send_event(self, req, conn):
     event = KytosEvent(
         name='kytos/of_stats.messages.out.ofpt_stats_request',
         content={
             'message': req,
             'destination': conn
         })
     self._buffer.put(event)
Ejemplo n.º 23
0
 def notify_lldp_change(self, state, interface_ids):
     """Dispatch a KytosEvent to notify changes to the LLDP status."""
     content = {'attribute': 'LLDP',
                'state': state,
                'interface_ids': interface_ids}
     event_out = KytosEvent(name='kytos/of_lldp.network_status.updated',
                            content=content)
     self.controller.buffers.app.put(event_out)
Ejemplo n.º 24
0
 def verify_storehouse(self, entities):
     """Request a list of box saved by specific entity."""
     name = 'kytos.storehouse.list'
     content = {'namespace': f'kytos.topology.{entities}.metadata',
                'callback': self.request_retrieve_entities}
     event = KytosEvent(name=name, content=content)
     self.controller.buffers.app.put(event)
     log.info(f'verify data in storehouse for {entities}.')
    def update_table(self, table):
        logging.info("update\n")
        logging.info(str(table))

        table = convert_format(table)
        logging.info("converted")
        logging.info(table)
        event = KytosEvent(name='snlab/ddp/setup', content=table)
        self.ctx.controller.buffers.app.put(event)
Ejemplo n.º 26
0
 def notify_link_status_change(self, link):
     """Send an event to notify about a status change on a link."""
     name = 'kytos/topology.'
     if link.is_active():
         status = 'link_up'
     else:
         status = 'link_down'
     event = KytosEvent(name=name + status, content={'link': link})
     self.controller.buffers.app.put(event)
Ejemplo n.º 27
0
 def _send_napp_event(self, switch, flow, command):
     """Send an Event to other apps informing about a FlowMod."""
     if command == 'add':
         name = 'kytos/flow_manager.flow.added'
     elif command == 'delete':
         name = 'kytos/flow_manager.flow.removed'
     content = {'datapath': switch, 'flow': flow}
     event_app = KytosEvent(name, content)
     self.controller.buffers.app.put(event_app)
Ejemplo n.º 28
0
def send_packet_out(controller, switch, port, data):
    """ Just prepare and send a PacketOut used by
    the Tracer. """
    output_action = ActionOutput()
    output_action.port = settings.OFPP_TABLE

    packet_out = PacketOut()
    packet_out.actions.append(output_action)
    packet_out.in_port = port
    packet_out.data = bytes(data)
    event_out = KytosEvent()
    event_out.name = 'kytos/of_lldp.messages.out.ofpt_packet_out'
    event_out.content = {
        'destination': switch.connection,
        'message': packet_out
    }

    log.debug('PacketOut %s sent' % event_out.content)
    controller.buffers.msg_out.put(event_out)
Ejemplo n.º 29
0
 def maintenance_event(self, operation):
     """Create events to start/end a maintenance."""
     if self._switches:
         switches = []
         for dpid in self._switches:
             switch = self.controller.switches.get(dpid, None)
             if switch:
                 switches.append(switch)
         event = KytosEvent(name=f'kytos/maintenance.{operation}_switch',
                            content={'switches': switches})
         self.controller.buffers.app.put(event)
     if self._unis:
         event = KytosEvent(name=f'kytos/maintenance.{operation}_uni',
                            content={'unis': self._unis})
         self.controller.buffers.app.put(event)
     if self._links:
         event = KytosEvent(name=f'kytos/maintenance.{operation}_link',
                            content={'links': self._links})
         self.controller.buffers.app.put(event)
Ejemplo n.º 30
0
 def clear_flows(self, dpid):
     """Clear all flows from switch identified by dpid."""
     switch = self.controller.get_switch_by_dpid(dpid)
     for flow in switch.flows:
         flow_mod = flow.as_flow_mod(FlowModCommand.OFPFC_DELETE)
         event_out = KytosEvent(name=('kytos/of_flow-manager.messages.out.'
                                      'ofpt_flow_mod'),
                                content={'destination': switch.connection,
                                         'message': flow_mod})
         self.controller.buffers.msg_out.put(event_out)
Ejemplo n.º 31
0
 def _new_port_stats(self, switch):
     """Send an event with the new port stats and clean resources."""
     all_port_stats = self._multipart_replies_ports[switch.id]
     del self._multipart_replies_ports[switch.id]
     del self._multipart_replies_xids[switch.id]['ports']
     port_stats_event = KytosEvent(name=f"kytos/of_core.port_stats",
                                   content={
                                       'switch': switch,
                                       'port_stats': all_port_stats
                                   })
     self.controller.buffers.app.put(port_stats_event)