utils

package
v0.0.0-...-0755659 Latest Latest
Warning

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

Go to latest
Published: Feb 8, 2019 License: Apache-2.0 Imports: 65 Imported by: 0

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 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

Check 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(dir, uid, gid string) 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 occured 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 CompareStringSlices

func CompareStringSlices(a, b []string) bool

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 CopyFile

func CopyFile(dst, src string) error

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

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 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), mode os.FileMode) 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 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 string, 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 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 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 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 GeneratePrivateKeyPEM

func GeneratePrivateKeyPEM() ([]byte, error)

GeneratePrivateKeyPEM generates and returns PEM serialzed

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 GetKubeClientFromPath

func GetKubeClientFromPath(configPath string) (*kubernetes.Clientset, *rest.Config, error)

GetKubeClientFromPath creates a kubernetes client from the specified configPath

func GetLocalKubeClient

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

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

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 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 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 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 IsClusterUnavailableError

func IsClusterUnavailableError(err error) bool

IsClusterUnavailableError determines if the specified error is a cluster unavailable error

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(dir string) (bool, error)

IsDirectory determines if dir 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 IsKubeAuthError

func IsKubeAuthError(err error) bool

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

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 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 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 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 NewExponentialBackOff

func NewExponentialBackOff(timeout time.Duration) backoff.BackOff

NewExponentialBackOff creates a new backoff interval with the specified timeout

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 NewRunner

func NewRunner(logger log.FieldLogger, setters ...CommandOptionSetter) *runner

NewRunner creates a new CommandRunner using ExecX APIs

func NewRunnerWithContext

func NewRunnerWithContext(ctx context.Context, log log.FieldLogger, setters ...CommandOptionSetter) *runner

NewRunnerWithContext creates a new CommandRunner using the specified context

func NewTailReader

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

func NewUninstallServiceError

func NewUninstallServiceError(servicePackage loc.Locator) error

NewUninstallServiceError returns a plan out of sync error

func NewUnlimitedExponentialBackOff

func NewUnlimitedExponentialBackOff() backoff.BackOff

NewUnlimitedExponentialBackOff returns a backoff interval without time restriction

func NopReader

func NopReader() *nopReader

NopReader returns a new no-op io.Reader

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 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

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 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 PrintStep

func PrintStep(current, target int, message string)

PrintStep prints step instead of the progress bar

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 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 (no error).

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, log 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 SHA512Half

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

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

func SSHRun

func SSHRun(ctx context.Context, client *ssh.Client, log logrus.FieldLogger, cmd string, env map[string]string) error

Run is a simple method to run external program and don't care about its output or exit status

func SSHRunAndParse

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

RunAndParse runs remote SSH command with environment variables set by `env` exitStatus is -1 if undefined

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 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 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 StderrLogger

func StderrLogger(log logrus.FieldLogger) io.Writer

StderrWriter returns io.Writer which would log with log.Warn

func StringInSlice

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

func StringsInSlice

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

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 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 ValidateKubernetesSubnets

func ValidateKubernetesSubnets(podCIDR, serviceCIDR string) error

ValidateKubernetesSubnets makes sure that the provided CIDR ranges can be used as pod/service Kubernetes subnets

func WatchTerminationSignals

func WatchTerminationSignals(ctx context.Context, cancel context.CancelFunc, stopper Stopper, log logrus.FieldLogger)

WatchTerminationSignals stops the provided stopper when it gets one of monitored signals

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 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 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
	RunStream(w io.Writer, args ...string) error
}

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

type ConsoleProgress

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

ConsoleProgress is a helper progress printer that prints all the output to the console

func NewConsoleProgress

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

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

func (*ConsoleProgress) NextStep

func (p *ConsoleProgress) NextStep(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

func (*ConsoleProgress) Print

func (p *ConsoleProgress) Print(message string, args ...interface{})

Print outputs the specified message in regular color

func (*ConsoleProgress) PrintCurrentStep

func (p *ConsoleProgress) PrintCurrentStep(message string, args ...interface{})

PrintCurrentStep updates message printed for current step that is in progress

func (*ConsoleProgress) PrintInfo

func (p *ConsoleProgress) PrintInfo(message string, args ...interface{})

PrintInfo outputs the specified info message in color

func (*ConsoleProgress) PrintSubStep

func (p *ConsoleProgress) PrintSubStep(message string, args ...interface{})

PrintSubStep outputs the message as a sub-step of the current step

func (*ConsoleProgress) PrintWarn

func (p *ConsoleProgress) PrintWarn(err error, message string, args ...interface{})

PrintWarn outputs the specified warning message in color and logs the error

func (*ConsoleProgress) Stop

func (p *ConsoleProgress) Stop()

Stop stops printing all updates

func (*ConsoleProgress) UpdateCurrentStep

func (p *ConsoleProgress) UpdateCurrentStep(message string, args ...interface{})

UpdateCurrentStep updates message printed for current step that is in progress

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 Emitter

type Emitter interface {
	// PrintStep formats the specified message string to stdout
	PrintStep(format string, args ...interface{}) (n int, err error)
}

Emitter abstracts a way to emit progess messages within an operation

func NopEmitter

func NopEmitter() Emitter

NopEmitter returns an emitter that does nothing

type ErrorUninstallService

type ErrorUninstallService struct {
	// Package refers to the service that failed to uninstall
	Package loc.Locator
}

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
}

Executable abstracts the specified 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

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 NopProgress

type NopProgress struct{}

NopProgress is a progress printer that reports nothing

func NewNopProgress

func NewNopProgress() *NopProgress

NewNopProgress returns an instance of discarding output progress reporter

func (*NopProgress) NextStep

func (*NopProgress) NextStep(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

func (*NopProgress) Print

func (*NopProgress) Print(message string, args ...interface{})

Print outputs the specified message in regular color

func (*NopProgress) PrintCurrentStep

func (*NopProgress) PrintCurrentStep(message string, args ...interface{})

PrintCurrentStep updates and prints current step

func (*NopProgress) PrintInfo

func (*NopProgress) PrintInfo(message string, args ...interface{})

PrintInfo outputs the specified info message in color

func (*NopProgress) PrintSubStep

func (*NopProgress) PrintSubStep(message string, args ...interface{})

PrintSubStep outputs the message as a sub-step of the current step

func (*NopProgress) PrintWarn

func (*NopProgress) PrintWarn(err error, message string, args ...interface{})

PrintWarn outputs the specified warning message in color and logs the error

func (*NopProgress) Stop

func (*NopProgress) Stop()

Stop stops printing all updates

func (*NopProgress) UpdateCurrentStep

func (*NopProgress) UpdateCurrentStep(message string, args ...interface{})

UpdateCurrentStep updates message printed for current step that is in progress

type OutputParseFn

type OutputParseFn func(r *bufio.Reader) error

func ParseAsString

func ParseAsString(out *string) OutputParseFn

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 as a sub-step of the current step
	PrintSubStep(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

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.

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 occured
	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
	// executes sequence
	Run(ctx context.Context) error
}

func NewSSHCommands

func NewSSHCommands(client *ssh.Client) SSHCommands

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 Stopper

type Stopper interface {
	// Stop performs implementation-specific cleanup tasks bound by the provided context
	Stop(context.Context) error
}

Stopper is a common interface for everything that can be stopped with a context

type StopperFunc

type StopperFunc func(context.Context) error

StopperFunc is an adapter function that allows the use of ordinary functions as Stoppers

func (StopperFunc) Stop

func (r StopperFunc) Stop(ctx context.Context) error

Stop invokes this stopper function. Stop implements Stopper

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
	Gid   int
	Gecos string
	Home  string
	Shell string
}

Adopted from https://raw.githubusercontent.com/opencontainers/runc/master/libcontainer/user/{user,lookup}.go User describes a system user as found in a passwd file 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

Jump to

Keyboard shortcuts

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