utils

package module
v0.0.3 Latest Latest
Warning

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

Go to latest
Published: Feb 9, 2022 License: MIT Imports: 28 Imported by: 186

README

go.viam.com/utils

PkgGoDev

This is a set of go utilities you can use via importing go.viam.com/utils.

Documentation

Overview

Package utils TODO

Package utils contains all utility functions that currently have no better home than here.

Index

Constants

This section is empty.

Variables

View Source
var Debug = false

Debug is helpful to turn on when the library isn't working quite right.

View Source
var ErrInsufficientX509KeyPair = errors.New("must provide both cert and key of an X509 key pair, not just one part")

ErrInsufficientX509KeyPair is returned when an incomplete X509 key pair is used.

View Source
var Logger = golog.Global

Logger is used various parts of the package for informational/debugging purposes.

Functions

func ContextMainIterFunc

func ContextMainIterFunc(ctx context.Context) func()

ContextMainIterFunc returns a function for indicating an iteration of the program has completed.

func ContextMainQuitSignal

func ContextMainQuitSignal(ctx context.Context) <-chan os.Signal

ContextMainQuitSignal returns a signal channel for quits. It may be nil if the value was never set.

func ContextMainReadyFunc

func ContextMainReadyFunc(ctx context.Context) func()

ContextMainReadyFunc returns a function for indicating readiness. This is intended for main functions that block forever (e.g. daemons).

func ContextWithIterFunc

func ContextWithIterFunc(ctx context.Context, f func()) context.Context

ContextWithIterFunc attaches an iteration func to the given context.

func ContextWithQuitSignal

func ContextWithQuitSignal(ctx context.Context, c <-chan os.Signal) context.Context

ContextWithQuitSignal attaches a quit signaler to the given context.

func ContextWithReadyFunc

func ContextWithReadyFunc(ctx context.Context, c chan<- struct{}) context.Context

ContextWithReadyFunc attaches a ready signaler to the given context.

func ContextualMain

func ContextualMain(main func(ctx context.Context, args []string, logger golog.Logger) error, logger golog.Logger)

ContextualMain calls a main entry point function with a cancellable context via SIGTERM. This should be called once per process so as to not clobber the signals from Notify.

func ContextualMainQuit

func ContextualMainQuit(main func(ctx context.Context, args []string, logger golog.Logger) error, logger golog.Logger)

ContextualMainQuit is the same as ContextualMain but catches quit signals into the provided context accessed via ContextMainQuitSignal.

func FilterOutError

func FilterOutError(err, target error) error

FilterOutError filters out an error based on the given target. For example, if err was context.Canceled and so was the target, this would return nil. Furthermore, if err was a multierr containing a context.Canceled, it would also be filtered out from a new multierr.

func FindGoroutineLeaks

func FindGoroutineLeaks() error

FindGoroutineLeaks finds any goroutine leaks after a program is done running. This should be used at the end of a main test run or a top-level process run.

func GetAllLocalIPv4s

func GetAllLocalIPv4s() ([]string, error)

GetAllLocalIPv4s finds all the local ips from all interfaces It only returns IPv4 addresses, and tries not to return any loopback addresses.

func ManagedGo

func ManagedGo(f func(), onComplete func())

ManagedGo keeps the given function alive in the background until it terminates normally.

func MergeContext added in v0.0.3

func MergeContext(ctx context.Context, otherCtx context.Context) (context.Context, func())

MergeContext merges the two given contexts together and returns a new "child" context parented by the first context that will be cancelled either by the returned cancel function or when either of the two initial contexts are canceled. Note: This implies that the values will only come from the first argument's context.

func MergeContextWithTimeout added in v0.0.3

func MergeContextWithTimeout(ctx context.Context, otherCtx context.Context, timeout time.Duration) (context.Context, func())

MergeContextWithTimeout merges the two given contexts together and returns a new "child" context parented by the first context that will be cancelled either by the returned cancel function, when either of the two initial contexts are canceled, or when the given timeout elapses. Note: This implies that the values will only come from the first argument's context.

func NewConfigValidationError

func NewConfigValidationError(path string, err error) error

NewConfigValidationError returns a config validation error occurring at a given path.

func NewConfigValidationFieldRequiredError

func NewConfigValidationFieldRequiredError(path, field string) error

NewConfigValidationFieldRequiredError returns a config validation error for a field missing at a given path.

func NewPlainTextHTTP2Server

func NewPlainTextHTTP2Server(handler http.Handler) (*http.Server, error)

NewPlainTextHTTP2Server returns an http.Server capable of handling HTTP/2 over plaintext via h2c for the given handler.

func NewPossiblySecureTCPListenerFromConfig added in v0.0.3

func NewPossiblySecureTCPListenerFromConfig(address string, tlsConfig *tls.Config) (net.Listener, bool, error)

NewPossiblySecureTCPListenerFromConfig returns a TCP listener at the given address that is either insecure or TLS based listener depending on presence of certificates in the given TLS Config. If no address is specified, the listener will bind to localhost IPV4 on a random port.

func NewPossiblySecureTCPListenerFromFile added in v0.0.2

func NewPossiblySecureTCPListenerFromFile(address string, tlsCertFile, tlsKeyFile string) (net.Listener, bool, error)

NewPossiblySecureTCPListenerFromFile returns a TCP listener at the given address that is either insecure or TLS based listener depending on presence of the tlsCertFile and tlsKeyFile which are expected to be an X509 key pair. If no address is specified, the listener will bind to localhost IPV4 on a random port.

func NewPossiblySecureTCPListenerFromMemory added in v0.0.3

func NewPossiblySecureTCPListenerFromMemory(address string, tlsCertPEM, tlsKeyPEM []byte) (net.Listener, bool, error)

NewPossiblySecureTCPListenerFromMemory returns a TCP listener at the given address that is either insecure or TLS based listener depending on presence of the tlsCertPEM and tlsKeyPEM which are expected to be an X509 key pair. If no address is specified, the listener will bind to localhost IPV4 on a random port.

func PanicCapturingGo

func PanicCapturingGo(f func())

PanicCapturingGo spawns a goroutine to run the given function and captures any panic that occurs and logs it.

func PanicCapturingGoWithCallback

func PanicCapturingGoWithCallback(f func(), callback func(err interface{}))

PanicCapturingGoWithCallback spawns a goroutine to run the given function and captures any panic that occurs, logs it, and calls the given callback. The callback can be used for restart functionality.

func ParseFlags

func ParseFlags(args []string, into interface{}) error

ParseFlags parses arguments derived from and into the given into struct.

func RandomAlphaString

func RandomAlphaString(size int) string

RandomAlphaString returns a random alphabetic string of the given size. Note(erd): all random strings are subject to modulus bias; hope that does not matter to you.

func RawBytesFromSlice

func RawBytesFromSlice(val interface{}) []byte

RawBytesFromSlice returns a view of the given slice value. It is valid as long as the given value stays within GC.

func ReadBytes

func ReadBytes(ctx context.Context, r io.Reader, toRead int) ([]byte, error)

ReadBytes ensures that all bytes requested to be read are read into a slice unless an error occurs. If the reader never returns the amount of bytes requested, this will block until the given context is done.

func SelectContextOrWait

func SelectContextOrWait(ctx context.Context, dur time.Duration) bool

SelectContextOrWait either terminates because the given context is done or the given duration elapses. It returns true if the duration elapsed.

func SelectContextOrWaitChan

func SelectContextOrWaitChan(ctx context.Context, c <-chan time.Time) bool

SelectContextOrWaitChan either terminates because the given context is done or the given time channel is received on. It returns true if the channel was received on.

func StringSliceRemove

func StringSliceRemove(from []string, at int) []string

StringSliceRemove removes an element from the slice at the given position.

func TryClose

func TryClose(ctx context.Context, target interface{}) error

TryClose attempts to close the target if it implements the right interface.

func TryReserveRandomPort

func TryReserveRandomPort() (port int, err error)

TryReserveRandomPort attempts to "reserve" a random port for later use. It works by listening on a TCP port and immediately closing that listener. In most contexts this is reliable if the port is immediately used after and there is not much port churn. Typically an OS will monotonically increase the port numbers it assigns.

func UncheckedError

func UncheckedError(err error)

UncheckedError is used in places where we really do not care about an error but we want to at least report it. Never use this for closing writers.

func UncheckedErrorFunc

func UncheckedErrorFunc(f func() error)

UncheckedErrorFunc is used in places where we really do not care about an error but we want to at least report it. Never use this for closing writers.

func UnmarshalFlags

func UnmarshalFlags(flagSet *flag.FlagSet, into interface{}) error

UnmarshalFlags unmarshals parsed flags into the given value.

Types

type HTTP2Server

type HTTP2Server struct {
	HTTP1 *http.Server
	HTTP2 *http2.Server
}

HTTP2Server provides dual access to HTTP/2 via a preconfigured HTTP/1 server and a direct access HTTP/2 server.

func NewHTTP2Server

func NewHTTP2Server() (*HTTP2Server, error)

NewHTTP2Server returns an HTTP/2 server. The returned struct contains the http2.Server itself as well as a http.Server that can be used to serve TLS based connections and is also used to gracefully shutdown the HTTP/2 server itself since it does not provide a proper shutdown method.

func (*HTTP2Server) Close

func (srv *HTTP2Server) Close() error

Close shuts down the HTTP/1 server which in turn triggers the HTTP/2 server to shutdown (albeit not immediately).

type NetPortFlag

type NetPortFlag int

NetPortFlag is used to correctly set and validate a network port.

func (*NetPortFlag) Get

func (npf *NetPortFlag) Get() interface{}

Get returns the value as an integer.

func (*NetPortFlag) Set

func (npf *NetPortFlag) Set(val string) error

Set attempts to set the value as a network port.

func (*NetPortFlag) String

func (npf *NetPortFlag) String() string

String returns the set value.

type RefCountedValue

type RefCountedValue interface {
	// Ref increments the reference count and returns the value.
	Ref() interface{}

	// Deref decrements the reference count and returns if this
	// dereference resulted in the value being unreferenced.
	Deref() (unreferenced bool)
}

RefCountedValue is a utility to "reference count" values in order to destruct them once no one references them. If you don't require that kind of logic, just rely on golang's garbage collection.

func NewRefCountedValue

func NewRefCountedValue(val interface{}) RefCountedValue

NewRefCountedValue returns a new reference counted value for the given value. Its reference count starts at zero but is not released. It is assumed the caller of this will reference it at least once.

type StringSet

type StringSet map[string]struct{}

StringSet represents a mathematical set of string.

func NewStringSet

func NewStringSet(values ...string) StringSet

NewStringSet returns a new string set from the given series of values where duplicates are okay.

Directories

Path Synopsis
Package artifact contains a solution for storing and fetching versioned blobs of data that are resolved on demand.
Package artifact contains a solution for storing and fetching versioned blobs of data that are resolved on demand.
cmd/artifact
Package main provides the artifact CLI for importing and exporting artifacts.
Package main provides the artifact CLI for importing and exporting artifacts.
tools
Package tools implements the sub-commands for the artifact CLI.
Package tools implements the sub-commands for the artifact CLI.
Package internal contains utilities not meant for external consumption.
Package internal contains utilities not meant for external consumption.
Package mongoutils contains utilities for working with MongoDB more effectively.
Package mongoutils contains utilities for working with MongoDB more effectively.
Package perf exposes application performance utilities.
Package perf exposes application performance utilities.
Package pexec defines process management utilities to be used as a library within a go process wishing to own sub-processes.
Package pexec defines process management utilities to be used as a library within a go process wishing to own sub-processes.
proto
rpc/examples/echo/v1
Package v1 is a reverse proxy.
Package v1 is a reverse proxy.
rpc/examples/fileupload/v1
Package v1 is a reverse proxy.
Package v1 is a reverse proxy.
rpc/v1
Package v1 is a reverse proxy.
Package v1 is a reverse proxy.
rpc/webrtc/v1
Package v1 is a reverse proxy.
Package v1 is a reverse proxy.
rpc
Package rpc provides a remote procedure call (RPC) library based on gRPC.
Package rpc provides a remote procedure call (RPC) library based on gRPC.
examples/echo/client
Package main runs a gRPC client over WebRTC connecting to the proto/rpc/examples/echo/v1 service.
Package main runs a gRPC client over WebRTC connecting to the proto/rpc/examples/echo/v1 service.
examples/echo/server
Package server implement an echo server.
Package server implement an echo server.
examples/echo/server/cmd
Package main runs a gRPC server running the proto/rpc/examples/echo/v1 service.
Package main runs a gRPC server running the proto/rpc/examples/echo/v1 service.
examples/fileupload/server
Package server implement a file upload server.
Package server implement a file upload server.
examples/fileupload/server/cmd
Package main runs a gRPC server running the proto/rpc/examples/fileupload/v1 service.
Package main runs a gRPC server running the proto/rpc/examples/fileupload/v1 service.
Package secrets helps manage application runtime secrets.
Package secrets helps manage application runtime secrets.
Package serial provides utilities for searching for and working with serial based devices.
Package serial provides utilities for searching for and working with serial based devices.
Package testutils provides various utilities for use in tests.
Package testutils provides various utilities for use in tests.
ext
Package testutilsext is purely for test utilities that may access other packages in the codebase that tend to use testutils.
Package testutilsext is purely for test utilities that may access other packages in the codebase that tend to use testutils.
Package usb provides utilities for searching for and working with usb based devices.
Package usb provides utilities for searching for and working with usb based devices.
Package web contains utilities to help build out a web service.
Package web contains utilities to help build out a web service.

Jump to

Keyboard shortcuts

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