api

package
v0.0.0-...-1233b70 Latest Latest
Warning

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

Go to latest
Published: Jun 20, 2026 License: AGPL-3.0 Imports: 12 Imported by: 0

Documentation

Index

Constants

View Source
const (
	StatusDone  = "done"
	StatusError = "error"
)

Status constants for ExecResult.

View Source
const (
	ConfigAuthEdit    = "config edit"
	ConfigAuthSet     = "config set"
	ConfigAuthDelete  = "config delete"
	ConfigAuthCommit  = "config commit"
	ConfigAuthDiscard = "config discard"
)

Config session authorization command strings shared by REST and gRPC.

View Source
const DefaultSessionTimeout = 30 * time.Minute

DefaultSessionTimeout is the maximum age of an idle config session.

Variables

View Source
var (
	ErrUnauthorized = errors.New("unauthorized")
	ErrNotFound     = errors.New("command not found")
)

Errors returned by the engine.

View Source
var ErrSessionForbidden = errors.New("session access forbidden")

ErrSessionForbidden is returned when a user tries to access another user's session.

Functions

func BuildCommand

func BuildCommand(command string, params map[string]string) (string, error)

BuildCommand appends params as "key value" pairs to a command string. Returns an error if any key or value contains whitespace.

func CommandSchema

func CommandSchema(cmd CommandMeta) map[string]any

CommandSchema generates a JSON Schema for a single command's parameters.

func IsLoopbackAddr

func IsLoopbackAddr(addr string) bool

IsLoopbackAddr returns true if the host portion of addr resolves to a loopback address or is literally "localhost". Used by REST and gRPC transports to enforce loopback-only policies for plaintext listeners.

func OpenAPISchema

func OpenAPISchema(commands []CommandMeta) ([]byte, error)

OpenAPISchema generates an OpenAPI 3.1 specification from the command list. The schema is built once at startup and cached by the caller.

Types

type APIEngine

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

APIEngine is the shared backend for REST and gRPC transports. Transports call engine methods only -- never the dispatcher directly. MUST call NewAPIEngine to construct.

func NewAPIEngine

func NewAPIEngine(exec Executor, cmds CommandSource, auth AuthChecker, stream StreamSource) *APIEngine

NewAPIEngine creates an API engine. All dependencies are provided as functions so the engine package has no import dependency on the dispatcher, plugin server, or YANG packages. stream may be nil if streaming is not supported.

func (*APIEngine) DescribeCommand

func (e *APIEngine) DescribeCommand(req *DescribeCommandRequest) (CommandMeta, error)

DescribeCommand returns metadata for a single command. Returns ErrNotFound if the command does not exist.

func (*APIEngine) Execute

func (e *APIEngine) Execute(ctx context.Context, req *ExecuteRequest) (*ExecResult, error)

Execute runs a command and returns the result. Returns ErrUnauthorized if the auth checker denies the request.

func (*APIEngine) ListCommands

func (e *APIEngine) ListCommands(req *ListCommandsRequest) []CommandMeta

ListCommands returns all available commands with metadata. If prefix is non-empty, only commands whose name starts with prefix are returned. This is a byte-level prefix match, not word-boundary: "peer" matches "peering" too.

func (*APIEngine) Stream

func (e *APIEngine) Stream(ctx context.Context, req *StreamRequest) (<-chan string, func(), error)

Stream starts a streaming command and returns a channel that delivers events. The caller MUST call the returned cancel function when done. Returns ErrUnauthorized if the auth checker denies the request. Returns an error if streaming is not configured.

type AuthChecker

type AuthChecker func(username, command string) bool

AuthChecker checks whether a user is allowed to run a command. Returns true if authorized.

type CallerIdentity

type CallerIdentity struct {
	Username   string
	RemoteAddr string
	Surface    string
	// ReadOnly means the transport admitted the caller with read-only access only.
	ReadOnly bool
}

CallerIdentity carries trusted caller metadata for an API request. Populated by the transport after authentication; not an auth credential.

type CommandMeta

type CommandMeta struct {
	Name        string      // Dispatch path, e.g. "show bgp rib status"
	Description string      // From YANG or registration
	ReadOnly    bool        // True if read-only command
	Params      []ParamMeta // Input parameters from YANG RPC (nil = no typed params)
}

CommandMeta describes a registered command for API consumers.

type CommandSource

type CommandSource func() []CommandMeta

CommandSource returns all available commands with metadata.

type ConfigCommitHook

type ConfigCommitHook func() error

ConfigCommitHook applies a saved config to the running daemon.

type ConfigCommitRequest

type ConfigCommitRequest struct {
	Username  string
	SessionID string
}

ConfigCommitRequest is the domain request for committing a session.

type ConfigDeleteRequest

type ConfigDeleteRequest struct {
	Username  string
	SessionID string
	Path      string
}

ConfigDeleteRequest is the domain request for deleting a config path.

type ConfigDiffRequest

type ConfigDiffRequest struct {
	Username  string
	SessionID string
}

ConfigDiffRequest is the domain request for showing session diff.

type ConfigDiscardRequest

type ConfigDiscardRequest struct {
	Username  string
	SessionID string
}

ConfigDiscardRequest is the domain request for discarding a session.

type ConfigEditor

type ConfigEditor interface {
	SetValue(path []string, key, value string) error
	DeleteByPath(fullPath []string) error
	Diff() string
	Save() error
	StageCandidate(stamp time.Time) (content string, version string, err error)
	MarkCommittedContent(content string)
	RestoreOriginalContent(content string) error
	Discard() error
	OriginalContent() string
	WorkingContent() string
}

ConfigEditor abstracts the config editing operations the engine needs. Implemented by the composition root using the real Editor.

type ConfigEditorFactory

type ConfigEditorFactory func() (ConfigEditor, error)

ConfigEditorFactory creates a new ConfigEditor for a session.

type ConfigSession

type ConfigSession struct {
	ID           string
	Editor       ConfigEditor
	Username     string
	CreatedAt    time.Time
	LastActivity time.Time
	// contains filtered or unexported fields
}

ConfigSession tracks a single config editing session.

type ConfigSessionManager

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

ConfigSessionManager manages config editing sessions for API use. Each session wraps a ConfigEditor with a unique ID and tracks ownership. Thread-safe for concurrent access. Idle sessions are automatically reaped by a background goroutine started via RunCleanup. Sessions idle beyond the timeout are discarded.

func NewConfigSessionManager

func NewConfigSessionManager(factory ConfigEditorFactory) *ConfigSessionManager

NewConfigSessionManager creates a session manager with the default timeout.

func (*ConfigSessionManager) CleanExpired

func (m *ConfigSessionManager) CleanExpired() int

CleanExpired discards sessions idle beyond the configured timeout. Returns the number of sessions cleaned. Safe for concurrent use.

func (*ConfigSessionManager) Commit

Commit applies the pending changes.

func (*ConfigSessionManager) Delete

Delete removes a config path from the session's candidate.

func (*ConfigSessionManager) DeleteSegments

func (m *ConfigSessionManager) DeleteSegments(username, sessionID string, path []string) error

DeleteSegments removes a config path using pre-split path segments.

func (*ConfigSessionManager) Diff

Diff returns the pending changes for a session.

func (*ConfigSessionManager) Discard

Discard throws away the session's candidate changes.

func (*ConfigSessionManager) Enter

func (m *ConfigSessionManager) Enter(username string) (string, error)

Enter creates a new config editing session.

func (*ConfigSessionManager) RunCleanup

func (m *ConfigSessionManager) RunCleanup(ctx context.Context)

RunCleanup starts a background goroutine that periodically reaps idle sessions. Blocks until ctx is canceled. Call as `go m.RunCleanup(ctx)`.

func (*ConfigSessionManager) Set

Set modifies a config path in the session's candidate.

func (*ConfigSessionManager) SetCommitHook

func (m *ConfigSessionManager) SetCommitHook(hook ConfigCommitHook)

SetCommitHook sets the hook called after a session save succeeds and before the session is removed. A hook error rolls the saved file back to its previous content and is returned to the client.

func (*ConfigSessionManager) SetSegments

func (m *ConfigSessionManager) SetSegments(username, sessionID string, path []string, value string) error

SetSegments modifies a config path using pre-split path segments. Use instead of Set when the path contains dots that are not separators (e.g., IP addresses in YANG list keys from gNMI).

func (*ConfigSessionManager) SetValidationHook

func (m *ConfigSessionManager) SetValidationHook(hook ConfigValidationHook)

SetValidationHook sets the hook called before a session save. Hook errors abort the commit before the config file is modified.

type ConfigSetRequest

type ConfigSetRequest struct {
	Username  string
	SessionID string
	Path      string
	Value     string
}

ConfigSetRequest is the domain request for setting a config value.

type ConfigValidationHook

type ConfigValidationHook func(previous, candidate string) error

ConfigValidationHook validates a candidate config before it is saved.

type DescribeCommandRequest

type DescribeCommandRequest struct {
	Caller CallerIdentity
	Path   string
}

DescribeCommandRequest is the domain request for describing a command.

type ExecResult

type ExecResult struct {
	Status string `json:"status"`          // "done", "error", or "partial"
	Data   any    `json:"data,omitempty"`  // Payload
	Error  string `json:"error,omitempty"` // Error message (when status is "error")
}

ExecResult is the standard API response envelope.

type ExecuteRequest

type ExecuteRequest struct {
	Caller  CallerIdentity
	Command string
}

ExecuteRequest is the domain request for command execution.

type Executor

type Executor func(ctx context.Context, caller CallerIdentity, command string) (string, error)

Executor runs a command and returns its raw output. The transport context plus caller metadata are passed through so the implementation can build a request-scoped CommandContext.

type ListCommandsRequest

type ListCommandsRequest struct {
	Caller CallerIdentity
	Prefix string
}

ListCommandsRequest is the domain request for listing commands.

type ParamMeta

type ParamMeta struct {
	Name        string // Parameter name (kebab-case from YANG)
	Type        string // YANG type: "string", "uint32", "boolean", etc.
	Description string // From YANG description
	Required    bool   // Mandatory in YANG
}

ParamMeta describes a single input parameter from YANG RPC metadata.

type StreamRequest

type StreamRequest struct {
	Caller  CallerIdentity
	Command string
}

StreamRequest is the domain request for streaming command execution.

type StreamSource

type StreamSource func(ctx context.Context, caller CallerIdentity, command string) (<-chan string, func(), error)

StreamSource creates a streaming event channel for a command. Returns the event channel, a cancel function, and any error. The channel is closed when the stream ends or cancel is called. Caller MUST call the cancel function when done to release resources.

Directories

Path Synopsis
Design: docs/architecture/api/architecture.md -- gRPC API transport
Design: docs/architecture/api/architecture.md -- gRPC API transport
Design: docs/architecture/api/architecture.md -- REST API transport
Design: docs/architecture/api/architecture.md -- REST API transport

Jump to

Keyboard shortcuts

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