Debian Codegraph @

vendor/github.com/coreos/etcd/etcdserver/server.go

raw
1 // Copyright 2015 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 etcdserver
16
17 import (
18 "context"
19 "encoding/json"
20 "expvar"
21 "fmt"
22 "math"
23 "math/rand"
24 "net/http"
25 "os"
26 "path"
27 "regexp"
28 "sync"
29 "sync/atomic"
30 "time"
31
32 "github.com/coreos/etcd/alarm"
33 "github.com/coreos/etcd/auth"
34 "github.com/coreos/etcd/compactor"
35 "github.com/coreos/etcd/discovery"
36 "github.com/coreos/etcd/etcdserver/api"
37 "github.com/coreos/etcd/etcdserver/api/v2http/httptypes"
38 pb "github.com/coreos/etcd/etcdserver/etcdserverpb"
39 "github.com/coreos/etcd/etcdserver/membership"
40 "github.com/coreos/etcd/etcdserver/stats"
41 "github.com/coreos/etcd/lease"
42 "github.com/coreos/etcd/lease/leasehttp"
43 "github.com/coreos/etcd/mvcc"
44 "github.com/coreos/etcd/mvcc/backend"
45 "github.com/coreos/etcd/pkg/fileutil"
46 "github.com/coreos/etcd/pkg/idutil"
47 "github.com/coreos/etcd/pkg/pbutil"
48 "github.com/coreos/etcd/pkg/runtime"
49 "github.com/coreos/etcd/pkg/schedule"
50 "github.com/coreos/etcd/pkg/types"
51 "github.com/coreos/etcd/pkg/wait"
52 "github.com/coreos/etcd/raft"
53 "github.com/coreos/etcd/raft/raftpb"
54 "github.com/coreos/etcd/rafthttp"
55 "github.com/coreos/etcd/snap"
56 "github.com/coreos/etcd/store"
57 "github.com/coreos/etcd/version"
58 "github.com/coreos/etcd/wal"
59
60 "github.com/coreos/go-semver/semver"
61 "github.com/coreos/pkg/capnslog"
62 )
63
64 const (
65 DefaultSnapCount = 100000
66
67 StoreClusterPrefix = "/0"
68 StoreKeysPrefix = "/1"
69
70 // HealthInterval is the minimum time the cluster should be healthy
71 // before accepting add member requests.
72 HealthInterval = 5 * time.Second
73
74 purgeFileInterval = 30 * time.Second
75 // monitorVersionInterval should be smaller than the timeout
76 // on the connection. Or we will not be able to reuse the connection
77 // (since it will timeout).
78 monitorVersionInterval = rafthttp.ConnWriteTimeout - time.Second
79
80 // max number of in-flight snapshot messages etcdserver allows to have
81 // This number is more than enough for most clusters with 5 machines.
82 maxInFlightMsgSnap = 16
83
84 releaseDelayAfterSnapshot = 30 * time.Second
85
86 // maxPendingRevokes is the maximum number of outstanding expired lease revocations.
87 maxPendingRevokes = 16
88
89 recommendedMaxRequestBytes = 10 * 1024 * 1024
90 )
91
92 var (
93 plog = capnslog.NewPackageLogger("github.com/coreos/etcd", "etcdserver")
94
95 storeMemberAttributeRegexp = regexp.MustCompile(path.Join(membership.StoreMembersPrefix, "[[:xdigit:]]{1,16}", "attributes"))
96 )
97
98 func init() {
99 rand.Seed(time.Now().UnixNano())
100
101 expvar.Publish(
102 "file_descriptor_limit",
103 expvar.Func(
104 func() interface{} {
105 n, _ := runtime.FDLimit()
106 return n
107 },
108 ),
109 )
110 }
111
112 type Response struct {
113 Term uint64
114 Index uint64
115 Event *store.Event
116 Watcher store.Watcher
117 Err error
118 }
119
120 type ServerV2 interface {
121 Server
122 // Do takes a V2 request and attempts to fulfill it, returning a Response.
123 Do(ctx context.Context, r pb.Request) (Response, error)
124 stats.Stats
125 ClientCertAuthEnabled() bool
126 }
127
128 type ServerV3 interface {
129 Server
130 ID() types.ID
131 RaftTimer
132 }
133
134 func (s *EtcdServer) ClientCertAuthEnabled() bool { return s.Cfg.ClientCertAuthEnabled }
135
136 type Server interface {
137 // Leader returns the ID of the leader Server.
138 Leader() types.ID
139
140 // AddMember attempts to add a member into the cluster. It will return
141 // ErrIDRemoved if member ID is removed from the cluster, or return
142 // ErrIDExists if member ID exists in the cluster.
143 AddMember(ctx context.Context, memb membership.Member) ([]*membership.Member, error)
144 // RemoveMember attempts to remove a member from the cluster. It will
145 // return ErrIDRemoved if member ID is removed from the cluster, or return
146 // ErrIDNotFound if member ID is not in the cluster.
147 RemoveMember(ctx context.Context, id uint64) ([]*membership.Member, error)
148 // UpdateMember attempts to update an existing member in the cluster. It will
149 // return ErrIDNotFound if the member ID does not exist.
150 UpdateMember(ctx context.Context, updateMemb membership.Member) ([]*membership.Member, error)
151
152 // ClusterVersion is the cluster-wide minimum major.minor version.
153 // Cluster version is set to the min version that an etcd member is
154 // compatible with when first bootstrap.
155 //
156 // ClusterVersion is nil until the cluster is bootstrapped (has a quorum).
157 //
158 // During a rolling upgrades, the ClusterVersion will be updated
159 // automatically after a sync. (5 second by default)
160 //
161 // The API/raft component can utilize ClusterVersion to determine if
162 // it can accept a client request or a raft RPC.
163 // NOTE: ClusterVersion might be nil when etcd 2.1 works with etcd 2.0 and
164 // the leader is etcd 2.0. etcd 2.0 leader will not update clusterVersion since
165 // this feature is introduced post 2.0.
166 ClusterVersion() *semver.Version
167 Cluster() api.Cluster
168 Alarms() []*pb.AlarmMember
169 }
170
171 // EtcdServer is the production implementation of the Server interface
172 type EtcdServer struct {
173 // inflightSnapshots holds count the number of snapshots currently inflight.
174 inflightSnapshots int64 // must use atomic operations to access; keep 64-bit aligned.
175 appliedIndex uint64 // must use atomic operations to access; keep 64-bit aligned.
176 committedIndex uint64 // must use atomic operations to access; keep 64-bit aligned.
177 // consistIndex used to hold the offset of current executing entry
178 // It is initialized to 0 before executing any entry.
179 consistIndex consistentIndex // must use atomic operations to access; keep 64-bit aligned.
180 r raftNode // uses 64-bit atomics; keep 64-bit aligned.
181
182 readych chan struct{}
183 Cfg ServerConfig
184
185 w wait.Wait
186
187 readMu sync.RWMutex
188 // read routine notifies etcd server that it waits for reading by sending an empty struct to
189 // readwaitC
190 readwaitc chan struct{}
191 // readNotifier is used to notify the read routine that it can process the request
192 // when there is no error
193 readNotifier *notifier
194
195 // stop signals the run goroutine should shutdown.
196 stop chan struct{}
197 // stopping is closed by run goroutine on shutdown.
198 stopping chan struct{}
199 // done is closed when all goroutines from start() complete.
200 done chan struct{}
201
202 errorc chan error
203 id types.ID
204 attributes membership.Attributes
205
206 cluster *membership.RaftCluster
207
208 store store.Store
209 snapshotter *snap.Snapshotter
210
211 applyV2 ApplierV2
212
213 // applyV3 is the applier with auth and quotas
214 applyV3 applierV3
215 // applyV3Base is the core applier without auth or quotas
216 applyV3Base applierV3
217 applyWait wait.WaitTime
218
219 kv mvcc.ConsistentWatchableKV
220 lessor lease.Lessor
221 bemu sync.Mutex
222 be backend.Backend
223 authStore auth.AuthStore
224 alarmStore *alarm.AlarmStore
225
226 stats *stats.ServerStats
227 lstats *stats.LeaderStats
228
229 SyncTicker *time.Ticker
230 // compactor is used to auto-compact the KV.
231 compactor compactor.Compactor
232
233 // peerRt used to send requests (version, lease) to peers.
234 peerRt http.RoundTripper
235 reqIDGen *idutil.Generator
236
237 // forceVersionC is used to force the version monitor loop
238 // to detect the cluster version immediately.
239 forceVersionC chan struct{}
240
241 // wgMu blocks concurrent waitgroup mutation while server stopping
242 wgMu sync.RWMutex
243 // wg is used to wait for the go routines that depends on the server state
244 // to exit when stopping the server.
245 wg sync.WaitGroup
246
247 // ctx is used for etcd-initiated requests that may need to be canceled
248 // on etcd server shutdown.
249 ctx context.Context
250 cancel context.CancelFunc
251
252 leadTimeMu sync.RWMutex
253 leadElectedTime time.Time
254 }
255
256 // NewServer creates a new EtcdServer from the supplied configuration. The
257 // configuration is considered static for the lifetime of the EtcdServer.
258 func NewServer(cfg ServerConfig) (srv *EtcdServer, err error) {
259 st := store.New(StoreClusterPrefix, StoreKeysPrefix)
260
261 var (
262 w *wal.WAL
263 n raft.Node
264 s *raft.MemoryStorage
265 id types.ID
266 cl *membership.RaftCluster
267 )
268
269 if cfg.MaxRequestBytes > recommendedMaxRequestBytes {
270 plog.Warningf("MaxRequestBytes %v exceeds maximum recommended size %v", cfg.MaxRequestBytes, recommendedMaxRequestBytes)
271 }
272
273 if terr := fileutil.TouchDirAll(cfg.DataDir); terr != nil {
274 return nil, fmt.Errorf("cannot access data directory: %v", terr)
275 }
276
277 haveWAL := wal.Exist(cfg.WALDir())
278
279 if err = fileutil.TouchDirAll(cfg.SnapDir()); err != nil {
280 plog.Fatalf("create snapshot directory error: %v", err)
281 }
282 ss := snap.New(cfg.SnapDir())
283
284 bepath := cfg.backendPath()
285 beExist := fileutil.Exist(bepath)
286 be := openBackend(cfg)
287
288 defer func() {
289 if err != nil {
290 be.Close()
291 }
292 }()
293
294 prt, err := rafthttp.NewRoundTripper(cfg.PeerTLSInfo, cfg.peerDialTimeout())
295 if err != nil {
296 return nil, err
297 }
298 var (
299 remotes []*membership.Member
300 snapshot *raftpb.Snapshot
301 )
302
303 switch {
304 case !haveWAL && !cfg.NewCluster:
305 if err = cfg.VerifyJoinExisting(); err != nil {
306 return nil, err
307 }
308 cl, err = membership.NewClusterFromURLsMap(cfg.InitialClusterToken, cfg.InitialPeerURLsMap)
309 if err != nil {
310 return nil, err
311 }
312 existingCluster, gerr := GetClusterFromRemotePeers(getRemotePeerURLs(cl, cfg.Name), prt)
313 if gerr != nil {
314 return nil, fmt.Errorf("cannot fetch cluster info from peer urls: %v", gerr)
315 }
316 if err = membership.ValidateClusterAndAssignIDs(cl, existingCluster); err != nil {
317 return nil, fmt.Errorf("error validating peerURLs %s: %v", existingCluster, err)
318 }
319 if !isCompatibleWithCluster(cl, cl.MemberByName(cfg.Name).ID, prt) {
320 return nil, fmt.Errorf("incompatible with current running cluster")
321 }
322
323 remotes = existingCluster.Members()
324 cl.SetID(existingCluster.ID())
325 cl.SetStore(st)
326 cl.SetBackend(be)
327 cfg.Print()
328 id, n, s, w = startNode(cfg, cl, nil)
329 case !haveWAL && cfg.NewCluster:
330 if err = cfg.VerifyBootstrap(); err != nil {
331 return nil, err
332 }
333 cl, err = membership.NewClusterFromURLsMap(cfg.InitialClusterToken, cfg.InitialPeerURLsMap)
334 if err != nil {
335 return nil, err
336 }
337 m := cl.MemberByName(cfg.Name)
338 if isMemberBootstrapped(cl, cfg.Name, prt, cfg.bootstrapTimeout()) {
339 return nil, fmt.Errorf("member %s has already been bootstrapped", m.ID)
340 }
341 if cfg.ShouldDiscover() {
342 var str string
343 str, err = discovery.JoinCluster(cfg.DiscoveryURL, cfg.DiscoveryProxy, m.ID, cfg.InitialPeerURLsMap.String())
344 if err != nil {
345 return nil, &DiscoveryError{Op: "join", Err: err}
346 }
347 var urlsmap types.URLsMap
348 urlsmap, err = types.NewURLsMap(str)
349 if err != nil {
350 return nil, err
351 }
352 if checkDuplicateURL(urlsmap) {
353 return nil, fmt.Errorf("discovery cluster %s has duplicate url", urlsmap)
354 }
355 if cl, err = membership.NewClusterFromURLsMap(cfg.InitialClusterToken, urlsmap); err != nil {
356 return nil, err
357 }
358 }
359 cl.SetStore(st)
360 cl.SetBackend(be)
361 cfg.PrintWithInitial()
362 id, n, s, w = startNode(cfg, cl, cl.MemberIDs())
363 case haveWAL:
364 if err = fileutil.IsDirWriteable(cfg.MemberDir()); err != nil {
365 return nil, fmt.Errorf("cannot write to member directory: %v", err)
366 }
367
368 if err = fileutil.IsDirWriteable(cfg.WALDir()); err != nil {
369 return nil, fmt.Errorf("cannot write to WAL directory: %v", err)
370 }
371
372 if cfg.ShouldDiscover() {
373 plog.Warningf("discovery token ignored since a cluster has already been initialized. Valid log found at %q", cfg.WALDir())
374 }
375 snapshot, err = ss.Load()
376 if err != nil && err != snap.ErrNoSnapshot {
377 return nil, err
378 }
379 if snapshot != nil {
380 if err = st.Recovery(snapshot.Data); err != nil {
381 plog.Panicf("recovered store from snapshot error: %v", err)
382 }
383 plog.Infof("recovered store from snapshot at index %d", snapshot.Metadata.Index)
384 if be, err = recoverSnapshotBackend(cfg, be, *snapshot); err != nil {
385 plog.Panicf("recovering backend from snapshot error: %v", err)
386 }
387 }
388 cfg.Print()
389 if !cfg.ForceNewCluster {
390 id, cl, n, s, w = restartNode(cfg, snapshot)
391 } else {
392 id, cl, n, s, w = restartAsStandaloneNode(cfg, snapshot)
393 }
394 cl.SetStore(st)
395 cl.SetBackend(be)
396 cl.Recover(api.UpdateCapability)
397 if cl.Version() != nil && !cl.Version().LessThan(semver.Version{Major: 3}) && !beExist {
398 os.RemoveAll(bepath)
399 return nil, fmt.Errorf("database file (%v) of the backend is missing", bepath)
400 }
401 default:
402 return nil, fmt.Errorf("unsupported bootstrap config")
403 }
404
405 if terr := fileutil.TouchDirAll(cfg.MemberDir()); terr != nil {
406 return nil, fmt.Errorf("cannot access member directory: %v", terr)
407 }
408
409 sstats := stats.NewServerStats(cfg.Name, id.String())
410 lstats := stats.NewLeaderStats(id.String())
411
412 heartbeat := time.Duration(cfg.TickMs) * time.Millisecond
413 srv = &EtcdServer{
414 readych: make(chan struct{}),
415 Cfg: cfg,
416 errorc: make(chan error, 1),
417 store: st,
418 snapshotter: ss,
419 r: *newRaftNode(
420 raftNodeConfig{
421 isIDRemoved: func(id uint64) bool { return cl.IsIDRemoved(types.ID(id)) },
422 Node: n,
423 heartbeat: heartbeat,
424 raftStorage: s,
425 storage: NewStorage(w, ss),
426 },
427 ),
428 id: id,
429 attributes: membership.Attributes{Name: cfg.Name, ClientURLs: cfg.ClientURLs.StringSlice()},
430 cluster: cl,
431 stats: sstats,
432 lstats: lstats,
433 SyncTicker: time.NewTicker(500 * time.Millisecond),
434 peerRt: prt,
435 reqIDGen: idutil.NewGenerator(uint16(id), time.Now()),
436 forceVersionC: make(chan struct{}),
437 }
438
439 srv.applyV2 = &applierV2store{store: srv.store, cluster: srv.cluster}
440
441 srv.be = be
442 minTTL := time.Duration((3*cfg.ElectionTicks)/2) * heartbeat
443
444 // always recover lessor before kv. When we recover the mvcc.KV it will reattach keys to its leases.
445 // If we recover mvcc.KV first, it will attach the keys to the wrong lessor before it recovers.
446 srv.lessor = lease.NewLessor(srv.be, int64(math.Ceil(minTTL.Seconds())))
447 srv.kv = mvcc.New(srv.be, srv.lessor, &srv.consistIndex)
448 if beExist {
449 kvindex := srv.kv.ConsistentIndex()
450 // TODO: remove kvindex != 0 checking when we do not expect users to upgrade
451 // etcd from pre-3.0 release.
452 if snapshot != nil && kvindex < snapshot.Metadata.Index {
453 if kvindex != 0 {
454 return nil, fmt.Errorf("database file (%v index %d) does not match with snapshot (index %d).", bepath, kvindex, snapshot.Metadata.Index)
455 }
456 plog.Warningf("consistent index never saved (snapshot index=%d)", snapshot.Metadata.Index)
457 }
458 }
459 newSrv := srv // since srv == nil in defer if srv is returned as nil
460 defer func() {
461 // closing backend without first closing kv can cause
462 // resumed compactions to fail with closed tx errors
463 if err != nil {
464 newSrv.kv.Close()
465 }
466 }()
467
468 srv.consistIndex.setConsistentIndex(srv.kv.ConsistentIndex())
469 tp, err := auth.NewTokenProvider(cfg.AuthToken,
470 func(index uint64) <-chan struct{} {
471 return srv.applyWait.Wait(index)
472 },
473 )
474 if err != nil {
475 plog.Errorf("failed to create token provider: %s", err)
476 return nil, err
477 }
478 srv.authStore = auth.NewAuthStore(srv.be, tp)
479 if num := cfg.AutoCompactionRetention; num != 0 {
480 srv.compactor, err = compactor.New(cfg.AutoCompactionMode, num, srv.kv, srv)
481 if err != nil {
482 return nil, err
483 }
484 srv.compactor.Run()
485 }
486
487 srv.applyV3Base = srv.newApplierV3Backend()
488 if err = srv.restoreAlarms(); err != nil {
489 return nil, err
490 }
491
492 // TODO: move transport initialization near the definition of remote
493 tr := &rafthttp.Transport{
494 TLSInfo: cfg.PeerTLSInfo,
495 DialTimeout: cfg.peerDialTimeout(),
496 ID: id,
497 URLs: cfg.PeerURLs,
498 ClusterID: cl.ID(),
499 Raft: srv,
500 Snapshotter: ss,
501 ServerStats: sstats,
502 LeaderStats: lstats,
503 ErrorC: srv.errorc,
504 }
505 if err = tr.Start(); err != nil {
506 return nil, err
507 }
508 // add all remotes into transport
509 for _, m := range remotes {
510 if m.ID != id {
511 tr.AddRemote(m.ID, m.PeerURLs)
512 }
513 }
514 for _, m := range cl.Members() {
515 if m.ID != id {
516 tr.AddPeer(m.ID, m.PeerURLs)
517 }
518 }
519 srv.r.transport = tr
520
521 return srv, nil
522 }
523
524 func (s *EtcdServer) adjustTicks() {
525 clusterN := len(s.cluster.Members())
526
527 // single-node fresh start, or single-node recovers from snapshot
528 if clusterN == 1 {
529 ticks := s.Cfg.ElectionTicks - 1
530 plog.Infof("%s as single-node; fast-forwarding %d ticks (election ticks %d)", s.ID(), ticks, s.Cfg.ElectionTicks)
531 s.r.advanceTicks(ticks)
532 return
533 }
534
535 if !s.Cfg.InitialElectionTickAdvance {
536 plog.Infof("skipping initial election tick advance (election tick %d)", s.Cfg.ElectionTicks)
537 return
538 }
539
540 // retry up to "rafthttp.ConnReadTimeout", which is 5-sec
541 // until peer connection reports; otherwise:
542 // 1. all connections failed, or
543 // 2. no active peers, or
544 // 3. restarted single-node with no snapshot
545 // then, do nothing, because advancing ticks would have no effect
546 waitTime := rafthttp.ConnReadTimeout
547 itv := 50 * time.Millisecond
548 for i := int64(0); i < int64(waitTime/itv); i++ {
549 select {
550 case <-time.After(itv):
551 case <-s.stopping:
552 return
553 }
554
555 peerN := s.r.transport.ActivePeers()
556 if peerN > 1 {
557 // multi-node received peer connection reports
558 // adjust ticks, in case slow leader message receive
559 ticks := s.Cfg.ElectionTicks - 2
560 plog.Infof("%s initialzed peer connection; fast-forwarding %d ticks (election ticks %d) with %d active peer(s)", s.ID(), ticks, s.Cfg.ElectionTicks, peerN)
561 s.r.advanceTicks(ticks)
562 return
563 }
564 }
565 }
566
567 // Start performs any initialization of the Server necessary for it to
568 // begin serving requests. It must be called before Do or Process.
569 // Start must be non-blocking; any long-running server functionality
570 // should be implemented in goroutines.
571 func (s *EtcdServer) Start() {
572 s.start()
573 s.goAttach(func() { s.adjustTicks() })
574 s.goAttach(func() { s.publish(s.Cfg.ReqTimeout()) })
575 s.goAttach(s.purgeFile)
576 s.goAttach(func() { monitorFileDescriptor(s.stopping) })
577 s.goAttach(s.monitorVersions)
578 s.goAttach(s.linearizableReadLoop)
579 s.goAttach(s.monitorKVHash)
580 }
581
582 // start prepares and starts server in a new goroutine. It is no longer safe to
583 // modify a server's fields after it has been sent to Start.
584 // This function is just used for testing.
585 func (s *EtcdServer) start() {
586 if s.Cfg.SnapCount == 0 {
587 plog.Infof("set snapshot count to default %d", DefaultSnapCount)
588 s.Cfg.SnapCount = DefaultSnapCount
589 }
590 s.w = wait.New()
591 s.applyWait = wait.NewTimeList()
592 s.done = make(chan struct{})
593 s.stop = make(chan struct{})
594 s.stopping = make(chan struct{})
595 s.ctx, s.cancel = context.WithCancel(context.Background())
596 s.readwaitc = make(chan struct{}, 1)
597 s.readNotifier = newNotifier()
598 if s.ClusterVersion() != nil {
599 plog.Infof("starting server... [version: %v, cluster version: %v]", version.Version, version.Cluster(s.ClusterVersion().String()))
600 } else {
601 plog.Infof("starting server... [version: %v, cluster version: to_be_decided]", version.Version)
602 }
603 // TODO: if this is an empty log, writes all peer infos
604 // into the first entry
605 go s.run()
606 }
607
608 func (s *EtcdServer) purgeFile() {
609 var dberrc, serrc, werrc <-chan error
610 if s.Cfg.MaxSnapFiles > 0 {
611 dberrc = fileutil.PurgeFile(s.Cfg.SnapDir(), "snap.db", s.Cfg.MaxSnapFiles, purgeFileInterval, s.done)
612 serrc = fileutil.PurgeFile(s.Cfg.SnapDir(), "snap", s.Cfg.MaxSnapFiles, purgeFileInterval, s.done)
613 }
614 if s.Cfg.MaxWALFiles > 0 {
615 werrc = fileutil.PurgeFile(s.Cfg.WALDir(), "wal", s.Cfg.MaxWALFiles, purgeFileInterval, s.done)
616 }
617 select {
618 case e := <-dberrc:
619 plog.Fatalf("failed to purge snap db file %v", e)
620 case e := <-serrc:
621 plog.Fatalf("failed to purge snap file %v", e)
622 case e := <-werrc:
623 plog.Fatalf("failed to purge wal file %v", e)
624 case <-s.stopping:
625 return
626 }
627 }
628
629 func (s *EtcdServer) ID() types.ID { return s.id }
630
631 func (s *EtcdServer) Cluster() api.Cluster { return s.cluster }
632
633 func (s *EtcdServer) ApplyWait() <-chan struct{} { return s.applyWait.Wait(s.getCommittedIndex()) }
634
635 type ServerPeer interface {
636 ServerV2
637 RaftHandler() http.Handler
638 LeaseHandler() http.Handler
639 }
640
641 func (s *EtcdServer) LeaseHandler() http.Handler {
642 if s.lessor == nil {
643 return nil
644 }
645 return leasehttp.NewHandler(s.lessor, s.ApplyWait)
646 }
647
648 func (s *EtcdServer) RaftHandler() http.Handler { return s.r.transport.Handler() }
649
650 // Process takes a raft message and applies it to the server's raft state
651 // machine, respecting any timeout of the given context.
652 func (s *EtcdServer) Process(ctx context.Context, m raftpb.Message) error {
653 if s.cluster.IsIDRemoved(types.ID(m.From)) {
654 plog.Warningf("reject message from removed member %s", types.ID(m.From).String())
655 return httptypes.NewHTTPError(http.StatusForbidden, "cannot process message from removed member")
656 }
657 if m.Type == raftpb.MsgApp {
658 s.stats.RecvAppendReq(types.ID(m.From).String(), m.Size())
659 }
660 return s.r.Step(ctx, m)
661 }
662
663 func (s *EtcdServer) IsIDRemoved(id uint64) bool { return s.cluster.IsIDRemoved(types.ID(id)) }
664
665 func (s *EtcdServer) ReportUnreachable(id uint64) { s.r.ReportUnreachable(id) }
666
667 // ReportSnapshot reports snapshot sent status to the raft state machine,
668 // and clears the used snapshot from the snapshot store.
669 func (s *EtcdServer) ReportSnapshot(id uint64, status raft.SnapshotStatus) {
670 s.r.ReportSnapshot(id, status)
671 }
672
673 type etcdProgress struct {
674 confState raftpb.ConfState
675 snapi uint64
676 appliedt uint64
677 appliedi uint64
678 }
679
680 // raftReadyHandler contains a set of EtcdServer operations to be called by raftNode,
681 // and helps decouple state machine logic from Raft algorithms.
682 // TODO: add a state machine interface to apply the commit entries and do snapshot/recover
683 type raftReadyHandler struct {
684 updateLeadership func(newLeader bool)
685 updateCommittedIndex func(uint64)
686 }
687
688 func (s *EtcdServer) run() {
689 sn, err := s.r.raftStorage.Snapshot()
690 if err != nil {
691 plog.Panicf("get snapshot from raft storage error: %v", err)
692 }
693
694 // asynchronously accept apply packets, dispatch progress in-order
695 sched := schedule.NewFIFOScheduler()
696
697 var (
698 smu sync.RWMutex
699 syncC <-chan time.Time
700 )
701 setSyncC := func(ch <-chan time.Time) {
702 smu.Lock()
703 syncC = ch
704 smu.Unlock()
705 }
706 getSyncC := func() (ch <-chan time.Time) {
707 smu.RLock()
708 ch = syncC
709 smu.RUnlock()
710 return
711 }
712 rh := &raftReadyHandler{
713 updateLeadership: func(newLeader bool) {
714 if !s.isLeader() {
715 if s.lessor != nil {
716 s.lessor.Demote()
717 }
718 if s.compactor != nil {
719 s.compactor.Pause()
720 }
721 setSyncC(nil)
722 } else {
723 if newLeader {
724 t := time.Now()
725 s.leadTimeMu.Lock()
726 s.leadElectedTime = t
727 s.leadTimeMu.Unlock()
728 }
729 setSyncC(s.SyncTicker.C)
730 if s.compactor != nil {
731 s.compactor.Resume()
732 }
733 }
734
735 // TODO: remove the nil checking
736 // current test utility does not provide the stats
737 if s.stats != nil {
738 s.stats.BecomeLeader()
739 }
740 },
741 updateCommittedIndex: func(ci uint64) {
742 cci := s.getCommittedIndex()
743 if ci > cci {
744 s.setCommittedIndex(ci)
745 }
746 },
747 }
748 s.r.start(rh)
749
750 ep := etcdProgress{
751 confState: sn.Metadata.ConfState,
752 snapi: sn.Metadata.Index,
753 appliedt: sn.Metadata.Term,
754 appliedi: sn.Metadata.Index,
755 }
756
757 defer func() {
758 s.wgMu.Lock() // block concurrent waitgroup adds in goAttach while stopping
759 close(s.stopping)
760 s.wgMu.Unlock()
761 s.cancel()
762
763 sched.Stop()
764
765 // wait for gouroutines before closing raft so wal stays open
766 s.wg.Wait()
767
768 s.SyncTicker.Stop()
769
770 // must stop raft after scheduler-- etcdserver can leak rafthttp pipelines
771 // by adding a peer after raft stops the transport
772 s.r.stop()
773
774 // kv, lessor and backend can be nil if running without v3 enabled
775 // or running unit tests.
776 if s.lessor != nil {
777 s.lessor.Stop()
778 }
779 if s.kv != nil {
780 s.kv.Close()
781 }
782 if s.authStore != nil {
783 s.authStore.Close()
784 }
785 if s.be != nil {
786 s.be.Close()
787 }
788 if s.compactor != nil {
789 s.compactor.Stop()
790 }
791 close(s.done)
792 }()
793
794 var expiredLeaseC <-chan []*lease.Lease
795 if s.lessor != nil {
796 expiredLeaseC = s.lessor.ExpiredLeasesC()
797 }
798
799 for {
800 select {
801 case ap := <-s.r.apply():
802 f := func(context.Context) { s.applyAll(&ep, &ap) }
803 sched.Schedule(f)
804 case leases := <-expiredLeaseC:
805 s.goAttach(func() {
806 // Increases throughput of expired leases deletion process through parallelization
807 c := make(chan struct{}, maxPendingRevokes)
808 for _, lease := range leases {
809 select {
810 case c <- struct{}{}:
811 case <-s.stopping:
812 return
813 }
814 lid := lease.ID
815 s.goAttach(func() {
816 ctx := s.authStore.WithRoot(s.ctx)
817 _, lerr := s.LeaseRevoke(ctx, &pb.LeaseRevokeRequest{ID: int64(lid)})
818 if lerr == nil {
819 leaseExpired.Inc()
820 } else {
821 plog.Warningf("failed to revoke %016x (%q)", lid, lerr.Error())
822 }
823
824 <-c
825 })
826 }
827 })
828 case err := <-s.errorc:
829 plog.Errorf("%s", err)
830 plog.Infof("the data-dir used by this member must be removed.")
831 return
832 case <-getSyncC():
833 if s.store.HasTTLKeys() {
834 s.sync(s.Cfg.ReqTimeout())
835 }
836 case <-s.stop:
837 return
838 }
839 }
840 }
841
842 func (s *EtcdServer) applyAll(ep *etcdProgress, apply *apply) {
843 s.applySnapshot(ep, apply)
844 s.applyEntries(ep, apply)
845
846 proposalsApplied.Set(float64(ep.appliedi))
847 s.applyWait.Trigger(ep.appliedi)
848 // wait for the raft routine to finish the disk writes before triggering a
849 // snapshot. or applied index might be greater than the last index in raft
850 // storage, since the raft routine might be slower than apply routine.
851 <-apply.notifyc
852
853 s.triggerSnapshot(ep)
854 select {
855 // snapshot requested via send()
856 case m := <-s.r.msgSnapC:
857 merged := s.createMergedSnapshotMessage(m, ep.appliedt, ep.appliedi, ep.confState)
858 s.sendMergedSnap(merged)
859 default:
860 }
861 }
862
863 func (s *EtcdServer) applySnapshot(ep *etcdProgress, apply *apply) {
864 if raft.IsEmptySnap(apply.snapshot) {
865 return
866 }
867
868 plog.Infof("applying snapshot at index %d...", ep.snapi)
869 defer plog.Infof("finished applying incoming snapshot at index %d", ep.snapi)
870
871 if apply.snapshot.Metadata.Index <= ep.appliedi {
872 plog.Panicf("snapshot index [%d] should > appliedi[%d] + 1",
873 apply.snapshot.Metadata.Index, ep.appliedi)
874 }
875
876 // wait for raftNode to persist snapshot onto the disk
877 <-apply.notifyc
878
879 newbe, err := openSnapshotBackend(s.Cfg, s.snapshotter, apply.snapshot)
880 if err != nil {
881 plog.Panic(err)
882 }
883
884 // always recover lessor before kv. When we recover the mvcc.KV it will reattach keys to its leases.
885 // If we recover mvcc.KV first, it will attach the keys to the wrong lessor before it recovers.
886 if s.lessor != nil {
887 plog.Info("recovering lessor...")
888 s.lessor.Recover(newbe, func() lease.TxnDelete { return s.kv.Write() })
889 plog.Info("finished recovering lessor")
890 }
891
892 plog.Info("restoring mvcc store...")
893
894 if err := s.kv.Restore(newbe); err != nil {
895 plog.Panicf("restore KV error: %v", err)
896 }
897 s.consistIndex.setConsistentIndex(s.kv.ConsistentIndex())
898
899 plog.Info("finished restoring mvcc store")
900
901 // Closing old backend might block until all the txns
902 // on the backend are finished.
903 // We do not want to wait on closing the old backend.
904 s.bemu.Lock()
905 oldbe := s.be
906 go func() {
907 plog.Info("closing old backend...")
908 defer plog.Info("finished closing old backend")
909
910 if err := oldbe.Close(); err != nil {
911 plog.Panicf("close backend error: %v", err)
912 }
913 }()
914
915 s.be = newbe
916 s.bemu.Unlock()
917
918 plog.Info("recovering alarms...")
919 if err := s.restoreAlarms(); err != nil {
920 plog.Panicf("restore alarms error: %v", err)
921 }
922 plog.Info("finished recovering alarms")
923
924 if s.authStore != nil {
925 plog.Info("recovering auth store...")
926 s.authStore.Recover(newbe)
927 plog.Info("finished recovering auth store")
928 }
929
930 plog.Info("recovering store v2...")
931 if err := s.store.Recovery(apply.snapshot.Data); err != nil {
932 plog.Panicf("recovery store error: %v", err)
933 }
934 plog.Info("finished recovering store v2")
935
936 s.cluster.SetBackend(s.be)
937 plog.Info("recovering cluster configuration...")
938 s.cluster.Recover(api.UpdateCapability)
939 plog.Info("finished recovering cluster configuration")
940
941 plog.Info("removing old peers from network...")
942 // recover raft transport
943 s.r.transport.RemoveAllPeers()
944 plog.Info("finished removing old peers from network")
945
946 plog.Info("adding peers from new cluster configuration into network...")
947 for _, m := range s.cluster.Members() {
948 if m.ID == s.ID() {
949 continue
950 }
951 s.r.transport.AddPeer(m.ID, m.PeerURLs)
952 }
953 plog.Info("finished adding peers from new cluster configuration into network...")
954
955 ep.appliedt = apply.snapshot.Metadata.Term
956 ep.appliedi = apply.snapshot.Metadata.Index
957 ep.snapi = ep.appliedi
958 ep.confState = apply.snapshot.Metadata.ConfState
959 }
960
961 func (s *EtcdServer) applyEntries(ep *etcdProgress, apply *apply) {
962 if len(apply.entries) == 0 {
963 return
964 }
965 firsti := apply.entries[0].Index
966 if firsti > ep.appliedi+1 {
967 plog.Panicf("first index of committed entry[%d] should <= appliedi[%d] + 1", firsti, ep.appliedi)
968 }
969 var ents []raftpb.Entry
970 if ep.appliedi+1-firsti < uint64(len(apply.entries)) {
971 ents = apply.entries[ep.appliedi+1-firsti:]
972 }
973 if len(ents) == 0 {
974 return
975 }
976 var shouldstop bool
977 if ep.appliedt, ep.appliedi, shouldstop = s.apply(ents, &ep.confState); shouldstop {
978 go s.stopWithDelay(10*100*time.Millisecond, fmt.Errorf("the member has been permanently removed from the cluster"))
979 }
980 }
981
982 func (s *EtcdServer) triggerSnapshot(ep *etcdProgress) {
983 if ep.appliedi-ep.snapi <= s.Cfg.SnapCount {
984 return
985 }
986
987 plog.Infof("start to snapshot (applied: %d, lastsnap: %d)", ep.appliedi, ep.snapi)
988 s.snapshot(ep.appliedi, ep.confState)
989 ep.snapi = ep.appliedi
990 }
991
992 func (s *EtcdServer) isMultiNode() bool {
993 return s.cluster != nil && len(s.cluster.MemberIDs()) > 1
994 }
995
996 func (s *EtcdServer) isLeader() bool {
997 return uint64(s.ID()) == s.Lead()
998 }
999
1000 // MoveLeader transfers the leader to the given transferee.
1001 func (s *EtcdServer) MoveLeader(ctx context.Context, lead, transferee uint64) error {
1002 now := time.Now()
1003 interval := time.Duration(s.Cfg.TickMs) * time.Millisecond
1004
1005 plog.Infof("%s starts leadership transfer from %s to %s", s.ID(), types.ID(lead), types.ID(transferee))
1006 s.r.TransferLeadership(ctx, lead, transferee)
1007 for s.Lead() != transferee {
1008 select {
1009 case <-ctx.Done(): // time out
1010 return ErrTimeoutLeaderTransfer
1011 case <-time.After(interval):
1012 }
1013 }
1014
1015 // TODO: drain all requests, or drop all messages to the old leader
1016
1017 plog.Infof("%s finished leadership transfer from %s to %s (took %v)", s.ID(), types.ID(lead), types.ID(transferee), time.Since(now))
1018 return nil
1019 }
1020
1021 // TransferLeadership transfers the leader to the chosen transferee.
1022 func (s *EtcdServer) TransferLeadership() error {
1023 if !s.isLeader() {
1024 plog.Printf("skipped leadership transfer for stopping non-leader member")
1025 return nil
1026 }
1027
1028 if !s.isMultiNode() {
1029 plog.Printf("skipped leadership transfer for single member cluster")
1030 return nil
1031 }
1032
1033 transferee, ok := longestConnected(s.r.transport, s.cluster.MemberIDs())
1034 if !ok {
1035 return ErrUnhealthy
1036 }
1037
1038 tm := s.Cfg.ReqTimeout()
1039 ctx, cancel := context.WithTimeout(s.ctx, tm)
1040 err := s.MoveLeader(ctx, s.Lead(), uint64(transferee))
1041 cancel()
1042 return err
1043 }
1044
1045 // HardStop stops the server without coordination with other members in the cluster.
1046 func (s *EtcdServer) HardStop() {
1047 select {
1048 case s.stop <- struct{}{}:
1049 case <-s.done:
1050 return
1051 }
1052 <-s.done
1053 }
1054
1055 // Stop stops the server gracefully, and shuts down the running goroutine.
1056 // Stop should be called after a Start(s), otherwise it will block forever.
1057 // When stopping leader, Stop transfers its leadership to one of its peers
1058 // before stopping the server.
1059 // Stop terminates the Server and performs any necessary finalization.
1060 // Do and Process cannot be called after Stop has been invoked.
1061 func (s *EtcdServer) Stop() {
1062 if err := s.TransferLeadership(); err != nil {
1063 plog.Warningf("%s failed to transfer leadership (%v)", s.ID(), err)
1064 }
1065 s.HardStop()
1066 }
1067
1068 // ReadyNotify returns a channel that will be closed when the server
1069 // is ready to serve client requests
1070 func (s *EtcdServer) ReadyNotify() <-chan struct{} { return s.readych }
1071
1072 func (s *EtcdServer) stopWithDelay(d time.Duration, err error) {
1073 select {
1074 case <-time.After(d):
1075 case <-s.done:
1076 }
1077 select {
1078 case s.errorc <- err:
1079 default:
1080 }
1081 }
1082
1083 // StopNotify returns a channel that receives a empty struct
1084 // when the server is stopped.
1085 func (s *EtcdServer) StopNotify() <-chan struct{} { return s.done }
1086
1087 func (s *EtcdServer) SelfStats() []byte { return s.stats.JSON() }
1088
1089 func (s *EtcdServer) LeaderStats() []byte {
1090 lead := atomic.LoadUint64(&s.r.lead)
1091 if lead != uint64(s.id) {
1092 return nil
1093 }
1094 return s.lstats.JSON()
1095 }
1096
1097 func (s *EtcdServer) StoreStats() []byte { return s.store.JsonStats() }
1098
1099 func (s *EtcdServer) checkMembershipOperationPermission(ctx context.Context) error {
1100 if s.authStore == nil {
1101 // In the context of ordinary etcd process, s.authStore will never be nil.
1102 // This branch is for handling cases in server_test.go
1103 return nil
1104 }
1105
1106 // Note that this permission check is done in the API layer,
1107 // so TOCTOU problem can be caused potentially in a schedule like this:
1108 // update membership with user A -> revoke root role of A -> apply membership change
1109 // in the state machine layer
1110 // However, both of membership change and role management requires the root privilege.
1111 // So careful operation by admins can prevent the problem.
1112 authInfo, err := s.AuthInfoFromCtx(ctx)
1113 if err != nil {
1114 return err
1115 }
1116
1117 return s.AuthStore().IsAdminPermitted(authInfo)
1118 }
1119
1120 func (s *EtcdServer) AddMember(ctx context.Context, memb membership.Member) ([]*membership.Member, error) {
1121 if err := s.checkMembershipOperationPermission(ctx); err != nil {
1122 return nil, err
1123 }
1124
1125 if s.Cfg.StrictReconfigCheck {
1126 // by default StrictReconfigCheck is enabled; reject new members if unhealthy
1127 if !s.cluster.IsReadyToAddNewMember() {
1128 plog.Warningf("not enough started members, rejecting member add %+v", memb)
1129 return nil, ErrNotEnoughStartedMembers
1130 }
1131 if !isConnectedFullySince(s.r.transport, time.Now().Add(-HealthInterval), s.ID(), s.cluster.Members()) {
1132 plog.Warningf("not healthy for reconfigure, rejecting member add %+v", memb)
1133 return nil, ErrUnhealthy
1134 }
1135 }
1136
1137 // TODO: move Member to protobuf type
1138 b, err := json.Marshal(memb)
1139 if err != nil {
1140 return nil, err
1141 }
1142 cc := raftpb.ConfChange{
1143 Type: raftpb.ConfChangeAddNode,
1144 NodeID: uint64(memb.ID),
1145 Context: b,
1146 }
1147 return s.configure(ctx, cc)
1148 }
1149
1150 func (s *EtcdServer) RemoveMember(ctx context.Context, id uint64) ([]*membership.Member, error) {
1151 if err := s.checkMembershipOperationPermission(ctx); err != nil {
1152 return nil, err
1153 }
1154
1155 // by default StrictReconfigCheck is enabled; reject removal if leads to quorum loss
1156 if err := s.mayRemoveMember(types.ID(id)); err != nil {
1157 return nil, err
1158 }
1159
1160 cc := raftpb.ConfChange{
1161 Type: raftpb.ConfChangeRemoveNode,
1162 NodeID: id,
1163 }
1164 return s.configure(ctx, cc)
1165 }
1166
1167 func (s *EtcdServer) mayRemoveMember(id types.ID) error {
1168 if !s.Cfg.StrictReconfigCheck {
1169 return nil
1170 }
1171
1172 if !s.cluster.IsReadyToRemoveMember(uint64(id)) {
1173 plog.Warningf("not enough started members, rejecting remove member %s", id)
1174 return ErrNotEnoughStartedMembers
1175 }
1176
1177 // downed member is safe to remove since it's not part of the active quorum
1178 if t := s.r.transport.ActiveSince(id); id != s.ID() && t.IsZero() {
1179 return nil
1180 }
1181
1182 // protect quorum if some members are down
1183 m := s.cluster.Members()
1184 active := numConnectedSince(s.r.transport, time.Now().Add(-HealthInterval), s.ID(), m)
1185 if (active - 1) < 1+((len(m)-1)/2) {
1186 plog.Warningf("reconfigure breaks active quorum, rejecting remove member %s", id)
1187 return ErrUnhealthy
1188 }
1189
1190 return nil
1191 }
1192
1193 func (s *EtcdServer) UpdateMember(ctx context.Context, memb membership.Member) ([]*membership.Member, error) {
1194 b, merr := json.Marshal(memb)
1195 if merr != nil {
1196 return nil, merr
1197 }
1198
1199 if err := s.checkMembershipOperationPermission(ctx); err != nil {
1200 return nil, err
1201 }
1202 cc := raftpb.ConfChange{
1203 Type: raftpb.ConfChangeUpdateNode,
1204 NodeID: uint64(memb.ID),
1205 Context: b,
1206 }
1207 return s.configure(ctx, cc)
1208 }
1209
1210 // Implement the RaftTimer interface
1211
1212 func (s *EtcdServer) Index() uint64 { return atomic.LoadUint64(&s.r.index) }
1213
1214 func (s *EtcdServer) Term() uint64 { return atomic.LoadUint64(&s.r.term) }
1215
1216 // Lead is only for testing purposes.
1217 // TODO: add Raft server interface to expose raft related info:
1218 // Index, Term, Lead, Committed, Applied, LastIndex, etc.
1219 func (s *EtcdServer) Lead() uint64 { return atomic.LoadUint64(&s.r.lead) }
1220
1221 func (s *EtcdServer) Leader() types.ID { return types.ID(s.Lead()) }
1222
1223 type confChangeResponse struct {
1224 membs []*membership.Member
1225 err error
1226 }
1227
1228 // configure sends a configuration change through consensus and
1229 // then waits for it to be applied to the server. It
1230 // will block until the change is performed or there is an error.
1231 func (s *EtcdServer) configure(ctx context.Context, cc raftpb.ConfChange) ([]*membership.Member, error) {
1232 cc.ID = s.reqIDGen.Next()
1233 ch := s.w.Register(cc.ID)
1234 start := time.Now()
1235 if err := s.r.ProposeConfChange(ctx, cc); err != nil {
1236 s.w.Trigger(cc.ID, nil)
1237 return nil, err
1238 }
1239 select {
1240 case x := <-ch:
1241 if x == nil {
1242 plog.Panicf("configure trigger value should never be nil")
1243 }
1244 resp := x.(*confChangeResponse)
1245 return resp.membs, resp.err
1246 case <-ctx.Done():
1247 s.w.Trigger(cc.ID, nil) // GC wait
1248 return nil, s.parseProposeCtxErr(ctx.Err(), start)
1249 case <-s.stopping:
1250 return nil, ErrStopped
1251 }
1252 }
1253
1254 // sync proposes a SYNC request and is non-blocking.
1255 // This makes no guarantee that the request will be proposed or performed.
1256 // The request will be canceled after the given timeout.
1257 func (s *EtcdServer) sync(timeout time.Duration) {
1258 req := pb.Request{
1259 Method: "SYNC",
1260 ID: s.reqIDGen.Next(),
1261 Time: time.Now().UnixNano(),
1262 }
1263 data := pbutil.MustMarshal(&req)
1264 // There is no promise that node has leader when do SYNC request,
1265 // so it uses goroutine to propose.
1266 ctx, cancel := context.WithTimeout(s.ctx, timeout)
1267 s.goAttach(func() {
1268 s.r.Propose(ctx, data)
1269 cancel()
1270 })
1271 }
1272
1273 // publish registers server information into the cluster. The information
1274 // is the JSON representation of this server's member struct, updated with the
1275 // static clientURLs of the server.
1276 // The function keeps attempting to register until it succeeds,
1277 // or its server is stopped.
1278 func (s *EtcdServer) publish(timeout time.Duration) {
1279 b, err := json.Marshal(s.attributes)
1280 if err != nil {
1281 plog.Panicf("json marshal error: %v", err)
1282 return
1283 }
1284 req := pb.Request{
1285 Method: "PUT",
1286 Path: membership.MemberAttributesStorePath(s.id),
1287 Val: string(b),
1288 }
1289
1290 for {
1291 ctx, cancel := context.WithTimeout(s.ctx, timeout)
1292 _, err := s.Do(ctx, req)
1293 cancel()
1294 switch err {
1295 case nil:
1296 close(s.readych)
1297 plog.Infof("published %+v to cluster %s", s.attributes, s.cluster.ID())
1298 return
1299 case ErrStopped:
1300 plog.Infof("aborting publish because server is stopped")
1301 return
1302 default:
1303 plog.Errorf("publish error: %v", err)
1304 }
1305 }
1306 }
1307
1308 func (s *EtcdServer) sendMergedSnap(merged snap.Message) {
1309 atomic.AddInt64(&s.inflightSnapshots, 1)
1310
1311 s.r.transport.SendSnapshot(merged)
1312 s.goAttach(func() {
1313 select {
1314 case ok := <-merged.CloseNotify():
1315 // delay releasing inflight snapshot for another 30 seconds to
1316 // block log compaction.
1317 // If the follower still fails to catch up, it is probably just too slow
1318 // to catch up. We cannot avoid the snapshot cycle anyway.
1319 if ok {
1320 select {
1321 case <-time.After(releaseDelayAfterSnapshot):
1322 case <-s.stopping:
1323 }
1324 }
1325 atomic.AddInt64(&s.inflightSnapshots, -1)
1326 case <-s.stopping:
1327 return
1328 }
1329 })
1330 }
1331
1332 // apply takes entries received from Raft (after it has been committed) and
1333 // applies them to the current state of the EtcdServer.
1334 // The given entries should not be empty.
1335 func (s *EtcdServer) apply(es []raftpb.Entry, confState *raftpb.ConfState) (appliedt uint64, appliedi uint64, shouldStop bool) {
1336 for i := range es {
1337 e := es[i]
1338 switch e.Type {
1339 case raftpb.EntryNormal:
1340 s.applyEntryNormal(&e)
1341 case raftpb.EntryConfChange:
1342 // set the consistent index of current executing entry
1343 if e.Index > s.consistIndex.ConsistentIndex() {
1344 s.consistIndex.setConsistentIndex(e.Index)
1345 }
1346 var cc raftpb.ConfChange
1347 pbutil.MustUnmarshal(&cc, e.Data)
1348 removedSelf, err := s.applyConfChange(cc, confState)
1349 s.setAppliedIndex(e.Index)
1350 shouldStop = shouldStop || removedSelf
1351 s.w.Trigger(cc.ID, &confChangeResponse{s.cluster.Members(), err})
1352 default:
1353 plog.Panicf("entry type should be either EntryNormal or EntryConfChange")
1354 }
1355 atomic.StoreUint64(&s.r.index, e.Index)
1356 atomic.StoreUint64(&s.r.term, e.Term)
1357 appliedt = e.Term
1358 appliedi = e.Index
1359 }
1360 return appliedt, appliedi, shouldStop
1361 }
1362
1363 // applyEntryNormal apples an EntryNormal type raftpb request to the EtcdServer
1364 func (s *EtcdServer) applyEntryNormal(e *raftpb.Entry) {
1365 shouldApplyV3 := false
1366 if e.Index > s.consistIndex.ConsistentIndex() {
1367 // set the consistent index of current executing entry
1368 s.consistIndex.setConsistentIndex(e.Index)
1369 shouldApplyV3 = true
1370 }
1371 defer s.setAppliedIndex(e.Index)
1372
1373 // raft state machine may generate noop entry when leader confirmation.
1374 // skip it in advance to avoid some potential bug in the future
1375 if len(e.Data) == 0 {
1376 select {
1377 case s.forceVersionC <- struct{}{}:
1378 default:
1379 }
1380 // promote lessor when the local member is leader and finished
1381 // applying all entries from the last term.
1382 if s.isLeader() {
1383 s.lessor.Promote(s.Cfg.electionTimeout())
1384 }
1385 return
1386 }
1387
1388 var raftReq pb.InternalRaftRequest
1389 if !pbutil.MaybeUnmarshal(&raftReq, e.Data) { // backward compatible
1390 var r pb.Request
1391 rp := &r
1392 pbutil.MustUnmarshal(rp, e.Data)
1393 s.w.Trigger(r.ID, s.applyV2Request((*RequestV2)(rp)))
1394 return
1395 }
1396 if raftReq.V2 != nil {
1397 req := (*RequestV2)(raftReq.V2)
1398 s.w.Trigger(req.ID, s.applyV2Request(req))
1399 return
1400 }
1401
1402 // do not re-apply applied entries.
1403 if !shouldApplyV3 {
1404 return
1405 }
1406
1407 id := raftReq.ID
1408 if id == 0 {
1409 id = raftReq.Header.ID
1410 }
1411
1412 var ar *applyResult
1413 needResult := s.w.IsRegistered(id)
1414 if needResult || !noSideEffect(&raftReq) {
1415 if !needResult && raftReq.Txn != nil {
1416 removeNeedlessRangeReqs(raftReq.Txn)
1417 }
1418 ar = s.applyV3.Apply(&raftReq)
1419 }
1420
1421 if ar == nil {
1422 return
1423 }
1424
1425 if ar.err != ErrNoSpace || len(s.alarmStore.Get(pb.AlarmType_NOSPACE)) > 0 {
1426 s.w.Trigger(id, ar)
1427 return
1428 }
1429
1430 plog.Errorf("applying raft message exceeded backend quota")
1431 s.goAttach(func() {
1432 a := &pb.AlarmRequest{
1433 MemberID: uint64(s.ID()),
1434 Action: pb.AlarmRequest_ACTIVATE,
1435 Alarm: pb.AlarmType_NOSPACE,
1436 }
1437 s.raftRequest(s.ctx, pb.InternalRaftRequest{Alarm: a})
1438 s.w.Trigger(id, ar)
1439 })
1440 }
1441
1442 // applyConfChange applies a ConfChange to the server. It is only
1443 // invoked with a ConfChange that has already passed through Raft
1444 func (s *EtcdServer) applyConfChange(cc raftpb.ConfChange, confState *raftpb.ConfState) (bool, error) {
1445 if err := s.cluster.ValidateConfigurationChange(cc); err != nil {
1446 cc.NodeID = raft.None
1447 s.r.ApplyConfChange(cc)
1448 return false, err
1449 }
1450 *confState = *s.r.ApplyConfChange(cc)
1451 switch cc.Type {
1452 case raftpb.ConfChangeAddNode:
1453 m := new(membership.Member)
1454 if err := json.Unmarshal(cc.Context, m); err != nil {
1455 plog.Panicf("unmarshal member should never fail: %v", err)
1456 }
1457 if cc.NodeID != uint64(m.ID) {
1458 plog.Panicf("nodeID should always be equal to member ID")
1459 }
1460 s.cluster.AddMember(m)
1461 if m.ID != s.id {
1462 s.r.transport.AddPeer(m.ID, m.PeerURLs)
1463 }
1464 case raftpb.ConfChangeRemoveNode:
1465 id := types.ID(cc.NodeID)
1466 s.cluster.RemoveMember(id)
1467 if id == s.id {
1468 return true, nil
1469 }
1470 s.r.transport.RemovePeer(id)
1471 case raftpb.ConfChangeUpdateNode:
1472 m := new(membership.Member)
1473 if err := json.Unmarshal(cc.Context, m); err != nil {
1474 plog.Panicf("unmarshal member should never fail: %v", err)
1475 }
1476 if cc.NodeID != uint64(m.ID) {
1477 plog.Panicf("nodeID should always be equal to member ID")
1478 }
1479 s.cluster.UpdateRaftAttributes(m.ID, m.RaftAttributes)
1480 if m.ID != s.id {
1481 s.r.transport.UpdatePeer(m.ID, m.PeerURLs)
1482 }
1483 }
1484 return false, nil
1485 }
1486
1487 // TODO: non-blocking snapshot
1488 func (s *EtcdServer) snapshot(snapi uint64, confState raftpb.ConfState) {
1489 clone := s.store.Clone()
1490 // commit kv to write metadata (for example: consistent index) to disk.
1491 // KV().commit() updates the consistent index in backend.
1492 // All operations that update consistent index must be called sequentially
1493 // from applyAll function.
1494 // So KV().Commit() cannot run in parallel with apply. It has to be called outside
1495 // the go routine created below.
1496 s.KV().Commit()
1497
1498 s.goAttach(func() {
1499 d, err := clone.SaveNoCopy()
1500 // TODO: current store will never fail to do a snapshot
1501 // what should we do if the store might fail?
1502 if err != nil {
1503 plog.Panicf("store save should never fail: %v", err)
1504 }
1505 snap, err := s.r.raftStorage.CreateSnapshot(snapi, &confState, d)
1506 if err != nil {
1507 // the snapshot was done asynchronously with the progress of raft.
1508 // raft might have already got a newer snapshot.
1509 if err == raft.ErrSnapOutOfDate {
1510 return
1511 }
1512 plog.Panicf("unexpected create snapshot error %v", err)
1513 }
1514 // SaveSnap saves the snapshot and releases the locked wal files
1515 // to the snapshot index.
1516 if err = s.r.storage.SaveSnap(snap); err != nil {
1517 plog.Fatalf("save snapshot error: %v", err)
1518 }
1519 plog.Infof("saved snapshot at index %d", snap.Metadata.Index)
1520
1521 // When sending a snapshot, etcd will pause compaction.
1522 // After receives a snapshot, the slow follower needs to get all the entries right after
1523 // the snapshot sent to catch up. If we do not pause compaction, the log entries right after
1524 // the snapshot sent might already be compacted. It happens when the snapshot takes long time
1525 // to send and save. Pausing compaction avoids triggering a snapshot sending cycle.
1526 if atomic.LoadInt64(&s.inflightSnapshots) != 0 {
1527 plog.Infof("skip compaction since there is an inflight snapshot")
1528 return
1529 }
1530
1531 // keep some in memory log entries for slow followers.
1532 compacti := uint64(1)
1533 if snapi > numberOfCatchUpEntries {
1534 compacti = snapi - numberOfCatchUpEntries
1535 }
1536 err = s.r.raftStorage.Compact(compacti)
1537 if err != nil {
1538 // the compaction was done asynchronously with the progress of raft.
1539 // raft log might already been compact.
1540 if err == raft.ErrCompacted {
1541 return
1542 }
1543 plog.Panicf("unexpected compaction error %v", err)
1544 }
1545 plog.Infof("compacted raft log at %d", compacti)
1546 })
1547 }
1548
1549 // CutPeer drops messages to the specified peer.
1550 func (s *EtcdServer) CutPeer(id types.ID) {
1551 tr, ok := s.r.transport.(*rafthttp.Transport)
1552 if ok {
1553 tr.CutPeer(id)
1554 }
1555 }
1556
1557 // MendPeer recovers the message dropping behavior of the given peer.
1558 func (s *EtcdServer) MendPeer(id types.ID) {
1559 tr, ok := s.r.transport.(*rafthttp.Transport)
1560 if ok {
1561 tr.MendPeer(id)
1562 }
1563 }
1564
1565 func (s *EtcdServer) PauseSending() { s.r.pauseSending() }
1566
1567 func (s *EtcdServer) ResumeSending() { s.r.resumeSending() }
1568
1569 func (s *EtcdServer) ClusterVersion() *semver.Version {
1570 if s.cluster == nil {
1571 return nil
1572 }
1573 return s.cluster.Version()
1574 }
1575
1576 // monitorVersions checks the member's version every monitorVersionInterval.
1577 // It updates the cluster version if all members agrees on a higher one.
1578 // It prints out log if there is a member with a higher version than the
1579 // local version.
1580 func (s *EtcdServer) monitorVersions() {
1581 for {
1582 select {
1583 case <-s.forceVersionC:
1584 case <-time.After(monitorVersionInterval):
1585 case <-s.stopping:
1586 return
1587 }
1588
1589 if s.Leader() != s.ID() {
1590 continue
1591 }
1592
1593 v := decideClusterVersion(getVersions(s.cluster, s.id, s.peerRt))
1594 if v != nil {
1595 // only keep major.minor version for comparison
1596 v = &semver.Version{
1597 Major: v.Major,
1598 Minor: v.Minor,
1599 }
1600 }
1601
1602 // if the current version is nil:
1603 // 1. use the decided version if possible
1604 // 2. or use the min cluster version
1605 if s.cluster.Version() == nil {
1606 verStr := version.MinClusterVersion
1607 if v != nil {
1608 verStr = v.String()
1609 }
1610 s.goAttach(func() { s.updateClusterVersion(verStr) })
1611 continue
1612 }
1613
1614 // update cluster version only if the decided version is greater than
1615 // the current cluster version
1616 if v != nil && s.cluster.Version().LessThan(*v) {
1617 s.goAttach(func() { s.updateClusterVersion(v.String()) })
1618 }
1619 }
1620 }
1621
1622 func (s *EtcdServer) updateClusterVersion(ver string) {
1623 if s.cluster.Version() == nil {
1624 plog.Infof("setting up the initial cluster version to %s", version.Cluster(ver))
1625 } else {
1626 plog.Infof("updating the cluster version from %s to %s", version.Cluster(s.cluster.Version().String()), version.Cluster(ver))
1627 }
1628 req := pb.Request{
1629 Method: "PUT",
1630 Path: membership.StoreClusterVersionKey(),
1631 Val: ver,
1632 }
1633 ctx, cancel := context.WithTimeout(s.ctx, s.Cfg.ReqTimeout())
1634 _, err := s.Do(ctx, req)
1635 cancel()
1636 switch err {
1637 case nil:
1638 return
1639 case ErrStopped:
1640 plog.Infof("aborting update cluster version because server is stopped")
1641 return
1642 default:
1643 plog.Errorf("error updating cluster version (%v)", err)
1644 }
1645 }
1646
1647 func (s *EtcdServer) parseProposeCtxErr(err error, start time.Time) error {
1648 switch err {
1649 case context.Canceled:
1650 return ErrCanceled
1651 case context.DeadlineExceeded:
1652 s.leadTimeMu.RLock()
1653 curLeadElected := s.leadElectedTime
1654 s.leadTimeMu.RUnlock()
1655 prevLeadLost := curLeadElected.Add(-2 * time.Duration(s.Cfg.ElectionTicks) * time.Duration(s.Cfg.TickMs) * time.Millisecond)
1656 if start.After(prevLeadLost) && start.Before(curLeadElected) {
1657 return ErrTimeoutDueToLeaderFail
1658 }
1659
1660 lead := types.ID(atomic.LoadUint64(&s.r.lead))
1661 switch lead {
1662 case types.ID(raft.None):
1663 // TODO: return error to specify it happens because the cluster does not have leader now
1664 case s.ID():
1665 if !isConnectedToQuorumSince(s.r.transport, start, s.ID(), s.cluster.Members()) {
1666 return ErrTimeoutDueToConnectionLost
1667 }
1668 default:
1669 if !isConnectedSince(s.r.transport, start, lead) {
1670 return ErrTimeoutDueToConnectionLost
1671 }
1672 }
1673
1674 return ErrTimeout
1675 default:
1676 return err
1677 }
1678 }
1679
1680 func (s *EtcdServer) KV() mvcc.ConsistentWatchableKV { return s.kv }
1681 func (s *EtcdServer) Backend() backend.Backend {
1682 s.bemu.Lock()
1683 defer s.bemu.Unlock()
1684 return s.be
1685 }
1686
1687 func (s *EtcdServer) AuthStore() auth.AuthStore { return s.authStore }
1688
1689 func (s *EtcdServer) restoreAlarms() error {
1690 s.applyV3 = s.newApplierV3()
1691 as, err := alarm.NewAlarmStore(s)
1692 if err != nil {
1693 return err
1694 }
1695 s.alarmStore = as
1696 if len(as.Get(pb.AlarmType_NOSPACE)) > 0 {
1697 s.applyV3 = newApplierV3Capped(s.applyV3)
1698 }
1699 if len(as.Get(pb.AlarmType_CORRUPT)) > 0 {
1700 s.applyV3 = newApplierV3Corrupt(s.applyV3)
1701 }
1702 return nil
1703 }
1704
1705 func (s *EtcdServer) getAppliedIndex() uint64 {
1706 return atomic.LoadUint64(&s.appliedIndex)
1707 }
1708
1709 func (s *EtcdServer) setAppliedIndex(v uint64) {
1710 atomic.StoreUint64(&s.appliedIndex, v)
1711 }
1712
1713 func (s *EtcdServer) getCommittedIndex() uint64 {
1714 return atomic.LoadUint64(&s.committedIndex)
1715 }
1716
1717 func (s *EtcdServer) setCommittedIndex(v uint64) {
1718 atomic.StoreUint64(&s.committedIndex, v)
1719 }
1720
1721 // goAttach creates a goroutine on a given function and tracks it using
1722 // the etcdserver waitgroup.
1723 func (s *EtcdServer) goAttach(f func()) {
1724 s.wgMu.RLock() // this blocks with ongoing close(s.stopping)
1725 defer s.wgMu.RUnlock()
1726 select {
1727 case <-s.stopping:
1728 plog.Warning("server has stopped (skipping goAttach)")
1729 return
1730 default:
1731 }
1732
1733 // now safe to add since waitgroup wait has not started yet
1734 s.wg.Add(1)
1735 go func() {
1736 defer s.wg.Done()
1737 f()
1738 }()
1739 }
1740
1741 func (s *EtcdServer) Alarms() []*pb.AlarmMember {
1742 return s.alarmStore.Get(pb.AlarmType_NONE)
1743 }