agent

package module
v0.0.0-...-fb5f2e6 Latest Latest
Warning

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

Go to latest
Published: May 9, 2025 License: GPL-3.0 Imports: 35 Imported by: 0

Documentation

Index

Constants

View Source
const (
	FlagType               = "type"
	FlagName               = "name"
	FlagCommandList        = "command-list"
	FlagProtocol           = "protocol"
	FlagIP                 = "ip"
	FlagPort               = "port"
	FlagRequestTimeout     = "request-timeout"
	FlagResponseTimeout    = "response-timeout"
	FlagThresholdMode      = "threshold-mode"
	FlagThresholdMax       = "threshold-max"
	FlagCommandInterval    = "command-interval"
	FlagMonitorName        = "monitor"
	FlagSourceSignificance = "significance"
	FlagSourceMaxValue     = "max-value"
	FlagMetricType         = "metric-type"
	FlagMetricInterval     = "interval-ms"
	FlagSampleTime         = "sampling-ms"
	FlagScriptName         = "script-name"
	FlagDiskPath           = "disk-path"
	FlagShapingEnabled     = "smart-shape"
	FlagLogState           = "log-state-changes"
)
View Source
const (
	VersionString   string = "5.4.0"
	CopyrightYear   string = "2025"
	ApplicationName string = "Loadbalancer.org Feedback Agent"
	AppIdentifier   string = "lbfeedback"

	ServiceStateStopped int = 1
	ServiceStateRunning int = 2
	ServiceStateFailed  int = 3

	ProtocolHTTP      string = "http"
	ProtocolHTTPS     string = "https"
	ProtocolTCP       string = "tcp"
	ProtocolSecureAPI string = "https-api"
	ProtocolLegacyAPI string = "http-api"
	ResponderNameAPI  string = "api"

	LogFileName                 string = "agent.log"
	ConfigFileName              string = "agent-config.json"
	LocalPathMode               bool   = false
	ForceAPISecure              bool   = true
	DefaultTLSCertExpiryMinutes int    = 720
)
View Source
const (
	MetricTypeCPU          = "cpu"
	ParamKeySampleTime     = "sampling-ms"
	CPUMetricMinSampleTime = 500
	CPUMetricDefaultMax    = 100
	CPUMetricMinInterval   = 500
)
View Source
const (
	MetricTypeRAM           = "ram"
	MemoryMetricDefaultMax  = 100
	MemoryMetricMinInterval = 500
)
View Source
const (
	MetricTypeScript        = "script"
	ScriptMetricDefaultMax  = 100
	ScriptMetricMinInterval = 3000
	ParamKeyScriptName      = "script-name"
)
View Source
const (
	MetricTypeDiskUsage  = "disk-usage"
	ParamKeyDiskPath     = "disk-path"
	DiskUsageDefaultMax  = 100
	DiskUsageMinInterval = 3000
)
View Source
const (
	MetricTypeNetConnections  = "netconn"
	NetConnectionsDefaultMax  = 2000
	NetConnectionsMinInterval = 3000
)
View Source
const (
	DefaultDirPermissions  fs.FileMode = 0755
	DefaultFilePermissions fs.FileMode = 0644

	DefaultConfigDir = "/opt/lbfeedback"
	DefaultLogDir    = "/var/log/lbfeedback"

	ExitStatusNormal = 0
	ExitStatusError  = 1
)
View Source
const (
	ThresholdStringAny         = "any"
	ThresholdStringNone        = "none"
	ThresholdStringOverallOnly = "overall"
	ThresholdStringMetricOnly  = "metric"
)
View Source
const (
	HAPEnumNone        = 0x000
	HAPMaskCommand     = 0x0FF
	HAPMaskAll         = 0xFFF
	HAPOnlineFlag      = 0x100
	HAPOfflineFlag     = 0x200
	HAPEnumUp          = 0x101
	HAPEnumReady       = 0x102
	HAPEnumDown        = 0x204
	HAPEnumDrain       = 0x208
	HAPEnumFail        = 0x210
	HAPEnumMaintenance = 0x220
	HAPEnumStopped     = 0x240

	HAPDefaultOnline  = HAPEnumUp | HAPEnumReady
	HAPDefaultOffline = HAPEnumDrain

	HAPCommandNone        = ""
	HAPCommandUp          = "up"
	HAPCommandReady       = "ready"
	HAPCommandDown        = "down"
	HAPCommandDrain       = "drain"
	HAPCommandFail        = "fail"
	HAPCommandMaintenance = "maint"
	HAPCommandStopped     = "stopped"

	HAPConfigDefault = "default"
	HAPConfigNone    = "none"
)

-- Constants for HAProxy command handling.

View Source
const (
	DefaultXCountLimit         = 0x10000000
	DefaultZMeanThreshold      = 1.0
	DefaultZPredictionInterval = 5
)
View Source
const (
	DefaultCommandInterval = 10
)
View Source
const (
	MonitorWaitInterval = 100
)

Variables

View Source
var HelpText = `` /* 4618-byte string literal not displayed */

HelpText defines the output printed on the command line when help mode is activated.

View Source
var PanicDebug = false

PanicDebug specifies if a panic should result in termination or instead be ignored in a parent service via recover().

View Source
var ShellBanner = `
     ▄ █           ` + ApplicationName + " v" + VersionString + `
     █ █ █▄▄       Copyright (C) ` + CopyrightYear + ` Loadbalancer.org Limited
     █ █ ▄ █       Licensed under the GNU General Public License v3

This program comes with ABSOLUTELY NO WARRANTY. This is free software, and 
you are welcome to redistribute it under certain conditions. For further
information, please read the LICENSE file distributed with this program.
`

ShellBanner provides the masthead printed at startup on the command line.

Functions

func BuildAPIDescription

func BuildAPIDescription(request *APIRequest) (desc string)

BuildAPIDescription makes a log line description of an API request.

func CreateDirectoryIfMissing

func CreateDirectoryIfMissing(dir string) (err error)

CreateDirectoryIfMissing creates a directory if it doesn't exist, and returns an error if creation is unsuccessful.

func CreateNewTLSCertificate

func CreateNewTLSCertificate(ipList []net.IP, validFor time.Duration) (cert *tls.Certificate,
	validTo time.Time, err error)

func FileExists

func FileExists(dirPath string, fileName string) (exists bool)

FileExists checks to see if a file exists at the given directory path and file name.

func GetParamValueString

func GetParamValueString(key string, params MetricParams) (str string, err error)

func LaunchAgentService

func LaunchAgentService() (exitStatus int)

LaunchAgentService creates a new FeedbackAgent service and runs it.

func NewNullLogger

func NewNullLogger() *log.Logger

NewNullLogger returns a new Logger instance that outputs to a NullWriter, which in turn does absolutely nothing.

func ParseIPAddress

func ParseIPAddress(ip string) (result string, err error)

func ParseNetworkPort

func ParseNetworkPort(port string) (result string, err error)

ParseNetworkPort parses a network port into a sanitised version, returning an error if it cannot be parsed.

func PlatformExecuteScript

func PlatformExecuteScript(fullPath string) (out string, err error)

func PlatformGetConnectionCount

func PlatformGetConnectionCount() (val int, err error)

func PlatformMain

func PlatformMain() (exitStatus int)

func PlatformOpenLogFile

func PlatformOpenLogFile(fullPath string) (file *os.File, err error)

func PlatformPrintHelpMessage

func PlatformPrintHelpMessage()

func PlatformPrintRunInstructions

func PlatformPrintRunInstructions()

func PointerHandleBoolString

func PointerHandleBoolString(input *string) (output *bool)

PointerHandleBoolString converts a string representation of a boolean state ("true" or "false") into a bool pointer type if is not nil. This is to provide a workaround for an annoying bug in the Go flags package.

func PointerHandleInt64Value

func PointerHandleInt64Value(input *int64) (output *int64)

PointerHandleInt64Value provides the same functionality as PointerHandleIntValue, but for 64-bit integer pointers.

func PointerHandleIntValue

func PointerHandleIntValue(input *int) (output *int)

PointerHandleIntValue filters an input integer pointer, setting the return value to nil if the input is less than zero.

func PointerHandleStringValue

func PointerHandleStringValue(input *string) (output *string)

PointerHandleStringValue filters an input string pointer, setting the output to nil if the string is empty.

func RandomHexBytes

func RandomHexBytes(n int) (str string)

RandomHexBytes generates a random hex string that is a specified number of bytes long.

func RemoveExtraSpaces

func RemoveExtraSpaces(str string) (result string)

RemoveExtraSpaces converts any repeated spaces in a string into single spaces and discards any that are leading or trailing.

func RunClientCLI

func RunClientCLI() (status int)

RunClientCLI delivers the client CLI personality of the Feedback Agent.

func ServiceRunningToString

func ServiceRunningToString(running bool) string

ServiceRunningToString converts a boolean running state to a descriptive string.

func StandardiseNameIdentifier

func StandardiseNameIdentifier(in string) (out string, err error)

StandardiseNameIdentifier validates and standardises an object name identifier.

func StringAddr

func StringAddr(s string) *string

Types

type APIConfig

type APIConfig struct {
	IPAddress string
	Port      string
	Key       string
}

func LoadAPIConfigFromFile

func LoadAPIConfigFromFile(dir string, file string) (config APIConfig, err error)

LoadAPIConfigFromFile attempts to load the API access details from the JSON config.

type APIRequest

type APIRequest struct {
	// Global API request fields that apply to any request.
	APIKey     string `json:"api-key,omitempty"`
	ID         int    `json:"id,omitempty"`
	Action     string `json:"action,omitempty"`
	Type       string `json:"type,omitempty"`
	TargetName string `json:"target-name,omitempty"`

	// API fields for FeedbackResponder operations.
	ProtocolName    *string                     `json:"protocol,omitempty"`
	ListenIPAddress *string                     `json:"ip,omitempty"`
	ListenPort      *string                     `json:"port,omitempty"`
	FeedbackSources *map[string]*FeedbackSource `json:"feedback-sources,omitempty"`
	RequestTimeout  *int                        `json:"request-timeout,omitempty"`
	ResponseTimeout *int                        `json:"response-timeout,omitempty"`
	CommandList     *string                     `json:"command-list,omitempty"`
	CommandInterval *int                        `json:"command-interval,omitempty"`
	ThresholdMode   *string                     `json:"threshold-mode,omitempty"`
	ThresholdScore  *int                        `json:"threshold-max,omitempty"`
	SmartShape      *bool                       `json:"smart-shape,omitempty"`
	LogStateChanges *bool                       `json:"log-state-changes,omitempty"`

	// API fields for SourceMonitor operations.
	SourceMonitorName  *string  `json:"monitor,omitempty"`
	SourceSignificance *float64 `json:"significance,omitempty"`
	SourceMaxValue     *int64   `json:"max-value,omitempty"`

	// API fields for SystemMonitor operations.
	MetricType     *string       `json:"metric-type,omitempty"`
	MetricInterval *int          `json:"interval-ms,omitempty"`
	MetricParams   *MetricParams `json:"metric-config,omitempty"`
}

APIRequest defines a request received from a client to the agent.

func ParseArgumentsToRequest

func ParseArgumentsToRequest(actionName string, actionType string, argv []string) (request APIRequest, err error)

func UnmarshalAPIRequest

func UnmarshalAPIRequest(requestJSON string) (request *APIRequest, err error)

UnmarshalAPIRequest unmarshals a JSON request string into an APIRequest.

type APIResponse

type APIResponse struct {
	APIName         string                     `json:"service"`
	Version         string                     `json:"version"`
	ID              *int                       `json:"id,omitempty"`
	Tag             string                     `json:"tag,omitempty"`
	Request         *APIRequest                `json:"request,omitempty"`
	Success         bool                       `json:"success"`
	Error           string                     `json:"error-name,omitempty"`
	Message         string                     `json:"message,omitempty"`
	Output          string                     `json:"output,omitempty"`
	AgentConfig     *FeedbackAgent             `json:"current-config,omitempty"`
	ServiceStatus   []APIServiceStatus         `json:"status,omitempty"`
	FeedbackSources map[string]*FeedbackSource `json:"feedback-sources,omitempty"`
}

APIResponse defines a response to be sent from the agent to a client.

func CLIHandleAgentAction

func CLIHandleAgentAction(actionName string, actionType string, argv []string) (
	responseObject *APIResponse, responseJSON string, err error)

func UnmarshalAPIResponse

func UnmarshalAPIResponse(responseJSON string) (response *APIResponse, err error)

UnmarshalAPIResponse parses a JSON request string into an APIRequest.

type APIServiceStatus

type APIServiceStatus struct {
	ServiceType   string `json:"type"`
	ServiceName   string `json:"name"`
	ServiceStatus string `json:"status"`
}

func AppendToStatusArray

func AppendToStatusArray(array []APIServiceStatus, serviceType string,
	name string, state string) []APIServiceStatus

AppendToStatusArray appends an item to a service status array.

type CPUMetric

type CPUMetric struct {
	SampleTime uint64
}

func (*CPUMetric) Configure

func (m *CPUMetric) Configure(params MetricParams) (err error)

func (*CPUMetric) GetDefaultMax

func (m *CPUMetric) GetDefaultMax() float64

func (*CPUMetric) GetDescription

func (m *CPUMetric) GetDescription() string

func (*CPUMetric) GetLoad

func (m *CPUMetric) GetLoad() (float64, error)

GetLoad returns the current CPU metric for the host system.

func (*CPUMetric) GetMetricName

func (m *CPUMetric) GetMetricName() string

func (*CPUMetric) GetMinInterval

func (m *CPUMetric) GetMinInterval() int

type DiskUsageMetric

type DiskUsageMetric struct {
	DiskPath string
}

func (*DiskUsageMetric) Configure

func (m *DiskUsageMetric) Configure(params MetricParams) (err error)

func (*DiskUsageMetric) GetDefaultMax

func (m *DiskUsageMetric) GetDefaultMax() float64

func (*DiskUsageMetric) GetDescription

func (m *DiskUsageMetric) GetDescription() string

func (*DiskUsageMetric) GetLoad

func (m *DiskUsageMetric) GetLoad() (val float64, err error)

func (*DiskUsageMetric) GetMetricName

func (m *DiskUsageMetric) GetMetricName() string

func (*DiskUsageMetric) GetMinInterval

func (m *DiskUsageMetric) GetMinInterval() int

type FeedbackAgent

type FeedbackAgent struct {
	// Config masthead fields. These were absent prior to v5.3.6 and
	// must therefore have the omitempty flag set for the JSON.
	ServiceName string `json:"service-name,omitempty"`
	Version     string `json:"version,omitempty"`

	// Agent configuration fields
	LogDir     string                        `json:"log-dir"`
	APIKey     string                        `json:"api-key,omitempty"`
	Monitors   map[string]*SystemMonitor     `json:"monitors"`
	Responders map[string]*FeedbackResponder `json:"responders"`
	// contains filtered or unexported fields
}

FeedbackAgent represents the main parent service which runs a configured set of SystemMonitor and FeedbackResponder objects, and provides the general utility functions for the project.

func (*FeedbackAgent) APIAddMonitor

func (agent *FeedbackAgent) APIAddMonitor(request *APIRequest) (err error)

func (*FeedbackAgent) APIAddResponder

func (agent *FeedbackAgent) APIAddResponder(request *APIRequest) (err error)

func (*FeedbackAgent) APIDeleteMonitor

func (agent *FeedbackAgent) APIDeleteMonitor(request *APIRequest) (
	err error)

func (*FeedbackAgent) APIDeleteResponder

func (agent *FeedbackAgent) APIDeleteResponder(request *APIRequest) (
	err error)

func (*FeedbackAgent) APIEditMonitor

func (agent *FeedbackAgent) APIEditMonitor(request *APIRequest) (err error)

func (*FeedbackAgent) APIEditResponder

func (agent *FeedbackAgent) APIEditResponder(request *APIRequest) (err error)

func (*FeedbackAgent) APIHandleGetConfig

func (agent *FeedbackAgent) APIHandleGetConfig() (config FeedbackAgent)

func (*FeedbackAgent) APIHandleGetFeedback

func (agent *FeedbackAgent) APIHandleGetFeedback(request *APIRequest) (
	feedback string, err error)

func (*FeedbackAgent) APIHandleGetSources

func (agent *FeedbackAgent) APIHandleGetSources(request *APIRequest) (
	sources map[string]*FeedbackSource, err error)

func (*FeedbackAgent) APIHandleMonitorRequest

func (agent *FeedbackAgent) APIHandleMonitorRequest(request *APIRequest) (
	err error)

func (*FeedbackAgent) APIHandleResponderRequest

func (agent *FeedbackAgent) APIHandleResponderRequest(request *APIRequest) (
	err error)

func (*FeedbackAgent) APIHandleSetCommands

func (agent *FeedbackAgent) APIHandleSetCommands(request *APIRequest,
	replace bool) (err error)

func (*FeedbackAgent) APIHandleSetInterval

func (agent *FeedbackAgent) APIHandleSetInterval(request *APIRequest) (
	err error)

func (*FeedbackAgent) APIHandleSetOnlineState

func (agent *FeedbackAgent) APIHandleSetOnlineState(name string,
	isOnline bool, commandMask int) (err error)

func (*FeedbackAgent) APIHandleSetThreshold

func (agent *FeedbackAgent) APIHandleSetThreshold(request *APIRequest) (
	err error)

APIHandleSetThreshold processes an API request to set a value or state for applying a threshold to the Feedback Agent output.

func (*FeedbackAgent) APIHandleSourceRequest

func (agent *FeedbackAgent) APIHandleSourceRequest(request *APIRequest) (
	err error)

func (*FeedbackAgent) AddMonitor

func (agent *FeedbackAgent) AddMonitor(name string, metric string, interval int,
	params MetricParams, shaping bool) (err error)

AddMonitor adds a monitor service to this FeedbackAgent.

func (*FeedbackAgent) AddMonitorObject

func (agent *FeedbackAgent) AddMonitorObject(monitor *SystemMonitor) (err error)

AddMonitorObject adds a monitor object to this FeedbackAgent.

func (*FeedbackAgent) AddResponder

func (agent *FeedbackAgent) AddResponder(name string,
	sources map[string]*FeedbackSource, protocol string, ip string,
	port string, hapCommands string, thresholdMode string,
	hapThreshold int, logStateChanges bool) (err error)

AddResponder creates a Responder associated with a given Monitor, returning an error if the Monitor does not exist.

func (*FeedbackAgent) AddResponderObject

func (agent *FeedbackAgent) AddResponderObject(responder *FeedbackResponder) (err error)

func (*FeedbackAgent) ConfigToJSON

func (agent *FeedbackAgent) ConfigToJSON() (output []byte, err error)

ConfigToJSON outputs this agent object's configuration as JSON.

func (*FeedbackAgent) DeleteMonitorByName

func (agent *FeedbackAgent) DeleteMonitorByName(name string) (err error)

DeleteMonitorByName deletes a SystemMonitor by name from the map.

func (*FeedbackAgent) DeleteResponderByName

func (agent *FeedbackAgent) DeleteResponderByName(name string) (err error)

DeleteResponderByName deletes a FeedbackResponder by name from the map.

func (*FeedbackAgent) EventHandleLoop

func (agent *FeedbackAgent) EventHandleLoop()

EventHandleLoop blocks until a signal is received from the system based on what is registered for the platform file. In the case of "platform_posix" this will be SIGTERM, SIGINT, etc.

func (*FeedbackAgent) GetAgentStatusString

func (agent *FeedbackAgent) GetAgentStatusString() (status string)

GetAgentStatusString outputs the current agent status as a descriptive string.

func (*FeedbackAgent) GetMonitorByName

func (agent *FeedbackAgent) GetMonitorByName(name string) (mon *SystemMonitor,
	err error)

GetMonitorByName gets a SystemMonitor by name from the map.

func (*FeedbackAgent) GetResponderByName

func (agent *FeedbackAgent) GetResponderByName(name string) (res *FeedbackResponder, err error)

GetResponderByName gets a FeedbackResponder by name from the map.

func (*FeedbackAgent) GetServiceStatusArray

func (agent *FeedbackAgent) GetServiceStatusArray() (array []APIServiceStatus)

GetServiceStatusArray builds an array of the service status.

func (*FeedbackAgent) InitialiseFileLogging

func (agent *FeedbackAgent) InitialiseFileLogging(dir string) (err error)

InitialiseFileLogging sets up file logging given a string specifying the log directory on the local system, disabling it entirely if an empty string is supplied.

func (*FeedbackAgent) InitialiseLogger

func (agent *FeedbackAgent) InitialiseLogger()

InitialiseLogger sets up logrus to show the timestamp in the correct format.

func (*FeedbackAgent) InitialisePaths

func (agent *FeedbackAgent) InitialisePaths()

InitialisePaths initialises the system paths for this FeedbackAgent.

func (*FeedbackAgent) InitialiseServiceMaps

func (agent *FeedbackAgent) InitialiseServiceMaps()

InitialiseServiceMaps clears all configured services from this FeedbackAgent.

func (*FeedbackAgent) JSONToConfig

func (agent *FeedbackAgent) JSONToConfig(config []byte) (err error)

JSONToConfig configures the FeedbackAgent service from a byte stream of JSON configuration data by parsing it.

func (*FeedbackAgent) LoadAgentConfig

func (agent *FeedbackAgent) LoadAgentConfig(dirPath string, fileName string) (
	success bool, err error)

LoadAgentConfig attempts to load the agent configuration from a specified path and name.

func (*FeedbackAgent) LoadOrCreateConfig

func (agent *FeedbackAgent) LoadOrCreateConfig() (err error)

LoadOrCreateConfig attempts to load the agent configuration from a JSON file at the configured system paths, and if it cannot do so, sets up the default agent configuration; this will be written to a new JSON file if one currently does not exist.

func (*FeedbackAgent) PlatformConfigureSignals

func (agent *FeedbackAgent) PlatformConfigureSignals()

func (*FeedbackAgent) ProcessAPIRequest

func (agent *FeedbackAgent) ProcessAPIRequest(request *APIRequest, parseErr error) (
	response *APIResponse, quitAfterResponding bool)

ProcessAPIRequest processes an incoming API request and performs the required actions.

func (*FeedbackAgent) ReceiveAPIRequest

func (agent *FeedbackAgent) ReceiveAPIRequest(requestJSON string) (
	responseJSON string, err error, quitAfterResponding bool)

ReceiveAPIRequest handles an incoming JSON API request received by this FeedbackAgent via a FeedbackResponder service.

func (*FeedbackAgent) RestartAllServices

func (agent *FeedbackAgent) RestartAllServices() (err error)

RestartAllServices restarts all FeedbackAgent services and reloads the configuration.

func (*FeedbackAgent) Run

func (agent *FeedbackAgent) Run() (exitStatus int)

Run initialises the agent parameters and runs its main function.

func (*FeedbackAgent) SaveAgentConfig

func (agent *FeedbackAgent) SaveAgentConfig(dirPath string, fileName string) (
	success bool, err error)

SaveAgentConfig saves the agent configuration to a specified directory and filename.

func (*FeedbackAgent) SaveAgentConfigToPaths

func (agent *FeedbackAgent) SaveAgentConfigToPaths() (success bool, err error)

SaveAgentConfigToPaths saves the agent configuration to the default system paths.

func (*FeedbackAgent) SelfSignalQuit

func (agent *FeedbackAgent) SelfSignalQuit()

SelfSignalQuit sends the agent event loop a quit signal.

func (*FeedbackAgent) SetDefaultPaths

func (agent *FeedbackAgent) SetDefaultPaths()

SetDefaultPaths sets the default paths for this FeedbackAgent.

func (*FeedbackAgent) SetDefaultServiceConfig

func (agent *FeedbackAgent) SetDefaultServiceConfig() (err error)

SetDefaultServiceConfig sets up the agent with a default configuration consisting of one CPU monitor and one HTTP responder, connected together.

func (*FeedbackAgent) StartAllServices

func (agent *FeedbackAgent) StartAllServices() (err error)

StartAllServices loads the JSON configuration file (or creates a new default file, loading a default configuration) and starts Monitors and Responders.

func (*FeedbackAgent) StartMonitorByName

func (agent *FeedbackAgent) StartMonitorByName(name string) (err error)

StartMonitorByName starts a SystemMonitor by name from the map.

func (*FeedbackAgent) StartResponderByName

func (agent *FeedbackAgent) StartResponderByName(name string) (err error)

StartResponderByName starts a FeedbackResponder by name from the map.

func (*FeedbackAgent) StopAllServices

func (agent *FeedbackAgent) StopAllServices() (err error)

StopAllServices signals all FeedbackAgent services to stop.

func (*FeedbackAgent) StopMonitorByName

func (agent *FeedbackAgent) StopMonitorByName(name string) (err error)

StopMonitorByName stops a SystemMonitor by name from the map.

func (*FeedbackAgent) StopResponderByName

func (agent *FeedbackAgent) StopResponderByName(name string) (err error)

StopResponderByName stops a FeedbackResponder by name from the map.

func (*FeedbackAgent) ValidateAPIRequest

func (agent *FeedbackAgent) ValidateAPIRequest(request *APIRequest) (errID string,
	errMsg string)

ValidateAPIRequest performs basic initial sanity checks of an API request.

type FeedbackResponder

type FeedbackResponder struct {
	// -- JSON configuration fields for the FeedbackResponder object.
	ProtocolName          string                     `json:"protocol"`
	ListenIPAddress       string                     `json:"ip"`
	ListenPort            string                     `json:"port"`
	FeedbackSources       map[string]*FeedbackSource `json:"feedback-sources,omitempty"`
	RequestTimeout        time.Duration              `json:"request-timeout,omitempty"`
	ResponseTimeout       time.Duration              `json:"response-timeout,omitempty"`
	HAProxyCommands       string                     `json:"haproxy-commands,omitempty"`
	CommandInterval       int                        `json:"command-interval,omitempty"`
	ThresholdScore        int                        `json:"global-threshold,omitempty"`
	ThresholdModeName     string                     `json:"threshold-mode,omitempty"`
	EnableOfflineInterval bool                       `json:"enable-offline-interval,omitempty"`
	LogStateChanges       bool                       `json:"log-state-changes,omitempty"`

	// -- Exported configuration fields.
	ResponderName string            `json:"-"`
	Connector     ProtocolConnector `json:"-"`
	LastError     error             `json:"-"`
	ParentAgent   *FeedbackAgent    `json:"-"`
	// contains filtered or unexported fields
}

FeedbackResponder implements a Feedback Responder service which uses the specified ProtocolConnector to listen for and respond to clients from data obtained via the associated SystemMonitor objects.

func NewResponder

func NewResponder(name string, sources map[string]*FeedbackSource,
	protocol string, ip string, port string, commands string,
	thresholdMode string, threshold int, agent *FeedbackAgent) (
	result *FeedbackResponder, err error)

NewResponder creates a new FeedbackResponder object. This constructor must be used when creating a new responder object.

func (*FeedbackResponder) AddFeedbackSource

func (fbr *FeedbackResponder) AddFeedbackSource(name string,
	significance *float64, maxValue *int64, threshold *int) (err error)

func (*FeedbackResponder) CommandMaskToString

func (fbr *FeedbackResponder) CommandMaskToString(commandMask int, enumMask int,
	filter int) (commands string)

CommandMaskToString converts an HAProxy command mask to a string, ignoring any command enums that don't have any bits matching the filter.

func (*FeedbackResponder) ConfigureCommands

func (fbr *FeedbackResponder) ConfigureCommands(commands string, replace bool,
	unset bool) (err error)

func (*FeedbackResponder) ConfigureInterval

func (fbr *FeedbackResponder) ConfigureInterval(interval int) (err error)

func (*FeedbackResponder) ConfigureThresholdMode

func (fbr *FeedbackResponder) ConfigureThresholdMode(name string) (err error)

ConfigureThresholdMode sets the current threshold name and string from a specified string value, returning an error (and leaving the mode unchanged) if the specified string is invalid.

func (*FeedbackResponder) ConfigureThresholdValue

func (fbr *FeedbackResponder) ConfigureThresholdValue(threshold int) (err error)

ConfigureThresholdValue sets the command threshold for this FeedbackResponder.

func (*FeedbackResponder) Copy

func (fbr *FeedbackResponder) Copy() (copy FeedbackResponder)

Copy copies this FeedbackResponder into a new object.

func (*FeedbackResponder) DeleteFeedbackSource

func (fbr *FeedbackResponder) DeleteFeedbackSource(name string) (err error)

func (*FeedbackResponder) EditFeedbackSource

func (fbr *FeedbackResponder) EditFeedbackSource(name string, significance *float64,
	maxValue *int64, threshold *int) (err error)

func (*FeedbackResponder) GenerateCommandString

func (fbr *FeedbackResponder) GenerateCommandString(online bool, currentMask int) (
	commands string)

GenerateCommandString generates an HAProxy command string based on the current command mask and a specified online state.

func (*FeedbackResponder) GetAvailabilityState

func (fbr *FeedbackResponder) GetAvailabilityState() (availability int, online bool, logText string)

GetAvailabilityState provides a corrected version of the algorithm mentioned on the Loadbalancer.org blog for the older Windows Feedback Agent, which calculates an availability score against a maximum value specified for a given metric, adjusted by a relative significance score (scaled proportion of the total significance for all monitors attached to this responder).

func (*FeedbackResponder) GetResponse

func (fbr *FeedbackResponder) GetResponse(request string) (response string,
	quitAfter bool)

GetResponse gets a string response from this FeedbackResponder, which will depend on its configuration and what it is supposed to do.

func (*FeedbackResponder) HandleFeedback

func (fbr *FeedbackResponder) HandleFeedback() (feedback string)

HandleFeedback generates a feedback string for this FeedbackResponder. It also changes the current online state as of the last query so that a command is sent for a specified period of time from the first request.

func (*FeedbackResponder) Initialise

func (fbr *FeedbackResponder) Initialise() (err error)

Initialise sets up this FeedbackResponder and configures defaults.

func (*FeedbackResponder) IsRunning

func (fbr *FeedbackResponder) IsRunning() (state bool)

IsRunning returns whether this FeedbackResponder is running or not.

func (*FeedbackResponder) Restart

func (fbr *FeedbackResponder) Restart() (err error)

Restart attempts to restart the FeedbackResponder service.

func (*FeedbackResponder) SetCommandState

func (fbr *FeedbackResponder) SetCommandState(isOnline bool, force bool, overrideMask int)

SetCommandState sets the current responder command state, resetting the state expiry.

func (*FeedbackResponder) Start

func (fbr *FeedbackResponder) Start() (err error)

Start starts the FeedbackResponder service, returning an error in the event of failure, by launching the main code of the service as a goroutine.

func (*FeedbackResponder) Stop

func (fbr *FeedbackResponder) Stop() (err error)

Stop stops the service from running.

type FeedbackSource

type FeedbackSource struct {
	Significance         float64        `json:"significance"`
	MaxValue             int64          `json:"max-value"`
	Threshold            int64          `json:"source-threshold,omitempty"`
	Monitor              *SystemMonitor `json:"-"`
	RelativeSignificance float64        `json:"-"`
}

FeedbackSource defines a source mapping for a FeedbackResponder to a SystemMonitor with a specified significance and maximum value.

type HTTPConnector

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

func (*HTTPConnector) Close

func (pc *HTTPConnector) Close() (err error)

func (*HTTPConnector) Listen

func (pc *HTTPConnector) Listen(fbr *FeedbackResponder) (err error)

type MemoryMetric

type MemoryMetric struct{}

func (*MemoryMetric) Configure

func (m *MemoryMetric) Configure(_ MetricParams) (err error)

func (*MemoryMetric) GetDefaultMax

func (m *MemoryMetric) GetDefaultMax() float64

func (*MemoryMetric) GetDescription

func (m *MemoryMetric) GetDescription() string

func (*MemoryMetric) GetLoad

func (m *MemoryMetric) GetLoad() (load float64, err error)

func (*MemoryMetric) GetMetricName

func (m *MemoryMetric) GetMetricName() string

func (*MemoryMetric) GetMinInterval

func (m *MemoryMetric) GetMinInterval() int

type MetricParams

type MetricParams map[string]string

type NetConnectionsMetric

type NetConnectionsMetric struct{}

func (*NetConnectionsMetric) Configure

func (m *NetConnectionsMetric) Configure(_ MetricParams) (err error)

func (*NetConnectionsMetric) GetDefaultMax

func (m *NetConnectionsMetric) GetDefaultMax() float64

func (*NetConnectionsMetric) GetDescription

func (m *NetConnectionsMetric) GetDescription() string

func (*NetConnectionsMetric) GetLoad

func (m *NetConnectionsMetric) GetLoad() (val float64, err error)

func (*NetConnectionsMetric) GetMetricName

func (m *NetConnectionsMetric) GetMetricName() string

func (*NetConnectionsMetric) GetMinInterval

func (m *NetConnectionsMetric) GetMinInterval() int

type NullWriter

type NullWriter struct{}

NullWriter is an I/O writer which does nothing, used for creating Loggers that don't log anywhere, so that log output can be selectively discarded without changing logging parameters globally.

func (NullWriter) Write

func (NullWriter) Write([]byte) (int, error)

Write accepts an array of bytes, and does precisely nothing with them.

type ProtocolConnector

type ProtocolConnector interface {
	Listen(fbr *FeedbackResponder) (err error)
	Close() (err error)
}

func NewFeedbackConnector

func NewFeedbackConnector(protocol string) (conn ProtocolConnector, err error)

NewFeedbackConnector creates a new connector for a given protocol and (if required) the configuration path containing the TLS certificate and key.

type ScriptMetric

type ScriptMetric struct {
	ScriptName string
	ScriptPath string
}

func (*ScriptMetric) Configure

func (m *ScriptMetric) Configure(params MetricParams) (err error)

func (*ScriptMetric) GetDefaultMax

func (m *ScriptMetric) GetDefaultMax() float64

func (*ScriptMetric) GetDescription

func (m *ScriptMetric) GetDescription() string

func (*ScriptMetric) GetLoad

func (m *ScriptMetric) GetLoad() (val float64, err error)

func (*ScriptMetric) GetMetricName

func (m *ScriptMetric) GetMetricName() string

func (*ScriptMetric) GetMinInterval

func (m *ScriptMetric) GetMinInterval() int

type StatisticsModel

type StatisticsModel struct {
	// The last value of x received as an observation.
	XLastValue float64 `json:"-"`
	// Count of observations in the current state (n).
	XCount uint64 `json:"-"`
	// The significance-adjusted mean of the observations,
	// where shaping is enabled.
	XReportedLoad float64 `json:"-"`
	// Standard deviation (sigma_x) of the set, cumulatively.
	XStdDev float64 `json:"-"`
	// Z-score of the last observation (XValue)
	ZScoreValue float64 `json:"-"`
	// The current sum of x in the current state.
	XSum float64 `json:"-"`
	// The current sum of x^2 in the current state.
	XSquaredSum float64 `json:"-"`
	// Smallest observation value encountered.
	XMin float64 `json:"-"`
	// Largest observation value encountered.
	XMax float64 `json:"-"`
	// Maximum observations before a recentre is forced.
	XCountLimit uint64 `json:"-"`
	// Current sum of Z-scores within the current Z-window.
	ZScoreSum float64 `json:"-"`
	// Current mean of Z-scores within the current Z-window.
	ZScoreMean float64 `json:"-"`
	// Current count of Z-scores comprising the mean Z-score.
	ZSampleCount uint64 `json:"-"`
	// The 2-tailed Z-value threshold for hypothesis significance;
	// a ZMeanThreshold of 1.0 is treated as (-1.0, +1.0) either side
	// of the mean; e.g a value of 1.0 is a range of 2 sigma.
	ZMeanThreshold float64 `json:"z-threshold"`
	// Number of Z-window samples to take before deciding significance.
	// If zero and a ZMeanThreshold is set, significance will be decided
	// after a single observation.
	ZPredictionInterval uint64 `json:"z-interval"`
	// Was this model recentred during the last observation?
	Recentred bool `json:"-"`
	// Is statistics-based shaping enabled?
	ShapingEnabled bool `json:"-"`
	// Have the model parameters been set, so we don't force to defaults?
	ParamsSet bool `json:"-"`
	// The last weight score computed by the model.
	LastResult int64 `json:"-"`
}

StatisticsModel provides a cumulative-mode calculation model that receives observations from a given system metric, and performs configurable trend analysis on these metrics to detect changes in the metric and calculate the appropriate weight score for use in load balancing applications. It provides a Z-score algorithm that aims to achieve the best of both worlds between direct feedback where there is a 1-to-1 correspondence between the observed metric and the weight, and a moving average approach, by estimating the slope of the data when a statistically significant trend occurs. As it is cumulative, this model has an entirely static footprint.

func (*StatisticsModel) ClearModel

func (model *StatisticsModel) ClearModel()

ClearModel resets to a zero-state for this statistics model without clearing the configuration parameters.

func (*StatisticsModel) GetResult

func (model *StatisticsModel) GetResult() int64

GetResult returns the weight score.

func (*StatisticsModel) HasObservations

func (model *StatisticsModel) HasObservations() bool

HasObservations returns if this model has any data yet to calculate.

func (*StatisticsModel) NewValue

func (model *StatisticsModel) NewValue(value float64)

NewValue observes a new value in the set into the statistics model by adding it into the sum values and recalculating the Z-scores, min-max values, mean and standard deviation.

func (*StatisticsModel) RecentreModel

func (model *StatisticsModel) RecentreModel()

RecentreModel consolidates the current parameter state in the series into a single observation by recentring the statistics.

func (*StatisticsModel) SetDefaultParams

func (model *StatisticsModel) SetDefaultParams()

SetDefaultParams sets the default model parameters, and also sets the flag to tell NewValue that a set of parameters has been configured, which will thereafter stop it from calling again.

type SystemMetric

type SystemMetric interface {
	Configure(params MetricParams) (err error)
	GetLoad() (val float64, err error)
	GetMetricName() string
	GetDescription() string
	GetDefaultMax() float64
	GetMinInterval() int
}

SystemMetric defines a "metric" capable of reporting a load score (0.0-100.0, as a float) to the System Metric Monitor.

func NewMetric

func NewMetric(metric string, params MetricParams, configPath string) (
	mc SystemMetric, err error)

type SystemMonitor

type SystemMonitor struct {
	Name       string           `json:"-"`
	MetricType string           `json:"metric-type"`
	Interval   int              `json:"interval-ms,omitempty"`
	Params     MetricParams     `json:"metric-config,omitempty"`
	SmartShape bool             `json:"smart-shape,omitempty"`
	FilePath   string           `json:"-"`
	StatsModel *StatisticsModel `json:"-"`
	SysMetric  SystemMetric     `json:"-"`
	LastError  error            `json:"-"`
	// contains filtered or unexported fields
}

SystemMonitor defines a System Metric Monitor that measures a parameter on the local system concurrently, with these values passed to a StatisticsModel for cumulative calculation into relative feedback weights.

func NewSystemMonitor

func NewSystemMonitor(name string, metric string, interval int,
	params MetricParams, filePath string, shaping bool) (
	mon *SystemMonitor, err error)

func (*SystemMonitor) Copy

func (monitor *SystemMonitor) Copy() (copy SystemMonitor)

func (*SystemMonitor) CurrentValue

func (monitor *SystemMonitor) CurrentValue() (result int64)

CurrentValue returns the current raw value for this monitor thread.

func (*SystemMonitor) Initialise

func (monitor *SystemMonitor) Initialise() (err error)

func (*SystemMonitor) IsRunning

func (monitor *SystemMonitor) IsRunning() (state bool)

func (*SystemMonitor) Restart

func (monitor *SystemMonitor) Restart() (err error)

Restart restarts this SystemMonitor service.

func (*SystemMonitor) Start

func (monitor *SystemMonitor) Start() (err error)

Start launches this SystemMonitor as a goroutine, returning any errors that occurred during the initial setup.

func (*SystemMonitor) Stop

func (monitor *SystemMonitor) Stop() (err error)

Stop stops this SystemMonitor service.

type TCPConnector

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

func (*TCPConnector) Close

func (pc *TCPConnector) Close() (err error)

func (*TCPConnector) Listen

func (pc *TCPConnector) Listen(fbr *FeedbackResponder) (err error)

type ThresholdMode

type ThresholdMode int
const (
	ThresholdModeAny ThresholdMode = iota
	ThresholdModeNone
	ThresholdModeOverallOnly
	ThresholdModeMetricOnly
)

Jump to

Keyboard shortcuts

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