Documentation ¶
Index ¶
- Constants
- Variables
- func AllowNewlines(s string) string
- func AsBool(v string) bool
- func CalculateSPKI(cert *x509.Certificate) string
- func CanUserWriteTo(path string) (bool, error)
- func ChainStreamServerInterceptors(first grpc.StreamServerInterceptor, rest ...grpc.StreamServerInterceptor) grpc.StreamServerInterceptor
- func ChainUnaryServerInterceptors(first grpc.UnaryServerInterceptor, rest ...grpc.UnaryServerInterceptor) grpc.UnaryServerInterceptor
- func CheckCertificateFormatFlag(s string) (string, error)
- func CheckSPKI(pins []string, certs []*x509.Certificate) error
- func CheckVersion(currentVersion, minVersion string) error
- func ChooseRandomString(slice []string) string
- func CipherSuiteMapping(cipherSuites []string) ([]uint16, error)
- func ClickableURL(in string) string
- func ClientIPFromConn(conn net.Conn) (string, error)
- func Color(color int, v interface{}) string
- func CompressTarGzArchive(files []string, fileReader ReadStatFS) (*bytes.Buffer, error)
- func Consolef(w io.Writer, log logrus.FieldLogger, component, msg string, ...)
- func ContainsExpansion(val string) bool
- func CopyStringsMap(in map[string]string) map[string]string
- func CreateCertificate(principal string, certType uint32) (*ssh.Certificate, ssh.Signer, error)
- func CreateEllipticCertificate(principal string, certType uint32) (*ssh.Certificate, ssh.Signer, error)
- func CreateTLSConfiguration(certFile, keyFile string, cipherSuites []uint16) (*tls.Config, error)
- func CryptoRandomHex(length int) (string, error)
- func DNSName(hostport string) (string, error)
- func DefaultCipherSuites() []uint16
- func DualPipeNetConn(srcAddr net.Addr, dstAddr net.Addr) (*PipeNetConn, *PipeNetConn)
- func EnsureLocalPath(customPath string, defaultLocalDir, defaultLocalPath string) (string, error)
- func EscapeControl(s string) string
- func Extract(r io.Reader, dir string) error
- func FSTryReadLock(filePath string) (unlock func() error, err error)
- func FSTryReadLockTimeout(ctx context.Context, filePath string, timeout time.Duration) (unlock func() error, err error)
- func FSTryWriteLock(filePath string) (unlock func() error, err error)
- func FSTryWriteLockTimeout(ctx context.Context, filePath string, timeout time.Duration) (unlock func() error, err error)
- func FastMarshal(v interface{}) ([]byte, error)
- func FastMarshalIndent(v interface{}, prefix, indent string) ([]byte, error)
- func FastUnmarshal(data []byte, v interface{}) error
- func FatalError(err error)
- func FileExists(fp string) bool
- func FnCacheGet[T any](ctx context.Context, cache *FnCache, key any, ...) (T, error)
- func FormatAlert(alert types.ClusterAlert) string
- func FormatErrorWithNewline(err error) string
- func GRPCClientStreamErrorInterceptor(ctx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn, method string, ...) (grpc.ClientStream, error)
- func GRPCClientUnaryErrorInterceptor(ctx context.Context, method string, req, reply interface{}, ...) error
- func GRPCServerStreamErrorInterceptor(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, ...) error
- func GRPCServerUnaryErrorInterceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, ...) (interface{}, error)
- func GenerateOTPURL(typ string, label string, parameters map[string][]byte) string
- func GenerateQRCode(u string) ([]byte, error)
- func GenerateSelfSignedSigningCert(entity pkix.Name, dnsNames []string, ttl time.Duration) ([]byte, []byte, error)
- func GetEC2IdentityDocument() ([]byte, error)
- func GetEC2NodeID() (string, error)
- func GetIterations() int
- func GetListenerFile(listener net.Listener) (*os.File, error)
- func GlobToRegexp(in string) string
- func GuessHostIP() (ip net.IP, err error)
- func HasBTF() error
- func HasPrefixAny(prefix string, values []string) bool
- func Host(hostname string) (string, error)
- func InitCLIParser(appName, appHelp string) (app *kingpin.Application)
- func InitLogger(purpose LoggingPurpose, level logrus.Level, verbose ...bool)
- func InitLoggerForTests()
- func IsCertExpiredError(err error) bool
- func IsConnectionRefused(err error) bool
- func IsDir(path string) bool
- func IsEC2NodeID(id string) bool
- func IsExpiredCredentialError(err error) bool
- func IsFailedToSendCloseNotifyError(err error) bool
- func IsFile(path string) bool
- func IsGroupMember(gid int) (bool, error)
- func IsHandshakeFailedError(err error) bool
- func IsLocalhost(host string) bool
- func IsOKNetworkError(err error) bool
- func IsPredicateError(err error) bool
- func IsSelfSigned(certificateChain []*x509.Certificate) bool
- func IsUntrustedCertErr(err error) bool
- func IsUseOfClosedNetworkError(err error) bool
- func IsValidHostname(hostname string) bool
- func KernelVersion() (*semver.Version, error)
- func MarshalPrivateKey(key crypto.Signer) ([]byte, []byte, error)
- func MarshalPublicKey(signer crypto.Signer) ([]byte, error)
- func MaxInt64(x, y int64) int64
- func MinInt64(x, y int64) int64
- func MinTTL(a, b time.Duration) time.Duration
- func MinVerWithoutPreRelease(currentVersion, minVersion string) (bool, error)
- func MkdirAll(targetDirectory string, mode os.FileMode) error
- func MultiCloser(closers ...io.Closer) io.Closer
- func NetAddrsToStrings(netAddrs []NetAddr) []string
- func NewCertPoolFromPath(path string) (*x509.CertPool, error)
- func NewDefaultLinear() *retryutils.Linear
- func NewLogger() *logrus.Logger
- func NewLoggerForTests() *logrus.Logger
- func NewStdlogger(logger LeveledOutputFunc, component string) *stdlog.Logger
- func NilCloser(r io.Closer) io.Closer
- func NodeIDFromIID(iid *imds.InstanceIdentityDocument) string
- func NopWriteCloser(r io.Writer) io.WriteCloser
- func NormalizePath(path string) (string, error)
- func OSRelease(rel io.Reader) (map[string]string, error)
- func ObeyIdleTimeout(conn net.Conn, timeout time.Duration, ownerName string) net.Conn
- func OpaqueAccessDenied(err error) error
- func OpenFile(path string) (*os.File, error)
- func ParseAdvertiseAddr(advertiseIP string) (string, string, error)
- func ParseOnOff(parameterName, val string, defaultValue bool) (bool, error)
- func ParsePrivateKey(bytes []byte) (crypto.Signer, error)
- func ParsePrivateKeyDER(der []byte) (crypto.Signer, error)
- func ParsePrivateKeyPEM(bytes []byte) (crypto.Signer, error)
- func ParsePublicKey(bytes []byte) (crypto.PublicKey, error)
- func PercentUsed(path string) (float64, error)
- func PrintVersion()
- func ProxyConn(ctx context.Context, client, server io.ReadWriteCloser) error
- func RandomDuration(max time.Duration) time.Duration
- func ReadAtMost(r io.Reader, limit int64) ([]byte, error)
- func ReadCertificates(certificateChainBytes []byte) ([]*x509.Certificate, error)
- func ReadCertificatesFromPath(path string) ([]*x509.Certificate, error)
- func ReadEnvironmentFile(filename string) ([]string, error)
- func ReadHostUUID(dataDir string) (string, error)
- func ReadOrMakeHostUUID(dataDir string) (string, error)
- func ReadPath(path string) ([]byte, error)
- func ReadYAML(reader io.Reader) (interface{}, error)
- func RemoveFromSlice(slice []string, values ...string) []string
- func ReplaceInSlice(s []string, old string, new string) []string
- func ReplaceLocalhost(addr, replaceWith string) string
- func ReplaceRegexp(expression string, replaceWith string, input string) (string, error)
- func ReplaceRegexpWithConfig(expression string, replaceWith string, input string, config RegexpConfig) (string, error)
- func ReplaceUnspecifiedHost(addr *NetAddr, defaultPort int) string
- func Round(x float64) float64
- func Roundtrip(addr string) (string, error)
- func RoundtripWithConn(conn net.Conn) (string, error)
- func SetupTLSConfig(config *tls.Config, cipherSuites []uint16)
- func SliceMatchesRegex(input string, expressions []string) (bool, error)
- func SplitHostPort(hostname string) (string, string, error)
- func SplitIdentifiers(s string) []string
- func StatDir(path string) (os.FileInfo, error)
- func StatFile(path string) (os.FileInfo, error)
- func StoreErrorOf(f func() error, err *error)
- func StringMapsEqual(a, b map[string]string) bool
- func StringSliceSubset(a []string, b []string) error
- func StringsSet(in []string) map[string]struct{}
- func StringsSliceFromSet(in map[string]struct{}) []string
- func SwitchLoggerToSyslog(logger *log.Logger) error
- func SwitchLoggingtoSyslog() error
- func TLSCertToX509(cert tls.Certificate) (*x509.Certificate, error)
- func TLSConfig(cipherSuites []uint16) *tls.Config
- func TLSDial(ctx context.Context, dial DialWithContextFunc, network, addr string, ...) (*tls.Conn, error)
- func ThisFunction() string
- func ToJSON(data []byte) ([]byte, error)
- func ToTTL(c clockwork.Clock, tm time.Time) time.Duration
- func TryReadValueAsFile(value string) (string, error)
- func UintSliceSubset(a []uint16, b []uint16) error
- func UpdateAppUsageTemplate(app *kingpin.Application, args []string)
- func UserMessageFromError(err error) string
- func VerifyCertificateChain(certificateChain []*x509.Certificate) error
- func VerifyCertificateExpiry(c *x509.Certificate, clock clockwork.Clock) error
- func VersionBeforeAlpha(version string) string
- func WriteCloserWithContext(ctx context.Context, closer WriteContextCloser) io.WriteCloser
- func WriteHostUUID(dataDir string, id string) error
- func WriteYAML(w io.Writer, values interface{}) error
- type Anonymizer
- type BufferSyncPool
- type CaptureNBytesWriter
- type CircularBuffer
- type CloseBroadcaster
- type CloserConn
- type DialWithContextFunc
- type Fields
- type FieldsCondition
- type FileNode
- type FnCache
- type FnCacheConfig
- type HMACAnonymizer
- type InMemoryFile
- type JSONFormatter
- type JumpHost
- type KeyStore
- type LeveledOutputFunc
- type LoadBalancer
- type Logger
- type LoggingPurpose
- type NetAddr
- func AddrsFromStrings(s apiutils.Strings, defaultPort int) ([]NetAddr, error)
- func DialAddrFromListenAddr(listenAddr NetAddr) NetAddr
- func FromAddr(a net.Addr) NetAddr
- func JoinAddrSlices(a []NetAddr, b []NetAddr) []NetAddr
- func MustParseAddr(a string) *NetAddr
- func MustParseAddrList(aList ...string) []NetAddr
- func ParseAddr(a string) (*NetAddr, error)
- func ParseAddrs(addrs []string) (result []NetAddr, err error)
- func ParseHostPortAddr(hostport string, defaultPort int) (*NetAddr, error)
- func (a *NetAddr) FullAddress() string
- func (a *NetAddr) Host() string
- func (a *NetAddr) IsEmpty() bool
- func (a *NetAddr) IsHostUnspecified() bool
- func (a *NetAddr) IsLocal() bool
- func (a *NetAddr) IsLoopback() bool
- func (a *NetAddr) MarshalYAML() (interface{}, error)
- func (a *NetAddr) Network() string
- func (a *NetAddr) Port(defaultPort int) int
- func (a *NetAddr) Set(s string) error
- func (a *NetAddr) String() string
- func (a *NetAddr) UnmarshalYAML(unmarshal func(interface{}) error) error
- type OpenFileWithFlagsFunc
- type PipeNetConn
- func (nc *PipeNetConn) Close() error
- func (nc *PipeNetConn) LocalAddr() net.Addr
- func (nc *PipeNetConn) Read(buf []byte) (n int, e error)
- func (nc *PipeNetConn) RemoteAddr() net.Addr
- func (nc *PipeNetConn) SetDeadline(t time.Time) error
- func (nc *PipeNetConn) SetReadDeadline(t time.Time) error
- func (nc *PipeNetConn) SetWriteDeadline(t time.Time) error
- func (nc *PipeNetConn) Write(buf []byte) (n int, e error)
- type PortList
- type PredicateError
- type ReadStatFS
- type RegexpConfig
- type RepeatReader
- type SlicePool
- type SliceSyncPool
- type Stater
- type SyncBuffer
- type SyncString
- type SyncWriter
- type TLSConn
- type TLSCredentials
- type TextFormatter
- type TimedCounter
- type TimeoutConn
- type Tracer
- type TrackingConn
- type TrackingReader
- type TrackingWriter
- type UID
- type WebLinks
- type WriteContextCloser
Constants ¶
const ( // Bold is an escape code to format as bold or increased intensity Bold = 1 // Red is an escape code for red terminal color Red = 31 // Yellow is an escape code for yellow terminal color Yellow = 33 // Blue is an escape code for blue terminal color Blue = 36 // Gray is an escape code for gray terminal color Gray = 37 )
const ( // DefaultLRUCapacity is a capacity for LRU session cache DefaultLRUCapacity = 1024 // DefaultCertTTL sets the TTL of the self-signed certificate (1 year) DefaultCertTTL = (24 * time.Hour) * 365 )
const ( // CertTeleportUser specifies teleport user CertTeleportUser = "x-teleport-user" // CertTeleportUserCA specifies teleport certificate authority CertTeleportUserCA = "x-teleport-user-ca" // CertExtensionRole specifies teleport role CertExtensionRole = "x-teleport-role" // CertExtensionAuthority specifies teleport authority's name // that signed this domain CertExtensionAuthority = "x-teleport-authority" // HostUUIDFile is the file name where the host UUID file is stored HostUUIDFile = "host_uuid" // CertTeleportClusterName is a name of the teleport cluster CertTeleportClusterName = "x-teleport-cluster-name" // CertTeleportUserCertificate is the certificate of the authenticated in user. CertTeleportUserCertificate = "x-teleport-certificate" // ExtIntCertType is an internal extension used to propagate cert type. ExtIntCertType = "certtype@teleport" // ExtIntCertTypeHost indicates a host-type certificate. ExtIntCertTypeHost = "host" // ExtIntCertTypeUser indicates a user-type certificate. ExtIntCertTypeUser = "user" )
const PortStartingNumber = 20000
PortStartingNumber is a starting port number for tests
const (
// SelfSignedCertsMsg is a helper message to point users towards helpful documentation.
SelfSignedCertsMsg = "Your proxy certificate is not trusted or expired. " +
"Please update the certificate or follow this guide for self-signed certs: https://goteleport.com/docs/setup/admin/self-signed-certs/"
)
Variables ¶
var ( // ErrFnCacheClosed is returned from Get when the FnCache context is closed ErrFnCacheClosed = errors.New("fncache permanently closed") )
var ErrLimitReached = &trace.LimitExceededError{Message: "the read limit is reached"}
ErrLimitReached means that the read limit is reached.
var ErrUnsuccessfulLockTry = errors.New("could not acquire lock on the file at this time")
ErrUnsuccessfulLockTry designates an error when we temporarily couldn't acquire lock (most probably it was already locked by someone else), another try might succeed.
var FullJitter = retryutils.NewFullJitter()
FullJitter is a global jitter instance used for one-off jitters. Prefer instantiating a new jitter instance for operations that require repeated calls
var HalfJitter = retryutils.NewHalfJitter()
HalfJitter is a global jitter instance used for one-off jitters. Prefer instantiating a new jitter instance for operations that require repeated calls.
var KnownFormatFields = knownFormatFieldsMap{ // contains filtered or unexported fields }
KnownFormatFields are the known fields for log entries
var SafeConfig = jsoniter.Config{ EscapeHTML: false, MarshalFloatWith6Digits: true, ObjectFieldMustBeSimpleString: true, SortMapKeys: true, }.Froze()
SafeConfig uses jsoniter's ConfigFastest settings but enables map key sorting to ensure CompareAndSwap checks consistently succeed.
var SeventhJitter = retryutils.NewSeventhJitter()
SeventhJitter is a global jitter instance used for one-off jitters. Prefer instantiating a new jitter instance for operations that require repeated calls.
Functions ¶
func AllowNewlines ¶
AllowNewlines escapes all ANSI escape sequences except newlines from string and returns a string that is safe to print on the CLI. This is to ensure that malicious servers can not hide output. For more details, see:
func AsBool ¶
AsBool converts string to bool, in case of the value is empty or unknown, defaults to false
func CalculateSPKI ¶
func CalculateSPKI(cert *x509.Certificate) string
CalculateSPKI the hash value of the SPKI header in a certificate.
func CanUserWriteTo ¶
CanUserWriteTo attempts to check if a user has write access to certain path. It also works around the program being run as root and tries to check the permissions of the user who executed the program as root. This should only be used for string formatting or inconsequential use cases as it's not bullet proof and can report wrong results.
func ChainStreamServerInterceptors ¶
func ChainStreamServerInterceptors(first grpc.StreamServerInterceptor, rest ...grpc.StreamServerInterceptor) grpc.StreamServerInterceptor
ChainStreamServerInterceptors takes 1 or more grpc.StreamServerInterceptors and chains them into a single grpc.StreamServerInterceptor. The first interceptor will be the outer most, while the last interceptor will be the inner most wrapper around the real call.
func ChainUnaryServerInterceptors ¶
func ChainUnaryServerInterceptors(first grpc.UnaryServerInterceptor, rest ...grpc.UnaryServerInterceptor) grpc.UnaryServerInterceptor
ChainUnaryServerInterceptors takes 1 or more grpc.UnaryServerInterceptors and chains them into a single grpc.UnaryServerInterceptor. The first interceptor will be the outer most, while the last interceptor will be the inner most wrapper around the real call.
func CheckCertificateFormatFlag ¶
CheckCertificateFormatFlag checks if the certificate format is valid.
func CheckSPKI ¶
func CheckSPKI(pins []string, certs []*x509.Certificate) error
CheckSPKI the passed in pin against the calculated value from a certificate.
func CheckVersion ¶
CheckVersion compares a version with a minimum version supported.
func ChooseRandomString ¶
ChooseRandomString returns a random string from the given slice.
func CipherSuiteMapping ¶
CipherSuiteMapping transforms Teleport formatted cipher suites strings into uint16 IDs.
func ClickableURL ¶
ClickableURL fixes address in url to make sure it's clickable, e.g. it replaces "undefined" address like 0.0.0.0 used in network listeners format with loopback 127.0.0.1
func ClientIPFromConn ¶
ClientIPFromConn extracts host from provided remote address.
func CompressTarGzArchive ¶
func CompressTarGzArchive(files []string, fileReader ReadStatFS) (*bytes.Buffer, error)
CompressTarGzArchive creates a Tar Gzip archive in memory, reading the files using the provided file reader
func Consolef ¶ added in v1.0.0
func Consolef(w io.Writer, log logrus.FieldLogger, component, msg string, params ...interface{})
Consolef prints the same message to a 'ui console' (if defined) and also to the logger with INFO priority
func ContainsExpansion ¶
ContainsExpansion returns true if value contains expansion syntax, e.g. $1 or ${10}
func CopyStringsMap ¶
CopyStringsMap returns a copy of the strings map
func CreateCertificate ¶
CreateCertificate creates a valid 2048-bit RSA certificate.
func CreateEllipticCertificate ¶
func CreateEllipticCertificate(principal string, certType uint32) (*ssh.Certificate, ssh.Signer, error)
CreateEllipticCertificate creates a valid, but not supported, ECDSA SSH certificate. This certificate is used to make sure Teleport rejects such certificates.
func CreateTLSConfiguration ¶
CreateTLSConfiguration sets up default TLS configuration
func CryptoRandomHex ¶ added in v1.0.0
CryptoRandomHex returns a hex-encoded random string generated with a crypto-strong pseudo-random generator. The length parameter controls how many random bytes are generated, and the returned hex string will be twice the length. An error is returned when fewer bytes were generated than length.
func DefaultCipherSuites ¶
func DefaultCipherSuites() []uint16
DefaultCipherSuites returns the default list of cipher suites that Teleport supports. By default Teleport only support modern ciphers (Chacha20 and AES GCM) and key exchanges which support perfect forward secrecy (ECDHE).
Note that TLS_RSA_WITH_AES_128_GCM_SHA{256,384} have been dropped due to being banned by HTTP2 which breaks GRPC clients. For more information see: https://tools.ietf.org/html/rfc7540#appendix-A. These two can still be manually added if needed.
func DualPipeNetConn ¶
func DualPipeNetConn(srcAddr net.Addr, dstAddr net.Addr) (*PipeNetConn, *PipeNetConn)
DualPipeAddrConn creates a net.Pipe to connect a client and a server. The two net.Conn instances are wrapped in an addrConn which holds the source and destination addresses.
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 EscapeControl ¶
EscapeControl escapes all ANSI escape sequences from string and returns a string that is safe to print on the CLI. This is to ensure that malicious servers can not hide output. For more details, see:
func Extract ¶
Extract extracts the contents of the specified tarball under dir. The resulting files and directories are created using the current user context. Extract will only unarchive files into dir, and will fail if the tarball tries to write files outside of dir.
func FSTryReadLock ¶
FSTryReadLock tries to grab write lock, returns ErrUnsuccessfulLockTry if lock is already acquired by someone else
func FSTryReadLockTimeout ¶
func FSTryReadLockTimeout(ctx context.Context, filePath string, timeout time.Duration) (unlock func() error, err error)
FSTryReadLockTimeout tries to grab read lock, it's doing it until locks is acquired, or timeout is expired, or context is expired.
func FSTryWriteLock ¶
FSTryWriteLock tries to grab write lock, returns ErrUnsuccessfulLockTry if lock is already acquired by someone else
func FSTryWriteLockTimeout ¶
func FSTryWriteLockTimeout(ctx context.Context, filePath string, timeout time.Duration) (unlock func() error, err error)
FSTryWriteLockTimeout tries to grab write lock, it's doing it until locks is acquired, or timeout is expired, or context is expired.
func FastMarshal ¶
FastMarshal uses the json-iterator library for fast JSON marshaling. Note, this function unmarshals floats with 6 digits precision.
func FastMarshalIndent ¶
FastMarshal uses the json-iterator library for fast JSON marshaling with indentation. Note, this function unmarshals floats with 6 digits precision.
func FastUnmarshal ¶
FastUnmarshal uses the json-iterator library for fast JSON unmarshalling. Note, this function marshals floats with 6 digits precision.
func FatalError ¶ added in v1.0.0
func FatalError(err error)
FatalError is for CLI front-ends: it detects gravitational/trace debugging information, sends it to the logger, strips it off and prints a clean message to stderr
func FileExists ¶
FileExists checks whether a file exists at a given path
func FnCacheGet ¶
func FnCacheGet[T any](ctx context.Context, cache *FnCache, key any, loadfn func(ctx context.Context) (T, error)) (T, error)
FnCacheGet loads the result associated with the supplied key. If no result is currently stored, or the stored result was acquired >ttl ago, then loadfn is used to reload it. Subsequent calls while the value is being loaded/reloaded block until the first call updates the entry. Note that the supplied context can cancel the call to Get, but will not cancel loading. The supplied loadfn should not be canceled just because the specific request happens to have been canceled.
func FormatAlert ¶
func FormatAlert(alert types.ClusterAlert) string
FormatAlert formats and colors the alert message if possible.
func FormatErrorWithNewline ¶
FormatErrorWithNewline returns user friendly error message from error. The error message is escaped if necessary. A newline is added if the error text does not end with a newline.
func GRPCClientStreamErrorInterceptor ¶
func GRPCClientStreamErrorInterceptor(ctx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn, method string, streamer grpc.Streamer, opts ...grpc.CallOption) (grpc.ClientStream, error)
GRPCClientStreamErrorInterceptor is GPRC client stream interceptor that handles converting errors to the appropriate grpc status error.
func GRPCClientUnaryErrorInterceptor ¶
func GRPCClientUnaryErrorInterceptor(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error
GRPCClientUnaryErrorInterceptor is a GPRC unary client interceptor that handles converting errors to the appropriate grpc status error.
func GRPCServerStreamErrorInterceptor ¶
func GRPCServerStreamErrorInterceptor(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error
GRPCServerStreamErrorInterceptor is a GPRC server stream interceptor that handles converting errors to the appropriate grpc status error.
func GRPCServerUnaryErrorInterceptor ¶
func GRPCServerUnaryErrorInterceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error)
GRPCServerUnaryErrorInterceptor is a GPRC unary server interceptor that handles converting errors to the appropriate grpc status error.
func GenerateOTPURL ¶
GenerateOTPURL returns a OTP Key URL that can be used to construct a HOTP or TOTP key. For more details see: https://github.com/google/google-authenticator/wiki/Key-Uri-Format Example: otpauth://totp/foo:bar@baz.com?secret=qux
func GenerateQRCode ¶
GenerateQRCode takes in a OTP Key URL and returns a PNG-encoded QR code.
func GenerateSelfSignedSigningCert ¶
func GenerateSelfSignedSigningCert(entity pkix.Name, dnsNames []string, ttl time.Duration) ([]byte, []byte, error)
GenerateSelfSignedSigningCert generates self-signed certificate used for digital signatures
func GetEC2IdentityDocument ¶
GetEC2IdentityDocument fetches the PKCS7 RSA2048 InstanceIdentityDocument from the IMDS for this EC2 instance.
func GetEC2NodeID ¶
GetEC2NodeID returns the node ID to use for this EC2 instance when using Simplified Node Joining.
func GetIterations ¶
func GetIterations() int
GetIterations provides a simple way to add iterations to the test by setting environment variable "ITERATIONS", by default it returns 1
func GetListenerFile ¶
GetListenerFile returns file associated with listener
func GlobToRegexp ¶
GlobToRegexp replaces glob-style standalone wildcard values with real .* regexp-friendly values, does not modify regexp-compatible values, quotes non-wildcard values
func GuessHostIP ¶ added in v1.0.0
GuessIP tries to guess an IP address this machine is reachable at on the internal network, always picking IPv4 from the internal address space
If no internal IPs are found, it returns 127.0.0.1 but it never returns an address from the public IP space
func HasBTF ¶
func HasBTF() error
HasBTF checks that the kernel has been compiled with BTF support and that the type information can be opened. Returns nil if BTF is there and accessible, otherwise an error describing the problem.
func HasPrefixAny ¶
HasPrefixAny determines if any of the string values have the given prefix.
func InitCLIParser ¶ added in v1.0.0
func InitCLIParser(appName, appHelp string) (app *kingpin.Application)
InitCLIParser configures kingpin command line args parser with some defaults common for all Teleport CLI tools
func InitLogger ¶
func InitLogger(purpose LoggingPurpose, level logrus.Level, verbose ...bool)
InitLogger configures the global logger for a given purpose / verbosity level
func InitLoggerForTests ¶ added in v1.0.0
func InitLoggerForTests()
InitLoggerForTests initializes the standard logger for tests.
func IsCertExpiredError ¶
IsCertExpiredError specifies whether this error indicates expired SSH certificate
func IsConnectionRefused ¶
IsConnectionRefused returns true if the given err is "connection refused" error.
func IsDir ¶ added in v1.0.0
IsDir is a helper function to quickly check if a given path is a valid directory
func IsEC2NodeID ¶
IsEC2NodeID returns true if the given ID looks like an EC2 node ID. Uses a simple regex to check. Node IDs are almost always UUIDs when set automatically, but can be manually overridden by admins. If someone manually sets a host ID that looks like one of our generated EC2 node IDs, they may be able to trick this function, so don't use it for any critical purpose.
func IsExpiredCredentialError ¶
IsExpiredCredentialError checks if an error corresponds to expired credentials.
func IsFailedToSendCloseNotifyError ¶
IsFailedToSendCloseNotifyError returns true if the provided error is the "tls: failed to send closeNotify".
func IsFile ¶ added in v1.0.0
IsFile is a convenience helper to check if the given path is a regular file
func IsGroupMember ¶
IsGroupMember returns whether currently logged user is a member of a group
func IsHandshakeFailedError ¶ added in v1.0.0
IsHandshakeFailedError specifies whether this error indicates failed handshake
func IsLocalhost ¶ added in v1.0.0
IsLocalhost returns true if this is a local hostname or ip
func IsOKNetworkError ¶
IsOKNetworkError returns true if the provided error received from a network operation is one of those that usually indicate normal connection close. If the error is a trace.Aggregate, all the errors must be OK network errors.
func IsPredicateError ¶
IsPredicateError determines if the error is from failing to parse predicate expression by checking if the error as a string contains predicate keywords.
func IsSelfSigned ¶
func IsSelfSigned(certificateChain []*x509.Certificate) bool
IsSelfSigned checks if the certificate is a self-signed certificate. To check if a certificate is self-signed, we make sure that only one certificate is in the chain and that the SubjectKeyId and AuthorityKeyId match.
From RFC5280: https://tools.ietf.org/html/rfc5280#section-4.2.1.1
The signature on a self-signed certificate is generated with the private key associated with the certificate's subject public key. (This proves that the issuer possesses both the public and private keys.) In this case, the subject and authority key identifiers would be identical, but only the subject key identifier is needed for certification path building.
func IsUntrustedCertErr ¶
IsUntrustedCertErr checks if an error is an untrusted cert error.
func IsUseOfClosedNetworkError ¶
IsUseOfClosedNetworkError returns true if the specified error indicates the use of a closed network connection.
func IsValidHostname ¶
IsValidHostname checks if a string represents a valid hostname.
func KernelVersion ¶
KernelVersion parses /proc/sys/kernel/osrelease and returns the kernel version of the host. This only returns something meaningful on Linux.
func MarshalPrivateKey ¶
MarshalPrivateKey will return a PEM encoded crypto.Signer. Only supports RSA private keys.
func MarshalPublicKey ¶
MarshalPublicKey returns a PEM encoded public key for a given crypto.Signer
func MinVerWithoutPreRelease ¶
MinVerWithoutPreRelease compares semver strings, but skips prerelease. This allows to compare two versions and ignore dev,alpha,beta, etc. strings.
func MultiCloser ¶
MultiCloser implements io.Close, it sequentially calls Close() on each object
func NetAddrsToStrings ¶
NetAddrsToStrings takes a list of netAddrs and returns a list of address strings.
func NewCertPoolFromPath ¶
NewCertPoolFromPath creates a new x509.CertPool from provided path.
func NewDefaultLinear ¶
func NewDefaultLinear() *retryutils.Linear
NewDefaultLinear creates a linear retry using a half jitter, 10s step, and maxing out at 1 minute. These values were selected by reviewing commonly used parameters elsewhere in the code base, which (at the time of writing) seem to converge on approximately this configuration for "critical but potentially load-inducing" operations like cache watcher registration and auth connector setup. It also includes an auto-reset value of 5m. Auto-reset is less commonly used, and if used should probably be shorter, but 5m is a reasonable safety net to reduce the impact of accidental misuse.
func NewLoggerForTests ¶
NewLoggerForTests creates a new logger for test environment
func NewStdlogger ¶
func NewStdlogger(logger LeveledOutputFunc, component string) *stdlog.Logger
NewStdlogger creates a new stdlib logger that uses the specified leveled logger for output and the given component as a logging prefix.
func NodeIDFromIID ¶
func NodeIDFromIID(iid *imds.InstanceIdentityDocument) string
NodeIDFromIID returns the node ID that must be used for nodes joining with the given Instance Identity Document.
func NopWriteCloser ¶
func NopWriteCloser(r 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 ObeyIdleTimeout ¶
ObeyIdleTimeout wraps an existing network connection with timeout-obeying Write() and Read() - it will drop the connection after 'timeout' on idle
Example: ObeyIdletimeout(conn, time.Second * 60, "api server").
func OpaqueAccessDenied ¶
OpaqueAccessDenied returns a generic NotFound instead of AccessDenied so as to avoid leaking the existence of secret resources.
func ParseAdvertiseAddr ¶
ParseAdvertiseAddr validates advertise address, makes sure it's not an unreachable or multicast address returns address split into host and port, port could be empty if not specified
func ParseOnOff ¶
ParseOnOff parses whether value is "on" or "off", parameterName is passed for error reporting purposes, defaultValue is returned when no value is set
func ParsePrivateKey ¶
ParsePrivateKey parses a PEM encoded private key and returns a crypto.Signer. Only supports RSA private keys.
func ParsePrivateKeyDER ¶
ParsePrivateKeyDER parses unencrypted DER-encoded private key
func ParsePrivateKeyPEM ¶
ParsePrivateKeyPEM parses PEM-encoded private key
func ParsePublicKey ¶
ParsePublicKey parses a PEM encoded public key and returns a crypto.PublicKey. Only support RSA public keys.
func PercentUsed ¶
PercentUsed returns percentage of disk space used. The percentage of disk space used is calculated from (total blocks - free blocks)/total blocks. The value is rounded to the nearest whole integer.
func ProxyConn ¶
func ProxyConn(ctx context.Context, client, server io.ReadWriteCloser) error
ProxyConn launches a double-copy loop that proxies traffic between the provided client and server connections.
Exits when one or both copies stop, or when the context is canceled, and closes both connections.
func RandomDuration ¶ added in v1.0.0
RandomDuration returns a duration in a range [0, max)
func ReadAtMost ¶
ReadAtMost reads up to limit bytes from r, and reports an error when limit bytes are read.
func ReadCertificates ¶
func ReadCertificates(certificateChainBytes []byte) ([]*x509.Certificate, error)
ReadCertificates parses PEM encoded bytes that can contain one or multiple certificates and returns a slice of x509.Certificate.
func ReadCertificatesFromPath ¶
func ReadCertificatesFromPath(path string) ([]*x509.Certificate, error)
ReadCertificatesFromPath parses PEM encoded certificates from provided path.
func ReadEnvironmentFile ¶
ReadEnvironmentFile will read environment variables from a passed in location. Lines that start with "#" or empty lines are ignored. Assignments are in the form name=value and no variable expansion occurs.
func ReadHostUUID ¶ added in v1.0.0
ReadHostUUID reads host UUID from the file in the data dir
func ReadOrMakeHostUUID ¶ added in v1.0.0
ReadOrMakeHostUUID looks for a hostid file in the data dir. If present, returns the UUID from it, otherwise generates one
func RemoveFromSlice ¶
RemoveFromSlice makes a copy of the slice and removes the passed in values from the copy.
func ReplaceInSlice ¶
ReplaceInSlice replaces element old with new and returns a new slice.
func ReplaceLocalhost ¶ added in v1.0.0
ReplaceLocalhost checks if a given address is link-local (like 0.0.0.0 or 127.0.0.1) and replaces it with the IP taken from replaceWith, preserving the original port
Both addresses are in "host:port" format The function returns the original value if it encounters any problems with parsing
func ReplaceRegexp ¶
ReplaceRegexp replaces value in string, accepts regular expression and simplified wildcard syntax, it has several important differeneces with standard lib regexp replacer: * Wildcard globs '*' are treated as regular expression .* expression * Expression is treated as regular expression if it starts with ^ and ends with $ * Full match is expected, partial replacements ignored * If there is no match, returns a NotFound error
func ReplaceRegexpWithConfig ¶
func ReplaceRegexpWithConfig(expression string, replaceWith string, input string, config RegexpConfig) (string, error)
ReplaceRegexpWithConfig behaves exactly like ReplaceRegexp but its behavior can be customized
func ReplaceUnspecifiedHost ¶
ReplaceUnspecifiedHost replaces unspecified "0.0.0.0" with localhost since "0.0.0.0" is never a valid principal (auth server explicitly removes it when issuing host certs) and when a reverse tunnel client used establishes SSH reverse tunnel connection the host is validated against the valid principal list.
func Round ¶
Round returns the nearest integer, rounding half away from zero.
Special cases are:
Round(±0) = ±0 Round(±Inf) = ±Inf Round(NaN) = NaN
Note: Copied from Go standard library to support Go 1.9.7 releases. This function was added in the standard library in Go 1.10.
func Roundtrip ¶
Roundtrip is a single connection simplistic HTTP client that allows us to bypass a connection pool to test load balancing used in tests, as it only supports GET request on /
func RoundtripWithConn ¶
RoundtripWithConn uses HTTP GET on the existing connection, used in tests as it only performs GET request on /
func SetupTLSConfig ¶
SetupTLSConfig sets up cipher suites in existing TLS config
func SliceMatchesRegex ¶
SliceMatchesRegex checks if input matches any of the expressions. The match is always evaluated as a regex either an exact match or regexp.
func SplitHostPort ¶
SplitHostPort splits host and port and checks that host is not empty
func SplitIdentifiers ¶
SplitIdentifiers splits list of identifiers by commas/spaces/newlines. Helpful when accepting lists of identifiers in CLI (role names, request IDs, etc).
func StoreErrorOf ¶
StoreErrorOf stores the error returned by f within *err.
func StringMapsEqual ¶
StringMapsEqual returns true if two strings maps are equal
func StringSliceSubset ¶
StringSliceSubset returns true if b is a subset of a.
func StringsSet ¶
StringsSet creates set of string (map[string]struct{}) from a list of strings
func StringsSliceFromSet ¶
StringsSliceFromSet returns a sorted strings slice from set
func SwitchLoggerToSyslog ¶
SwitchLoggerToSyslog tells the logger to send the output to syslog.
func SwitchLoggingtoSyslog ¶
func SwitchLoggingtoSyslog() error
SwitchLoggingtoSyslog tells the default logger to send the output to syslog. This code is behind a build flag because Windows does not support syslog.
func TLSCertToX509 ¶
func TLSCertToX509(cert tls.Certificate) (*x509.Certificate, error)
TLSCertToX509 is a helper function that converts a tls.Certificate into an *x509.Certificate
func TLSDial ¶
func TLSDial(ctx context.Context, dial DialWithContextFunc, network, addr string, tlsConfig *tls.Config) (*tls.Conn, error)
TLSDial dials and establishes TLS connection using custom dialer is similar to tls.DialWithDialer
func ToJSON ¶
ToJSON converts a single YAML document into a JSON document or returns an error. If the document appears to be JSON the YAML decoding path is not used (so that error messages are JSON specific). Creds to: k8s.io for the code
func ToTTL ¶
ToTTL converts expiration time to TTL duration relative to current time as provided by clock
func TryReadValueAsFile ¶
TryReadValueAsFile is a utility function to read a value from the disk if it looks like an absolute path, otherwise, treat it as a value. It only support absolute paths to avoid ambiguity in interpretation of the value
func UintSliceSubset ¶
UintSliceSubset returns true if b is a subset of a.
func UpdateAppUsageTemplate ¶
func UpdateAppUsageTemplate(app *kingpin.Application, args []string)
UpdateAppUsageTemplate updates usage template for kingpin applications by pre-parsing the arguments then applying any changes to the usage template if necessary.
func UserMessageFromError ¶ added in v1.0.0
UserMessageFromError returns user-friendly error message from error. The error message will be formatted for output depending on the debug flag
func VerifyCertificateChain ¶
func VerifyCertificateChain(certificateChain []*x509.Certificate) error
VerifyCertificateChain reads in chain of certificates and makes sure the chain from leaf to root is valid. This ensures that clients (web browsers and CLI) won't have problem validating the chain.
func VerifyCertificateExpiry ¶
func VerifyCertificateExpiry(c *x509.Certificate, clock clockwork.Clock) error
VerifyCertificateExpiry checks the certificate's expiration status.
func VersionBeforeAlpha ¶
VersionBeforeAlpha appends "-aa" to the version so that it comes before <version>-alpha. This ban be used to make version checks work during development.
func WriteCloserWithContext ¶
func WriteCloserWithContext(ctx context.Context, closer WriteContextCloser) io.WriteCloser
WriteCloserWithContext converts ContextCloser to io.Closer, whenever new Close method will be called, the ctx will be passed to it
func WriteHostUUID ¶ added in v1.0.0
WriteHostUUID writes host UUID into a file
Types ¶
type Anonymizer ¶
type Anonymizer interface { // Anonymize returns anonymized string from the provided data Anonymize(data []byte) string }
Anonymizer defines an interface for anonymizing data
type BufferSyncPool ¶
BufferSyncPool is a sync pool of bytes.Buffer
func NewBufferSyncPool ¶
func NewBufferSyncPool(size int64) *BufferSyncPool
NewBufferSyncPool returns a new instance of sync pool of bytes.Buffers that creates new buffers with preallocated underlying buffer of size
func (*BufferSyncPool) Get ¶
func (b *BufferSyncPool) Get() *bytes.Buffer
Get returns a new or already allocated buffer
func (*BufferSyncPool) Put ¶
func (b *BufferSyncPool) Put(buf *bytes.Buffer)
Put resets the buffer (does not free the memory) and returns it back to the pool. Users should be careful not to use the buffer (e.g. via Bytes) after it was returned
func (*BufferSyncPool) Size ¶
func (b *BufferSyncPool) Size() int64
Size returns default allocated buffer size
type CaptureNBytesWriter ¶
type CaptureNBytesWriter struct {
// contains filtered or unexported fields
}
CaptureNBytesWriter is an io.Writer thats captures up to first n bytes of the incoming data in memory, and then it ignores the rest of the incoming data.
func NewCaptureNBytesWriter ¶
func NewCaptureNBytesWriter(max int) *CaptureNBytesWriter
NewCaptureNBytesWriter creates a new CaptureNBytesWriter.
func (CaptureNBytesWriter) Bytes ¶
func (w CaptureNBytesWriter) Bytes() []byte
Bytes returns all captured bytes.
type CircularBuffer ¶
CircularBuffer implements an in-memory circular buffer of predefined size
func NewCircularBuffer ¶
func NewCircularBuffer(size int) (*CircularBuffer, error)
NewCircularBuffer returns a new instance of a circular buffer that will hold size elements before it rotates
func (*CircularBuffer) Add ¶
func (t *CircularBuffer) Add(d float64)
Add pushes a new item onto the buffer
func (*CircularBuffer) Data ¶
func (t *CircularBuffer) Data(n int) []float64
Data returns the most recent n elements in the correct order
type CloseBroadcaster ¶ added in v1.0.0
CloseBroadcaster is a helper struct that implements io.Closer and uses channel to broadcast it's closed state once called
func NewCloseBroadcaster ¶ added in v1.0.0
func NewCloseBroadcaster() *CloseBroadcaster
NewCloseBroadcaster returns new instance of close broadcaster
func (*CloseBroadcaster) Close ¶ added in v1.0.0
func (b *CloseBroadcaster) Close() error
Close closes channel (once) to start broadcasting it's closed state
type CloserConn ¶
CloserConn wraps connection and attaches additional closers to it
func NewCloserConn ¶
func NewCloserConn(conn net.Conn, closers ...io.Closer) *CloserConn
NewCloserConn returns new connection wrapper that when closed will also close passed closers
func (*CloserConn) AddCloser ¶
func (c *CloserConn) AddCloser(closer io.Closer)
AddCloser adds any closer in ctx that will be called whenever server closes session channel
func (*CloserConn) Close ¶
func (c *CloserConn) Close() error
Close connection, all closers, and cancel context.
func (*CloserConn) Context ¶
func (c *CloserConn) Context() context.Context
Context returns a context that is canceled once the connection is closed.
type DialWithContextFunc ¶
DialWithContext dials with context
type Fields ¶
type Fields map[string]interface{}
Fields represents a generic string-keyed map.
func (Fields) GetStrings ¶
GetStrings returns a slice-of-strings representation of a field.
type FieldsCondition ¶
FieldsCondition is a boolean function on Fields.
func ToFieldsCondition ¶
func ToFieldsCondition(expr *types.WhereExpr) (FieldsCondition, error)
ToFieldsCondition converts a WhereExpr into a FieldsCondition.
type FnCache ¶
type FnCache struct {
// contains filtered or unexported fields
}
FnCache is a helper for temporarily storing the results of regularly called functions. This helper is used to limit the amount of backend reads that occur while the primary cache is unhealthy. Most resources do not require this treatment, but certain resources (cas, nodes, etc) can be loaded on a per-request basis and can cause significant numbers of backend reads if the cache is unhealthy or taking a while to init.
func NewFnCache ¶
func NewFnCache(cfg FnCacheConfig) (*FnCache, error)
type FnCacheConfig ¶
type FnCacheConfig struct { // TTL is the time to live for cache entries. TTL time.Duration // Clock is the clock used to determine the current time. Clock clockwork.Clock // Context is the context used to cancel the cache. All loadfns // will be provided this context. Context context.Context // ReloadOnErr causes entries to be reloaded immediately if // the currently loaded value is an error. Note that all concurrent // requests registered before load completes still observe the // same error. This option is only really useful for longer TTLs. ReloadOnErr bool // CleanupInterval is the interval at which cleanups occur (defaults to // 16x the supplied TTL). Longer cleanup intervals are appropriate for // caches where keys are unlikely to become orphaned. Shorter cleanup // intervals should be used when keys regularly become orphaned. CleanupInterval time.Duration }
func (*FnCacheConfig) CheckAndSetDefaults ¶
func (c *FnCacheConfig) CheckAndSetDefaults() error
type HMACAnonymizer ¶
type HMACAnonymizer struct {
// contains filtered or unexported fields
}
hmacAnonymizer implements anonymization using HMAC
func NewHMACAnonymizer ¶
func NewHMACAnonymizer(key string) (*HMACAnonymizer, error)
NewHMACAnonymizer returns a new HMAC-based anonymizer
func (*HMACAnonymizer) Anonymize ¶
func (a *HMACAnonymizer) Anonymize(data []byte) string
Anonymize anonymizes the provided data using HMAC
type InMemoryFile ¶
type InMemoryFile struct {
// contains filtered or unexported fields
}
InMemoryFile stores the required properties to emulate a File in memory It contains the File properties like name, size, mode It also contains the File contents It does not support folders
func NewInMemoryFile ¶
func (*InMemoryFile) Content ¶
func (fi *InMemoryFile) Content() []byte
Content returns the file bytes
func (*InMemoryFile) IsDir ¶
func (fi *InMemoryFile) IsDir() bool
IsDir checks whether the file is a directory
func (*InMemoryFile) ModTime ¶
func (fi *InMemoryFile) ModTime() time.Time
ModTime returns the last modification time
func (*InMemoryFile) Size ¶
func (fi *InMemoryFile) Size() int64
Size returns the file size (calculated when writing the file)
func (*InMemoryFile) Sys ¶
func (fi *InMemoryFile) Sys() interface{}
Sys is platform independent InMemoryFile's implementation is no-op
type JSONFormatter ¶
type JSONFormatter struct { log.JSONFormatter ExtraFields []string // contains filtered or unexported fields }
JSONFormatter implements the logrus.Formatter interface and adds extra fields to log entries
func NewTestJSONFormatter ¶
func NewTestJSONFormatter() *JSONFormatter
func (*JSONFormatter) CheckAndSetDefaults ¶
func (j *JSONFormatter) CheckAndSetDefaults() error
CheckAndSetDefaults checks and sets log format configuration
type JumpHost ¶
type JumpHost struct { // Username to login as Username string // Addr is a target addr Addr NetAddr }
JumpHost is a target jump host
func ParseProxyJump ¶
ParseProxyJump parses strings like user@host:port,bob@host:port
type KeyStore ¶
type KeyStore struct {
// contains filtered or unexported fields
}
KeyStore is used to sign and decrypt data using X509 digital signatures.
func ParseKeyStorePEM ¶
ParseKeyStorePEM parses signing key store from PEM encoded key pair
func (*KeyStore) GetKeyPair ¶
func (ks *KeyStore) GetKeyPair() (*rsa.PrivateKey, []byte, error)
type LeveledOutputFunc ¶
type LeveledOutputFunc func(args ...interface{})
LeveledOutputFunc describes a function that emits given arguments at a specific level to an underlying logger
type LoadBalancer ¶
LoadBalancer implements naive round robin TCP load balancer used in tests.
func NewLoadBalancer ¶
func NewLoadBalancer(ctx context.Context, frontend NetAddr, backends ...NetAddr) (*LoadBalancer, error)
NewLoadBalancer returns new load balancer listening on frontend and redirecting requests to backends using round robin algo
func NewRandomLoadBalancer ¶
func NewRandomLoadBalancer(ctx context.Context, frontend NetAddr, backends ...NetAddr) (*LoadBalancer, error)
NewRandomLoadBalancer returns new load balancer listening on frontend and redirecting requests to backends randomly.
func (*LoadBalancer) AddBackend ¶
func (l *LoadBalancer) AddBackend(b NetAddr)
AddBackend adds backend
func (*LoadBalancer) Addr ¶
func (l *LoadBalancer) Addr() net.Addr
Addr returns the frontend listener address. Call this after Listen, otherwise Addr returns nil.
func (*LoadBalancer) Close ¶
func (l *LoadBalancer) Close() error
func (*LoadBalancer) Listen ¶
func (l *LoadBalancer) Listen() error
Listen creates a listener on the frontend addr
func (*LoadBalancer) RemoveBackend ¶
func (l *LoadBalancer) RemoveBackend(b NetAddr) error
RemoveBackend removes backend
func (*LoadBalancer) Serve ¶
func (l *LoadBalancer) Serve() error
Serve starts accepting connections
func (*LoadBalancer) Wait ¶
func (l *LoadBalancer) Wait()
Wait is here to workaround issue https://github.com/golang/go/issues/10527 in tests
type Logger ¶
type Logger interface { logrus.FieldLogger // GetLevel specifies the level at which this logger // value is logging GetLevel() logrus.Level // SetLevel sets the logger's level to the specified value SetLevel(level logrus.Level) }
Logger describes a logger value
func WrapLogger ¶
WrapLogger wraps an existing logger entry and returns an value satisfying the Logger interface
type LoggingPurpose ¶
type LoggingPurpose int
const ( LoggingForDaemon LoggingPurpose = iota LoggingForCLI )
type NetAddr ¶
type NetAddr struct { // Addr is the host:port address, like "localhost:22" Addr string `json:"addr"` // AddrNetwork is the type of a network socket, like "tcp" or "unix" AddrNetwork string `json:"network,omitempty"` // Path is a socket file path, like '/var/path/to/socket' in "unix:///var/path/to/socket" Path string `json:"path,omitempty"` }
NetAddr is network address that includes network, optional path and host port
func AddrsFromStrings ¶
AddrsFromStrings returns strings list converted to address list
func DialAddrFromListenAddr ¶
DialAddrFromListenAddr returns dial address from listen address
func JoinAddrSlices ¶
JoinAddrSlices joins two addr slices and returns a resulting slice
func MustParseAddr ¶ added in v1.0.0
MustParseAddr parses the provided string into NetAddr or panics on an error
func MustParseAddrList ¶
MustParseAddrList parses the provided list of strings into a NetAddr list or panics on error
func ParseAddr ¶
ParseAddr takes strings like "tcp://host:port/path" and returns *NetAddr or an error
func ParseAddrs ¶
ParseAddrs parses the provided slice of strings as a slice of NetAddr's.
func ParseHostPortAddr ¶ added in v1.0.0
ParseHostPortAddr takes strings like "host:port" and returns *NetAddr or an error
If defaultPort == -1 it expects 'hostport' string to have it
func (*NetAddr) FullAddress ¶
FullAddress returns full address including network and address (tcp://0.0.0.0:1243)
func (*NetAddr) IsHostUnspecified ¶
IsHostUnspecified returns true if this address' host is unspecified.
func (*NetAddr) IsLoopback ¶ added in v1.0.0
IsLoopback returns true if this is a loopback address
func (*NetAddr) MarshalYAML ¶ added in v1.0.0
MarshalYAML defines how a network address should be marshaled to a string
func (*NetAddr) Port ¶
Port returns defaultPort if no port is set or is invalid, the real port otherwise
func (*NetAddr) UnmarshalYAML ¶
UnmarshalYAML defines how a string can be unmarshalled into a network address
type OpenFileWithFlagsFunc ¶
OpenFileWithFlagsFunc defines a function used to open files providing options.
type PipeNetConn ¶
type PipeNetConn struct {
// contains filtered or unexported fields
}
PipeNetConn implements net.Conn from a provided io.Reader,io.Writer and io.Closer
func NewPipeNetConn ¶
func NewPipeNetConn(reader io.Reader, writer io.Writer, closer io.Closer, fakelocalAddr net.Addr, fakeRemoteAddr net.Addr) *PipeNetConn
NewPipeNetConn constructs a new PipeNetConn, providing a net.Conn implementation synthesized from the supplied io.Reader, io.Writer & io.Closer.
func (*PipeNetConn) Close ¶
func (nc *PipeNetConn) Close() error
func (*PipeNetConn) LocalAddr ¶
func (nc *PipeNetConn) LocalAddr() net.Addr
func (*PipeNetConn) RemoteAddr ¶
func (nc *PipeNetConn) RemoteAddr() net.Addr
func (*PipeNetConn) SetDeadline ¶
func (nc *PipeNetConn) SetDeadline(t time.Time) error
func (*PipeNetConn) SetReadDeadline ¶
func (nc *PipeNetConn) SetReadDeadline(t time.Time) error
func (*PipeNetConn) SetWriteDeadline ¶
func (nc *PipeNetConn) SetWriteDeadline(t time.Time) error
type PortList ¶ added in v1.0.0
PortList is a list of TCP ports.
func GetFreeTCPPorts ¶ added in v1.0.0
GetFreeTCPPorts returns n ports starting from port 20000.
func (*PortList) Pop ¶ added in v1.0.0
Pop returns a value from the list, it panics if the value is not there
func (*PortList) PopInt ¶
PopInt returns a value from the list, it panics if not enough values were allocated
func (*PortList) PopIntSlice ¶
PopIntSlice returns a slice of values from the list, it panics if not enough ports were allocated
type PredicateError ¶
type PredicateError struct {
Err error
}
func (PredicateError) Error ¶
func (p PredicateError) Error() string
type ReadStatFS ¶
type ReadStatFS interface { fs.ReadFileFS fs.StatFS }
ReadStatFS combines two interfaces: fs.ReadFileFS and fs.StatFS We need both when creating the archive to be able to: - read file contents - `ReadFile` provided by fs.ReadFileFS - set the correct file permissions - `Stat() ... Mode()` provided by fs.StatFS
type RegexpConfig ¶
type RegexpConfig struct { // IgnoreCase specifies whether matching is case-insensitive IgnoreCase bool }
RegexpConfig defines the configuration of the regular expression matcher
type RepeatReader ¶
type RepeatReader struct {
// contains filtered or unexported fields
}
RepeatReader repeats the same byte count times without allocating any data, the single instance of the repeat reader is not goroutine safe
func NewRepeatReader ¶
func NewRepeatReader(repeat byte, count int) *RepeatReader
NewRepeatReader returns a repeat reader
type SlicePool ¶
type SlicePool interface { // Zero zeroes slice Zero(b []byte) // Get returns a new or already allocated slice Get() []byte // Put returns slice back to the pool Put(b []byte) // Size returns a slice size Size() int64 }
SlicePool manages a pool of slices in attempts to manage memory in go more efficiently and avoid frequent allocations
type SliceSyncPool ¶
SliceSyncPool is a sync pool of slices (usually large) of the same size to optimize memory usage, see sync.Pool for more details
func NewSliceSyncPool ¶
func NewSliceSyncPool(sliceSize int64) *SliceSyncPool
NewSliceSyncPool returns a new slice pool, using sync.Pool of pre-allocated or newly allocated slices of the predefined size and capacity
func (*SliceSyncPool) Get ¶
func (s *SliceSyncPool) Get() []byte
Get returns a new or already allocated slice
func (*SliceSyncPool) Put ¶
func (s *SliceSyncPool) Put(b []byte)
Put returns slice back to the pool
type Stater ¶
Stater is extension interface of the net.Conn for implementations that track connection statistics.
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 SyncString ¶
SyncString is a string value that can be concurrently accessed
type SyncWriter ¶
func NewSyncWriter ¶
func NewSyncWriter(w io.Writer) *SyncWriter
type TLSConn ¶
type TLSConn interface { net.Conn // ConnectionState returns basic TLS details about the connection. // More info at: https://pkg.go.dev/crypto/tls#Conn.ConnectionState ConnectionState() tls.ConnectionState // Handshake runs the client or server handshake protocol if it has not yet // been run. // More info at: https://pkg.go.dev/crypto/tls#Conn.Handshake Handshake() error // HandshakeContext runs the client or server handshake protocol if it has // not yet been run. // More info at: https://pkg.go.dev/crypto/tls#Conn.HandshakeContext HandshakeContext(context.Context) error }
TLSConn is a `net.Conn` that implements some of the functions defined by the `tls.Conn` struct. This interface can be used where it could receive a `tls.Conn` wrapped in another connection. For example, in the ALPN Proxy, some TLS Connections can be wrapped with ping protocol.
type TLSCredentials ¶ added in v1.0.0
type TLSCredentials struct { // PublicKey in PEM format PublicKey []byte // PrivateKey in PEM format PrivateKey []byte Cert []byte }
TLSCredentials keeps the typical 3 components of a proper HTTPS configuration
func GenerateSelfSignedCert ¶ added in v1.0.0
func GenerateSelfSignedCert(hostNames []string) (*TLSCredentials, error)
GenerateSelfSignedCert generates a self-signed certificate that is valid for given domain names and ips, returns PEM-encoded bytes with key and cert
type TextFormatter ¶
type TextFormatter struct { // ComponentPadding is a padding to pick when displaying // and formatting component field, defaults to DefaultComponentPadding ComponentPadding int // EnableColors enables colored output EnableColors bool // FormatCaller is a function to return (part) of source file path for output. // Defaults to filePathAndLine() if unspecified FormatCaller func() (caller string) // ExtraFields represent the extra fields that will be added to the log message ExtraFields []string // contains filtered or unexported fields }
func NewDefaultTextFormatter ¶
func NewDefaultTextFormatter(enableColors bool) *TextFormatter
func (*TextFormatter) CheckAndSetDefaults ¶
func (tf *TextFormatter) CheckAndSetDefaults() error
CheckAndSetDefaults checks and sets log format configuration
type TimedCounter ¶
type TimedCounter struct {
// contains filtered or unexported fields
}
TimedCounter is essentially a lightweight rate calculator. It counts events that happen over a period of time, e.g. have there been more than 4 errors in the last 30 seconds. Automatically expires old events so they are not included in the count. Not safe for concurrent use.
func NewTimedCounter ¶
func NewTimedCounter(clock clockwork.Clock, timeout time.Duration) *TimedCounter
NewTimedCounter creates a new timed counter with the specified timeout
func (*TimedCounter) Count ¶
func (c *TimedCounter) Count() int
Count fetches the number of recorded events currently in the measurement time window.
func (*TimedCounter) Increment ¶
func (c *TimedCounter) Increment() int
Increment adds a new item into the counter, returning the current count.
type TimeoutConn ¶ added in v1.2.6
type TimeoutConn struct { net.Conn TimeoutDuration time.Duration // Name is only useful for debugging/logging, it's a convenient // way to tag every idle connection OwnerName string }
TimeoutConn wraps an existing net.Conn and adds read/write timeouts for it, allowing to implement "disconnect after XX of idle time" policy
Usage example: tc := utils.ObeyIdleTimeout(conn, time.Second * 30, "ssh connection") io.Copy(tc, xxx)
type Tracer ¶
type Tracer struct { // Started records starting time of the call Started time.Time // Description is arbitrary description Description string }
Tracer helps to trace execution of functions
type TrackingConn ¶
type TrackingConn struct { // net.Conn is the underlying net.Conn. net.Conn // contains filtered or unexported fields }
TrackingConn is a net.Conn that keeps track of how much data was transmitted (TX) and received (RX) over the net.Conn. A maximum of about 18446 petabytes can be kept track of for TX and RX before it rolls over. See https://golang.org/ref/spec#Numeric_types for more details.
func NewTrackingConn ¶
func NewTrackingConn(conn net.Conn) *TrackingConn
NewTrackingConn returns a net.Conn that can keep track of how much data was transmitted over it.
func (*TrackingConn) Stat ¶
func (s *TrackingConn) Stat() (uint64, uint64)
Stat returns the transmitted (TX) and received (RX) bytes over the net.Conn.
type TrackingReader ¶
type TrackingReader struct {
// contains filtered or unexported fields
}
TrackingReader is an io.Reader that counts the total number of bytes read. It's thread-safe if the underlying io.Reader is thread-safe.
func NewTrackingReader ¶
func NewTrackingReader(r io.Reader) *TrackingReader
NewTrackingReader creates a TrackingReader around r.
func (*TrackingReader) Count ¶
func (r *TrackingReader) Count() uint64
Count returns the total number of bytes read so far.
type TrackingWriter ¶
type TrackingWriter struct {
// contains filtered or unexported fields
}
TrackingWriter is an io.Writer that counts the total number of bytes written. It's thread-safe if the underlying io.Writer is thread-safe.
func NewTrackingWriter ¶
func NewTrackingWriter(w io.Writer) *TrackingWriter
NewTrackingWriter creates a TrackingWriter around w.
func (*TrackingWriter) Count ¶
func (w *TrackingWriter) Count() uint64
Count returns the total number of bytes written so far.
type UID ¶
type UID interface { // New returns a new UUID4. New() string }
UID provides an interface for generating unique identifiers.
type WebLinks ¶
type WebLinks struct { // NextPage is the next page of pagination links. NextPage string // PrevPage is the previous page of pagination links. PrevPage string // FirstPage is the first page of pagination links. FirstPage string // LastPage is the last page of pagination links. LastPage string }
WebLinks holds the pagination links parsed out of a request header conforming to RFC 8288.
func ParseWebLinks ¶
ParseWebLinks partially implements RFC 8288 parsing, enough to support GitHub pagination links. See https://tools.ietf.org/html/rfc8288 for more details on Web Linking and https://github.com/google/go-github for the API client that this function was original extracted from.
Link headers typically look like:
Link: <https://api.github.com/user/teams?page=2>; rel="next", <https://api.github.com/user/teams?page=34>; rel="last"
Source Files ¶
- addr.go
- anonymizer.go
- archive.go
- broadcaster.go
- buf.go
- certs.go
- checker.go
- circular_buffer.go
- cli.go
- cmp.go
- config.go
- conn.go
- copy.go
- disk.go
- distro.go
- ec2.go
- environment.go
- equals.go
- errors.go
- fields.go
- fncache.go
- formatter.go
- fs.go
- fs_unix.go
- grpc.go
- inmemory_fs.go
- jsontools.go
- kernel.go
- keys.go
- linking.go
- listener.go
- loadbalancer.go
- net.go
- node.go
- otp.go
- pipenetconn.go
- proxyconn.go
- proxyjump.go
- rand.go
- repeat.go
- replace.go
- retry.go
- round.go
- slice.go
- spki.go
- sync_writer.go
- syslog.go
- time.go
- timed_counter.go
- timeout.go
- tls.go
- tlsdial.go
- uid.go
- unpack.go
- utils.go
- ver.go
- writer.go
Directories ¶
Path | Synopsis |
---|---|
TODO(awly): combine Expression and Matcher.
|
TODO(awly): combine Expression and Matcher. |
Package prompt implements CLI prompts to the user.
|
Package prompt implements CLI prompts to the user. |
package socks implements a SOCKS5 handshake.
|
package socks implements a SOCKS5 handshake. |
Package workpool provies the `Pool` type which functions as a means of managing the number of concurrent workers, grouped by key.
|
Package workpool provies the `Pool` type which functions as a means of managing the number of concurrent workers, grouped by key. |