util

package
v0.7.0 Latest Latest
Warning

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

Go to latest
Published: May 7, 2023 License: Apache-2.0 Imports: 24 Imported by: 0

Documentation

Index

Constants

View Source
const Separator = '/'

Variables

View Source
var BuildGitInfo string

BuildGitInfo stores some pretty-formatted information about the repository and working tree at build time. It's set by the GIT_INFO argument in the Dockerfiles and set to the output of:

git describe --long --dirty

While public, this value is not expected to be used externally. You should use GetBuildInfo instead.

Functions

func AddHandler

func AddHandler[T any, R any](
	logPrefix string,
	mux *http.ServeMux,
	endpoint string,
	method string,
	reqTypeName string,
	handle func(context.Context, *T) (_ *R, statusCode int, _ error),
)

AddHandler is a helper function to wrap the handle function with JSON [de]serialization and check that the HTTP method is correct

The provided logPrefix is prepended to every log line emitted by the wrapped handler function, to offer distinction where that's useful.

func AtomicMax added in v0.1.4

func AtomicMax[A AtomicInt[I], I constraints.Integer](a A, i I) I

AtomicMax atomically sets a to the maximum of *a and i, returning the old value at a.

On ISAs without atomic maximum/minimum instructions, a fallback is typically implemented as the Load + CompareAndSwap loop that this function uses. At time of writing (Go 1.20), the Go standard library does not include atomic maximum/minimum functions.

This function is lock-free but not wait-free.

func MakePPROF added in v0.1.14

func MakePPROF(addr string) *http.Server

func Max

func Max[T constraints.Ordered](x, y T) T

Max returns the maximum of the two values

func Min

func Min[T constraints.Ordered](x, y T) T

Min returns the minimum of the two values

func NewCondChannelPair

func NewCondChannelPair() (CondChannelSender, CondChannelReceiver)

NewCondChannelPair creates a sender/receiver pair for a sync.Cond-like interface

The differences from sync.Cond are that receiving is exposed through a channel (so it can be select-ed) and there is no equivalent to (*Cond).Broadcast()

func NewSingleSignalPair

func NewSingleSignalPair() (SignalSender, SignalReceiver)

func PatchPathEscape

func PatchPathEscape(path string) string

func PodReady

func PodReady(pod *corev1.Pod) bool

PodReady returns true iff the pod is marked as ready (as determined by the pod's Status.Conditions)

func PodStartedBefore

func PodStartedBefore(p, q *corev1.Pod) bool

PodStartedBefore returns true iff Pod p started before Pod q

func SaturatingSub

func SaturatingSub[T constraints.Unsigned](x, y T) T

SaturatingSub returns x - y if x >= y, otherwise zero

func StartPrometheusMetricsServer added in v0.6.0

func StartPrometheusMetricsServer(ctx context.Context, port uint16, reg *prometheus.Registry) error

Starts the prometheus server in a background thread. Returns error if binding on the port fails.

Types

type AtomicInt added in v0.1.4

type AtomicInt[I any] interface {
	Add(delta I) (new I)                      //nolint:predeclared // same var names as methods
	CompareAndSwap(old, new I) (swapped bool) //nolint:predeclared // same var names as methods
	Load() I
	Store(val I)
	Swap(new I) (old I) //nolint:predeclared // same var names as methods
}

AtomicInt represents the shared interface provided by various atomic.<NAME> integers

This interface type is primarily used by AtomicMax.

type BuildInfo

type BuildInfo struct {
	GitInfo   string `json:"gitInfo"`
	GoVersion string `json:"goVersion"`
}

BuildInfo stores a little bit of information about the build of the current binary

All strings are guaranteed to be non-empty.

func GetBuildInfo

func GetBuildInfo() BuildInfo

GetBuildInfo makes a best-effort attempt to return some information about how the currently running binary was built

type ChanMutex

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

ChanMutex is a select-able mutex

It is fair if and only if receiving on a channel is fair. As of Go 1.19/2022-01-17, receiving on a channel appears to be fair. However: this is a runtime implementation detail, and so it may change without notice in the future.

Unlike sync.Mutex, ChanMutex requires initialization before use because it's basically just a channel.

Also unlike sync.Mutex, a ChanMutex may be copied without issue (again, because it's just a channel).

func NewChanMutex

func NewChanMutex() ChanMutex

NewChanMutex creates a new ChanMutex

func (*ChanMutex) DeadlockChecker added in v0.1.12

func (m *ChanMutex) DeadlockChecker(timeout, delay time.Duration) func(ctx context.Context)

DeadlockChecker creates a function that, when called, periodically attempts to acquire the lock, panicking if it fails

The returned function exits when the context is done.

func (*ChanMutex) Lock

func (m *ChanMutex) Lock()

Lock locks m

This method is semantically equivalent to sync.Mutex.Lock

func (*ChanMutex) TryLock

func (m *ChanMutex) TryLock(ctx context.Context) error

TryLock blocks until locking m succeeds or the context is cancelled

If the context is cancelled while waiting to lock m, the lock will be left unchanged and ctx.Err() will be returned.

func (*ChanMutex) Unlock

func (m *ChanMutex) Unlock()

Unlock unlocks m

This method is semantically equivalent to sync.Mutex.Unlock

func (*ChanMutex) WaitLock

func (m *ChanMutex) WaitLock() <-chan struct{}

WaitLock is like Lock, but instead returns a channel

If receiving on the channel succeeds, the caller "holds" the lock and must now be responsible for Unlock-ing it.

type CondChannelReceiver

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

CondChannelReceiver is the receiving half of a sync.Cond-like interface

func (*CondChannelReceiver) Consume

func (c *CondChannelReceiver) Consume()

Consume removes any existing signal created by Send, requiring an additional Send to be made before the receiving on Recv will unblock

This method is non-blocking.

func (*CondChannelReceiver) Recv

func (c *CondChannelReceiver) Recv() <-chan struct{}

Recv returns a channel for which receiving will complete either (a) immediately, if Send has been called without Consume or another receive since; or (b) as soon as Send is next called

This method is non-blocking but receiving on the returned channel may block.

type CondChannelSender

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

CondChannelSender is the sending half of a sync.Cond-like interface

func (*CondChannelSender) Send

func (c *CondChannelSender) Send()

Send performs a non-blocking notify of the associated CondChannelReceiver

If there is currently a receiver waiting via Recv, then this will immediately wake them. Otherwise, the next receive on the channel returned by Recv will complete immediately.

func (*CondChannelSender) Unsend added in v0.1.4

func (c *CondChannelSender) Unsend() bool

Unsend cancels an existing signal that has been sent but not yet received.

It returns whether there was a signal to be cancelled.

type IndexedWatchStore added in v0.6.0

type IndexedWatchStore[T any, I WatchIndex[T]] struct {
	*WatchStore[T]
	// contains filtered or unexported fields
}

IndexedWatchStore represents a WatchStore, wrapped with a privileged WatchIndex that can be used to efficiently answer queries.

func NewIndexedWatchStore added in v0.6.0

func NewIndexedWatchStore[T any, I WatchIndex[T]](store *WatchStore[T], index I) IndexedWatchStore[T, I]

NewIndexedWatchStore creates a new IndexedWatchStore from the WatchStore and the index to use.

Note: the index type is assumed to have reference semantics; i.e. any shallow copy of the value will affect any other shallow copy.

For more information, refer to IndexedWatchStore.

func (IndexedWatchStore[T, I]) GetIndexed added in v0.6.0

func (w IndexedWatchStore[T, I]) GetIndexed(f func(I) (*T, bool)) (obj *T, ok bool)

func (IndexedWatchStore[T, I]) ListIndexed added in v0.6.0

func (w IndexedWatchStore[T, I]) ListIndexed(f func(I) []*T) (list []*T)

func (IndexedWatchStore[T, I]) WithIndex added in v0.6.0

func (w IndexedWatchStore[T, I]) WithIndex(f func(I))

WithIndex calls a function with the current state of the index, locking the WatchStore around it.

It is almost guaranteed to be an error to indirectly return the index with this function.

type InitWatchMode

type InitWatchMode string

InitWatchMode dictates the behavior of Watch with respect to any initial calls to handlers.AddFunc before returning

If set to InitWatchModeSync, then AddFunc will be called while processing the initial listing, meaning that the returned WatchStore is guaranteed contain the state of the cluster (although it may update before any access).

Otherwise, if set to InitWatchModeDefer, then AddFunc will not be called until after Watch returns. Correspondingly, the WatchStore will not update until then either.

const (
	InitWatchModeSync  InitWatchMode = "sync"
	InitWatchModeDefer InitWatchMode = "defer"
)

type JSONPatch

type JSONPatch struct {
	Op    JSONPatchOp `json:"op"`
	From  string      `json:"from,omitempty"`
	Path  string      `json:"path"`
	Value any         `json:"value,omitempty"`
}

type JSONPatchOp

type JSONPatchOp string
const (
	PatchAdd     JSONPatchOp = "add"
	PatchRemove  JSONPatchOp = "remove"
	PatchReplace JSONPatchOp = "replace"
	PatchMove    JSONPatchOp = "move"
	PatchCopy    JSONPatchOp = "copy"
	PatchTest    JSONPatchOp = "test"
)

type NameIndex added in v0.6.0

type NameIndex[T any] struct {
	// contains filtered or unexported fields
}

NameIndex is a WatchIndex that provides efficient lookup for a value with a particular name

func NewNameIndex added in v0.6.0

func NewNameIndex[T any]() *NameIndex[T]

func (*NameIndex[T]) Add added in v0.6.0

func (i *NameIndex[T]) Add(obj *T)

func (*NameIndex[T]) Delete added in v0.6.0

func (i *NameIndex[T]) Delete(obj *T)

func (*NameIndex[T]) Get added in v0.6.0

func (i *NameIndex[T]) Get(namespace string, name string) (obj *T, ok bool)

func (*NameIndex[T]) Update added in v0.6.0

func (i *NameIndex[T]) Update(oldObj, newObj *T)

type NamespacedName added in v0.6.0

type NamespacedName struct {
	Namespace string `json:"namespace"`
	Name      string `json:"name"`
}

NamespacedName represents a resource name with the namespace it's in.

When printed with '%v', NamespacedName is rendered as "<namespace>/<name>". Printing with '%+v' or '%#v' renders as it would normally.

func GetNamespacedName added in v0.6.0

func GetNamespacedName(obj metav1.ObjectMetaAccessor) NamespacedName

func (NamespacedName) Format added in v0.6.0

func (n NamespacedName) Format(state fmt.State, verb rune)

type SignalReceiver

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

func (SignalReceiver) Close

func (s SignalReceiver) Close()

func (SignalReceiver) Recv

func (s SignalReceiver) Recv() chan struct{}

type SignalSender

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

func (SignalSender) Send

func (s SignalSender) Send()

type TimeRange

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

func NewTimeRange

func NewTimeRange(units time.Duration, min, max int) *TimeRange

func (TimeRange) Random

func (r TimeRange) Random() time.Duration

Random returns a random time.Duration within the range

type WatchAccessors

type WatchAccessors[L any, T any] struct {
	Items func(L) []T
}

WatchAccessors provides the "glue" functions for Watch to go from a list L (returned by the client's List) to the underlying slice of items []T

type WatchClient

type WatchClient[L any] interface {
	List(context.Context, metav1.ListOptions) (L, error)
	Watch(context.Context, metav1.ListOptions) (watch.Interface, error)
}

WatchClient is implemented by the specific interfaces of kubernetes clients, like `Clientset.CoreV1().Pods(namespace)` or `..Nodes()`

This interface should be *already implemented* by whatever the correct client is.

type WatchConfig

type WatchConfig struct {
	// LogName is the name of the watcher for use in logs
	LogName string

	// RetryRelistAfter gives a retry interval when a re-list fails. If left nil, then Watch will
	// not retry.
	RetryRelistAfter *TimeRange
	// RetryWatchAfter gives a retry interval when a non-initial watch fails. If left nil, then
	// Watch will not retry.
	RetryWatchAfter *TimeRange
}

WatchConfig is the miscellaneous configuration used by Watch

type WatchHandlerFuncs

type WatchHandlerFuncs[P any] struct {
	AddFunc    func(obj P, preexisting bool)
	UpdateFunc func(oldObj P, newObj P)
	DeleteFunc func(obj P, mayBeStale bool)
}

WatchHandlerFuncs provides the set of callbacks to use for events from Watch

type WatchIndex added in v0.6.0

type WatchIndex[T any] interface {
	Add(obj *T)
	Update(oldObj, newObj *T)
	Delete(obj *T)
}

WatchIndex represents types that provide some kind of additional index on top of the base listing

Indexing is functionally implemented in the same way that WatchHandlerFuncs is, with the main difference being that more things are done for you with WatchIndexes. In particular, indexes can be added and removed after the Watch has already started, and the locking behavior is explicit.

type WatchObject

type WatchObject[T any] interface {
	~*T
	runtime.Object
	metav1.ObjectMetaAccessor
}

WatchObject is implemented by pointers to T, where T is typically the resource that we're actually watching.

Example implementors: *corev1.Pod, *corev1.Node

type WatchStore

type WatchStore[T any] struct {
	// contains filtered or unexported fields
}

WatchStore provides an interface for getting information about a list of Ts using the event listener from a previous call to Watch

func Watch

func Watch[C WatchClient[L], L metav1.ListMetaAccessor, T any, P WatchObject[T]](
	ctx context.Context,
	client C,
	config WatchConfig,
	accessors WatchAccessors[L, T],
	mode InitWatchMode,
	opts metav1.ListOptions,
	handlers WatchHandlerFuncs[P],
) (*WatchStore[T], error)

Watch starts a goroutine for watching events, using the provided WatchHandlerFuncs as the callbacks for each type of event.

The type C is the kubernetes client we use to get the objects, L representing a list of these, T representing the object type, and P as a pointer to T.

func (*WatchStore[T]) Items

func (w *WatchStore[T]) Items() []*T

func (*WatchStore[T]) Relist added in v0.5.2

func (w *WatchStore[T]) Relist() <-chan struct{}

Relist triggers re-listing the WatchStore, returning a channel that will be closed once the re-list is complete

func (*WatchStore[T]) Stop

func (w *WatchStore[T]) Stop()

func (*WatchStore[T]) Stopped added in v0.5.2

func (w *WatchStore[T]) Stopped() bool

Jump to

Keyboard shortcuts

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