embed - ActiveState ActiveGo 1.8
...

Package embed

import "github.com/coreos/etcd/embed"
Overview
Index

Overview ▾

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

Launch an embedded etcd server using the configuration defaults:

import (
	"log"
	"time"

	"github.com/coreos/etcd/embed"
)

func main() {
	cfg := embed.NewConfig()
	cfg.Dir = "default.etcd"
	e, err := embed.StartEtcd(cfg)
	if err != nil {
		log.Fatal(err)
	}
	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!")
	}
	log.Fatal(<-e.Err())
}

Constants

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

    DefaultName         = "default"
    DefaultMaxSnapshots = 5
    DefaultMaxWALs      = 5

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

Variables

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

Config holds the arguments for configuring an etcd server.

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"`
    EnableV2            bool   `json:"enable-v2"`

    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:"-"`
    // ServiceRegister is for registering users' gRPC services. A simple usage example:
    //	cfg := embed.NewConfig()
    //	cfg.ServerRegister = func(s *grpc.Server) {
    //		pb.RegisterFooServer(s, &fooServer{})
    //		pb.RegisterBarServer(s, &barServer{})
    //	}
    //	embed.StartEtcd(cfg)
    ServiceRegister func(*grpc.Server) `json:"-"`

    AuthToken string `json:"auth-token"`
}

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 0.0.0.0. e.g. advertise peer URL localhost:2380 or listen peer URL 0.0.0.0:2380 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 127.0.0.1. 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

Etcd contains a running etcd server and its listeners.

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

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