lambda

package module
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Apr 16, 2018 License: Apache-2.0 Imports: 26 Imported by: 0

README

Kubernetes Client Lambda

Build Status codecov Go Doc

logo

What is Kubernetes Client Lambda?

Kubernetes Client Lambda (aka KCL) is a wrapper library for kubernetes/client-go. Basically it contains these following feature:

  • Dynamic client & client pool
  • Hide details about client-go's informer and lister.
  • Hide annoying group & versions and use resources as enum.
  • Lambda styled resource filtering & manipulating. (inspired by Groovy)
  • It's really easy to use.

With KCL, you can operate kubernetes resources like this example:

// See doc for more info about lambda functions Grep / Map..
import kubernetes "github.com/yue9944882/kubernetes-client-lambda"

// In-Cluster example
// var kcl kubernetes.KubernetesClientLambda = kubernetes.InCluster()
kubernetes.InCluster().Type(kubernetes.ReplicaSet).InNamespace("test").
    List().
    NamePrefix("foo-").
    Map(func(rs *api_ext_v1.ReplicaSet) rs*api_ext_v1.ReplicaSet {
        // Edit in-place or clone a new one
        rs.Meta.Labels["foo-label1"] = "test" 
        return rs
    }).Update()


// Out-Of-Cluster example
kubernetes.OutOfClusterDefault().Type(kubernetes.Pod).InNamespace("devops").
    List().
    NameEqual("test-pod").Each(
        func(pod *api_v1.Pod) {
            count++
    })

As the following example is shown, Calling Mock() on Kubernetes Type Enumeration will create the expected mocking resources for you:

import kubernetes "github.com/yue9944882/kubernetes-client-lambda"

var kcl KubernetesClientLambda = kubernetes.Mock()
How to Get it?
go get github.com/yue9944882/kubernetes-client-lambda
Supported Lambda Function Type

We support following types of lambda function:

Primitive Lambda Type

Name Parameter Type Return Type
Function Resource -
Consumer Resource
Predicate Resource bool
Producer - Resource
Kubernetes Resource Lambda Snippet
Name Pipelinable Description
NameEqual yes Filter out resources if its name mismatches
NamePrefix yes Filter out resources if its name doesn't have the prefix
NameRegex yes Filter out resources if its name doesn't match the regular expression
HasAnnotation yes Filter out resources if it doesn't have the annotation
HasAnnotationKey yes Filter out resources if it doesn't have the annotation key
HasLabel yes Filter out resources if it doesn't have the label
HasLabelKey yes Filter out resources if it doesn't have the label key

And these lambda can be consumed by following function:

Primitive Pipeline Type
Name Pipelinable Lambda Type Description
Collect yes - Deep copies the elements and put them into collection
Add yes Producer Add the element returned by lambda into collection
Map yes Consumer Add all the elements returned by lambda to a new collection
Grep yes Predicate Remove the element from collection if applied lambda returned a false
First yes Predicate Take only the first element when applied lambda returned a true
Iter no Function Apply the lambda to every elements in the collection

Primitive methods like CreateIfNotExist, DeleteIfExist have no parameter and just consumes all elements at the end of the pipelining. Here are supported primitive kubernetes operation functions below:

Basic Operation
Operation Param Return1 Return2
Each Function lambda error -
Any Predicate bool lambda error
Every Predicate bool lambda error
NotEmpty - bool lambda error
Kubernetes Operation
Operation Param Return1 Return2
Create - bool(sucess) lambda error
CreateIfNotExists - bool(success) lambda error
Delete - bool(sucess) lambda error
DeleteIfExists - bool(success) lambda error
Update - bool(sucess) lambda error
UpdateIfExists - bool(success) lambda error
UpdateOrCreate - bool(success) lambda error

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// core
	Pod                   = Resource{"Pods", ""}
	Namespace             = Resource{"Namespaces", ""}
	Node                  = Resource{"Nodes", ""}
	Event                 = Resource{"Events", ""}
	Service               = Resource{"Services", ""}
	Endpoints             = Resource{"Endpoints", ""}
	LimitRange            = Resource{"LimitRanges", ""}
	Secret                = Resource{"Secrets", ""}
	ConfigMap             = Resource{"ConfigMaps", ""}
	ServiceAccout         = Resource{"ServiceAccounts", ""}
	PodTemplate           = Resource{"PodTemplates", ""}
	ResourceQuota         = Resource{"ResourceQuotas", ""}
	PersistentVolume      = Resource{"PersistentVolumes", ""}
	PersistentVolumeClaim = Resource{"PersistentVolumeClaims", ""}
	ReplicationController = Resource{"ReplicationControllers", ""}

	// extensions
	Ingress           = Resource{"Ingresses", ""}
	ReplicaSet        = Resource{"ReplicaSets", "v1beta1"}
	Deployment        = Resource{"Deployments", ""}
	DaemonSet         = Resource{"DaemonSets", ""}
	PodSecurityPolicy = Resource{"PodSecurityPolicies", ""}

	// apps
	StatefulSet        = Resource{"StatefulSets", ""}
	ControllerRevision = Resource{"ControllerRevisions", ""}

	// rbac
	ClusterRole        = Resource{"ClusterRoles", ""}
	ClusterRoleBinding = Resource{"ClusterRoleBindings", ""}
	Role               = Resource{"Roles", ""}
	RoleBinding        = Resource{"RoleBindings", ""}

	// batch
	Job     = Resource{"Jobs", ""}
	CronJob = Resource{"CronJobs", ""}

	// storage
	StorageClass = Resource{"StorageClasses", ""}

	// autoscaling
	HorizontalPodAutoscalerV1 = Resource{"HorizontalPodAutoscalers", "v1"}
	HorizontalPodAutoscalerV2 = Resource{"HorizontalPodAutoscalers", "v2beta1"}
)

Functions

func NewFakes added in v1.1.0

func NewFakes(objects ...runtime.Object) (dynamic.ClientPool, kubernetes.Interface)

Types

type Consumer

type Consumer interface{}

Consumer is a function has one parameter and returns one value. Nil is not allowed to be used as parameter or return value, or panic will occur. Consumer is always used to apply some transformation to elements.

type ErrMultiLambdaFailure

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

ErrMultiLambdaFailure contains one or more error occured from lambda invocation chain

func (ErrMultiLambdaFailure) Error

func (e ErrMultiLambdaFailure) Error() string

type FakeClient added in v1.1.0

type FakeClient struct {
	*dynamic_fake.FakeClient
}

FakeClient is a fake implementation of dynamic.Interface.

func (*FakeClient) GetRateLimiter added in v1.1.0

func (c *FakeClient) GetRateLimiter() flowcontrol.RateLimiter

GetRateLimiter returns the rate limiter for this client.

func (*FakeClient) ParameterCodec added in v1.1.0

func (c *FakeClient) ParameterCodec(parameterCodec runtime.ParameterCodec) dynamic.Interface

ParameterCodec returns a client with the provided parameter codec.

func (*FakeClient) Resource added in v1.1.0

func (c *FakeClient) Resource(resource *metav1.APIResource, namespace string) dynamic.ResourceInterface

Resource returns an API interface to the specified resource for this client's group and version. If resource is not a namespaced resource, then namespace is ignored. The ResourceClient inherits the parameter codec of this client

type FakeClientPool added in v1.1.0

type FakeClientPool struct {
	*testing.Fake
}

FakeClientPool provides a fake implementation of dynamic.ClientPool. It assumes resource GroupVersions are the same as their corresponding kind GroupVersions.

func (*FakeClientPool) ClientForGroupVersionKind added in v1.1.0

func (p *FakeClientPool) ClientForGroupVersionKind(kind schema.GroupVersionKind) (dynamic.Interface, error)

ClientForGroupVersionKind returns a client configured for the specified groupVersionKind. Kind may be empty.

func (*FakeClientPool) ClientForGroupVersionResource added in v1.1.0

func (p *FakeClientPool) ClientForGroupVersionResource(resource schema.GroupVersionResource) (dynamic.Interface, error)

ClientForGroupVersionKind returns a client configured for the specified groupVersionResource. Resource may be empty.

type FakeResourceClient added in v1.1.0

type FakeResourceClient struct {
	*dynamic_fake.FakeResourceClient
}

FakeResourceClient is a fake implementation of dynamic.ResourceInterface

func (*FakeResourceClient) Get added in v1.1.0

Get gets the resource with the specified name.

func (*FakeResourceClient) List added in v1.1.0

type Function

type Function interface{}

Function is a function has one parameter and has no return value. The parameter must not be a nil

type KubernetesClientLambda

type KubernetesClientLambda interface {
	Type(Resource) *kubernetesExecutable
}

KubernetesClientLambda provides manipulation interface for resources

func Mock

func Mock(objects ...runtime.Object) KubernetesClientLambda

the mock KubernetesClient is statusful and if you want to reset its status then use MockReset

func OutOfClusterDefault

func OutOfClusterDefault() KubernetesClientLambda

OutOfClusterDefault loads configuration from ~/.kube/config

func OutOfClusterInContext

func OutOfClusterInContext(context string) KubernetesClientLambda

OutOfClusterInContext is used to switch context of multi-cluster kubernetes

type Lambda

type Lambda struct {
	Errors []error
	// contains filtered or unexported fields
}

Lambda is a basic and core type of KCL. It holds a channel for receiving elements from previous lambda or kubernetes resource fetcher. Error is assigned if any error occured during lambda pipelining. The error will be recorded but the lambda pipelining will continue on, and forcing it fail-hard needs call MustNoError method. The error can be also be returned at the end of a pipeline via lambda operation method which is defined in lambda_operation.go

func (*Lambda) Add

func (lambda *Lambda) Add(producer Producer) *Lambda

Add calls the producer and put the returned value into elements

func (*Lambda) Any

func (lambda *Lambda) Any(predicate Predicate) (any bool, err error)

Any checks if any element get a true from predicate

func (*Lambda) Collect

func (lambda *Lambda) Collect() *Lambda

Collect deep copies every element in the lambda

func (*Lambda) Create

func (lambda *Lambda) Create() (created bool, err error)

Create creates every element remains in lambda collection Returns true if every element is successfully created and lambda error chain Fails if any element already exists

func (*Lambda) CreateIfNotExist

func (lambda *Lambda) CreateIfNotExist() (created, existed bool, err error)

CreateIfNotExist creates element in the lambda collection Will not return false if any element fails to be created

func (*Lambda) Delete

func (lambda *Lambda) Delete() (deleted bool, err error)

Delete remove every element in the lambda collection

func (*Lambda) DeleteIfExist

func (lambda *Lambda) DeleteIfExist() (deleted, existed bool, err error)

DeleteIfExist delete elements in the lambda collection if it exists

func (*Lambda) Dummy

func (lambda *Lambda) Dummy() *Lambda

Dummy do nothing and passing the elements next

func (*Lambda) Each

func (lambda *Lambda) Each(function Function) error

Each applies function to every element

func (*Lambda) Element added in v1.1.0

func (lambda *Lambda) Element() (runtime.Object, error)

Element returns a single element. Note that if multiple elements exists in the lambda pipeline, a random object may be returned.

func (*Lambda) Elements added in v1.1.0

func (lambda *Lambda) Elements() ([]runtime.Object, error)

Elements returns all elements from the lambda pipeline.

func (*Lambda) Every

func (lambda *Lambda) Every(predicate Predicate) (every bool, err error)

Every checks if every element get a true from predicate

func (*Lambda) First

func (lambda *Lambda) First(predicate Predicate) *Lambda

First returnes the first element matches the predicate

func (*Lambda) Grep

func (lambda *Lambda) Grep(predicate Predicate) *Lambda

Grep returnes the elements matches the predicate

func (*Lambda) HasAnnotation

func (lambda *Lambda) HasAnnotation(key, value string) *Lambda

HasAnnotation filter the elements out if it doesn't have the arugument annotation

func (*Lambda) HasAnnotationKey

func (lambda *Lambda) HasAnnotationKey(key string) *Lambda

HasAnnotationKey filter the elements out if it doesn't have the arugument annotation key

func (*Lambda) HasLabel

func (lambda *Lambda) HasLabel(key, value string) *Lambda

HasLabel filter the elements out if it doesn't have the arugument label

func (*Lambda) HasLabelKey

func (lambda *Lambda) HasLabelKey(key string) *Lambda

HasLabelKey filter the elements out if it doesn't have the arugument label key

func (*Lambda) Iter

func (lambda *Lambda) Iter(function Function) *Lambda

Iter iterates the elements and apply function to them Note that modifying is not recommened in Iter, use Map to modify elements instead

func (*Lambda) LatestCreated added in v1.1.0

func (lambda *Lambda) LatestCreated() *Lambda

LatestCreated filters out the latest created object

func (*Lambda) List added in v1.0.0

func (lambda *Lambda) List() *Lambda

func (*Lambda) ListWithLabelSelector added in v1.1.0

func (lambda *Lambda) ListWithLabelSelector(selector labels.Selector) *Lambda

List lists all items indexed in the local cache

func (*Lambda) Map

func (lambda *Lambda) Map(consumer Consumer) *Lambda

Map transforms and replace the elements and put them to the next lambda

func (*Lambda) MustNoError

func (lambda *Lambda) MustNoError() *Lambda

MustNoError panics if any error occured

func (*Lambda) NameEqual

func (lambda *Lambda) NameEqual(name string) *Lambda

NameEqual filter the elements out if its name mismatches with the argument name

func (*Lambda) NamePrefix

func (lambda *Lambda) NamePrefix(prefix string) *Lambda

NamePrefix filter the elements out if its name doesn't have the prefix

func (*Lambda) NameRegex

func (lambda *Lambda) NameRegex(regex string) *Lambda

NameRegex filter the elements out if its name fails to matches the regexp

func (*Lambda) NoError

func (lambda *Lambda) NoError() bool

NoError checks if any error occured before

func (*Lambda) NotEmpty

func (lambda *Lambda) NotEmpty() (noempty bool, err error)

NotEmpty checks if any element remains Returns true if the lambda collection is not empty and error if upstream lambda fails

func (*Lambda) Update

func (lambda *Lambda) Update() (updated bool, err error)

Update updates elements to kuberentes resources

func (*Lambda) UpdateIfExist

func (lambda *Lambda) UpdateIfExist() (updated, existed bool, err error)

UpdateIfExist checks if the element exists and update it value

func (*Lambda) UpdateOrCreate added in v1.0.0

func (lambda *Lambda) UpdateOrCreate() (updated, created bool, err error)

type Predicate

type Predicate interface{}

Predicate is a function has only one parameter and return boolean. When return value type is not boolean, panic will occur. The parameter can be of any type but nil and predicates is always used to test an element.

type Producer

type Producer interface{}

Producer is a function takes no parameter and returns a value. Producer is recommeneded to be a closure so that the returning value can be controlled outside lambda.

type Resource

type Resource struct {
	Name    string
	Version string
}

Resource is kubernetes resource enumeration hiding api version

func GetResources added in v1.0.0

func GetResources() []Resource

func (Resource) GetAPIVersion added in v1.1.0

func (r Resource) GetAPIVersion() string

func (Resource) GetKind added in v1.1.0

func (r Resource) GetKind() string

func (Resource) GetResource added in v1.1.0

func (r Resource) GetResource() string

type ResourceIndexer added in v1.0.0

type ResourceIndexer interface {
	IsNamespaced(resource Resource) bool
	GetAPIResource(resource Resource) *metav1.APIResource
	GetGroupVersionKind(resource Resource) schema.GroupVersionKind
	GetGroupVersionResource(resource Resource) schema.GroupVersionResource
}

func GetResouceIndexerInstance added in v1.0.0

func GetResouceIndexerInstance() (indexer ResourceIndexer)

getResouceIndexerInstance blocks until initIndexer is invoked

type SortedGVKs added in v1.0.0

type SortedGVKs []schema.GroupVersionKind

func (SortedGVKs) Len added in v1.0.0

func (s SortedGVKs) Len() int

func (SortedGVKs) Less added in v1.0.0

func (s SortedGVKs) Less(i, j int) bool

func (SortedGVKs) Swap added in v1.0.0

func (s SortedGVKs) Swap(i, j int)

type Version added in v1.1.0

type Version string

func (Version) GetNumericVersion added in v1.1.0

func (v Version) GetNumericVersion() string

func (Version) GetSuffix added in v1.1.0

func (v Version) GetSuffix() string

Jump to

Keyboard shortcuts

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