cell

package
v1.15.4 Latest Latest
Warning

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

Go to latest
Published: Apr 11, 2024 License: Apache-2.0 Imports: 37 Imported by: 1

Documentation

Index

Constants

This section is empty.

Variables

View Source
var NoStatus = &StatusNode{Message: "No status reported", LastLevel: StatusUnknown}

Functions

This section is empty.

Types

type AllSettings

type AllSettings map[string]any

type Cell

type Cell interface {
	// Info provides a structural summary of the cell for printing purposes.
	Info(container) Info

	// Apply the cell to the dependency graph container.
	Apply(container) error
}

Cell is the modular building block of the hive.

A cell can be constructed with:

  • Module(): Create a named set of cells.
  • Provide(): Provide object constructors.
  • Invoke(): Invoke a function to instantiate objects.
  • Decorate(): Decorate a set of cells to augment an object.
  • Config(): Cell providing a configuration struct.

func Config

func Config[Cfg Flagger](def Cfg) Cell

Config constructs a new config cell.

The configuration struct `T` needs to implement the Flags method that registers the flags. The structure is populated and provided via dependency injection by Hive.Run(). The underlying mechanism for populating the struct is viper's Unmarshal().

func Decorate

func Decorate(dtor any, cells ...Cell) Cell

Decorate takes a decorator function and a set of cells and returns a decorator cell.

A decorator function is a function that takes as arguments objects in the hive and returns one or more augmented objects. The cells wrapped with a decorator will be provided the returned augmented objects.

Example:

cell.Decorate(
	func(e Example) Example {
		return e.WithMoreMagic()
	},
	cell.Invoke(func(e Example) {
		// e now has more magic
	},
)

func Group

func Group(cells ...Cell) Cell

Group a set of cells. Unlike Module(), Group() does not create a new scope.

func Invoke

func Invoke(funcs ...any) Cell

Invoke constructs a cell for invoke functions. The invoke functions are executed when the hive is started to instantiate all objects via the constructors.

func Metric

func Metric[S any](ctor func() S) Cell

Metric constructs a new metric cell.

This cell type provides `S` to the hive as returned by `ctor`, it also makes each individual field value available via the `hive-metrics` value group. Infrastructure components such as a registry, inspection tool, or documentation generator can collect all metrics in the hive via this value group.

The `ctor` constructor must return a struct or pointer to a struct of type `S`. The returned struct must only contain public fields. All field types should implement the `github.com/cilium/cilium/pkg/metrics/metric.WithMetadata` and `github.com/prometheus/client_golang/prometheus.Collector` interfaces.

func Module

func Module(id, title string, cells ...Cell) Cell

Module creates a scoped set of cells with a given identifier.

The id and title will be included in the object dump (hive.PrintObjects). The id must be lower-case, at most 30 characters and only contain [a-z0-9-_]. Title can contain [a-zA-Z0-9_- ] and must be shorter than 80 characters.

Private constructors with a module (ProvidePrivate) are only accessible within this module and its sub-modules.

func Provide

func Provide(ctors ...any) Cell

Provide constructs a new cell with the given constructors. Constructor is any function that takes zero or more parameters and returns one or more values and optionally an error. For example, the following forms are accepted:

func() A
func(A, B, C) (D, error).

If the constructor depends on a type that is not provided by any constructor the hive will fail to run with an error pointing at the missing type.

A constructor can also take as parameter a structure of parameters annotated with `cell.In`, or return a struct annotated with `cell.Out`:

type params struct {
	cell.In
	Flower *Flower
	Sun *Sun
}

type out struct {
	cell.Out
	Honey *Honey
	Nectar *Nectar
}

func newBee(params) (out, error)

func ProvidePrivate

func ProvidePrivate(ctors ...any) Cell

ProvidePrivate is like Provide, but the constructed objects are only available within the module it is defined and nested modules.

type DefaultLifecycle added in v1.14.7

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

DefaultLifecycle lifecycle implements a simple lifecycle management that conforms to Lifecycle. It is exported for use in applications that have nested lifecycles (e.g. operator).

func (*DefaultLifecycle) Append added in v1.14.7

func (lc *DefaultLifecycle) Append(hook HookInterface)

func (*DefaultLifecycle) PrintHooks added in v1.14.7

func (lc *DefaultLifecycle) PrintHooks()

func (*DefaultLifecycle) Start added in v1.14.7

func (lc *DefaultLifecycle) Start(ctx context.Context) error

func (*DefaultLifecycle) Stop added in v1.14.7

func (lc *DefaultLifecycle) Stop(ctx context.Context) error

type Flagger

type Flagger interface {
	// Flags registers the configuration options as command-line flags.
	//
	// By convention a flag name matches the field name
	// if they're the same under case-insensitive comparison when dashes are
	// removed. E.g. "my-config-flag" matches field "MyConfigFlag". The
	// correspondence to the flag can be also specified with the mapstructure
	// tag: MyConfigFlag `mapstructure:"my-config-flag"`.
	//
	// Exported fields that are not found from the viper settings will cause
	// hive.Run() to fail. Unexported fields are ignored.
	//
	// See https://pkg.go.dev/github.com/mitchellh/mapstructure for more info.
	Flags(*pflag.FlagSet)
}

Flagger is implemented by configuration structs to provide configuration for a cell.

type FullModuleID added in v1.15.0

type FullModuleID []string

FullModuleID is the fully qualified module identifier, e.g. the concat of nested module ids, e.g. "agent.controlplane.endpoint-manager". Provided in the module's scope.

func (FullModuleID) String added in v1.15.0

func (f FullModuleID) String() string

type Health

type Health interface {
	// All returns a copy of all module statuses.
	// This includes unknown status for modules that have not reported a status yet.
	All() []Status

	// Get returns a copy of a modules status, by module ID.
	// This includes unknown status for modules that have not reported a status yet.
	Get(FullModuleID) (Status, error)

	// Stats returns a map of the number of module statuses reported by level.
	Stats() map[Level]uint64

	// Stop stops the health provider from processing updates.
	Stop(context.Context) error

	// Subscribe to health status updates.
	Subscribe(context.Context, func(Update), func(error))
	// contains filtered or unexported methods
}

Health provides exported functions for accessing health status data. As well, provides unexported functions for use during module apply.

func NewHealthProvider

func NewHealthProvider() Health

NewHealthProvider starts and returns a health status which processes health status updates.

type HealthReporter

type HealthReporter interface {
	// OK declares that a Module has achieved a desired state and has not entered
	// any unexpected or incorrect states.
	// Modules should only declare themselves as 'OK' once they have stabilized,
	// rather than during their initial state. This should be left to be reported
	// as the default "unknown" to denote that the module has not reached a "ready"
	// health state.
	OK(status string)

	// Stopped reports that a module has completed, and will no longer report any
	// health status.
	// Implementations should differentiate that a stopped module may also be OK or Degraded.
	// Stopping a reporting should only affect future updates.
	Stopped(reason string)

	// Degraded declares that a module has entered a degraded state.
	// This means that it may have failed to provide it's intended services, or
	// to perform it's desired task.
	Degraded(reason string, err error)
}

HealthReporter provides a method of declaring a Modules health status.

func GetHealthReporter added in v1.15.0

func GetHealthReporter(parent Scope, name string) HealthReporter

GetHealthReporter creates a new reporter under the given parent scope.

type Hook added in v1.14.7

type Hook struct {
	OnStart func(HookContext) error
	OnStop  func(HookContext) error
}

Hook is a pair of start and stop callbacks. Both are optional. They're paired up to make sure that on failed start all corresponding stop hooks are executed.

func (Hook) Start added in v1.14.7

func (h Hook) Start(ctx HookContext) error

func (Hook) Stop added in v1.14.7

func (h Hook) Stop(ctx HookContext) error

type HookContext added in v1.14.7

type HookContext context.Context

HookContext is a context passed to a lifecycle hook that is cancelled in case of timeout. Hooks that perform long blocking operations directly in the start or stop function (e.g. connecting to external services to initialize) must abort any such operation if this context is cancelled.

type HookInterface added in v1.14.7

type HookInterface interface {
	Start(HookContext) error
	Stop(HookContext) error
}

HookInterface mirrors the Hook interface from pkg/hive/lifecycle.go. Because pkg/hive/cell depends on HookInterface then we need to have a copy of it here. Hive provides a "cell" version of this HookInterface interface that does not depend on pkg/hive/lifecycle.go thus allowing the cell package to define lifecycle hooks.

type In

type In = dig.In

In when embedded into a struct used as constructor parameter makes the exported values of that struct become dependency injected values. In other words, it allows moving a long list of constructor parameters into a struct.

Struct fields can be annotated with `optional:"true"` to make the dependency optional. If the type is not found in the dependency graph, the value is set to the zero value.

See https://pkg.go.dev/go.uber.org/dig#In for more information.

type Info

type Info interface {
	Print(indent int, w *InfoPrinter)
}

Info provides a simple way of printing cells hierarchically in textual form.

type InfoLeaf

type InfoLeaf string

func (InfoLeaf) Print

func (l InfoLeaf) Print(indent int, w *InfoPrinter)

type InfoNode

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

func NewInfoNode

func NewInfoNode(header string) *InfoNode

func (*InfoNode) Add

func (n *InfoNode) Add(child Info)

func (*InfoNode) AddLeaf

func (n *InfoNode) AddLeaf(format string, args ...any)

func (*InfoNode) Print

func (n *InfoNode) Print(indent int, w *InfoPrinter)

type InfoPrinter

type InfoPrinter struct {
	io.Writer
	// contains filtered or unexported fields
}

func NewInfoPrinter

func NewInfoPrinter() *InfoPrinter

type InfoStruct

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

func (*InfoStruct) Print

func (n *InfoStruct) Print(indent int, w *InfoPrinter)

type InvokerList

type InvokerList interface {
	AppendInvoke(func() error)
}

type Level

type Level string

Level denotes what kind an update is.

const (
	// StatusUnknown is the default status of a Module, prior to it reporting
	// any status.
	// All created
	StatusUnknown Level = "Unknown"

	// StatusStopped is the status of a Module that has completed, further updates
	// will not be processed.
	StatusStopped Level = "Stopped"

	// StatusDegraded is the status of a Module that has entered a degraded state.
	StatusDegraded Level = "Degraded"

	// StatusOK is the status of a Module that has achieved a desired state.
	StatusOK Level = "OK"
)

type Lifecycle added in v1.14.7

type Lifecycle interface {
	Append(HookInterface)

	Start(context.Context) error
	Stop(context.Context) error
	PrintHooks()
}

Lifecycle enables cells to register start and stop hooks, either from a constructor or an invoke function.

type ModuleID added in v1.15.0

type ModuleID string

ModuleID is the module identifier. Provided in the module's scope.

type Out

type Out = dig.Out

Out when embedded into a struct that is returned by a constructor will make the values in the struct become objects in the dependency graph instead of the struct itself.

See https://pkg.go.dev/go.uber.org/dig#Out for more information.

type Scope added in v1.15.0

type Scope interface {
	// Name returns the name of the scope.
	Name() string

	// Close removes the scope from the tree, and stops all reporters under this scope.
	// Using a reporter that is under this scope after Close has been called will result
	// in a noop update and warning log.
	// Thus it is preferable for all reporters to be Stopped first, before calling Close.
	Close()
	// contains filtered or unexported methods
}

Scope provides a node in the structured health reporter tree that is serves only as a parent for other nodes (scopes or reporters), and is used to group related reporters together.

func GetSubScope added in v1.15.0

func GetSubScope(parent Scope, name string) Scope

GetSubScope creates a new reporter scope under the given parent scope. This creates a new node in the structured health reporter tree, and any calls to GetSubScope or GetHealthReporter from the returned scope will return a child node of this reporter tree.

GetSubScope can be chained together to create various levels of sub reporters.

Example:

1. Init root scope (note: this is provided to modules automatically). root := rootScope(hr)

root

2. Create endpoint-manager subscope, and reporter under that scope (with ok!)

endpointManagerScope := GetSubScope(root, "endpoint-manager") GetHealthReporter(endpointManagerScope, "endpoint-000").OK("it works!")

 root(OK)
	└── scope(endpoint-manager, OK)
		└── reporter(endpoint-000, OK)

3. Create another reporter under that scope with degraded GetHealthReporter(endpointManagerScope, "endpoint-000").Degraded("oh no!")

 root(Degraded)
	└── scope(endpoint-manager, Degraded)
		└── reporter(endpoint-000, OK)
		└── reporter(endpoint-000, Degraded)

4. Close the endpoint-manager scope s.Close()

root(OK) 	// status has been reported, but we no longer have any degraded status
			// default to ok status.

func TestScope added in v1.15.0

func TestScope() Scope

TestScope exposes creating a root scope for testing purposes only.

func TestScopeFromProvider added in v1.15.0

func TestScopeFromProvider(moduleID FullModuleID, hp Health) Scope

TestScope exposes creating a root scope from a health provider for testing purposes only.

type Status

type Status struct {
	// Update is the last reported update for a module.
	Update

	FullModuleID FullModuleID

	// Stopped is true when a module has been completed, thus it contains
	// its last reporter status. New updates will not be processed.
	Stopped bool
	// Final is the stopped message, if the module has been stopped.
	Final Update
	// LastOK is the time of the last OK status update.
	LastOK time.Time
	// LastUpdated is the time of the last status update.
	LastUpdated time.Time
}

Status is a modules last health state, including the last update.

func (*Status) JSON added in v1.15.0

func (s *Status) JSON() ([]byte, error)

func (*Status) Level added in v1.15.0

func (s *Status) Level() Level

func (*Status) String

func (s *Status) String() string

String returns a string representation of a Status, implements fmt.Stringer.

type StatusNode added in v1.15.0

type StatusNode struct {
	ID              string        `json:"id"`
	LastLevel       Level         `json:"level,omitempty"`
	Name            string        `json:"name"`
	Message         string        `json:"message,omitempty"`
	UpdateTimestamp time.Time     `json:"timestamp"`
	Count           int           `json:"count"`
	SubStatuses     []*StatusNode `json:"sub_statuses,omitempty"`
	Error           string        `json:"error,omitempty"`
}

StatusNode is a model struct for a status tree realization result. It is created upon status tree realization, for now it is only used for for generating a plaintext representation of the status tree. In the future we will want to use this to generate a structured JSON representation of the status tree.

func (*StatusNode) JSON added in v1.15.0

func (s *StatusNode) JSON() ([]byte, error)

func (*StatusNode) Level added in v1.15.0

func (s *StatusNode) Level() Level

func (*StatusNode) String added in v1.15.0

func (s *StatusNode) String() string

func (*StatusNode) StringIndent added in v1.15.0

func (s *StatusNode) StringIndent(ident int) string

func (*StatusNode) Timestamp added in v1.15.0

func (s *StatusNode) Timestamp() time.Time

type StatusResult added in v1.15.0

type StatusResult struct {
	Update
	FullModuleID FullModuleID
	Stopped      bool
}

type Update

type Update interface {
	// Level returns the level of the update.
	Level() Level

	// String returns a string representation of the update.
	String() string

	// JSON returns a JSON representation of the update, this is used by the agent
	// health CLI to unmarshal health status into cell.StatusNode.
	JSON() ([]byte, error)

	Timestamp() time.Time
}

Update represents an instantaneous health status update.

Jump to

Keyboard shortcuts

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