utils

package
v0.0.0-...-3bfe646 Latest Latest
Warning

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

Go to latest
Published: Jun 28, 2023 License: Apache-2.0 Imports: 74 Imported by: 38

Documentation

Index

Constants

View Source
const (
	// KeySuffix is the standard extension used for x509 key files generated by gravity
	KeySuffix = "key"
	// CertSuffix is the standard extension used for x509 cert files generated by gravity
	CertSuffix = "cert"
)

Variables

View Source
var DiscardPrinter = nopPrinter{}

DiscardPrinter is a Printer that discards all input

View Source
var DiscardingLog = newDiscardingLogger()

DiscardingLog is a logger that discards output

View Source
var Exe = must(NewCurrentExecutable())

Exe is the Executable for the currently running gravity binary

Functions

func BoolPtr

func BoolPtr(v bool) *bool

BoolPtr returns a pointer to a bool with value v

func BoolValue

func BoolValue(v *bool) bool

BoolValue returns the boolean value in v or false if it's nil

func CheckEmail

func CheckEmail(email string) error

CheckEmail is a simplistic email checker

func CheckInPlanet

func CheckInPlanet() bool

CheckInPlanet returns whether the process was started inside the container

func CheckName

func CheckName(name string) error

CheckName makes sure that the provided string is a valid app name

func CheckUserName

func CheckUserName(name string) error

CheckUserName validates user name

func Chown

func Chown(path string, uid, gid int) error

Chown adjusts ownership of the specified directory and all its subdirectories

func Collect

func Collect(ctx context.Context, cancel func(), errChan chan error, valuesChan chan interface{}) ([]interface{}, error)

Collect collects errors and values from channel provided, honouring timeout it will expect exactly cap(errChan) messages value channel could be nil. If not nil, then cap(errCh) == cap(valueCh) it will also cancel context on first error occurred if cancel func is not nil

func CollectErrors

func CollectErrors(ctx context.Context, errChan chan error) error

CollectErrors exhausts error channel errChan up to its capacity and returns aggregate error if any

func CombineLabels

func CombineLabels(labels ...map[string]string) (result map[string]string)

CombineLabels combines the specified label sets into a single map. Existing labels will get overwritten with the last value

func CombinedOutput

func CombinedOutput(cmd *exec.Cmd, out io.Writer) (string, error)

func ConvertEC2Error

func ConvertEC2Error(err error) error

ConvertEC2Error converts error from AWS EC2 API to appropriate trace error.

func ConvertS3Error

func ConvertS3Error(err error) error

ConvertS3Error converts an error from AWS S3 API to an appropriate trace error

func CopyDirContents

func CopyDirContents(fromDir, toDir string) error

CopyDirContents copies all contents of the source directory (including the source directory itself and all its sub-directories) to the destination directory

func CopyExecutable

func CopyExecutable(dst string, src io.Reader) error

CopyExecutable copies the provided reader to the specified destination and sets executable permissions.

func CopyFile

func CopyFile(dst, src string) error

CopyFile copies contents of src to dst atomically using SharedReadWriteMask as permissions.

func CopyFileWithOptions

func CopyFileWithOptions(dst, src string, options ...FileOption) error

CopyFileWithOptions copies the contents from src to dst atomically. Applies specified options to the target path

func CopyFileWithPerms

func CopyFileWithPerms(dst, src string, perm os.FileMode) error

CopyFileWithPerms copies the contents from src to dst atomically. Uses CopyReaderWithPerms for its implementation - see function documentation for details of operation

func CopyReader

func CopyReader(dst string, src io.Reader) error

CopyReader copies contents of src to dst atomically using SharedReadWriteMask as permissions.

func CopyReaderWithOptions

func CopyReaderWithOptions(dst string, src io.Reader, options ...FileOption) error

CopyReaderWithOptions copies the contents from src to dst atomically. If dst does not exist, CopyReaderWithOptions creates it. Callers choose the options to apply on the resulting file with options

func CopyReaderWithPerms

func CopyReaderWithPerms(dst string, src io.Reader, perm os.FileMode) error

CopyReaderWithPerms copies the contents from src to dst atomically. If dst does not exist, CopyReaderWithPerms creates it with permissions perm. If the copy fails, CopyReaderWithPerms aborts and dst is preserved. Adopted with modifications from https://go-review.googlesource.com/#/c/1591/9/src/io/ioutil/ioutil.go

func CopyWithRetries

func CopyWithRetries(ctx context.Context, targetPath string, open func() (io.ReadCloser, error), options ...FileOption) error

CopyWithRetries copies the contents of the reader obtained with open to targetPath retrying on transient errors

func CreateTLSArchive

func CreateTLSArchive(a TLSArchive) (io.ReadCloser, error)

CreateTLSArchive creates archive with TLS keypairs, where keys are stored with extension ".key" and certificates are stored with extension ".cert"

func DecryptPGP

func DecryptPGP(data io.Reader, passphrase string) (io.Reader, error)

DecryptPGP returns a stream with "data" decrypted by the provided passphrase

func DefaultStepPrinter

func DefaultStepPrinter(out io.Writer, current, target int, message string)

DefaultStepPrinter outputs the message to out as it is.

func DetectPlanetEnvironment

func DetectPlanetEnvironment()

DetectPlanetEnvironment detects if the process is executed inside the container

func DurationPtr

func DurationPtr(v time.Duration) *teleservices.Duration

DurationPtr returns a pointer to the provided duration value

func EncryptPGP

func EncryptPGP(data io.Reader, passphrase string) (io.ReadCloser, error)

EncryptPGP returns a stream with "data" encrypted by the provided passphrase

func EnsureLineInFile

func EnsureLineInFile(path, line string) error

EnsureLineInFile makes sure the specified file contains provided line

func EnsureLocalPath

func EnsureLocalPath(customPath, defaultLocalDir, defaultLocalPath string) (string, error)

EnsureLocalPath makes sure the path exists, or, if omitted results in the subpath in default gravity config directory, e.g.

EnsureLocalPath("/custom/myconfig", ".gravity", "config") -> /custom/myconfig EnsureLocalPath("", ".gravity", "config") -> ${HOME}/.gravity/config

It also makes sure that base dir exists

func EnsurePort

func EnsurePort(address, defaultPort string) string

EnsurePort makes sure that the provided address includes a port and adds the specified default one if it does not.

func EnsurePortURL

func EnsurePortURL(url, defaultPort string) string

EnsurePortURL is like EnsurePort but for URLs.

func EnsureScheme

func EnsureScheme(url, defaultScheme string) string

EnsureScheme makes sure the provided URL contains http or https scheme and adds the specified default one if it does not.

func EtcdHasMember

func EtcdHasMember(peers []etcd.Member, peerURL string) *etcd.Member

EtcdHasMember returns the peer given its peerURL. Returns nil if no peer exists with the specified peerURL

func EtcdInitialCluster

func EtcdInitialCluster(memberListOutput string) (string, error)

EtcdInitialCluster interprets the output of etcdctl member list as a comma-separated list of name:ip pairs.

func Exec

func Exec(cmd *exec.Cmd, out io.Writer, setters ...CommandOptionSetter) error

func ExecL

func ExecL(cmd *exec.Cmd, out io.Writer, logger log.FieldLogger, setters ...CommandOptionSetter) error

ExecL executes the specified cmd and logs the command line to the specified entry

func ExecUnprivileged

func ExecUnprivileged(ctx context.Context, command string, args []string, opts ...CommandOptionSetter) error

ExecUnprivileged executes the specified command as unprivileged user

func ExecWithInput

func ExecWithInput(cmd *exec.Cmd, input string, out io.Writer, setters ...CommandOptionSetter) error

func ExecuteWithDelay

func ExecuteWithDelay(args []string, delay time.Duration) error

func ExitStatusFromError

func ExitStatusFromError(err error) *int

ExitStatusFromError returns the exit status from the specified error. If the error is not exit status error, return nil

func ExtractHost

func ExtractHost(addr string) string

ExtractHost returns only the host part from the provided address.

func FindETCDMemberID

func FindETCDMemberID(output, name string) (string, error)

FindETCDMemberID finds Member ID by node name in the output from etcd member list:

6e3bd23ae5f1eae0: name=node2 peerURLs=http://localhost:23802 clientURLs=http://127.0.0.1:23792
924e2e83e93f2560: name=node3 peerURLs=http://localhost:23803 clientURLs=http://127.0.0.1:23793
a8266ecf031671f3: name=node1 peerURLs=http://localhost:23801 clientURLs=http://127.0.0.1:23791

func FlattenStringSlice

func FlattenStringSlice(slice []string) (retval []string)

FlattenStringSlice takes a slice of strings like ["one,two", "three"] and returns ["one", "two", "three"]

func FlattenVersion

func FlattenVersion(version string) string

FlattenVersion removes or replaces characters from the version string to make it useable as part of kubernetes resource names

func FormatBoolPtr

func FormatBoolPtr(v *bool) string

FormatBoolPtr formats the bool pointer value for output

func FormatMeta

func FormatMeta(meta metav1.ObjectMeta) string

FormatMeta formats the specified object metadata for output

func FormatStringPtrWithDefault

func FormatStringPtrWithDefault(v *string, def string) string

FormatStringPtrWithDefault formats the string pointer value for output. If the pointer value is nil, the specified default is used

func GeneratePrivateKeyPEM

func GeneratePrivateKeyPEM() ([]byte, error)

GeneratePrivateKeyPEM generates and returns PEM serialzed

func GenerateSelfSignedCert

func GenerateSelfSignedCert(hostNames []string) (*teleutils.TLSCredentials, error)

GenerateSelfSignedCert generates a self signed certificate that is valid for given domain names and ips, returns PEM-encoded bytes with key and cert Generates a certificate that is compatible with the MacOS requirements described at: https://support.apple.com/en-us/HT210176

func GetKubeClient

func GetKubeClient(configPath string) (client *kubernetes.Clientset, config *rest.Config, err error)

GetKubeClient returns instance of client to the kubernetes cluster using in-cluster configuration if available and falling back to configuration file under configPath otherwise

func GetLocalKubeClient

func GetLocalKubeClient() (*kubernetes.Clientset, *rest.Config, error)

GetLocalKubeClient returns a client with config from KUBECONFIG env var or ~/.kube/config

func GetLocalPath

func GetLocalPath(customPath, defaultLocalDir, defaultLocalPath string) (string, error)

GetLocalPath constructs path to the local gravity config file like described in the EnsureLocalPath above.

func GetMasters

func GetMasters(nodes map[string]v1.Node) (ips []string)

GetMasters returns IPs of nodes which are marked with a "master" label

func GetNodes

func GetNodes(client corev1.NodeInterface) (nodes map[string]v1.Node, err error)

GetNodes returns the map of kubernetes nodes keyed by advertise IPs

func GetPasswd

func GetPasswd() (io.ReadCloser, error)

GetPasswd returns the reader to the contents of the passwd file

func Getenv

func Getenv(envs ...string) (environ map[string]string)

Getenv returns the map of name->value pairs that captures the specified list of environment variables. Only variables with a value are captured

func GetenvDuration

func GetenvDuration(name string) (dur time.Duration, err error)

GetenvDuration returns the specified environment variable value parsed as a duration.

func GetenvInt

func GetenvInt(name string) (int, error)

GetenvInt returns the specified environment variable value parsed as an integer.

func GetenvWithDefault

func GetenvWithDefault(name, defaultValue string) string

GetenvWithDefault returns the value of the environment variable given with name or defaultValue if the variable does not exist

func GetenvsByPrefix

func GetenvsByPrefix(prefix string) (environ map[string]string)

GetenvsByPrefix returns environment variables with names matching specified prefix.

func HasOneOfPrefixes

func HasOneOfPrefixes(s string, prefixes ...string) bool

HasOneOfPrefixes returns true if the provided string starts with any of the specified prefixes

func Hosts

func Hosts(addrs []string) (hosts []string)

Hosts returns a list of hosts from the provided host:port addresses

func InitGRPCLogger

func InitGRPCLogger(severityLevel string, verbosity int)

InitGRPCLogger initializes the logger with specified severity and verbosity. Severity level is one of `info`, `warning` or `error` and defaults to error if unspecified. Verbosity is a non-negative integer.

func InitGRPCLoggerFromEnvironment

func InitGRPCLoggerFromEnvironment()

InitGRPCLoggerFromEnvironment configures the GRPC logger if any of the related environment variables are set.

func InitGRPCLoggerWithDefaults

func InitGRPCLoggerWithDefaults()

InitGRPCLoggerWithDefaults configures the GRPC logger with debug defaults.

func InitLogging

func InitLogging(level log.Level, logFile string)

InitLogging initializes logging to log both to syslog and to a file

func Int64Ptr

func Int64Ptr(v int64) *int64

Int64Ptr returns a pointer to an int64 with value v

func IntPtr

func IntPtr(v int) *int

IntPtr returns a pointer to an int with value v

func IsAPIServerService

func IsAPIServerService(service v1.Service) bool

IsAPIServerService return true if the given service specifies the API server service

func IsAbortError

func IsAbortError(err error) bool

IsAbortError returns true if the specified error is of type AbortRetry

func IsClosedConnectionError

func IsClosedConnectionError(err error) bool

IsClosedConnectionError determines if the specified error is a closed connection error

func IsClosedResponseBodyErrorMessage

func IsClosedResponseBodyErrorMessage(err string) bool

IsClosedResponseBodyErrorMessage determines if the error message describes a closed response body error

func IsClusterDegradedError

func IsClusterDegradedError(err error) bool

IsClusterDegradedError determines if the error indicates that the cluster is degraded

func IsClusterUnavailableError

func IsClusterUnavailableError(err error) bool

IsClusterUnavailableError determines if the specified error is a cluster unavailable error

func IsConnectionProblem

func IsConnectionProblem(err error) bool

IsConnectionProblem determines whether err signifies a connection problem

func IsConnectionRefusedError

func IsConnectionRefusedError(err error) bool

IsConnectionRefusedError determines whether err is a 'connection refused' error. err is expected to be non-nil

func IsConnectionResetError

func IsConnectionResetError(err error) bool

IsConnectionResetError determines whether err is a 'connection reset by peer' error. err is expected to be non-nil

func IsContextCancelledError

func IsContextCancelledError(err error) bool

IsContextCancelledError returns true if the provided error is a result of a context cancellation

func IsContinueError

func IsContinueError(err error) bool

IsContinueError returns true if provided error is of ContinueRetry type

func IsDirectory

func IsDirectory(path string) (bool, error)

IsDirectory determines if path specifies a directory

func IsDirectoryEmpty

func IsDirectoryEmpty(dir string) (bool, error)

IsDirectoryEmpty returns true if the specified directory is empty The directory must exist or an error will be returned

func IsFile

func IsFile(path string) (bool, error)

IsFile determines if path specifies a regular file

func IsHeadlessService

func IsHeadlessService(service v1.Service) bool

IsHeadlessService return true if the given service is a headless service (explicitly without a cluster IP)

func IsKubeAuthError

func IsKubeAuthError(err error) bool

IsKubeAuthError determines whether the specified error is an authorization error from kubernetes client.

func IsKubernetesLabel

func IsKubernetesLabel(key string) bool

IsKubernetesLabel returns true if the provided label key is in Kubernetes namespace.

This and getLabelNamespace function below are adopted from:

https://github.com/kubernetes/kubernetes/blob/release-1.16/cmd/kubelet/app/options/options.go#L249.

func IsNetworkError

func IsNetworkError(err error) bool

IsNetworkError returns true if the provided error is Go's network error

func IsPathError

func IsPathError(err error) bool

IsPathError determines if the specified err is of type os.PathError

func IsResourceBusyError

func IsResourceBusyError(err error) bool

IsResourceBusyError determines if the specified error identifies a 'device or resource busy' error

func IsStreamClosedError

func IsStreamClosedError(err error) bool

IsStreamClosedError determines if the given error is a response/stream closed error

func IsTransientClusterError

func IsTransientClusterError(err error) bool

IsTransientClusterError determines if the specified error corresponds to a transient error - e.g. which can be retried. An error that can be retried is either a connection failure or an etcd cluster error.

func KubeServiceNames

func KubeServiceNames(serviceName, namespace string) []string

KubeServiceNames returns all possible DNS names a specified Kubernetes service can be accessed by in the specified namespace.

func LoadKubeConfig

func LoadKubeConfig() (*clientcmdapi.Config, error)

LoadKubeConfig tries to read a kubeconfig file and if it can't, returns an error. One exception, missing files result in empty configs, not an error.

func LocalIPNetworks

func LocalIPNetworks() (blocks []net.IPNet, err error)

LocalIPNetworks returns the list of all local IP networks

func LoggerWithService

func LoggerWithService(service v1.Service, logger log.FieldLogger) log.FieldLogger

LoggerWithService returns a new logger with service-relevant metadata

func MakeSelector

func MakeSelector(in map[string]string) labels.Selector

MakeSelector converts set of key-value pairs to selector

func MatchesLabels

func MatchesLabels(targetLabels, wantedLabels map[string]string) bool

MatchesLabels determines whether a set of "target" labels matches the set of "wanted" labels

func Max

func Max(x, y int) int

Max returns the greater of two numbers

func MaxInt64

func MaxInt64(x, y uint64) uint64

MaxInt64 returns the greater of (x, y).

func Min

func Min(x, y int) int

Min returns the smaller of two numbers

func MkdirAll

func MkdirAll(targetDirectory string, mode os.FileMode) error

MkdirAll creates directory and subdirectories

func MustSHA512Half

func MustSHA512Half(v []byte) string

MustSHA512Half panics if it fails to compute SHA512 hash, use only in tests

func NewExitCodeError

func NewExitCodeError(exitCode int) error

NewExitCodeError returns a new error with the specified exit code

func NewExitCodeErrorWithMessage

func NewExitCodeErrorWithMessage(exitCode int, message string) error

NewExitCodeErrorWithMessage returns a new error that wraps a specific exit code and message

func NewExponentialBackOff

func NewExponentialBackOff(timeout time.Duration) *backoff.ExponentialBackOff

NewExponentialBackOff creates a new backoff interval with the specified timeout

func NewFailedPreconditionError

func NewFailedPreconditionError(err error) error

NewFailedPreconditionError returns a new failed precondition error with optional original error err

func NewMultiWriteCloser

func NewMultiWriteCloser(writeClosers ...io.WriteCloser) io.WriteCloser

NewMultiWriteCloser returns new WriteCloser, all writes go to all writers one by one and close closes all closers one by one

func NewPreconditionFailedError

func NewPreconditionFailedError(err error) error

NewPreconditionFailedError returns a new error signifying a failed precondition

func NewTailReader

func NewTailReader(path string) (io.ReadCloser, error)

func NewUninstallServiceError

func NewUninstallServiceError(err error, servicePackage loc.Locator) error

NewUninstallServiceError returns a plan out of sync error

func NewUnlimitedExponentialBackOff

func NewUnlimitedExponentialBackOff() *backoff.ExponentialBackOff

NewUnlimitedExponentialBackOff returns a backoff interval without time restriction

func NopWriteCloser

func NopWriteCloser(w io.Writer) io.WriteCloser

NopWriteCloser returns a WriteCloser with a no-op Close method wrapping the provided Writer w.

func NormalizePath

func NormalizePath(path string) (string, error)

NormalizePath normalises path, evaluating symlinks and converting local paths to absolute

func OpenFile

func OpenFile(path string) (*os.File, error)

OpenFile opens the file at the provided path in a+ mode

func ParseAddrList

func ParseAddrList(l string) ([]string, error)

ParseAddrList parses a comma-separated list of addresses

func ParseBoolFlag

func ParseBoolFlag(r *http.Request, name string, def bool) (bool, error)

ParseBoolFlag extracts boolean parameter of the specified name from the provided request's query string, or returns default.

func ParseDDOutput

func ParseDDOutput(output string) (uint64, error)

ParseDDOutput parses the output of "dd" command and returns the reported speed in bytes per second.

Example output:

$ dd if=/dev/zero of=/tmp/testfile bs=1G count=1 1+0 records in 1+0 records out 1073741824 bytes (1.1 GB) copied, 4.52455 s, 237 MB/s

func ParseDiscard

func ParseDiscard(r *bufio.Reader) error

ParseDiscard returns a no-op parser function that discards the input

func ParseFilename

func ParseFilename(req *http.Request, key string) (string, error)

ParseFilename parses the filename for the specified form data.

func ParseHostOverride

func ParseHostOverride(override string) (domain, ip string, err error)

ParseHostOverride parses DNS host override in the format <host>/<ip>

func ParseHostPort

func ParseHostPort(in string) (host string, port int32, err error)

ParseHostPort parses the provided address as host:port

func ParseLabels

func ParseLabels(labelsS string) map[string]string

ParseLabels parses a string like "a=b,c=d" as a map

func ParseOpsCenterAddress

func ParseOpsCenterAddress(in, defaultPort string) string

ParseOpsCenterAddress parses OpsCenter address

func ParsePorts

func ParsePorts(ranges string) ([]int, error)

ParsePorts parses the provided string specifying one or multiple ports or port ranges in the following form:

"80, 8081, 8001-8003"

and translates it to an int slice with these ports

func ParseProxy

func ParseProxy(proxy string) (*url.URL, error)

ParseProxy parses the provided HTTP(-S) proxy address and returns it in the parsed URL form. The proxy value is expected to be a complete URL that includes a scheme (http, https or socks5).

This function is loosely based on Go's proxy parsing method:

https://github.com/golang/go/blob/release-branch.go1.15/src/vendor/golang.org/x/net/http/httpproxy/proxy.go#L149-L170

func ParseProxyAddr

func ParseProxyAddr(proxyAddr, defaultWebPort, defaultSSHPort string) (host string, webPort string, sshPort string, err error)

ParseProxyAddr parses proxy address in the format "host:webPort,sshPort"

If web/SSH ports are missing the provided defaults are used.

func ParseSystemdVersion

func ParseSystemdVersion(out string) (int, error)

ParseSystemdVersion parses the output of "systemctl --version" command and returns systemd version number. The output looks like this:

systemd 219
+PAM +AUDIT +SELINUX +IMA -APPARMOR +SMACK +SYSVINIT +UTMP +LIBCRYPTSETUP +GCRYPT +GNUTLS +ACL +XZ -LZ4 -SECCOMP +BLKID +ELFUTILS +KMOD +IDN

func ParseZoneOverride

func ParseZoneOverride(override string) (zone, nameserver string, err error)

ParseZoneOverride parses DNS zone override in the format <host>/<ip> or <host>/<ip>:<port>

func PickAdvertiseIP

func PickAdvertiseIP() (string, error)

PickAdvertiseIP selects an advertise IP among the host's interfaces

func PlanetCommand

func PlanetCommand(cmd Command) []string

PlanetCommand returns a new command to run the specified command cmd inside planet container.

func PlanetCommandArgs

func PlanetCommandArgs(args ...string) []string

PlanetCommandArgs returns a new command to run the command specified with args inside planet container. For details of operation see PlanetCommandSlice

func PlanetCommandSlice

func PlanetCommandSlice(args []string, gravityArgs ...string) []string

PlanetCommandSlice returns a new command to run the command specified with args inside planet. If the process is already running inside the container, the command is returned unaltered. gravityArgs optionally specify additional arguments to the gravity binary The command is using the path of the currently running process for the fork call.

func PlanetEnterCommand

func PlanetEnterCommand(args ...string) []string

PlanetEnterCommand returns command that runs in planet using gravity from path

func PrintProgress

func PrintProgress(current, target int, message string)

PrintProgress prints generic progress with stages

func ProgressBar

func ProgressBar(current, target int64) string

func ReadEnv

func ReadEnv(path string) (map[string]string, error)

ReadEnv reads the file at the specified path as a file containing environment variables (e.g. /etc/environment)

func ReadPath

func ReadPath(path string) ([]byte, error)

ReadPath reads file at given path

func ReaderForPath

func ReaderForPath(path string) (io.ReadCloser, error)

ReaderForPath returns a reader for file at given path

func RecursiveGlob

func RecursiveGlob(dir string, patterns []string, handler func(match string) error) error

RecursiveGlob recursively walks the dir and returns the list of files matching the specified patterns.

func RemoveContents

func RemoveContents(dir string) error

RemoveContents removes any children of dir. It removes everything it can but returns the first error it encounters. If the dir does not exist, RemoveContents returns nil.

func RemoveNewlines

func RemoveNewlines(s string) string

RemoveNewlines removes newlines from string

func ResolveAddr

func ResolveAddr(dnsAddr, addr string) (hostPort string, err error)

ResolveAddr resolves the provided hostname using the local resolver

func Retry

func Retry(period time.Duration, maxAttempts int, fn func() error) error

Retry attempts to execute fn up to maxAttempts sleeping for period between attempts. fn can return an instance of Abort to abort or Continue to continue the execution.

func RetryFor

func RetryFor(ctx context.Context, timeout time.Duration, fn func() error) error

RetryFor retries the provided function until it succeeds or until timeout has been reached

func RetryOnNetworkError

func RetryOnNetworkError(period time.Duration, maxAttempts int, fn func() error) error

RetryOnNetworkError attempts to execute fn up to maxAttempts sleeping for period between attempts if the encountered error is of network nature.

func RetryRead

func RetryRead(getReadCloser func() (io.ReadCloser, error), period time.Duration, attempts int) (io.ReadCloser, error)

RetryRead reads the contents of the reader to the temporary file and retries several times on failure. It closes the reader returned by getReadCloser function at all times

func RetryTransient

func RetryTransient(ctx context.Context, interval backoff.BackOff, fn func() error) error

RetryTransient retries the specified operation fn using the specified backoff interval if the operation is experiencing transient errors. Etcd cluster errors as well as kubernetes unauthorzied errors are considered transient. Returns any non-transient error or nil if the operation is successful.

func RetryWithInterval

func RetryWithInterval(ctx context.Context, interval backoff.BackOff, fn func() error) error

RetryWithInterval retries the specified operation fn using the specified backoff interval. classify specifies the error classifier that can create circuit-breakers for specific error conditions. classify should return backoff.PermanentError if the error should not be retried and returned directly. Returns nil on success or the last received error upon exhausting the interval.

func RunCommand

func RunCommand(ctx context.Context, logger log.FieldLogger, args ...string) ([]byte, error)

RunCommand executes the command specified with args

func RunGravityCommand

func RunGravityCommand(ctx context.Context, log log.FieldLogger, args ...string) ([]byte, error)

RunGravityCommand executes the command specified with args with the current process binary

func RunInPlanetCommand

func RunInPlanetCommand(ctx context.Context, log log.FieldLogger, args ...string) ([]byte, error)

RunInPlanetCommand executes the command specified with args inside planet container

func RunKubernetesTests

func RunKubernetesTests() bool

RunKubernetesTests returns true if requested to run tests against running kubernetes. This mode requires kubeconfig to point to proper cluster with gravity running

func RunPlanetCommand

func RunPlanetCommand(ctx context.Context, log log.FieldLogger, args ...string) ([]byte, error)

RunPlanetCommand executes the command specified with args as a planet command inside the container

func RunStream

func RunStream(ctx context.Context, stdout, stderr io.Writer, args ...string) error

RunStream executes a command specified with args and streams output to w

func SHA512Half

func SHA512Half(v []byte) (string, error)

SHA512Half is a first half of SHA512 hash of the byte string

func SSHRunAndParse

func SSHRunAndParse(
	ctx context.Context,
	client *ssh.Client,
	log logrus.FieldLogger,
	cmd string,
	env map[string]string,
	output io.Writer,
	parse OutputParseFn,
) (err error)

SSHRunAndParse runs remote SSH command cmd with environment variables set with env. parse if set, will be provided the reader that consumes stdout of the command. Returns *ssh.ExitError if the command has completed with a non-0 exit code, *ssh.ExitMissingError if the other side has terminated the session without providing the exit code and nil for no error

func SanitizeSemver

func SanitizeSemver(ver semver.Version) error

SanitizeSemver validates semver pre-release/metadata fields are alphanumeric characters dash and dot as per https://semver.org/#semantic-versioning-specification-semver

func SaveKubeConfig

func SaveKubeConfig(config clientcmdapi.Config) error

SaveKubeConfig saves updated config to location specified by environment variable or default location

func SelectSubnet

func SelectSubnet(blocks []string) (string, error)

SelectSubnet returns a /16 subnet that does not overlap with the provided subnet blocks

func SelectVPCSubnet

func SelectVPCSubnet(vpcBlock string, subnetBlocks []string) (string, error)

SelectVPCSubnet returns a /24 subnet that does not overlap with the provided subnet blocks from the provided VPC block

func Self

func Self(args ...string) []string

Self returns the command line for the currently running executable. args specifies additional command line arguments

func ShouldReconnectPeer

func ShouldReconnectPeer(err error) error

ShouldReconnectPeer implements the error classification for peer connection errors

It detects unrecoverable errors and aborts the reconnect attempts

func SplitHostPort

func SplitHostPort(in, defaultPort string) (host string, port string)

SplitHostPort extracts host name without port from host

func SplitSlice

func SplitSlice(slice []string, batchSize int) (result [][]string)

SplitSlice splits the provided string slice into batches of specified size.

func StatDir

func StatDir(path string) (os.FileInfo, error)

StatDir stats directory, returns error if file exists, but not a directory

func StatFile

func StatFile(path string) (os.FileInfo, error)

StatFile determines if the specified path refers to a file. Returns file information on success. If path refers to a directory, an error is returned

func StringInSlice

func StringInSlice(haystack []string, needle string) bool

func StringPtr

func StringPtr(s string) *string

StringPtr returns a pointer to the provided string

func StringSlicesEqual

func StringSlicesEqual(a, b []string) bool

StringSlicesEqual determines whether the two slices are equal. The slices are treated as immutable. If the slices contain the same set of values in different order, the slices must be sorted prior to calling this to correctly determine whether they are the same

func StringValue

func StringValue(v *string) string

StringValue returns the string value in v or an empty string if it's nil

func StringsInSlice

func StringsInSlice(haystack []string, needles ...string) bool

func SyslogWrite

func SyslogWrite(priority syslog.Priority, message, tag string) error

SyslogWrite writes the message to the system log with the specified priority and tag.

func TeeReadCloser

func TeeReadCloser(r io.ReadCloser, w io.Writer) io.ReadCloser

TeeReadCloser is just like TeeReader but implements io.ReadCloser

func ThrottlingPipe

func ThrottlingPipe(ctx context.Context, inCh <-chan string, outCh chan string)

ThrottlingPipe connects a producer writing to inCh with a consumer reading from outCh. The function matches the consumption rate of outCh by dropping all values but the last one it receives from inCh. The last value is always guaranteed to be sent to consumer.

func TimestampedStepPrinter

func TimestampedStepPrinter(out io.Writer, current, target int, message string)

TimestampedStepPrinter adds timestamps to the printed messages.

func ToError

func ToError(i interface{}) error

ToError either returns error as is, or converts it to Errorf in case of unknown object

func ToRawTrace

func ToRawTrace(err trace.Error) *trace.RawTrace

ToRawTrace converts the trace error to marshable format

func ToUnknownResource

func ToUnknownResource(resource teleservices.Resource) (*teleservices.UnknownResource, error)

ToUnknownResource converts the provided resource to a generic resource type

func TrimPathPrefix

func TrimPathPrefix(path string, prefixPath ...string) string

TrimPathPrefix returns the provided path without the specified prefix path

Leading path separator is also stripped.

func URLHostname

func URLHostname(address string) (string, error)

URLHostname returns hostname without port for given URL address

func URLSplitHostPort

func URLSplitHostPort(in, defaultPort string) (string, string, error)

URLSplitHostPort extracts host name without port from URL

func UTC

func UTC(t *time.Time)

UTC converts time to UTC timezone

func UnmarshalError

func UnmarshalError(bytes []byte, err *trace.TraceErr) error

UnmarshalError unmarshals bytes as JSON-encoded error

func WithTempDir

func WithTempDir(fn func(dir string) error, prefix string) error

WithTempDir creates a temporary directory and executes the specified function fn providing it with the name of the directory. After fn is finished, the directory is automatically removed.

func WrapExitCodeError

func WrapExitCodeError(exitCode int, err error) error

WrapExitCodeError returns a new error with the specified exit code that wrap another error

func WriteEnv

func WriteEnv(path string, env map[string]string) error

WriteEnv writes the provided env as an environment variables file at the specified path

func WriteJSON

func WriteJSON(m Marshaler, w io.Writer) error

WriteJSON writes JSON serialized object into provided writer

func WritePath

func WritePath(path string, data []byte, perm os.FileMode) error

WritePath writes file to given path

func WriteYAML

func WriteYAML(m Marshaler, w io.Writer) error

WriteYAML writes YAML serialized object into provided writer

Types

type AbortRetry

type AbortRetry struct {
	Err error
}

AbortRetry if returned from Retry, will lead to retries to be stopped, but the Retry function will return internal Error

func Abort

func Abort(err error) *AbortRetry

Abort causes Retry function to stop with error

func (*AbortRetry) Error

func (a *AbortRetry) Error() string

Error returns the abort error string representation

func (*AbortRetry) OriginalError

func (a *AbortRetry) OriginalError() string

OriginalError returns the original error message this abort error wraps

type Address

type Address struct {
	// Addr is a hostname or an IP address
	Addr string
	// Port is the port number
	Port int32
}

Address contains parsed network address

func NewAddress

func NewAddress(address string) (*Address, error)

NewAddress parses the provided network address, port is mandatory

func (Address) Equal

func (a Address) Equal(other Address) bool

Equal returns true if this address is equal to the other

func (Address) EqualAddr

func (a Address) EqualAddr(other Address) bool

EqualAddr returns true if the addr portion of this address is equal to the other's

func (Address) EqualPort

func (a Address) EqualPort(other Address) bool

EqualPort returns true if the port portion of this address is equal to the other's

func (Address) String

func (a Address) String() string

String returns the address string

type BandwidthWriter

type BandwidthWriter struct {
	sync.Mutex
	// contains filtered or unexported fields
}

BandwidthWriter is a writer that calculates amount of traffic (bytes) going through it

func NewBandwidthWriter

func NewBandwidthWriter() *BandwidthWriter

NewBandwidthWriter creates a new writer that calculates its traffic bandwidth

Writer needs to be closed after it is no longer needed to prevent leaking goroutines

func (*BandwidthWriter) Close

func (w *BandwidthWriter) Close() error

Close stops the writer's goroutine

func (*BandwidthWriter) Max

func (w *BandwidthWriter) Max() uint64

Max returns the maximum recorded value

func (*BandwidthWriter) Write

func (w *BandwidthWriter) Write(p []byte) (int, error)

Write adds the amount of provided bytes to the current second's total

type Capacity

type Capacity uint64

Capacity allows to define capacity in a human readable form (e.g. "10GB")

func MustParseCapacity

func MustParseCapacity(data string) Capacity

MustParseCapacity parses the provided string as capacity or panics

func (Capacity) Bytes

func (c Capacity) Bytes() uint64

Bytes returns the number of bytes

func (Capacity) MarshalJSON

func (c Capacity) MarshalJSON() ([]byte, error)

MarshalJSON marshals capacity to a string in a human friendly form

func (Capacity) Megabytes

func (c Capacity) Megabytes() uint64

Megabytes returns the number of megabytes

func (Capacity) String

func (c Capacity) String() string

String returns a human friendly capacity representation

func (*Capacity) UnmarshalJSON

func (c *Capacity) UnmarshalJSON(data []byte) error

UnmarshalJSON unmarshals capacity from a human friendly form

type CertificateName

type CertificateName struct {
	// CommonName is the certificate common name
	CommonName string `json:"cn"`
	// Organization is the subject/issuer organization
	Organization []string `json:"org"`
	// OrganizationalUnit is the subject/issuer unit
	OrganizationalUnit []string `json:"org_unit"`
}

CertificateName contains information about certificate subject/issuer

type CertificateOutput

type CertificateOutput struct {
	// IssuedTo contains  certificate subject
	IssuedTo CertificateName `json:"issued_to"`
	// IssuedBy contains  certificate issuer
	IssuedBy CertificateName `json:"issued_by"`
	// Validity contains certificate validity dates
	Validity CertificateValidity `json:"validity"`
}

CertificateOutput contains information about cluster certificate

func ParseCertificate

func ParseCertificate(data []byte) (*CertificateOutput, error)

ParseCertificate parses the provided data as PEM-formatted x509 certificate (or chain) and returns a web-UI-friendly representation of it

type CertificateValidity

type CertificateValidity struct {
	// NotBefore is the issue date
	NotBefore time.Time `json:"not_before"`
	// NotAfter is the expiration date
	NotAfter time.Time `json:"not_after"`
}

CertificateValidity contains information about certificate validity dates

type CleanupReadCloser

type CleanupReadCloser struct {
	io.ReadCloser
	Cleanup func()
}

CleanupReadCloser is an io.ReadCloser that tracks when the reading side is closed and then runs the configured cleanup callback.

func (*CleanupReadCloser) Close

func (r *CleanupReadCloser) Close() (err error)

Close delegates to the underlying io.Reader and runs the specified Cleanup. Implements io.Closer

func (*CleanupReadCloser) Read

func (r *CleanupReadCloser) Read(p []byte) (int, error)

Read delegates reading to the underlying io.Reader Implements io.Reader

type ClusterDegradedError

type ClusterDegradedError struct{}

ClusterDegradedError indicates that the cluster is degraded

func (ClusterDegradedError) Error

func (ClusterDegradedError) Error() string

Error returns the text representation of this error

func (ClusterDegradedError) IsCompareFailedError

func (ClusterDegradedError) IsCompareFailedError() bool

IsCompareFailedError returns true to indicate this error complies with compare failed error protocol

type Command

type Command interface {
	// Args returns the complete command line of this command
	Args() []string
}

Command abstracts a CLI command

type CommandOptionSetter

type CommandOptionSetter func(cmd *exec.Cmd)

CommandOptionSetter defines a type for a functional option setter for exec.Cmd

func Dir

func Dir(dir string) CommandOptionSetter

Dir sets the command's working dir

func Stderr

func Stderr(w io.Writer) CommandOptionSetter

Stderr redirects the command's stderr to the specified writer

func Stdout

func Stdout(w io.Writer) CommandOptionSetter

Stdout redirects the command's stdout to the specified writer

type CommandRunner

type CommandRunner interface {
	// RunStream executes a command specified with args and streams
	// output to w using ctx for cancellation
	RunStream(ctx context.Context, stdout, stderr io.Writer, args ...string) error
}

CommandRunner abstracts command execution. w specifies the sink for command's output. The command is given with args

Runner is the default CommandRunner

type CommandRunnerFunc

type CommandRunnerFunc func(ctx context.Context, stdout, stderr io.Writer, args ...string) error

CommandRunnerFunc is the wrapper that allows standalone functions to act as CommandRunners

func (CommandRunnerFunc) RunStream

func (r CommandRunnerFunc) RunStream(ctx context.Context, stdout, stderr io.Writer, args ...string) error

RunStream invokes r with the specified arguments. Implements CommandRunner

type ContinueRetry

type ContinueRetry struct {
	Message string
}

ContinueRetry if returned from Retry, will be lead to retry next time

func Continue

func Continue(format string, args ...interface{}) *ContinueRetry

Continue causes Retry function to continue trying and logging message

func (*ContinueRetry) Error

func (s *ContinueRetry) Error() string

Error returns the continue error string representation

type DockerInfo

type DockerInfo struct {
	ServerVersion string
	StorageDriver string
}

DockerInfo is structured information returned by docker info

func ParseDockerInfo

func ParseDockerInfo(r io.Reader) (*DockerInfo, error)

ParseDockerInfo parses output produced by `docker info` command

type ErrorUninstallService

type ErrorUninstallService struct {
	// Package refers to the service that failed to uninstall
	Package loc.Locator
	// Err specifies the actual error encountered while uninstalling
	// the service
	Err error
}

ErrorUninstallService is an error returned for failed service uninstall attempts

func (*ErrorUninstallService) Error

func (r *ErrorUninstallService) Error() string

Error implements error interface

type EtcdMember

type EtcdMember struct {
	// Name is etcd member name
	Name string `json:"name"`
	// PeerURLs is etcd peer URLs
	PeerURLs string `json:"peer_urls"`
}

EtcdMember describes an etcd member from "etcdctl member list" output

type EtcdMemberList

type EtcdMemberList []EtcdMember

EtcdMemberList represents parsed "etcdctl member list" output

func EtcdParseMemberList

func EtcdParseMemberList(memberListOutput string) (EtcdMemberList, error)

EtcdParseMemberList parses "etcdctl member list" output

func (EtcdMemberList) HasMember

func (l EtcdMemberList) HasMember(name string) bool

HasMember returns true if member list contains specified member

type Executable

type Executable struct {
	// Path specifies the path to the gravity binary
	Path string
	// WorkingDir specifies the working directory of the current process
	WorkingDir string
}

Executable describes a running gravity binary

func NewCurrentExecutable

func NewCurrentExecutable() (*Executable, error)

NewCurrentExecutable returns a new Executable for the currently running gravity binary

func (Executable) PlanetCommand

func (r Executable) PlanetCommand(cmd Command) []string

PlanetCommand returns a new command to run the specified command cmd inside planet container.

func (Executable) PlanetCommandArgs

func (r Executable) PlanetCommandArgs(args ...string) []string

PlanetCommandArgs returns a new command to run the command specified with args inside planet container. For details of operation see PlanetCommandSlice

func (Executable) PlanetCommandSlice

func (r Executable) PlanetCommandSlice(args []string, gravityArgs ...string) []string

PlanetCommandSlice returns a new command to run the command specified with args inside planet. If the process is already running inside the container, the command is returned unaltered. gravityArgs optionally specify additional arguments to the gravity binary

func (Executable) Self

func (r Executable) Self(args ...string) []string

Self returns the command line for the currently running executable. args specifies additional command line arguments

type ExitCodeError

type ExitCodeError interface {
	error
	// ExitCode returns the numeric error code to exit with
	ExitCode() int
	// OrigError returns the original error this error wraps.
	OrigError() error
}

ExitCodeError defines an interface for exit code errors

type FileOption

type FileOption func(path string) error

FileOption defines a functional option to apply to specified path

func OwnerOption

func OwnerOption(uid, gid int) FileOption

OwnerOption changes the owner on the specified file to (uid, gid)

func PermOption

func PermOption(perm os.FileMode) FileOption

PermOption changes the file permissions on the specified file to perm

type Hook

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

Hook implements log.Hook and multiplexes log messages both to stderr and a log file. The console output is limited to warning level and above while logging to file logs at all levels.

func (*Hook) Fire

func (r *Hook) Fire(entry *log.Entry) error

Fire writes the provided log entry to the configured log file

It never returns an error to avoid default logrus behavior of spitting out fire hook errors into stderr.

func (*Hook) Levels

func (r *Hook) Levels() []log.Level

type Marshaler

type Marshaler interface {
	// ToMarshal returns object that needs to be marshaled
	ToMarshal() interface{}
}

Marshaler defines an interface for marshalable objects

type MultiCloser

type MultiCloser []io.Closer

MultiCloser is a list of closers with combined Close method

func (MultiCloser) Close

func (m MultiCloser) Close() error

Close closes all closers one by one

type MultiWriteCloser

type MultiWriteCloser struct {
	io.Writer
	MultiCloser
}

MultiWriteCloser returns multi writer and multi closer

func (*MultiWriteCloser) Close

func (m *MultiWriteCloser) Close() error

Close closes all closers one by one

type NopReader

type NopReader struct{}

NopReader is a io.Reader that does nothing

func NewNopReader

func NewNopReader() *NopReader

NewNopReader returns a new no-op io.Reader

func (*NopReader) Read

func (r *NopReader) Read(_ []byte) (n int, err error)

Read is no-op, always returns 0

type OutputParseFn

type OutputParseFn func(r *bufio.Reader) error

OutputParseFn defines a parser function for arbitrary input r

func ParseAsString

func ParseAsString(out *string) OutputParseFn

ParseAsString returns a parser function that extracts the stream contents as a string

type Printer

type Printer interface {
	io.Writer
	Printf(format string, args ...interface{})
	Print(args ...interface{})
	Println(args ...interface{})
	PrintStep(format string, args ...interface{})
}

Printer describes a capability to output to standard output

type Progress

type Progress interface {
	// UpdateCurrentStep updates message printed for current step that is in progress
	UpdateCurrentStep(message string, args ...interface{})
	// NextStep prints information about next step. It also prints
	// updates on the current step if it takes longer than default timeout
	NextStep(message string, args ...interface{})
	// Stop stops printing all updates
	Stop()
	// PrintCurrentStep updates and prints current step
	PrintCurrentStep(message string, args ...interface{})
	// PrintSubStep outputs the message at info level a sub-step.
	PrintSubStep(message string, args ...interface{})
	// PrintSubWarn outputs the message at warning level as a sub-step.
	PrintSubWarn(message string, args ...interface{})
	// PrintSubDebug outputs the message at debug level as a sub-step.
	PrintSubDebug(message string, args ...interface{})
	// Print outputs the specified message in regular color
	Print(message string, args ...interface{})
	// PrintInfo outputs the specified info message in color
	PrintInfo(message string, args ...interface{})
	// PrintWarn outputs the specified warning message in color and logs the error
	PrintWarn(err error, message string, args ...interface{})
}

Progress is a progress reporter

var DiscardProgress Progress = &nopProgress{}

DiscardProgress is a progress reporter that discards all progress output

func NewConsoleProgress

func NewConsoleProgress(ctx context.Context, title string, steps int) Progress

NewConsoleProgress returns new instance of progress reporter steps is the total amount of steps this progress reporter will report.

func NewProgress

func NewProgress(ctx context.Context, title string, steps int, silent bool) Progress

NewProgress returns new instance of progress reporter based on verbosity - returns either console printer or discarding progress

If negative total number of steps is provided, it means amount of steps is unknown beforehand and the step numbers will not be printed.

func NewProgressWithConfig

func NewProgressWithConfig(ctx context.Context, title string, config ProgressConfig) Progress

NewProgressWithConfig returns new progress reporter for the given set of options

type ProgressConfig

type ProgressConfig struct {
	// Steps specifies the total number of steps.
	// No steps will be displayed if unspecified
	Steps int
	// Timeout specifies the allotted time.
	// Defaults to progressMaxTimeout if unspecified
	Timeout time.Duration
	// Output specifies the output sink.
	// Defaults to os.Stdout if unspecified
	Output io.Writer
	// Level defines the reporting level.
	Level ProgressLevel
	// StepPrinter allows to override printer that prints a single step.
	StepPrinter StepPrinter
}

ProgressConfig defines configuration for the progress printer

type ProgressLevel

type ProgressLevel int32

ProgressLevel represents a level at which reporter reports progress.

const (
	// ProgressLevelNone disables all output.
	ProgressLevelNone ProgressLevel = -1
	// ProgressLevelInfo is the level for basic informational messages.
	ProgressLevelInfo ProgressLevel = iota
	// ProgressLevelDebug is the level for more detailed information.
	ProgressLevelDebug
)

type SSHCommands

type SSHCommands interface {
	// adds new command with default policy
	C(format string, a ...interface{}) SSHCommands
	// adds new command which will tolerate any error occurred
	IgnoreError(format string, a ...interface{}) SSHCommands
	// WithRetries executes the specified command as a script,
	// retrying several times upon failure
	WithRetries(format string, a ...interface{}) SSHCommands
	// WithLogger sets logger
	WithLogger(logrus.FieldLogger) SSHCommands
	// WithOutput sets the output sink
	WithOutput(io.Writer) SSHCommands
	// executes sequence
	Run(ctx context.Context) error
}

SSHCommands abstracts a way of executing a set of remote commands

func NewSSHCommands

func NewSSHCommands(client *ssh.Client) SSHCommands

NewSSHCommands returns a new remote command executor that will use the specified runner to execute commands

type SafeByteBuffer

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

SafeByteBuffer is a goroutine safe bytes.Buffer

func (*SafeByteBuffer) String

func (s *SafeByteBuffer) String() string

String returns the contents of the unread portion of the buffer as a string. If the Buffer is a nil pointer, it returns "<nil>".

func (*SafeByteBuffer) Write

func (s *SafeByteBuffer) Write(p []byte) (n int, err error)

Write appends the contents of p to the buffer, growing the buffer as needed. It returns the number of bytes written.

type StderrLogger

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

StderrLogger is a stdlib-compatible logger that logs to the underlying logger at Warn level

func NewStderrLogger

func NewStderrLogger(log logrus.FieldLogger) *StderrLogger

NewStderrLogger returns a new io.Writer that logs its input with log.Warn

func (*StderrLogger) Write

func (w *StderrLogger) Write(p []byte) (n int, err error)

type StepPrinter

type StepPrinter func(out io.Writer, current, target int, message string)

StepPrinter prints a single step message.

type StringSet

type StringSet map[string]struct{}

func NewStringSet

func NewStringSet() StringSet

func NewStringSetFromSlice

func NewStringSetFromSlice(slice []string) StringSet

func (StringSet) Add

func (s StringSet) Add(v string)

func (StringSet) AddSet

func (s StringSet) AddSet(right StringSet)

func (StringSet) AddSlice

func (s StringSet) AddSlice(slice []string)

func (StringSet) Diff

func (s StringSet) Diff(another StringSet) StringSet

Diff returns difference between this and provided set.

func (StringSet) Has

func (s StringSet) Has(item string) (exists bool)

func (StringSet) Remove

func (s StringSet) Remove(v string)

func (StringSet) Slice

func (s StringSet) Slice() (slice []string)

type SyncBuffer

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

SyncBuffer is in memory bytes buffer that is safe for concurrent writes

func NewSyncBuffer

func NewSyncBuffer() *SyncBuffer

NewSyncBuffer returns new in memory buffer

func (*SyncBuffer) Bytes

func (b *SyncBuffer) Bytes() []byte

Bytes returns contents of the buffer after this call, all writes will fail

func (*SyncBuffer) Close

func (b *SyncBuffer) Close() error

Close closes reads and writes on the buffer

func (*SyncBuffer) String

func (b *SyncBuffer) String() string

String returns contents of the buffer after this call, all writes will fail

func (*SyncBuffer) Write

func (b *SyncBuffer) Write(data []byte) (n int, err error)

type TLSArchive

type TLSArchive map[string]*authority.TLSKeyPair

TLSArchive designed to store a set of keypairs following a special naming convention, where every keypair has a name and they are serialized using extension ".cert" and extension ".key" convention

func ReadTLSArchive

func ReadTLSArchive(source io.Reader) (TLSArchive, error)

ReadTLSArchive reads TLS packed archive, where keys are stored with extension ".key" and certificates are stored with extension ".cert"

func (TLSArchive) AddKeyPair

func (ta TLSArchive) AddKeyPair(name string, kp authority.TLSKeyPair) error

AddKeyPair adds TLSArchiveKeyPair to archive

func (TLSArchive) GetKeyPair

func (ta TLSArchive) GetKeyPair(name string) (*authority.TLSKeyPair, error)

GetKeyPair returns KeyPair by name

type TailReader

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

func (*TailReader) Close

func (t *TailReader) Close() error

func (*TailReader) Read

func (t *TailReader) Read(p []byte) (int, error)

type TransferRate

type TransferRate uint64

TransferRate allows to define transfer rate in a human friendly form (e.g. "10MB/s")

func MustParseTransferRate

func MustParseTransferRate(data string) TransferRate

MustParseTransferRate parses the provided data as a transfer rate or panics

func (TransferRate) BytesPerSecond

func (r TransferRate) BytesPerSecond() uint64

BytesPerSecond returns a number of bytes per second the transfer rate represents

func (TransferRate) MarshalJSON

func (r TransferRate) MarshalJSON() ([]byte, error)

MarshalJSON marshals transfer rate into a human friendly form

func (TransferRate) String

func (r TransferRate) String() string

String returns a human friendly formatted transfer rate

func (*TransferRate) UnmarshalJSON

func (r *TransferRate) UnmarshalJSON(data []byte) error

UnmarshalJSON unmarshals transfer rate from a human friendly form

type UnsupportedFilesystemError

type UnsupportedFilesystemError struct {
	// Err is the original error
	Err error
	// Path is path to the directory with unsupported filesystem
	Path string
}

UnsupportedFilesystemError represents a condition when an action is being performed on an unsupported filesystem, for example an attempt to create a bolt database file on filesystem that does not support mmap

func NewUnsupportedFilesystemError

func NewUnsupportedFilesystemError(err error, path string) *UnsupportedFilesystemError

NewUnsupportedFilesystemError creates a new error for an unsupported filesystem at the specified path

func (*UnsupportedFilesystemError) Error

Error returns the string representation of the error

type User

type User struct {
	Name  string
	Pass  string
	Uid   int //nolint:stylecheck,revive
	Gid   int //nolint:stylecheck,revive
	Gecos string
	Home  string
	Shell string
}

User describes a system user as found in a passwd file. Adopted from https://raw.githubusercontent.com/opencontainers/runc/master/libcontainer/user/{user,lookup}.go See: man 5 passwd

func ParsePasswd

func ParsePasswd(passwd io.Reader) (users []User, err error)

ParsePasswd interprets the specified passwd file as a list of users

Directories

Path Synopsis
Package fields provides methods for making log fields from various objects.
Package fields provides methods for making log fields from various objects.

Jump to

Keyboard shortcuts

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