Documentation
¶
Index ¶
- Constants
- Variables
- func BoolPtr(v bool) *bool
- func BoolValue(v *bool) bool
- func CheckEmail(email string) error
- func CheckInPlanet() bool
- func CheckName(name string) error
- func CheckUserName(name string) error
- func Chown(dir, uid, gid string) error
- func Collect(ctx context.Context, cancel func(), errChan chan error, ...) ([]interface{}, error)
- func CollectErrors(ctx context.Context, errChan chan error) error
- func CombineLabels(labels ...map[string]string) (result map[string]string)
- func CombinedOutput(cmd *exec.Cmd, out io.Writer) (string, error)
- func CompareStringSlices(a, b []string) bool
- func ConvertS3Error(err error) error
- func CopyDirContents(fromDir, toDir string) error
- func CopyFile(dst, src string) error
- func CopyFileWithPerms(dst, src string, perm os.FileMode) error
- func CopyReader(dst string, src io.Reader) error
- func CopyReaderWithPerms(dst string, src io.Reader, perm os.FileMode) error
- func CopyWithRetries(ctx context.Context, targetPath string, open func() (io.ReadCloser, error), ...) error
- func CreateTLSArchive(a TLSArchive) (io.ReadCloser, error)
- func DecryptPGP(data io.Reader, passphrase string) (io.Reader, error)
- func DetectPlanetEnvironment()
- func DurationPtr(v time.Duration) *teleservices.Duration
- func EncryptPGP(data io.Reader, passphrase string) (io.ReadCloser, error)
- func EnsureLineInFile(path, line string) error
- func EnsureLocalPath(customPath string, defaultLocalDir, defaultLocalPath string) (string, error)
- func EtcdInitialCluster(memberListOutput string) (string, error)
- func Exec(cmd *exec.Cmd, out io.Writer, setters ...CommandOptionSetter) error
- func ExecL(cmd *exec.Cmd, out io.Writer, logger log.FieldLogger, ...) error
- func ExecWithInput(cmd *exec.Cmd, input string, out io.Writer, setters ...CommandOptionSetter) error
- func ExecuteWithDelay(args []string, delay time.Duration) error
- func ExtractHost(addr string) string
- func FindETCDMemberID(output, name string) (string, error)
- func FlattenStringSlice(slice []string) (retval []string)
- func FlattenVersion(version string) string
- func GeneratePrivateKeyPEM() ([]byte, error)
- func GetKubeClient(configPath string) (client *kubernetes.Clientset, config *rest.Config, err error)
- func GetKubeClientFromPath(configPath string) (*kubernetes.Clientset, *rest.Config, error)
- func GetLocalKubeClient() (*kubernetes.Clientset, *rest.Config, error)
- func GetMasters(nodes map[string]v1.Node) (ips []string)
- func GetNodes(client corev1.NodeInterface) (nodes map[string]v1.Node, err error)
- func GetPasswd() (io.ReadCloser, error)
- func HasOneOfPrefixes(s string, prefixes ...string) bool
- func Hosts(addrs []string) (hosts []string)
- func Int64Ptr(v int64) *int64
- func IntPtr(v int) *int
- func IsAbortError(err error) bool
- func IsClosedConnectionError(err error) bool
- func IsClosedResponseBodyErrorMessage(err string) bool
- func IsClusterUnavailableError(err error) bool
- func IsConnectionResetError(err error) bool
- func IsContextCancelledError(err error) bool
- func IsContinueError(err error) bool
- func IsDirectory(dir string) (bool, error)
- func IsDirectoryEmpty(dir string) (bool, error)
- func IsKubeAuthError(err error) bool
- func IsNetworkError(err error) bool
- func IsPathError(err error) bool
- func IsStreamClosedError(err error) bool
- func IsTransientClusterError(err error) bool
- func LoadKubeConfig() (*clientcmdapi.Config, error)
- func LocalIPNetworks() (blocks []net.IPNet, err error)
- func MakeSelector(in map[string]string) labels.Selector
- func MatchesLabels(targetLabels, wantedLabels map[string]string) bool
- func Max(x, y int) int
- func MaxInt64(x, y uint64) uint64
- func Min(x, y int) int
- func MkdirAll(targetDirectory string, mode os.FileMode) error
- func MustSHA512Half(v []byte) string
- func NewExponentialBackOff(timeout time.Duration) backoff.BackOff
- func NewMultiWriteCloser(writeClosers ...io.WriteCloser) io.WriteCloser
- func NewRunner(logger log.FieldLogger, setters ...CommandOptionSetter) *runner
- func NewRunnerWithContext(ctx context.Context, log log.FieldLogger, setters ...CommandOptionSetter) *runner
- func NewTailReader(path string) (io.ReadCloser, error)
- func NewUninstallServiceError(servicePackage loc.Locator) error
- func NewUnlimitedExponentialBackOff() backoff.BackOff
- func NopReader() *nopReader
- func NopWriteCloser(w io.Writer) io.WriteCloser
- func NormalizePath(path string) (string, error)
- func OpenFile(path string) (*os.File, error)
- func ParseAddrList(l string) ([]string, error)
- func ParseDDOutput(output string) (uint64, error)
- func ParseDiscard(r *bufio.Reader) error
- func ParseHostOverride(override string) (domain, ip string, err error)
- func ParseHostPort(in string) (host string, port int32, err error)
- func ParseLabels(labelsS string) map[string]string
- func ParseOpsCenterAddress(in, defaultPort string) string
- func ParsePorts(ranges string) ([]int, error)
- func ParseProxyAddr(proxyAddr, defaultWebPort, defaultSSHPort string) (host string, webPort string, sshPort string, err error)
- func ParseSystemdVersion(out string) (int, error)
- func ParseZoneOverride(override string) (zone, nameserver string, err error)
- func PickAdvertiseIP() (string, error)
- func PlanetCommand(cmd Command) []string
- func PlanetCommandArgs(args ...string) []string
- func PlanetCommandSlice(args []string, gravityArgs ...string) []string
- func PlanetEnterCommand(args ...string) []string
- func PrintProgress(current, target int, message string)
- func PrintStep(current, target int, message string)
- func ProgressBar(current, target int64) string
- func ReadEnv(path string) (map[string]string, error)
- func ReadPath(path string) ([]byte, error)
- func RecursiveGlob(dir string, patterns []string, handler func(match string) error) error
- func RemoveContents(dir string) error
- func RemoveNewlines(s string) string
- func ResolveAddr(dnsAddr, addr string) (hostPort string, err error)
- func Retry(period time.Duration, maxAttempts int, fn func() error) error
- func RetryFor(ctx context.Context, timeout time.Duration, fn func() error) error
- func RetryOnNetworkError(period time.Duration, maxAttempts int, fn func() error) error
- func RetryRead(getReadCloser func() (io.ReadCloser, error), period time.Duration, ...) (io.ReadCloser, error)
- func RetryTransient(ctx context.Context, interval backoff.BackOff, fn func() error) error
- func RetryWithInterval(ctx context.Context, interval backoff.BackOff, fn func() error) error
- func RunCommand(ctx context.Context, log log.FieldLogger, args ...string) ([]byte, error)
- func RunGravityCommand(ctx context.Context, log log.FieldLogger, args ...string) ([]byte, error)
- func RunInPlanetCommand(ctx context.Context, log log.FieldLogger, args ...string) ([]byte, error)
- func RunKubernetesTests() bool
- func RunPlanetCommand(ctx context.Context, log log.FieldLogger, args ...string) ([]byte, error)
- func SHA512Half(v []byte) (string, error)
- func SSHRun(ctx context.Context, client *ssh.Client, log logrus.FieldLogger, cmd string, ...) error
- func SSHRunAndParse(ctx context.Context, client *ssh.Client, log logrus.FieldLogger, cmd string, ...) (exitStatus int, err error)
- func SaveKubeConfig(config clientcmdapi.Config) error
- func SelectSubnet(blocks []string) (string, error)
- func SelectVPCSubnet(vpcBlock string, subnetBlocks []string) (string, error)
- func ShouldReconnectPeer(err error) error
- func SplitHostPort(in, defaultPort string) (host string, port string)
- func StatDir(path string) (os.FileInfo, error)
- func StatFile(path string) (os.FileInfo, error)
- func StderrLogger(log logrus.FieldLogger) io.Writer
- func StringInSlice(haystack []string, needle string) bool
- func StringsInSlice(haystack []string, needles ...string) bool
- func TeeReadCloser(r io.ReadCloser, w io.Writer) io.ReadCloser
- func ThrottlingPipe(ctx context.Context, inCh <-chan string, outCh chan string)
- func ToError(i interface{}) error
- func ToRawTrace(err trace.Error) *trace.RawTrace
- func ToUnknownResource(resource teleservices.Resource) (*teleservices.UnknownResource, error)
- func TrimPathPrefix(path string, prefixPath ...string) string
- func URLHostname(address string) (string, error)
- func URLSplitHostPort(in, defaultPort string) (string, string, error)
- func UTC(t *time.Time)
- func UnmarshalError(bytes []byte, err *trace.TraceErr) error
- func ValidateKubernetesSubnets(podCIDR, serviceCIDR string) error
- func WatchTerminationSignals(ctx context.Context, cancel context.CancelFunc, stopper Stopper, ...)
- func WithTempDir(fn func(dir string) error, prefix string) error
- func WriteEnv(path string, env map[string]string) error
- func WriteJSON(m Marshaler, w io.Writer) error
- func WritePath(path string, data []byte, perm os.FileMode) error
- func WriteYAML(m Marshaler, w io.Writer) error
- type AbortRetry
- type Address
- type BandwidthWriter
- type Capacity
- type CertificateName
- type CertificateOutput
- type CertificateValidity
- type CleanupReadCloser
- type Command
- type CommandOptionSetter
- type CommandRunner
- type ConsoleProgress
- func (p *ConsoleProgress) NextStep(message string, args ...interface{})
- func (p *ConsoleProgress) Print(message string, args ...interface{})
- func (p *ConsoleProgress) PrintCurrentStep(message string, args ...interface{})
- func (p *ConsoleProgress) PrintInfo(message string, args ...interface{})
- func (p *ConsoleProgress) PrintSubStep(message string, args ...interface{})
- func (p *ConsoleProgress) PrintWarn(err error, message string, args ...interface{})
- func (p *ConsoleProgress) Stop()
- func (p *ConsoleProgress) UpdateCurrentStep(message string, args ...interface{})
- type ContinueRetry
- type DockerInfo
- type Emitter
- type ErrorUninstallService
- type EtcdMember
- type EtcdMemberList
- type Executable
- type Marshaler
- type MultiCloser
- type MultiWriteCloser
- type NopProgress
- func (*NopProgress) NextStep(message string, args ...interface{})
- func (*NopProgress) Print(message string, args ...interface{})
- func (*NopProgress) PrintCurrentStep(message string, args ...interface{})
- func (*NopProgress) PrintInfo(message string, args ...interface{})
- func (*NopProgress) PrintSubStep(message string, args ...interface{})
- func (*NopProgress) PrintWarn(err error, message string, args ...interface{})
- func (*NopProgress) Stop()
- func (*NopProgress) UpdateCurrentStep(message string, args ...interface{})
- type OutputParseFn
- type Progress
- type SSHCommands
- type SafeByteBuffer
- type Stopper
- type StopperFunc
- type StringSet
- func (s StringSet) Add(v string)
- func (s StringSet) AddSet(right StringSet)
- func (s StringSet) AddSlice(slice []string)
- func (s StringSet) Diff(another StringSet) StringSet
- func (s StringSet) Has(item string) (exists bool)
- func (s StringSet) Remove(v string)
- func (s StringSet) Slice() (slice []string)
- type SyncBuffer
- type TLSArchive
- type TailReader
- type TransferRate
- type UnsupportedFilesystemError
- type User
Constants ¶
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 ¶
var Exe = must(NewCurrentExecutable())
Exe is the Executable for the currently running gravity binary
Functions ¶
func CheckInPlanet ¶
func CheckInPlanet() bool
CheckInPlanet returns whether the process was started inside the container
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 ¶
CollectErrors exhausts error channel errChan up to its capacity and returns aggregate error if any
func CombineLabels ¶
CombineLabels combines the specified label sets into a single map. Existing labels will get overwritten with the last value
func CompareStringSlices ¶
func ConvertS3Error ¶
ConvertS3Error converts an error from AWS S3 API to an appropriate trace error
func CopyDirContents ¶
CopyDirContents copies all contents of the source directory (including the source directory itself and all its sub-directories) to the destination directory
func CopyFile ¶
CopyFile copies contents of src to dst atomically using SharedReadWriteMask as permissions.
func CopyFileWithPerms ¶
CopyFileWithPerms copies the contents from src to dst atomically. Uses CopyReaderWithPerms for its implementation - see function documentation for details of operation
func CopyReader ¶
CopyReader copies contents of src to dst atomically using SharedReadWriteMask as permissions.
func CopyReaderWithPerms ¶
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 ¶
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 ¶
EncryptPGP returns a stream with "data" encrypted by the provided passphrase
func EnsureLineInFile ¶
EnsureLineInFile makes sure the specified file contains provided line
func EnsureLocalPath ¶
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 ¶
EtcdInitialCluster interprets the output of etcdctl member list as a comma-separated list of name:ip pairs.
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 ExtractHost ¶
ExtractHost returns only the host part from the provided address.
func FindETCDMemberID ¶
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 ¶
FlattenStringSlice takes a slice of strings like ["one,two", "three"] and returns ["one", "two", "three"]
func FlattenVersion ¶
FlattenVersion removes or replaces characters from the version string to make it useable as part of kubernetes resource names
func GeneratePrivateKeyPEM ¶
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 ¶
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 ¶
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 ¶
HasOneOfPrefixes returns true if the provided string starts with any of the specified prefixes
func IsAbortError ¶
IsAbortError returns true if the specified error is of type AbortRetry
func IsClosedConnectionError ¶
IsClosedConnectionError determines if the specified error is a closed connection error
func IsClosedResponseBodyErrorMessage ¶
IsClosedResponseBodyErrorMessage determines if the error message describes a closed response body error
func IsClusterUnavailableError ¶
IsClusterUnavailableError determines if the specified error is a cluster unavailable error
func IsConnectionResetError ¶
IsConnectionResetError determines whether err is a 'connection reset by peer' error. err is expected to be non-nil
func IsContextCancelledError ¶
IsContextCancelledError returns true if the provided error is a result of a context cancellation
func IsContinueError ¶
IsContinueError returns true if provided error is of ContinueRetry type
func IsDirectory ¶
IsDirectory determines if dir specifies a directory
func IsDirectoryEmpty ¶
IsDirectoryEmpty returns true if the specified directory is empty The directory must exist or an error will be returned
func IsKubeAuthError ¶
IsKubeAuthError determines whether the specified error is an authorization error from kubernetes client.
func IsNetworkError ¶
IsNetworkError returns true if the provided error is Go's network error
func IsPathError ¶
IsPathError determines if the specified err is of type os.PathError
func IsStreamClosedError ¶
IsStreamClosedError determines if the given error is a response/stream closed error
func IsTransientClusterError ¶
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 ¶
LocalIPNetworks returns the list of all local IP networks
func MakeSelector ¶
MakeSelector converts set of key-value pairs to selector
func MatchesLabels ¶
MatchesLabels determines whether a set of "target" labels matches the set of "wanted" labels
func MustSHA512Half ¶
MustSHA512Half panics if it fails to compute SHA512 hash, use only in tests
func NewExponentialBackOff ¶
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 ¶
NewUninstallServiceError returns a plan out of sync error
func NewUnlimitedExponentialBackOff ¶
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 ¶
NormalizePath normalises path, evaluating symlinks and converting local paths to absolute
func ParseAddrList ¶
ParseAddrList parses a comma-separated list of addresses
func ParseDDOutput ¶
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 ParseHostOverride ¶
ParseHostOverride parses DNS host override in the format <host>/<ip>
func ParseHostPort ¶
ParseHostPort parses the provided address as host:port
func ParseLabels ¶
ParseLabels parses a string like "a=b,c=d" as a map
func ParseOpsCenterAddress ¶
ParseOpsCenterAddress parses OpsCenter address
func ParsePorts ¶
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 ¶
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 ¶
ParseZoneOverride parses DNS zone override in the format <host>/<ip> or <host>/<ip>:<port>
func PickAdvertiseIP ¶
PickAdvertiseIP selects an advertise IP among the host's interfaces
func PlanetCommand ¶
PlanetCommand returns a new command to run the specified command cmd inside planet container.
func PlanetCommandArgs ¶
PlanetCommandArgs returns a new command to run the command specified with args inside planet container. For details of operation see PlanetCommandSlice
func PlanetCommandSlice ¶
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 ¶
PlanetEnterCommand returns command that runs in planet using gravity from path
func PrintProgress ¶
PrintProgress prints generic progress with stages
func ProgressBar ¶
func ReadEnv ¶
ReadEnv reads the file at the specified path as a file containing environment variables (e.g. /etc/environment)
func RecursiveGlob ¶
RecursiveGlob recursively walks the dir and returns the list of files matching the specified patterns.
func RemoveContents ¶
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 ¶
RemoveNewlines removes newlines from string
func ResolveAddr ¶
ResolveAddr resolves the provided hostname using the local resolver
func Retry ¶
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 ¶
RetryFor retries the provided function until it succeeds or until timeout has been reached
func RetryOnNetworkError ¶
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 ¶
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 ¶
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 ¶
RunCommand executes the command specified with args
func RunGravityCommand ¶
RunGravityCommand executes the command specified with args with the current process binary
func RunInPlanetCommand ¶
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 ¶
RunPlanetCommand executes the command specified with args as a planet command inside the container
func SHA512Half ¶
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 ¶
SelectSubnet returns a /16 subnet that does not overlap with the provided subnet blocks
func SelectVPCSubnet ¶
SelectVPCSubnet returns a /24 subnet that does not overlap with the provided subnet blocks from the provided VPC block
func ShouldReconnectPeer ¶
ShouldReconnectPeer implements the error classification for peer connection errors
It detects unrecoverable errors and aborts the reconnect attempts
func SplitHostPort ¶
SplitHostPort extracts host name without port from host
func StatFile ¶
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 StringsInSlice ¶
func TeeReadCloser ¶
func TeeReadCloser(r io.ReadCloser, w io.Writer) io.ReadCloser
TeeReadCloser is just like TeeReader but implements io.ReadCloser
func ThrottlingPipe ¶
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 ¶
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 ¶
TrimPathPrefix returns the provided path without the specified prefix path
Leading path separator is also stripped.
func URLHostname ¶
URLHostname returns hostname without port for given URL address
func URLSplitHostPort ¶
URLSplitHostPort extracts host name without port from URL
func UnmarshalError ¶
UnmarshalError unmarshals bytes as JSON-encoded error
func ValidateKubernetesSubnets ¶
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 ¶
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 ¶
WriteEnv writes the provided env as an environment variables file at the specified path
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 (*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 ¶
NewAddress parses the provided network address, port is mandatory
func (Address) EqualAddr ¶
EqualAddr returns true if the addr portion of this address is equal to the other's
type BandwidthWriter ¶
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
type Capacity ¶
type Capacity uint64
Capacity allows to define capacity in a human readable form (e.g. "10GB")
func MustParseCapacity ¶
MustParseCapacity parses the provided string as capacity or panics
func (Capacity) MarshalJSON ¶
MarshalJSON marshals capacity to a string in a human friendly form
func (*Capacity) UnmarshalJSON ¶
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
type Command ¶
type Command interface {
// Args returns the complete command line of this command
Args() []string
}
Command abstracts a CLI command
type CommandOptionSetter ¶
CommandOptionSetter defines a type for a functional option setter for exec.Cmd
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 ¶
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) 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 ¶
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
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 ¶
MultiCloser is a list of closers with combined Close method
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) UpdateCurrentStep ¶
func (*NopProgress) UpdateCurrentStep(message string, args ...interface{})
UpdateCurrentStep updates message printed for current step that is in progress
type OutputParseFn ¶
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 ¶
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>".
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 ¶
StopperFunc is an adapter function that allows the use of ordinary functions as Stoppers
type StringSet ¶
type StringSet map[string]struct{}
func NewStringSet ¶
func NewStringSet() StringSet
func NewStringSetFromSlice ¶
type SyncBuffer ¶
type SyncBuffer struct {
// contains filtered or unexported fields
}
SyncBuffer is in memory bytes buffer that is safe for concurrent writes
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
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
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 ¶
func (e *UnsupportedFilesystemError) Error() string
Error returns the string representation of the error
type User ¶
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