Ejemplo n.º 1
0
class SwitchFeatures(GenericMessage):
    """Message sent by the switch device to the controller.

    This message is the response for a features_request message, sent by the
    controller to the switch device. The 'OFPT_FEATURES_REPLY' message inherits
    from this class, despite the strange name.
    """

    header = Header(message_type=Type.OFPT_FEATURES_REPLY)

    #: Datapath unique ID. The lower 48-bits are for a MAC address, while the upper 16-bits are
    #: implemented-defined.
    datapath_id = DPID()

    #: Max packets buffered at once.
    n_buffers = UBInt32()

    #: Number of tables supported by datapath.
    n_tables = UBInt8()

    #: Identify auxiliary connections
    auxiliary_id = UBInt8()

    #: Align to 64-bits.
    pad = Pad(2)

    # Features
    #: Bitmap of support "ofp_capabilities"
    capabilities = UBInt32(enum_ref=Capabilities)

    reserved = UBInt32()

    def __init__(self,
                 xid=None,
                 datapath_id=None,
                 n_buffers=None,
                 n_tables=None,
                 auxiliary_id=None,
                 capabilities=None,
                 reserved=None):
        """Create a SwitchFeatures with the optional parameters below.

        Args:
            xid (int): xid to be used on the message header.
            datapath_id (int): Datapath unique ID.
                The lower 48-bits are for MAC address, while
                the upper 16-bits are implementer-defined.
            n_buffers (int): Max packets buffered at once.
            n_tables (int): Number of tables supported by datapath.
            auxiliary_id (int): Identify auxiliary connections.
            capabilities (int): bitmap of supported capabilities.
            reserved (int): Reserved.
        """
        super().__init__(xid)
        self.datapath_id = datapath_id
        self.n_buffers = n_buffers
        self.n_tables = n_tables
        self.auxiliary_id = auxiliary_id
        self.capabilities = capabilities
        self.reserved = reserved
Ejemplo n.º 2
0
class PortMod(GenericMessage):
    """Implement messages to modify the physical port behavior."""

    header = Header(message_type=Type.OFPT_PORT_MOD)
    port_no = UBInt32()
    pad = Pad(4)
    hw_addr = HWAddress()
    pad2 = Pad(2)
    config = UBInt32(enum_ref=PortConfig)
    mask = UBInt32(enum_ref=PortConfig)
    advertise = UBInt32(enum_ref=PortFeatures)
    #: Pad to 64-bits.
    pad3 = Pad(4)

    def __init__(self, xid=None, port_no=None, hw_addr=None, config=None,
                 mask=None, advertise=None):
        """The constructor just assings parameters to object attributes.

        Args:
            xid (int): OpenFlow xid to the header.
            port_no (int): Physical port number.
            hw_addr (HWAddress): The hardware address is not configurable.
                This is used to sanity-check the request,
                so it must be the same as returned in an ofp_phy_port struct.
            config (PortConfig): Bitmap of OFPPC_* flags
            mask (PortConfig): Bitmap of OFPPC_* flags to be changed
            advertise (PortFeatures): Bitmap of OFPPF_*. Zero all bits to
                prevent any action taking place.
        """
        super().__init__(xid)
        self.port_no = port_no
        self.hw_addr = hw_addr
        self.config = config
        self.mask = mask
        self.advertise = advertise
Ejemplo n.º 3
0
class PortStatsPropExperimenter(PortStatsPropHeader):
    """
    Experimenter port stats property.
    """
    experimenter = UBInt32()
    exp_type = UBInt32()
    experimenter_data = UBInt32()

    def __init__(self,
                 experimenter=None,
                 exp_type=None,
                 experimenter_data=None):
        """
        Create the experimenter port stats property.

        :param experimenter: Experimenter ID which takes the same form as in ExperimenterHeader
        :param exp_type: Experimenter defined
        Followed by:
            - Exactly (length - 12) bytes containing the experimenter data, then
            - Exactly (length + 7)/8*8 - (length) (between 0 and 7) bytes of all-zeros bytes
        :param experimenter_data: Experimenter Data
        """
        super().type = PortStatsPropType.OFPPSPT_EXPERIMENTER
        self.experimenter = experimenter
        self.exp_type = exp_type
        self.experimenter_data = experimenter_data
        super().length = self.__sizeof__()
Ejemplo n.º 4
0
    def test_error_message_header_bad_property_codes(self):
        """
        Testing the header BadPropertyCodes.
        This function will test all code values for this enum class.
        :return: None
        """

        error_type = 14
        error_type_value = Error.ErrorType.OFPET_BAD_PROPERTY

        error_code = 0

        iter_given_code = Error.ErrorType.get_class(
            error_type_value).__iter__()
        length = Error.ErrorType.get_class(error_type_value).__len__()

        while error_code < self.MAX_BAD_PROPERTY_CODE_VALUE or length > 0:
            data = UBInt32(random.randint(2, 250)).pack()
            xid = random.randint(2, 250)

            test_value = b'\x05\x01\x00\x10' + UBInt32(xid).pack() + UBInt16(error_type).pack() + \
                        UBInt16(error_code).pack() + data

            if error_code < self.MAX_BAD_PROPERTY_CODE_VALUE:
                error_code += 1
            length -= 1
            test_object_error_messages = Error.ErrorMsg(
                xid, error_type_value, iter_given_code.__next__(),
                data).pack()

            self.assertEqual(test_value, test_object_error_messages)
Ejemplo n.º 5
0
class QueueStats(GenericStruct):
    """Implements the reply body of a port_no."""

    port_no = UBInt32()
    queue_id = UBInt32()
    tx_bytes = UBInt64()
    tx_packets = UBInt64()
    tx_errors = UBInt64()
    duration_sec = UBInt32()
    duration_nsec = UBInt32()

    def __init__(self, port_no=None, queue_id=None, tx_bytes=None,
                 tx_packets=None, tx_errors=None, duration_sec=None,
                 duration_nsec=None):
        """The constructor just assings parameters to object attributes.

        Args:
            port_no (:class:`int`, :class:`.Port`): Port Number.
            queue_id (int): Queue ID.
            tx_bytes (int): Number of transmitted bytes.
            tx_packets (int): Number of transmitted packets.
            tx_errors (int): Number of packets dropped due to overrun.
            duration_sec (int): Time queue has been alive in seconds.
            duration_nsec (int): Time queue has been alive in nanoseconds
                beyond duration_sec.
        """
        super().__init__()
        self.port_no = port_no
        self.queue_id = queue_id
        self.tx_bytes = tx_bytes
        self.tx_packets = tx_packets
        self.tx_errors = tx_errors
        self.duration_sec = duration_sec
        self.duration_nsec = duration_nsec
Ejemplo n.º 6
0
class MeterBandHeader(GenericStruct):
    """Common header for all meter bands."""

    band_type = UBInt16(enum_ref=MeterBandType)
    length = UBInt16()
    rate = UBInt32()
    burst_size = UBInt32()

    def __init__(self,
                 band_type=None,
                 length=None,
                 rate=None,
                 burst_size=None):
        """Instance attributes assignments.

        Args:
            band_type (MeterBandType): One of OFPMBT_*.
            length (int): Length in bytes of this band.
            rate (int): Rate for this band.
            burst_size (int): Size of bursts.
        """
        super().__init__()
        self.band_type = band_type
        self.length = length
        self.rate = rate
        self.burst_size = burst_size
Ejemplo n.º 7
0
class MeterBandExperimenter(GenericStruct):
    """OFPMBT_EXPERIMENTER band - Write actions in action set."""

    band_type = UBInt16(MeterBandType.OFPMBT_EXPERIMENTER,
                        enum_ref=MeterBandType)
    length = UBInt16()
    rate = UBInt32()
    burst_size = UBInt32()
    experimenter = UBInt32()

    def __init__(self,
                 length=None,
                 rate=None,
                 burst_size=None,
                 experimenter=None):
        """Instance attributes assignment.

        Args:
            length (int): Length in bytes of this band.
            rate (int): Rate for remarking packets.
            burst_size (int): Size of bursts.
            experimenter (int): Experimenter ID which takes the same form as in
                :class:`.ExperimenterHeader`.
        """
        super().__init__()
        self.length = length
        self.rate = rate
        self.burst_size = burst_size
        self.experimenter = experimenter
class TableModPropExperimenter(TableModPropHeader):
    """Experimenter table mod property"""

    #: Experimenter ID which takes the same form as in struct experimenter_header
    experimenter = UBInt32()
    #: Experimenter defined.
    exp_type = UBInt32()
    """Followed by:
        - Exactly (length - 12) bytes containing the experimenter data, then
        - Exactly (length + 7)/ 8 * 8 - (length) (between 0 and 7) bytes of all-zero bytes.
    """
    experimenter_data = UBInt32()

    def __init__(self, experimenter=None, exp_type=None):
        """

        :param experimenter: (int) Experimenter ID which takes the same form as in struct experimenter_header
        :param exp_type: (int) Experimenter defined.
        """
        super().__init__(TableModPropType.OFPTMPT_EXPERIMENTER)

        self.experimenter = experimenter

        self.exp_type = exp_type
        super().length = len(self)
Ejemplo n.º 9
0
class TableModPropExperimenter(GenericStruct):
    """Experimenter table mod property"""

    #: OFPTMPT_EXPERIMENTER
    type = UBInt16(TableModPropType.OFPTMPT_EXPERIMENTER)
    #: Length in bytes of this property
    length = UBInt16()
    #: Experimenter ID which takes the same
    # form as in struct
    # ofp_experimenter_header.
    experimenter = UBInt32()
    #: Experimenter defined
    exp_type = UBInt32()
    #: Followed by: Exactly (length - 12) bytes containing the experimenter data, then
    # Exactly (length + 7)/8*8 - (length) (between 0 and 7)
    # bytes of all-zero bytes
    experimenter_data = UBInt32()

    def __int__(self, experimenter_type=TableModPropType.OFPTMPT_EXPERIMENTER, length=None, experimenter=None, exp_type=None,
                experimenter_data=None):
        self.type = experimenter_type
        self.length = length
        self.experimenter = experimenter
        self.exp_type = exp_type
        self.experimenter_data = experimenter_data
Ejemplo n.º 10
0
class BundlePropExperimenter(BundlePropHeader):
    """Experimenter bundle property"""

    #: Experimenter ID which takes the same form as in struct experimenter_header
    experimenter = UBInt32()
    #: Experimenter defined
    exp_type = UBInt32()
    """Followed by:
        - Exactly (length - 12) bytes containing the experimenter data, then
        - Exactly (length + 7)/ 8 * 8 - (length) (between 0 and 7) bytes of all-zero bytes.
    """

    experimenter_data = UBInt32()

    def __init__(self, experimenter=None, exp_type=None):
        """
        :param experimenter: Experimenter ID which takes the same form as in struct experimenter_header
        :param exp_type: Experimenter defined
        """
        super().__init__()

        super().type = BundlePropType.OFPBPT_EXPERIMENTER

        self.experimenter = experimenter

        self.exp_type = exp_type

        super().length = self.__sizeof__()
Ejemplo n.º 11
0
class MeterFeatures(GenericStruct):
    """Body of reply to OFPMP_METER_FEATURES request. Meter features."""

    max_meter = UBInt32()
    band_types = UBInt32(enum_ref=MeterBandType)
    capabilities = UBInt32(enum_ref=MeterFlags)
    max_bands = UBInt8()
    max_color = UBInt8()
    pad = Pad(2)

    def __init__(self,
                 max_meter=None,
                 band_types=None,
                 capabilities=None,
                 max_bands=None,
                 max_color=None):
        """Create a MeterFeatures with the optional parameters below.

        Args:
            max_meter(int): Maximum number of meters.
            band_types (|MeterBandType_v0x05|):
                Bitmaps of OFPMBT_* values supported.
            capabilities (|MeterFlags_v0x05|): Bitmaps of "ofp_meter_flags".
            max_bands(int): Maximum bands per meters
            max_color(int): Maximum color value
        """
        super().__init__()
        self.max_meter = max_meter
        self.band_types = band_types
        self.capabilities = capabilities
        self.max_bands = max_bands
        self.max_color = max_color
Ejemplo n.º 12
0
class ExperimenterProperty(Property):
    """Experimenter table feature property.

    This class represents property with the following types:
        OFPTFPT_EXPERIMENTER
        OFPTFPT_EXPERIMENTER_MISS

    """
    experimenter = UBInt32()
    exp_type = UBInt32()

    experimenter_data = UBInt32()

    def __init__(self,
                 property_type=TableFeaturePropType.OFPTFPT_EXPERIMENTER,
                 experimenter=None,
                 exp_type=None,
                 experimenter_data=None):
        """ Create or initialize an object Experimenter table feature property.

        :param property_type(int): One of OFPTFPT_EXPERIMENTER, OFPTFPT_EXPERIMENTER_MISS.
        :param experimenter(int): Experimenter ID which takes the same form as in strcut ExperimenterHeader.
        :param exp_type(int): Experimenter defined.
        Followed by:
            - Exactly (length - 12) bytes containing the experimenter data, then
            - Exactly (length + 7)/8*8 - (length) (between 0 and 7) bytes of all-zero bytes.
        :param experimenter_data(int): Experimenter data.
        """

        super().__init__(property_type)
        self.experimenter = experimenter
        self.exp_type = exp_type
        self.experimenter_data = experimenter_data
        self.update_length()
class ExperimenterHeader(GenericMessage):
    """OpenFlow Experimenter message.

    The experimenter field is a 32-bit value that uniquely identifies the
    experimenter. If the most significant byte is zero, the next three bytes
    are the experimenter’s IEEE OUI. If the most significant byte is not zero,
    it is a value allocated by the Open Networking Foundation. If experimenter
    does not have (or wish to use) their OUI, they should contact the Open
    Networking Foundation to obtain a unique experimenter ID.

    The rest of the body is uninterpreted by standard OpenFlow processing and
    is arbitrarily defined by the corresponding experimenter.

    If a switch does not understand a experimenter extension, it must send an
    OFPT_ERROR message with a OFPBRC_BAD_EXPERIMENTER error code and
    OFPET_BAD_REQUEST error type.
    """

    header = Header(message_type=Type.OFPT_EXPERIMENTER)
    experimenter = UBInt32()
    exp_type = UBInt32()

    def __init__(self, xid=None, experimenter=None, exp_type=None):
        """The constructor takes the parameters below.

        Args:
            xid (int): xid to be used on the message header.
            experimenter (int): Vendor ID:
                MSB 0: low-order bytes are IEEE OUI.
                MSB != 0: defined by ONF.
            exp_type (int): Experimenter defined.
        """
        super().__init__(xid)
        self.experimenter = experimenter
        self.exp_type = exp_type
Ejemplo n.º 14
0
class MeterBandDscpRemark(GenericStruct):
    """OFPMBT_DSCP_REMARK band - Remark DSCP in the IP header."""

    band_type = UBInt16(MeterBandType.OFPMBT_DSCP_REMARK,
                        enum_ref=MeterBandType)
    length = UBInt16()
    rate = UBInt32()
    burst_size = UBInt32()
    prec_level = UBInt8()
    pad = Pad(3)

    def __init__(self,
                 length=None,
                 rate=None,
                 burst_size=None,
                 prec_level=None):
        """Instance attributes assignment.

        Args:
            length (int): Length in bytes of this band.
            rate (int): Rate for remarking packets.
            burst_size (int): Size of bursts.
            prec_level (int): Number of precendence level to substract.
        """
        super().__init__()
        self.length = length
        self.rate = rate
        self.burst_size = burst_size
        self.prec_level = prec_level
Ejemplo n.º 15
0
    def test_error_message_header_async_config_failed_codes(self):
        """
        Testing the header AsyncConfigFailedCodes.
        This function will test all code values for this enum class.
        :return: None
        """

        error_type = 15
        error_type_value = Error.ErrorType.OFPET_ASYNC_CONFIG_FAILED

        error_code = 0

        iter_given_code = Error.ErrorType.get_class(
            error_type_value).__iter__()
        length = Error.ErrorType.get_class(error_type_value).__len__()

        while error_code < self.MAX_ASYNC_CONFIG_FAILED_CODE_VALUE or length > 0:
            data = UBInt32(random.randint(2, 250)).pack()
            xid = random.randint(2, 250)

            test_value = b'\x05\x01\x00\x10' + UBInt32(xid).pack() + UBInt16(error_type).pack() + \
                        UBInt16(error_code).pack() + data

            if error_code < self.MAX_ASYNC_CONFIG_FAILED_CODE_VALUE:
                error_code += 1
            length -= 1

            test_object_error_messages = Error.ErrorMsg(
                xid, error_type_value, iter_given_code.__next__(),
                data).pack()

            self.assertEqual(test_value, test_object_error_messages)
Ejemplo n.º 16
0
class PacketQueue(GenericStruct):
    """Describe a queue."""

    #: id for the specific queue
    queue_id = UBInt32()
    #: Port this queue is attached to.
    port = UBInt32()
    #: Length, in bytes, of this queue desc.
    length = UBInt16()
    #: 64-bit alignment.
    pad = Pad(6)
    #: List of properties
    properties = ListOfProperties()

    def __init__(self, queue_id=None, port=None, length=None, properties=None):
        """Create a PacketQueue with the optional parameters below.

        Args:
            queue_id (int): ID of the specific queue.
            port (int): Port his queue is attached to.
            length (int): Length in bytes of this queue desc.
            properties(~pyof.v0x04.common.queue.ListOfProperties):
                Queue's list of properties. Default is an empty list.
        """
        super().__init__()
        self.queue_id = queue_id
        self.port = port
        self.length = length
        self.properties = [] if properties is None else properties
Ejemplo n.º 17
0
    def test_error_experimenter_message(self):
        """
        Testing the Experimenter Message.
        This function will test all code values for this enum class.
        :return: None
        """
        MAX_VALUE = 5
        # Max number of IDs to be created in the test
        MAX_NUM_ID = 20

        type = 0xffff

        for id in range(0, MAX_NUM_ID):

            # Generate a random int number between 2 and 250
            exp_code = random.randint(2, 250)

            # Generate a random int number between 2 and 120 and then convert it in binary
            data = UBInt8(random.randint(2, 120)).pack()

            # Generate a random int number between 2 and 250
            xid = random.randint(2, 250)

            test_value = b'\x05\x01\x00\x11' + UBInt32(xid).pack() + UBInt16(type).pack() + \
                        UBInt16(exp_code).pack() + UBInt32(id).pack() + data

            self.test_error_experimenter_message.__init__(
                xid, exp_code, id, data)

            test_object_error_messages = self.test_error_experimenter_message.pack(
            )

            self.assertEqual(test_value, test_object_error_messages)
Ejemplo n.º 18
0
class FlowRemoved(GenericMessage):
    """Flow removed (datapath -> controller)."""

    #: :class:`~.header.Header`: OpenFlow Header
    header = Header(message_type=Type.OFPT_FLOW_REMOVED)
    #: :class:`~.flow_match.Match`: OpenFlow Header
    match = Match()
    cookie = UBInt64()

    priority = UBInt16()
    reason = UBInt8(enum_ref=FlowRemovedReason)
    #: Align to 32-bits.
    pad = Pad(1)

    duration_sec = UBInt32()
    duration_nsec = UBInt32()

    idle_timeout = UBInt16()
    #: Align to 64-bits.
    pad2 = Pad(2)
    packet_count = UBInt64()
    byte_count = UBInt64()

    def __init__(self,
                 xid=None,
                 match=None,
                 cookie=None,
                 priority=None,
                 reason=None,
                 duration_sec=None,
                 duration_nsec=None,
                 idle_timeout=None,
                 packet_count=None,
                 byte_count=None):
        """Assign parameters to object attributes.

        Args:
            xid (int): OpenFlow Header's xid.
            match (Match): Fields' description.
            cookie (int): Opaque controller-issued identifier.
            priority (int): Priority level of flow entry.
            reason (FlowRemovedReason): Why the flow was removed.
            duration_sec (int): Time the flow was alive in seconds.
            duration_nsec (int): Time the flow was alive in nanoseconds in
                addition to duration_sec.
            idle_timeout (int): Idle timeout from original flow mod.
            packet_count (int): Number of packets.
            byte_count (int): Byte count.
        """
        super().__init__(xid)
        self.match = match
        self.cookie = cookie
        self.priority = priority
        self.reason = reason
        self.duration_sec = duration_sec
        self.duration_nsec = duration_nsec
        self.idle_timeout = idle_timeout
        self.packet_count = packet_count
        self.byte_count = byte_count
Ejemplo n.º 19
0
class Bucket(GenericStruct):
    """Bucket for use in groups."""

    length = UBInt16()
    weight = UBInt16()
    watch_port = UBInt32()
    watch_group = UBInt32()
    pad = Pad(4)
    actions = FixedTypeList(ActionHeader)

    def __init__(self,
                 length=None,
                 weight=None,
                 watch_port=None,
                 watch_group=None,
                 actions=None):
        """Initialize all instance variables.

        Args:
            length (int): Length the bucket in bytes, including this header and
                any padding to make it 64-bit aligned.
            weight (int): Relative weight of bucket. Only defined for select
                groups.
            watch_port (int): Port whose state affects whether this bucket is
                live. Only required for fast failover groups.
            watch_group (int): Group whose state affects whether this bucket is
                live. Only required for fast failover groups.
            actions (~pyof.v0x04.common.action.ListOfActions): The action
                length is inferred from the length field in the header.

        """
        super().__init__()
        self.length = length
        self.weight = weight
        self.watch_port = watch_port
        self.watch_group = watch_group
        self.actions = actions

    def unpack(self, buff, offset=0):
        """Unpack bucket.

        Bucket has a dynamic content with length as first field.
        The length is needed to compute the total buffer offset.
        """
        length = UBInt16()
        length.unpack(buff, offset=offset)
        super().unpack(buff[:offset + length.value], offset=offset)

    def get_size(self, value=None):
        """
        Return the Bucket length.

        If the object length is None, returns the minimum size.
        """
        if self.length is None:
            return super().get_size()

        return self.length
Ejemplo n.º 20
0
class FlowMonitorRequest(GenericStruct):
    """
    Body for ofp_multipart_request of type OFPMP_FLOW_MONITOR.

     The OFPMP_FLOW_MONITOR request’s body consists of an array of zero or more
     instances of this structure. The request arranges to monitor the flows
     that match the specified criteria, which are interpreted in the same way as
     for OFPMP_FLOW.

    ’id’ identifies a particular monitor for the purpose of allowing it to be
     canceled later with OFPFMC_DELETE. ’id’ must be unique among
     existing monitors that have not already been canceled.

    """
    #: Controller-assigned ID for this monitor
    monitor_id = UBInt32()
    #: Required output port, if not OFPP_ANY
    out_port = UBInt32(enum_ref=PortNo)
    #: Required group number, if not OFPG_ANY
    out_group = UBInt32(enum_ref=Group)
    #: OFPFMF_*
    flags = UBInt16(enum_ref=FlowMonitorFlags)
    #: One table’s ID or OFPTT_ALL (all tables)
    table_id = UBInt8(enum_ref=Table)
    #: One of OFPFMC_*
    command = UBInt8(enum_ref=FlowMonitorCommand)
    #: Fields to match. Variable size
    match = Match()

    def __init__(self, monitor_id=None, out_port=PortNo.OFPP_ANY, out_group=Group.OFPG_ANY, flags=FlowMonitorFlags,
                 table_id=Table.OFPTT_ALL,
                 command=FlowMonitorCommand, match=None):
        """
        Create a FlowStatsRequest with the optional parameters below.

        Args:
            monitor_id (int): uniquely identifies a monitor for a specific controller connection within a switch
            (from pyof_table_stats)
                0xff for all tables or 0xfe for emergency.
            out_port (:class:`int`, :class:`~pyof.v0x05.common.port.PortNo`):
                Require matching entries to include this as an output port.
                A value of :attr:`.PortNo.OFPP_ANY` indicates no restriction.
            out_group: Require matching entries to include this as an output
                group. A value of :attr:`Group.OFPG_ANY` indicates no
                restriction.
            table_id (int): ID of table to read (from pyof_table_stats)
                0xff for all tables or 0xfe for emergency.
            command: defines what operation must be done on that monitor
            match (~pyof.v0x05.common.flow_match.Match): Fields to match.
        """
        super().__init__()
        self.monitor_id = monitor_id
        self.out_port = out_port
        self.out_group = out_group
        self.flags = flags
        self.table_id = table_id
        self.command = command
        self.match = Match() if match is None else match
Ejemplo n.º 21
0
class FlowStats(GenericStruct):
    """Body of reply to OFPST_FLOW request."""

    length = UBInt16()
    table_id = UBInt8()
    #: Align to 32 bits.
    pad = Pad(1)
    duration_sec = UBInt32()
    duration_nsec = UBInt32()
    priority = UBInt16()
    idle_timeout = UBInt16()
    hard_timeout = UBInt16()
    flags = UBInt16()
    #: Align to 64-bits
    pad2 = Pad(4)
    cookie = UBInt64()
    packet_count = UBInt64()
    byte_count = UBInt64()
    match = Match()

    def __init__(self, length=None, table_id=None, duration_sec=None,
                 duration_nsec=None, priority=None, idle_timeout=None,
                 hard_timeout=None, flags=None, cookie=None, packet_count=None,
                 byte_count=None, match=None):
        """The constructor just assings parameters to object attributes.

        Args:
            length (int): Length of this entry.
            table_id (int): ID of table flow came from.
            duration_sec (int): Time flow has been alive in seconds.
            duration_nsec (int): Time flow has been alive in nanoseconds in
                addition to duration_sec.
            priority (int): Priority of the entry. Only meaningful when this
                is not an exact-match entry.
            idle_timeout (int): Number of seconds idle before expiration.
            hard_timeout (int): Number of seconds before expiration.
            cookie (int): Opaque controller-issued identifier.
            packet_count (int): Number of packets in flow.
            byte_count (int): Number of bytes in flow.
            match (Match): Description of fields.
        """
        super().__init__()
        self.length = length
        self.table_id = table_id
        self.duration_sec = duration_sec
        self.duration_nsec = duration_nsec
        self.priority = priority
        self.idle_timeout = idle_timeout
        self.hard_timeout = hard_timeout
        self.flags = flags
        self.cookie = cookie
        self.packet_count = packet_count
        self.byte_count = byte_count
Ejemplo n.º 22
0
class AggregateStatsRequest(GenericStruct):
    """Body for ofp_stats_request of type OFPST_AGGREGATE."""

    #: ID of table to read (from ofp_table_stats) OFPTT_ALL for all tables.
    table_id = UBInt8()
    #: Align to 32 bits.
    pad = Pad(3)
    #: Require matching entries to include this as an output port. A value of
    #: OFPP_ANY indicates no restriction.
    out_port = UBInt32()
    #: Require matching entries to include this as an output group. A value of
    #: OFPG_ANY indicates no restriction.
    out_group = UBInt32()
    #: Align to 64 bits
    pad2 = Pad(4)
    #: Require matching entries to contain this cookie value
    cookie = UBInt64()
    #: Mask used to restrict the cookie bits that must match. A value of 0
    #: indicates no restriction.
    cookie_mask = UBInt64()
    #: Fields to match. Variable size.
    match = Match()

    def __init__(self,
                 table_id=Table.OFPTT_ALL,
                 out_port=PortNo.OFPP_ANY,
                 out_group=Group.OFPG_ANY,
                 cookie=0,
                 cookie_mask=0,
                 match=None):
        """Create a AggregateStatsRequest with the optional parameters below.

        Args:
            table_id (int): ID of table to read (from ofp_table_stats)
                OFPTT_ALL for all tables.
            out_port (int): Require matching entries to include this as an
                output port. A value of OFPP_ANY indicates no restriction.
            out_group (int): Require matching entries to include this as an
                output group. A value of OFPG_ANY indicates no restriction.
            cookie (int): Require matching entries to contain this cookie value
            cookie_mask (int): Mask used to restrict the cookie bits that must
                match. A value of 0 indicates no restriction.
            match (~pyof.v0x04.common.flow_match.Match):
                Fields to match. Variable size
        """
        super().__init__()
        self.table_id = table_id
        self.out_port = out_port
        self.out_group = out_group
        self.cookie = cookie
        self.cookie_mask = cookie_mask
        self.match = Match() if match is None else match
Ejemplo n.º 23
0
def handleFeatureRequest(device, header, body, verbose):
    if (verbose):
        print("Got FeatureReq")
    ofFeaturesReply = FeaturesReply(
        xid=header.xid,
        datapath_id=DPID(device.switch_features["dpid"]),
        n_buffers=UBInt32(device.switch_features["no_of_buffers"]),
        n_tables=UBInt32(device.switch_features["no_of_tables"]),
        capabilities=UBInt32(device.switch_features["capabilities"]),
        actions=UBInt32(device.switch_features["actions"]),
        ports=device.switch_features["ports"])
    device.comm_sock.send(ofFeaturesReply.pack())
    if (verbose):
        print("Sent FeatureRes")
Ejemplo n.º 24
0
class MeterBandHeader(GenericStruct):
    """Common header for all meter bands."""

    band_type = UBInt16(enum_ref=MeterBandType)
    length = UBInt16()
    rate = UBInt32()
    burst_size = UBInt32()

    def __init__(self, band_type=None, rate=None, burst_size=None):
        """Create a MeterBandHeader with the optional parameters below.

        Args:
            band_type (MeterBandType): One of OFPMBT_*.
            rate (int): Rate for this band.
            burst_size (int): Size of bursts.
        """
        super().__init__()
        self.band_type = band_type
        self.rate = rate
        self.burst_size = burst_size
        self.update_length()

    def update_length(self):
        """Update the length attribute of current instance."""
        self.length = self.get_size()

    def unpack(self, buff=None, offset=0):
        """Unpack *buff* into this object.

        This method will convert a binary data into a readable value according
        to the attribute format.

        Args:
            buff (bytes): Binary buffer.
            offset (int): Where to begin unpacking.

        Raises:
            :exc:`~.exceptions.UnpackException`: If unpack fails.

        """
        band_type = UBInt16(enum_ref=MeterBandType)
        band_type.unpack(buff, offset)
        self.__class__ = MeterBandType(band_type.value).find_class()

        length = UBInt16()
        length.unpack(buff, offset=offset + 2)

        super().unpack(buff[:offset + length.value], offset)
Ejemplo n.º 25
0
class ActionEnqueue(ActionHeader):
    """Send packets to a queue's port.

    A switch may support only queues that are tied to specific PCP/TOS bits.
    In that case, we cannot map an arbitrary flow to a specific queue,
    therefore the action ENQUEUE is not supported. The user can still use
    these queues and map flows to them by setting the relevant fields
    (TOS, VLAN PCP).
    """

    port = UBInt16()
    #: Pad for 64-bit alignment.
    pad = Pad(6)
    queue_id = UBInt32()

    _allowed_types = (ActionType.OFPAT_ENQUEUE, )

    def __init__(self, port=None, queue_id=None):
        """Create an ActionEnqueue with the optional parameters below.

        Args:
            port (physical port or :attr:`.Port.OFPP_IN_PORT`): Queue's port.
            queue_id (int): Where to enqueue the packets.
        """
        super().__init__(action_type=ActionType.OFPAT_ENQUEUE, length=16)
        self.port = port
        self.queue_id = queue_id
Ejemplo n.º 26
0
class RoleBaseMessage(GenericMessage):
    """Role basic structure for RoleRequest and RoleReply messages."""

    #: :class:`~pyof.v0x04.common.header.Header`
    #: Type OFPT_ROLE_REQUEST/OFPT_ROLE_REPLY.
    header = Header()
    #: One of NX_ROLE_*. (:class:`~.controller2switch.common.ControllerRole`)
    role = UBInt32(enum_ref=ControllerRole)
    #: Align to 64 bits.
    pad = Pad(4)
    #: Master Election Generation Id.
    generation_id = UBInt64()

    def __init__(self, xid=None, role=None, generation_id=None):
        """Create a RoleBaseMessage with the optional parameters below.

        Args:
            xid (int): OpenFlow xid to the header.
            role (:class:`~.controller2switch.common.ControllerRole`): .
            generation_id (int): Master Election Generation Id.

        """
        super().__init__(xid)
        self.role = role
        self.generation_id = generation_id
Ejemplo n.º 27
0
class TableStats(GenericStruct):
    """Body of reply to OFPST_TABLE request."""

    table_id = UBInt8()
    #: Align to 32-bits.
    pad = Pad(3)
    active_count = UBInt32()
    lookup_count = UBInt64()
    matched_count = UBInt64()

    def __init__(self, table_id=None, name=None, max_entries=None,
                 active_count=None, lookup_count=None,
                 matched_count=None):
        """The constructor just assings parameters to object attributes.

        Args:
            table_id (int): Identifier of table.  Lower numbered tables are
                consulted first.
            active_count (int): Number of active entries.
            lookup_count (int): Number of packets looked up in table.
            matched_count (int): Number of packets that hit table.
        """
        super().__init__()
        self.table_id = table_id
        self.active_count = active_count
        self.lookup_count = lookup_count
        self.matched_count = matched_count
Ejemplo n.º 28
0
class ActionVendorHeader(ActionHeader):
    """Action header for :attr:`ActionType.OFPAT_VENDOR`.

    The rest of the body is vendor-defined.
    """

    action_type = UBInt16(ActionType.OFPAT_VENDOR, enum_ref=ActionType)
    length = UBInt16()
    vendor = UBInt32()

    def __init__(self, length=None, vendor=None):
        """The following constructor parameters are optional.

        Args:
            length (int): Length is a multiple of 8.
            vender (int): Vendor ID with the same form as in VendorHeader.
                Defaults to None.
        """
        super().__init__()
        self.length = length
        self.vendor = vendor

    def allowed_types():
       """Return the Allowed Action Type

       Returns:
           action_types (list): list of allowed types
       """
       return [ActionType.OFPAT_VENDOR]
Ejemplo n.º 29
0
class ActionNWAddr(ActionHeader):
    """Action structure for :attr:`ActionType.OFPAT_SET_NW_SRC` or _DST."""

    nw_addr_type = UBInt16(enum_ref=ActionType)
    length = UBInt16(8)
    nw_addr = UBInt32()

    def __init__(self, nw_addr_type=None, nw_addr=None):
        """The following constructor parameters are optional.

        Args:
            nw_addr_type (ActionType): :attr:`~ActionType.OFPAT_SET_NW_SRC` or
                :attr:`~ActionType.OFPAT_SET_NW_DST`.
            nw_addr (int): IP Address.
        """
        super().__init__()
        self.nw_addr_type = nw_addr_type
        self.nw_addr = nw_addr

    def allowed_types():
       """Return the Allowed Action Type

       Returns:
           action_types (list): list of allowed types
       """
       return [ActionType.OFPAT_SET_NW_SRC, ActionType.OFPAT_SET_NW_DST]
Ejemplo n.º 30
0
class ActionEnqueue(ActionHeader):
    """Send packets to a queue's port.

    A switch may support only queues that are tied to specific PCP/TOS bits.
    In that case, we cannot map an arbitrary flow to a specific queue,
    therefore the action ENQUEUE is not supported. The user can still use
    these queues and map flows to them by setting the relevant fields
    (TOS, VLAN PCP).
    """

    action_type = UBInt16(ActionType.OFPAT_ENQUEUE, enum_ref=ActionType)
    length = UBInt16(16)
    port = UBInt16()
    #: Pad for 64-bit alignment.
    pad = Pad(6)
    queue_id = UBInt32()

    def __init__(self, port=None, queue_id=None):
        """The following constructor parameters are optional.

        Args:
            port (physical port or :attr:`.Port.OFPP_IN_PORT`): Queue's port.
            queue_id (int): Where to enqueue the packets.
        """
        super().__init__()
        self.port = port
        self.queue_id = queue_id

    def allowed_types():
       """Return the Allowed Action Type

       Returns:
           action_types (list): list of allowed types
       """
       return [ActionType.OFPAT_ENQUEUE]