consul

package module
v0.0.0-...-856af4c Latest Latest
Warning

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

Go to latest
Published: Apr 10, 2016 License: MIT Imports: 9 Imported by: 0

README

consul Build Status GoDoc Coverage Status Go Report Card API

Consul plugin for simple dynamic service discovery and optional traffic balancing in vinxi proxies.

Supports multiple Consul servers, non-blocking multi-thread service discovery, retry policy on discovery error and transparent fallback to the next Consul server available.

Installation

go get -u gopkg.in/vinxi/consul.v0

API

See godoc reference.

Example

Server discovery with default roundrobin balancer
package main

import (
  "fmt"
  "gopkg.in/vinxi/consul.v0"
  "gopkg.in/vinxi/forward.v0"
  "gopkg.in/vinxi/vinxi.v0"
)

const port = 3100

func main() {
  // Create the Consul client
  cc := consul.New(consul.NewConfig("web", "http://demo.consul.io"))

  // Create a new vinxi proxy
  vs := vinxi.NewServer(vinxi.ServerOptions{Port: port})
  vs.Use(cc)

  fw, _ := forward.New(forward.PassHostHeader(true))
  vs.UseFinalHandler(fw)

  fmt.Printf("Server listening on port: %d\n", port)
  err := vs.Listen()
  if err != nil {
    fmt.Errorf("Error: %s\n", err)
  }
}

License

MIT

Documentation

Overview

Package consul implements a high-level wrapper Consul HTTP client for easy service discovery. Provides additional features, such as time based lookups and retry policy.

Index

Constants

View Source
const (
	// RetryTimes defines the default max amount of times to retry a request.
	RetryTimes = 5

	// RetryWait defines the default amount of time to wait before each retry attempt.
	RetryWait = 100 * time.Millisecond
)
View Source
const Version = "0.1.0"

Version defines the current package semantic version.

Variables

View Source
var (
	// DefaultBalancer stores the roundrobin balancer used by default.
	DefaultBalancer = balancer.DefaultBalancer

	// ConsulMaxWaitTime defines the maximum Consul wait time before treat it as timeout error.
	ConsulMaxWaitTime = 5 * time.Second

	// ConsulWaitTimeInterval defines the wait interval for node servers become available.
	ConsulWaitTimeInterval = 100 * time.Millisecond
)
View Source
var (
	// ConstantBackoff provides a built-in retry strategy based on constant back off.
	ConstantBackoff = retry.New(retry.ConstantBackoff(RetryTimes, RetryWait), nil)

	// ExponentialBackoff provides a built-int retry strategy based on exponential back off.
	ExponentialBackoff = retry.New(retry.ExponentialBackoff(RetryTimes, RetryWait), nil)

	// DefaultRetrier stores the default retry strategy used by the plugin.
	// By default will use a constant retry strategy with a maximum of 3 retry attempts.
	DefaultRetrier = ConstantBackoff
)
View Source
var (
	// DefaultRefreshTime defines the default refresh inverval to be used.
	DefaultRefreshTime = 5 * time.Minute
)
View Source
var (
	// ErrDiscoveryTimeout is used in case that discovery timeout exceeded.
	ErrDiscoveryTimeout = errors.New("consul: cannot discover servers due to timeout")
)

Functions

func MapConsulEntries

func MapConsulEntries(entries []*consul.ServiceEntry) []string

MapConsulEntries maps the Consul specific service entry struct into a string hostname + port scheme.

Types

type Client

type Client interface {
	Health(service string, tag string, queryOpts *consul.QueryOptions) ([]*consul.ServiceEntry, *consul.QueryMeta, error)
}

Client is a wrapper around the Consul API.

func NewClient

func NewClient(c *consul.Config) Client

NewClient returns an implementation of the Client interface expecting a fully setup Consul Client.

type Config

type Config struct {
	// Service stores the Consul service name used for discovery.
	Service string

	// Tag stores the optional Consul service tag.
	Tag string

	// QueryOptions stores the Consul client addition query options.
	QueryOptions *consul.QueryOptions

	// Instances stores the consul.Config objects per Consul server.
	Instances []*consul.Config

	// Datacenter to use. If not provided, the default agent datacenter is used.
	Datacenter string

	// Token is used to provide a per-request ACL token
	// which overrides the agent's default token.
	Token string

	// HTTPClient is the client to use. Default will be
	// used if not provided.
	HTTPClient *http.Client

	// HTTPAuth is the auth info to use for http access.
	HTTPAuth *consul.HttpBasicAuth

	// WaitTime limits how long a Watch will block. If not provided,
	// the agent default values will be used.
	WaitTime time.Duration

	// RefreshTime defines the Consul server refresh how long a Watch will block. If not provided,
	// the agent default values will be used.
	RefreshTime time.Duration

	// Mapper stores the service entry specific map function.
	// Useful to validate, normalize or filter service instances.
	// Defaults to MapConsulEntries.
	Mapper func([]*consul.ServiceEntry) []string
}

Config is used to configure Consul clients and servers.

func NewConfig

func NewConfig(service string, servers ...string) *Config

NewConfig creates a new Consul client config preconfigured for the given Consul service and a list of Consul servers.

func (*Config) SetServer

func (c *Config) SetServer(server ...string) error

SetServer sets one or multiple Consul servers, creating the default config

type Consul

type Consul struct {
	// RWMutex provides a struct mutex to prevent data races.
	sync.RWMutex

	// Config stores the Consul client vinxi config options used for discovery.
	Config *Config

	// Retrier stores the retry strategy to be used if Consul discovery process fails.
	Retrier Retrier

	// Balancer stores the balancer to be used to distribute traffic
	// load across multiple servers provided by Consul.
	Balancer balancer.Balancer
	// contains filtered or unexported fields
}

Consul is a wrapper around the Consul API for convenience with additional capabilities. Service discoverability will be performed in background.

func New

func New(config *Config) *Consul

New creates a new Consul provider middleware, implementing a Consul client that will ask to Consul servers.

func (*Consul) GetNodes

func (c *Consul) GetNodes() ([]string, error)

GetNodes returns a list of server nodes hostnames for the configured service.

func (*Consul) HandleHTTP

func (c *Consul) HandleHTTP(w http.ResponseWriter, r *http.Request, h http.Handler)

HandleHTTP returns the list of healthy entries for a given service filtered by tag.

func (*Consul) Start

func (c *Consul) Start()

Start starts the Consul servers update interval goroutine.

func (*Consul) Stop

func (c *Consul) Stop()

Stop stops the Consul servers update interval goroutine.

func (*Consul) UpdateNodes

func (c *Consul) UpdateNodes() ([]string, error)

UpdateNodes is used to update a list of server nodes for the current discovery service.

type Retrier

type Retrier interface {
	Run(func() error) error
}

Retrier defines the required interface implemented by retry strategies.

type Retry

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

Retry provides a retry.Retrier capable interface that encapsulates Consul client and user defined strategy.

func NewRetrier

func NewRetrier(r Retrier) *Retry

NewRetrier creates a default retrier for the given Consul client and context.

func (*Retry) Run

func (r *Retry) Run(fn func() error) error

Run runs the given function multiple times, acting like a proxy to user defined retry strategy.

Directories

Path Synopsis
_examples

Jump to

Keyboard shortcuts

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