util

package
v0.29.2 Latest Latest
Warning

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

Go to latest
Published: May 14, 2024 License: Apache-2.0 Imports: 20 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 AbsDiff added in v0.12.0

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

AbsDiff returns the absolute value of the difference between x and y

func AddHandler

func AddHandler[T any, R any](
	logger *zap.Logger,
	mux *http.ServeMux,
	endpoint string,
	method string,
	reqTypeName string,
	handle func(context.Context, *zap.Logger, *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[T any]() (SignalSender[T], SignalReceiver[T])

func PodCompleted added in v0.8.0

func PodCompleted(pod *corev1.Pod) bool

PodCompleted returns true iff all of the Pod's containers have stopped and will not be restarted

func PodNameFields added in v0.10.0

func PodNameFields(pod *corev1.Pod) zap.Field

func PodPreferredAZIfPresent added in v0.27.0

func PodPreferredAZIfPresent(pod *corev1.Pod) string

PodPreferredAZIfPresent returns the desired availability zone of the Pod, if it has one

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 RegisterMetric added in v0.8.0

func RegisterMetric[P prometheus.Collector](reg prometheus.Registerer, collector P) P

func RootError added in v0.8.0

func RootError(err error) error

RootError returns the root cause of the error, calling errors.Unwrap until it returns nil

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, logger *zap.Logger, port uint16, reg *prometheus.Registry) error

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

func VMNameFields added in v0.10.0

func VMNameFields(vm *vmapi.VirtualMachine) zap.Field

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 BroadcastReceiver added in v0.18.0

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

func (*BroadcastReceiver) Awake added in v0.18.0

func (r *BroadcastReceiver) Awake()

Awake marks the most recent broadcast event as received, so that the next call to Wait returns a channel that will only be closed once there's been a new event after this call to Awake.

func (*BroadcastReceiver) Wait added in v0.18.0

func (r *BroadcastReceiver) Wait() <-chan struct{}

Wait returns a channel that will be closed once there has been an event broadcasted since the BroadcastReceiver was created, or the last call to Awake().

Typical usage of Wait will involve selecting on the channel returned and calling Awake immediately in the branch handling the event, for example:

select {
case <-ctx.Done():
    return
case <-receiver.Wait():
    receiver.Awake()
    ...
}

type Broadcaster added in v0.18.0

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

func NewBroadcaster added in v0.18.0

func NewBroadcaster() *Broadcaster

func (*Broadcaster) Broadcast added in v0.18.0

func (b *Broadcaster) Broadcast()

Broadcast sends a signal to all receivers

func (*Broadcaster) NewReceiver added in v0.18.0

func (b *Broadcaster) NewReceiver() BroadcastReceiver

NewReceiver creates a new BroadcastReceiver that will receive only future broadcasted events.

It's generally not recommended to call (*BroadcastReceiver).Wait() on a single BroadcastReceiver from more than one thread at a time, although it *is* thread-safe.

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 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 TryPodOwnerVirtualMachine added in v0.18.1

func TryPodOwnerVirtualMachine(pod *corev1.Pod) *NamespacedName

TryPodOwnerVirtualMachine returns the name of the VirtualMachine that owns the pod, if there is one that does. Otherwise returns nil.

func TryPodOwnerVirtualMachineMigration added in v0.18.1

func TryPodOwnerVirtualMachineMigration(pod *corev1.Pod) *NamespacedName

TryPodOwnerVirtualMachineMigration returns the name of the VirtualMachineMigration that owns the pod, if there is one. Otherwise returns nil.

func (NamespacedName) Format added in v0.6.0

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

func (NamespacedName) MarshalLogObject added in v0.10.0

func (n NamespacedName) MarshalLogObject(enc zapcore.ObjectEncoder) error

MarshalLogObject implements zapcore.ObjectMarshaler, so that NamespacedName can be used with zap.Object

type RecentCounter added in v0.28.0

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

RecentCounter is a struct that keeps track of recent timestamps within a given interval.

func NewRecentCounter added in v0.28.0

func NewRecentCounter(interval time.Duration) *RecentCounter

func (*RecentCounter) Get added in v0.28.0

func (rc *RecentCounter) Get() uint

Get returns the number of recent timestamps stored in the RecentCounter.

func (*RecentCounter) Inc added in v0.28.0

func (rc *RecentCounter) Inc()

Inc increments the counter and adds the current timestamp to the list of timestamps.

type SignalReceiver

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

func (SignalReceiver[T]) Close

func (s SignalReceiver[T]) Close()

func (SignalReceiver[T]) Recv

func (s SignalReceiver[T]) Recv() <-chan T

type SignalSender

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

func (SignalSender[T]) Send

func (s SignalSender[T]) Send(data T)

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

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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