cache

package
v0.1.4 Latest Latest
Warning

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

Go to latest
Published: Oct 27, 2020 License: Apache-2.0 Imports: 24 Imported by: 0

Documentation

Overview

Package cache implements lightweight Kubernetes cluster caching that stores only resource references and ownership references. In addition to references cache might be configured to store custom metadata and whole body of selected resources.

The library uses Kubernetes watch API to maintain cache up to date. This approach reduces number of Kubernetes API requests and provides instant access to the required Kubernetes resources.

Index

Examples

Constants

View Source
const (
	ClusterRetryTimeout = 10 * time.Second
)

Variables

This section is empty.

Functions

func NewClusterCache

func NewClusterCache(config *rest.Config, opts ...func(cache *clusterCache)) *clusterCache

NewClusterCache creates new instance of cluster cache

Example (InspectNamespaceResources)
// kubernetes cluster config here
config := &rest.Config{}

clusterCache := NewClusterCache(config,
	// cache default namespace only
	SetNamespaces([]string{"default", "kube-system"}),
	// configure custom logic to cache resources manifest and additional metadata
	SetPopulateResourceInfoHandler(func(un *unstructured.Unstructured, isRoot bool) (info interface{}, cacheManifest bool) {
		// if resource belongs to 'extensions' group then mark if with 'deprecated' label
		if un.GroupVersionKind().Group == "extensions" {
			info = []string{"deprecated"}
		}
		_, ok := un.GetLabels()["acme.io/my-label"]
		// cache whole manifest if resource has label
		cacheManifest = ok
		return
	}),
)
// Ensure cluster is synced before using it
if err := clusterCache.EnsureSynced(); err != nil {
	panic(err)
}
// Iterate default namespace resources tree
for _, root := range clusterCache.GetNamespaceTopLevelResources("default") {
	clusterCache.IterateHierarchy(root.ResourceKey(), func(resource *Resource, _ map[kube.ResourceKey]*Resource) {
		println(fmt.Sprintf("resource: %s, info: %v", resource.Ref.String(), resource.Info))
	})
}
Output:

Example (ResourceUpdatedEvents)
// kubernetes cluster config here
config := &rest.Config{}

clusterCache := NewClusterCache(config)
// Ensure cluster is synced before using it
if err := clusterCache.EnsureSynced(); err != nil {
	panic(err)
}
unsubscribe := clusterCache.OnResourceUpdated(func(newRes *Resource, oldRes *Resource, _ map[kube.ResourceKey]*Resource) {
	if newRes == nil {
		println(fmt.Sprintf("%s deleted", oldRes.Ref.String()))
	} else if oldRes == nil {
		println(fmt.Sprintf("%s created", newRes.Ref.String()))
	} else {
		println(fmt.Sprintf("%s updated", newRes.Ref.String()))
	}
})
defer unsubscribe()
// observe resource modifications for 1 minute
time.Sleep(time.Minute)
Output:

func SetKubectl

func SetKubectl(kubectl kube.Kubectl) func(cache *clusterCache)

SetKubectl allows to override kubectl wrapper implementation

func SetMaxConcurrentList

func SetMaxConcurrentList(val int64)

SetMaxConcurrentList set maximum number of concurrent K8S list calls. If set to 0 then no limit is enforced. Note: method is not thread safe. Use it during initialization before executing ClusterCache.EnsureSynced method.

Types

type ClusterCache

type ClusterCache interface {
	// EnsureSynced checks cache state and synchronizes it if necessary
	EnsureSynced() error
	// GetServerVersion returns observed cluster version
	GetServerVersion() string
	// GetAPIGroups returns information about observed API groups
	GetAPIGroups() []metav1.APIGroup
	// Invalidate cache and executes callback that optionally might update cache settings
	Invalidate(opts ...UpdateSettingsFunc)
	// GetNamespaceTopLevelResources returns top level resources in the specified namespace
	GetNamespaceTopLevelResources(namespace string) map[kube.ResourceKey]*Resource
	// IterateHierarchy iterates resource tree starting from the specified top level resource and executes callback for each resource in the tree
	IterateHierarchy(key kube.ResourceKey, action func(resource *Resource, namespaceResources map[kube.ResourceKey]*Resource))
	// IsNamespaced answers if specified group/kind is a namespaced resource API or not
	IsNamespaced(gk schema.GroupKind) (bool, error)
	// GetManagedLiveObjs helps finding matching live K8S resources for a given resources list.
	// The function returns all resources from cache for those `isManaged` function returns true and resources
	// specified in targetObjs list.
	GetManagedLiveObjs(targetObjs []*unstructured.Unstructured, isManaged func(r *Resource) bool) (map[kube.ResourceKey]*unstructured.Unstructured, error)
	// GetClusterInfo returns cluster cache statistics
	GetClusterInfo() ClusterInfo
	// OnResourceUpdated register event handler that is executed every time when resource get's updated in the cache
	OnResourceUpdated(handler OnResourceUpdatedHandler) Unsubscribe
	// OnEvent register event handler that is executed every time when new K8S event received
	OnEvent(handler OnEventHandler) Unsubscribe
}

type ClusterInfo

type ClusterInfo struct {
	// Server holds cluster API server URL
	Server string
	// K8SVersion holds Kubernetes version
	K8SVersion string
	// ResourcesCount holds number of observed Kubernetes resources
	ResourcesCount int
	// APIsCount holds number of observed Kubernetes API count
	APIsCount int
	// LastCacheSyncTime holds time of most recent cache synchronization
	LastCacheSyncTime *time.Time
	// SyncError holds most recent cache synchronization error
	SyncError error
}

ClusterInfo holds cluster cache stats

type OnEventHandler

type OnEventHandler func(event watch.EventType, un *unstructured.Unstructured)

OnEventHandler is a function that handles Kubernetes event

type OnPopulateResourceInfoHandler

type OnPopulateResourceInfoHandler func(un *unstructured.Unstructured, isRoot bool) (info interface{}, cacheManifest bool)

OnPopulateResourceInfoHandler returns additional resource metadata that should be stored in cache

type OnResourceUpdatedHandler

type OnResourceUpdatedHandler func(newRes *Resource, oldRes *Resource, namespaceResources map[kube.ResourceKey]*Resource)

OnResourceUpdatedHandler handlers resource update event

type Resource

type Resource struct {
	// ResourceVersion holds most recent observed resource version
	ResourceVersion string
	// Resource reference
	Ref v1.ObjectReference
	// References to resource owners
	OwnerRefs []metav1.OwnerReference
	// Optional additional information about the resource
	Info interface{}
	// Optional whole resource manifest
	Resource *unstructured.Unstructured
}

Resource holds the information about Kubernetes resource, ownership references and optional information

func (*Resource) ResourceKey

func (r *Resource) ResourceKey() kube.ResourceKey

type Settings

type Settings struct {
	// ResourceHealthOverride contains health assessment overrides
	ResourceHealthOverride health.HealthOverride
	// ResourcesFilter holds filter that excludes resources
	ResourcesFilter kube.ResourceFilter
}

Settings caching customizations

type Unsubscribe

type Unsubscribe func()

type UpdateSettingsFunc

type UpdateSettingsFunc func(cache *clusterCache)

func SetConfig

func SetConfig(config *rest.Config) UpdateSettingsFunc

SetConfig updates cluster rest config

func SetNamespaces

func SetNamespaces(namespaces []string) UpdateSettingsFunc

SetNamespaces updates list of monitored namespaces

func SetPopulateResourceInfoHandler

func SetPopulateResourceInfoHandler(handler OnPopulateResourceInfoHandler) UpdateSettingsFunc

SetPopulateResourceInfoHandler updates handler that populates resource info

func SetSettings

func SetSettings(settings Settings) UpdateSettingsFunc

SetSettings updates caching settings

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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