logsv2

package
v0.29.0 Latest Latest
Warning

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

Go to latest
Published: Dec 2, 2026 License: AGPL-3.0 Imports: 40 Imported by: ? 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 logsv2 is the log capability for a set of sources (contract v2).

A plugin describes the resources it can show logs for (LogResource), how to list, and watch, the sources of one resource (SourceResolver) and how to open one source's stream (SourceKind). A session shows the sources of a resource. The SDK keeps the catalog of the session's sources, applies its selection and its limit and runs the streams: one goroutine per session, the scheduler, owns the catalog, the selection, the state of every source, the resume points and the slots, and is the only writer of the session's output.

v1 (package pkg/v1/logs) stays as it is and keeps serving old plugins. A plugin registers either or both; the host asks for v2 first. A v1 message is never decoded as a v2 message.

Index

Constants

View Source
const (
	// DefaultPageSize is the page of a catalog call that does not ask for one.
	DefaultPageSize = 50
	// MaxPageSize is the largest page of a catalog call.
	MaxPageSize = 200
	// MaxFacetValues is the most values a facet lists.
	MaxFacetValues = 20
	// SnapshotWholeMax is the most sources a catalog may hold for a snapshot to list it whole. The
	// rule applies only when the total is known: a plugin that does not know it lists the selected sources.
	SnapshotWholeMax = 50
	// SnapshotSelectedExtra is how many sources a snapshot lists beyond the limit when the
	// catalog is too large to list whole: only the selected ones.
	SnapshotSelectedExtra = 100
)
View Source
const (
	// MaxSourceIDBytes bounds LogSource.ID, which must not be empty.
	MaxSourceIDBytes = 1024
	// MaxSourceKindBytes bounds LogSource.Kind.
	MaxSourceKindBytes = 64
	// MaxSourceLabelBytes bounds LogSource.Label.
	MaxSourceLabelBytes = 2048
	// MaxSourceLabels bounds the entries of LogSource.Labels.
	MaxSourceLabels = 16
	// MaxSourceLabelKeyBytes bounds a key of LogSource.Labels.
	MaxSourceLabelKeyBytes = 64
	// MaxSourceLabelValueBytes bounds a value of LogSource.Labels.
	MaxSourceLabelValueBytes = 512
	// MaxSourceRank bounds the values of LogSource.Rank.
	MaxSourceRank = 16
	// MaxSourceInstanceBytes bounds LogSource.Instance.
	MaxSourceInstanceBytes = 1024
	// MaxReasonBytes bounds the text a plugin gives for a change of its catalog or for the end of a
	// source: SourceEvent.Reason and EndedError.Reason. Text beyond it is cut where a character ends.
	MaxReasonBytes = 256
)

Bounds of the text and the lists a plugin describes its sources with. The text of a source travels in every message that lists, selects or reports it, and protobuf text is UTF-8: a source beyond these bounds is dropped where it enters a session, instead of ending the stream that would carry it.

View Source
const (
	// MaxResourceKeyBytes bounds the key of a log resource.
	MaxResourceKeyBytes = 256
	// MaxKindKeyBytes bounds the key of a source kind.
	MaxKindKeyBytes = 64
	// MaxDimensionKeyBytes bounds the key of a dimension, which is a key of LogSource.Labels.
	MaxDimensionKeyBytes = MaxSourceLabelKeyBytes
	// MaxDisplayLabelBytes bounds the label of a dimension and of an option: the text the UI shows.
	MaxDisplayLabelBytes = 256
	// MaxLimitCeiling bounds LogResource.LimitCeiling. The snapshot of a session lists at most its
	// limit plus SnapshotSelectedExtra sources, and the limit is at most the ceiling, so the ceiling
	// bounds the reply that holds a snapshot, which must fit the wire.
	MaxLimitCeiling = 1000
)

Bounds of what a plugin registers. A registration that is beyond them is refused when the manager is made.

View Source
const (
	// SummaryInterval is the shortest time between two summary events of a session.
	SummaryInterval = 250 * time.Millisecond
	// MaxRemovedEntries is how many removed sources the catalog keeps; sources that the
	// selection includes are always kept.
	MaxRemovedEntries = 1000
)
View Source
const (
	// DefaultLimit is the number of sources a session streams at once unless it asks for another.
	DefaultLimit = 20
	// SDKLimitCeiling is the highest limit of a resource that declares no ceiling.
	SDKLimitCeiling = 100
	// MinTailLines is the least a source's share of the tail budget comes to.
	MinTailLines = 50
)
View Source
const (
	// BreakerThreshold is how many permanent failures of one class in a row hold promotions back.
	BreakerThreshold = 3
	// StartBurst is how many sources a session opens at once.
	StartBurst = 10
	// StartInterval is the time between the openings of a session after its burst: ten each second.
	StartInterval = 100 * time.Millisecond
	// ReconnectInitialDelay is the first backoff of a source that reconnects.
	ReconnectInitialDelay = time.Second
	// ReconnectMaxDelay is the longest backoff.
	ReconnectMaxDelay = 30 * time.Second
	// MaxAttemptsWithoutFollow is how many attempts a session that does not follow gives a source
	// that keeps failing with a transient error before it fails the source; a session that follows
	// retries for as long as the source is selected.
	MaxAttemptsWithoutFollow = 5
	// ResumeMaxLines and ResumeMaxBytes bound a resume: the lines a resumed source may be
	// asked for, and the lines and bytes that are dropped to find the point where it stopped.
	ResumeMaxLines = 1000
	// ResumeMaxBytes is the other bound of a resume.
	ResumeMaxBytes = 1 << 20
	// StableAfter is how long a stream must have been open for its next failure to start the
	// backoff over.
	StableAfter = 30 * time.Second
)
View Source
const (
	// MaxBatchLines is the most lines a batch carries.
	MaxBatchLines = 100
	// MaxBatchBytes is the most content a batch carries; a line that alone reaches it
	// travels alone.
	MaxBatchBytes = 1 << 20
	// BatchDelay is the longest a line waits for others before its batch is sent.
	BatchDelay = 20 * time.Millisecond
	// MaxLineBytes is the longest line the SDK reads as one line; a longer one is read as
	// several, each at most this long.
	MaxLineBytes = 1 << 20
)
View Source
const MaxSelectionRefs = 5000

MaxSelectionRefs bounds Include plus Exclude of one selection.

PluginID is the key the capability is registered under, beside "log", the key of contract v1. A plugin registers the contract it serves; the host asks for this one first.

Variables

View Source
var ErrReplayUnknown = errors.New("log replay is unknown")

ErrReplayUnknown is what ReplayCount returns when it cannot tell how many of the first lines of a stream are replay: the opening carries no replay flags and no caught-up event.

View Source
var ErrSourceNotReady = errors.New("log source is not ready")

ErrSourceNotReady is what Open returns for a source that cannot be opened yet: the source turns pending, takes no slot and no failure is counted. An Updated event with a non-empty Instance for the source opens it again.

Functions

func RegisterLogPluginServer

func RegisterLogPluginServer(registrar grpc.ServiceRegistrar, server logsv2pb.LogPluginServer)

RegisterLogPluginServer registers the log service. It keeps the generated handlers, except that the requests that create or change a session are admitted before generated decoding, so that a refusal reaches the caller with its classification and no provider code has run.

func RegisterPlugin

func RegisterPlugin(p *sdk.Plugin, opts PluginOpts) error

RegisterPlugin registers the log capability, contract v2, with the plugin system. It returns an error, with the class INVALID_REQUEST, for a registration that is beyond the bounds of PluginOpts.

Types

type CreateSessionOptions

type CreateSessionOptions struct {
	// SessionID is optional: a host-generated UUID that correlates acceptance and cleanup if
	// the reply is lost. It confers no authority and does not make creation idempotent. The output
	// of the session can reach the host on the stream before CreateSession returns, so a host that
	// wants it from the first frame sets the ID and registers it before it calls.
	SessionID string
	// Origins are the resources whose sources the session streams. The manager takes exactly one.
	Origins []SourceOrigin
	// Selection is which sources stream; the zero value selects none (a fixed selection). The
	// default selection is DefaultSelection().
	Selection SourceSelection
	// Limit is how many sources stream at once: zero is DefaultLimit, and a limit above the
	// resource's ceiling is clamped.
	Limit   int32
	Options LogSessionOptions
}

CreateSessionOptions describe a session to open.

func CreateSessionOptionsFromProto

func CreateSessionOptionsFromProto(p *logsv2pb.CreateSessionRequest) (CreateSessionOptions, error)

CreateSessionOptionsFromProto decodes a create request: it refuses a frame that is too large and a field the contract does not have, and validates what it decodes.

func (CreateSessionOptions) ToProto

ToProto validates the options and bounds the encoded frame before it allocates the resource bodies.

func (CreateSessionOptions) Validate

func (o CreateSessionOptions) Validate() error

Validate checks the options without a live connection: canonical metadata, values, bindings.

type DimensionFilter

type DimensionFilter struct {
	Key    string
	Values []string
	Not    bool
}

DimensionFilter keeps the sources whose label Key is one of Values (or, with Not, is none of them). Values are alternatives: OR. A source without the key fails a positive filter and passes a Not filter. A positive filter with no value keeps nothing; a Not filter with no value keeps everything.

type EndCause

type EndCause int

EndCause says why a session ended. A cause that a newer plugin sends and this SDK does not know is kept as it came, and the zero value is none.

const (
	// EndClosed means CloseSession was called.
	EndClosed EndCause = iota + 1
	// EndCompleted means a session that does not follow ran out of work.
	EndCompleted
	// EndPluginStopped means the plugin is stopping.
	EndPluginStopped
	// EndConnectionLost means the connection the session ran on was retired.
	EndConnectionLost
	// EndFailed means the session could not go on.
	EndFailed
)

type EndedError

type EndedError struct {
	Reason string
}

EndedError is what a source kind returns from Open, or from the Read of its stream, when the source has no stream to give and will have none: the previous container of one that never restarted, say. It is neither a failure nor a break that opens again. The source turns ended: its slot is free, it is not tried again, it counts for nothing in the breaker, and the view is told why, in the ended message of the source and in a system line "ended: <reason>" after the lines it delivered. A new Instance opens an ended source again. When the Read of a stream returns it, the stream has ended with that reason, and the last line that has no line break is still delivered, as it is at io.EOF.

Reason is public text, as the reason of a SourceEvent is: valid UTF-8 and at most MaxReasonBytes bytes. The SDK replaces bytes that are not UTF-8 and cuts a longer text where a character ends. An EndedError may be returned as a value or as a pointer, and may be wrapped.

func (EndedError) Error

func (e EndedError) Error() string

Error describes the end for a log; the view is told the reason as the SDK cleans it.

type Event

type Event struct {
	Type EventType
	// Source is set for EventSourceState.
	Source SourceInfo
	// Ref is set for EventSourceCaughtUp.
	Ref SourceRef
	// Summary is set for EventSummary.
	Summary Summary
	// Cause and Message are set for EventSessionEnded.
	Cause   EndCause
	Message string
}

Event is a report on a session.

type EventType

type EventType int

EventType tells what an Event reports.

const (
	// EventSourceState reports the state of a selected source.
	EventSourceState EventType = iota
	// EventSourceCaughtUp reports that a source's replay has been delivered.
	EventSourceCaughtUp
	// EventSummary reports the counts of the catalog; at most one every SummaryInterval.
	EventSummary
	// EventSessionReady reports that every source given a slot at the start has opened,
	// ended, failed or turned pending.
	EventSessionReady
	// EventSessionEnded reports the end of the session and its cause.
	EventSessionEnded
)

type Facet

type Facet struct {
	Key string
	// Values are at most MaxFacetValues, the most frequent first.
	Values []FacetValue
	// More is true when the dimension has more values than listed.
	More bool
}

Facet lists the values of one dimension among the sources that match every filter but the dimension's own.

type FacetValue

type FacetValue struct {
	Value string
	Count *int
}

FacetValue is one value of a dimension and how many sources have it. Count is nil when the plugin does not know it.

type FacetValuePage

type FacetValuePage struct {
	Values []FacetValue
	// Next is empty on the last page, and otherwise a cursor: opaque text that names the last value
	// of the page in the order of the values. It is good for the session that issued it for as long
	// as the session lasts, and it is as long as the value, at most about 700 bytes. A host keeps it
	// whole.
	Next string
}

FacetValuePage is a page of the values of a dimension in value order.

type FacetValuesRequest

type FacetValuesRequest struct {
	Key string
	// Text keeps the values that hold it, case-insensitively.
	Text string
	// Cursor is the Next of the previous page of a call with the same key and text; empty for the
	// first page. See FacetValuePage.Next.
	Cursor string
	// Limit is the page size: at most MaxPageSize; zero: DefaultPageSize.
	Limit int
}

FacetValuesRequest asks for a page of the values of one dimension.

type ListSourcesRequest

type ListSourcesRequest struct {
	// Text is the same matcher as SourceRule.Text.
	Text  string
	Where []DimensionFilter
	// States keeps the sources in one of these states; empty: every state but removed. A removed
	// source is listed only when StateRemoved is asked for.
	States []SourceState
	// Cursor is the Next of the previous page of a call with the same text, filters and states;
	// empty for the first page. See SourcePage.Next.
	Cursor string
	// Limit is the page size: at most MaxPageSize; zero: DefaultPageSize.
	Limit int
}

ListSourcesRequest asks for a page of the catalog.

type LogLevel

type LogLevel int

LogLevel is the severity of a line. A level that a newer plugin sends and this SDK does not know is kept as it came.

const (
	// LogLevelUnspecified means no severity was assigned.
	LogLevelUnspecified LogLevel = iota
	// LogLevelTrace is fine-grained tracing.
	LogLevelTrace
	// LogLevelDebug is diagnostic output.
	LogLevelDebug
	// LogLevelInfo is routine output.
	LogLevelInfo
	// LogLevelWarn is a potential problem.
	LogLevelWarn
	// LogLevelError is a failed operation.
	LogLevelError
	// LogLevelFatal is a failure that prevents going on.
	LogLevelFatal
)

type LogLine

type LogLine struct {
	N uint32
	// TimestampMicros is in epoch microseconds; zero means the line has none.
	TimestampMicros int64
	Content         []byte
	Level           LogLevel
	Origin          LogLineOrigin
	// Replay is true for a line the source already held when its stream opened, up to the
	// source's caught-up event. It is set only when the source's entry says replay.
	Replay bool
}

LogLine is one line of a source. N names the source and instance in the session's table; it starts at 1, and 0 is never sent.

type LogLineBatch

type LogLineBatch struct {
	Sources []SourceEntry
	Lines   []LogLine
}

LogLineBatch is what the plugin sends for the lines of a session: at most MaxBatchLines lines, MaxBatchBytes of content or BatchDelay of lines; an oversized line travels alone. Sources holds the entries of the n that the lines use for the first time. A host that drops a batch it cannot take, to bound its memory, must still keep the Sources of the batch: an n is described once, in the first batch that uses it, so the lines that use it later have no label without it.

type LogLineOrigin

type LogLineOrigin int32

LogLineOrigin tells where a line comes from. Its values are the numbers of the proto enum: a number that a newer plugin sends and this SDK does not know is kept as it came, so it equals none of the constants below, and a reader treats it as an origin it does not know, not as the nearest one.

const (
	// LogLineOriginUnspecified is the zero value: the plugin did not say where the line comes from.
	LogLineOriginUnspecified LogLineOrigin = iota
	// LogLineOriginCurrent is a line of the source's current instance.
	LogLineOriginCurrent
	// LogLineOriginPrevious is a line of the source's previous instance.
	LogLineOriginPrevious
	// LogLineOriginSystem is a line the SDK wrote: a lifecycle marker. A restarted, resumed or gap
	// line goes ahead of the first line its stream delivers and carries that line's timestamp, so that
	// it sits among the lines it is about. Every other system line carries the time it was written, and
	// so does one of these when that line has no timestamp or its stream ended before it delivered one.
	LogLineOriginSystem
)

type LogOption

type LogOption struct {
	Kind OptionKind
	// Label is what the UI shows: UTF-8, at most MaxDisplayLabelBytes bytes.
	Label string
}

LogOption declares an option a resource supports, with the label the UI shows.

type LogResource

type LogResource struct {
	// Resolve lists, and watches, the sources of one origin.
	Resolve SourceResolver
	// Dimensions are the label keys the UI may group and filter by, in order.
	Dimensions []SourceDimension
	// LimitCeiling is the highest limit a session of the resource accepts; zero: the
	// SDK ceiling (SDKLimitCeiling). It is at most MaxLimitCeiling.
	LimitCeiling int32
	// Options say which of since, previous and tail the resource supports: at most one of each kind.
	Options []LogOption
}

LogResource describes the logs of one resource kind. The key it is registered under in PluginOpts.Resources is the resource kind: UTF-8, not empty and at most MaxResourceKeyBytes bytes.

type LogSessionOptions

type LogSessionOptions struct {
	// Follow keeps the streams open for the lines that come, and watches the catalog.
	Follow bool
	// TailBudget is the number of last lines wanted for the whole view; each source's share is
	// max(MinTailLines, TailBudget / min(limit, selected sources)) at its first open. Zero means that
	// no limit is set, not that no lines are wanted: a source is opened with OpenRequest.TailLines
	// zero, and what that gives is for its kind to say (a kind that reads a log may send all of it).
	// There is no value yet for no backlog, what kubectl logs --tail=0 gives.
	TailBudget int64
	// SinceTime asks for the lines since a time, one absolute time for the whole session.
	SinceTime *time.Time
	// Previous asks for the previous instance of every source.
	Previous bool
	// ReplayMarkers asks the plugin to flag each source's replay and tell when it has been
	// delivered. Session.ReplayMarkers says whether the plugin accepted.
	ReplayMarkers bool
}

LogSessionOptions are the options of a session; they are fixed for its life. To change one, close the session and open another.

type LogSource

type LogSource struct {
	// ID is unique inside its origin and opaque. It is not empty, and at most MaxSourceIDBytes bytes.
	ID string
	// Kind selects the SourceKind that opens the source. At most MaxSourceKindBytes bytes.
	Kind string
	// Label is the full display name: tooltip, copy, export. At most MaxSourceLabelBytes bytes.
	Label string
	// Labels holds the values of the resource's dimensions: at most MaxSourceLabels entries, a key at
	// most MaxSourceLabelKeyBytes bytes long and a value at most MaxSourceLabelValueBytes.
	Labels map[string]string
	// Rank orders the sources that compete for slots, lexicographically and computed
	// from this source alone; lower streams first. A rank change never stops a stream. At most
	// MaxSourceRank values.
	Rank []int64
	// Default is false for a source outside the default rule.
	Default bool
	// Instance is opaque. Empty means the source cannot be opened yet. A new value is a new stream
	// of the same source (a restarted container): it opens from its start once the current stream has
	// finished, and at once, as far as the start rate allows, when the source waits to reconnect.
	// At most MaxSourceInstanceBytes bytes.
	Instance string
}

LogSource is one log-producing entity of an origin. A resolver describes it; the SDK never changes it. Treat a LogSource as a value: the SDK copies its maps and slices when it stores it.

Every text of a source is UTF-8 and bounded, because it travels in the messages of each session that lists, selects or reports the source, and a message that holds text that is not UTF-8 cannot be sent. A plugin whose names can hold other bytes, file paths for one, must escape them. The SDK drops a source that is beyond the bounds below, when the resolver lists it or reports it in an event, and logs that it did: the source is never stored, and an update that is out of bounds leaves the source as it was.

type Manager

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

Manager runs the log sessions of a plugin process.

func NewManager

func NewManager(cfg ManagerConfig) (*Manager, error)

NewManager checks the registration and the configuration and returns a manager. A registration that is beyond the bounds of PluginOpts is refused with the class INVALID_REQUEST.

func (*Manager) BindConnectionContextProvider

func (m *Manager) BindConnectionContextProvider(provider resourcev2.ConnectionContextProvider)

BindConnectionContextProvider binds sessions to the active source generation.

func (*Manager) Close

func (m *Manager) Close()

Close refuses every later session, ends the active ones and waits for them. It may be called more than once, and concurrently, as may Wait.

func (*Manager) CloseSession

func (m *Manager) CloseSession(_ *types.PluginContext, sessionID string) error

CloseSession ends a session, and waits up to the shutdown timeout for what it holds to be released. It forgets the session even when the wait runs out.

func (*Manager) CreateSession

func (m *Manager) CreateSession(pluginctx *types.PluginContext, opts CreateSessionOptions) (*Session, error)

CreateSession opens a session on one origin. It returns once the origin's catalog has been listed, with a snapshot of it. The session outlives the call: its lifetime is the lease on the connection it runs on, and it ends with CloseSession, the retirement of the connection or the manager.

The lease on the configured connection is held until the session's scheduler and every stream it opened have returned. Retirement cancels the session, but cannot destroy a client that is still in use.

func (*Manager) GetSession

func (m *Manager) GetSession(_ *types.PluginContext, sessionID string) (*Session, error)

GetSession returns a snapshot of a session, with the sources of its catalog that a snapshot lists.

func (*Manager) GetSupportedResources

func (m *Manager) GetSupportedResources(*types.PluginContext) ([]ResourceInfo, error)

GetSupportedResources lists every resource kind with its dimensions, ceiling and options.

func (*Manager) ListFacetValues

func (m *Manager) ListFacetValues(_ *types.PluginContext, sessionID string, req FacetValuesRequest) (*FacetValuePage, error)

ListFacetValues pages the values of one dimension of a session's catalog.

func (*Manager) ListSessions

func (m *Manager) ListSessions(_ *types.PluginContext) ([]*Session, error)

ListSessions returns snapshots of every session, by ID, without their sources: the list is not paged, so it would grow with the catalog of every session. GetSession and ListSources give the sources of one.

func (*Manager) ListSources

func (m *Manager) ListSources(_ *types.PluginContext, sessionID string, req ListSourcesRequest) (*SourcePage, error)

ListSources pages the catalog of a session.

func (*Manager) Stream

func (m *Manager) Stream(ctx context.Context, in <-chan StreamInput) (<-chan StreamOutput, error)

Stream returns the output every session shares. One stream carries all of it: a second one while one is open is refused with CONFLICT, because two readers of one output would split its frames between them, and the end of either would close the sessions of both. A context that ends, or an input that closes, ends the stream and closes every session; a StreamInput with the close command closes one, without waiting for it.

func (*Manager) UpdateSelection

func (m *Manager) UpdateSelection(
	_ *types.PluginContext, sessionID string, selection SourceSelection, limit int32,
) (SelectionResult, error)

UpdateSelection replaces the selection of a session, and its limit unless limit is zero. It returns the applied revision and never waits on output. The zero selection selects nothing: it deselects every source and stops every stream.

func (*Manager) Wait

func (m *Manager) Wait()

Wait stops the manager from taking sessions and blocks until the sessions it holds have finished. Unlike Close it cancels none of them. A start that comes after Wait began is refused with a CONNECTION_ERROR.

type ManagerConfig

type ManagerConfig struct {
	Logger    logging.Logger
	Settings  settings.Provider
	Resources map[string]LogResource
	Kinds     map[string]SourceKind
	// Clock is optional: nil is the real clock.
	Clock timeutil.Clock
	// Jitter is optional: it spreads a reconnect delay; nil is a random spread of 20% around it.
	Jitter func(time.Duration) time.Duration
}

ManagerConfig configures the Manager.

type OpenFunc

type OpenFunc func(ctx *types.PluginContext, req OpenRequest) (io.ReadCloser, error)

OpenFunc opens the stream of one source. The reader yields the source's lines; a line starts with an RFC 3339 timestamp and a space when the source can supply one, and the SDK reads it as the line's timestamp. The SDK closes the reader. See SourceKind for what the function owes its context, and for its errors.

type OpenRequest

type OpenRequest struct {
	Ref    SourceRef
	Origin SourceOrigin
	Source LogSource
	// Follow keeps the stream open for the lines that come.
	Follow bool
	// Previous asks for the previous instance of the source.
	Previous bool
	// TailLines is the number of last lines wanted. Zero means that no limit is set, not that no
	// lines are wanted: the stream opens as it does for a source that is asked for no tail, which for
	// a kind that reads a log is all of it. There is no value yet for no backlog.
	TailLines int64
	// SinceTime asks for the lines since a time.
	SinceTime *time.Time
	// Resume is set when the stream opens again where an earlier one stopped. The point belongs to
	// one instance of the source: a new instance has none until it has delivered a line of its own,
	// and opens from its start, with no Resume and no TailLines, until then. The SDK drops
	// the lines before Resume.After and the first Resume.SkipAt at After, so a kind that
	// cannot use it may ignore it; a kind that can asks its source for the lines since
	// After, After included, which makes the stream short. A stream that starts after After
	// with fewer lines at After than were delivered there is read as one that lost lines (the
	// source wrote more than the tail meanwhile), and the viewer is told that lines may be
	// missing; a source whose since is exclusive must be asked from just before After.
	Resume *Resume
}

OpenRequest asks a source kind to open one source's stream.

type OptionKind

type OptionKind int

OptionKind names an option of a resource's logs. A kind that a newer plugin sends and this SDK does not know is kept as it came, and the zero value is none.

const (
	// OptionSince lets the user ask for the lines since a time.
	OptionSince OptionKind = iota + 1
	// OptionPrevious lets the user ask for the previous instance of a source.
	OptionPrevious
	// OptionTail lets the user ask for the last lines of each source.
	OptionTail
)

type OriginInfo

type OriginInfo struct {
	ResourceKey string
	ResourceID  string
}

OriginInfo names the resource of an origin; it is what a session reports of it.

type Plugin

type Plugin struct {
	plugin.NetRPCUnsupportedPlugin

	Impl Provider
}

Plugin implements the hashicorp go-plugin interfaces for the log capability, contract v2.

func (*Plugin) BindConnectionContextProvider

func (p *Plugin) BindConnectionContextProvider(provider resourcev2.ConnectionContextProvider)

BindConnectionContextProvider forwards the source binding to providers that consume it.

func (*Plugin) GRPCClient

func (p *Plugin) GRPCClient(_ context.Context, _ *plugin.GRPCBroker, c *grpc.ClientConn) (any, error)

GRPCClient creates a remote log provider over the supplied connection.

func (*Plugin) GRPCServer

func (p *Plugin) GRPCServer(_ *plugin.GRPCBroker, s *grpc.Server) error

GRPCServer registers the log service.

type PluginClient

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

PluginClient is the client the host uses: a Provider over a connection to a log plugin.

func NewPluginClient

func NewPluginClient(conn grpc.ClientConnInterface) *PluginClient

NewPluginClient returns a client of the log service on a connection.

func (*PluginClient) CloseSession

func (c *PluginClient) CloseSession(pc *types.PluginContext, sessionID string) error

CloseSession ends a session.

func (*PluginClient) CreateSession

func (c *PluginClient) CreateSession(pc *types.PluginContext, opts CreateSessionOptions) (*Session, error)

CreateSession checks the route, bounds the frame, and validates what the plugin returns.

func (*PluginClient) GetSession

func (c *PluginClient) GetSession(pc *types.PluginContext, sessionID string) (*Session, error)

GetSession returns a snapshot of a session.

func (*PluginClient) GetSupportedResources

func (c *PluginClient) GetSupportedResources(pc *types.PluginContext) ([]ResourceInfo, error)

GetSupportedResources lists what the plugin can show logs of.

func (*PluginClient) ListFacetValues

func (c *PluginClient) ListFacetValues(
	pc *types.PluginContext, sessionID string, req FacetValuesRequest,
) (*FacetValuePage, error)

ListFacetValues pages the values of one dimension of the catalog of a session.

func (*PluginClient) ListSessions

func (c *PluginClient) ListSessions(pc *types.PluginContext) ([]*Session, error)

ListSessions returns snapshots of the sessions of the plugin, without their sources.

func (*PluginClient) ListSources

func (c *PluginClient) ListSources(pc *types.PluginContext, sessionID string, req ListSourcesRequest) (*SourcePage, error)

ListSources pages the catalog of a session.

func (*PluginClient) Stream

func (c *PluginClient) Stream(ctx context.Context, in <-chan StreamInput) (<-chan StreamOutput, error)

Stream carries the traffic of every session. Closing the input closes the sessions, as does the end of ctx. When the stream breaks while ctx is alive, the last message of the output is one whose Err says why; the output closes after it. The receiver of the output owns it.

func (*PluginClient) UpdateSelection

func (c *PluginClient) UpdateSelection(
	pc *types.PluginContext, sessionID string, selection SourceSelection, limit int32,
) (SelectionResult, error)

UpdateSelection replaces the selection of a session, and its limit unless it is zero.

type PluginOpts

type PluginOpts struct {
	// Resources maps a resource kind to its description.
	Resources map[string]LogResource
	// Kinds maps a source kind to the code that opens it.
	Kinds map[string]SourceKind
}

PluginOpts registers log resources and the kinds of source that serve them. A registration that cannot work is refused when the manager is made, and RegisterPlugin returns the error: a resource without a resolver, a kind without an Open function, a key that is empty or not UTF-8 or is longer than its bound, a ceiling beyond MaxLimitCeiling, and a dimension or an option that is empty, repeated or unknown, or whose label is not UTF-8 or is longer than MaxDisplayLabelBytes.

type PluginServer

type PluginServer struct {
	Impl Provider
	// contains filtered or unexported fields
}

PluginServer adapts a log provider to gRPC and keeps the classification of its errors.

func (*PluginServer) CloseSession

CloseSession ends a session.

func (*PluginServer) CreateSession

CreateSession admits the wire of the request, checks the trusted route, and returns a session only when its snapshot is valid and fits the wire; otherwise it closes the session.

func (*PluginServer) GetSession

GetSession returns a snapshot of a session.

func (*PluginServer) GetSupportedResources

func (s *PluginServer) GetSupportedResources(
	ctx context.Context, _ *emptypb.Empty,
) (*logsv2pb.GetSupportedResourcesResponse, error)

GetSupportedResources lists what the provider can show logs of.

func (*PluginServer) ListFacetValues

ListFacetValues pages the values of one dimension.

func (*PluginServer) ListSessions

ListSessions returns snapshots of the sessions of the provider.

func (*PluginServer) ListSources

ListSources pages the catalog of a session.

func (*PluginServer) Stream

func (s *PluginServer) Stream(stream logsv2pb.LogPlugin_StreamServer) (streamErr error)

Stream carries the traffic of every session until the RPC ends. The end of the host's side of the stream closes the sessions; so does the end of the RPC.

func (*PluginServer) UpdateSelection

UpdateSelection applies a selection and a limit to a session.

type Provider

type Provider interface {
	// GetSupportedResources lists every resource kind with its dimensions, limit ceiling and
	// options.
	GetSupportedResources(ctx *types.PluginContext) ([]ResourceInfo, error)
	// CreateSession opens a session. It returns once the catalog of the session's origin has
	// been listed, with a snapshot that carries the summary and the sources. The session
	// outlives the call. The output of the session can reach the host on the stream before the
	// call returns, so a host that wants it from the first frame sets CreateSessionOptions.SessionID
	// and registers it before it calls.
	CreateSession(ctx *types.PluginContext, opts CreateSessionOptions) (*Session, error)
	// UpdateSelection replaces the selection, and the limit unless it is zero. It returns the
	// applied revision and never waits on output. The zero selection selects nothing: it
	// deselects every source.
	UpdateSelection(
		ctx *types.PluginContext, sessionID string, selection SourceSelection, limit int32,
	) (SelectionResult, error)
	// ListSources pages the catalog of a session.
	ListSources(ctx *types.PluginContext, sessionID string, req ListSourcesRequest) (*SourcePage, error)
	// ListFacetValues pages the values of one dimension of a session's catalog.
	ListFacetValues(ctx *types.PluginContext, sessionID string, req FacetValuesRequest) (*FacetValuePage, error)
	// GetSession returns a snapshot of a session.
	GetSession(ctx *types.PluginContext, sessionID string) (*Session, error)
	// ListSessions returns snapshots of every session, without their sources: the list is not
	// paged. GetSession gives the sources of one session, and ListSources pages them.
	ListSessions(ctx *types.PluginContext) ([]*Session, error)
	// CloseSession ends a session and releases everything it holds.
	CloseSession(ctx *types.PluginContext, sessionID string) error
	// Stream carries the lines and events of every session until ctx ends or in closes; either
	// closes every session. Closing the input is the end of the stream; a StreamInput with the
	// close command closes one session without waiting for it. A provider has one stream: a
	// second Stream while one is open is refused with the class CONFLICT, and a host that wants
	// another opens it once the first has ended.
	Stream(ctx context.Context, in <-chan StreamInput) (<-chan StreamOutput, error)
}

Provider is what a log plugin serves and what the host calls: the manager in a plugin process, the client in the host.

type ReplayCountFunc

type ReplayCountFunc func(ctx *types.PluginContext, req OpenRequest) (int64, error)

ReplayCountFunc tells how many of the first lines of the stream Open will open for req are replay: lines the source already held. It may return ErrReplayUnknown.

type ResolveRequest

type ResolveRequest struct {
	// Origin is the resource whose sources are wanted, with its data and bindings.
	Origin SourceOrigin
	// Watch asks for Events: the session follows its sources.
	Watch bool
}

ResolveRequest asks a resolver for the sources of one origin.

type ResolveResult

type ResolveResult struct {
	Sources []LogSource
	Events  <-chan SourceEvent
}

ResolveResult is the current catalog of one origin and, when the request watched, the stream of its changes. Events must carry every change made after Sources was listed, and must stop, and be closed, when the call's context ends.

type ResourceInfo

type ResourceInfo struct {
	Resource     string
	Dimensions   []SourceDimension
	LimitCeiling int32
	Options      []LogOption
}

ResourceInfo describes the logs of one resource kind as GetSupportedResources reports them.

type Resume

type Resume struct {
	// After is the timestamp of the last line delivered; the stream must include the lines at it.
	After time.Time
	// SkipAt is how many lines at After were delivered already.
	SkipAt int
}

Resume is the point an interrupted source goes on from.

type SelectionResult

type SelectionResult struct {
	// Revision is the revision the update produced; a summary with this revision or a later
	// one reflects it.
	Revision uint64
	// Limit is the limit after clamping.
	Limit int32
}

SelectionResult is what UpdateSelection applied.

type Session

type Session struct {
	ID         string
	Origins    []OriginInfo
	Options    LogSessionOptions
	Status     SessionStatus
	EndCause   EndCause
	EndMessage string
	Summary    Summary
	// Sources is the whole catalog while the total is known and at most SnapshotWholeMax sources,
	// otherwise the selected sources: those that hold a slot, then the others in streaming order,
	// at most limit plus SnapshotSelectedExtra. CreateSession and GetSession carry it; ListSessions,
	// which is not paged, leaves it out, and ListSources pages the catalog of a session.
	Sources []SourceInfo
	// ReplayMarkers is true when the plugin accepted the request for replay markers.
	ReplayMarkers bool
	CreatedAt     time.Time
}

Session is a snapshot of a session.

type SessionStatus

type SessionStatus int

SessionStatus is the state of a session as a whole. A failed source never changes it. A status that a newer plugin sends and this SDK does not know is kept as it came, and the zero value is none.

const (
	// SessionInitializing lasts until every source given a slot at the start has opened,
	// ended, failed or turned pending.
	SessionInitializing SessionStatus = iota + 1
	// SessionActive is a session that is running.
	SessionActive
	// SessionEnded is a session that has ended; its EndCause says why.
	SessionEnded
)

type SourceDimension

type SourceDimension struct {
	// Key is a key of LogSource.Labels: UTF-8, not empty, not repeated within a resource and at most
	// MaxDimensionKeyBytes bytes.
	Key string
	// Label is what the UI shows: UTF-8, at most MaxDisplayLabelBytes bytes.
	Label string
}

SourceDimension names a label key the UI may group and filter by.

type SourceEntry

type SourceEntry struct {
	N      uint32
	Ref    SourceRef
	Label  string
	Labels map[string]string
	// Replay is true when the source's lines carry the replay flag and a caught-up event
	// follows its replay.
	Replay bool
}

SourceEntry names one source's instance. A batch carries an entry for each n it uses for the first time in the session. One n belongs to one (source, instance) and is never reused. An n starts at 1, and 0 is never sent.

type SourceEvent

type SourceEvent struct {
	Type   SourceEventType
	Source LogSource
	// Reason is optional public-safe text. When the event gives a source that was opened a new
	// Instance, the SDK writes it in the system line ("restarted: <reason>") that goes ahead of the
	// first line the new instance delivers, with that line's timestamp, or when its stream ends if it
	// delivers none; for a removal, in the line that tells the source left. It is UTF-8 of at most
	// MaxReasonBytes bytes: the SDK replaces bytes that are not UTF-8 and cuts a longer text where
	// a character ends.
	Reason string
}

SourceEvent is a change of the catalog.

type SourceEventType

type SourceEventType int

SourceEventType tells what a SourceEvent did to the catalog.

const (
	// SourceAdded puts a source in the catalog; for an ID the catalog knows it is an update.
	SourceAdded SourceEventType = iota
	// SourceUpdated replaces the source with the same ID.
	SourceUpdated
	// SourceRemoved takes the source out of the catalog.
	SourceRemoved
)

type SourceInfo

type SourceInfo struct {
	Ref            SourceRef
	Kind           string
	Label          string
	Labels         map[string]string
	Default        bool
	State          SourceState
	WaitingReason  WaitingReason
	FailureCode    string
	FailureMessage string
	// EndedMessage says why an ended source has no stream, when its kind said so with an
	// EndedError. It is empty in every other state and for a stream that finished on its own.
	EndedMessage string
	// Selected is true when the session's selection covers the source.
	Selected bool
	// Pinned is true when the selection includes the source.
	Pinned bool
}

SourceInfo is a source as a session reports it.

type SourceKind

type SourceKind struct {
	Open OpenFunc
	// ReplayCount is optional. The SDK calls it, for a session that asked for replay markers,
	// before the first opening of an instance; a resumed opening skips it.
	ReplayCount ReplayCountFunc
}

SourceKind opens the sources of one kind. The key it is registered under in PluginOpts.Kinds is the value of LogSource.Kind: UTF-8, not empty and at most MaxKindKeyBytes bytes.

The context that each function gets is the one of the reader of one source. It ends when the source is stopped (deselected, preempted by a pin or a lowered limit, removed) and when the session ends, and every function must honour it: one that does not return when its context ends holds the slot of its source, and with it the session and the lease on its connection, for ever. The session then never finishes: CloseSession gives up after ten seconds, and Manager.Close and Manager.Wait never return. The SDK stops a stream that is open by closing it, so the Close of the stream that Open returns must make a Read that is blocked return.

An error from Open, ReplayCount or Read is classified by the class it carries: an error made with resourcev2.NewError, or one that wraps it. NOT_FOUND, FORBIDDEN, PERMISSION_DENIED, UNAUTHORIZED, INVALID_REQUEST, INVALID_INPUT and UNSUPPORTED are permanent: the source fails at once and is not tried again. Every other class, and every error that carries none (a raw error of the provider or of the network), is transient: the source reconnects after a backoff, holding its slot, for as long as it stays selected; a session that does not follow gives it MaxAttemptsWithoutFollow attempts. A kind therefore returns a classified error for what trying again cannot cure: a raw 403 of the provider would be retried for ever. ErrSourceNotReady, EndedError and ErrReplayUnknown are the errors that are not failures.

type SourceOrigin

type SourceOrigin struct {
	ResourceKey  string
	ResourceID   string
	ResourceData *resourcev2.Value
	// Reference and Route are the caller's actual bindings; see v1's CreateSessionOptions.
	Reference *resourcev2.ResourceReference
	Route     *resourcev2.AccessRoute
}

SourceOrigin is what a session shows logs for: a resource. The index of an origin in CreateSessionOptions.Origins is its origin number in every SourceRef.

type SourcePage

type SourcePage struct {
	Sources []SourceInfo
	// Next is empty on the last page, and otherwise a cursor. A cursor is opaque text that names a
	// position in the order of the catalog, the label and the id of the last source of the page, and
	// not a snapshot: it does not expire when the catalog changes, and a source that joins before the
	// position is not seen by the walk that holds it. It is good for the session that issued it for as
	// long as the session lasts. It holds the label and the id, so it is as long as they are: at most
	// about 4.2 KB. A host keeps it whole.
	Next string
	// Revision is the revision of the catalog the page was made from; see Summary.Revision.
	Revision uint64
	// Total and Matching, and Facets, are optional and come with the first page.
	Total    *int
	Matching *int
	Facets   []Facet
}

SourcePage is a page of the catalog in label order, then id.

type SourceRef

type SourceRef struct {
	Origin uint32
	ID     string
}

SourceRef names a source: the index of its origin in the session's origins and the source's ID inside that origin.

type SourceResolver

type SourceResolver func(ctx *types.PluginContext, req ResolveRequest) (*ResolveResult, error)

SourceResolver lists, and watches, the sources of one origin. The context is the session's: it carries the connection and ends with the session.

type SourceRule

type SourceRule struct {
	DefaultsOnly bool
	Text         string
	Where        []DimensionFilter
}

SourceRule keeps the sources that satisfy every part that is set: DefaultsOnly keeps the sources inside the default rule, Text is a case-insensitive substring of the source's label, id or dimension value, and every filter of Where holds (AND across filters). A rule with no part set keeps every source.

type SourceSelection

type SourceSelection struct {
	Rules   []SourceRule
	Include []SourceRef
	Exclude []SourceRef
}

SourceSelection says which sources of a session are selected: not excluded and either included, which pins them, or kept by a rule (the rules are alternatives: OR). Exclude wins over everything. A selection with no rule is fixed: sources that join the catalog later are not selected. Include plus Exclude hold at most MaxSelectionRefs refs. The zero selection selects nothing, and so does an absent one on the wire: UpdateSelection with it deselects every source and stops every stream, and a session created with it streams nothing. DefaultSelection is the one for the sources inside the default rule.

func DefaultSelection

func DefaultSelection() SourceSelection

DefaultSelection is the selection of the sources inside the default rule. A host sends it for a session that is to show its default sources: a session that is given no selection selects none.

type SourceState

type SourceState int

SourceState is the state of one source, owned by the session scheduler. Its values are the numbers of the proto enum and start at 1: the zero value is no state. A state that a newer plugin sends and this SDK does not know is kept as it came, so it equals none of the constants below.

const (
	// StateAvailable is a source in the catalog that is not selected.
	StateAvailable SourceState = iota + 1
	// StateWaiting is a selected source without a slot; see WaitingReason.
	StateWaiting
	// StatePending is a selected source that cannot be opened yet.
	StatePending
	// StateConnecting is a source that holds a slot and is being opened.
	StateConnecting
	// StateStreaming is a source whose stream is open.
	StateStreaming
	// StateReconnecting is a source that holds a slot and whose stream opens again after a
	// transient failure: after a backoff, or at once when the plugin reports a new instance of it.
	StateReconnecting
	// StateEnded is a source whose stream finished on its own.
	StateEnded
	// StateFailed is a source that failed for good.
	StateFailed
	// StateRemoved is a source that left the catalog.
	StateRemoved
)

type StreamCommand

type StreamCommand int

StreamCommand is a command on the stream's input. A command that a newer host sends and this SDK does not know is kept as it came, and a plugin ignores it.

const (
	// StreamCommandClose has the effect of CloseSession.
	StreamCommandClose StreamCommand = iota + 1
)

type StreamInput

type StreamInput struct {
	SessionID string
	Command   StreamCommand
}

StreamInput is a message from the host to the plugin on the stream.

type StreamOutput

type StreamOutput struct {
	SessionID string
	Batch     *LogLineBatch
	Event     *Event
	Err       error
}

StreamOutput is a message from the plugin to the host on the stream: a batch of lines or an event of one session. A client's output also ends with a message whose Err is set when the stream broke; it never travels on the wire.

A message with no Batch, no Event and no Err carries a payload that this SDK does not know, which a newer plugin sent: a consumer ignores it. It is not an error, and it is not a batch with no lines. The SessionID can be that of a session that CreateSession has not returned for yet: the output of a session can reach the host before the reply to its creation does.

type Summary

type Summary struct {
	Total    *int
	Selected *int
	// Streaming counts the sources that hold a slot: connecting, streaming or reconnecting.
	Streaming int
	Waiting   *int
	Pending   *int
	Failed    *int
	// FailureClass is the class of the failure that holds promotions back, or of the latest
	// failed source.
	FailureClass string
	Limit        int32
	Ceiling      int32
	// Revision counts the changes of the selection, the limit and the catalog; it starts at 1, and
	// 0 is never sent. A change of the state of a source does not count.
	Revision uint64
	// CatalogStopped is true once the resolver of a session that follows has closed its events: the
	// SDK no longer sees the sources that come or go, so the list is not live. The sources that
	// stream keep streaming. It stays true for the rest of the session. False is a catalog that is
	// followed, and is what a plugin that does not say it means.
	CatalogStopped bool
}

Summary counts the sources of a session. Total, Selected, Waiting, Pending and Failed are nil when the plugin does not know the count, as one whose catalog is paged by its provider may not: a count that is absent is unknown, never zero. The manager of this SDK knows them all, and a host must not assume that every plugin does.

type WaitingReason

type WaitingReason int

WaitingReason says why a selected source has no slot. A reason that a newer plugin sends and this SDK does not know is kept as it came: it equals none of the constants below, not even WaitingNone, so a host shows the source as waiting for a reason it cannot name.

const (
	// WaitingNone is the reason of a source that is not waiting.
	WaitingNone WaitingReason = iota
	// WaitingLimit means every slot of the session's limit is taken.
	WaitingLimit
	// WaitingBreaker means repeated failures hold promotions back.
	WaitingBreaker
)

Directories

Path Synopsis
Package logtest helps the authors of a log plugin, contract v2, test it against the real manager of the SDK without a process, a network or a real clock.
Package logtest helps the authors of a log plugin, contract v2, test it against the real manager of the SDK without a process, a network or a real clock.

Jump to

Keyboard shortcuts

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