aboutsummaryrefslogtreecommitdiff
path: root/ouroboros/event.py
blob: 24b58b832c5db75cac8c7d544797d505c7a6dd80 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
#
# SPDX-FileCopyrightText: 2016 - 2026 Dimitri Staessens
# SPDX-License-Identifier: LGPL-2.1-only
#

"""
Asynchronous flow event monitoring for Ouroboros.
"""

from __future__ import annotations

from enum import IntFlag
from typing import TYPE_CHECKING, Any, List, Optional, Tuple, Type

from _ouroboros_dev_cffi import ffi, lib

from ouroboros._timespec import fl_to_timespec
from ouroboros.dev import Flow
from ouroboros.errors import FlowEventError, raise_errno

if TYPE_CHECKING:
    from types import TracebackType


class FEventType(IntFlag):
    """
    Types of flow events.
    """

    FLOW_PKT     = lib.FLOW_PKT
    FLOW_DOWN    = lib.FLOW_DOWN
    FLOW_UP      = lib.FLOW_UP
    FLOW_ALLOC   = lib.FLOW_ALLOC
    FLOW_DEALLOC = lib.FLOW_DEALLOC
    FLOW_PEER    = lib.FLOW_PEER


class FEventQueue:
    """
    A queue of flow events waiting to be drained.
    """

    def __init__(self) -> None:
        self._fq = lib.fqueue_create()
        if self._fq == ffi.NULL:
            raise MemoryError("Failed to create FEventQueue")

    def __enter__(self) -> FEventQueue:
        return self

    def __exit__(self, exc_type: Optional[Type[BaseException]],
                 exc_value: Optional[BaseException],
                 tb: Optional[TracebackType]) -> None:
        self.destroy()

    def __del__(self) -> None:
        self.destroy()

    def destroy(self) -> None:
        """
        Destroy the underlying queue. Idempotent.
        """

        if self._fq != ffi.NULL:
            lib.fqueue_destroy(self._fq)

            self._fq = ffi.NULL

    def next(self) -> Tuple[Flow, FEventType]:
        """
        Return the next ``(flow, event_type)`` pair from the queue.

        :return: The :class:`~ouroboros.dev.Flow` the event occurred
                 on, and its :class:`FEventType`.
        :raises FlowEventError: On a negative ouroboros return code.
        """

        fd = lib.fqueue_next(self._fq)

        raise_errno(fd, default=FlowEventError)

        _type = lib.fqueue_type(self._fq)

        raise_errno(_type, default=FlowEventError)

        return Flow(fd), FEventType(_type)

    @property
    def handle(self) -> Any:
        """
        Return the underlying ``fqueue_t *``.

        :return: The underlying ``fqueue_t *`` CFFI pointer.
        """

        return self._fq


class FlowSet:
    """
    A set of flows that can be monitored for events.
    """

    def __init__(self, flows: Optional[List[Flow]] = None) -> None:
        self._set = lib.fset_create()
        if self._set == ffi.NULL:
            raise MemoryError("Failed to create FlowSet")

        if flows is not None:
            for flow in flows:
                if lib.fset_add(self._set, flow.fileno()) != 0:
                    lib.fset_destroy(self._set)

                    self._set = ffi.NULL
                    raise MemoryError(f"Failed to add flow {flow.fileno()}.")

    def __enter__(self) -> FlowSet:
        return self

    def __exit__(self, exc_type: Optional[Type[BaseException]],
                 exc_value: Optional[BaseException],
                 tb: Optional[TracebackType]) -> None:
        self.destroy()

    def __del__(self) -> None:
        self.destroy()

    def destroy(self) -> None:
        """
        Destroy the underlying set. Idempotent.
        """

        if self._set != ffi.NULL:
            lib.fset_destroy(self._set)

            self._set = ffi.NULL

    def add(self, flow: Flow) -> None:
        """
        Add *flow* to this set.

        :param flow:         The flow to add to this set.
        :raises ValueError:  If the FlowSet has been destroyed.
        :raises MemoryError: If the flow could not be added.
        """

        if self._set == ffi.NULL:
            raise ValueError("FlowSet has been destroyed")

        if lib.fset_add(self._set, flow.fileno()) != 0:
            raise MemoryError(f"Failed to add flow {flow.fileno()}")

    def zero(self) -> None:
        """
        Remove all flows from this set.

        :raises ValueError: If the FlowSet has been destroyed.
        """

        if self._set == ffi.NULL:
            raise ValueError("FlowSet has been destroyed")

        lib.fset_zero(self._set)

    def remove(self, flow: Flow) -> None:
        """
        Remove *flow* from this set.

        :param flow:        The flow to remove from this set.
        :raises ValueError: If the FlowSet has been destroyed.
        """

        if self._set == ffi.NULL:
            raise ValueError("FlowSet has been destroyed")

        lib.fset_del(self._set, flow.fileno())

    def wait(self,
             fq: FEventQueue,
             timeo: Optional[float] = None) -> None:
        """
        Wait for at least one event on one of the monitored flows.

        :param fq:    The :class:`FEventQueue` to drain events into.
        :param timeo: Wait timeout in seconds (None blocks forever).
        :raises ValueError: If the FlowSet has been destroyed.
        :raises FlowEventError: On a negative ouroboros return code.
        """

        if self._set == ffi.NULL:
            raise ValueError("FlowSet has been destroyed")

        _timeo = fl_to_timespec(ffi, timeo)

        rc = lib.fevent(self._set, fq.handle, _timeo)

        raise_errno(rc, default=FlowEventError)