Passed
Pull Request — master (#425)
by Carlos Eduardo
02:30
created

DPID.value()   A

Complexity

Conditions 1

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1.125

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 8
ccs 1
cts 2
cp 0.5
rs 9.4285
cc 1
crap 1.125
1
"""Basic types used in structures and messages."""
2
3
# System imports
4 1
import struct
5
6
# Local source tree imports
7 1
from pyof.foundation import exceptions
8 1
from pyof.foundation.base import GenericStruct, GenericType
9
10
# Third-party imports
11
12 1
__all__ = ('BinaryData', 'Char', 'ConstantTypeList', 'FixedTypeList',
13
           'IPAddress', 'DPID', 'HWAddress', 'Pad', 'UBInt8', 'UBInt16',
14
           'UBInt32', 'UBInt64')
15
16
17 1
class Pad(GenericType):
18
    """Class for padding attributes."""
19
20 1
    _fmt = ''
21
22 1
    def __init__(self, length=0):
23
        """Pad up to ``length``, in bytes.
24
25
        Args:
26
            length (int): Total length, in bytes.
27
        """
28 1
        super().__init__()
29 1
        self._length = length
30
31 1
    def __repr__(self):
32
        return "{}({})".format(type(self).__name__, self._length)
33
34 1
    def __str__(self):
35
        return '0' * self._length
36
37 1
    def get_size(self, value=None):
38
        """Return the type size in bytes.
39
40
        Args:
41
            value (int): In structs, the user can assign other value instead of
42
                this class' instance. Here, in such cases, ``self`` is a class
43
                attribute of the struct.
44
45
        Returns:
46
            int: Size in bytes.
47
        """
48 1
        return self._length
49
50 1
    def unpack(self, buff, offset=0):
51
        """Unpack *buff* into this object.
52
53
        Do nothing, since the _length is already defined and it is just a Pad.
54
        Keep buff and offset just for compability with other unpack methods.
55
56
        Args:
57
            buff: Buffer where data is located.
58
            offset (int): Where data stream begins.
59
        """
60 1
        pass
61
62 1
    def pack(self, value=None):
63
        """Pack the object.
64
65
        Args:
66
            value (int): In structs, the user can assign other value instead of
67
                this class' instance. Here, in such cases, ``self`` is a class
68
                attribute of the struct.
69
70
        Returns:
71
            bytes: the byte 0 (zero) *length* times.
72
        """
73 1
        return b'\x00' * self._length
74
75
76 1
class UBInt8(GenericType):
77
    """Format character for an Unsigned Char.
78
79
    Class for an 8-bit (1-byte) Unsigned Integer.
80
    """
81
82 1
    _fmt = "!B"
83
84
85 1
class UBInt16(GenericType):
86
    """Format character for an Unsigned Short.
87
88
    Class for an 16-bit (2-byte) Unsigned Integer.
89
    """
90
91 1
    _fmt = "!H"
92
93
94 1
class UBInt32(GenericType):
95
    """Format character for an Unsigned Int.
96
97
    Class for an 32-bit (4-byte) Unsigned Integer.
98
    """
99
100 1
    _fmt = "!I"
101
102
103 1
class UBInt64(GenericType):
104
    """Format character for an Unsigned Long Long.
105
106
    Class for an 64-bit (8-byte) Unsigned Integer.
107
    """
108
109 1
    _fmt = "!Q"
110
111
112 1
class DPID(GenericType):
113
    """DataPath ID. Identifies a switch."""
114
115 1
    _fmt = "!8B"
116
117 1
    def __init__(self, dpid=None):
118
        """Create an instance and optionally set its dpid value.
119
120
        Args:
121
            dpid (str): String with DPID value(e.g. `00:00:00:00:00:00:00:01`).
122
        """
123 1
        super().__init__(value=dpid)
124
125 1
    def __str__(self):
126
        return self._value
127
128 1
    @property
129
    def value(self):
130
        """Return dpid value.
131
132
        Returns:
133
            str: DataPath ID stored by DPID class.
134
        """
135
        return self._value
136
137 1
    def pack(self, value=None):
138
        """Pack the value as a binary representation.
139
140
        Returns:
141
            bytes: The binary representation.
142
143
        Raises:
144
            struct.error: If the value does not fit the binary format.
145
        """
146 1
        if isinstance(value, type(self)):
147 1
            return value.pack()
148 1
        if value is None:
149 1
            value = self._value
150 1
        return struct.pack('!8B', *[int(v, 16) for v in value.split(':')])
151
152 1
    def unpack(self, buff, offset=0):
153
        """Unpack a binary message into this object's attributes.
154
155
        Unpack the binary value *buff* and update this object attributes based
156
        on the results.
157
158
        Args:
159
            buff (bytes): Binary data package to be unpacked.
160
            offset (int): Where to begin unpacking.
161
162
        Raises:
163
            Exception: If there is a struct unpacking error.
164
        """
165 1
        begin = offset
166 1
        hexas = []
167 1
        while begin < offset + 8:
168 1
            number = struct.unpack("!B", buff[begin:begin+1])[0]
169 1
            hexas.append("%.2x" % number)
170 1
            begin += 1
171 1
        self._value = ':'.join(hexas)
172
173
174 1
class Char(GenericType):
175
    """Build a double char type according to the length."""
176
177 1
    def __init__(self, value=None, length=0):
178
        """The constructor takes the optional parameters below.
179
180
        Args:
181
            value: The character to be build.
182
            length (int): Character size.
183
        """
184 1
        super().__init__(value)
185 1
        self.length = length
186 1
        self._fmt = '!{}{}'.format(self.length, 's')
187
188 1 View Code Duplication
    def pack(self, value=None):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
189
        """Pack the value as a binary representation.
190
191
        Returns:
192
            bytes: The binary representation.
193
194
        Raises:
195
            struct.error: If the value does not fit the binary format.
196
        """
197 1
        if isinstance(value, type(self)):
198 1
            return value.pack()
199
200 1
        try:
201 1
            if value is None:
202 1
                value = self.value
203 1
            packed = struct.pack(self._fmt, bytes(value, 'ascii'))
204 1
            return packed[:-1] + b'\0'  # null-terminated
205
        except struct.error as err:
206
            msg = "Char Pack error. "
207
            msg += "Class: {}, struct error: {} ".format(type(value).__name__,
208
                                                         err)
209
            raise exceptions.PackException(msg)
210
211 1
    def unpack(self, buff, offset=0):
212
        """Unpack a binary message into this object's attributes.
213
214
        Unpack the binary value *buff* and update this object attributes based
215
        on the results.
216
217
        Args:
218
            buff (bytes): Binary data package to be unpacked.
219
            offset (int): Where to begin unpacking.
220
221
        Raises:
222
            Exception: If there is a struct unpacking error.
223
        """
224 1
        try:
225 1
            begin = offset
226 1
            end = begin + self.length
227 1
            unpacked_data = struct.unpack(self._fmt, buff[begin:end])[0]
228
        except struct.error:
229
            raise Exception("%s: %s" % (offset, buff))
230
231 1
        self._value = unpacked_data.decode('ascii').rstrip('\0')
232
233
234 1
class IPAddress(GenericType):
235
    """Defines a IP address."""
236
237 1
    netmask = UBInt32()
238 1
    max_prefix = UBInt32(32)
239
240 1
    def __init__(self, address="0.0.0.0/32"):
241
        """The constructor takes the parameters below.
242
243
        Args:
244
            address (str): IP Address using ipv4. Defaults to '0.0.0.0/32'
245
        """
246 1
        if address.find('/') >= 0:
247 1
            address, netmask = address.split('/')
248
        else:
249 1
            netmask = 32
250
251 1
        super().__init__(address)
252 1
        self.netmask = int(netmask)
253
254 1 View Code Duplication
    def pack(self, value=None):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
255
        """Pack the value as a binary representation.
256
257
        If the value is None the self._value will be used to pack.
258
259
        Args:
260
            value (str): IP Address with ipv4 format.
261
262
        Returns:
263
            bytes: The binary representation.
264
265
        Raises:
266
            struct.error: If the value does not fit the binary format.
267
        """
268 1
        if isinstance(value, type(self)):
269 1
            return value.pack()
270
271 1
        if value is None:
272 1
            value = self._value
273
274 1
        if value.find('/') >= 0:
275
            value = value.split('/')[0]
276
277 1
        try:
278 1
            value = value.split('.')
279 1
            return struct.pack('!4B', *[int(x) for x in value])
280
        except struct.error as err:
281
            msg = "IPAddress error. "
282
            msg += "Class: {}, struct error: {} ".format(type(value).__name__,
283
                                                         err)
284
            raise exceptions.PackException(msg)
285
286 1
    def unpack(self, buff, offset=0):
287
        """Unpack a binary message into this object's attributes.
288
289
        Unpack the binary value *buff* and update this object attributes based
290
        on the results.
291
292
        Args:
293
            buff (bytes): Binary data package to be unpacked.
294
            offset (int): Where to begin unpacking.
295
296
        Raises:
297
            Exception: If there is a struct unpacking error.
298
        """
299 1
        try:
300 1
            unpacked_data = struct.unpack('!4B', buff[offset:offset+4])
301 1
            self._value = '.'.join([str(x) for x in unpacked_data])
302
        except struct.error as e:
303
            raise exceptions.UnpackException('%s; %s: %s' % (e, offset, buff))
304
305 1
    def get_size(self, value=None):
306
        """Return the ip address size in bytes.
307
308
        Args:
309
            value: In structs, the user can assign other value instead of
310
                this class' instance. Here, in such cases, ``self`` is a class
311
                attribute of the struct.
312
313
        Returns:
314
            int: The address size in bytes.
315
        """
316 1
        return 4
317
318
319 1
class HWAddress(GenericType):
320
    """Defines a hardware address."""
321
322 1
    def __init__(self, hw_address='00:00:00:00:00:00'):  # noqa
323
        """The constructor takes the parameters below.
324
325
        Args:
326
            hw_address (bytes): Hardware address. Defaults to
327
                '00:00:00:00:00:00'.
328
        """
329 1
        super().__init__(hw_address)
330
331 1 View Code Duplication
    def pack(self, value=None):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
332
        """Pack the value as a binary representation.
333
334
        If the passed value (or the self._value) is zero (int), then the pack
335
        will assume that the value to be packed is '00:00:00:00:00:00'.
336
337
        Returns
338
            bytes: The binary representation.
339
340
        Raises:
341
            struct.error: If the value does not fit the binary format.
342
        """
343 1
        if isinstance(value, type(self)):
344 1
            return value.pack()
345
346 1
        if value is None:
347 1
            value = self._value
348
349 1
        if value == 0:
350
            value = '00:00:00:00:00:00'
351
352 1
        value = value.split(':')
353
354 1
        try:
355 1
            return struct.pack('!6B', *[int(x, 16) for x in value])
356
        except struct.error as err:
357
            msg = "HWAddress error. "
358
            msg += "Class: {}, struct error: {} ".format(type(value).__name__,
359
                                                         err)
360
            raise exceptions.PackException(msg)
361
362 1
    def unpack(self, buff, offset=0):
363
        """Unpack a binary message into this object's attributes.
364
365
        Unpack the binary value *buff* and update this object attributes based
366
        on the results.
367
368
        Args:
369
            buff (bytes): Binary data package to be unpacked.
370
            offset (int): Where to begin unpacking.
371
372
        Raises:
373
            Exception: If there is a struct unpacking error.
374
        """
375 1
        def _int2hex(n):
376 1
            return "{0:0{1}x}".format(n, 2)
377
378 1
        try:
379 1
            unpacked_data = struct.unpack('!6B', buff[offset:offset+6])
380
        except struct.error as e:
381
            raise exceptions.UnpackException('%s; %s: %s' % (e, offset, buff))
382
383 1
        transformed_data = ':'.join([_int2hex(x) for x in unpacked_data])
384 1
        self._value = transformed_data
385
386 1
    def get_size(self, value=None):
387
        """Return the address size in bytes.
388
389
        Args:
390
            value: In structs, the user can assign other value instead of
391
                this class' instance. Here, in such cases, ``self`` is a class
392
                attribute of the struct.
393
394
        Returns:
395
            int: The address size in bytes.
396
        """
397 1
        return 6
398
399 1
    def is_broadcast(self):
400
        """Return true if the value is a broadcast address. False otherwise."""
401
        return self.value == 'ff:ff:ff:ff:ff:ff'
402
403
404 1
class BinaryData(GenericType):
405
    """Class to create objects that represent binary data.
406
407
    This is used in the ``data`` attribute from
408
    :class:`~pyof.v0x01.asynchronous.packet_in.PacketIn` and
409
    :class:`~pyof.v0x01.controller2switch.packet_out.PacketOut` messages.
410
    Both the :meth:`pack` and :meth:`unpack` methods will return the
411
    binary data itself. :meth:`get_size` method will
412
    return the size of the instance using Python's :func:`len`.
413
    """
414
415 1
    def __init__(self, value=b''):  # noqa
416
        """The constructor takes the parameter below.
417
418
        Args:
419
            value (bytes): The binary data. Defaults to an empty value.
420
421
        Raises:
422
            ValueError: If given value is not bytes.
423
        """
424 1
        if not isinstance(value, bytes):
425 1
            raise ValueError('BinaryData must contain bytes.')
426 1
        super().__init__(value)
427
428 1
    def pack(self, value=None):
429
        """Pack the value as a binary representation.
430
431
        Returns:
432
            bytes: The binary representation.
433
434
        Raises:
435
            :exc:`~.exceptions.NotBinaryData`: If value is not :class:`bytes`.
436
        """
437 1
        if isinstance(value, type(self)):
438 1
            return value.pack()
439
440 1
        if value is None:
441 1
            value = self._value
442
443 1
        if value:
444 1
            if isinstance(value, bytes):
445 1
                return value
446 1
            raise ValueError('BinaryData must contain bytes.')
447
448 1
        return b''
449
450 1
    def unpack(self, buff, offset=0):
451
        """Unpack a binary message into this object's attributes.
452
453
        Unpack the binary value *buff* and update this object attributes based
454
        on the results. Since the *buff* is binary data, no conversion is done.
455
456
        Args:
457
            buff (bytes): Binary data package to be unpacked.
458
            offset (int): Where to begin unpacking.
459
        """
460 1
        self._value = buff[offset:]
461
462 1
    def get_size(self, value=None):
463
        """Return the size in bytes.
464
465
        Args:
466
            value (bytes): In structs, the user can assign other value instead
467
                of this class' instance. Here, in such cases, ``self`` is a
468
                class attribute of the struct.
469
470
        Returns:
471
            int: The address size in bytes.
472
        """
473 1
        if value is None:
474 1
            return len(self._value)
475 1
        elif hasattr(value, 'get_size'):
476 1
            return value.get_size()
477
478 1
        return len(value)
479
480
481 1
class TypeList(list, GenericStruct):
482
    """Base class for lists that store objects of one single type."""
483
484 1
    def __init__(self, items):
485
        """Initialize the list with one item or a list of items.
486
487
        Args:
488
            items (iterable, ``pyof_class``): Items to be stored.
489
        """
490 1
        super().__init__()
491 1
        if isinstance(items, list):
492 1
            self.extend(items)
493 1
        elif items:
494
            self.append(items)
495
496 1
    def extend(self, items):
497
        """Extend the list by adding all items of ``items``.
498
499
        Args:
500
            items (iterable): Items to be added to the list.
501
502
        Raises:
503
            :exc:`~.exceptions.WrongListItemType`: If an item has an unexpected
504
                type.
505
        """
506 1
        for item in items:
507 1
            self.append(item)
508
509 1
    def pack(self, value=None):
510
        """Pack the value as a binary representation.
511
512
        Returns:
513
            bytes: The binary representation.
514
        """
515 1
        if isinstance(value, type(self)):
516 1
            return value.pack()
517
518 1
        if value is None:
519 1
            value = self
520
        else:
521 1
            container = type(self)(items=None)
522 1
            container.extend(value)
523 1
            value = container
524
525 1
        bin_message = b''
526 1
        try:
527 1
            for item in value:
528 1
                bin_message += item.pack()
529 1
            return bin_message
530
        except exceptions.PackException as err:
531
            msg = "{} pack error: {}".format(type(self).__name__, err)
532
            raise exceptions.PackException(msg)
533
534 1
    def unpack(self, buff, item_class, offset=0):
535
        """Unpack the elements of the list.
536
537
        This unpack method considers that all elements have the same size.
538
        To use this class with a pyof_class that accepts elements with
539
        different sizes, you must reimplement the unpack method.
540
541
        Args:
542
            buff (bytes): The binary data to be unpacked.
543
            item_class (:obj:`type`): Class of the expected items on this list.
544
            offset (int): If we need to shift the beginning of the data.
545
        """
546 1
        begin = offset
547 1
        limit_buff = len(buff)
548
549 1
        while begin < limit_buff:
550 1
            item = item_class()
551 1
            item.unpack(buff, begin)
552 1
            self.append(item)
553 1
            begin += item.get_size()
554
555 1
    def get_size(self, value=None):
556
        """Return the size in bytes.
557
558
        Args:
559
            value: In structs, the user can assign other value instead of
560
                this class' instance. Here, in such cases, ``self`` is a class
561
                attribute of the struct.
562
563
        Returns:
564
            int: The size in bytes.
565
        """
566 1
        if value is None:
567 1
            if not self:
568
                # If this is a empty list, then returns zero
569 1
                return 0
570 1
            elif issubclass(type(self[0]), GenericType):
571
                # If the type of the elements is GenericType, then returns the
572
                # length of the list multiplied by the size of the GenericType.
573
                return len(self) * self[0].get_size()
574
575
            # Otherwise iter over the list accumulating the sizes.
576 1
            return sum(item.get_size() for item in self)
577
578 1
        return type(self)(value).get_size()
579
580 1
    def __str__(self):
581
        """Human-readable object representantion."""
582
        return "{}".format([str(item) for item in self])
583
584
585 1
class FixedTypeList(TypeList):
586
    """A list that stores instances of one pyof class."""
587
588 1
    _pyof_class = None
589
590 1
    def __init__(self, pyof_class, items=None):
591
        """The constructor parameters follows.
592
593
        Args:
594
            pyof_class (:obj:`type`): Class of the items to be stored.
595
            items (iterable, ``pyof_class``): Items to be stored.
596
        """
597 1
        self._pyof_class = pyof_class
598 1
        super().__init__(items)
599
600 1
    def append(self, item):
601
        """Append one item to the list.
602
603
        Args:
604
            item: Item to be appended. Its type must match the one defined in
605
                the constructor.
606
607
        Raises:
608
            :exc:`~.exceptions.WrongListItemType`: If the item has a different
609
                type than the one specified in the constructor.
610
        """
611 1
        if isinstance(item, list):
612
            self.extend(item)
613 1
        elif issubclass(item.__class__, self._pyof_class):
614 1
            list.append(self, item)
615
        else:
616
            raise exceptions.WrongListItemType(item.__class__.__name__,
617
                                               self._pyof_class.__name__)
618
619 1
    def insert(self, index, item):
620
        """Insert an item at the specified index.
621
622
        Args:
623
            index (int): Position to insert the item.
624
            item: Item to be inserted. It must have the type specified in the
625
                constructor.
626
627
        Raises:
628
            :exc:`~.exceptions.WrongListItemType`: If the item has a different
629
                type than the one specified in the constructor.
630
        """
631
        if issubclass(item.__class__, self._pyof_class):
632
            list.insert(self, index, item)
633
        else:
634
            raise exceptions.WrongListItemType(item.__class__.__name__,
635
                                               self._pyof_class.__name__)
636
637 1
    def unpack(self, buff, offset=0):
638
        """Unpack the elements of the list.
639
640
        This unpack method considers that all elements have the same size.
641
        To use this class with a pyof_class that accepts elements with
642
        different sizes, you must reimplement the unpack method.
643
644
        Args:
645
            buff (bytes): The binary data to be unpacked.
646
            offset (int): If we need to shift the beginning of the data.
647
        """
648 1
        super().unpack(buff, self._pyof_class, offset)
649
650
651 1
class ConstantTypeList(TypeList):
652
    """List that contains only objects of the same type (class).
653
654
    The types of all items are expected to be the same as the first item's.
655
    Otherwise, :exc:`~.exceptions.WrongListItemType` is raised in many
656
    list operations.
657
    """
658
659 1
    def __init__(self, items=None):  # noqa
660
        """The contructor can contain the items to be stored.
661
662
        Args:
663
            items (iterable, :class:`object`): Items to be stored.
664
665
        Raises:
666
            :exc:`~.exceptions.WrongListItemType`: If an item has a different
667
                type than the first item to be stored.
668
        """
669
        super().__init__(items)
670
671 1
    def append(self, item):
672
        """Append one item to the list.
673
674
        Args:
675
            item: Item to be appended.
676
677
        Raises:
678
            :exc:`~.exceptions.WrongListItemType`: If an item has a different
679
                type than the first item to be stored.
680
        """
681
        if isinstance(item, list):
682
            self.extend(item)
683
        elif not self:
684
            list.append(self, item)
685
        elif item.__class__ == self[0].__class__:
686
            list.append(self, item)
687
        else:
688
            raise exceptions.WrongListItemType(item.__class__.__name__,
689
                                               self[0].__class__.__name__)
690
691 1
    def insert(self, index, item):
692
        """Insert an item at the specified index.
693
694
        Args:
695
            index (int): Position to insert the item.
696
            item: Item to be inserted.
697
698
        Raises:
699
            :exc:`~.exceptions.WrongListItemType`: If an item has a different
700
                type than the first item to be stored.
701
        """
702
        if not self:
703
            list.append(self, item)
704
        elif item.__class__ == self[0].__class__:
705
            list.insert(self, index, item)
706
        else:
707
            raise exceptions.WrongListItemType(item.__class__.__name__,
708
                                               self[0].__class__.__name__)
709