# -*- coding: utf-8 -*-
"""Base Class
================
.. module:: pcapkit.foundation.engines.engine
This is the abstract base class implementation for
all engine support functionality.
"""
import abc
from typing import TYPE_CHECKING, Generic, TypeVar
from pcapkit.corekit.module import ModuleDescriptor
from pcapkit.foundation.reassembly import ReassemblyManager
from pcapkit.foundation.traceflow import TraceFlowManager
from pcapkit.utilities.exceptions import RegistryError, UnsupportedCall, stacklevel
from pcapkit.utilities.warnings import AttributeWarning, RegistryWarning, warn
__all__ = ['Engine']
if TYPE_CHECKING:
from typing import Any, Callable, Optional, Type
from pcapkit.foundation.extraction import Extractor
#: A :mod:`pcapkit.toolkit` reassembly or flow tracing adapter. Called on a
#: frame with the arguments its engine passes, it returns the reassembler's or
#: the flow tracer's input record, a tuple of them, or :data:`None`.
Adapter = Callable[..., Any]
_T = TypeVar('_T')
[docs]
class EngineBase(Generic[_T], metaclass=EngineMeta):
"""Base class for engine support.
Args:
extractor: :class:`~pcapkit.foundation.extraction.Extractor` instance.
Note:
This class is for internal use only. For customisation, please use
:class:`Engine` instead.
"""
if TYPE_CHECKING:
#: Engine name.
__engine_name__: 'str'
#: Engine module name.
__engine_module__: 'str'
##########################################################################
# Defaults.
##########################################################################
#: Reassembly adapters. For each reassembler this engine supports, under the
#: name it is registered by in :attr:`Extractor.__reassembly__
#: <pcapkit.foundation.extraction.Extractor.__reassembly__>`, the
#: :mod:`pcapkit.toolkit` function that makes its input from a frame. An
#: enabled reassembler with no entry is disabled at startup, with a warning,
#: and an engine with none supports no reassembly.
#:
#: .. versionadded:: 1.7.0
__reassembly__ = {} # type: dict[str, ModuleDescriptor[Adapter] | Adapter]
#: Flow tracing adapters. For each flow tracer this engine supports, under the
#: name it is registered by in :attr:`Extractor.__traceflow__
#: <pcapkit.foundation.extraction.Extractor.__traceflow__>`, the
#: :mod:`pcapkit.toolkit` function that makes its input from a frame. An
#: enabled flow tracer with no entry is dropped at startup, with a warning,
#: and an engine with none supports no flow tracing.
#:
#: .. versionadded:: 1.7.0
__traceflow__ = {} # type: dict[str, ModuleDescriptor[Adapter] | Adapter]
##########################################################################
# Properties.
##########################################################################
@property
def name(self) -> 'str':
"""Engine name.
Note:
This instance property is not what a class attribute lookup
reaches: on the class, the metaclass property of the same name
answers instead, with the same value.
"""
if hasattr(self, '__engine_name__'):
return self.__engine_name__
return type(self).name # type: ignore[return-value]
@property
def module(self) -> 'str':
"""Engine module name.
Note:
This instance property is not what a class attribute lookup
reaches: on the class, the metaclass property of the same name
answers instead, with the same value.
"""
if hasattr(self, '__engine_module__'):
return self.__engine_module__
return type(self).module # type: ignore[return-value]
@property
def extractor(self) -> 'Extractor':
"""Extractor instance."""
return self._extractor
##########################################################################
# Availability.
##########################################################################
[docs]
@classmethod
def unsupported_reason(cls) -> 'Optional[str]':
"""Why this engine cannot run in this environment, if it cannot.
Engines are normally gated by whether their third-party module imports,
which :meth:`pcapkit.foundation.extraction.Extractor.import_test` decides.
This hook is for the cases that question cannot answer -- most often a
dependency that installs cleanly and only fails when it is *used*, so the
import test passes and the error escapes from the engine's constructor as
a hard failure instead of degrading to the default engine.
The default is :data:`None`, i.e. always available; override it only where
there is a real limitation, and return a short phrase naming the *cause*
rather than merely refusing, since the string is shown to the user.
Returns:
A phrase describing the limitation, or :data:`None` when the engine is
usable here.
See Also:
:class:`pcapkit.foundation.engines.pypcapfile.PyPCAPFile` overrides
this, because ``pypcapfile`` installs on Python 3.12 and newer and then
raises :exc:`ModuleNotFoundError` on first use.
"""
return None
##########################################################################
# Reassembly.
##########################################################################
[docs]
@classmethod
def register_reassembly(cls, protocol: 'str', adapter: 'ModuleDescriptor[Adapter] | Adapter') -> 'None':
"""Register the adapter feeding a reassembler from this engine's frames.
Arguments:
protocol: name the reassembler is registered by in
:attr:`Extractor.__reassembly__
<pcapkit.foundation.extraction.Extractor.__reassembly__>`,
lower-cased
adapter: module descriptor or callable, taking a frame as this
engine's own adapters do
Raises:
RegistryError: If ``adapter`` is neither a module descriptor nor
callable.
Warns:
RegistryWarning: If a different adapter is already registered under
``protocol``; it is overwritten.
The entry is written on ``cls`` alone, so a subclass registering one
leaves the engine it derives from as it was.
.. versionadded:: 1.7.0
"""
cls._register_adapter('__reassembly__', 'reassembly', protocol, adapter)
@classmethod
def _register_adapter(cls, table: 'str', kind: 'str', protocol: 'str',
adapter: 'ModuleDescriptor[Adapter] | Adapter') -> 'None':
"""Write an adapter into this engine's own copy of an adapter map.
Arguments:
table: the map's attribute, ``'__reassembly__'`` or ``'__traceflow__'``
kind: what the map feeds, as the overwrite warning names it
protocol: name to register ``adapter`` under, lower-cased
adapter: module descriptor or callable
Raises:
RegistryError: If ``adapter`` is neither a module descriptor nor
callable.
Warns:
RegistryWarning: If a different adapter is already registered under
``protocol``; it is overwritten.
"""
if not isinstance(adapter, ModuleDescriptor) and not callable(adapter):
raise RegistryError(f'adapter must be a module descriptor or callable, not {adapter!r}')
if table not in cls.__dict__:
setattr(cls, table, dict(getattr(cls, table)))
adapters = getattr(cls, table) # type: dict[str, ModuleDescriptor[Adapter] | Adapter]
name = protocol.lower()
incumbent = adapters.get(name)
if incumbent is not None and incumbent != adapter:
warn(f'{cls.__name__}: {kind} adapter {name} already registered, overwriting',
RegistryWarning, stacklevel=stacklevel())
adapters[name] = adapter
[docs]
def _setup_reassembly(self, *, parse: 'bool' = False) -> 'None':
"""Disable each enabled reassembler this engine has no adapter for.
Args:
parse: whether this engine parses its frames with the extraction's
stops and context; as the extraction's engine, it then hands them
to each reassembler kept, whose reassembled payloads are parsed
with them as the frames' next layers are (:issue:`2933`)
Warns:
AttributeWarning: For each reassembler disabled; once, naming them
all, if this engine supports no reassembly, which then stays off.
"""
ext = self._extractor
if not ext._flag_r or not ext._reasm:
return
adapters = self.__reassembly__
if not adapters:
ignored = list(ext._reasm)
ext._flag_r = False
ext._reasm = ReassemblyManager()
warn(f"'Extractor(engine={ext._exnam})' object does not support reassembly; "
f'so reassembly={ignored!r} will be ignored', AttributeWarning, stacklevel=stacklevel())
return
unsupported = [name for name in ext._reasm if name not in adapters]
if unsupported:
for name in unsupported:
warn(f"'Extractor(engine={ext._exnam})' object does not support {ext._reasm[name].name} "
f'reassembly; so {name!r} will be ignored', AttributeWarning,
stacklevel=stacklevel())
ext._reasm = ReassemblyManager((name, reasm) for (name, reasm) in ext._reasm.items()
if name in adapters)
keywords = self._frame_keywords() if parse else None
if keywords is None:
return
for (_, reasm) in ext._reasm.items():
reasm._parse_keywords = dict(keywords)
[docs]
def _frame_keywords(self) -> 'Optional[dict[str, Any]]':
"""The stops and context this engine parses its frames with, those set.
Returns:
The extraction's ``layer``, ``protocol`` and ``context`` keywords,
only those set, so an ``analyze`` taking no keywords, as a custom
``__protocol_type__``'s may, is called as before when the extraction
sets none; :data:`None` unless this engine is the extraction's, since a
third-party one runs this one's ``run`` for the global header alone
(:meth:`Extractor.record_header
<pcapkit.foundation.extraction.Extractor.record_header>`) and parses
no frame with them.
"""
ext = self._extractor
if getattr(ext, '_exeng', None) is not self:
return None
keywords = {} # type: dict[str, Any]
if ext._exlyr is not None:
keywords['layer'] = ext._exlyr
if ext._exptl is not None:
keywords['protocol'] = ext._exptl
if ext._exctx:
keywords['context'] = ext._exctx
return keywords
[docs]
def _reassemble(self, timestamp: 'float', *args: 'Any', **kwargs: 'Any') -> 'None':
"""Feed a frame to every enabled reassembler.
Arguments:
timestamp: capture timestamp of the frame, in seconds since the Unix
epoch
*args: the frame, as this engine's adapters take it
**kwargs: as this engine's adapters take them
Each reassembler's clock is first advanced to ``timestamp``, so a buffer
expires once the capture passes its deadline whether or not the frame is
its protocol's. The adapter's record, or each of a tuple of them, is then
fed in.
"""
adapters = self.__reassembly__
for (name, reasm) in self._extractor._reasm.items():
reasm.advance(timestamp)
adapter = adapters[name]
if isinstance(adapter, ModuleDescriptor):
adapter = adapter.klass
data = adapter(*args, **kwargs)
if data is None:
continue
for packet in (data if isinstance(data, tuple) else (data,)):
reasm(packet)
##########################################################################
# Flow tracing.
##########################################################################
[docs]
@classmethod
def register_traceflow(cls, protocol: 'str', adapter: 'ModuleDescriptor[Adapter] | Adapter') -> 'None':
"""Register the adapter feeding a flow tracer from this engine's frames.
Arguments:
protocol: name the flow tracer is registered by in
:attr:`Extractor.__traceflow__
<pcapkit.foundation.extraction.Extractor.__traceflow__>`,
lower-cased
adapter: module descriptor or callable, taking a frame as this
engine's own adapters do
Raises:
RegistryError: If ``adapter`` is neither a module descriptor nor
callable.
Warns:
RegistryWarning: If a different adapter is already registered under
``protocol``; it is overwritten.
The entry is written on ``cls`` alone, so a subclass registering one
leaves the engine it derives from as it was.
.. versionadded:: 1.7.0
"""
cls._register_adapter('__traceflow__', 'flow tracing', protocol, adapter)
[docs]
def _setup_traceflow(self, *, parse: 'bool' = False) -> 'None':
"""Drop each enabled flow tracer this engine has no adapter for.
Args:
parse: whether this engine parses its frames with the extraction's
stops and context; as the extraction's engine, it then hands them
to each flow tracer kept, whose ``analyze`` reassemblers parse
their payloads with them as the frames' next layers are
(:issue:`2946`)
Warns:
AttributeWarning: For each flow tracer dropped; once, naming them
all, if this engine supports no flow tracing.
Dropping the last flow tracer turns flow tracing off.
"""
ext = self._extractor
if not ext._flag_t:
return
held = [name for (name, tracer) in ext._trace.items() if tracer is not None]
adapters = self.__traceflow__
unsupported = [name for name in held if name not in adapters]
keywords = self._frame_keywords() if parse else None
if keywords is not None:
for (name, tracer) in ext._trace.items():
if tracer is not None and name not in unsupported:
tracer._parse_keywords = dict(keywords)
if not unsupported:
return
if not adapters:
warn(f"'Extractor(engine={ext._exnam})' object does not support flow tracing; "
f'so traceflow={held!r} will be ignored', AttributeWarning, stacklevel=stacklevel())
else:
for name in unsupported:
warn(f"'Extractor(engine={ext._exnam})' object does not support {ext._trace[name].name} "
f'flow tracing; so {name!r} will be ignored', AttributeWarning,
stacklevel=stacklevel())
# NOTE: a dropped tracer is passed as None, which the manager reads as disabled; with none
# left, tracing is off, so the Extractor neither finishes nor reports a tracer it lost.
ext._trace = TraceFlowManager(**{name: (None if name in unsupported else tracer)
for (name, tracer) in ext._trace.items()})
if len(unsupported) == len(held):
ext._flag_t = False
[docs]
def _traceflow(self, *args: 'Any', **kwargs: 'Any') -> 'None':
"""Feed a frame to every enabled flow tracer.
Arguments:
*args: the frame, as this engine's adapters take it
**kwargs: as this engine's adapters take them
Each flow tracer is fed its adapter's record, or each of a tuple of
them.
"""
adapters = self.__traceflow__
for (name, tracer) in self._extractor._trace.items():
if tracer is None:
continue
adapter = adapters[name]
if isinstance(adapter, ModuleDescriptor):
adapter = adapter.klass
data = adapter(*args, **kwargs)
if data is None:
continue
for packet in (data if isinstance(data, tuple) else (data,)):
tracer(packet)
##########################################################################
# Data models.
##########################################################################
def __init__(self, extractor: 'Extractor') -> 'None':
#: Extractor instance this engine reads for.
self._extractor = extractor
[docs]
def __call__(self) -> 'None':
"""Start extraction.
This method will directly call :meth:`run` to start the
extraction process.
"""
self.run()
##########################################################################
# Methods.
##########################################################################
[docs]
@abc.abstractmethod
def run(self) -> 'None':
"""Start extraction.
This method is the entry point for file extraction. It is to be used
for preparing the extraction process, such as parsing the file header
and setting up the extraction engines.
"""
[docs]
@abc.abstractmethod
def read_frame(self) -> '_T':
"""Read frame.
This method is to be used for reading a frame from the file. It is to
read a frame from the file using the prepared engine instance and
return the parsed frame.
"""
[docs]
def close(self) -> 'None':
"""Close engine.
This method is to be used for closing the engine instance. It is to
close the engine instance after the extraction process is finished.
"""
[docs]
class Engine(EngineBase[_T], Generic[_T]):
"""Base class for engine support.
Example:
Registration is opt-in. Pass keyword argument ``engine`` at class
definition to register the engine under that name:
.. code-block:: python
class MyEngine(Engine, engine='my_engine'):
...
Omit it and the subclass is *not* registered, which is how a class
that is not meant to be selectable by name declines:
.. code-block:: python
class MyMixin(Engine): # not registered
...
Such a class can still be registered later, on demand:
.. code-block:: python
Extractor.register_engine('my_mixin', MyMixin)
Args:
extractor: :class:`~pcapkit.foundation.extraction.Extractor` instance.
.. versionchanged:: 1.3.0
:attr:`~EngineBase.name` and :attr:`~EngineBase.module` are properties,
read from ``__engine_name__`` and ``__engine_module__`` or else from the
class, where they were abstract class methods each engine implemented.
A subclass registers itself with
:class:`~pcapkit.foundation.extraction.Extractor` at class definition.
.. versionchanged:: 1.5.0
Registration is opt-in, under the ``engine`` class keyword, which
replaces 1.4.x's ``name`` with no alias; 1.4.x registered every
subclass, under its :attr:`~EngineBase.name` (its ``__engine_name__``,
else its class name) when ``name`` was omitted (:issue:`514`).
"""
[docs]
def __init_subclass__(cls, /, engine: 'Optional[str]' = None, *args: 'Any', **kwargs: 'Any') -> 'None':
"""Initialise subclass.
This method is to be used for registering the engine class to
:class:`~pcapkit.foundation.extraction.Extractor` class.
Args:
engine: Engine name to register the subclass under, lowercased.
:data:`None` (the default) skips registration entirely.
*args: Arbitrary positional arguments.
**kwargs: Arbitrary keyword arguments.
Raises:
UnsupportedCall: If any unrecognised class keyword is given.
Registration is **opt-in**: the subclass is registered if and only if
``engine`` is given. This is what lets a subclass decline registration
rather than having to inherit :class:`EngineBase` to avoid it, and it
matches :meth:`EnumSchema.__init_subclass__
<pcapkit.protocols.schema.EnumSchema.__init_subclass__>`, which
guards on its own ``code`` keyword the same way.
Note:
:attr:`__engine_name__
<pcapkit.foundation.engines.engine.EngineBase.__engine_name__>` is
*not* an opt-in. It supplies the
:attr:`name <pcapkit.foundation.engines.engine.EngineBase.name>`
the engine reports, which it does whether or not the engine is
registered; only the keyword decides registration.
Note:
The keyword is ``engine`` rather than ``name`` because, below
Python 3.11, ``abc.ABCMeta.__new__`` takes ``mcls``, ``name``,
``bases`` and ``namespace`` as positional-*or-keyword* parameters, so
a class keyword by any of those names makes the class statement raise
:exc:`TypeError` before this method is reached. ``metaclass`` is
unusable on every version, since the ``class`` statement consumes it.
See Also:
For more details, please refer to
:meth:`pcapkit.foundation.extraction.Extractor.register_engine`.
"""
# NOTE: an unknown class keyword would be dropped by ``super().__init_subclass__()``,
# silently skipping registration, so reject it; ``args`` is reachable by a direct call.
if args or kwargs:
unexpected = ', '.join([*map(repr, args), *sorted(kwargs)])
raise UnsupportedCall(f'{cls.__name__}: unexpected class keyword(s): {unexpected}')
if engine is not None:
from pcapkit.foundation.extraction import \
Extractor # pylint: disable=import-outside-toplevel
Extractor.register_engine(engine.lower(), cls)
return super().__init_subclass__()