plugin

package
v1.10.0 Latest Latest
Warning

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

Go to latest
Published: Apr 8, 2024 License: MIT Imports: 54 Imported by: 0

Documentation

Overview

Example (ExecuteCommand)
out, err := ExecuteCommand(context.Background(), `echo "hakuna matata"`)
if err != nil {
	panic(err)
}

fmt.Println(out.Stdout)
Output:

hakuna matata
Example (ExecuteCommandWithEnv)
out, err := ExecuteCommand(context.Background(), `sh -c "echo ${CUSTOM_ENV}"`, ExecuteCommandEnvs(map[string]string{
	"CUSTOM_ENV": "magic-value",
}))
if err != nil {
	panic(err)
}

fmt.Println(out.Stdout)
Output:

magic-value
Example (ParseCommand)
type (
	CommitCmd struct {
		All     bool   `arg:"-a"`
		Message string `arg:"-m"`
	}
	Commands struct {
		Commit *CommitCmd `arg:"subcommand:commit"`
		Quiet  bool       `arg:"-q"` // this flag is global to all subcommands
	}
)

rawCommand := "./example commit -m 'hakuna matata' -a -q"

var cmd Commands
err := ParseCommand("./example", rawCommand, &cmd)
if err != nil {
	panic(err)
}

switch {
case cmd.Commit != nil:
	fmt.Println(heredoc.Docf(`
			global quiet flag: %v
			commit message: %v
			commit all flag: %v
		`, cmd.Commit.All, cmd.Commit.Message, cmd.Quiet))
}
Output:

global quiet flag: true
commit message: hakuna matata
commit all flag: true

Index

Examples

Constants

View Source
const (

	// DependencyDirEnvName define environment variable where plugin dependency binaries are stored.
	DependencyDirEnvName = "PLUGIN_DEPENDENCY_DIR"
)

Variables

View Source
var ErrNotStartedPluginManager = errors.New("plugin manager is not started yet")

ErrNotStartedPluginManager is an error returned when Plugin Manager was not yet started and initialized successfully.

Functions

func DoesBinaryExist

func DoesBinaryExist(path string) bool

DoesBinaryExist returns true if a given file exists.

func ExecuteCommandWithEnvs

func ExecuteCommandWithEnvs(ctx context.Context, rawCmd string, envs map[string]string) (string, error)

ExecuteCommandWithEnvs is a simple wrapper around exec.CommandContext to simplify running a given command. Deprecated: Use ExecuteCommand(ctx, rawCmd, ExecuteCommandEnvs(envs)) instead.

func GenerateKubeConfig

func GenerateKubeConfig(restCfg *rest.Config, clusterName string, pluginCtx config.PluginContext, input KubeConfigInput) ([]byte, error)

GenerateKubeConfig generates kubeconfig based on RBAC policy.

func IsNotFoundError

func IsNotFoundError(err error) bool

IsNotFoundError returns true if one of the error in the chain is the not found error instance.

func MergeExecutorConfigs

func MergeExecutorConfigs(in []*executor.Config, dest any) error

MergeExecutorConfigs merges input configuration into a given destination. Rules: - Destination MUST be a pointer to a struct. - if `yaml:"omitempty"` tag is not specified, then empty fields are take into account, and resets previous value. - Merging strategy can be found here https://github.com/knadh/koanf#merge-behavior.

func MergeExecutorConfigsWithDefaults

func MergeExecutorConfigsWithDefaults(defaults any, in []*executor.Config, dest any) error

MergeExecutorConfigsWithDefaults merges input configuration into a given destination. Rules: - Destination MUST be a pointer to a struct. - Default MUST be a Go object with the `yaml` tag. - if `yaml:"omitempty"` tag is not specified, then empty fields are take into account, and resets previous value. - Merging strategy can be found here https://github.com/knadh/koanf#merge-behavior.

func MergeSourceConfigs

func MergeSourceConfigs(in []*source.Config, dest any) error

MergeSourceConfigs merges input configuration into a given destination. Rules: - Destination MUST be a pointer to a struct. - if `yaml:"omitempty"` tag is not specified, then empty fields are take into account, and resets previous value. - Merging strategy can be found here https://github.com/knadh/koanf#merge-behavior.

func MergeSourceConfigsWithDefaults

func MergeSourceConfigsWithDefaults(defaults any, in []*source.Config, dest any) error

MergeSourceConfigsWithDefaults merges input configuration into a given destination. Rules: - Destination MUST be a pointer to a struct. - Default MUST be a Go object with the `yaml` tag. - if `yaml:"omitempty"` tag is not specified, then empty fields are take into account, and resets previous value. - Merging strategy can be found here https://github.com/knadh/koanf#merge-behavior.

func NewPluginLoggers

func NewPluginLoggers(bkLogger logrus.FieldLogger, logConfig config.Logger, pluginKey string, pluginType Type) (hclog.Logger, io.Writer, io.Writer)

NewPluginLoggers returns a copy of parent with a log settings dedicated for a given plugin. The log level is taken from the environment variable with a pattern: LOG_LEVEL_{pluginType}_{pluginRepo}_{pluginName}. If env variable is not set, default value is "info". Loggers: - hashicorp client logger always has the configured log level - binary standard output is logged only if debug level is set, otherwise it is discarded - binary standard error is logged always on error level

func NewStaticPluginServer

func NewStaticPluginServer(cfg StaticPluginServerConfig) (string, func() error)

NewStaticPluginServer return function to start the static plugin HTTP server suitable for local development or e2e tests.

func ParseCommand

func ParseCommand(pluginName, command string, destination any) error

ParseCommand processes a given command string and stores the result in a given destination. Destination MUST be a pointer to a struct.

If `-h,--help` flag was specified, arg.ErrHelp is returned and command might be not fully parsed.

To support flags, positional arguments, and subcommands add dedicated `arg:` tag. To learn more, visit github.com/alexflint/go-arg

func PersistKubeConfig

func PersistKubeConfig(_ context.Context, kc []byte) (string, func(context.Context) error, error)

PersistKubeConfig creates a temporary kubeconfig file and returns its path and a function to delete it.

func ValidateKubeConfigProvided

func ValidateKubeConfigProvided(pluginName string, kubeconfig []byte) error

ValidateKubeConfigProvided returns an error if a given kubeconfig is empty or nil.

Types

type Collector

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

Collector provides functionality to collect all enabled plugins based on the Botkube configuration.

func NewCollector

func NewCollector(log logrus.FieldLogger) *Collector

NewCollector returns a new Collector instance.

func (*Collector) GetAllEnabledAndUsedPlugins

func (c *Collector) GetAllEnabledAndUsedPlugins(cfg *config.Config) ([]string, []string)

GetAllEnabledAndUsedPlugins returns the list of all plugins that are both enabled and bind to at least one communicator or action (automation) that is enabled.

type Dependencies

type Dependencies map[string]Dependency

Dependencies holds the dependencies for a given platform binary.

type Dependency

type Dependency struct {
	URL string `yaml:"url"`
}

Dependency holds the dependency information.

type ExecuteCommandMutation

type ExecuteCommandMutation func(*ExecuteCommandOptions)

ExecuteCommandMutation is a function type that can be used to modify ExecuteCommandOptions.

func ExecuteClearColorCodes

func ExecuteClearColorCodes() ExecuteCommandMutation

ExecuteClearColorCodes is a function that enables removing color codes.

func ExecuteCommandDependencyDir

func ExecuteCommandDependencyDir(dir string) ExecuteCommandMutation

ExecuteCommandDependencyDir is a function that sets the dependency directory.

func ExecuteCommandEnvs

func ExecuteCommandEnvs(envs map[string]string) ExecuteCommandMutation

ExecuteCommandEnvs is a function that sets the environment variables.

func ExecuteCommandStdin

func ExecuteCommandStdin(in io.Reader) ExecuteCommandMutation

ExecuteCommandStdin is a function that sets the stdin of the command.

func ExecuteCommandWorkingDir

func ExecuteCommandWorkingDir(dir string) ExecuteCommandMutation

ExecuteCommandWorkingDir is a function that sets the working directory of the command.

type ExecuteCommandOptions

type ExecuteCommandOptions struct {
	Envs            map[string]string
	DependencyDir   string
	WorkDir         string
	Stdin           io.Reader
	ClearColorCodes bool
}

ExecuteCommandOptions represents the options for executing a command.

type ExecuteCommandOutput

type ExecuteCommandOutput struct {
	Stdout   string
	Stderr   string
	ExitCode int
}

ExecuteCommandOutput holds ExecuteCommand output.

func ExecuteCommand

func ExecuteCommand(ctx context.Context, rawCmd string, mutators ...ExecuteCommandMutation) (ExecuteCommandOutput, error)

ExecuteCommand is a simple wrapper around exec.CommandContext to simplify running a given command.

func (ExecuteCommandOutput) CombinedOutput

func (out ExecuteCommandOutput) CombinedOutput() string

CombinedOutput return combined stdout and stderr.

type ExternalRequest

type ExternalRequest struct {
	Payload ExternalRequestPayload `yaml:"payload,omitempty"`
}

ExternalRequest contains the external request metadata for a given plugin.

type ExternalRequestPayload

type ExternalRequestPayload struct {
	// JSONSchema is a JSON schema for a given incoming webhook payload.
	JSONSchema JSONSchema `yaml:"jsonSchema"`
}

ExternalRequestPayload contains the external request payload metadata for a given plugin.

type HealthMonitor

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

HealthMonitor restarts a failed plugin process and inform scheduler to start dispatching loop again with a new client that was generated.

func NewHealthMonitor

func NewHealthMonitor(logger logrus.FieldLogger, logCfg config.Logger, policy config.PluginRestartPolicy, schedulerChan chan string, sourceSupervisorChan, executorSupervisorChan chan pluginMetadata, executorsStore *store[executor.Executor], sourcesStore *store[source.Source], healthCheckInterval time.Duration, stats *HealthStats) *HealthMonitor

NewHealthMonitor returns a new HealthMonitor instance.

func (*HealthMonitor) Start

func (m *HealthMonitor) Start(ctx context.Context)

Start starts monitor processes for sources and executors.

type HealthStats

type HealthStats struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

HealthStats holds information about plugin health and restarts.

func NewHealthStats

func NewHealthStats(threshold int) *HealthStats

NewHealthStats returns a new HealthStats instance.

func (*HealthStats) GetRestartCount

func (h *HealthStats) GetRestartCount(plugin string) int

GetRestartCount returns restart count for a plugin.

func (*HealthStats) GetStats

func (h *HealthStats) GetStats(plugin string) (status string, restarts int, threshold int, timestamp string)

GetStats returns plugin status, restart count, restart threshold and last transition time.

func (*HealthStats) Increment

func (h *HealthStats) Increment(plugin string)

Increment increments restart count for a plugin.

type Index

type Index struct {
	Entries []IndexEntry `yaml:"entries"`
}

Index defines the plugin repository index.

func (Index) Validate

func (in Index) Validate() error

Validate validates that entries define in a given index don't conflict with each other by having the same name, type and version.

type IndexBuilder

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

IndexBuilder provides functionality to generate plugin index.

func NewIndexBuilder

func NewIndexBuilder(log logrus.FieldLogger) *IndexBuilder

NewIndexBuilder returns a new IndexBuilder instance.

func (*IndexBuilder) Build

func (i *IndexBuilder) Build(dir, urlBasePath, pluginNameFilter string, skipChecksum, useArchive bool) (Index, error)

Build returns plugin index built based on plugins found in a given directory.

type IndexEntry

type IndexEntry struct {
	Name             string          `yaml:"name"`
	Type             Type            `yaml:"type"`
	Description      string          `yaml:"description"`
	DocumentationURL string          `yaml:"documentationUrl,omitempty"`
	Version          string          `yaml:"version"`
	URLs             []IndexURL      `yaml:"urls"`
	JSONSchema       JSONSchema      `yaml:"jsonSchema"`
	ExternalRequest  ExternalRequest `yaml:"externalRequest,omitempty"`
	Recommended      bool            `yaml:"recommended"`
}

IndexEntry defines the plugin definition.

type IndexRenderData

type IndexRenderData struct {
	Remote remote.Config `yaml:"remote"`
}

IndexRenderData returns plugin index render data.

type IndexURL

type IndexURL struct {
	URL          string           `yaml:"url"`
	Checksum     string           `yaml:"checksum"`
	Platform     IndexURLPlatform `yaml:"platform"`
	Dependencies Dependencies     `yaml:"dependencies,omitempty"`
}

IndexURL holds the binary url details.

type IndexURLPlatform

type IndexURLPlatform struct {
	OS   string `yaml:"os"`
	Arch string `yaml:"architecture"`
}

IndexURLPlatform holds platform information about a given binary URL.

type JSONSchema

type JSONSchema struct {
	Value  string `yaml:"value,omitempty"`
	RefURL string `yaml:"refURL,omitempty"`
}

func (*JSONSchema) Get

func (s *JSONSchema) Get(ctx context.Context, httpCli *http.Client) (json.RawMessage, error)

Get returns the JSON schema. When RefURL is not empty, Get tries to fetch the schema from the URL.

type KubeConfigInput

type KubeConfigInput struct {
	Channel string
}

KubeConfigInput defines the input for GenerateKubeConfig.

type Manager

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

Manager provides functionality for managing executor and source plugins.

func NewManager

func NewManager(logger logrus.FieldLogger, logCfg config.Logger, cfg config.PluginManagement, executors, sources []string, schedulerChan chan string, stats *HealthStats) *Manager

NewManager returns a new Manager instance.

func (*Manager) GetExecutor

func (m *Manager) GetExecutor(name string) (executor.Executor, error)

GetExecutor returns the executor client for a given plugin.

func (*Manager) GetSource

func (m *Manager) GetSource(name string) (source.Source, error)

GetSource returns the source client for a given plugin.

func (*Manager) Shutdown

func (m *Manager) Shutdown()

Shutdown performs any necessary cleanup. This method blocks until all cleanup is finished.

func (*Manager) Start

func (m *Manager) Start(ctx context.Context) error

Start downloads and starts all enabled plugins.

type NotFoundPluginError

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

NotFoundPluginError is an error returned when a given Plugin cannot be found in a given repository.

func NewNotFoundPluginError

func NewNotFoundPluginError(msg string, args ...any) *NotFoundPluginError

NewNotFoundPluginError return a new NotFoundPluginError instance.

func (NotFoundPluginError) Error

func (n NotFoundPluginError) Error() string

Error returns the error message.

func (*NotFoundPluginError) Is

func (n *NotFoundPluginError) Is(target error) bool

Is returns true if target is not found error.

type StaticPluginServerConfig

type StaticPluginServerConfig struct {
	BinariesDirectory string
	Host              string `envconfig:"default=http://host.k3d.internal"`
	Port              int    `envconfig:"default=3000"`
}

StaticPluginServerConfig holds configuration for fake plugin server.

type TmpDir

type TmpDir string

TmpDir represents temporary directory.

func (TmpDir) Get

func (t TmpDir) Get() (string, bool)

Get returns temporary directory path.

func (TmpDir) GetDirectory

func (t TmpDir) GetDirectory() string

GetDirectory returns temporary directory.

type Type

type Type string

Type represents the plugin type.

const (
	// TypeSource represents the source plugin.
	TypeSource Type = "source"
	// TypeExecutor represents the executor plugin.
	TypeExecutor Type = "executor"
)

func (Type) IsValid

func (t Type) IsValid() bool

IsValid checks if type is a known type.

func (Type) String

func (t Type) String() string

String returns a string type representation.

type URL

type URL struct {
	URL      string
	Checksum string
}

Jump to

Keyboard shortcuts

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