consultant

package module
v0.2.3 Latest Latest
Warning

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

Go to latest
Published: Sep 21, 2018 License: MPL-2.0 Imports: 17 Imported by: 0

README

consultant

Helpful wrappers around Consul API client

Build Status

Client

Our Consultant Client is a thin wrapper around the Consul API Client. It provides

  • Simplified Service Retrieval (docs)
  • Simplified Service Registration (docs)
  • Simplified Key Retrieval (docs)

Sibling Services Locator

If you run in an environment where you are running several instances of the same service, it can be useful sometimes to have a way for each service too find it's sibling services.

Service Candidate Election

With a multi-service setup, there are times where might want one service to be responsible for a specific task. This task can range from being considered the leader of the entire cluster of services OR simply a single sub-task that must run atomically.

Managed Services

Service lifecycle manager

Watch Plan Helpers

watch.go contains two sets of methods:

  • Package helper functions that will construct one of the already available watch functions provided by hashi
  • Helper methods hanging off of our Client struct that will fill in some values based on the client's own definition

TODO:

  • More tests
  • More docs
  • More stuff
  • ManagedService consistency checks

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Debug

func Debug()

Debug will enable additional logging

func DisableDebug

func DisableDebug()

func GetMyAddress

func GetMyAddress() (string, error)

GetMyAddress will attempt to locate your local RFC-1918 address

DEPRECATED: Please use util.MyAddress()

func SetPackageLogger

func SetPackageLogger(logger Logger)

func WatchChecks

func WatchChecks(service, state string, stale bool, token, datacenter string) (*watch.Plan, error)

WatchChecks wraps the creation of a "checks" plan

func WatchEvent

func WatchEvent(name, token, datacenter string) (*watch.Plan, error)

WatchEvent wraps the creation of an "event" plan

func WatchKey

func WatchKey(key string, stale bool, token, datacenter string) (*watch.Plan, error)

WatchKey wraps the creation of a "key" plan

func WatchKeyPrefix

func WatchKeyPrefix(prefix string, stale bool, token, datacenter string) (*watch.Plan, error)

WatchKeyPrefix wraps the creation of a "keyprefix" plan

func WatchNodes

func WatchNodes(stale bool, token, datacenter string) (*watch.Plan, error)

WatchNodes wraps the creation of a "nodes" plan

func WatchService

func WatchService(service, tag string, passingOnly, stale bool, token, datacenter string) (*watch.Plan, error)

WatchService wraps the creation of a "service" plan

func WatchServices

func WatchServices(stale bool, token, datacenter string) (*watch.Plan, error)

WatchServices wraps the creation of a "services" plan

Types

type Candidate

type Candidate struct {
	*candidate.Candidate
}

func NewCandidate

func NewCandidate(client *Client, candidateID, key, ttl string) (*Candidate, error)

NewCandidate creates a new Candidate

DEPRECATED: Will be removed in a future release

- "client" must be a valid api client

- "candidateID" should be an implementation-relevant unique identifier for this candidate

- "key" must be the full path to a KV, it will be created if it doesn't already exist

- "ttl" is the duration to set on the kv session ttl, will default to 30s if not specified

func (*Candidate) DeregisterUpdate

func (c *Candidate) DeregisterUpdate(id string)

DeregisterUpdate will remove an update chan from this candidate

DEPRECATED: Use Unwatch()

func (*Candidate) DeregisterUpdates

func (c *Candidate) DeregisterUpdates()

DeregisterUpdates will empty out the map of update channels

DEPRECATED: Use RemoveWatchers()

func (*Candidate) RegisterUpdate

func (c *Candidate) RegisterUpdate(id string) (string, chan bool)

Register returns a channel for updates in leader status - only one message per candidate instance will be sent

DEPRECATED: Use Watch()

type CandidateSessionParts

type CandidateSessionParts struct {
	*candidate.SessionNameParts
	Prefix     string
	ID         string
	RandomUUID string
}

CandidateSessionParts will be removed in a future release.

DEPRECATED: Use candidate.SessionParts

func ParseCandidateSessionName

func ParseCandidateSessionName(name string) (*CandidateSessionParts, error)

ParseCandidateSessionName is provided so you don't have to parse it yourself :)

DEPRECATED: Use candidate.ParseSessionName

type Client

type Client struct {
	*api.Client
	// contains filtered or unexported fields
}

func NewClient

func NewClient(conf *api.Config) (*Client, error)

NewClient constructs a new consultant client.

func NewDefaultClient

func NewDefaultClient() (*Client, error)

NewDefaultClient creates a new client with default configuration values

func (*Client) BuildServiceURL

func (c *Client) BuildServiceURL(protocol, serviceName, tag string, passingOnly bool, options *api.QueryOptions) (*url.URL, error)

BuildServiceURL will attempt to locate a healthy instance of the specified service name + tag combination, then attempt to construct a *net.URL from the resulting service information

func (*Client) Config

func (c *Client) Config() api.Config

Config returns the API Client configuration struct as it was at time of construction

func (*Client) EnsureKey

func (c *Client) EnsureKey(key string, options *api.QueryOptions) (*api.KVPair, *api.QueryMeta, error)

EnsureKey will fetch a key/value and ensure the key is present. The value may still be empty.

func (*Client) ManagedServiceRegister

func (c *Client) ManagedServiceRegister(reg *SimpleServiceRegistration) (*ManagedService, error)

ManagedServiceRegister will return an instance of ManagedService after registering service

NOTE: This forces the "EnableTagOverride" option to "true"

func (*Client) MyAddr

func (c *Client) MyAddr() string

MyAddr returns either the self-determine or set IP address of our host

func (*Client) MyHost

func (c *Client) MyHost() string

MyHost returns either the self-determined or set name of our host

func (*Client) MyNode

func (c *Client) MyNode() string

MyNode returns the name of the Consul Node this client is connected to

func (*Client) PickService

func (c *Client) PickService(service, tag string, passingOnly bool, options *api.QueryOptions) (*api.ServiceEntry, *api.QueryMeta, error)

PickService will attempt to locate any registered service with a name + tag combination and return one at random from the resulting list

func (*Client) ServiceByTags

func (c *Client) ServiceByTags(service string, tags []string, tagsOption TagsOption, passingOnly bool, options *api.QueryOptions) ([]*api.ServiceEntry, *api.QueryMeta, error)

ServiceByTags - this wraps the consul Health().Service() call, adding the tagsOption parameter and accepting a slice of tags. tagsOption should be one of the following:

TagsAll - this will return only services that have all the specified tags present.
TagsExactly - like TagsAll, but will return only services that match exactly the tags specified, no more.
TagsAny - this will return services that match any of the tags specified.
TagsExclude - this will return services don't have any of the tags specified.

func (*Client) SetMyAddr

func (c *Client) SetMyAddr(myAddr string)

SetMyAddr allows you to manually specify the IP address of our host

func (*Client) SetMyHost

func (c *Client) SetMyHost(myHost string)

SetMyHost allows you to to manually specify the name of our host

func (*Client) SimpleServiceRegister

func (c *Client) SimpleServiceRegister(reg *SimpleServiceRegistration) (string, error)

SimpleServiceRegister is a helper method to ease consul service registration

func (*Client) WatchChecks

func (c *Client) WatchChecks(service, state string, stale bool, handler watch.HandlerFunc) (*watch.Plan, error)

WatchChecks will attempt to create a "checks" watch plan based on an existing client configuration

func (*Client) WatchEvent

func (c *Client) WatchEvent(name string, handler watch.HandlerFunc) (*watch.Plan, error)

WatchEvent will attempt to create an "event" watch plan based on an existing client configuration

func (*Client) WatchKey

func (c *Client) WatchKey(key string, stale bool, handler watch.HandlerFunc) (*watch.Plan, error)

WatchKey will attempt to create a "key" watch plan based on an existing client configuration

func (*Client) WatchKeyPrefix

func (c *Client) WatchKeyPrefix(prefix string, stale bool, handler watch.HandlerFunc) (*watch.Plan, error)

WatchKeyPrefix will attempt to create a "keyprefix" watch plan based on an existing client configuration

func (*Client) WatchNodes

func (c *Client) WatchNodes(stale bool, handler watch.HandlerFunc) (*watch.Plan, error)

WatchNodes will attempt to create a "nodes" watch plan based on an existing client configuration

func (*Client) WatchService

func (c *Client) WatchService(service, tag string, passingOnly, stale bool, handler watch.HandlerFunc) (*watch.Plan, error)

WatchService will attempt to create a "service" watch plan based on an existing client configuration

func (*Client) WatchServices

func (c *Client) WatchServices(stale bool, handler watch.HandlerFunc) (*watch.Plan, error)

WatchServices will attempt to create a "services" watch plan based on an existing client configuration

type Logger

type Logger interface {
	log.Logger
}

Logger is here for compatibility and will be removed in the future

type ManagedService

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

ManagedService is a service lifecycle helper object. It provides an easy api to add / remove tags, create a SiblingWatcher or Candidate, and deregistration.

NOTE: Currently no sanity checking is performed against Consul itself. If you directly modify the service definition via the consul api / ui, this object will be defunct.

func NewManagedService

func NewManagedService(client *Client, serviceID, serviceName string, registeredTags []string) (*ManagedService, error)

func (*ManagedService) AddTags

func (ms *ManagedService) AddTags(tags ...string) error

AddTags will attempt to add the provided tags to the service registration in consul

- Input is "uniqued" before processing occurs. - If delta is 0, this is a no-op

func (*ManagedService) Candidate

func (ms *ManagedService) Candidate() *Candidate

Candidate returns the current candidate for this service. Does not create one

func (*ManagedService) Deregister

func (ms *ManagedService) Deregister() error

Deregister will remove this service from the service catalog in consul

func (*ManagedService) Meta

func (ms *ManagedService) Meta() *ManagedServiceMeta

Meta returns service metadata object containing ID, Name, and the Tags that were present at registration time

func (*ManagedService) NewCandidate

func (ms *ManagedService) NewCandidate(key, ttl string, wait bool) (*Candidate, error)

NewCandidate will attempt to construct a Candidate for this service

NOTE: If a Candidate was previously created, it will be halted, removed, and a new one created

func (*ManagedService) NewSiblingLocator

func (ms *ManagedService) NewSiblingLocator(allowStale bool) (*SiblingLocator, error)

NewSiblingLocator will attempt to construct a SiblingLocator for this service.

NOTE: If a SiblingLocator was previously created, it will be overwritten

func (*ManagedService) RemoveTags

func (ms *ManagedService) RemoveTags(tags ...string) error

RemoveTags will attempt to remove the provided set of tags from the service registration in consul.

- You cannot remove the Service ID tag. - Input is "uniqued" before processing occurs. - If delta is 0, this is a no-op.

func (*ManagedService) SiblingLocator

func (ms *ManagedService) SiblingLocator() *SiblingLocator

SiblingLocator returns the current SiblingLocator for this service. Does not create one

type ManagedServiceMeta

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

ManagedServiceMeta is a small container object for on-creation details on the service

func (*ManagedServiceMeta) ID

func (m *ManagedServiceMeta) ID() string

func (*ManagedServiceMeta) Name

func (m *ManagedServiceMeta) Name() string

func (*ManagedServiceMeta) RegisteredTags

func (m *ManagedServiceMeta) RegisteredTags() []string

Returns list of tags service was registered with

type Sibling

type Sibling struct {
	Node    api.Node
	Service api.AgentService
	Checks  api.HealthChecks
}

Sibling is a thread-safe representation of the Consul api.ServiceEntry object returned by the Health().Service() api

type SiblingCallback

type SiblingCallback func(index uint64, siblings Siblings)

SiblingCallback is the prototype for a callback that can be registered in a SiblingLocator. It will be called whenever a running watcher receives a new service list from Consul, or optionally when a call to Current is made.

"index" will be "math.MaxUint64" when called using "Current"

type SiblingLocator

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

SiblingLocator provides a way for a local service to find other services registered in Consul that share it's name and tags (if any).

func NewSiblingLocator

func NewSiblingLocator(client *Client, config SiblingLocatorConfig) (*SiblingLocator, error)

func NewSiblingLocatorWithAgentService

func NewSiblingLocatorWithAgentService(c *Client, n *api.Node, as *api.AgentService) (*SiblingLocator, error)

NewSiblingLocatorWithAgentService will construct a SiblingLocator from a consul api node and agent service struct

func NewSiblingLocatorWithCatalogService

func NewSiblingLocatorWithCatalogService(c *Client, cs *api.CatalogService) (*SiblingLocator, error)

NewSiblingLocatorWithCatalogService will construct a SiblingLocator from a consul api catalog service struct

func (*SiblingLocator) AddCallback

func (sl *SiblingLocator) AddCallback(name string, cb SiblingCallback) string

func (*SiblingLocator) Current

func (sl *SiblingLocator) Current(passingOnly, sendToCallbacks bool) (Siblings, error)

Current will immediately execute a Health().Service() call, returning and optionally sending the result to any registered callbacks

- passingOnly will limit the response to only registrations deemed "healthy"

- sendToCallbacks will send the results to any callbacks registered at time of execution. Your callbacks can determine the difference between a watcher update and a "Current" call by looking for math.MaxUint64 as the index value

func (*SiblingLocator) RemoveCallback

func (sl *SiblingLocator) RemoveCallback(name string)

func (*SiblingLocator) RemoveCallbacks

func (sl *SiblingLocator) RemoveCallbacks()

RemoveCallbacks will empty out the map of registered callbacks

func (*SiblingLocator) StartWatcher

func (sl *SiblingLocator) StartWatcher(passingOnly bool) error

StartWatcher will spin up a Consul WatchPlan that watches for other registered services with the same name and set of tags.

- passingOnly will limit the response to only registrations deemed "healthy"

func (*SiblingLocator) StopWatcher

func (sl *SiblingLocator) StopWatcher()

StopWatcher will stop the sibling watchplan. If the plan was previously stopped, this is a noop.

type SiblingLocatorConfig

type SiblingLocatorConfig struct {
	ServiceID   string // REQUIRED ID of service you want to find siblings for.  Used to exclude local service from responses
	ServiceName string // REQUIRED name of service

	NodeName    string   // OPTIONAL name of node where service was registered.  Used to exclude local service from responses.  Will use node client is connected to if not defined.
	ServiceTags []string // OPTIONAL tags to require when looking for siblings
	AllowStale  bool     // OPTIONAL allow "stale" values
	Datacenter  string   // OPTIONAL consul datacenter.  Will use value from Client if left blank
	Token       string   // OPTIONAL consul acl token.  Will use value from Client if left blank
}

SiblingLocatorConfig is used to construct a SiblingLocator. All values except ServiceTags are required.

type Siblings

type Siblings []Sibling

Siblings is provided to any callbacks

type SimpleServiceRegistration

type SimpleServiceRegistration struct {
	Name string // [required] name to register service under
	Port int    // [required] external port to advertise for service consumers

	ID                string   // [optional] specific id for service, will be generated if not set
	RandomID          bool     // [optional] if ID is not set, use a random uuid if true, or hostname if false
	Address           string   // [optional] determined automatically by Register() if not set
	Tags              []string // [optional] desired tags: Register() adds serviceId
	CheckTCP          bool     // [optional] if true register a TCP check
	CheckPath         string   // [optional] register an http check with this path if set
	CheckScheme       string   // [optional] override the http check scheme (default: http)
	CheckPort         int      // [optional] if set, this is the port that the health check lives at
	Interval          string   // [optional] check interval
	EnableTagOverride bool     // [optional] whether we should allow tag overriding (new in 0.6+)
}

SimpleServiceRegistration describes a service that we want to register

type TagsOption

type TagsOption int
const (
	// TagsAll means all tags passed must be present, though other tags are okay
	TagsAll TagsOption = iota

	// TagsAny means any service having at least one of the tags are returned
	TagsAny

	// TagsExactly means that the service tags must match those passed exactly
	TagsExactly

	// TagsExclude means skip services that match any tags passed
	TagsExclude
)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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