Back to / embed

Package embed

Latest Go to latest

The latest major version is .

Published: Jul 14, 2017 | License: Apache-2.0 | Module:


Package embed provides bindings for embedding an etcd server in a program.

Launch an embedded etcd server using the configuration defaults:

import (


func main() {
	cfg := embed.NewConfig()
	cfg.Dir = "default.etcd"
	e, err := embed.StartEtcd(cfg)
	if err != nil {
	defer e.Close()
	select {
	case <-e.Server.ReadyNotify():
		log.Printf("Server is ready!")
	case <-time.After(60 * time.Second):
		e.Server.Stop() // trigger a shutdown
		log.Printf("Server took too long to start!")



const (
	ClusterStateFlagNew      = "new"
	ClusterStateFlagExisting = "existing"

	DefaultName         = "default"
	DefaultMaxSnapshots = 5
	DefaultMaxWALs      = 5

	DefaultListenPeerURLs   = "http://localhost:2380"
	DefaultListenClientURLs = "http://localhost:2379"


var (
	ErrConflictBootstrapFlags = fmt.Errorf("multiple discovery or bootstrap flags are set. " +
		"Choose one of \"initial-cluster\", \"discovery\" or \"discovery-srv\"")
	ErrUnsetAdvertiseClientURLsFlag = fmt.Errorf("--advertise-client-urls is required when --listen-client-urls is set explicitly")

	DefaultInitialAdvertisePeerURLs = "http://localhost:2380"
	DefaultAdvertiseClientURLs      = "http://localhost:2379"

type Config

type Config struct {
	CorsInfo                *cors.CORSInfo
	LPUrls, LCUrls          []url.URL
	Dir                     string `json:"data-dir"`
	WalDir                  string `json:"wal-dir"`
	MaxSnapFiles            uint   `json:"max-snapshots"`
	MaxWalFiles             uint   `json:"max-wals"`
	Name                    string `json:"name"`
	SnapCount               uint64 `json:"snapshot-count"`
	AutoCompactionRetention int    `json:"auto-compaction-retention"`

	// TickMs is the number of milliseconds between heartbeat ticks.
	// TODO: decouple tickMs and heartbeat tick (current heartbeat tick = 1).
	// make ticks a cluster wide configuration.
	TickMs            uint  `json:"heartbeat-interval"`
	ElectionMs        uint  `json:"election-timeout"`
	QuotaBackendBytes int64 `json:"quota-backend-bytes"`

	APUrls, ACUrls      []url.URL
	ClusterState        string `json:"initial-cluster-state"`
	DNSCluster          string `json:"discovery-srv"`
	Dproxy              string `json:"discovery-proxy"`
	Durl                string `json:"discovery"`
	InitialCluster      string `json:"initial-cluster"`
	InitialClusterToken string `json:"initial-cluster-token"`
	StrictReconfigCheck bool   `json:"strict-reconfig-check"`

	ClientTLSInfo transport.TLSInfo
	ClientAutoTLS bool
	PeerTLSInfo   transport.TLSInfo
	PeerAutoTLS   bool

	Debug        bool   `json:"debug"`
	LogPkgLevels string `json:"log-package-levels"`
	EnablePprof  bool
	Metrics      string `json:"metrics"`

	// ForceNewCluster starts a new cluster even if previously started; unsafe.
	ForceNewCluster bool `json:"force-new-cluster"`

	// UserHandlers is for registering users handlers and only used for
	// embedding etcd into other applications.
	// The map key is the route path for the handler, and
	// you must ensure it can't be conflicted with etcd's.
	UserHandlers map[string]http.Handler `json:"-"`

Config holds the arguments for configuring an etcd server.

func ConfigFromFile

func ConfigFromFile(path string) (*Config, error)

func NewConfig

func NewConfig() *Config

NewConfig creates a new Config populated with default values.

func (Config) ElectionTicks

func (cfg Config) ElectionTicks() int

func (Config) InitialClusterFromName

func (cfg Config) InitialClusterFromName(name string) (ret string)

func (Config) IsNewCluster

func (cfg Config) IsNewCluster() bool

func (*Config) PeerURLsMapAndToken

func (cfg *Config) PeerURLsMapAndToken(which string) (urlsmap types.URLsMap, token string, err error)

PeerURLsMapAndToken sets up an initial peer URLsMap and cluster token for bootstrap or discovery.

func (*Config) UpdateDefaultClusterFromName

func (cfg *Config) UpdateDefaultClusterFromName(defaultInitialCluster string) (string, error)

UpdateDefaultClusterFromName updates cluster advertise URLs with, if available, default host, if advertise URLs are default values(localhost:2379,2380) AND if listen URL is e.g. advertise peer URL localhost:2380 or listen peer URL then the advertise peer host would be updated with machine's default host, while keeping the listen URL's port. User can work around this by explicitly setting URL with It returns the default hostname, if used, and the error, if any, from getting the machine's default host. TODO: check whether fields are set instead of whether fields have default value

func (*Config) Validate

func (cfg *Config) Validate() error

type Etcd

type Etcd struct {
	Peers   []net.Listener
	Clients []net.Listener
	Server  *etcdserver.EtcdServer
	// contains filtered or unexported fields

Etcd contains a running etcd server and its listeners.

func StartEtcd

func StartEtcd(inCfg *Config) (e *Etcd, err error)

StartEtcd launches the etcd server and HTTP handlers for client/server communication. The returned Etcd.Server is not guaranteed to have joined the cluster. Wait on the Etcd.Server.ReadyNotify() channel to know when it completes and is ready for use.

func (*Etcd) Close

func (e *Etcd) Close()

func (*Etcd) Config

func (e *Etcd) Config() Config

Config returns the current configuration.

func (*Etcd) Err

func (e *Etcd) Err() <-chan error

Package Files

Documentation was rendered with GOOS=linux and GOARCH=amd64.

Jump to identifier

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to identifier