distributed

package
v0.16.10 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 17, 2026 License: BSD-3-Clause, GPL-3.0 Imports: 31 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package distributed implements netcap's agent → collector transport.

Agents connect over TLS 1.3 with mutual authentication. Both sides use self-signed Ed25519 certificates and trust each other by pinning the SHA-256 of the peer's public key (SPKI). The collector derives a client's identity, and therefore its output directory, from its allowlist entry, never from anything the client sends.

After the handshake the connection carries frames:

[1 byte type][4 byte big-endian payload length][payload]

The agent sends Hello once, then Batch frames. The collector answers each Batch with an Ack carrying its sequence number once the data is written, or with an Error frame and closes the connection.

Index

Constants

View Source
const (
	FrameHello byte = 1 // agent → collector, types.AgentHello
	FrameBatch byte = 2 // agent → collector, types.Batch
	FrameAck   byte = 3 // collector → agent, 8 byte big-endian sequence number
	FrameError byte = 4 // collector → agent, UTF-8 reason
)

Frame types.

View Source
const DefaultMaxFrame = 4 << 20

DefaultMaxFrame bounds a frame payload. It is checked before allocating.

View Source
const MaxRecordSize = DefaultMaxFrame - batchOverhead

MaxRecordSize is the largest single record a batch can carry within DefaultMaxFrame.

View Source
const ProtocolVersion = 1

ProtocolVersion is the wire protocol version sent in the agent hello.

Variables

View Source
var (
	// ErrFrameTooLarge is returned for a frame whose declared length exceeds the limit.
	ErrFrameTooLarge = errors.New("frame too large")
	// ErrUnknownFrame is returned for an unknown frame type.
	ErrUnknownFrame = errors.New("unknown frame type")
)
View Source
var ErrServerClosed = errors.New("server closed")

ErrServerClosed is returned by Serve after Shutdown.

View Source
var ErrSinkClosed = errors.New("sink closed")

ErrSinkClosed is returned by Write after Close.

Functions

func ClientTLSConfig

func ClientTLSConfig(id tls.Certificate, serverFingerprint string) (*tls.Config, error)

ClientTLSConfig returns a TLS 1.3 config that presents id and accepts only a server whose key has the pinned fingerprint.

func CountRecords

func CountRecords(t types.Type, data []byte) (int, error)

CountRecords checks that data is a sequence of complete length-delimited records, each a valid protobuf of the record type for t, and returns how many there are. The collector refuses to write anything that fails this, so a malformed batch can never corrupt an output file.

func DecodeAck

func DecodeAck(p []byte) (uint64, error)

DecodeAck decodes an ack payload.

func EncodeAck

func EncodeAck(seq uint64) []byte

EncodeAck encodes an ack payload.

func Fingerprint

func Fingerprint(cert *x509.Certificate) string

Fingerprint returns the lowercase hex SHA-256 of the certificate's public key.

func GenerateIdentity

func GenerateIdentity(certPath, keyPath, commonName string) (string, error)

GenerateIdentity creates a self-signed Ed25519 certificate and key and writes them as PEM to certPath and keyPath with mode 0600. Existing files are never overwritten. It returns the SPKI fingerprint to pin on the other side.

func IdentityFingerprint

func IdentityFingerprint(id tls.Certificate) (string, error)

IdentityFingerprint returns the fingerprint of a loaded identity.

func LoadIdentity

func LoadIdentity(certPath, keyPath string) (tls.Certificate, error)

LoadIdentity loads a certificate and key written by GenerateIdentity.

func NormalizeFingerprint

func NormalizeFingerprint(s string) (string, error)

NormalizeFingerprint lowercases a fingerprint, strips ':' separators and checks that it is 32 bytes of hex.

func PeerName

func PeerName(cs tls.ConnectionState, allow Allowlist) (string, error)

PeerName returns the allowlist name of the client on an established server-side connection.

func ReadFrame

func ReadFrame(r io.Reader, maxPayload int) (t byte, payload []byte, err error)

ReadFrame reads one frame. A declared length above maxPayload fails with ErrFrameTooLarge before any payload memory is allocated.

func RunBatcher

func RunBatcher(ch <-chan []byte, cfg BatcherConfig)

RunBatcher reads length-delimited records from ch and emits batches until ch is closed, then emits what is left. A record larger than MaxBytes is sent in a batch of its own; only one larger than MaxRecordSize is dropped.

func ServerTLSConfig

func ServerTLSConfig(id tls.Certificate, allow Allowlist) *tls.Config

ServerTLSConfig returns a TLS 1.3 config that requires a client certificate whose key is in allow.

func ValidName

func ValidName(name string) bool

ValidName reports whether name may be used as a client name.

func WriteFrame

func WriteFrame(w io.Writer, t byte, payload []byte) error

WriteFrame writes one frame in a single Write call.

Types

type Allowlist

type Allowlist map[string]string

Allowlist maps a client key fingerprint to the client's name.

func LoadAllowlist

func LoadAllowlist(path string) (Allowlist, error)

LoadAllowlist parses the allowlist file at path.

func ParseAllowlist

func ParseAllowlist(r io.Reader) (Allowlist, error)

ParseAllowlist reads lines of "<fingerprint> <name>". Blank lines and lines starting with '#' are ignored. Any malformed line, invalid name, or duplicate fingerprint or name is an error, so a typo stops the collector rather than silently locking a client out or merging two clients.

type BatcherConfig

type BatcherConfig struct {
	Type             types.Type
	MaxBytes         int           // flush when Data would exceed this; clamped to MaxRecordSize
	FlushInterval    time.Duration // flush a non-empty batch at least this often; 0 disables
	ContainsPayloads bool
	Emit             func(*types.Batch)
	OnOversize       func(size int) // called for a record too large to ever send
}

BatcherConfig configures RunBatcher.

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client delivers batches to a collector over one TLS connection, waits for each to be acknowledged, and reconnects with backoff when the connection drops. Unacknowledged batches are kept in memory and resent.

func NewClient

func NewClient(cfg ClientConfig) (*Client, error)

NewClient validates cfg and starts the sender goroutine.

func (*Client) Close

func (c *Client) Close(ctx context.Context) (ClientStats, error)

Close stops accepting batches and waits until the queue is delivered or ctx ends. It returns the final stats; Pending > 0 means batches were not delivered.

func (*Client) Enqueue

func (c *Client) Enqueue(b *types.Batch) error

Enqueue assigns b a sequence number and queues it. It never blocks; when the queue exceeds MaxPending the oldest batches are dropped and counted.

func (*Client) Stats

func (c *Client) Stats() ClientStats

Stats returns a snapshot of the delivery counters.

type ClientConfig

type ClientConfig struct {
	Addr              string
	Identity          tls.Certificate
	ServerFingerprint string
	Hello             types.AgentHello // ProtocolVersion and Session are filled in

	MaxPending  int           // bytes of unacknowledged batches kept for resend, default 64 MiB
	DialTimeout time.Duration // default 10s
	AckTimeout  time.Duration // default 60s
	MinBackoff  time.Duration // default 1s
	MaxBackoff  time.Duration // default 60s

	Logger *log.Logger // default log.Default()
}

ClientConfig configures an agent Client.

type ClientStats

type ClientStats struct {
	Acked    uint64 // written by the collector
	Dropped  uint64 // evicted because MaxPending was exceeded
	Rejected uint64 // refused by the collector as invalid
	Pending  int    // still queued
}

ClientStats counts what happened to enqueued batches.

type Server

type Server struct {
	// contains filtered or unexported fields
}

Server accepts agent connections and writes their batches into a Sink.

func NewServer

func NewServer(cfg ServerConfig) (*Server, error)

NewServer validates cfg and returns a Server.

func (*Server) Serve

func (s *Server) Serve(ln net.Listener) error

Serve accepts TCP connections on ln until Shutdown. It never panics on peer input: every per-connection failure is logged and ends that connection.

func (*Server) Shutdown

func (s *Server) Shutdown(ctx context.Context) ([]SinkFileInfo, error)

Shutdown stops accepting, interrupts open connections, waits for their handlers to return, then closes the sink. Batches that were not acknowledged are resent by their agents.

type ServerConfig

type ServerConfig struct {
	Identity  tls.Certificate
	Allowlist Allowlist
	Sink      *Sink

	MaxFrame         int           // default DefaultMaxFrame
	MaxConns         int           // default 256
	HandshakeTimeout time.Duration // default 10s
	IdleTimeout      time.Duration // max wait for the next frame, default 5m
	WriteTimeout     time.Duration // default 30s

	Logger *log.Logger // default log.Default()
}

ServerConfig configures a collector Server.

type Sink

type Sink struct {
	// contains filtered or unexported fields
}

Sink writes batches into <root>/<client>/<Type>.ncap.gz, one gzip stream per client and type. It is safe for concurrent use.

func NewSink

func NewSink(root string) (*Sink, error)

NewSink creates root if needed and returns a sink writing below it.

func (*Sink) Close

func (s *Sink) Close() ([]SinkFileInfo, error)

Close finalizes every gzip stream and closes the files. Further writes fail.

func (*Sink) Root

func (s *Sink) Root() string

Root returns the absolute output directory.

func (*Sink) Write

func (s *Sink) Write(client string, hello *types.AgentHello, b *types.Batch, numRecords int) error

Write appends the records of b, which must already have been validated with CountRecords, to the file for (client, b.MessageType). The file and its header are created on first use, and the first batch is written like any other. numRecords is added to the file's record count.

type SinkFileInfo

type SinkFileInfo struct {
	Client  string
	Type    types.Type
	Path    string
	Records int64
}

SinkFileInfo describes one output file.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL