node

package
v0.10.0 Latest Latest
Warning

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

Go to latest
Published: Jun 13, 2019 License: Apache-2.0 Imports: 38 Imported by: 0

Documentation

Overview

Package node implements the components for operating a node in Kubernetes. This includes controllers for managin the node object, running scheduled pods, and exporting HTTP endpoints expected by the Kubernets API server.

There are two primary controllers, the node runner and the pod runner.

nodeRunner, _ := node.NewNodeController(...)
	// setup other things
podRunner, _ := node.NewPodController(...)

go podRunner.Run(ctx)

select {
case <-podRunner.Ready():
	go nodeRunner.Run(ctx)
case <-ctx.Done()
	return ctx.Err()
}

After calling start, cancelling the passed in context will shutdown the controller. Note this example elides error handling.

Up to this point you have an active node in Kubernetes which can have pods scheduled to it. However the API server expects nodes to implement API endpoints in order to support certain features such as fetching logs or execing a new process. The api package provides some helpers for this: `api.AttachPodRoutes` and `api.AttachMetricsRoutes`.

mux := http.NewServeMux()
api.AttachPodRoutes(provider, mux)

You must configure your own HTTP server, but these helpers will add handlers at the correct URI paths to your serve mux. You are not required to use go's built-in `*http.ServeMux`, but it does implement the `ServeMux` interface defined in this package which is used for these helpers.

Note: The metrics routes may need to be attached to a different HTTP server, depending on your configuration.

For more fine-grained control over the API, see the `node/api` package which only implements the HTTP handlers that you can use in whatever way you want.

This uses open-cenesus to implement tracing (but no internal metrics yet) which is propagated through the context. This is passed on even to the providers.

Index

Constants

View Source
const (
	// ReasonOptionalConfigMapNotFound is the reason used in events emitted when an optional configmap is not found.
	ReasonOptionalConfigMapNotFound = "OptionalConfigMapNotFound"
	// ReasonOptionalConfigMapKeyNotFound is the reason used in events emitted when an optional configmap key is not found.
	ReasonOptionalConfigMapKeyNotFound = "OptionalConfigMapKeyNotFound"
	// ReasonFailedToReadOptionalConfigMap is the reason used in events emitted when an optional configmap could not be read.
	ReasonFailedToReadOptionalConfigMap = "FailedToReadOptionalConfigMap"

	// ReasonOptionalSecretNotFound is the reason used in events emitted when an optional secret is not found.
	ReasonOptionalSecretNotFound = "OptionalSecretNotFound"
	// ReasonOptionalSecretKeyNotFound is the reason used in events emitted when an optional secret key is not found.
	ReasonOptionalSecretKeyNotFound = "OptionalSecretKeyNotFound"
	// ReasonFailedToReadOptionalSecret is the reason used in events emitted when an optional secret could not be read.
	ReasonFailedToReadOptionalSecret = "FailedToReadOptionalSecret"

	// ReasonMandatoryConfigMapNotFound is the reason used in events emitted when an mandatory configmap is not found.
	ReasonMandatoryConfigMapNotFound = "MandatoryConfigMapNotFound"
	// ReasonMandatoryConfigMapKeyNotFound is the reason used in events emitted when an mandatory configmap key is not found.
	ReasonMandatoryConfigMapKeyNotFound = "MandatoryConfigMapKeyNotFound"
	// ReasonFailedToReadMandatoryConfigMap is the reason used in events emitted when an mandatory configmap could not be read.
	ReasonFailedToReadMandatoryConfigMap = "FailedToReadMandatoryConfigMap"

	// ReasonMandatorySecretNotFound is the reason used in events emitted when an mandatory secret is not found.
	ReasonMandatorySecretNotFound = "MandatorySecretNotFound"
	// ReasonMandatorySecretKeyNotFound is the reason used in events emitted when an mandatory secret key is not found.
	ReasonMandatorySecretKeyNotFound = "MandatorySecretKeyNotFound"
	// ReasonFailedToReadMandatorySecret is the reason used in events emitted when an mandatory secret could not be read.
	ReasonFailedToReadMandatorySecret = "FailedToReadMandatorySecret"

	// ReasonInvalidEnvironmentVariableNames is the reason used in events emitted when a configmap/secret referenced in a ".spec.containers[*].envFrom" field contains invalid environment variable names.
	ReasonInvalidEnvironmentVariableNames = "InvalidEnvironmentVariableNames"
)
View Source
const (
	DefaultPingInterval         = 10 * time.Second
	DefaultStatusUpdateInterval = 1 * time.Minute
)

The default intervals used for lease and status updates.

Variables

This section is empty.

Functions

func PatchNodeStatus

func PatchNodeStatus(nodes v1.NodeInterface, nodeName types.NodeName, oldNode *corev1.Node, newNode *corev1.Node) (*corev1.Node, []byte, error)

PatchNodeStatus patches node status. Copied from github.com/kubernetes/kubernetes/pkg/util/node

func UpdateNodeLease

func UpdateNodeLease(ctx context.Context, leases v1beta1.LeaseInterface, lease *coord.Lease) (*coord.Lease, error)

UpdateNodeLease updates the node lease.

If this function returns an errors.IsNotFound(err) error, this likely means that node leases are not supported, if this is the case, call UpdateNodeStatus instead.

If you use this function, it is up to you to syncronize this with other operations.

func UpdateNodeStatus

func UpdateNodeStatus(ctx context.Context, nodes v1.NodeInterface, n *corev1.Node) (_ *corev1.Node, retErr error)

UpdateNodeStatus triggers an update to the node status in Kubernetes. It first fetches the current node details and then sets the status according to the passed in node object.

If you use this function, it is up to you to syncronize this with other operations. This reduces the time to second-level precision.

Types

type ErrorHandler

type ErrorHandler func(context.Context, error) error

ErrorHandler is a type of function used to allow callbacks for handling errors. It is expected that if a nil error is returned that the error is handled and progress can continue (or a retry is possible).

type NaiveNodeProvider

type NaiveNodeProvider struct{}

NaiveNodeProvider is a basic node provider that only uses the passed in context on `Ping` to determine if the node is healthy.

func (NaiveNodeProvider) NotifyNodeStatus

func (NaiveNodeProvider) NotifyNodeStatus(ctx context.Context, f func(*corev1.Node))

NotifyNodeStatus implements the NodeProvider interface.

This NaiveNodeProvider does not support updating node status and so this function is a no-op.

func (NaiveNodeProvider) Ping

Ping just implements the NodeProvider interface. It returns the error from the passed in context only.

type NodeController

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

NodeController deals with creating and managing a node object in Kubernetes. It can register a node with Kubernetes and periodically update its status. NodeController manages a single node entity.

func NewNodeController

func NewNodeController(p NodeProvider, node *corev1.Node, nodes v1.NodeInterface, opts ...NodeControllerOpt) (*NodeController, error)

NewNodeController creates a new node controller. This does not have any side-effects on the system or kubernetes.

Use the node's `Run` method to register and run the loops to update the node in Kubernetes.

Note: When if there are multiple NodeControllerOpts which apply against the same underlying options, the last NodeControllerOpt will win.

func (*NodeController) Ready

func (n *NodeController) Ready() <-chan struct{}

Ready returns a channel that gets closed when the node is fully up and running. Note that if there is an error on startup this channel will never be started.

func (*NodeController) Run

func (n *NodeController) Run(ctx context.Context) error

Run registers the node in kubernetes and starts loops for updating the node status in Kubernetes.

The node status must be updated periodically in Kubertnetes to keep the node active. Newer versions of Kubernetes support node leases, which are essentially light weight pings. Older versions of Kubernetes require updating the node status periodically.

If Kubernetes supports node leases this will use leases with a much slower node status update (because some things still expect the node to be updated periodically), otherwise it will only use node status update with the configured ping interval.

type NodeControllerOpt

type NodeControllerOpt func(*NodeController) error // nolint: golint

NodeControllerOpt are the functional options used for configuring a node

func WithNodeEnableLeaseV1Beta1

func WithNodeEnableLeaseV1Beta1(client v1beta1.LeaseInterface, baseLease *coord.Lease) NodeControllerOpt

WithNodeEnableLeaseV1Beta1 enables support for v1beta1 leases. If client is nil, leases will not be enabled. If baseLease is nil, a default base lease will be used.

The lease will be updated after each successful node ping. To change the lease update interval, you must set the node ping interval. See WithNodePingInterval().

This also affects the frequency of node status updates:

  • When leases are *not* enabled (or are disabled due to no support on the cluster) the node status is updated at every ping interval.
  • When node leases are enabled, node status updates are controlled by the node status update interval option.

To set a custom node status update interval, see WithNodeStatusUpdateInterval().

func WithNodePingInterval

func WithNodePingInterval(d time.Duration) NodeControllerOpt

WithNodePingInterval sets the interval for checking node status If node leases are not supported (or not enabled), this is the frequency with which the node status will be updated in Kubernetes.

func WithNodeStatusUpdateErrorHandler

func WithNodeStatusUpdateErrorHandler(h ErrorHandler) NodeControllerOpt

WithNodeStatusUpdateErrorHandler adds an error handler for cases where there is an error when updating the node status. This allows the caller to have some control on how errors are dealt with when updating a node's status.

The error passed to the handler will be the error received from kubernetes when updating node status.

func WithNodeStatusUpdateInterval

func WithNodeStatusUpdateInterval(d time.Duration) NodeControllerOpt

WithNodeStatusUpdateInterval sets the interval for updating node status This is only used when leases are supported and only for updating the actual node status, not the node lease. When node leases are not enabled (or are not supported on the cluster) this has no affect and node status is updated on the "ping" interval.

type NodeProvider

type NodeProvider interface {
	// Ping checks if the node is still active.
	// This is intended to be lightweight as it will be called periodically as a
	// heartbeat to keep the node marked as ready in Kubernetes.
	Ping(context.Context) error

	// NotifyNodeStatus is used to asynchronously monitor the node.
	// The passed in callback should be called any time there is a change to the
	// node's status.
	// This will generally trigger a call to the Kubernetes API server to update
	// the status.
	//
	// NotifyNodeStatus should not block callers.
	NotifyNodeStatus(ctx context.Context, cb func(*corev1.Node))
}

NodeProvider is the interface used for registering a node and updating its status in Kubernetes.

Note: Implementers can choose to manage a node themselves, in which case it is not needed to provide an implementation for this interface.

type PodController

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

PodController is the controller implementation for Pod resources.

func NewPodController

func NewPodController(cfg PodControllerConfig) (*PodController, error)

func (*PodController) Ready

func (pc *PodController) Ready() <-chan struct{}

Ready returns a channel which gets closed once the PodController is ready to handle scheduled pods. This channel will never close if there is an error on startup. The status of this channel after sthudown is indeterminate.

func (*PodController) Run

func (pc *PodController) Run(ctx context.Context, podSyncWorkers int) error

Run will set up the event handlers for types we are interested in, as well as syncing informer caches and starting workers. It will block until the context is cancelled, at which point it will shutdown the work queue and wait for workers to finish processing their current work items.

type PodControllerConfig

type PodControllerConfig struct {
	// PodClient is used to perform actions on the k8s API, such as updating pod status
	// This field is required
	PodClient corev1client.PodsGetter

	// PodInformer is used as a local cache for pods
	// This should be configured to only look at pods scheduled to the node which the controller will be managing
	PodInformer corev1informers.PodInformer

	EventRecorder record.EventRecorder

	Provider PodLifecycleHandler

	// Listers used for filling details for things like downward API in pod spec.
	ConfigMapLister corev1listers.ConfigMapLister
	SecretLister    corev1listers.SecretLister
	ServiceLister   corev1listers.ServiceLister
}

PodControllerConfig is used to configure a new PodController.

type PodLifecycleHandler

type PodLifecycleHandler interface {
	// CreatePod takes a Kubernetes Pod and deploys it within the provider.
	CreatePod(ctx context.Context, pod *corev1.Pod) error

	// UpdatePod takes a Kubernetes Pod and updates it within the provider.
	UpdatePod(ctx context.Context, pod *corev1.Pod) error

	// DeletePod takes a Kubernetes Pod and deletes it from the provider.
	DeletePod(ctx context.Context, pod *corev1.Pod) error

	// GetPod retrieves a pod by name from the provider (can be cached).
	GetPod(ctx context.Context, namespace, name string) (*corev1.Pod, error)

	// GetPodStatus retrieves the status of a pod by name from the provider.
	GetPodStatus(ctx context.Context, namespace, name string) (*corev1.PodStatus, error)

	// GetPods retrieves a list of all pods running on the provider (can be cached).
	GetPods(context.Context) ([]*corev1.Pod, error)
}

PodLifecycleHandler defines the interface used by the PodController to react to new and changed pods scheduled to the node that is being managed.

Errors produced by these methods should implement an interface from github.com/virtual-kubelet/virtual-kubelet/errdefs package in order for the core logic to be able to understand the type of failure.

type PodNotifier

type PodNotifier interface {
	// NotifyPods instructs the notifier to call the passed in function when
	// the pod status changes.
	//
	// NotifyPods should not block callers.
	NotifyPods(context.Context, func(*corev1.Pod))
}

PodNotifier notifies callers of pod changes. Providers should implement this interface to enable callers to be notified of pod status updates asyncronously.

Directories

Path Synopsis
Package api implements HTTP handlers for handling requests that the kubelet would normally implement, such as pod logs, exec, etc.
Package api implements HTTP handlers for handling requests that the kubelet would normally implement, such as pod logs, exec, etc.

Jump to

Keyboard shortcuts

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