util

package
v0.0.0-...-d0b943e Latest Latest
Warning

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

Go to latest
Published: Apr 5, 2016 License: Apache-2.0 Imports: 28 Imported by: 0

Documentation

Overview

Package util is a generated protocol buffer package.

It is generated from these files:

cockroach/util/build.proto
cockroach/util/unresolved_addr.proto

It has these top-level messages:

BuildInfo
UnresolvedAddr

Index

Constants

View Source
const (
	// AcceptHeader is the canonical header name for accept.
	AcceptHeader = "Accept"
	// AcceptEncodingHeader is the canonical header name for accept encoding.
	AcceptEncodingHeader = "Accept-Encoding"
	// ContentEncodingHeader is the canonical header name for content type.
	ContentEncodingHeader = "Content-Encoding"
	// ContentTypeHeader is the canonical header name for content type.
	ContentTypeHeader = "Content-Type"
	// JSONContentType is the JSON content type.
	JSONContentType = "application/json"
	// AltJSONContentType is the alternate JSON content type.
	AltJSONContentType = "application/x-json"
	// ProtoContentType is the protobuf content type.
	ProtoContentType = "application/x-protobuf"
	// AltProtoContentType is the alternate protobuf content type.
	AltProtoContentType = "application/x-google-protobuf"
	// YAMLContentType is the YAML content type.
	YAMLContentType = "text/yaml"
	// AltYAMLContentType is the alternate YAML content type.
	AltYAMLContentType = "application/x-yaml"
	// PlaintextContentType is the plaintext content type.
	PlaintextContentType = "text/plain"
	// SnappyEncoding is the snappy encoding.
	SnappyEncoding = "snappy"
	// GzipEncoding is the gzip encoding.
	GzipEncoding = "gzip"
)

Variables

View Source
var (
	ErrInvalidLengthBuild = fmt.Errorf("proto: negative length found during unmarshaling")
	ErrIntOverflowBuild   = fmt.Errorf("proto: integer overflow")
)
View Source
var (
	ErrInvalidLengthUnresolvedAddr = fmt.Errorf("proto: negative length found during unmarshaling")
	ErrIntOverflowUnresolvedAddr   = fmt.Errorf("proto: integer overflow")
)

AllEncodings includes all supported encodings.

View Source
var PanicTester = panicTesterImpl{}

PanicTester is a Tester which panics.

View Source
var TestAddr = NewUnresolvedAddr("tcp", "127.0.0.1:0")

TestAddr is an address to use for test servers. Listening on port 0 causes the kernel to allocate an unused port.

Functions

func CleanupDir

func CleanupDir(dir string)

CleanupDir removes the passed-in directory and all contents. Errors are ignored.

func CloneProto

func CloneProto(pb proto.Message) proto.Message

CloneProto uses proto.Clone to return a deep copy of pb. It panics if pb recursively contains any instances of types which are known to be unsupported by proto.Clone.

This function and its associated lint (see `make check`) exist to ensure we do not attempt to proto.Clone types which are not supported by proto.Clone. This hackery is necessary because proto.Clone gives no direct indication that it has incompletely cloned a type; it merely logs to standard output (see https://github.com/golang/protobuf/blob/89238a3/proto/clone.go#L204).

The concrete case against which this is currently guarding may be resolved upstream, see https://github.com/gogo/protobuf/issues/147.

func CreateRestrictedFile

func CreateRestrictedFile(t Tester, contents []byte, tempdir, name string) string

CreateRestrictedFile creates a file on disk which contains the supplied byte string as its content. The resulting file will have restrictive permissions; specifically, u=rw (0600). Returns the path of the created file along with a function that will delete the created file.

This is needed for some Go libraries (e.g. postgres SQL driver) which will refuse to open certificate files that have overly permissive permissions.

func CreateTempDir

func CreateTempDir(t Tester, prefix string) string

CreateTempDir creates a temporary directory and returns its path. You should usually call defer CleanupDir(dir) right after.

func EqualPtrFields

func EqualPtrFields(src, dst reflect.Value, prefix string) []string

EqualPtrFields uses reflection to check two "mirror" structures for matching pointer fields that point to the same object. Used to verify cloning/deep copy functions.

func Errorf

func Errorf(format string, a ...interface{}) error

Errorf is a passthrough to fmt.Errorf, with an additional prefix containing the filename and line number.

func ErrorfSkipFrames

func ErrorfSkipFrames(skip int, format string, a ...interface{}) error

ErrorfSkipFrames allows the skip count for stack frames to be specified. This is useful when generating errors via helper methods. Skip should be specified as the number of additional stack frames between the location at which the error is caused and the location at which the error is generated.

func FatalIfUnexpected

func FatalIfUnexpected(err error)

FatalIfUnexpected calls Log.Fatal(err) unless err is nil, cmux.ErrListenerClosed, or the net package's errClosed.

func GetContentType

func GetContentType(request *http.Request) string

GetContentType pulls out the content type from a request header it ignores every value after the first semicolon

func GetJSON

func GetJSON(httpClient *http.Client, scheme, hostport, path string, v interface{}) error

GetJSON uses the supplied client to retrieve the URL specified by the parameters and unmarshals the result into the supplied interface.

TODO(cdo): Refactor the *JSON methods to handle more encodings.

func IsClosedConnection

func IsClosedConnection(err error) bool

IsClosedConnection returns true if err is cmux.ErrListenerClosed, grpc.ErrServerStopped, io.EOF, or the net package's errClosed.

func ListenAndServeGRPC

func ListenAndServeGRPC(stopper *stop.Stopper, server *grpc.Server,
	addr net.Addr) (net.Listener, error)

ListenAndServeGRPC creates a listener and serves the specified grpc Server on it, closing the listener when signalled by the stopper.

func MarshalResponse

func MarshalResponse(r *http.Request, value interface{}, allowed []EncodingType) (
	body []byte, contentType string, err error)

MarshalResponse examines the request Accept header to determine the client's preferred response encoding. Supported content types include JSON, protobuf, and YAML. If the Accept header is not available, the Content-Type header specifying the request encoding is used. The value parameter is marshalled using the response encoding and the resulting body and content type are returned. If the encoding could not be determined by either header, the response is marshalled using JSON. Falls back to JSON when the protobuf format cannot be used for the given value.

func MoveTopKToFront

func MoveTopKToFront(data sort.Interface, k int)

MoveTopKToFront moves the top K elements to the front. It makes O(n) calls to data.Less and data.Swap (with very high probability). It uses Hoare's selection algorithm (aka quickselect).

func NoZeroField

func NoZeroField(v interface{}) error

NoZeroField returns nil if none of the fields of the struct underlying the interface are equal to the zero value, and an error otherwise. It will panic if the struct has unexported fields and for any non-struct.

func PostJSON

func PostJSON(httpClient *http.Client, scheme, hostport, path, body string, v interface{}) error

PostJSON uses the supplied client to perform a POST to the URL specified by the parameters and unmarshals the result into the supplied interface. This function assumes that the body is also JSON.

func RetryForDuration

func RetryForDuration(duration time.Duration, fn func() error) error

RetryForDuration will retry the given function until it either returns without error, or the given duration has elapsed. The function is invoked immediately at first and then successively with an exponential backoff starting at 1ns and ending at the specified duration.

func ServeHandler

func ServeHandler(
	stopper *stop.Stopper, handler http.Handler, ln net.Listener, tlsConfig *tls.Config,
) func(net.Listener, func(net.Conn)) error

ServeHandler serves the handler on the listener and returns a function that serves an additional listener using a function that takes a connection. The returned function can be called multiple times.

func SucceedsSoon

func SucceedsSoon(t Tester, fn func() error)

SucceedsSoon fails the test (with t.Fatal) unless the supplied function runs without error within a preset maximum duration. The function is invoked immediately at first and then successively with an exponential backoff starting at 1ns and ending at the maximum duration (currently 15s).

func SucceedsSoonDepth

func SucceedsSoonDepth(depth int, t Tester, fn func() error)

SucceedsSoonDepth is like SucceedsSoon() but with an additional stack depth offset.

func TruncateDuration

func TruncateDuration(d time.Duration, r time.Duration) time.Duration

TruncateDuration returns a new duration obtained from the first argument by discarding the portions at finer resolution than that given by the second argument. Example: TruncateDuration(time.Second+1, time.Second) == time.Second.

func UnmarshalRequest

func UnmarshalRequest(r *http.Request, body []byte, value interface{}, allowed []EncodingType) error

UnmarshalRequest examines the request Content-Type header in order to determine the encoding of the supplied body. Supported content types include:

JSON     - {"application/json", "application/x-json"}
Protobuf - {"application/x-protobuf", "application/x-google-protobuf"}
YAML     - {"text/yaml", "application/x-yaml"}

The body is unmarshalled into the supplied value parameter. An error is returned on an unmarshalling error or on an unsupported content type.

Types

type BuildInfo

type BuildInfo struct {
	GoVersion   string `protobuf:"bytes,1,opt,name=go_version,json=goVersion" json:"goVersion"`
	Tag         string `protobuf:"bytes,2,opt,name=tag" json:"tag"`
	Time        string `protobuf:"bytes,3,opt,name=time" json:"time"`
	Deps        string `protobuf:"bytes,4,opt,name=deps" json:"dependencies"`
	CgoCompiler string `protobuf:"bytes,5,opt,name=cgo_compiler,json=cgoCompiler" json:"cgoCompiler"`
	Platform    string `protobuf:"bytes,6,opt,name=platform" json:"platform"`
}

BuildInfo describes build information for this CockroachDB binary.

func GetBuildInfo

func GetBuildInfo() BuildInfo

GetBuildInfo ...

func (*BuildInfo) Descriptor

func (*BuildInfo) Descriptor() ([]byte, []int)

func (*BuildInfo) Marshal

func (m *BuildInfo) Marshal() (data []byte, err error)

func (*BuildInfo) MarshalTo

func (m *BuildInfo) MarshalTo(data []byte) (int, error)

func (*BuildInfo) ProtoMessage

func (*BuildInfo) ProtoMessage()

func (*BuildInfo) Reset

func (m *BuildInfo) Reset()

func (BuildInfo) Short

func (b BuildInfo) Short() string

Short returns a pretty printed build and version summary.

func (*BuildInfo) Size

func (m *BuildInfo) Size() (n int)

func (*BuildInfo) String

func (m *BuildInfo) String() string

func (*BuildInfo) Unmarshal

func (m *BuildInfo) Unmarshal(data []byte) error

type EncodingType

type EncodingType int

EncodingType is an enum describing available encodings.

const (
	// JSONEncoding includes application/json and application/x-json.
	JSONEncoding EncodingType = iota
	// ProtoEncoding includes application/x-protobuf and application/x-google-protobuf.
	ProtoEncoding
	// YAMLEncoding includes text/yaml and application/x-yaml.
	YAMLEncoding
)

type Tester

type Tester interface {
	Error(args ...interface{})
	Errorf(format string, args ...interface{})
	Failed() bool
	Fatal(args ...interface{})
	Fatalf(format string, args ...interface{})
}

Tester is a proxy for e.g. testing.T which does not introduce a dependency on "testing".

type Timer

type Timer struct {
	*time.Timer
	Read bool
}

The Timer type represents a single event. When the Timer expires, the current time will be sent on Timer.C.

This timer implementation is an abstraction around the standard library's time.Timer that provides a temporary workaround for the issue described in https://github.com/golang/go/issues/14038. As such, this timer should only be used when Reset is planned to be called continually in a loop. For this Reset pattern to work, Timer.Read must be set to true whenever a timestamp is read from the Timer.C channel. If Timer.Read is not set to true when the channel is read from, the next call to Timer.Reset will deadlock. This pattern looks something like:

var timer util.Timer
defer timer.Stop()
for {
    timer.Reset(wait)
    switch {
    case <-timer.C:
        timer.Read = true
        ...
    }
}

Note that unlike the standard library's Timer type, this Timer will not begin counting down until Reset is called for the first time, as there is no constructor function.

func (*Timer) Reset

func (t *Timer) Reset(d time.Duration)

Reset changes the timer to expire after duration d and returns the new value of the timer. This method includes the fix proposed in https://github.com/golang/go/issues/11513#issuecomment-157062583, but requires users of Timer to set Timer.Read to true whenever they successfully read from the Timer's channel. Reset operates on and returns a value so that Timer can be stack allocated.

func (*Timer) Stop

func (t *Timer) Stop() bool

Stop prevents the Timer from firing. It returns true if the call stops the timer, false if the timer has already expired, been stopped previously, or had never been initialized with a call to Timer.Reset. Stop does not close the channel, to prevent a read from succeeding incorrectly.

type UnresolvedAddr

type UnresolvedAddr struct {
	NetworkField string `protobuf:"bytes,1,opt,name=network_field,json=networkField" json:"network"`
	AddressField string `protobuf:"bytes,2,opt,name=address_field,json=addressField" json:"address"`
}

/ UnresolvedAddr is an unresolved version of net.Addr.

func MakeUnresolvedAddr

func MakeUnresolvedAddr(network, addr string) UnresolvedAddr

MakeUnresolvedAddr populates an UnresolvedAddr from a network and raw address string.

func NewUnresolvedAddr

func NewUnresolvedAddr(network, addr string) *UnresolvedAddr

NewUnresolvedAddr creates a new UnresolvedAddr from a network and raw address string.

func (*UnresolvedAddr) Descriptor

func (*UnresolvedAddr) Descriptor() ([]byte, []int)

func (*UnresolvedAddr) Marshal

func (m *UnresolvedAddr) Marshal() (data []byte, err error)

func (*UnresolvedAddr) MarshalTo

func (m *UnresolvedAddr) MarshalTo(data []byte) (int, error)

func (*UnresolvedAddr) Network

func (a *UnresolvedAddr) Network() string

Network returns the address's network name.

func (*UnresolvedAddr) ProtoMessage

func (*UnresolvedAddr) ProtoMessage()

func (*UnresolvedAddr) Reset

func (m *UnresolvedAddr) Reset()

func (UnresolvedAddr) Resolve

func (a UnresolvedAddr) Resolve() (net.Addr, error)

Resolve attempts to resolve a into a net.Addr.

func (*UnresolvedAddr) Size

func (m *UnresolvedAddr) Size() (n int)

func (*UnresolvedAddr) String

func (a *UnresolvedAddr) String() string

String returns the address's string form.

func (*UnresolvedAddr) Unmarshal

func (m *UnresolvedAddr) Unmarshal(data []byte) error

Directories

Path Synopsis
Package hlc implements the Hybrid Logical Clock outlined in "Logical Physical Clocks and Consistent Snapshots in Globally Distributed Databases", available online at http://www.cse.buffalo.edu/tech-reports/2014-04.pdf.
Package hlc implements the Hybrid Logical Clock outlined in "Logical Physical Clocks and Consistent Snapshots in Globally Distributed Databases", available online at http://www.cse.buffalo.edu/tech-reports/2014-04.pdf.
Package interval implements an interval tree based on an augmented Left-Leaning Red Black tree.
Package interval implements an interval tree based on an augmented Left-Leaning Red Black tree.
Package leaktest provides tools to detect leaked goroutines in tests.
Package leaktest provides tools to detect leaked goroutines in tests.
log
Package log implements logging analogous to the Google-internal C++ INFO/ERROR/V setup.
Package log implements logging analogous to the Google-internal C++ INFO/ERROR/V setup.
Package metric provides server metrics (a.k.a.
Package metric provides server metrics (a.k.a.
Package tracing is a generated protocol buffer package.
Package tracing is a generated protocol buffer package.

Jump to

Keyboard shortcuts

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