| 1 |
// Copyright 2016 The etcd Authors |
| 2 |
// |
| 3 |
// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 |
// you may not use this file except in compliance with the License. |
| 5 |
// You may obtain a copy of the License at |
| 6 |
// |
| 7 |
// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 |
// |
| 9 |
// Unless required by applicable law or agreed to in writing, software |
| 10 |
// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 |
// See the License for the specific language governing permissions and |
| 13 |
// limitations under the License. |
| 14 |
|
| 15 |
package embed |
| 16 |
|
| 17 |
import ( |
| 18 |
"crypto/tls" |
| 19 |
"fmt" |
| 20 |
"io/ioutil" |
| 21 |
"net" |
| 22 |
"net/http" |
| 23 |
"net/url" |
| 24 |
"os" |
| 25 |
"path/filepath" |
| 26 |
"strings" |
| 27 |
"time" |
| 28 |
|
| 29 |
"github.com/coreos/etcd/compactor" |
| 30 |
"github.com/coreos/etcd/etcdserver" |
| 31 |
"github.com/coreos/etcd/pkg/cors" |
| 32 |
"github.com/coreos/etcd/pkg/netutil" |
| 33 |
"github.com/coreos/etcd/pkg/srv" |
| 34 |
"github.com/coreos/etcd/pkg/tlsutil" |
| 35 |
"github.com/coreos/etcd/pkg/transport" |
| 36 |
"github.com/coreos/etcd/pkg/types" |
| 37 |
|
| 38 |
"github.com/coreos/pkg/capnslog" |
| 39 |
"github.com/ghodss/yaml" |
| 40 |
"google.golang.org/grpc" |
| 41 |
"google.golang.org/grpc/grpclog" |
| 42 |
) |
| 43 |
|
| 44 |
const ( |
| 45 |
ClusterStateFlagNew = "new" |
| 46 |
ClusterStateFlagExisting = "existing" |
| 47 |
|
| 48 |
DefaultName = "default" |
| 49 |
DefaultMaxSnapshots = 5 |
| 50 |
DefaultMaxWALs = 5 |
| 51 |
DefaultMaxTxnOps = uint(128) |
| 52 |
DefaultMaxRequestBytes = 1.5 * 1024 * 1024 |
| 53 |
DefaultGRPCKeepAliveMinTime = 5 * time.Second |
| 54 |
DefaultGRPCKeepAliveInterval = 2 * time.Hour |
| 55 |
DefaultGRPCKeepAliveTimeout = 20 * time.Second |
| 56 |
|
| 57 |
DefaultListenPeerURLs = "http://localhost:2380" |
| 58 |
DefaultListenClientURLs = "http://localhost:2379" |
| 59 |
|
| 60 |
DefaultLogOutput = "default" |
| 61 |
|
| 62 |
// DefaultStrictReconfigCheck is the default value for "--strict-reconfig-check" flag. |
| 63 |
// It's enabled by default. |
| 64 |
DefaultStrictReconfigCheck = true |
| 65 |
// DefaultEnableV2 is the default value for "--enable-v2" flag. |
| 66 |
// v2 is enabled by default. |
| 67 |
// TODO: disable v2 when deprecated. |
| 68 |
DefaultEnableV2 = true |
| 69 |
|
| 70 |
// maxElectionMs specifies the maximum value of election timeout. |
| 71 |
// More details are listed in ../Documentation/tuning.md#time-parameters. |
| 72 |
maxElectionMs = 50000 |
| 73 |
) |
| 74 |
|
| 75 |
var ( |
| 76 |
ErrConflictBootstrapFlags = fmt.Errorf("multiple discovery or bootstrap flags are set. " + |
| 77 |
"Choose one of \"initial-cluster\", \"discovery\" or \"discovery-srv\"") |
| 78 |
ErrUnsetAdvertiseClientURLsFlag = fmt.Errorf("--advertise-client-urls is required when --listen-client-urls is set explicitly") |
| 79 |
|
| 80 |
DefaultInitialAdvertisePeerURLs = "http://localhost:2380" |
| 81 |
DefaultAdvertiseClientURLs = "http://localhost:2379" |
| 82 |
|
| 83 |
defaultHostname string |
| 84 |
defaultHostStatus error |
| 85 |
) |
| 86 |
|
| 87 |
func init() { |
| 88 |
defaultHostname, defaultHostStatus = netutil.GetDefaultHost() |
| 89 |
} |
| 90 |
|
| 91 |
// Config holds the arguments for configuring an etcd server. |
| 92 |
type Config struct { |
| 93 |
// member |
| 94 |
|
| 95 |
CorsInfo *cors.CORSInfo |
| 96 |
LPUrls, LCUrls []url.URL |
| 97 |
Dir string `json:"data-dir"` |
| 98 |
WalDir string `json:"wal-dir"` |
| 99 |
MaxSnapFiles uint `json:"max-snapshots"` |
| 100 |
MaxWalFiles uint `json:"max-wals"` |
| 101 |
Name string `json:"name"` |
| 102 |
SnapCount uint64 `json:"snapshot-count"` |
| 103 |
|
| 104 |
// AutoCompactionMode is either 'periodic' or 'revision'. |
| 105 |
AutoCompactionMode string `json:"auto-compaction-mode"` |
| 106 |
// AutoCompactionRetention is either duration string with time unit |
| 107 |
// (e.g. '5m' for 5-minute), or revision unit (e.g. '5000'). |
| 108 |
// If no time unit is provided and compaction mode is 'periodic', |
| 109 |
// the unit defaults to hour. For example, '5' translates into 5-hour. |
| 110 |
AutoCompactionRetention string `json:"auto-compaction-retention"` |
| 111 |
|
| 112 |
// TickMs is the number of milliseconds between heartbeat ticks. |
| 113 |
// TODO: decouple tickMs and heartbeat tick (current heartbeat tick = 1). |
| 114 |
// make ticks a cluster wide configuration. |
| 115 |
TickMs uint `json:"heartbeat-interval"` |
| 116 |
ElectionMs uint `json:"election-timeout"` |
| 117 |
|
| 118 |
// InitialElectionTickAdvance is true, then local member fast-forwards |
| 119 |
// election ticks to speed up "initial" leader election trigger. This |
| 120 |
// benefits the case of larger election ticks. For instance, cross |
| 121 |
// datacenter deployment may require longer election timeout of 10-second. |
| 122 |
// If true, local node does not need wait up to 10-second. Instead, |
| 123 |
// forwards its election ticks to 8-second, and have only 2-second left |
| 124 |
// before leader election. |
| 125 |
// |
| 126 |
// Major assumptions are that: |
| 127 |
// - cluster has no active leader thus advancing ticks enables faster |
| 128 |
// leader election, or |
| 129 |
// - cluster already has an established leader, and rejoining follower |
| 130 |
// is likely to receive heartbeats from the leader after tick advance |
| 131 |
// and before election timeout. |
| 132 |
// |
| 133 |
// However, when network from leader to rejoining follower is congested, |
| 134 |
// and the follower does not receive leader heartbeat within left election |
| 135 |
// ticks, disruptive election has to happen thus affecting cluster |
| 136 |
// availabilities. |
| 137 |
// |
| 138 |
// Disabling this would slow down initial bootstrap process for cross |
| 139 |
// datacenter deployments. Make your own tradeoffs by configuring |
| 140 |
// --initial-election-tick-advance at the cost of slow initial bootstrap. |
| 141 |
// |
| 142 |
// If single-node, it advances ticks regardless. |
| 143 |
// |
| 144 |
// See https://github.com/coreos/etcd/issues/9333 for more detail. |
| 145 |
InitialElectionTickAdvance bool `json:"initial-election-tick-advance"` |
| 146 |
|
| 147 |
QuotaBackendBytes int64 `json:"quota-backend-bytes"` |
| 148 |
MaxTxnOps uint `json:"max-txn-ops"` |
| 149 |
MaxRequestBytes uint `json:"max-request-bytes"` |
| 150 |
|
| 151 |
// gRPC server options |
| 152 |
|
| 153 |
// GRPCKeepAliveMinTime is the minimum interval that a client should |
| 154 |
// wait before pinging server. When client pings "too fast", server |
| 155 |
// sends goaway and closes the connection (errors: too_many_pings, |
| 156 |
// http2.ErrCodeEnhanceYourCalm). When too slow, nothing happens. |
| 157 |
// Server expects client pings only when there is any active streams |
| 158 |
// (PermitWithoutStream is set false). |
| 159 |
GRPCKeepAliveMinTime time.Duration `json:"grpc-keepalive-min-time"` |
| 160 |
// GRPCKeepAliveInterval is the frequency of server-to-client ping |
| 161 |
// to check if a connection is alive. Close a non-responsive connection |
| 162 |
// after an additional duration of Timeout. 0 to disable. |
| 163 |
GRPCKeepAliveInterval time.Duration `json:"grpc-keepalive-interval"` |
| 164 |
// GRPCKeepAliveTimeout is the additional duration of wait |
| 165 |
// before closing a non-responsive connection. 0 to disable. |
| 166 |
GRPCKeepAliveTimeout time.Duration `json:"grpc-keepalive-timeout"` |
| 167 |
|
| 168 |
// clustering |
| 169 |
|
| 170 |
APUrls, ACUrls []url.URL |
| 171 |
ClusterState string `json:"initial-cluster-state"` |
| 172 |
DNSCluster string `json:"discovery-srv"` |
| 173 |
Dproxy string `json:"discovery-proxy"` |
| 174 |
Durl string `json:"discovery"` |
| 175 |
InitialCluster string `json:"initial-cluster"` |
| 176 |
InitialClusterToken string `json:"initial-cluster-token"` |
| 177 |
StrictReconfigCheck bool `json:"strict-reconfig-check"` |
| 178 |
EnableV2 bool `json:"enable-v2"` |
| 179 |
|
| 180 |
// security |
| 181 |
|
| 182 |
ClientTLSInfo transport.TLSInfo |
| 183 |
ClientAutoTLS bool |
| 184 |
PeerTLSInfo transport.TLSInfo |
| 185 |
PeerAutoTLS bool |
| 186 |
|
| 187 |
// CipherSuites is a list of supported TLS cipher suites between |
| 188 |
// client/server and peers. If empty, Go auto-populates the list. |
| 189 |
// Note that cipher suites are prioritized in the given order. |
| 190 |
CipherSuites []string `json:"cipher-suites"` |
| 191 |
|
| 192 |
// debug |
| 193 |
|
| 194 |
Debug bool `json:"debug"` |
| 195 |
LogPkgLevels string `json:"log-package-levels"` |
| 196 |
LogOutput string `json:"log-output"` |
| 197 |
EnablePprof bool `json:"enable-pprof"` |
| 198 |
Metrics string `json:"metrics"` |
| 199 |
ListenMetricsUrls []url.URL |
| 200 |
ListenMetricsUrlsJSON string `json:"listen-metrics-urls"` |
| 201 |
|
| 202 |
// ForceNewCluster starts a new cluster even if previously started; unsafe. |
| 203 |
ForceNewCluster bool `json:"force-new-cluster"` |
| 204 |
|
| 205 |
// UserHandlers is for registering users handlers and only used for |
| 206 |
// embedding etcd into other applications. |
| 207 |
// The map key is the route path for the handler, and |
| 208 |
// you must ensure it can't be conflicted with etcd's. |
| 209 |
UserHandlers map[string]http.Handler `json:"-"` |
| 210 |
// ServiceRegister is for registering users' gRPC services. A simple usage example: |
| 211 |
// cfg := embed.NewConfig() |
| 212 |
// cfg.ServerRegister = func(s *grpc.Server) { |
| 213 |
// pb.RegisterFooServer(s, &fooServer{}) |
| 214 |
// pb.RegisterBarServer(s, &barServer{}) |
| 215 |
// } |
| 216 |
// embed.StartEtcd(cfg) |
| 217 |
ServiceRegister func(*grpc.Server) `json:"-"` |
| 218 |
|
| 219 |
// auth |
| 220 |
|
| 221 |
AuthToken string `json:"auth-token"` |
| 222 |
|
| 223 |
// Experimental flags |
| 224 |
|
| 225 |
ExperimentalInitialCorruptCheck bool `json:"experimental-initial-corrupt-check"` |
| 226 |
ExperimentalCorruptCheckTime time.Duration `json:"experimental-corrupt-check-time"` |
| 227 |
ExperimentalEnableV2V3 string `json:"experimental-enable-v2v3"` |
| 228 |
} |
| 229 |
|
| 230 |
// configYAML holds the config suitable for yaml parsing |
| 231 |
type configYAML struct { |
| 232 |
Config |
| 233 |
configJSON |
| 234 |
} |
| 235 |
|
| 236 |
// configJSON has file options that are translated into Config options |
| 237 |
type configJSON struct { |
| 238 |
LPUrlsJSON string `json:"listen-peer-urls"` |
| 239 |
LCUrlsJSON string `json:"listen-client-urls"` |
| 240 |
CorsJSON string `json:"cors"` |
| 241 |
APUrlsJSON string `json:"initial-advertise-peer-urls"` |
| 242 |
ACUrlsJSON string `json:"advertise-client-urls"` |
| 243 |
ClientSecurityJSON securityConfig `json:"client-transport-security"` |
| 244 |
PeerSecurityJSON securityConfig `json:"peer-transport-security"` |
| 245 |
} |
| 246 |
|
| 247 |
type securityConfig struct { |
| 248 |
CAFile string `json:"ca-file"` |
| 249 |
CertFile string `json:"cert-file"` |
| 250 |
KeyFile string `json:"key-file"` |
| 251 |
CertAuth bool `json:"client-cert-auth"` |
| 252 |
TrustedCAFile string `json:"trusted-ca-file"` |
| 253 |
AutoTLS bool `json:"auto-tls"` |
| 254 |
} |
| 255 |
|
| 256 |
// NewConfig creates a new Config populated with default values. |
| 257 |
func NewConfig() *Config { |
| 258 |
lpurl, _ := url.Parse(DefaultListenPeerURLs) |
| 259 |
apurl, _ := url.Parse(DefaultInitialAdvertisePeerURLs) |
| 260 |
lcurl, _ := url.Parse(DefaultListenClientURLs) |
| 261 |
acurl, _ := url.Parse(DefaultAdvertiseClientURLs) |
| 262 |
cfg := &Config{ |
| 263 |
CorsInfo: &cors.CORSInfo{}, |
| 264 |
MaxSnapFiles: DefaultMaxSnapshots, |
| 265 |
MaxWalFiles: DefaultMaxWALs, |
| 266 |
Name: DefaultName, |
| 267 |
SnapCount: etcdserver.DefaultSnapCount, |
| 268 |
MaxTxnOps: DefaultMaxTxnOps, |
| 269 |
MaxRequestBytes: DefaultMaxRequestBytes, |
| 270 |
GRPCKeepAliveMinTime: DefaultGRPCKeepAliveMinTime, |
| 271 |
GRPCKeepAliveInterval: DefaultGRPCKeepAliveInterval, |
| 272 |
GRPCKeepAliveTimeout: DefaultGRPCKeepAliveTimeout, |
| 273 |
TickMs: 100, |
| 274 |
ElectionMs: 1000, |
| 275 |
InitialElectionTickAdvance: true, |
| 276 |
LPUrls: []url.URL{*lpurl}, |
| 277 |
LCUrls: []url.URL{*lcurl}, |
| 278 |
APUrls: []url.URL{*apurl}, |
| 279 |
ACUrls: []url.URL{*acurl}, |
| 280 |
ClusterState: ClusterStateFlagNew, |
| 281 |
InitialClusterToken: "etcd-cluster", |
| 282 |
StrictReconfigCheck: DefaultStrictReconfigCheck, |
| 283 |
LogOutput: DefaultLogOutput, |
| 284 |
Metrics: "basic", |
| 285 |
EnableV2: DefaultEnableV2, |
| 286 |
AuthToken: "simple", |
| 287 |
} |
| 288 |
cfg.InitialCluster = cfg.InitialClusterFromName(cfg.Name) |
| 289 |
return cfg |
| 290 |
} |
| 291 |
|
| 292 |
func logTLSHandshakeFailure(conn *tls.Conn, err error) { |
| 293 |
state := conn.ConnectionState() |
| 294 |
remoteAddr := conn.RemoteAddr().String() |
| 295 |
serverName := state.ServerName |
| 296 |
if len(state.PeerCertificates) > 0 { |
| 297 |
cert := state.PeerCertificates[0] |
| 298 |
ips, dns := cert.IPAddresses, cert.DNSNames |
| 299 |
plog.Infof("rejected connection from %q (error %q, ServerName %q, IPAddresses %q, DNSNames %q)", remoteAddr, err.Error(), serverName, ips, dns) |
| 300 |
} else { |
| 301 |
plog.Infof("rejected connection from %q (error %q, ServerName %q)", remoteAddr, err.Error(), serverName) |
| 302 |
} |
| 303 |
} |
| 304 |
|
| 305 |
// SetupLogging initializes etcd logging. |
| 306 |
// Must be called after flag parsing. |
| 307 |
func (cfg *Config) SetupLogging() { |
| 308 |
cfg.ClientTLSInfo.HandshakeFailure = logTLSHandshakeFailure |
| 309 |
cfg.PeerTLSInfo.HandshakeFailure = logTLSHandshakeFailure |
| 310 |
|
| 311 |
capnslog.SetGlobalLogLevel(capnslog.INFO) |
| 312 |
if cfg.Debug { |
| 313 |
capnslog.SetGlobalLogLevel(capnslog.DEBUG) |
| 314 |
grpc.EnableTracing = true |
| 315 |
// enable info, warning, error |
| 316 |
grpclog.SetLoggerV2(grpclog.NewLoggerV2(os.Stderr, os.Stderr, os.Stderr)) |
| 317 |
} else { |
| 318 |
// only discard info |
| 319 |
grpclog.SetLoggerV2(grpclog.NewLoggerV2(ioutil.Discard, os.Stderr, os.Stderr)) |
| 320 |
} |
| 321 |
if cfg.LogPkgLevels != "" { |
| 322 |
repoLog := capnslog.MustRepoLogger("github.com/coreos/etcd") |
| 323 |
settings, err := repoLog.ParseLogLevelConfig(cfg.LogPkgLevels) |
| 324 |
if err != nil { |
| 325 |
plog.Warningf("couldn't parse log level string: %s, continuing with default levels", err.Error()) |
| 326 |
return |
| 327 |
} |
| 328 |
repoLog.SetLogLevel(settings) |
| 329 |
} |
| 330 |
|
| 331 |
// capnslog initially SetFormatter(NewDefaultFormatter(os.Stderr)) |
| 332 |
// where NewDefaultFormatter returns NewJournaldFormatter when syscall.Getppid() == 1 |
| 333 |
// specify 'stdout' or 'stderr' to skip journald logging even when running under systemd |
| 334 |
switch cfg.LogOutput { |
| 335 |
case "stdout": |
| 336 |
capnslog.SetFormatter(capnslog.NewPrettyFormatter(os.Stdout, cfg.Debug)) |
| 337 |
case "stderr": |
| 338 |
capnslog.SetFormatter(capnslog.NewPrettyFormatter(os.Stderr, cfg.Debug)) |
| 339 |
case DefaultLogOutput: |
| 340 |
default: |
| 341 |
plog.Panicf(`unknown log-output %q (only supports %q, "stdout", "stderr")`, cfg.LogOutput, DefaultLogOutput) |
| 342 |
} |
| 343 |
} |
| 344 |
|
| 345 |
func ConfigFromFile(path string) (*Config, error) { |
| 346 |
cfg := &configYAML{Config: *NewConfig()} |
| 347 |
if err := cfg.configFromFile(path); err != nil { |
| 348 |
return nil, err |
| 349 |
} |
| 350 |
return &cfg.Config, nil |
| 351 |
} |
| 352 |
|
| 353 |
func (cfg *configYAML) configFromFile(path string) error { |
| 354 |
b, err := ioutil.ReadFile(path) |
| 355 |
if err != nil { |
| 356 |
return err |
| 357 |
} |
| 358 |
|
| 359 |
defaultInitialCluster := cfg.InitialCluster |
| 360 |
|
| 361 |
err = yaml.Unmarshal(b, cfg) |
| 362 |
if err != nil { |
| 363 |
return err |
| 364 |
} |
| 365 |
|
| 366 |
if cfg.LPUrlsJSON != "" { |
| 367 |
u, err := types.NewURLs(strings.Split(cfg.LPUrlsJSON, ",")) |
| 368 |
if err != nil { |
| 369 |
plog.Fatalf("unexpected error setting up listen-peer-urls: %v", err) |
| 370 |
} |
| 371 |
cfg.LPUrls = []url.URL(u) |
| 372 |
} |
| 373 |
|
| 374 |
if cfg.LCUrlsJSON != "" { |
| 375 |
u, err := types.NewURLs(strings.Split(cfg.LCUrlsJSON, ",")) |
| 376 |
if err != nil { |
| 377 |
plog.Fatalf("unexpected error setting up listen-client-urls: %v", err) |
| 378 |
} |
| 379 |
cfg.LCUrls = []url.URL(u) |
| 380 |
} |
| 381 |
|
| 382 |
if cfg.CorsJSON != "" { |
| 383 |
if err := cfg.CorsInfo.Set(cfg.CorsJSON); err != nil { |
| 384 |
plog.Panicf("unexpected error setting up cors: %v", err) |
| 385 |
} |
| 386 |
} |
| 387 |
|
| 388 |
if cfg.APUrlsJSON != "" { |
| 389 |
u, err := types.NewURLs(strings.Split(cfg.APUrlsJSON, ",")) |
| 390 |
if err != nil { |
| 391 |
plog.Fatalf("unexpected error setting up initial-advertise-peer-urls: %v", err) |
| 392 |
} |
| 393 |
cfg.APUrls = []url.URL(u) |
| 394 |
} |
| 395 |
|
| 396 |
if cfg.ACUrlsJSON != "" { |
| 397 |
u, err := types.NewURLs(strings.Split(cfg.ACUrlsJSON, ",")) |
| 398 |
if err != nil { |
| 399 |
plog.Fatalf("unexpected error setting up advertise-peer-urls: %v", err) |
| 400 |
} |
| 401 |
cfg.ACUrls = []url.URL(u) |
| 402 |
} |
| 403 |
|
| 404 |
if cfg.ListenMetricsUrlsJSON != "" { |
| 405 |
u, err := types.NewURLs(strings.Split(cfg.ListenMetricsUrlsJSON, ",")) |
| 406 |
if err != nil { |
| 407 |
plog.Fatalf("unexpected error setting up listen-metrics-urls: %v", err) |
| 408 |
} |
| 409 |
cfg.ListenMetricsUrls = []url.URL(u) |
| 410 |
} |
| 411 |
|
| 412 |
// If a discovery flag is set, clear default initial cluster set by InitialClusterFromName |
| 413 |
if (cfg.Durl != "" || cfg.DNSCluster != "") && cfg.InitialCluster == defaultInitialCluster { |
| 414 |
cfg.InitialCluster = "" |
| 415 |
} |
| 416 |
if cfg.ClusterState == "" { |
| 417 |
cfg.ClusterState = ClusterStateFlagNew |
| 418 |
} |
| 419 |
|
| 420 |
copySecurityDetails := func(tls *transport.TLSInfo, ysc *securityConfig) { |
| 421 |
tls.CAFile = ysc.CAFile |
| 422 |
tls.CertFile = ysc.CertFile |
| 423 |
tls.KeyFile = ysc.KeyFile |
| 424 |
tls.ClientCertAuth = ysc.CertAuth |
| 425 |
tls.TrustedCAFile = ysc.TrustedCAFile |
| 426 |
} |
| 427 |
copySecurityDetails(&cfg.ClientTLSInfo, &cfg.ClientSecurityJSON) |
| 428 |
copySecurityDetails(&cfg.PeerTLSInfo, &cfg.PeerSecurityJSON) |
| 429 |
cfg.ClientAutoTLS = cfg.ClientSecurityJSON.AutoTLS |
| 430 |
cfg.PeerAutoTLS = cfg.PeerSecurityJSON.AutoTLS |
| 431 |
|
| 432 |
return cfg.Validate() |
| 433 |
} |
| 434 |
|
| 435 |
func updateCipherSuites(tls *transport.TLSInfo, ss []string) error { |
| 436 |
if len(tls.CipherSuites) > 0 && len(ss) > 0 { |
| 437 |
return fmt.Errorf("TLSInfo.CipherSuites is already specified (given %v)", ss) |
| 438 |
} |
| 439 |
if len(ss) > 0 { |
| 440 |
cs := make([]uint16, len(ss)) |
| 441 |
for i, s := range ss { |
| 442 |
var ok bool |
| 443 |
cs[i], ok = tlsutil.GetCipherSuite(s) |
| 444 |
if !ok { |
| 445 |
return fmt.Errorf("unexpected TLS cipher suite %q", s) |
| 446 |
} |
| 447 |
} |
| 448 |
tls.CipherSuites = cs |
| 449 |
} |
| 450 |
return nil |
| 451 |
} |
| 452 |
|
| 453 |
// Validate ensures that '*embed.Config' fields are properly configured. |
| 454 |
func (cfg *Config) Validate() error { |
| 455 |
if err := checkBindURLs(cfg.LPUrls); err != nil { |
| 456 |
return err |
| 457 |
} |
| 458 |
if err := checkBindURLs(cfg.LCUrls); err != nil { |
| 459 |
return err |
| 460 |
} |
| 461 |
if err := checkBindURLs(cfg.ListenMetricsUrls); err != nil { |
| 462 |
return err |
| 463 |
} |
| 464 |
if err := checkHostURLs(cfg.APUrls); err != nil { |
| 465 |
// TODO: return err in v3.4 |
| 466 |
addrs := make([]string, len(cfg.APUrls)) |
| 467 |
for i := range cfg.APUrls { |
| 468 |
addrs[i] = cfg.APUrls[i].String() |
| 469 |
} |
| 470 |
plog.Warningf("advertise-peer-urls %q is deprecated (%v)", strings.Join(addrs, ","), err) |
| 471 |
} |
| 472 |
if err := checkHostURLs(cfg.ACUrls); err != nil { |
| 473 |
// TODO: return err in v3.4 |
| 474 |
addrs := make([]string, len(cfg.ACUrls)) |
| 475 |
for i := range cfg.ACUrls { |
| 476 |
addrs[i] = cfg.ACUrls[i].String() |
| 477 |
} |
| 478 |
plog.Warningf("advertise-client-urls %q is deprecated (%v)", strings.Join(addrs, ","), err) |
| 479 |
} |
| 480 |
|
| 481 |
// Check if conflicting flags are passed. |
| 482 |
nSet := 0 |
| 483 |
for _, v := range []bool{cfg.Durl != "", cfg.InitialCluster != "", cfg.DNSCluster != ""} { |
| 484 |
if v { |
| 485 |
nSet++ |
| 486 |
} |
| 487 |
} |
| 488 |
|
| 489 |
if cfg.ClusterState != ClusterStateFlagNew && cfg.ClusterState != ClusterStateFlagExisting { |
| 490 |
return fmt.Errorf("unexpected clusterState %q", cfg.ClusterState) |
| 491 |
} |
| 492 |
|
| 493 |
if nSet > 1 { |
| 494 |
return ErrConflictBootstrapFlags |
| 495 |
} |
| 496 |
|
| 497 |
if cfg.TickMs <= 0 { |
| 498 |
return fmt.Errorf("--heartbeat-interval must be >0 (set to %dms)", cfg.TickMs) |
| 499 |
} |
| 500 |
if cfg.ElectionMs <= 0 { |
| 501 |
return fmt.Errorf("--election-timeout must be >0 (set to %dms)", cfg.ElectionMs) |
| 502 |
} |
| 503 |
if 5*cfg.TickMs > cfg.ElectionMs { |
| 504 |
return fmt.Errorf("--election-timeout[%vms] should be at least as 5 times as --heartbeat-interval[%vms]", cfg.ElectionMs, cfg.TickMs) |
| 505 |
} |
| 506 |
if cfg.ElectionMs > maxElectionMs { |
| 507 |
return fmt.Errorf("--election-timeout[%vms] is too long, and should be set less than %vms", cfg.ElectionMs, maxElectionMs) |
| 508 |
} |
| 509 |
|
| 510 |
// check this last since proxying in etcdmain may make this OK |
| 511 |
if cfg.LCUrls != nil && cfg.ACUrls == nil { |
| 512 |
return ErrUnsetAdvertiseClientURLsFlag |
| 513 |
} |
| 514 |
|
| 515 |
switch cfg.AutoCompactionMode { |
| 516 |
case "": |
| 517 |
case compactor.ModeRevision, compactor.ModePeriodic: |
| 518 |
default: |
| 519 |
return fmt.Errorf("unknown auto-compaction-mode %q", cfg.AutoCompactionMode) |
| 520 |
} |
| 521 |
|
| 522 |
return nil |
| 523 |
} |
| 524 |
|
| 525 |
// PeerURLsMapAndToken sets up an initial peer URLsMap and cluster token for bootstrap or discovery. |
| 526 |
func (cfg *Config) PeerURLsMapAndToken(which string) (urlsmap types.URLsMap, token string, err error) { |
| 527 |
token = cfg.InitialClusterToken |
| 528 |
switch { |
| 529 |
case cfg.Durl != "": |
| 530 |
urlsmap = types.URLsMap{} |
| 531 |
// If using discovery, generate a temporary cluster based on |
| 532 |
// self's advertised peer URLs |
| 533 |
urlsmap[cfg.Name] = cfg.APUrls |
| 534 |
token = cfg.Durl |
| 535 |
case cfg.DNSCluster != "": |
| 536 |
clusterStrs, cerr := srv.GetCluster("etcd-server", cfg.Name, cfg.DNSCluster, cfg.APUrls) |
| 537 |
if cerr != nil { |
| 538 |
plog.Errorf("couldn't resolve during SRV discovery (%v)", cerr) |
| 539 |
return nil, "", cerr |
| 540 |
} |
| 541 |
for _, s := range clusterStrs { |
| 542 |
plog.Noticef("got bootstrap from DNS for etcd-server at %s", s) |
| 543 |
} |
| 544 |
clusterStr := strings.Join(clusterStrs, ",") |
| 545 |
if strings.Contains(clusterStr, "https://") && cfg.PeerTLSInfo.CAFile == "" { |
| 546 |
cfg.PeerTLSInfo.ServerName = cfg.DNSCluster |
| 547 |
} |
| 548 |
urlsmap, err = types.NewURLsMap(clusterStr) |
| 549 |
// only etcd member must belong to the discovered cluster. |
| 550 |
// proxy does not need to belong to the discovered cluster. |
| 551 |
if which == "etcd" { |
| 552 |
if _, ok := urlsmap[cfg.Name]; !ok { |
| 553 |
return nil, "", fmt.Errorf("cannot find local etcd member %q in SRV records", cfg.Name) |
| 554 |
} |
| 555 |
} |
| 556 |
default: |
| 557 |
// We're statically configured, and cluster has appropriately been set. |
| 558 |
urlsmap, err = types.NewURLsMap(cfg.InitialCluster) |
| 559 |
} |
| 560 |
return urlsmap, token, err |
| 561 |
} |
| 562 |
|
| 563 |
func (cfg Config) InitialClusterFromName(name string) (ret string) { |
| 564 |
if len(cfg.APUrls) == 0 { |
| 565 |
return "" |
| 566 |
} |
| 567 |
n := name |
| 568 |
if name == "" { |
| 569 |
n = DefaultName |
| 570 |
} |
| 571 |
for i := range cfg.APUrls { |
| 572 |
ret = ret + "," + n + "=" + cfg.APUrls[i].String() |
| 573 |
} |
| 574 |
return ret[1:] |
| 575 |
} |
| 576 |
|
| 577 |
func (cfg Config) IsNewCluster() bool { return cfg.ClusterState == ClusterStateFlagNew } |
| 578 |
func (cfg Config) ElectionTicks() int { return int(cfg.ElectionMs / cfg.TickMs) } |
| 579 |
|
| 580 |
func (cfg Config) defaultPeerHost() bool { |
| 581 |
return len(cfg.APUrls) == 1 && cfg.APUrls[0].String() == DefaultInitialAdvertisePeerURLs |
| 582 |
} |
| 583 |
|
| 584 |
func (cfg Config) defaultClientHost() bool { |
| 585 |
return len(cfg.ACUrls) == 1 && cfg.ACUrls[0].String() == DefaultAdvertiseClientURLs |
| 586 |
} |
| 587 |
|
| 588 |
func (cfg *Config) ClientSelfCert() (err error) { |
| 589 |
if !cfg.ClientAutoTLS { |
| 590 |
return nil |
| 591 |
} |
| 592 |
if !cfg.ClientTLSInfo.Empty() { |
| 593 |
plog.Warningf("ignoring client auto TLS since certs given") |
| 594 |
return nil |
| 595 |
} |
| 596 |
chosts := make([]string, len(cfg.LCUrls)) |
| 597 |
for i, u := range cfg.LCUrls { |
| 598 |
chosts[i] = u.Host |
| 599 |
} |
| 600 |
cfg.ClientTLSInfo, err = transport.SelfCert(filepath.Join(cfg.Dir, "fixtures", "client"), chosts) |
| 601 |
if err != nil { |
| 602 |
return err |
| 603 |
} |
| 604 |
return updateCipherSuites(&cfg.ClientTLSInfo, cfg.CipherSuites) |
| 605 |
} |
| 606 |
|
| 607 |
func (cfg *Config) PeerSelfCert() (err error) { |
| 608 |
if !cfg.PeerAutoTLS { |
| 609 |
return nil |
| 610 |
} |
| 611 |
if !cfg.PeerTLSInfo.Empty() { |
| 612 |
plog.Warningf("ignoring peer auto TLS since certs given") |
| 613 |
return nil |
| 614 |
} |
| 615 |
phosts := make([]string, len(cfg.LPUrls)) |
| 616 |
for i, u := range cfg.LPUrls { |
| 617 |
phosts[i] = u.Host |
| 618 |
} |
| 619 |
cfg.PeerTLSInfo, err = transport.SelfCert(filepath.Join(cfg.Dir, "fixtures", "peer"), phosts) |
| 620 |
if err != nil { |
| 621 |
return err |
| 622 |
} |
| 623 |
return updateCipherSuites(&cfg.PeerTLSInfo, cfg.CipherSuites) |
| 624 |
} |
| 625 |
|
| 626 |
// UpdateDefaultClusterFromName updates cluster advertise URLs with, if available, default host, |
| 627 |
// if advertise URLs are default values(localhost:2379,2380) AND if listen URL is 0.0.0.0. |
| 628 |
// e.g. advertise peer URL localhost:2380 or listen peer URL 0.0.0.0:2380 |
| 629 |
// then the advertise peer host would be updated with machine's default host, |
| 630 |
// while keeping the listen URL's port. |
| 631 |
// User can work around this by explicitly setting URL with 127.0.0.1. |
| 632 |
// It returns the default hostname, if used, and the error, if any, from getting the machine's default host. |
| 633 |
// TODO: check whether fields are set instead of whether fields have default value |
| 634 |
func (cfg *Config) UpdateDefaultClusterFromName(defaultInitialCluster string) (string, error) { |
| 635 |
if defaultHostname == "" || defaultHostStatus != nil { |
| 636 |
// update 'initial-cluster' when only the name is specified (e.g. 'etcd --name=abc') |
| 637 |
if cfg.Name != DefaultName && cfg.InitialCluster == defaultInitialCluster { |
| 638 |
cfg.InitialCluster = cfg.InitialClusterFromName(cfg.Name) |
| 639 |
} |
| 640 |
return "", defaultHostStatus |
| 641 |
} |
| 642 |
|
| 643 |
used := false |
| 644 |
pip, pport := cfg.LPUrls[0].Hostname(), cfg.LPUrls[0].Port() |
| 645 |
if cfg.defaultPeerHost() && pip == "0.0.0.0" { |
| 646 |
cfg.APUrls[0] = url.URL{Scheme: cfg.APUrls[0].Scheme, Host: fmt.Sprintf("%s:%s", defaultHostname, pport)} |
| 647 |
used = true |
| 648 |
} |
| 649 |
// update 'initial-cluster' when only the name is specified (e.g. 'etcd --name=abc') |
| 650 |
if cfg.Name != DefaultName && cfg.InitialCluster == defaultInitialCluster { |
| 651 |
cfg.InitialCluster = cfg.InitialClusterFromName(cfg.Name) |
| 652 |
} |
| 653 |
|
| 654 |
cip, cport := cfg.LCUrls[0].Hostname(), cfg.LCUrls[0].Port() |
| 655 |
if cfg.defaultClientHost() && cip == "0.0.0.0" { |
| 656 |
cfg.ACUrls[0] = url.URL{Scheme: cfg.ACUrls[0].Scheme, Host: fmt.Sprintf("%s:%s", defaultHostname, cport)} |
| 657 |
used = true |
| 658 |
} |
| 659 |
dhost := defaultHostname |
| 660 |
if !used { |
| 661 |
dhost = "" |
| 662 |
} |
| 663 |
return dhost, defaultHostStatus |
| 664 |
} |
| 665 |
|
| 666 |
// checkBindURLs returns an error if any URL uses a domain name. |
| 667 |
func checkBindURLs(urls []url.URL) error { |
| 668 |
for _, url := range urls { |
| 669 |
if url.Scheme == "unix" || url.Scheme == "unixs" { |
| 670 |
continue |
| 671 |
} |
| 672 |
host, _, err := net.SplitHostPort(url.Host) |
| 673 |
if err != nil { |
| 674 |
return err |
| 675 |
} |
| 676 |
if host == "localhost" { |
| 677 |
// special case for local address |
| 678 |
// TODO: support /etc/hosts ? |
| 679 |
continue |
| 680 |
} |
| 681 |
if net.ParseIP(host) == nil { |
| 682 |
return fmt.Errorf("expected IP in URL for binding (%s)", url.String()) |
| 683 |
} |
| 684 |
} |
| 685 |
return nil |
| 686 |
} |
| 687 |
|
| 688 |
func checkHostURLs(urls []url.URL) error { |
| 689 |
for _, url := range urls { |
| 690 |
host, _, err := net.SplitHostPort(url.Host) |
| 691 |
if err != nil { |
| 692 |
return err |
| 693 |
} |
| 694 |
if host == "" { |
| 695 |
return fmt.Errorf("unexpected empty host (%s)", url.String()) |
| 696 |
} |
| 697 |
} |
| 698 |
return nil |
| 699 |
} |