runtimevar

package
v0.11.0 Latest Latest
Warning

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

Go to latest
Published: Feb 28, 2019 License: Apache-2.0 Imports: 12 Imported by: 81

Documentation

Overview

Package runtimevar provides an easy and portable way to watch runtime configuration variables.

It provides a blocking method that returns a Snapshot of the variable value whenever a change is detected.

Subpackages contain distinct implementations of runtimevar for various providers, including Cloud and on-prem solutions. For example, "etcdvar" supports variables stored in etcd. Your application should import one of these provider-specific subpackages and use its exported function(s) to create a *Variable; do not use the New function in this package. For example:

var v *runtimevar.Variable
var err error
v, err = etcdvar.New("my variable", etcdClient, runtimevar.JSONDecode, nil)
...

Then, write your application code using the *Variable type. You can easily reconfigure your initialization code to choose a different provider. You can develop your application locally using filevar or constantvar, and deploy it to multiple Cloud providers. You may find http://github.com/google/wire useful for managing your initialization code.

OpenCensus Integration

OpenCensus supports tracing and metric collection for multiple languages and backend providers. See https://opencensus.io.

This API collects an OpenCensus metric "gocloud.dev/runtimevar/value_changes", a count of the number of times all variables have changed values, by provider.

To enable metric collection in your application, see "Exporting stats" at https://opencensus.io/quickstart/go/metrics.

Example (JsonVariable)
package main

import (
	"context"
	"fmt"
	"log"

	"gocloud.dev/runtimevar"
	"gocloud.dev/runtimevar/constantvar"
)

func main() {
	// DBConfig is the sample config struct we're going to parse our JSON into.
	type DBConfig struct {
		Host     string
		Port     int
		Username string
	}

	// Here's our sample JSON config.
	const jsonConfig = `{"Host": "gocloud.dev", "Port": 8080, "Username": "testuser"}`

	// We need a Decoder that decodes raw bytes into our config.
	decoder := runtimevar.NewDecoder(DBConfig{}, runtimevar.JSONDecode)

	// Next, a construct a *Variable using a constructor from one of the
	// runtimevar subpackages. This example uses constantvar.
	v := constantvar.NewBytes([]byte(jsonConfig), decoder)
	defer v.Close()

	// Call Watch to retrieve the value.
	snapshot, err := v.Watch(context.Background())
	if err != nil {
		log.Fatalf("Error in retrieving variable: %v", err)
	}
	// snapshot.Value will be of type DBConfig.
	fmt.Printf("Config: %+v\n", snapshot.Value.(DBConfig))

}
Output:

Config: {Host:gocloud.dev Port:8080 Username:testuser}
Example (StringVariable)
package main

import (
	"context"
	"fmt"
	"log"

	"gocloud.dev/runtimevar"
	"gocloud.dev/runtimevar/constantvar"
)

func main() {
	// Construct a *Variable using a constructor from one of the
	// runtimevar subpackages. This example uses constantvar.
	// The variable value is of type string, so we use StringDecoder.
	v := constantvar.NewBytes([]byte("hello world"), runtimevar.StringDecoder)
	defer v.Close()

	// Call Watch to retrieve the value.
	snapshot, err := v.Watch(context.Background())
	if err != nil {
		log.Fatalf("Error in retrieving variable: %v", err)
	}
	// snapshot.Value will be of type string.
	fmt.Printf("%q\n", snapshot.Value.(string))

}
Output:

"hello world"

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// StringDecoder decodes into strings.
	StringDecoder = NewDecoder("", stringDecode)

	// BytesDecoder copies the slice of bytes.
	BytesDecoder = NewDecoder([]byte{}, bytesDecode)

	// JSONDecode can be passed to NewDecoder when decoding JSON (https://golang.org/pkg/encoding/json/).
	JSONDecode = json.Unmarshal
)
View Source
var New = newVar

New is intended for use by provider implementations.

View Source
var (
	OpenCensusViews = []*view.View{
		{
			Name:        pkgName + "/value_changes",
			Measure:     changeMeasure,
			Description: "Count of variable value changes by provider.",
			TagKeys:     []tag.Key{oc.ProviderKey},
			Aggregation: view.Count(),
		},
	}
)

Functions

func GobDecode

func GobDecode(data []byte, obj interface{}) error

GobDecode can be passed to NewDecoder when decoding gobs (https://golang.org/pkg/encoding/gob/).

Types

type Decode

type Decode func([]byte, interface{}) error

Decode is a function type for unmarshaling/decoding a slice of bytes into an arbitrary type. Decode functions are used when creating a Decoder via NewDecoder. This package provides common Decode functions including GobDecode and JSONDecode.

type Decoder

type Decoder struct {
	// contains filtered or unexported fields
}

Decoder decodes a slice of bytes into a particular Go object.

This package provides some common Decoders that you can use directly, including StringDecoder and BytesDecoder. You can also NewDecoder to construct other Decoders.

func NewDecoder

func NewDecoder(obj interface{}, fn Decode) *Decoder

NewDecoder returns a Decoder that uses fn to decode a slice of bytes into an object of type obj.

This package provides some common Decode functions, including JSONDecode and GobDecode, which can be passed to this function to create Decoders for JSON and gob values.

func (*Decoder) Decode

func (d *Decoder) Decode(b []byte) (interface{}, error)

Decode decodes b into a new instance of the target type.

type Snapshot

type Snapshot struct {
	// Value contains the value of the variable.
	// The type for Value depends on the provider; for most providers, it depends
	// on the decoder used when creating Variable.
	Value interface{}

	// UpdateTime is the time when the last change was detected.
	UpdateTime time.Time
	// contains filtered or unexported fields
}

Snapshot contains a snapshot of a variable's value and metadata about it. It is intended to be read-only for users.

func (*Snapshot) As added in v0.9.0

func (s *Snapshot) As(i interface{}) bool

As converts i to provider-specific types.

This function (and the other As functions in this package) are inherently provider-specific, and using them will make that part of your application non-portable, so use with care.

See the documentation for the subpackage you used to instantiate Variable to see which type(s) are supported.

Usage:

1. Declare a variable of the provider-specific type you want to access.

2. Pass a pointer to it to As.

3. If the type is supported, As will return true and copy the provider-specific type into your variable. Otherwise, it will return false.

See https://github.com/google/go-cloud/blob/master/internal/docs/design.md#as for more background.

type Variable

type Variable struct {
	// contains filtered or unexported fields
}

Variable provides an easy and portable way to watch runtime configuration variables. To create a Variable, use constructors found in provider-specific subpackages.

func (*Variable) Close

func (c *Variable) Close() error

Close closes the Variable; don't call Watch after this.

func (*Variable) ErrorAs added in v0.10.0

func (c *Variable) ErrorAs(err error, i interface{}) bool

ErrorAs converts i to provider-specific types. ErrorAs panics if i is nil or not a pointer. ErrorAs returns false if err == nil. See Snapshot.As for more details.

func (*Variable) Watch

func (c *Variable) Watch(ctx context.Context) (_ Snapshot, err error)

Watch returns a Snapshot of the current value of the variable.

The first call to Watch will block while reading the variable from the provider, and will return the resulting Snapshot or error. If an error is returned, the returned Snapshot is a zero value and should be ignored.

Subsequent calls will block until the variable's value changes or a different error occurs.

Watch should not be called on the same variable from multiple goroutines concurrently. The typical use case is to call it in a single goroutine in a loop.

If the variable does not exist, Watch returns an error for which gcerrors.Code will return gcerrors.NotFound.

Directories

Path Synopsis
Package blobvar provides a runtimevar implementation with variables read from a blob.Bucket.
Package blobvar provides a runtimevar implementation with variables read from a blob.Bucket.
Package constantvar provides a runtimevar implementation with Variables that never change.
Package constantvar provides a runtimevar implementation with Variables that never change.
Package driver provides the interface for providers of runtimevar.
Package driver provides the interface for providers of runtimevar.
Package drivertest provides a conformance test for implementations of runtimevar.
Package drivertest provides a conformance test for implementations of runtimevar.
Package etcdvar provides a runtimevar implementation with variables backed by etcd.
Package etcdvar provides a runtimevar implementation with variables backed by etcd.
Package filevar provides a runtimevar implementation with variables backed by the filesystem.
Package filevar provides a runtimevar implementation with variables backed by the filesystem.
_demo
This binary demonstrates watching over a configuration file using the runtimevar package with the filevar package as the driver implementation.
This binary demonstrates watching over a configuration file using the runtimevar package with the filevar package as the driver implementation.
Package paramstore provides a runtimevar implementation with variables read from AWS Systems Manager Parameter Store (https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-paramstore.html) Use NewVariable to construct a *runtimevar.Variable.
Package paramstore provides a runtimevar implementation with variables read from AWS Systems Manager Parameter Store (https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-paramstore.html) Use NewVariable to construct a *runtimevar.Variable.
Package runtimeconfigurator provides a runtimevar implementation with variables read from GCP Cloud Runtime Configurator (https://cloud.google.com/deployment-manager/runtime-configurator).
Package runtimeconfigurator provides a runtimevar implementation with variables read from GCP Cloud Runtime Configurator (https://cloud.google.com/deployment-manager/runtime-configurator).

Jump to

Keyboard shortcuts

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