Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 52 additions & 0 deletions ccsdspy/tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import glob
import io
import os
import socket

import numpy as np
import pytest
Expand All @@ -16,6 +17,57 @@
from ccsdspy import _test_data_directory


STREAM_PACKETS = [
bytes.fromhex("0001c0000000") + b"a",
bytes.fromhex("0002c0010002") + b"bcd",
]


@pytest.mark.parametrize("read_size", [1, 4, 8])
@pytest.mark.parametrize("include_primary_header", [True, False])
def test_iter_packet_bytes_short_reads(read_size, include_primary_header):
class ShortReadStream(io.BytesIO):
def read(self, size=-1):
return super().read(read_size if size < 0 else min(size, read_size))

stream = ShortReadStream(b"".join(STREAM_PACKETS))
packets = list(utils.iter_packet_bytes(stream, include_primary_header))
expected = STREAM_PACKETS if include_primary_header else [p[6:] for p in STREAM_PACKETS]
assert packets == expected
assert not stream.closed


@pytest.mark.parametrize("include_primary_header", [True, False])
def test_iter_packet_bytes_before_eof(include_primary_header):
reader, writer = socket.socketpair()
with reader, writer, reader.makefile("rb") as stream:
reader.settimeout(2)
packets = utils.iter_packet_bytes(stream, include_primary_header)
for packet in STREAM_PACKETS:
writer.sendall(packet)
assert next(packets) == (packet if include_primary_header else packet[6:])
writer.shutdown(socket.SHUT_WR)
assert list(packets) == []
assert not stream.closed


@pytest.mark.parametrize("tail_size", [0, 3, 6, 8])
@pytest.mark.parametrize("include_primary_header", [True, False])
def test_iter_packet_bytes_truncated_tail(tail_size, include_primary_header, caplog):
tail = STREAM_PACKETS[1][:tail_size]
stream = io.BytesIO(STREAM_PACKETS[0] + tail)
packets = list(utils.iter_packet_bytes(stream, include_primary_header))
expected = [STREAM_PACKETS[0]]
if tail_size >= 6:
expected.append(tail)
if not include_primary_header:
expected = [p[6:] for p in expected]
assert packets == expected
assert any(
record.message.startswith("File appears truncated") for record in caplog.records
) == (tail_size > 0)


def test_count_packets_missing_bytes():
dir_path = os.path.dirname(os.path.realpath(__file__))
data_path = os.path.join(dir_path, "data", "split")
Expand Down
75 changes: 42 additions & 33 deletions ccsdspy/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,18 +32,35 @@ def get_packet_apid(primary_header_bytes):
get_packet_apid.__doc__ = decode._get_packet_apid.__doc__


def _read_bytes(file, num_bytes):
"""Read up to num_bytes, combining short reads until EOF."""
data = bytearray()
while len(data) < num_bytes:
chunk = file.read(num_bytes - len(data))
if chunk == b"":
break
data.extend(chunk)
return bytes(data)


def iter_packet_bytes(file, include_primary_header=True):
"""Iterate through packets as raw bytes objects, in the order they appear in a file.
"""Iterate through packets as raw bytes objects from a file or blocking stream.

This function works with mixed files containing multiple APIDs, which may
include both fixed length and variable length packets.

If end of last packet doesn't align with end of file, a warning is issued.
The input must start at a packet boundary and contain valid packets. Short
reads are combined until a packet is complete. An empty read marks EOF.
File-like objects supplied by the caller are left open.

If the input ends during a packet, a warning is logged. A final packet with
a complete primary header is yielded even if its data is truncated.

Parameters
----------
file : str, file-like
Path to file on the local file system, or file-like object
Path to file on the local file system, or blocking binary file-like object
with a read(size) method
include_primary_header : bool
If set to False, excludes the primary header bytes (the first six)

Expand All @@ -52,47 +69,39 @@ def iter_packet_bytes(file, include_primary_header=True):
packet_bytes : bytes
Bytes associated with each packet as it appears in the file. When
include_primary_header=False, the primary header bytes are excluded.

Warns
-----
UserWarning
If the file appears truncated, or if there is garbage at the end of the file.
"""
if hasattr(file, "read"):
file_bytes = np.frombuffer(file.read(), "u1")
else:
file_bytes = np.fromfile(file, "u1")

offset = 0

if include_primary_header:
delta_idx = 0
else:
delta_idx = PRIMARY_HEADER_NUM_BYTES

while offset < len(file_bytes):
pri_header_bytes = file_bytes[offset : offset + PRIMARY_HEADER_NUM_BYTES].tobytes()
if not hasattr(file, "read"):
with open(file, "rb") as stream:
yield from iter_packet_bytes(stream, include_primary_header)
return

while True:
pri_header_bytes = _read_bytes(file, PRIMARY_HEADER_NUM_BYTES)
if not pri_header_bytes:
break

if len(pri_header_bytes) != PRIMARY_HEADER_NUM_BYTES:
log.warning(
"File appears truncated or with garbage bytes. Unable to enough "
"File appears truncated or with garbage bytes. Unable to read enough "
"bytes for primary header"
)
break

packet_nbytes = get_packet_total_bytes(pri_header_bytes)
packet_bytes = file_bytes[offset + delta_idx : offset + packet_nbytes].tobytes()

yield packet_bytes
data_nbytes = packet_nbytes - PRIMARY_HEADER_NUM_BYTES
packet_bytes = _read_bytes(file, data_nbytes)

offset += packet_nbytes
if include_primary_header:
yield pri_header_bytes + packet_bytes
else:
yield packet_bytes

if offset != len(file_bytes):
missing_bytes = offset - len(file_bytes)
message = (
f"File appears truncated-- missing {missing_bytes} byte (or " "maybe garbage at end)"
)
log.warning(message)
if len(packet_bytes) != data_nbytes:
missing_bytes = data_nbytes - len(packet_bytes)
log.warning(
f"File appears truncated-- missing {missing_bytes} byte (or maybe garbage at end)"
)
break


def split_packet_bytes(file, include_primary_header=True):
Expand Down
15 changes: 15 additions & 0 deletions docs/user-guide/utils.rst
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,21 @@ This generates the following output for a sequence of variable length packets:
These functions perform integrity checks wile iterating through the packets in the given file:
- **File Integrity Check**: A `UserWarning` is issued if the total bytes successfully read from packets don't match the file size, e.g., "File appears truncated-- missing X byte (or maybe garbage at end)". This applies to mixed APID files and both packet types.

`utils.iter_packet_bytes()` also accepts blocking binary streams. It combines
partial reads and yields each packet as soon as it is complete. The caller must
provide valid packets starting at a packet boundary and handle any recovery after
data loss. A read returning ``b''`` ends iteration.

For an already connected blocking TCP socket ``sock``:

.. code-block:: python

from ccsdspy.utils import iter_packet_bytes

with sock.makefile('rb') as stream:
for packet in iter_packet_bytes(stream):
print(packet.hex())

Counting Number of Packets in a File
====================================
Sometimes, it is desirable to know the number of packets in a file. For this, the `utils.count_packets()` function can be used. It's argument is a file-like object or name of a file. It accepts the optional arguments `return_missing_bytes=True` which can be used to determine the number of bytes which would be needed to be added to the file to complete the last packet (computed using the packet length set in the primary header of last packet).
Expand Down
Loading