facts

package
v0.0.0-...-48273b5 Latest Latest
Warning

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

Go to latest
Published: Nov 19, 2024 License: Apache-2.0 Imports: 35 Imported by: 0

Documentation

Index

Constants

View Source
const (
	FactKubernetesCluster = "kubernetes_cluster_name"
	FactUpdatedAt         = "fact_updated_at"
)

Variables

View Source
var ErrContainerDoesNotExists = errors.New("the container doesn't exist but process seems to belong to a container")

ErrContainerDoesNotExists is the default error value when a container does not exists.

Functions

func ByteCountDecimal

func ByteCountDecimal(b uint64) string

func CleanFacts

func CleanFacts(facts map[string]string)

CleanFacts will remove key with empty values and truncate value with 100 characters or more.

func ContainerIgnoredPorts

func ContainerIgnoredPorts(c Container) map[int]bool

ContainerIgnoredPorts return ports ignored by a container.

func LabelsAndAnnotations

func LabelsAndAnnotations(c Container) map[string]string

LabelsAndAnnotations return labels and annotations merged. Annotation take precedence over labels.

func NewNoRuntimeError

func NewNoRuntimeError(err error) error

func PendingSystemUpdate

func PendingSystemUpdate(ctx context.Context, inContainer bool, hostRootPath string) (pendingUpdates int, pendingSecurityUpdates int)

PendingSystemUpdate return the number of pending update & pending security update for the system. If the value of a field is -1, it means that value is unknown.

func PendingSystemUpdateFreshness

func PendingSystemUpdateFreshness(_ context.Context, inContainer bool, hostRootPath string) time.Time

PendingSystemUpdateFreshness return the indicative value for last update of the preferred method. It could be zero if the preferred method don't have any cache or we can't determine the freshness value.

Types

type CPUUsage

type CPUUsage struct {
	User      float64 `json:"user"`
	Nice      float64 `json:"nice"`
	System    float64 `json:"system"`
	Idle      float64 `json:"idle"`
	IOWait    float64 `json:"iowait"`
	Guest     float64 `json:"guest"`
	GuestNice float64 `json:"guest_nice"`
	IRQ       float64 `json:"irq"`
	SoftIRQ   float64 `json:"softirq"`
	Steal     float64 `json:"steal"`
}

CPUUsage contains usage of CPU.

type ConfidenceLevel

type ConfidenceLevel int

ConfidenceLevel describe how confident a provided is about information returned.

const (
	ConfidenceHigh ConfidenceLevel = iota + 1
	ConfidenceMedium
	ConfidenceLow
)

List of possible confidence level.

type Container

type Container interface {
	Annotations() map[string]string
	Command() []string
	ContainerJSON() string
	ContainerName() string
	CreatedAt() time.Time
	Environment() map[string]string
	FinishedAt() time.Time
	Health() (ContainerHealth, string)
	ID() string
	ImageID() string
	ImageName() string
	// Labels returns the container labels. They must not be mutated.
	Labels() map[string]string
	ListenAddresses() []ListenAddress
	LogPath() string
	PodName() string
	PodNamespace() string
	PrimaryAddress() string
	StartedAt() time.Time
	State() ContainerState
	StoppedAndReplaced() bool
	RuntimeName() string
	PID() int
}

Container is an interface that defines all the information retrievable of a container.

type ContainerEvent

type ContainerEvent struct {
	Type        EventType
	ContainerID string
	Container   Container
}

ContainerEvent encapsulates an event related to a container.

type ContainerFilter

type ContainerFilter struct {
	DisabledByDefault bool
	AllowList         []string
	DenyList          []string
}

func (ContainerFilter) ContainerEnabled

func (cf ContainerFilter) ContainerEnabled(c Container) (enabled bool, explicit bool)

ContainerEnabled returns true if this container should be monitored by Glouton. Also return a 2nd boolean telling is this container is explicitly enabled or if it's the default.

func (ContainerFilter) ContainerIgnored

func (cf ContainerFilter) ContainerIgnored(c Container) bool

ContainerIgnored return true if a container is ignored by Glouton.

type ContainerHealth

type ContainerHealth int

ContainerHealth is the health status.

const (
	// ContainerHealthUnknown is the default state value.
	ContainerHealthUnknown ContainerHealth = iota
	// ContainerStarting is the value for which the container status is starting.
	ContainerStarting
	// ContainerHealthy is the value for which the container status is healthy.
	ContainerHealthy
	// ContainerUnhealthy is the value for which the container status is unhealthy.
	ContainerUnhealthy
	// ContainerNoHealthCheck is the value for which the container status indicates not health check.
	ContainerNoHealthCheck
)

type ContainerRuntimeProcessQuerier

type ContainerRuntimeProcessQuerier interface {
	// Processes could be unimplemented. Return empty processes and nil as error
	Processes(ctx context.Context) ([]Process, error)
	ContainerFromCGroup(ctx context.Context, cgroupData string) (Container, error)
	ContainerFromPID(ctx context.Context, parentContainerID string, pid int) (Container, error)
}

ContainerRuntimeProcessQuerier encapsulates queries about containers information.

type ContainerState

type ContainerState int

ContainerState is the container lifecycle state.

const (
	// ContainerUnknown is the default container state.
	ContainerUnknown ContainerState = iota
	// ContainerCreated is the state in which a container was just created.
	ContainerCreated
	// ContainerRunning is the state in which a container is currently running.
	ContainerRunning
	// ContainerRestarting is the state in which a container is restarting.
	ContainerRestarting
	// ContainerStopped is the state in which a container was stopped.
	ContainerStopped
)

func (ContainerState) IsRunning

func (st ContainerState) IsRunning() bool

IsRunning checks if a container is currently in a running state.

func (ContainerState) String

func (st ContainerState) String() string

String returns the container state as string.

type EventType

type EventType int

EventType is the container event.

const (
	// EventTypeUnknown is the default event value.
	EventTypeUnknown EventType = iota
	// EventTypeCreate is the event type for which the event is "Create".
	EventTypeCreate
	// EventTypeStart is the event type for which the event is "Start".
	EventTypeStart
	// EventTypeKill is the event type for which the event is "Kill".
	EventTypeKill
	// EventTypeStop is the event type for which the event is "Stop".
	EventTypeStop
	// EventTypeDelete is the event type for which the event is "Delete".
	EventTypeDelete
	// EventTypeHealth is the event type for which the event is "Health".
	EventTypeHealth
)

type FactCallback

type FactCallback func(ctx context.Context, currentFact map[string]string) map[string]string

FactCallback is a function called on each update of facts that may return additional facts.

It returns the list of new or updated facts.

type FactProvider

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

FactProvider provider information about system. Mostly static facts like OS version, architecture, ...

It also possible to define fixed facts that this provider won't discover. This is useful for fact like "featureX_enabled" that other part of the code may set.

There is also the possibility to add callback that are called on each update.

There is one special fact named "fact_updated_at" which contains the last update of the facts.

func NewFacter

func NewFacter(factPath, hostRootPath, ipIndicatorURL string) *FactProvider

NewFacter creates a new Fact provider

factPath is the path to a yaml file that contains additional facts, usually facts that require root privilege to be read.

hostRootPath is the path where host filesystem is visible. When running outside any container, it should be "/". When running inside a container it should be the path where host root is mounted.

ipIndicatorURL is and URL which return the public IP.

func (*FactProvider) AddCallback

func (f *FactProvider) AddCallback(cb FactCallback)

AddCallback adds a FactCallback to provide additional facts. It currently not possible to remove a callback.

func (*FactProvider) Facts

func (f *FactProvider) Facts(ctx context.Context, maxAge time.Duration) (facts map[string]string, err error)

Facts returns the list of facts for this system.

func (*FactProvider) FastFacts

func (f *FactProvider) FastFacts(ctx context.Context) (facts map[string]string, err error)

FastFacts returns an incomplete list of facts for this system. The slowest facts are not executed in order to improve the starting time.

func (*FactProvider) SetFact

func (f *FactProvider) SetFact(key string, value string)

SetFact override/add a manual facts

Any fact set using this method is valid until next call to SetFact.

type FactProviderMock

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

FactProviderMock provides only hardcoded facts but is useful for testing.

func NewMockFacter

func NewMockFacter(facts map[string]string) *FactProviderMock

NewMockFacter creates a new lying Fact provider.

func (*FactProviderMock) Facts

func (f *FactProviderMock) Facts(_ context.Context, maxAge time.Duration) (facts map[string]string, err error)

Facts returns the list of facts for this system.

func (*FactProviderMock) SetFact

func (f *FactProviderMock) SetFact(key string, value string)

SetFact override/add a manual facts

Any fact set using this method is valid until next call to SetFact.

type FakeContainer

type FakeContainer struct {
	FakeRuntimeName        string
	FakeAnnotations        map[string]string
	FakeCommand            []string
	FakeContainerJSON      string
	FakeContainerName      string
	FakeCreatedAt          time.Time
	FakeEnvironment        map[string]string
	FakeFinishedAt         time.Time
	FakeHealth             ContainerHealth
	FakeHealthMessage      string
	FakeID                 string
	FakeImageID            string
	FakeImageName          string
	FakeLabels             map[string]string
	FakeListenAddresses    []ListenAddress
	FakeLogPath            string
	FakePodName            string
	FakePodNamespace       string
	FakePrimaryAddress     string
	FakeStartedAt          time.Time
	FakeState              ContainerState
	FakeStoppedAndReplaced bool
	FakePID                int

	// Test* flags are only used by tests
	TestIgnored bool
	TestHasPod  bool
}

FakeContainer is a structure used to emulate containers for tests purposes It is defined in this file instead of the test file because it is used by multiples tests files.

func (FakeContainer) Annotations

func (c FakeContainer) Annotations() map[string]string

func (FakeContainer) Command

func (c FakeContainer) Command() []string

func (FakeContainer) ContainerJSON

func (c FakeContainer) ContainerJSON() string

func (FakeContainer) ContainerName

func (c FakeContainer) ContainerName() string

func (FakeContainer) CreatedAt

func (c FakeContainer) CreatedAt() time.Time

func (FakeContainer) Diff

func (c FakeContainer) Diff(other Container) string

func (FakeContainer) Environment

func (c FakeContainer) Environment() map[string]string

func (FakeContainer) FinishedAt

func (c FakeContainer) FinishedAt() time.Time

func (FakeContainer) Health

func (c FakeContainer) Health() (ContainerHealth, string)

func (FakeContainer) ID

func (c FakeContainer) ID() string

func (FakeContainer) ImageID

func (c FakeContainer) ImageID() string

func (FakeContainer) ImageName

func (c FakeContainer) ImageName() string

func (FakeContainer) Labels

func (c FakeContainer) Labels() map[string]string

func (FakeContainer) ListenAddresses

func (c FakeContainer) ListenAddresses() []ListenAddress

func (FakeContainer) LogPath

func (c FakeContainer) LogPath() string

func (FakeContainer) PID

func (c FakeContainer) PID() int

func (FakeContainer) PodName

func (c FakeContainer) PodName() string

func (FakeContainer) PodNamespace

func (c FakeContainer) PodNamespace() string

func (FakeContainer) PrimaryAddress

func (c FakeContainer) PrimaryAddress() string

func (FakeContainer) RuntimeName

func (c FakeContainer) RuntimeName() string

func (FakeContainer) StartedAt

func (c FakeContainer) StartedAt() time.Time

func (FakeContainer) State

func (c FakeContainer) State() ContainerState

func (FakeContainer) StoppedAndReplaced

func (c FakeContainer) StoppedAndReplaced() bool

type ListenAddress

type ListenAddress struct {
	NetworkFamily string
	Address       string
	Port          int
}

ListenAddress is net.Addr implmentation.

func (ListenAddress) Network

func (l ListenAddress) Network() string

Network is the method from net.Addr.

func (ListenAddress) String

func (l ListenAddress) String() string

type MemoryUsage

type MemoryUsage struct {
	Total   float64 `json:"total"`
	Used    float64 `json:"used"`
	Free    float64 `json:"free"`
	Buffers float64 `json:"buffers"`
	Cached  float64 `json:"cached"`
}

MemoryUsage contains usage of Memory.

type NetstatProvider

type NetstatProvider struct {
	FilePath string
}

NetstatProvider provide netstat information from both a file (output of netstat command) and using gopsutil

The file is useful since gopsutil will be run with current privilege which are unlikely to be root. The file should be the output of netstat run as root.

func (NetstatProvider) Netstat

func (np NetstatProvider) Netstat(_ context.Context, processes map[int]Process) (netstat map[int][]ListenAddress, err error)

Netstat return a mapping from PID to listening addresses

Supported addresses network is currently "tcp", "udp" or "unix".

type NoRuntimeError

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

NoRuntimeError wraps an error from a container when the error likely indicates that runtime isn't running.

func (NoRuntimeError) Error

func (e NoRuntimeError) Error() string

func (NoRuntimeError) Unwrap

func (e NoRuntimeError) Unwrap() error

type Process

type Process struct {
	PID             int           `json:"pid"`
	PPID            int           `json:"ppid"`
	CreateTime      time.Time     `json:"-"`
	CreateTimestamp int64         `json:"create_time"`
	CmdLineList     []string      `json:"-"`
	CmdLine         string        `json:"cmdline"`
	Name            string        `json:"name"`
	MemoryRSS       uint64        `json:"memory_rss"`
	CPUPercent      float64       `json:"cpu_percent"`
	CPUTime         float64       `json:"cpu_times"`
	Status          ProcessStatus `json:"status"`
	Username        string        `json:"username"`
	Executable      string        `json:"exe"`
	ContainerID     string        `json:"-"`
	ContainerName   string        `json:"instance"`
	NumThreads      int           `json:"num_threads"`
}

Process describe one Process.

func (*Process) Update

func (p *Process) Update(other Process)

Update update self taking any non-zero fields from other.

type ProcessLister

type ProcessLister interface {
	Processes(ctx context.Context, maxAge time.Duration) (processes []Process, err error)
}

ProcessLister return a list of Process. Some fields won't be used and will be filled by ProcessProvider. For example Container or CPUPercent.

type ProcessProvider

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

ProcessProvider provider information about processes.

func NewProcess

func NewProcess(pslister ProcessLister, cr containerRuntime) *ProcessProvider

NewProcess creates a new Process provider

Docker provider should be given to allow processes to be associated with a Docker container. useProc should be true if the Agent see all processes (running outside container or with host PID namespace).

func (*ProcessProvider) Processes

func (pp *ProcessProvider) Processes(ctx context.Context, maxAge time.Duration) (processes map[int]Process, err error)

Processes returns the list of processes present on this system.

It may use a cached value as old as maxAge.

func (*ProcessProvider) ProcessesWithTime

func (pp *ProcessProvider) ProcessesWithTime(ctx context.Context, maxAge time.Duration) (processes map[int]Process, updateAt time.Time, err error)

ProcessesWithTime returns the list of processes present on this system and the date of last update

It the same as Processes but also return the date of last update.

func (*ProcessProvider) TopInfo

func (pp *ProcessProvider) TopInfo(ctx context.Context, maxAge time.Duration) (topinfo TopInfo, err error)

TopInfo returns a topinfo object

It may use a cached value as old as maxAge.

type ProcessStatus

type ProcessStatus string
const (
	ProcessStatusRunning     ProcessStatus = "running"
	ProcessStatusSleeping    ProcessStatus = "sleeping"
	ProcessStatusStopped     ProcessStatus = "stopped"
	ProcessStatusIdle        ProcessStatus = "idle"
	ProcessStatusZombie      ProcessStatus = "zombie"
	ProcessStatusIOWait      ProcessStatus = "disk-sleep"
	ProcessStatusTracingStop ProcessStatus = "tracing-stop"
	ProcessStatusDead        ProcessStatus = "dead"
	ProcessStatusUnknown     ProcessStatus = "?"
)

func PsStat2Status

func PsStat2Status(psStat string) ProcessStatus

PsStat2Status convert status (value in ps output - or in /proc/pid/stat) to human status.

type PsutilLister

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

PsutilLister contains the passwd cache information.

func NewPsUtilLister

func NewPsUtilLister(hostRootPath string) PsutilLister

NewPsUtilLister creates and populate a PsUtilLister.

func (PsutilLister) Processes

func (z PsutilLister) Processes(ctx context.Context, maxAge time.Duration) (processes []Process, err error)

Processes retrieves the list of all the current processes and their respective information.

type SwapUsage

type SwapUsage struct {
	Total float64 `json:"total"`
	Used  float64 `json:"used"`
	Free  float64 `json:"free"`
}

SwapUsage contains usage of Swap.

type SystemProcessInformationStruct

type SystemProcessInformationStruct struct {
	NextEntryOffset              uint32
	NumberOfThreads              uint32
	WorkingSetPrivateSize        int64
	HardFaultCount               uint32
	NumberOfThreadsHighWatermark uint32
	CycleTime                    uint64
	CreateTime                   int64
	UserTime                     int64
	KernelTime                   int64
	ImageName                    UnicodeString
	BasePriority                 int32
	UniqueProcessID              uintptr
	InheritedFromUniqueProcessID uintptr
	HandleCount                  uint32
	SessionID                    uint32
	PageDirectoryBase            uintptr
	PeakVirtualSize              uintptr
	VirtualSize                  uintptr
	PageFaultCount               uint32
	PeakWorkingSetSize           uintptr
	WorkingSetSize               uintptr
	QuotaPeakPagedPoolUsage      uintptr
	QuotaPagedPoolUsage          uintptr
	QuotaPeakNonPagedPoolUsage   uintptr
	QuotaNonPagedPoolUsage       uintptr
	PagefileUsage                uintptr
	PeakPagefileUsage            uintptr
	PrivatePageCount             uintptr
	ReadOperationCount           int64
	WriteOperationCount          int64
	OtherOperationCount          int64
	ReadTransferCount            int64
	WriteTransferCount           int64
	OtherTransferCount           int64
}

SystemProcessInformationStruct is windows-specific, necessary for running assertions on its size

type TopInfo

type TopInfo struct {
	Time                   int64                 `json:"time"`
	Uptime                 int                   `json:"uptime"`
	Loads                  []float64             `json:"loads"`
	Users                  int                   `json:"users"`
	Processes              []Process             `json:"processes"`
	CPU                    CPUUsage              `json:"cpu"`
	Memory                 MemoryUsage           `json:"memory"`
	Swap                   SwapUsage             `json:"swap"`
	ProcessListTruncatedAt *int                  `json:"process_list_truncated_at"`
	ProcessesCount         map[ProcessStatus]int `json:"processes_count"`
}

TopInfo contains all information to show a top-like view.

type UnicodeString

type UnicodeString struct {
	Length        uint16
	MaximumLength uint16

	Buffer unsafe.Pointer
	// contains filtered or unexported fields
}

UnicodeString represents an unicode string.

Directories

Path Synopsis
container-runtime
kubernetes
Package kubernetes isn't really a container runtime but wraps one to add information from PODs
Package kubernetes isn't really a container runtime but wraps one to add information from PODs
merge
Package merge will merge multiple container runtime.
Package merge will merge multiple container runtime.

Jump to

Keyboard shortcuts

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