Flow Tracing Base Class¶
pcapkit.foundation.traceflow.traceflow contains
TraceFlow, the abstract base
class of a custom flow tracing class, and
TraceFlowBase, which it and the
built-in flow tracing classes derive from.
- class pcapkit.foundation.traceflow.traceflow.TraceFlow[_DT, _BT: Info, _IT: Info, _PT: Info](*, fout='./tmp', format='pcap', byteorder=sys.byteorder, nanosecond=False, bidirectional=True, analyze=False, timeout=None)[source]¶
Bases:
TraceFlowBase[_DT,_BT,_IT,_PT],Generic[_DT,_BT,_IT,_PT]Base flow tracing class.
Example
Registration is opt-in. Pass keyword argument
protocolat class definition to register the flow tracing class under that protocol name:class MyProtocol(TraceFlow, protocol='my_protocol'): ...
Omit it and the subclass is not registered, which is how a class that is not meant to be selectable by name declines:
class MyMixin(TraceFlow): # not registered ...
Such a class can still be registered later, on demand:
Extractor.register_traceflow('my_mixin', MyMixin)
- Parameters:
fout (
str) – output pathformat (
str) – output formatbyteorder (
Literal['little','big']) – output file byte ordernanosecond (
bool) – output nanosecond-resolution file flagbidirectional (
bool) – trace both halves of a conversation as one flowanalyze (
bool) – reassemble each flow’s application layertimeout (
float|None) – idle timeout in seconds, on the capture’s clock;Nonekeeps every flow untilfinish()
Changed in version 1.3.0:
nameandprotocolare read from__protocol_name__and__protocol_type__, where they were abstract properties each flow tracing class implemented, and the built-in name is short:'TCP'rather than'Transmission Control Protocol'. A subclass registers itself withExtractorat class definition.Changed in version 1.5.0: Registration is opt-in, under the
protocolclass keyword; 1.4.x registered every subclass, under itsnamewhen the keyword was omitted (#514). Thebidirectionalandanalysearguments are added, and a flow covers both directions of a conversation unlessbidirectional=Falseis passed.Changed in version 1.7.0: Every argument is keyword-only, with its real default in the signature, where
foutandformatwere required and tookNonefor'./tmp'and'pcap';analyseis renamedanalyze, with no alias (#2839).Changed in version 1.10.0: Takes
timeout, and a flow idle for longer is finalised (#2956).See also
For customisation and extension, see Customisation & Extensions.
- property name: str¶
Protocol name of current class.
Note
Also a class variable, set by
__protocol_name__.
- property protocol: Type[pcapkit.protocols.protocol.ProtocolBase]¶
Protocol of current class.
Note
Also a class variable, set by
__protocol_type__.
- property registry: dict[str, ModuleDescriptor[TraceFlowBase] | Type[TraceFlowBase]]¶
Mapping of protocol names to flow tracing classes.
Note
A class variable only, defined on
TraceFlowMeta. It is not per-class: it reads__traceflow__, the one table every flow tracing registration lands in. It is not__output__, the separate output-dumper table this class owns.
- __protocol_type__: Type[ProtocolBase]¶
Protocol of current flow tracing object.
- _bidir¶
Bidirectional tracing flag. If set to
True, both halves of a conversation share one buffer entry, one label and one output file; otherwise each direction is a flow of its own.- Type:
- _fopen: OrderedDict[int, dictdumper.dumper.Dumper]¶
Dumpers keeping their flow’s output file open, by
id(), least recently written first; see_write().- Type:
- _endian¶
Output file byte order.
- Type:
Literal[‘little’, ‘big’]
- _analyze¶
Application-layer analysis flag. If set to
True, each flow reassembles the payload it carries so that itspacketcan be read; otherwise no payload is buffered andpacketisNone.- Type:
- _parse_keywords: dict[str, Any]¶
Keyword arguments a reassembled payload’s parse takes under
analyze: the stops and context the engine parses its frames with, asEngineBase._setup_traceflowhands them over (#2946).
- _timeout¶
Idle timeout in seconds, on the capture’s clock.
math.infkeeps every flow untilfinish().- Type:
- _seen: dict[_DT, Decimal]¶
Capture timestamp of each open flow’s latest packet, by buffer ID, which
advance()reads; written by_touch(), and only whiletimeoutis finite.- Type:
Defaults
- __output__: DefaultDict[str, tuple[ModuleDescriptor[dictdumper.dumper.Dumper] | Type[dictdumper.dumper.Dumper], str | None]]¶
Format dumper mapping for writing output files. Each value pairs the dumper, as a module descriptor or a
dictdumper.dumper.Dumpersubclass, with the file extension of its format.
Properties
- property timeout: float¶
Idle timeout, in seconds, of the current flow tracing object.
A flow whose latest packet is more than this many seconds old on the capture’s own clock is finalised – see
advance().math.inf, for a tracer given no timeout, keeps every flow untilfinish().Added in version 1.10.0.
Methods
- classmethod register_dumper(format, dumper, *, ext)¶
Register a new dumper class.
Notes
The fully qualified class name of the new dumper class should be
{dumper.module}.{dumper.name}.The overwrite guard fires only when the incumbent dumper differs from the replacement, so re-registering the exact same object is a silent no-op rather than a warning about nothing displaced – the identity guard of the code-keyed registrars (#718, #739).
__output__maps each format to a(dumper, ext)pair, so the identity check compares the incumbent dumper (index0), not the pair – a re-registration that only changesextis still identity-equal on the dumper and stays silent, since the dumper is what “the same object” means here, not the pair as a whole.__output__is also acollections.defaultdict, unlike theExtractorengine, reassembly and flow tracing registries;dict.get()does not invoke the default factory the waycls.__output__[format]would, so it stays non-inserting here as well.The dumper
formatshipped with, as its descriptor or as the class it names, restores the shipped entry rather than storing the class, so an override can be undone and the deferred import is kept (#1363, #1364).- Parameters:
format (
str) – format namedumper (
ModuleDescriptor[dictdumper.dumper.Dumper] |Type[dictdumper.dumper.Dumper]) – module descriptor or adictdumper.dumper.Dumpersubclassext (
str) – file extension
- Raises:
RegistryError – If
dumperis not a class, or not adictdumper.dumper.Dumpersubclass, such asDumper.- Warns:
RegistryWarning– If a different dumper is already registered forformat; it is overwritten.
Removed in version 1.1.1.post2:
register, which this replaces with no alias.Changed in version 1.3.0:
dumper, a module descriptor or a class, replaces themoduleandclass_name pair, with no alias.Changed in version 1.7.0:
extis keyword-only (#2839).
- classmethod register_callback(callback, *, index=None)¶
Register callback function.
- Parameters:
callback (
Callable[[_IT],None]) – callback function, which will be called when a traced flow is finalised, with the flow’s index entry (trace.tcp.index) as its only argumentindex (
int|None) – index to be inserted in the callback list; by default, the callback will be appended to the end of the list
Every callback runs on each finalised flow, once its output file holds every frame the entry lists. One raising an
Exceptiondoes not stop the rest, and the first such error propagates once they have run.Changed in version 1.7.0: A callback that raises no longer stops the ones after it (#2855).
- classmethod make_fout(fout='./tmp', *, format='pcap')¶
Make root path for output.
- Parameters:
- Return type:
- Returns:
Dumper of specified format and file extension of output file.
- Warns:
FormatWarning– Ifformatis not supported.FileWarning– Iffoutexists but is not a directory, andformatis not supported.
- Raises:
FileExists – If
foutexists but is not a directory, andformatis supported.
Changed in version 1.7.0:
fmtis renamedformat, with no alias, and is keyword-only (#2839).
- make_bufid(packet)¶
Derive the buffer ID a packet belongs to.
- Parameters:
packet (
_PT) – a flow packet- Returns:
the packet’s two endpoints, as
_endpoints()reads them, in one flattuple–(address, port, address, port)for TCP and UDP,(address, address)for IP.- Return type:
_DT
Tracing bidirectionally means both halves of a conversation have to land on the same key, so the two endpoints are ordered canonically – the lesser first – rather than as (source, destination): the client’s
A→Band the server’sB→Aboth reduce tomin(A, B), max(A, B).The result stays a plain
tuple, which is deliberate and not merely convenient: it is adictkey, and anInfocannot be one – inheritingcollections.abc.Mappingsets__hash__toNone.Note
Both endpoints of a flow are of the same address family, so the comparison never has to order an
IPv4Addressagainst anIPv6Address– which raisesTypeError.Changed in version 1.10.0: Defined here for every flow tracer, reading the endpoints from
_endpoints(), whereTCPdefined it (#2956).
- abstractmethod dump(packet)¶
Dump frame to output files.
- Parameters:
packet (
_PT) – a flow packet (trace.tcp.packet)
- abstractmethod trace(packet, *, output=False)¶
Trace packets.
- Overloads:
- Parameters:
packet (
_PT) – a flow packet (trace.tcp.packet)output (
bool) – flag if has formatted dumper
- Returns:
If
outputisTrue, returns the initiatedDumperobject, which will dump data to the output file named after the flow label; otherwise, returns the flow label itself.
- abstractmethod submit()¶
Submit traced TCP flows.
- Return type:
- Returns:
Traced TCP flow (trace.tcp.index).
- advance(timestamp)¶
Advance the capture clock, finalising every flow it leaves idle.
- Parameters:
timestamp (
float) – Capture timestamp of the current frame, in seconds since the Unix epoch.
A flow is idle once more than
timeoutseconds separatetimestampfrom its latest packet, and is finalised then, its callbacks run, asfinish()finalises it at the end of the capture. The two are compared exactly, as the decimals_exact()reads, so a flow exactlytimeoutseconds idle is kept whatever its timestamps’ binary rounding. That is the idle timeout by which IPFIX ends a flow, flowEndReason0x01of Information Element 136. TheExtractorcalls this with every frame’s timestamp before the frame is fed, and a flow packet calls it with its own, so a tracer fed by hand times flows out too.A flow tracer whose flows never record a packet’s time, as one built on
TraceFlowthat does not call_touch(), has nothing to time out, and nothing is finalised.Added in version 1.10.0.
- finish()¶
Finalise every flow still being traced.
Called by
Extractor._cleanuponce the capture has been read to its end, which is the point at which a flow that was never superseded can be said to be over.The base implementation only calls
close(), so a tracer that has no such notion need not override it.submit()must remain able to report a flow that was never finalised, since nothing guarantees this is called: a tracer driven directly rather than through anExtractornever sees an end of capture.Implementations must be idempotent:
Extractor._cleanupcan run more than once for one extraction.
- close()¶
Close every flow output file this tracer keeps open.
_write()keeps a flow’s file open between its frames. A flow written to after this reopens its file, so tracing can go on.finish()calls this, and so does__call__()when tracing a frame raises; a tracer dropped before either closes them when it is collected.Added in version 1.7.0.
Data Models
- classmethod __init_subclass__(protocol=None, *args, **kwargs)[source]¶
Initialise subclass.
This method is to be used for registering the flow tracing class to
Extractorclass.- Parameters:
- Raises:
UnsupportedCall – If any unrecognised class keyword is given.
Registration is opt-in: the subclass is registered if and only if
protocolis given. This is what lets a subclass decline registration rather than having to inheritTraceFlowBaseto avoid it, and it matchesEnumSchema.__init_subclass__, which guards on its owncodekeyword the same way.Note
__protocol_name__is not an opt-in. It supplies thenamethe class reports, which it does whether or not the class is registered; only the keyword decides registration.See also
For more details, please refer to
pcapkit.foundation.extraction.Extractor.register_traceflow().
- __call__(packet)¶
Dump frame to output files.
- Parameters:
packet (
_PT) – a flow packet (trace.tcp.packet)
An error closes every output file kept open (
close()), since the caller may then stop beforefinish().
Utilities
- _write(dumper, value, name, *, hold=True)¶
Write a frame to a flow’s output file, keeping the file open.
- Parameters:
dumper (
dictdumper.dumper.Dumper) – the flow’s output dumpervalue (
Any) – the framename (
str) – name of the frame’s blockhold (
bool) – whether the flow takes more frames, and so whether its file is worth keeping open
Keeping the file open between frames, through
open(), saves reopening it per frame (#2815). At mostTRACE_OPEN_FILE_LIMITfiles are kept open: past it, the one written least recently is closed, and reopened on its flow’s next frame.
- _release(dumper)¶
Close a flow’s output file, once the flow takes no more frames.
- Parameters:
dumper (
dictdumper.dumper.Dumper) – the flow’s output dumper
- _endpoints(packet)¶
The endpoints of a flow packet: its sender’s, then its receiver’s.
- Parameters:
packet (
_PT) – a flow packet- Return type:
- Returns:
(address, port)of the source, then of the destination, which is how TCP and UDP key a flow. A tracer whose protocol has no ports, asIP, overrides it.
make_bufid()keys a flow on them,_make_label()names it after them, and_append()tells the directions apart by them.Added in version 1.10.0.
- _make_label(packet)¶
Label a new flow after the packet that opens it.
- Parameters:
packet (
_PT) – the flow packet opening the flow- Return type:
- Returns:
The fields of each endpoint
_endpoints()reads, joined by_, source first, then the packet’s timestamp, the three joined by-, and made unique within the tracer by_unique_label(). On an IPv6 flow every:is replaced by., since a Windows file name cannot carry one, where it separates the drive letter.
So the label names the initiator first, and the reverse half of a bidirectional conversation joins the flow rather than minting a label of its own.
Added in version 1.10.0.
- _unique_label(label)¶
Make a new flow’s label unique within this tracer.
- Parameters:
label (
str) – the label built from the packet that opens the flow- Return type:
- Returns:
labelitself if no earlier flow carries it; otherwiselabelsuffixed with the first of-1,-2, … that is still unused.
The label names the flow’s output file, which is opened – and so truncated – when the flow starts. Two flows with one label would therefore share one file, and the later would erase the earlier: the same endpoints opening a second flow at the same capture timestamp, as a flow superseded or timed out on its endpoints’ next packet can. A label that does not collide is returned unchanged.
- _make_fpout(label, protocol)¶
Make the dumper a new flow writes its output file through.
- Parameters:
- Return type:
- Returns:
A dumper of the tracer’s output format, writing the file
_output_path()reports, or no file when the format writes none.
Added in version 1.10.0.
- _output_path(label)¶
Path of a flow’s output file, as an index entry reports it.
- Parameters:
label (
str) – the flow’s label- Return type:
- Returns:
The file
trace()writes the flow to, orNonewhen the output format writes no file at all. An empty extension still writes one, named after the label alone.
submit()and_finalise()both report through this, so an open flow and a finalised one name the same file (#2237).
- _append(buffer, packet)¶
Record a packet’s frame number in its flow, and in the direction it went.
- Parameters:
buffer (
_BT) – the flow’s buffer, holdingindex,origin,forwardandreverseas each built-in flow tracer’s doespacket (
_PT) – a flow packet
The frame joins
index, which keeps both directions in capture order, andforwardif its source endpoint is theoriginthat opened the flow,reverseotherwise, so each half stays recoverable on its own.Added in version 1.10.0.
- _touch(bufid, timestamp)¶
Note when an open flow last saw a packet, for
advance()to time it out.- Parameters:
bufid (
_DT) – buffer identifier of the flowtimestamp (
float) – capture timestamp of the packet
The latest timestamp is kept, so a capture whose timestamps step back does not age a flow. Nothing is noted while
timeoutis infinite.Added in version 1.10.0.
- _make_index(buffer)¶
Report a flow’s buffer as its index entry.
- Parameters:
buffer (
_BT) – a flow buffer- Return type:
_IT- Returns:
The flow’s index entry.
- Raises:
NotImplementedError – Unless the flow tracer overrides it, as each built-in does; only
_finalise()and the built-ins’submit()call it.
Added in version 1.10.0.
- _finalise(bufid)¶
Finalise a flow: report it, and stop tracing into it.
- Parameters:
bufid (
_DT) – buffer identifier of the flow to finalise- Return type:
_IT- Returns:
The flow’s index entry, from
_make_index().
Called once per flow, from where its tracer ends it:
finish()at the end of the capture,advance()once it is idle, or a rule of the tracer’s own, such as a TCP connection’s reuse.The flow’s file is closed and its entry stored before the callbacks run, so a callback that raises propagates and leaves the flow in the index. One raising an
Exceptiondoes not stop the callbacks after it: the first such error is re-raised once all have run, and a later one logged, byrun_callbacks(), to the logger of the module the tracer is defined in.
Internal Definitions¶
- class pcapkit.foundation.traceflow.traceflow.TraceFlowBase[_DT, _BT: Info, _IT: Info, _PT: Info](*, fout='./tmp', format='pcap', byteorder=sys.byteorder, nanosecond=False, bidirectional=True, analyze=False, timeout=None)[source]¶
Bases:
Generic[_DT,_BT,_IT,_PT]Base flow tracing class.
- Parameters:
fout (
str) – output pathformat (
str) – output formatbyteorder (
Literal['little','big']) – output file byte ordernanosecond (
bool) – output nanosecond-resolution file flagbidirectional (
bool) – trace both halves of a conversation as one flowanalyze (
bool) – reassemble each flow’s application layertimeout (
float|None) – idle timeout in seconds, on the capture’s clock;Nonekeeps every flow untilfinish()
Note
This class is for internal use only. For customisation, please use
TraceFlowinstead.
- class pcapkit.foundation.traceflow.traceflow.TraceFlowMeta(name, bases, namespace, /, **kwargs)[source]¶
Bases:
ABCMetaMeta class to add dynamic support to
TraceFlow.It provides
TraceFlow.name,TraceFlow.protocolandTraceFlow.registryas class properties, the first two read from__protocol_name__and__protocol_type__where a subclass sets them.
Type Variables¶
- pcapkit.foundation.traceflow.traceflow._BT: pcapkit.corekit.infoclass.Info¶
Buffer data structure.
- pcapkit.foundation.traceflow.traceflow._IT: pcapkit.corekit.infoclass.Info¶
Index data structure.
- pcapkit.foundation.traceflow.traceflow._PT: pcapkit.corekit.infoclass.Info¶
Packet data structure.