hive

package module
v1.0.4 Latest Latest
Warning

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

Go to latest
Published: Jun 9, 2026 License: Apache-2.0 Imports: 18 Imported by: 15

README

🐝 Hive GoDoc

Hive is a dependency injection framework for Go. To build an application in Hive you tell it your object constructors and then ask it to invoke functions that make use of those constructors. Hive figures out what constructors to call and in what order.

Hive is built on top of uber/dig and is similar to uber/fx. The main difference to uber/fx is opinionated way to provide configuration and command-line inspection tooling (go run ./example hive). Hive was built for the needs of the Cilium project to improve modularity of the Cilium codebase.

To get started, see the documentation and explore the example.

Documentation

Overview

Package hive provides the infrastructure for building Cilium applications from modular components (cells).

Hive is implemented using the uber/dig library, which provides the dependency injection for objects in the hive. It is similar to uber/fx, but adds an opinionated approach to configuration.

The configuration for cells is extracted from Viper. By default the field names are assumed to correspond to flag names, e.g. field 'MyOption' corresponds to '--my-option' flag.

The hive constructor, New(), takes the viper instance and the pflag FlagSet as parameters and registers the flags from all cells and binds them to viper variables. Once the FlagSet and viper configuration has been parsed one can call Populate() to pull the values from viper and construct the application. The hive can then be Run().

Example

For a runnable example see pkg/hive/example.

Try running:

example$ go run .
(ctrl-c stops)

example$ go run . --dot-graph | dot -Tx11

Try also commenting out cell.Provide lines and seeing what the dependency errors look like.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AddConfigOverride

func AddConfigOverride[Cfg cell.Flagger](h *Hive, override func(*Cfg))

AddConfigOverride appends a config override function to modify a configuration after it has been parsed.

This method is only meant to be used in tests.

func RunRepl

func RunRepl(h *Hive, in *os.File, out *os.File, prompt string)

Types

type ErrPopulate

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

func (ErrPopulate) Error

func (e ErrPopulate) Error() string

Error implements error.

func (ErrPopulate) Pretty

func (e ErrPopulate) Pretty() string

type Hive

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

Hive is a framework building modular applications.

It implements dependency injection using the dig library.

See pkg/hive/example for a runnable example application.

func New

func New(cells ...cell.Cell) *Hive

New returns a new hive that can be run, or inspected. The command-line flags from the cells are registered as part of this.

The object graph is not constructed until methods of the hive are invoked.

Applications should call RegisterFlags() to register the hive's command-line flags. Likewise if configuration settings come from configuration files, then the Viper() method can be used to populate the hive's viper instance.

func NewWithOptions

func NewWithOptions(opts Options, cells ...cell.Cell) *Hive

func (*Hive) AppendInvoke

func (h *Hive) AppendInvoke(invoke func(*slog.Logger, time.Duration) error)

func (*Hive) Command

func (h *Hive) Command() *cobra.Command

Command constructs the cobra command for hive. The hive command can be used to inspect the dependency graph.

func (*Hive) Populate

func (h *Hive) Populate(log *slog.Logger) error

Populate instantiates the hive. Use for testing that the hive can be instantiated.

func (*Hive) PrintDotGraph

func (h *Hive) PrintDotGraph() error

func (*Hive) PrintObjects

func (h *Hive) PrintObjects(w io.Writer, log *slog.Logger) error

func (*Hive) RegisterFlags

func (h *Hive) RegisterFlags(flags *pflag.FlagSet)

RegisterFlags adds all flags in the hive to the given flag set. Fatals if a flag already exists in the given flag set. Use with e.g. cobra.Command:

cmd := &cobra.Command{...}
h.RegisterFlags(cmd.Flags())

func (*Hive) Run

func (h *Hive) Run(log *slog.Logger, opts ...RunOptionFunc) error

Run populates the cell configurations and runs the hive cells. Interrupt signal or call to Shutdowner.Shutdown() will cause the hive to stop.

func (*Hive) ScriptCommands

func (h *Hive) ScriptCommands(log *slog.Logger) (map[string]script.Cmd, error)

func (*Hive) Shutdown

func (h *Hive) Shutdown(opts ...ShutdownOption)

Shutdown implements the Shutdowner interface and is provided for the cells to use for triggering a early shutdown.

func (*Hive) Start

func (h *Hive) Start(log *slog.Logger, ctx context.Context) error

Start starts the hive. The context allows cancelling the start. If context is cancelled and the start hooks do not respect the cancellation then after 5 more seconds the process will be terminated forcefully.

func (*Hive) Stop

func (h *Hive) Stop(log *slog.Logger, ctx context.Context) error

Stop stops the hive. The context allows cancelling the stop. If context is cancelled and the stop hooks do not respect the cancellation then after 5 more seconds the process will be terminated forcefully.

func (*Hive) Viper

func (h *Hive) Viper() *viper.Viper

Viper returns the hive's viper instance.

type Metrics added in v1.0.1

type Metrics interface {
	StartDuration(time.Duration)
	StopDuration(time.Duration)
	PopulateDuration(time.Duration)
}

type NopMetrics added in v1.0.1

type NopMetrics struct{}

func (NopMetrics) PopulateDuration added in v1.0.1

func (NopMetrics) PopulateDuration(duration time.Duration)

PopulateDuration implements Metrics.

func (NopMetrics) StartDuration added in v1.0.1

func (NopMetrics) StartDuration(duration time.Duration)

StartDuration implements Metrics.

func (NopMetrics) StopDuration added in v1.0.1

func (NopMetrics) StopDuration(duration time.Duration)

StopDuration implements Metrics.

type Options

type Options struct {
	// EnvPrefix is the prefix to use for environment variables, e.g.
	// with prefix "CILIUM" the flag "foo" can be set with environment
	// variable "CILIUM_FOO".
	EnvPrefix string

	// ModuleDecorator is an optional set of decorator functions to use for each
	// module. This can be used to provide module-scoped overrides to objects.
	// For example:
	//
	// 	opts.ModuleDecorators = cell.ModuleDecorators{
	// 		func(foo Foo, id cell.ModuleID) Foo {
	// 			return foo.With("moduleID", id)
	//		},
	//	}
	//
	// The above would give each cell within a module an augmented version of 'Foo'.
	// The object that is being decorated (the return value) must already exist in
	// the object graph.
	ModuleDecorators cell.ModuleDecorators

	// ModulePrivateProvider is an optional set of private provide functions to
	// use for each module. This can be used to provide module-scoped objects.
	// For example:
	//
	// 	opts.ModulePrivateProviders = cell.ModulePrivateProviders{
	// 		func(id cell.ModuleID) Foo {
	// 			return foo.New(id)
	//		},
	//	}
	//
	ModulePrivateProviders cell.ModulePrivateProviders

	// DecodeHooks are optional additional decode hooks to use with cell.Config
	// to decode a configuration flag into a config field. See existing hooks
	// in [cell/config.go] for examples.
	DecodeHooks cell.DecodeHooks

	StartTimeout time.Duration
	StopTimeout  time.Duration

	// LogThreshold is an optional threshold to reduce logging verbosity.
	// When an Invoke or Lifecycle Start/Stop hook takes longer than this
	// threshold, it will be logged at Info level. Otherwise it is logged
	// at Debug level.
	LogThreshold time.Duration
}

func DefaultOptions

func DefaultOptions() Options

type RunOptionFunc

type RunOptionFunc func(*Hive)

RunOptionFunc is a functional option type for configuring hive on Run stage.

func WithLogThreshold

func WithLogThreshold(threshold time.Duration) RunOptionFunc

WithLogThreshold overrides hive LogThreshold option.

func WithStartTimeout

func WithStartTimeout(timeout time.Duration) RunOptionFunc

WithStartTimeout overrides hive StartTimeout option.

func WithStopTimeout

func WithStopTimeout(timeout time.Duration) RunOptionFunc

WithStopTimeout overrides hive StopTimeout option.

type ScriptCmd

type ScriptCmd struct {
	Name string
	Cmd  script.Cmd
}

type ScriptCmdOut

type ScriptCmdOut struct {
	cell.Out

	ScriptCmd ScriptCmd `group:"script-commands"`
}

func NewScriptCmd

func NewScriptCmd(name string, cmd script.Cmd) ScriptCmdOut

type ScriptCmds

type ScriptCmds struct {
	cell.In

	ScriptCmds []ScriptCmd `group:"script-commands"`
}

func (ScriptCmds) Map

func (sc ScriptCmds) Map() map[string]script.Cmd

type ScriptCmdsOut

type ScriptCmdsOut struct {
	cell.Out

	ScriptCmds []ScriptCmd `group:"script-commands,flatten"`
}

func NewScriptCmds

func NewScriptCmds(cmds map[string]script.Cmd) (out ScriptCmdsOut)

type ShutdownOption

type ShutdownOption interface {
	// contains filtered or unexported methods
}

func ShutdownWithError

func ShutdownWithError(err error) ShutdownOption

ShutdownWithError shuts down with an error.

type Shutdowner

type Shutdowner interface {
	Shutdown(...ShutdownOption)
}

Shutdowner provides Shutdown(), which is a way to trigger stop for hive.

To shut down with an error, call Shutdown with ShutdownWithError(err). This error will be returned from Run().

Directories

Path Synopsis
mini command
Package hivetest makes testing components using hive easier.
Package hivetest makes testing components using hive easier.
Package script implements a small, customizable, platform-agnostic scripting language.
Package script implements a small, customizable, platform-agnostic scripting language.
scripttest
Package scripttest adapts the script engine for use in tests.
Package scripttest adapts the script engine for use in tests.

Jump to

Keyboard shortcuts

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