package
0.0.0-20230628214157-3bfe64699e82
Repository: https://github.com/gravitational/gravity.git
Documentation: pkg.go.dev
# Functions
Abort causes Retry function to stop with error.
BoolPtr returns a pointer to a bool with value v.
BoolValue returns the boolean value in v or false if it's nil.
CheckEmail is a simplistic email checker.
CheckInPlanet returns whether the process was started inside the container.
CheckName makes sure that the provided string is a valid app name.
CheckUserName validates user name.
Chown adjusts ownership of the specified directory and all its subdirectories.
Collect collects errors and values from channel provided, honouring timeout it will expect exactly cap(errChan) messages value channel could be nil.
CollectErrors exhausts error channel errChan up to its capacity and returns aggregate error if any.
No description provided by the author
CombineLabels combines the specified label sets into a single map.
Continue causes Retry function to continue trying and logging message.
ConvertEC2Error converts error from AWS EC2 API to appropriate trace error.
ConvertS3Error converts an error from AWS S3 API to an appropriate trace error.
CopyDirContents copies all contents of the source directory (including the source directory itself and all its sub-directories) to the destination directory.
CopyExecutable copies the provided reader to the specified destination and sets executable permissions.
CopyFile copies contents of src to dst atomically using SharedReadWriteMask as permissions.
CopyFileWithOptions copies the contents from src to dst atomically.
CopyFileWithPerms copies the contents from src to dst atomically.
CopyReader copies contents of src to dst atomically using SharedReadWriteMask as permissions.
CopyReaderWithOptions copies the contents from src to dst atomically.
CopyReaderWithPerms copies the contents from src to dst atomically.
CopyWithRetries copies the contents of the reader obtained with open to targetPath retrying on transient errors.
CreateTLSArchive creates archive with TLS keypairs, where keys are stored with extension ".key" and certificates are stored with extension ".cert".
DecryptPGP returns a stream with "data" decrypted by the provided passphrase.
DefaultStepPrinter outputs the message to out as it is.
DetectPlanetEnvironment detects if the process is executed inside the container.
Dir sets the command's working dir.
DurationPtr returns a pointer to the provided duration value.
EncryptPGP returns a stream with "data" encrypted by the provided passphrase.
EnsureLineInFile makes sure the specified file contains provided line.
EnsureLocalPath makes sure the path exists, or, if omitted results in the subpath in default gravity config directory, e.g.
EnsurePort makes sure that the provided address includes a port and adds the specified default one if it does not.
EnsurePortURL is like EnsurePort but for URLs.
EnsureScheme makes sure the provided URL contains http or https scheme and adds the specified default one if it does not.
EtcdHasMember returns the peer given its peerURL.
EtcdInitialCluster interprets the output of etcdctl member list as a comma-separated list of name:ip pairs.
EtcdParseMemberList parses "etcdctl member list" output.
No description provided by the author
ExecL executes the specified cmd and logs the command line to the specified entry.
ExecUnprivileged executes the specified command as unprivileged user.
No description provided by the author
No description provided by the author
ExitStatusFromError returns the exit status from the specified error.
ExtractHost returns only the host part from the provided address.
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
.
FlattenStringSlice takes a slice of strings like ["one,two", "three"] and returns ["one", "two", "three"].
FlattenVersion removes or replaces characters from the version string to make it useable as part of kubernetes resource names.
FormatBoolPtr formats the bool pointer value for output.
FormatMeta formats the specified object metadata for output.
FormatStringPtrWithDefault formats the string pointer value for output.
GeneratePrivateKeyPEM generates and returns PEM serialzed.
GenerateSelfSignedCert generates a self signed certificate that is valid for given domain names and ips, returns PEM-encoded bytes with key and cert Generates a certificate that is compatible with the MacOS requirements described at: https://support.apple.com/en-us/HT210176.
Getenv returns the map of name->value pairs that captures the specified list of environment variables.
GetenvDuration returns the specified environment variable value parsed as a duration.
GetenvInt returns the specified environment variable value parsed as an integer.
GetenvsByPrefix returns environment variables with names matching specified prefix.
GetenvWithDefault returns the value of the environment variable given with name or defaultValue if the variable does not exist.
GetKubeClient returns instance of client to the kubernetes cluster using in-cluster configuration if available and falling back to configuration file under configPath otherwise.
GetLocalKubeClient returns a client with config from KUBECONFIG env var or ~/.kube/config.
GetLocalPath constructs path to the local gravity config file like described in the EnsureLocalPath above.
GetMasters returns IPs of nodes which are marked with a "master" label.
GetNodes returns the map of kubernetes nodes keyed by advertise IPs.
GetPasswd returns the reader to the contents of the passwd file.
HasOneOfPrefixes returns true if the provided string starts with any of the specified prefixes.
Hosts returns a list of hosts from the provided host:port addresses.
InitGRPCLogger initializes the logger with specified severity and verbosity.
InitGRPCLoggerFromEnvironment configures the GRPC logger if any of the related environment variables are set.
InitGRPCLoggerWithDefaults configures the GRPC logger with debug defaults.
InitLogging initializes logging to log both to syslog and to a file.
Int64Ptr returns a pointer to an int64 with value v.
IntPtr returns a pointer to an int with value v.
IsAbortError returns true if the specified error is of type AbortRetry.
IsAPIServerService return true if the given service specifies the API server service.
IsClosedConnectionError determines if the specified error is a closed connection error.
IsClosedResponseBodyErrorMessage determines if the error message describes a closed response body error.
IsClusterDegradedError determines if the error indicates that the cluster is degraded.
IsClusterUnavailableError determines if the specified error is a cluster unavailable error.
IsConnectionProblem determines whether err signifies a connection problem.
IsConnectionRefusedError determines whether err is a 'connection refused' error.
IsConnectionResetError determines whether err is a 'connection reset by peer' error.
IsContextCancelledError returns true if the provided error is a result of a context cancellation.
IsContinueError returns true if provided error is of ContinueRetry type.
IsDirectory determines if path specifies a directory.
IsDirectoryEmpty returns true if the specified directory is empty The directory must exist or an error will be returned.
IsFile determines if path specifies a regular file.
IsHeadlessService return true if the given service is a headless service (explicitly without a cluster IP).
IsKubeAuthError determines whether the specified error is an authorization error from kubernetes client.
IsKubernetesLabel returns true if the provided label key is in Kubernetes namespace.
IsNetworkError returns true if the provided error is Go's network error.
IsPathError determines if the specified err is of type os.PathError.
IsResourceBusyError determines if the specified error identifies a 'device or resource busy' error.
IsStreamClosedError determines if the given error is a response/stream closed error.
IsTransientClusterError determines if the specified error corresponds to a transient error - e.g.
KubeServiceNames returns all possible DNS names a specified Kubernetes service can be accessed by in the specified namespace.
LoadKubeConfig tries to read a kubeconfig file and if it can't, returns an error.
LocalIPNetworks returns the list of all local IP networks.
LoggerWithService returns a new logger with service-relevant metadata.
MakeSelector converts set of key-value pairs to selector.
MatchesLabels determines whether a set of "target" labels matches the set of "wanted" labels.
Max returns the greater of two numbers.
MaxInt64 returns the greater of (x, y).
Min returns the smaller of two numbers.
MkdirAll creates directory and subdirectories.
MustParseCapacity parses the provided string as capacity or panics.
MustParseTransferRate parses the provided data as a transfer rate or panics.
MustSHA512Half panics if it fails to compute SHA512 hash, use only in tests.
NewAddress parses the provided network address, port is mandatory.
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.
NewConsoleProgress returns new instance of progress reporter steps is the total amount of steps this progress reporter will report.
NewCurrentExecutable returns a new Executable for the currently running gravity binary.
NewExitCodeError returns a new error with the specified exit code.
NewExitCodeErrorWithMessage returns a new error that wraps a specific exit code and message.
NewExponentialBackOff creates a new backoff interval with the specified timeout.
NewFailedPreconditionError returns a new failed precondition error with optional original error err.
NewMultiWriteCloser returns new WriteCloser, all writes go to all writers one by one and close closes all closers one by one.
NewNopReader returns a new no-op io.Reader.
NewPreconditionFailedError returns a new error signifying a failed precondition.
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.
NewProgressWithConfig returns new progress reporter for the given set of options.
NewSSHCommands returns a new remote command executor that will use the specified runner to execute commands.
NewStderrLogger returns a new io.Writer that logs its input with log.Warn.
No description provided by the author
No description provided by the author
NewSyncBuffer returns new in memory buffer.
No description provided by the author
NewUninstallServiceError returns a plan out of sync error.
NewUnlimitedExponentialBackOff returns a backoff interval without time restriction.
NewUnsupportedFilesystemError creates a new error for an unsupported filesystem at the specified path.
NopWriteCloser returns a WriteCloser with a no-op Close method wrapping the provided Writer w.
NormalizePath normalises path, evaluating symlinks and converting local paths to absolute.
OpenFile opens the file at the provided path in a+ mode.
OwnerOption changes the owner on the specified file to (uid, gid).
ParseAddrList parses a comma-separated list of addresses.
ParseAsString returns a parser function that extracts the stream contents as a string.
ParseBoolFlag extracts boolean parameter of the specified name from the provided request's query string, or returns default.
ParseCertificate parses the provided data as PEM-formatted x509 certificate (or chain) and returns a web-UI-friendly representation of it.
ParseDDOutput parses the output of "dd" command and returns the reported speed in bytes per second.
ParseDiscard returns a no-op parser function that discards the input.
ParseDockerInfo parses output produced by `docker info` command.
ParseFilename parses the filename for the specified form data.
ParseHostOverride parses DNS host override in the format <host>/<ip>.
ParseHostPort parses the provided address as host:port.
ParseLabels parses a string like "a=b,c=d" as a map.
ParseOpsCenterAddress parses OpsCenter address.
ParsePasswd interprets the specified passwd file as a list of users.
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.
ParseProxy parses the provided HTTP(-S) proxy address and returns it in the parsed URL form.
ParseProxyAddr parses proxy address in the format "host:webPort,sshPort"
If web/SSH ports are missing the provided defaults are used.
ParseSystemdVersion parses the output of "systemctl --version" command and returns systemd version number.
ParseZoneOverride parses DNS zone override in the format <host>/<ip> or <host>/<ip>:<port>.
PermOption changes the file permissions on the specified file to perm.
PickAdvertiseIP selects an advertise IP among the host's interfaces.
PlanetCommand returns a new command to run the specified command cmd inside planet container.
PlanetCommandArgs returns a new command to run the command specified with args inside planet container.
PlanetCommandSlice returns a new command to run the command specified with args inside planet.
PlanetEnterCommand returns command that runs in planet using gravity from path.
PrintProgress prints generic progress with stages.
No description provided by the author
ReadEnv reads the file at the specified path as a file containing environment variables (e.g.
ReaderForPath returns a reader for file at given path.
ReadPath reads file at given path.
ReadTLSArchive reads TLS packed archive, where keys are stored with extension ".key" and certificates are stored with extension ".cert".
RecursiveGlob recursively walks the dir and returns the list of files matching the specified patterns.
RemoveContents removes any children of dir.
RemoveNewlines removes newlines from string.
ResolveAddr resolves the provided hostname using the local resolver.
Retry attempts to execute fn up to maxAttempts sleeping for period between attempts.
RetryFor retries the provided function until it succeeds or until timeout has been reached.
RetryOnNetworkError attempts to execute fn up to maxAttempts sleeping for period between attempts if the encountered error is of network nature.
RetryRead reads the contents of the reader to the temporary file and retries several times on failure.
RetryTransient retries the specified operation fn using the specified backoff interval if the operation is experiencing transient errors.
RetryWithInterval retries the specified operation fn using the specified backoff interval.
RunCommand executes the command specified with args.
RunGravityCommand executes the command specified with args with the current process binary.
RunInPlanetCommand executes the command specified with args inside planet container.
RunKubernetesTests returns true if requested to run tests against running kubernetes.
RunPlanetCommand executes the command specified with args as a planet command inside the container.
RunStream executes a command specified with args and streams output to w.
SanitizeSemver validates semver pre-release/metadata fields are alphanumeric characters dash and dot as per https://semver.org/#semantic-versioning-specification-semver.
SaveKubeConfig saves updated config to location specified by environment variable or default location.
SelectSubnet returns a /16 subnet that does not overlap with the provided subnet blocks.
SelectVPCSubnet returns a /24 subnet that does not overlap with the provided subnet blocks from the provided VPC block.
Self returns the command line for the currently running executable.
SHA512Half is a first half of SHA512 hash of the byte string.
ShouldReconnectPeer implements the error classification for peer connection errors
It detects unrecoverable errors and aborts the reconnect attempts.
SplitHostPort extracts host name without port from host.
SplitSlice splits the provided string slice into batches of specified size.
SSHRunAndParse runs remote SSH command cmd with environment variables set with env.
StatDir stats directory, returns error if file exists, but not a directory.
StatFile determines if the specified path refers to a file.
Stderr redirects the command's stderr to the specified writer.
Stdout redirects the command's stdout to the specified writer.
No description provided by the author
StringPtr returns a pointer to the provided string.
No description provided by the author
StringSlicesEqual determines whether the two slices are equal.
StringValue returns the string value in v or an empty string if it's nil.
SyslogWrite writes the message to the system log with the specified priority and tag.
TeeReadCloser is just like TeeReader but implements io.ReadCloser.
ThrottlingPipe connects a producer writing to inCh with a consumer reading from outCh.
TimestampedStepPrinter adds timestamps to the printed messages.
ToError either returns error as is, or converts it to Errorf in case of unknown object.
ToRawTrace converts the trace error to marshable format.
ToUnknownResource converts the provided resource to a generic resource type.
TrimPathPrefix returns the provided path without the specified prefix path
Leading path separator is also stripped.
UnmarshalError unmarshals bytes as JSON-encoded error.
URLHostname returns hostname without port for given URL address.
URLSplitHostPort extracts host name without port from URL.
UTC converts time to UTC timezone.
WithTempDir creates a temporary directory and executes the specified function fn providing it with the name of the directory.
WrapExitCodeError returns a new error with the specified exit code that wrap another error.
WriteEnv writes the provided env as an environment variables file at the specified path.
WriteJSON writes JSON serialized object into provided writer.
WritePath writes file to given path.
WriteYAML writes YAML serialized object into provided writer.
# Constants
CertSuffix is the standard extension used for x509 cert files generated by gravity.
KeySuffix is the standard extension used for x509 key files generated by gravity.
ProgressLevelDebug is the level for more detailed information.
ProgressLevelInfo is the level for basic informational messages.
ProgressLevelNone disables all output.
# Variables
DiscardingLog is a logger that discards output.
DiscardPrinter is a Printer that discards all input.
DiscardProgress is a progress reporter that discards all progress output.
Exe is the Executable for the currently running gravity binary.
Runner is the default CommandRunner.
# Structs
AbortRetry if returned from Retry, will lead to retries to be stopped, but the Retry function will return internal Error.
Address contains parsed network address.
BandwidthWriter is a writer that calculates amount of traffic (bytes) going through it.
CertificateName contains information about certificate subject/issuer.
CertificateOutput contains information about cluster certificate.
CertificateValidity contains information about certificate validity dates.
CleanupReadCloser is an io.ReadCloser that tracks when the reading side is closed and then runs the configured cleanup callback.
ClusterDegradedError indicates that the cluster is degraded.
ContinueRetry if returned from Retry, will be lead to retry next time.
DockerInfo is structured information returned by docker info.
ErrorUninstallService is an error returned for failed service uninstall attempts.
EtcdMember describes an etcd member from "etcdctl member list" output.
Executable describes a running gravity binary.
Hook implements log.Hook and multiplexes log messages both to stderr and a log file.
MultiWriteCloser returns multi writer and multi closer.
NopReader is a io.Reader that does nothing.
ProgressConfig defines configuration for the progress printer.
SafeByteBuffer is a goroutine safe bytes.Buffer.
StderrLogger is a stdlib-compatible logger that logs to the underlying logger at Warn level.
SyncBuffer is in memory bytes buffer that is safe for concurrent writes.
No description provided by the author
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.
User describes a system user as found in a passwd file.
# Interfaces
Command abstracts a CLI command.
CommandRunner abstracts command execution.
ExitCodeError defines an interface for exit code errors.
Marshaler defines an interface for marshalable objects.
Printer describes a capability to output to standard output.
Progress is a progress reporter.
SSHCommands abstracts a way of executing a set of remote commands.
# Type aliases
Capacity allows to define capacity in a human readable form (e.g.
CommandOptionSetter defines a type for a functional option setter for exec.Cmd.
CommandRunnerFunc is the wrapper that allows standalone functions to act as CommandRunners.
EtcdMemberList represents parsed "etcdctl member list" output.
FileOption defines a functional option to apply to specified path.
MultiCloser is a list of closers with combined Close method.
OutputParseFn defines a parser function for arbitrary input r.
ProgressLevel represents a level at which reporter reports progress.
StepPrinter prints a single step message.
No description provided by the author
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.
TransferRate allows to define transfer rate in a human friendly form (e.g.