containercollection

package
v0.12.1 Latest Latest
Warning

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

Go to latest
Published: Jan 2, 2023 License: Apache-2.0 Imports: 29 Imported by: 3

Documentation

Overview

Package containercollection provides the ContainerCollection struct to keep track of the set of running containers and primitives to query that set with various criteria.

It is used by the Gadget Tracer Manager to keep track of containers part of Kubernetes pods and by Local Gadget Manager to keep track of containers on a Linux system.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ContainerSelectorMatches

func ContainerSelectorMatches(s *ContainerSelector, c *Container) bool

ContainerSelectorMatches tells if a container matches the criteria in a container selector.

func GetColumns

func GetColumns() *columns.Columns[Container]

Types

type Container

type Container struct {
	// Container Runtime
	Runtime string `json:"runtime,omitempty" column:"runtime,minWidth:5,maxWidth:10" columnTags:"runtime"`

	// ID is the container id, typically a 64 hexadecimal string
	ID string `json:"id,omitempty" column:"id,width:13,maxWidth:64" columnTags:"runtime"`

	// Pid is the process id of the container
	Pid uint32 `json:"pid,omitempty" column:"pid,template:pid,hide"`

	// Container's configuration is the config.json from the OCI runtime
	// spec
	OciConfig *ocispec.Spec `json:"ociConfig,omitempty"`

	// Bundle is the directory containing the config.json from the OCI
	// runtime spec
	// See https://github.com/opencontainers/runtime-spec/blob/main/bundle.md
	Bundle string `json:"bundle,omitempty"`

	// Linux metadata can be derived from the pid via /proc/$pid/...
	Mntns       uint64 `json:"mntns,omitempty" column:"mntns,template:ns"`
	Netns       uint64 `json:"netns,omitempty" column:"netns,template:ns"`
	HostNetwork bool   `json:"hostNetwork,omitempty" column:"hostNetwork,width:11,fixed,hide"`
	CgroupPath  string `json:"cgroupPath,omitempty"`
	CgroupID    uint64 `json:"cgroupID,omitempty"`
	// Data required to find the container to Pod association in the
	// gadgettracermanager.
	CgroupV1 string `json:"cgroupV1,omitempty"`
	CgroupV2 string `json:"cgroupV2,omitempty"`

	// Kubernetes metadata
	Namespace string            `json:"namespace,omitempty"`
	Podname   string            `json:"podname,omitempty"`
	Name      string            `json:"name,omitempty" column:"name,width:30" columnTags:"runtime"`
	Labels    map[string]string `json:"labels,omitempty"`
	PodUID    string            `json:"podUID,omitempty"`
	// contains filtered or unexported fields
}

Container represents a container with its metadata.

func (*Container) GetOwnerReference

func (c *Container) GetOwnerReference() (*metav1.OwnerReference, error)

GetOwnerReference returns the owner reference information of the container. Currently it's added to the seccomp profile as annotations to help users to identify the workflow of the profile. We "lazily enrich" this information because this operation is expensive and this information is only needed in some cases.

func (*Container) IsEnriched added in v0.11.0

func (c *Container) IsEnriched() bool

type ContainerCollection

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

ContainerCollection holds a set of containers. It can be embedded as an anonymous struct to help other structs implement the ContainerResolver interface. For this reason, some methods are namespaced with 'Container' to make this clear.

func (*ContainerCollection) AddContainer

func (cc *ContainerCollection) AddContainer(container *Container)

AddContainer adds a container to the collection.

func (*ContainerCollection) Close

func (cc *ContainerCollection) Close()

func (*ContainerCollection) ContainerLen

func (cc *ContainerCollection) ContainerLen() (count int)

ContainerLen returns how many containers are stored in the collection.

func (*ContainerCollection) ContainerRange

func (cc *ContainerCollection) ContainerRange(f func(*Container))

ContainerRange iterates over the containers of the collection and calls the callback function for each of them.

func (*ContainerCollection) ContainerRangeWithSelector

func (cc *ContainerCollection) ContainerRangeWithSelector(
	containerSelector *ContainerSelector,
	f func(*Container),
)

ContainerRangeWithSelector iterates over the containers of the collection and calls the callback function for each of those that matches the container selector.

func (*ContainerCollection) Enrich

func (cc *ContainerCollection) Enrich(event *eventtypes.CommonData, mountnsid uint64)

func (*ContainerCollection) GetContainer

func (cc *ContainerCollection) GetContainer(id string) *Container

GetContainer looks up a container by the container id and return it if found, or return nil if not found.

func (*ContainerCollection) GetContainersBySelector

func (cc *ContainerCollection) GetContainersBySelector(
	containerSelector *ContainerSelector,
) []*Container

GetContainersBySelector returns a slice of containers that match the selector or an empty slice if there are not matches

func (*ContainerCollection) Initialize

func (cc *ContainerCollection) Initialize(options ...ContainerCollectionOption) error

Initialize initializes a ContainerCollection. It is useful when ContainerCollection is embedded as an anonymous struct because we don't use a contructor in that case.

func (*ContainerCollection) LookupContainerByMntns

func (cc *ContainerCollection) LookupContainerByMntns(mntnsid uint64) *Container

LookupContainerByMntns returns a container by its mount namespace inode id. If not found nil is returned.

func (*ContainerCollection) LookupMntnsByContainer

func (cc *ContainerCollection) LookupMntnsByContainer(namespace, pod, container string) (mntns uint64)

LookupMntnsByContainer returns the mount namespace inode of the container specified in arguments or zero if not found

func (*ContainerCollection) LookupMntnsByPod

func (cc *ContainerCollection) LookupMntnsByPod(namespace, pod string) map[string]uint64

LookupMntnsByPod returns the mount namespace inodes of all containers belonging to the pod specified in arguments, indexed by the name of the containers or an empty map if not found

func (*ContainerCollection) LookupOwnerReferenceByMntns

func (cc *ContainerCollection) LookupOwnerReferenceByMntns(mntns uint64) *metav1.OwnerReference

LookupOwnerReferenceByMntns returns a pointer to the owner reference of the container identified by the mount namespace, or nil if not found

func (*ContainerCollection) LookupPIDByContainer

func (cc *ContainerCollection) LookupPIDByContainer(namespace, pod, container string) (pid uint32)

LookupPIDByContainer returns the PID of the container specified in arguments or zero if not found

func (*ContainerCollection) LookupPIDByPod

func (cc *ContainerCollection) LookupPIDByPod(namespace, pod string) map[string]uint32

LookupPIDByPod returns the PID of all containers belonging to the pod specified in arguments, indexed by the name of the containers or an empty map if not found

func (*ContainerCollection) RemoveContainer

func (cc *ContainerCollection) RemoveContainer(id string)

RemoveContainer removes a container from the collection.

func (*ContainerCollection) Subscribe

func (cc *ContainerCollection) Subscribe(key interface{}, selector ContainerSelector, f FuncNotify) []*Container

Subscribe returns the list of existing containers and registers a callback for notifications about additions and deletions of containers

func (*ContainerCollection) Unsubscribe

func (cc *ContainerCollection) Unsubscribe(key interface{})

Unsubscribe undoes a previous call to Subscribe

type ContainerCollectionOption

type ContainerCollectionOption func(*ContainerCollection) error

ContainerCollectionOption are options to pass to Initialize using the functional option code pattern.

func WithCgroupEnrichment

func WithCgroupEnrichment() ContainerCollectionOption

WithCgroupEnrichment enables an enricher to add the cgroup metadata

func WithContainerRuntimeEnrichment

func WithContainerRuntimeEnrichment(runtime *containerutils.RuntimeConfig) ContainerCollectionOption

WithContainerRuntimeEnrichment automatically adds the container name using the requested container runtime.

Pay attention if you want to use it with other enrichers that set the Kubernetes metadata as this enricher also collects such info from the runtime. Notice also that, if such info is missing in the runtime, it hardcodes the namespace to "default" and the podname equal to the container name because some gadgets need those two values to be set.

ContainerCollection.Initialize(WithContainerRuntimeEnrichment(*RuntimeConfig))

func WithFallbackPodInformer

func WithFallbackPodInformer(nodeName string) ContainerCollectionOption

WithFallbackPodInformer uses a pod informer as a fallback mechanism to a main hook. If the podinformer detects a new container and it hasn't been added to the list of containers it means the main hook is not working fine. We warn the user about it.

func WithInitialKubernetesContainers

func WithInitialKubernetesContainers(nodeName string) ContainerCollectionOption

WithInitialKubernetesContainers gets initial containers from the Kubernetes API with the process ID from CRI.

This cannot be used together with WithPodInformer() since the pod informer already gets initial containers.

func WithKubernetesEnrichment

func WithKubernetesEnrichment(nodeName string, kubeconfig *rest.Config) ContainerCollectionOption

WithKubernetesEnrichment automatically adds pod metadata

ContainerCollection.Initialize(WithKubernetesEnrichment())

func WithLinuxNamespaceEnrichment

func WithLinuxNamespaceEnrichment() ContainerCollectionOption

WithLinuxNamespaceEnrichment enables an enricher to add the namespaces metadata

func WithMultipleContainerRuntimesEnrichment

func WithMultipleContainerRuntimesEnrichment(runtimes []*containerutils.RuntimeConfig) ContainerCollectionOption

WithMultipleContainerRuntimesEnrichment is a wrapper for WithContainerRuntimeEnrichment() to allow caller to add multiple runtimes in one single call.

ContainerCollection.Initialize(WithMultipleContainerRuntimesEnrichment([]*RuntimeConfig)...)

func WithNodeName

func WithNodeName(nodeName string) ContainerCollectionOption

func WithOCIConfigEnrichment added in v0.11.0

func WithOCIConfigEnrichment() ContainerCollectionOption

WithOCIConfigEnrichment enriches container using provided OCI config

func WithPodInformer

func WithPodInformer(nodeName string) ContainerCollectionOption

WithPodInformer uses a pod informer to get both initial containers and the stream of container events. It then uses the CRI interface to get the process ID.

This cannot be used together with WithInitialKubernetesContainers() since the pod informer already gets initial containers.

func WithPubSub

func WithPubSub(funcs ...FuncNotify) ContainerCollectionOption

WithPubSub enables subscription with container events with Subscribe(). Optionally, a list of callbacks can be registered from the beginning, so they would get called for initial containers too.

func WithRuncFanotify

func WithRuncFanotify() ContainerCollectionOption

WithRuncFanotify uses fanotify to detect when containers are created and add them in the ContainerCollection.

ContainerCollection.Initialize(WithRuncFanotify())

type ContainerResolver

type ContainerResolver interface {
	// LookupMntnsByContainer returns the mount namespace inode of the container
	// specified in arguments or zero if not found
	LookupMntnsByContainer(namespace, pod, container string) uint64

	// LookupContainerByMntns returns a container by its mount namespace
	// inode id. If not found nil is returned.
	LookupContainerByMntns(mntnsid uint64) *Container

	// LookupMntnsByPod returns the mount namespace inodes of all containers
	// belonging to the pod specified in arguments, indexed by the name of the
	// containers or an empty map if not found
	LookupMntnsByPod(namespace, pod string) map[string]uint64

	// LookupPIDByContainer returns the PID of the container
	// specified in arguments or zero if not found
	LookupPIDByContainer(namespace, pod, container string) uint32

	// LookupPIDByPod returns the PID of all containers belonging to
	// the pod specified in arguments, indexed by the name of the
	// containers or an empty map if not found
	LookupPIDByPod(namespace, pod string) map[string]uint32

	// LookupOwnerReferenceByMntns returns a pointer to the owner reference of the
	// container identified by the mount namespace, or nil if not found
	LookupOwnerReferenceByMntns(mntns uint64) *metav1.OwnerReference

	// GetContainersBySelector returns a slice of containers that match
	// the selector or an empty slice if there are not matches
	GetContainersBySelector(containerSelector *ContainerSelector) []*Container

	// Subscribe returns the list of existing containers and registers a
	// callback for notifications about additions and deletions of
	// containers
	Subscribe(key interface{}, s ContainerSelector, f FuncNotify) []*Container

	// Unsubscribe undoes a previous call to Subscribe
	Unsubscribe(key interface{})
}

ContainerResolver offers primitives to look up running containers with various criteria, and to subscribe to container creation and termination.

type ContainerSelector

type ContainerSelector struct {
	Namespace string
	Podname   string
	Labels    map[string]string
	Name      string
}

type EventType

type EventType int
const (
	EventTypeAddContainer EventType = iota
	EventTypeRemoveContainer
)

func EventTypeFromString added in v0.12.0

func EventTypeFromString(s string) EventType

func (*EventType) MarshalText added in v0.12.0

func (e *EventType) MarshalText() (text []byte, err error)

func (*EventType) String added in v0.12.0

func (e *EventType) String() string

func (*EventType) UnmarshalText added in v0.12.0

func (e *EventType) UnmarshalText(bytes []byte) error

type FuncNotify

type FuncNotify func(event PubSubEvent)

type GadgetPubSub

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

GadgetPubSub provides a synchronous publish subscribe mechanism for gadgets to be informed of container creation and deletion. It needs to be synchronous so that gadgets have time to attach their tracer before the container is started.

func NewGadgetPubSub

func NewGadgetPubSub() *GadgetPubSub

func (*GadgetPubSub) Publish

func (g *GadgetPubSub) Publish(eventType EventType, container *Container)

func (*GadgetPubSub) Subscribe

func (g *GadgetPubSub) Subscribe(key interface{}, callback FuncNotify, initializer func())

Subscribe registers the callback to be called for every container event published with Publish(). Optionally, the caller can pass an initializer() function that is guaranteed to be called before any new container events are published.

func (*GadgetPubSub) Unsubscribe

func (g *GadgetPubSub) Unsubscribe(key interface{})

type K8sClient

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

func NewK8sClient

func NewK8sClient(nodeName string) (*K8sClient, error)

func (*K8sClient) Close

func (k *K8sClient) Close()

func (*K8sClient) GetNonRunningContainers

func (k *K8sClient) GetNonRunningContainers(pod *v1.Pod) []string

GetNonRunningContainers returns the list of containers IDs that are not running.

func (*K8sClient) ListContainers

func (k *K8sClient) ListContainers() (arr []Container, err error)

ListContainers return a list of the current containers that are running in the node.

func (*K8sClient) PodToContainers

func (k *K8sClient) PodToContainers(pod *v1.Pod) []Container

PodToContainers returns a list of the containers of a given Pod. Containers that are not running or don't have an ID are not considered.

type PodInformer

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

func NewPodInformer

func NewPodInformer(node string) (*PodInformer, error)

func (*PodInformer) CreatedChan

func (p *PodInformer) CreatedChan() <-chan *v1.Pod

func (*PodInformer) DeletedChan

func (p *PodInformer) DeletedChan() <-chan string

func (*PodInformer) Run

func (p *PodInformer) Run(threadiness int, stopCh chan struct{})

func (*PodInformer) Stop

func (p *PodInformer) Stop()

type PubSubEvent

type PubSubEvent struct {
	Timestamp string     `json:"timestamp,omitempty" column:"timestamp,maxWidth:30" columnTags:"runtime"`
	Type      EventType  `json:"event" column:"event,maxWidth:10" columnTags:"runtime"`
	Container *Container `json:"container"`
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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