lambda

package module
v0.0.0-rc1 Latest Latest
Warning

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

Go to latest
Published: Dec 29, 2017 License: Apache-2.0 Imports: 19 Imported by: 0

README

Kubernetes Client Lambda

Build Status codecov Go Doc

What is Kubernetes Client Lambda?

logo

Kubernetes Client Lambda (KCL) is a wrapper library over kubernetes/client-go which provides light-weight lambda-styled streamized kubernetes resource manipulation interface. This project is basically inspired by Groovy style lambda, and is aiming at reducing the coding-overhead when referencing too many struct / interface provided by kubernetes/client-go. The only dependency of this project is kubernetes/client-go, so this project can be pure and light-weight for you. Currently KCL only provides support for those common-used resources like Pod / Service.. Click to see all the supported resources in KCL.

Note that: KCL can be compatible with any kubernetes version, because KCL is a wrapping over client-go and client-go will provide it

Also, KCL defines more useful primitive operation type beyond those provided, e.g. Create-If-Not-Exist, Update-Or-Create, Delete-If-Exist.., which can help you make your code more clean. These primitive operation is always at the end of streaming and consumes all the remaining element and apply operation on every element.

Basically, KCL is implemented by golang reflect and golang native facilities. KCL defines various resources provided by kubernetes as enumeratoin which hides some unneccessary details like API-version. Sometimes, managing these details can be painful for kubernetes developers. Meanwhile, I find it costs time when mocking kubernetes resources in static unit test, so KCL provides a very simple mocking for kubernetes resources which is implemented via map.

detail

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
kubernetes.ReplicaSet.InCluster().InNamespace("test").NameEqual("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.Pod.OutOfCluster(config).InNamespace("devops").NameEqual("test-pod").Each(
    func(pod *api_v1.Pod) {
        count++
    },
)
How to Use it?
go get github.com/yue9944882/kubernetes-client-lambda
Why Kubernetes Client Lambda is better?
  • Manipulating kubernetes resources in one line
  • Lambda-styled kubernetes resource processing.
  • Pipelined and streamlized.
  • Light-weight and only depends on kubernetes/client-go
  • User-friendly mocking kubernetes static interface
How to Mock Kubernetes Resources?

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

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

kubernetes.ReplicaSet.Mock().InNamespace("test").Add(
    // An anonymous function simply returns a pointer to kubernetes resource 
    // Returned objects will be added to stream
    func(){
        rs.Name = "foo"
        rs.Namespace = "test"
        return &rs
    },
).Create()

Checkout more examples under example folder.

Supported Lambda Function Type

First we have following types of lambda function:

(KR denotes Kubernetes Resources, a pointer to resouce, e.g. *api_v1.Pod, *api_ext_v1.ReplicaSet..)

Primitive Lambda
Name Parameter Type Return Type
Function KR -
Consumer KR KR
Predicate KR bool
Producer - KR
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

This section is empty.

Functions

This section is empty.

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 Function

type Function interface{}

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

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) (bool, 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() (allCreated 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() (success 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 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) Every

func (lambda *Lambda) Every(predicate Predicate) (bool, 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) 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() (bool, 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 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() (success bool, err error)

Sync automatically decides to create / update a resource If the resource doesn't exist,

type ListPageFunc

type ListPageFunc interface{}

type ListPager

type ListPager struct {
	PageSize int64
	PageFn   ListPageFunc
}

func (*ListPager) List

func (p *ListPager) List(options meta_v1.ListOptions) (<-chan kubernetesResource, 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 string
const (
	Namespace             Resource = "Namespace"
	Node                  Resource = "Node"
	StorageClass          Resource = "StorageClass"
	Pod                   Resource = "Pod"
	ReplicaSet            Resource = "ReplicaSet"
	ReplicationController Resource = "ReplicationController"
	Deployment            Resource = "Deployment"
	ConfigMap             Resource = "ConfigMap"
	Ingress               Resource = "Ingress"
	Service               Resource = "Service"
	Endpoint              Resource = "Endpoint"
	Secret                Resource = "Secret"
	DaemonSet             Resource = "DaemonSet"
	StatefulSet           Resource = "StatefulSet"
)

func (Resource) GeResourcetName

func (rs Resource) GeResourcetName() string

func (Resource) GetObject

func (rs Resource) GetObject() runtime.Object

func (Resource) InCluster

func (rs Resource) InCluster() *kubernetesExecutable

func (Resource) Mock

func (rs Resource) Mock() *kubernetesExecutable

Mock return a mock interface of lambda KubernetesClient the mock KubernetesClient is statusful and if you want to reset its status then use MockReset

func (Resource) OutOfCluster

func (rs Resource) OutOfCluster(config *rest.Config) *kubernetesExecutable

func (Resource) ResetMock

func (rs Resource) ResetMock()

func (Resource) String

func (rs Resource) String() string

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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