Skip to content

Commit

Permalink
Improve unpack_message with multiple versions
Browse files Browse the repository at this point in the history
Reuse unpack_message method from v0x01.common.utils and v0x04.common.utils
Fix kytos#344
  • Loading branch information
macartur committed Nov 22, 2017
1 parent 1eeec4a commit a71d595
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 16 deletions.
23 changes: 8 additions & 15 deletions pyof/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,12 @@
This package was moved from kytos/of_core for the purpose of creating a generic
method to perform package unpack independent of the OpenFlow version.
"""
from pyof import v0x01, v0x04
from pyof.v0x01.common.utils import Header0x01, unpack_message_v0x01
from pyof.v0x04.common.utils import unpack_message as unpack_message_v0x04
from pyof.foundation.exceptions import UnpackException

PYOF_VERSION_LIBS = {0x01: v0x01,
0x04: v0x04}
PYOF_UNPACK_MESSAGE = {0x01: unpack_message_v0x01,
0x04: unpack_message_v0x04}


def validate_packet(packet):
Expand Down Expand Up @@ -45,23 +46,15 @@ def unpack(packet):
"""
validate_packet(packet)

version = packet[0]

try:
pyof_lib = PYOF_VERSION_LIBS[version]
unpack_message = PYOF_UNPACK_MESSAGE[version]
except KeyError:
raise UnpackException('Version not supported')

try:
header = pyof_lib.common.header.Header()
header.unpack(packet[:header.get_size()])
message = pyof_lib.common.utils.new_message_from_header(header)

binary_data = packet[header.get_size():]
binary_data_size = header.length - header.get_size()

if binary_data and len(binary_data) == binary_data_size:
message.unpack(binary_data)
return message
message = unpack_message(packet)
except (UnpackException, ValueError) as exception:
raise UnpackException(exception)
return message
10 changes: 9 additions & 1 deletion pyof/v0x04/common/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,15 @@ def new_message_from_header(header):


def unpack_message(buffer):
"""Unpack the whole buffer, including header pack."""
"""Unpack the whole buffer, including header pack.
Args:
buffer (bytes): Bytes representation of a openflow message.
Returns:
object: Instance of openflow message.
"""
hdr_size = Header().get_size()
hdr_buff, msg_buff = buffer[:hdr_size], buffer[hdr_size:]
header = Header()
Expand Down

0 comments on commit a71d595

Please sign in to comment.