server.go 75 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657
  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. package etcdserver
  15. import (
  16. "context"
  17. "encoding/json"
  18. "expvar"
  19. "fmt"
  20. "math"
  21. "math/rand"
  22. "net/http"
  23. "os"
  24. "path"
  25. "regexp"
  26. "sync"
  27. "sync/atomic"
  28. "time"
  29. "go.etcd.io/etcd/auth"
  30. "go.etcd.io/etcd/etcdserver/api"
  31. "go.etcd.io/etcd/etcdserver/api/membership"
  32. "go.etcd.io/etcd/etcdserver/api/rafthttp"
  33. "go.etcd.io/etcd/etcdserver/api/snap"
  34. "go.etcd.io/etcd/etcdserver/api/v2discovery"
  35. "go.etcd.io/etcd/etcdserver/api/v2http/httptypes"
  36. stats "go.etcd.io/etcd/etcdserver/api/v2stats"
  37. "go.etcd.io/etcd/etcdserver/api/v2store"
  38. "go.etcd.io/etcd/etcdserver/api/v3alarm"
  39. "go.etcd.io/etcd/etcdserver/api/v3compactor"
  40. pb "go.etcd.io/etcd/etcdserver/etcdserverpb"
  41. "go.etcd.io/etcd/lease"
  42. "go.etcd.io/etcd/lease/leasehttp"
  43. "go.etcd.io/etcd/mvcc"
  44. "go.etcd.io/etcd/mvcc/backend"
  45. "go.etcd.io/etcd/pkg/fileutil"
  46. "go.etcd.io/etcd/pkg/idutil"
  47. "go.etcd.io/etcd/pkg/pbutil"
  48. "go.etcd.io/etcd/pkg/runtime"
  49. "go.etcd.io/etcd/pkg/schedule"
  50. "go.etcd.io/etcd/pkg/traceutil"
  51. "go.etcd.io/etcd/pkg/types"
  52. "go.etcd.io/etcd/pkg/wait"
  53. "go.etcd.io/etcd/raft"
  54. "go.etcd.io/etcd/raft/raftpb"
  55. "go.etcd.io/etcd/version"
  56. "go.etcd.io/etcd/wal"
  57. "github.com/coreos/go-semver/semver"
  58. "github.com/coreos/pkg/capnslog"
  59. humanize "github.com/dustin/go-humanize"
  60. "github.com/prometheus/client_golang/prometheus"
  61. "go.uber.org/zap"
  62. )
  63. const (
  64. DefaultSnapshotCount = 100000
  65. // DefaultSnapshotCatchUpEntries is the number of entries for a slow follower
  66. // to catch-up after compacting the raft storage entries.
  67. // We expect the follower has a millisecond level latency with the leader.
  68. // The max throughput is around 10K. Keep a 5K entries is enough for helping
  69. // follower to catch up.
  70. DefaultSnapshotCatchUpEntries uint64 = 5000
  71. StoreClusterPrefix = "/0"
  72. StoreKeysPrefix = "/1"
  73. // HealthInterval is the minimum time the cluster should be healthy
  74. // before accepting add member requests.
  75. HealthInterval = 5 * time.Second
  76. purgeFileInterval = 30 * time.Second
  77. // monitorVersionInterval should be smaller than the timeout
  78. // on the connection. Or we will not be able to reuse the connection
  79. // (since it will timeout).
  80. monitorVersionInterval = rafthttp.ConnWriteTimeout - time.Second
  81. // max number of in-flight snapshot messages etcdserver allows to have
  82. // This number is more than enough for most clusters with 5 machines.
  83. maxInFlightMsgSnap = 16
  84. releaseDelayAfterSnapshot = 30 * time.Second
  85. // maxPendingRevokes is the maximum number of outstanding expired lease revocations.
  86. maxPendingRevokes = 16
  87. recommendedMaxRequestBytes = 10 * 1024 * 1024
  88. readyPercent = 0.9
  89. )
  90. var (
  91. plog = capnslog.NewPackageLogger("go.etcd.io/etcd", "etcdserver")
  92. storeMemberAttributeRegexp = regexp.MustCompile(path.Join(membership.StoreMembersPrefix, "[[:xdigit:]]{1,16}", "attributes"))
  93. )
  94. func init() {
  95. rand.Seed(time.Now().UnixNano())
  96. expvar.Publish(
  97. "file_descriptor_limit",
  98. expvar.Func(
  99. func() interface{} {
  100. n, _ := runtime.FDLimit()
  101. return n
  102. },
  103. ),
  104. )
  105. }
  106. type Response struct {
  107. Term uint64
  108. Index uint64
  109. Event *v2store.Event
  110. Watcher v2store.Watcher
  111. Err error
  112. }
  113. type ServerV2 interface {
  114. Server
  115. Leader() types.ID
  116. // Do takes a V2 request and attempts to fulfill it, returning a Response.
  117. Do(ctx context.Context, r pb.Request) (Response, error)
  118. stats.Stats
  119. ClientCertAuthEnabled() bool
  120. }
  121. type ServerV3 interface {
  122. Server
  123. RaftStatusGetter
  124. }
  125. func (s *EtcdServer) ClientCertAuthEnabled() bool { return s.Cfg.ClientCertAuthEnabled }
  126. type Server interface {
  127. // AddMember attempts to add a member into the cluster. It will return
  128. // ErrIDRemoved if member ID is removed from the cluster, or return
  129. // ErrIDExists if member ID exists in the cluster.
  130. AddMember(ctx context.Context, memb membership.Member) ([]*membership.Member, error)
  131. // RemoveMember attempts to remove a member from the cluster. It will
  132. // return ErrIDRemoved if member ID is removed from the cluster, or return
  133. // ErrIDNotFound if member ID is not in the cluster.
  134. RemoveMember(ctx context.Context, id uint64) ([]*membership.Member, error)
  135. // UpdateMember attempts to update an existing member in the cluster. It will
  136. // return ErrIDNotFound if the member ID does not exist.
  137. UpdateMember(ctx context.Context, updateMemb membership.Member) ([]*membership.Member, error)
  138. // PromoteMember attempts to promote a non-voting node to a voting node. It will
  139. // return ErrIDNotFound if the member ID does not exist.
  140. // return ErrLearnerNotReady if the member are not ready.
  141. // return ErrMemberNotLearner if the member is not a learner.
  142. PromoteMember(ctx context.Context, id uint64) ([]*membership.Member, error)
  143. // ClusterVersion is the cluster-wide minimum major.minor version.
  144. // Cluster version is set to the min version that an etcd member is
  145. // compatible with when first bootstrap.
  146. //
  147. // ClusterVersion is nil until the cluster is bootstrapped (has a quorum).
  148. //
  149. // During a rolling upgrades, the ClusterVersion will be updated
  150. // automatically after a sync. (5 second by default)
  151. //
  152. // The API/raft component can utilize ClusterVersion to determine if
  153. // it can accept a client request or a raft RPC.
  154. // NOTE: ClusterVersion might be nil when etcd 2.1 works with etcd 2.0 and
  155. // the leader is etcd 2.0. etcd 2.0 leader will not update clusterVersion since
  156. // this feature is introduced post 2.0.
  157. ClusterVersion() *semver.Version
  158. Cluster() api.Cluster
  159. Alarms() []*pb.AlarmMember
  160. }
  161. // EtcdServer is the production implementation of the Server interface
  162. type EtcdServer struct {
  163. // inflightSnapshots holds count the number of snapshots currently inflight.
  164. inflightSnapshots int64 // must use atomic operations to access; keep 64-bit aligned.
  165. appliedIndex uint64 // must use atomic operations to access; keep 64-bit aligned.
  166. committedIndex uint64 // must use atomic operations to access; keep 64-bit aligned.
  167. term uint64 // must use atomic operations to access; keep 64-bit aligned.
  168. lead uint64 // must use atomic operations to access; keep 64-bit aligned.
  169. // consistIndex used to hold the offset of current executing entry
  170. // It is initialized to 0 before executing any entry.
  171. consistIndex consistentIndex // must use atomic operations to access; keep 64-bit aligned.
  172. r raftNode // uses 64-bit atomics; keep 64-bit aligned.
  173. readych chan struct{}
  174. Cfg ServerConfig
  175. lgMu *sync.RWMutex
  176. lg *zap.Logger
  177. w wait.Wait
  178. readMu sync.RWMutex
  179. // read routine notifies etcd server that it waits for reading by sending an empty struct to
  180. // readwaitC
  181. readwaitc chan struct{}
  182. // readNotifier is used to notify the read routine that it can process the request
  183. // when there is no error
  184. readNotifier *notifier
  185. // stop signals the run goroutine should shutdown.
  186. stop chan struct{}
  187. // stopping is closed by run goroutine on shutdown.
  188. stopping chan struct{}
  189. // done is closed when all goroutines from start() complete.
  190. done chan struct{}
  191. // leaderChanged is used to notify the linearizable read loop to drop the old read requests.
  192. leaderChanged chan struct{}
  193. leaderChangedMu sync.RWMutex
  194. errorc chan error
  195. id types.ID
  196. attributes membership.Attributes
  197. cluster *membership.RaftCluster
  198. v2store v2store.Store
  199. snapshotter *snap.Snapshotter
  200. applyV2 ApplierV2
  201. // applyV3 is the applier with auth and quotas
  202. applyV3 applierV3
  203. // applyV3Base is the core applier without auth or quotas
  204. applyV3Base applierV3
  205. applyWait wait.WaitTime
  206. kv mvcc.ConsistentWatchableKV
  207. lessor lease.Lessor
  208. bemu sync.Mutex
  209. be backend.Backend
  210. authStore auth.AuthStore
  211. alarmStore *v3alarm.AlarmStore
  212. stats *stats.ServerStats
  213. lstats *stats.LeaderStats
  214. SyncTicker *time.Ticker
  215. // compactor is used to auto-compact the KV.
  216. compactor v3compactor.Compactor
  217. // peerRt used to send requests (version, lease) to peers.
  218. peerRt http.RoundTripper
  219. reqIDGen *idutil.Generator
  220. // forceVersionC is used to force the version monitor loop
  221. // to detect the cluster version immediately.
  222. forceVersionC chan struct{}
  223. // wgMu blocks concurrent waitgroup mutation while server stopping
  224. wgMu sync.RWMutex
  225. // wg is used to wait for the go routines that depends on the server state
  226. // to exit when stopping the server.
  227. wg sync.WaitGroup
  228. // ctx is used for etcd-initiated requests that may need to be canceled
  229. // on etcd server shutdown.
  230. ctx context.Context
  231. cancel context.CancelFunc
  232. leadTimeMu sync.RWMutex
  233. leadElectedTime time.Time
  234. *AccessController
  235. }
  236. // NewServer creates a new EtcdServer from the supplied configuration. The
  237. // configuration is considered static for the lifetime of the EtcdServer.
  238. func NewServer(cfg ServerConfig) (srv *EtcdServer, err error) {
  239. st := v2store.New(StoreClusterPrefix, StoreKeysPrefix)
  240. var (
  241. w *wal.WAL
  242. n raft.Node
  243. s *raft.MemoryStorage
  244. id types.ID
  245. cl *membership.RaftCluster
  246. )
  247. if cfg.MaxRequestBytes > recommendedMaxRequestBytes {
  248. if cfg.Logger != nil {
  249. cfg.Logger.Warn(
  250. "exceeded recommended request limit",
  251. zap.Uint("max-request-bytes", cfg.MaxRequestBytes),
  252. zap.String("max-request-size", humanize.Bytes(uint64(cfg.MaxRequestBytes))),
  253. zap.Int("recommended-request-bytes", recommendedMaxRequestBytes),
  254. zap.String("recommended-request-size", humanize.Bytes(uint64(recommendedMaxRequestBytes))),
  255. )
  256. } else {
  257. plog.Warningf("MaxRequestBytes %v exceeds maximum recommended size %v", cfg.MaxRequestBytes, recommendedMaxRequestBytes)
  258. }
  259. }
  260. if terr := fileutil.TouchDirAll(cfg.DataDir); terr != nil {
  261. return nil, fmt.Errorf("cannot access data directory: %v", terr)
  262. }
  263. haveWAL := wal.Exist(cfg.WALDir())
  264. if err = fileutil.TouchDirAll(cfg.SnapDir()); err != nil {
  265. if cfg.Logger != nil {
  266. cfg.Logger.Fatal(
  267. "failed to create snapshot directory",
  268. zap.String("path", cfg.SnapDir()),
  269. zap.Error(err),
  270. )
  271. } else {
  272. plog.Fatalf("create snapshot directory error: %v", err)
  273. }
  274. }
  275. ss := snap.New(cfg.Logger, cfg.SnapDir())
  276. bepath := cfg.backendPath()
  277. beExist := fileutil.Exist(bepath)
  278. be := openBackend(cfg)
  279. defer func() {
  280. if err != nil {
  281. be.Close()
  282. }
  283. }()
  284. prt, err := rafthttp.NewRoundTripper(cfg.PeerTLSInfo, cfg.peerDialTimeout())
  285. if err != nil {
  286. return nil, err
  287. }
  288. var (
  289. remotes []*membership.Member
  290. snapshot *raftpb.Snapshot
  291. )
  292. switch {
  293. case !haveWAL && !cfg.NewCluster:
  294. if err = cfg.VerifyJoinExisting(); err != nil {
  295. return nil, err
  296. }
  297. cl, err = membership.NewClusterFromURLsMap(cfg.Logger, cfg.InitialClusterToken, cfg.InitialPeerURLsMap)
  298. if err != nil {
  299. return nil, err
  300. }
  301. existingCluster, gerr := GetClusterFromRemotePeers(cfg.Logger, getRemotePeerURLs(cl, cfg.Name), prt)
  302. if gerr != nil {
  303. return nil, fmt.Errorf("cannot fetch cluster info from peer urls: %v", gerr)
  304. }
  305. if err = membership.ValidateClusterAndAssignIDs(cfg.Logger, cl, existingCluster); err != nil {
  306. return nil, fmt.Errorf("error validating peerURLs %s: %v", existingCluster, err)
  307. }
  308. if !isCompatibleWithCluster(cfg.Logger, cl, cl.MemberByName(cfg.Name).ID, prt) {
  309. return nil, fmt.Errorf("incompatible with current running cluster")
  310. }
  311. remotes = existingCluster.Members()
  312. cl.SetID(types.ID(0), existingCluster.ID())
  313. cl.SetStore(st)
  314. cl.SetBackend(be)
  315. id, n, s, w = startNode(cfg, cl, nil)
  316. cl.SetID(id, existingCluster.ID())
  317. case !haveWAL && cfg.NewCluster:
  318. if err = cfg.VerifyBootstrap(); err != nil {
  319. return nil, err
  320. }
  321. cl, err = membership.NewClusterFromURLsMap(cfg.Logger, cfg.InitialClusterToken, cfg.InitialPeerURLsMap)
  322. if err != nil {
  323. return nil, err
  324. }
  325. m := cl.MemberByName(cfg.Name)
  326. if isMemberBootstrapped(cfg.Logger, cl, cfg.Name, prt, cfg.bootstrapTimeout()) {
  327. return nil, fmt.Errorf("member %s has already been bootstrapped", m.ID)
  328. }
  329. if cfg.ShouldDiscover() {
  330. var str string
  331. str, err = v2discovery.JoinCluster(cfg.Logger, cfg.DiscoveryURL, cfg.DiscoveryProxy, m.ID, cfg.InitialPeerURLsMap.String())
  332. if err != nil {
  333. return nil, &DiscoveryError{Op: "join", Err: err}
  334. }
  335. var urlsmap types.URLsMap
  336. urlsmap, err = types.NewURLsMap(str)
  337. if err != nil {
  338. return nil, err
  339. }
  340. if checkDuplicateURL(urlsmap) {
  341. return nil, fmt.Errorf("discovery cluster %s has duplicate url", urlsmap)
  342. }
  343. if cl, err = membership.NewClusterFromURLsMap(cfg.Logger, cfg.InitialClusterToken, urlsmap); err != nil {
  344. return nil, err
  345. }
  346. }
  347. cl.SetStore(st)
  348. cl.SetBackend(be)
  349. id, n, s, w = startNode(cfg, cl, cl.MemberIDs())
  350. cl.SetID(id, cl.ID())
  351. case haveWAL:
  352. if err = fileutil.IsDirWriteable(cfg.MemberDir()); err != nil {
  353. return nil, fmt.Errorf("cannot write to member directory: %v", err)
  354. }
  355. if err = fileutil.IsDirWriteable(cfg.WALDir()); err != nil {
  356. return nil, fmt.Errorf("cannot write to WAL directory: %v", err)
  357. }
  358. if cfg.ShouldDiscover() {
  359. if cfg.Logger != nil {
  360. cfg.Logger.Warn(
  361. "discovery token is ignored since cluster already initialized; valid logs are found",
  362. zap.String("wal-dir", cfg.WALDir()),
  363. )
  364. } else {
  365. plog.Warningf("discovery token ignored since a cluster has already been initialized. Valid log found at %q", cfg.WALDir())
  366. }
  367. }
  368. snapshot, err = ss.Load()
  369. if err != nil && err != snap.ErrNoSnapshot {
  370. return nil, err
  371. }
  372. if snapshot != nil {
  373. if err = st.Recovery(snapshot.Data); err != nil {
  374. if cfg.Logger != nil {
  375. cfg.Logger.Panic("failed to recover from snapshot")
  376. } else {
  377. plog.Panicf("recovered store from snapshot error: %v", err)
  378. }
  379. }
  380. if cfg.Logger != nil {
  381. cfg.Logger.Info(
  382. "recovered v2 store from snapshot",
  383. zap.Uint64("snapshot-index", snapshot.Metadata.Index),
  384. zap.String("snapshot-size", humanize.Bytes(uint64(snapshot.Size()))),
  385. )
  386. } else {
  387. plog.Infof("recovered store from snapshot at index %d", snapshot.Metadata.Index)
  388. }
  389. if be, err = recoverSnapshotBackend(cfg, be, *snapshot); err != nil {
  390. if cfg.Logger != nil {
  391. cfg.Logger.Panic("failed to recover v3 backend from snapshot", zap.Error(err))
  392. } else {
  393. plog.Panicf("recovering backend from snapshot error: %v", err)
  394. }
  395. }
  396. if cfg.Logger != nil {
  397. s1, s2 := be.Size(), be.SizeInUse()
  398. cfg.Logger.Info(
  399. "recovered v3 backend from snapshot",
  400. zap.Int64("backend-size-bytes", s1),
  401. zap.String("backend-size", humanize.Bytes(uint64(s1))),
  402. zap.Int64("backend-size-in-use-bytes", s2),
  403. zap.String("backend-size-in-use", humanize.Bytes(uint64(s2))),
  404. )
  405. }
  406. }
  407. if !cfg.ForceNewCluster {
  408. id, cl, n, s, w = restartNode(cfg, snapshot)
  409. } else {
  410. id, cl, n, s, w = restartAsStandaloneNode(cfg, snapshot)
  411. }
  412. cl.SetStore(st)
  413. cl.SetBackend(be)
  414. cl.Recover(api.UpdateCapability)
  415. if cl.Version() != nil && !cl.Version().LessThan(semver.Version{Major: 3}) && !beExist {
  416. os.RemoveAll(bepath)
  417. return nil, fmt.Errorf("database file (%v) of the backend is missing", bepath)
  418. }
  419. default:
  420. return nil, fmt.Errorf("unsupported bootstrap config")
  421. }
  422. if terr := fileutil.TouchDirAll(cfg.MemberDir()); terr != nil {
  423. return nil, fmt.Errorf("cannot access member directory: %v", terr)
  424. }
  425. sstats := stats.NewServerStats(cfg.Name, id.String())
  426. lstats := stats.NewLeaderStats(id.String())
  427. heartbeat := time.Duration(cfg.TickMs) * time.Millisecond
  428. srv = &EtcdServer{
  429. readych: make(chan struct{}),
  430. Cfg: cfg,
  431. lgMu: new(sync.RWMutex),
  432. lg: cfg.Logger,
  433. errorc: make(chan error, 1),
  434. v2store: st,
  435. snapshotter: ss,
  436. r: *newRaftNode(
  437. raftNodeConfig{
  438. lg: cfg.Logger,
  439. isIDRemoved: func(id uint64) bool { return cl.IsIDRemoved(types.ID(id)) },
  440. Node: n,
  441. heartbeat: heartbeat,
  442. raftStorage: s,
  443. storage: NewStorage(w, ss),
  444. },
  445. ),
  446. id: id,
  447. attributes: membership.Attributes{Name: cfg.Name, ClientURLs: cfg.ClientURLs.StringSlice()},
  448. cluster: cl,
  449. stats: sstats,
  450. lstats: lstats,
  451. SyncTicker: time.NewTicker(500 * time.Millisecond),
  452. peerRt: prt,
  453. reqIDGen: idutil.NewGenerator(uint16(id), time.Now()),
  454. forceVersionC: make(chan struct{}),
  455. AccessController: &AccessController{CORS: cfg.CORS, HostWhitelist: cfg.HostWhitelist},
  456. }
  457. serverID.With(prometheus.Labels{"server_id": id.String()}).Set(1)
  458. srv.applyV2 = &applierV2store{store: srv.v2store, cluster: srv.cluster}
  459. srv.be = be
  460. minTTL := time.Duration((3*cfg.ElectionTicks)/2) * heartbeat
  461. // always recover lessor before kv. When we recover the mvcc.KV it will reattach keys to its leases.
  462. // If we recover mvcc.KV first, it will attach the keys to the wrong lessor before it recovers.
  463. srv.lessor = lease.NewLessor(
  464. srv.getLogger(),
  465. srv.be,
  466. lease.LessorConfig{
  467. MinLeaseTTL: int64(math.Ceil(minTTL.Seconds())),
  468. CheckpointInterval: cfg.LeaseCheckpointInterval,
  469. ExpiredLeasesRetryInterval: srv.Cfg.ReqTimeout(),
  470. })
  471. srv.kv = mvcc.New(srv.getLogger(), srv.be, srv.lessor, &srv.consistIndex, mvcc.StoreConfig{CompactionBatchLimit: cfg.CompactionBatchLimit})
  472. if beExist {
  473. kvindex := srv.kv.ConsistentIndex()
  474. // TODO: remove kvindex != 0 checking when we do not expect users to upgrade
  475. // etcd from pre-3.0 release.
  476. if snapshot != nil && kvindex < snapshot.Metadata.Index {
  477. if kvindex != 0 {
  478. return nil, fmt.Errorf("database file (%v index %d) does not match with snapshot (index %d)", bepath, kvindex, snapshot.Metadata.Index)
  479. }
  480. if cfg.Logger != nil {
  481. cfg.Logger.Warn(
  482. "consistent index was never saved",
  483. zap.Uint64("snapshot-index", snapshot.Metadata.Index),
  484. )
  485. } else {
  486. plog.Warningf("consistent index never saved (snapshot index=%d)", snapshot.Metadata.Index)
  487. }
  488. }
  489. }
  490. newSrv := srv // since srv == nil in defer if srv is returned as nil
  491. defer func() {
  492. // closing backend without first closing kv can cause
  493. // resumed compactions to fail with closed tx errors
  494. if err != nil {
  495. newSrv.kv.Close()
  496. }
  497. }()
  498. srv.consistIndex.setConsistentIndex(srv.kv.ConsistentIndex())
  499. tp, err := auth.NewTokenProvider(cfg.Logger, cfg.AuthToken,
  500. func(index uint64) <-chan struct{} {
  501. return srv.applyWait.Wait(index)
  502. },
  503. )
  504. if err != nil {
  505. if cfg.Logger != nil {
  506. cfg.Logger.Warn("failed to create token provider", zap.Error(err))
  507. } else {
  508. plog.Errorf("failed to create token provider: %s", err)
  509. }
  510. return nil, err
  511. }
  512. srv.authStore = auth.NewAuthStore(srv.getLogger(), srv.be, tp, int(cfg.BcryptCost))
  513. if num := cfg.AutoCompactionRetention; num != 0 {
  514. srv.compactor, err = v3compactor.New(cfg.Logger, cfg.AutoCompactionMode, num, srv.kv, srv)
  515. if err != nil {
  516. return nil, err
  517. }
  518. srv.compactor.Run()
  519. }
  520. srv.applyV3Base = srv.newApplierV3Backend()
  521. if err = srv.restoreAlarms(); err != nil {
  522. return nil, err
  523. }
  524. if srv.Cfg.EnableLeaseCheckpoint {
  525. // setting checkpointer enables lease checkpoint feature.
  526. srv.lessor.SetCheckpointer(func(ctx context.Context, cp *pb.LeaseCheckpointRequest) {
  527. srv.raftRequestOnce(ctx, pb.InternalRaftRequest{LeaseCheckpoint: cp})
  528. })
  529. }
  530. // TODO: move transport initialization near the definition of remote
  531. tr := &rafthttp.Transport{
  532. Logger: cfg.Logger,
  533. TLSInfo: cfg.PeerTLSInfo,
  534. DialTimeout: cfg.peerDialTimeout(),
  535. ID: id,
  536. URLs: cfg.PeerURLs,
  537. ClusterID: cl.ID(),
  538. Raft: srv,
  539. Snapshotter: ss,
  540. ServerStats: sstats,
  541. LeaderStats: lstats,
  542. ErrorC: srv.errorc,
  543. }
  544. if err = tr.Start(); err != nil {
  545. return nil, err
  546. }
  547. // add all remotes into transport
  548. for _, m := range remotes {
  549. if m.ID != id {
  550. tr.AddRemote(m.ID, m.PeerURLs)
  551. }
  552. }
  553. for _, m := range cl.Members() {
  554. if m.ID != id {
  555. tr.AddPeer(m.ID, m.PeerURLs)
  556. }
  557. }
  558. srv.r.transport = tr
  559. return srv, nil
  560. }
  561. func (s *EtcdServer) getLogger() *zap.Logger {
  562. s.lgMu.RLock()
  563. l := s.lg
  564. s.lgMu.RUnlock()
  565. return l
  566. }
  567. func tickToDur(ticks int, tickMs uint) string {
  568. return fmt.Sprintf("%v", time.Duration(ticks)*time.Duration(tickMs)*time.Millisecond)
  569. }
  570. func (s *EtcdServer) adjustTicks() {
  571. lg := s.getLogger()
  572. clusterN := len(s.cluster.Members())
  573. // single-node fresh start, or single-node recovers from snapshot
  574. if clusterN == 1 {
  575. ticks := s.Cfg.ElectionTicks - 1
  576. if lg != nil {
  577. lg.Info(
  578. "started as single-node; fast-forwarding election ticks",
  579. zap.String("local-member-id", s.ID().String()),
  580. zap.Int("forward-ticks", ticks),
  581. zap.String("forward-duration", tickToDur(ticks, s.Cfg.TickMs)),
  582. zap.Int("election-ticks", s.Cfg.ElectionTicks),
  583. zap.String("election-timeout", tickToDur(s.Cfg.ElectionTicks, s.Cfg.TickMs)),
  584. )
  585. } else {
  586. plog.Infof("%s as single-node; fast-forwarding %d ticks (election ticks %d)", s.ID(), ticks, s.Cfg.ElectionTicks)
  587. }
  588. s.r.advanceTicks(ticks)
  589. return
  590. }
  591. if !s.Cfg.InitialElectionTickAdvance {
  592. if lg != nil {
  593. lg.Info("skipping initial election tick advance", zap.Int("election-ticks", s.Cfg.ElectionTicks))
  594. }
  595. return
  596. }
  597. if lg != nil {
  598. lg.Info("starting initial election tick advance", zap.Int("election-ticks", s.Cfg.ElectionTicks))
  599. }
  600. // retry up to "rafthttp.ConnReadTimeout", which is 5-sec
  601. // until peer connection reports; otherwise:
  602. // 1. all connections failed, or
  603. // 2. no active peers, or
  604. // 3. restarted single-node with no snapshot
  605. // then, do nothing, because advancing ticks would have no effect
  606. waitTime := rafthttp.ConnReadTimeout
  607. itv := 50 * time.Millisecond
  608. for i := int64(0); i < int64(waitTime/itv); i++ {
  609. select {
  610. case <-time.After(itv):
  611. case <-s.stopping:
  612. return
  613. }
  614. peerN := s.r.transport.ActivePeers()
  615. if peerN > 1 {
  616. // multi-node received peer connection reports
  617. // adjust ticks, in case slow leader message receive
  618. ticks := s.Cfg.ElectionTicks - 2
  619. if lg != nil {
  620. lg.Info(
  621. "initialized peer connections; fast-forwarding election ticks",
  622. zap.String("local-member-id", s.ID().String()),
  623. zap.Int("forward-ticks", ticks),
  624. zap.String("forward-duration", tickToDur(ticks, s.Cfg.TickMs)),
  625. zap.Int("election-ticks", s.Cfg.ElectionTicks),
  626. zap.String("election-timeout", tickToDur(s.Cfg.ElectionTicks, s.Cfg.TickMs)),
  627. zap.Int("active-remote-members", peerN),
  628. )
  629. } else {
  630. plog.Infof("%s initialized peer connection; fast-forwarding %d ticks (election ticks %d) with %d active peer(s)", s.ID(), ticks, s.Cfg.ElectionTicks, peerN)
  631. }
  632. s.r.advanceTicks(ticks)
  633. return
  634. }
  635. }
  636. }
  637. // Start performs any initialization of the Server necessary for it to
  638. // begin serving requests. It must be called before Do or Process.
  639. // Start must be non-blocking; any long-running server functionality
  640. // should be implemented in goroutines.
  641. func (s *EtcdServer) Start() {
  642. s.start()
  643. s.goAttach(func() { s.adjustTicks() })
  644. s.goAttach(func() { s.publish(s.Cfg.ReqTimeout()) })
  645. s.goAttach(s.purgeFile)
  646. s.goAttach(func() { monitorFileDescriptor(s.getLogger(), s.stopping) })
  647. s.goAttach(s.monitorVersions)
  648. s.goAttach(s.linearizableReadLoop)
  649. s.goAttach(s.monitorKVHash)
  650. }
  651. // start prepares and starts server in a new goroutine. It is no longer safe to
  652. // modify a server's fields after it has been sent to Start.
  653. // This function is just used for testing.
  654. func (s *EtcdServer) start() {
  655. lg := s.getLogger()
  656. if s.Cfg.SnapshotCount == 0 {
  657. if lg != nil {
  658. lg.Info(
  659. "updating snapshot-count to default",
  660. zap.Uint64("given-snapshot-count", s.Cfg.SnapshotCount),
  661. zap.Uint64("updated-snapshot-count", DefaultSnapshotCount),
  662. )
  663. } else {
  664. plog.Infof("set snapshot count to default %d", DefaultSnapshotCount)
  665. }
  666. s.Cfg.SnapshotCount = DefaultSnapshotCount
  667. }
  668. if s.Cfg.SnapshotCatchUpEntries == 0 {
  669. if lg != nil {
  670. lg.Info(
  671. "updating snapshot catch-up entries to default",
  672. zap.Uint64("given-snapshot-catchup-entries", s.Cfg.SnapshotCatchUpEntries),
  673. zap.Uint64("updated-snapshot-catchup-entries", DefaultSnapshotCatchUpEntries),
  674. )
  675. }
  676. s.Cfg.SnapshotCatchUpEntries = DefaultSnapshotCatchUpEntries
  677. }
  678. s.w = wait.New()
  679. s.applyWait = wait.NewTimeList()
  680. s.done = make(chan struct{})
  681. s.stop = make(chan struct{})
  682. s.stopping = make(chan struct{})
  683. s.ctx, s.cancel = context.WithCancel(context.Background())
  684. s.readwaitc = make(chan struct{}, 1)
  685. s.readNotifier = newNotifier()
  686. s.leaderChanged = make(chan struct{})
  687. if s.ClusterVersion() != nil {
  688. if lg != nil {
  689. lg.Info(
  690. "starting etcd server",
  691. zap.String("local-member-id", s.ID().String()),
  692. zap.String("local-server-version", version.Version),
  693. zap.String("cluster-id", s.Cluster().ID().String()),
  694. zap.String("cluster-version", version.Cluster(s.ClusterVersion().String())),
  695. )
  696. } else {
  697. plog.Infof("starting server... [version: %v, cluster version: %v]", version.Version, version.Cluster(s.ClusterVersion().String()))
  698. }
  699. membership.ClusterVersionMetrics.With(prometheus.Labels{"cluster_version": version.Cluster(s.ClusterVersion().String())}).Set(1)
  700. } else {
  701. if lg != nil {
  702. lg.Info(
  703. "starting etcd server",
  704. zap.String("local-member-id", s.ID().String()),
  705. zap.String("local-server-version", version.Version),
  706. zap.String("cluster-version", "to_be_decided"),
  707. )
  708. } else {
  709. plog.Infof("starting server... [version: %v, cluster version: to_be_decided]", version.Version)
  710. }
  711. }
  712. // TODO: if this is an empty log, writes all peer infos
  713. // into the first entry
  714. go s.run()
  715. }
  716. func (s *EtcdServer) purgeFile() {
  717. var dberrc, serrc, werrc <-chan error
  718. if s.Cfg.MaxSnapFiles > 0 {
  719. dberrc = fileutil.PurgeFile(s.getLogger(), s.Cfg.SnapDir(), "snap.db", s.Cfg.MaxSnapFiles, purgeFileInterval, s.done)
  720. serrc = fileutil.PurgeFile(s.getLogger(), s.Cfg.SnapDir(), "snap", s.Cfg.MaxSnapFiles, purgeFileInterval, s.done)
  721. }
  722. if s.Cfg.MaxWALFiles > 0 {
  723. werrc = fileutil.PurgeFile(s.getLogger(), s.Cfg.WALDir(), "wal", s.Cfg.MaxWALFiles, purgeFileInterval, s.done)
  724. }
  725. lg := s.getLogger()
  726. select {
  727. case e := <-dberrc:
  728. if lg != nil {
  729. lg.Fatal("failed to purge snap db file", zap.Error(e))
  730. } else {
  731. plog.Fatalf("failed to purge snap db file %v", e)
  732. }
  733. case e := <-serrc:
  734. if lg != nil {
  735. lg.Fatal("failed to purge snap file", zap.Error(e))
  736. } else {
  737. plog.Fatalf("failed to purge snap file %v", e)
  738. }
  739. case e := <-werrc:
  740. if lg != nil {
  741. lg.Fatal("failed to purge wal file", zap.Error(e))
  742. } else {
  743. plog.Fatalf("failed to purge wal file %v", e)
  744. }
  745. case <-s.stopping:
  746. return
  747. }
  748. }
  749. func (s *EtcdServer) Cluster() api.Cluster { return s.cluster }
  750. func (s *EtcdServer) ApplyWait() <-chan struct{} { return s.applyWait.Wait(s.getCommittedIndex()) }
  751. type ServerPeer interface {
  752. ServerV2
  753. RaftHandler() http.Handler
  754. LeaseHandler() http.Handler
  755. }
  756. func (s *EtcdServer) LeaseHandler() http.Handler {
  757. if s.lessor == nil {
  758. return nil
  759. }
  760. return leasehttp.NewHandler(s.lessor, s.ApplyWait)
  761. }
  762. func (s *EtcdServer) RaftHandler() http.Handler { return s.r.transport.Handler() }
  763. // Process takes a raft message and applies it to the server's raft state
  764. // machine, respecting any timeout of the given context.
  765. func (s *EtcdServer) Process(ctx context.Context, m raftpb.Message) error {
  766. if s.cluster.IsIDRemoved(types.ID(m.From)) {
  767. if lg := s.getLogger(); lg != nil {
  768. lg.Warn(
  769. "rejected Raft message from removed member",
  770. zap.String("local-member-id", s.ID().String()),
  771. zap.String("removed-member-id", types.ID(m.From).String()),
  772. )
  773. } else {
  774. plog.Warningf("reject message from removed member %s", types.ID(m.From).String())
  775. }
  776. return httptypes.NewHTTPError(http.StatusForbidden, "cannot process message from removed member")
  777. }
  778. if m.Type == raftpb.MsgApp {
  779. s.stats.RecvAppendReq(types.ID(m.From).String(), m.Size())
  780. }
  781. return s.r.Step(ctx, m)
  782. }
  783. func (s *EtcdServer) IsIDRemoved(id uint64) bool { return s.cluster.IsIDRemoved(types.ID(id)) }
  784. func (s *EtcdServer) ReportUnreachable(id uint64) { s.r.ReportUnreachable(id) }
  785. // ReportSnapshot reports snapshot sent status to the raft state machine,
  786. // and clears the used snapshot from the snapshot store.
  787. func (s *EtcdServer) ReportSnapshot(id uint64, status raft.SnapshotStatus) {
  788. s.r.ReportSnapshot(id, status)
  789. }
  790. type etcdProgress struct {
  791. confState raftpb.ConfState
  792. snapi uint64
  793. appliedt uint64
  794. appliedi uint64
  795. }
  796. // raftReadyHandler contains a set of EtcdServer operations to be called by raftNode,
  797. // and helps decouple state machine logic from Raft algorithms.
  798. // TODO: add a state machine interface to apply the commit entries and do snapshot/recover
  799. type raftReadyHandler struct {
  800. getLead func() (lead uint64)
  801. updateLead func(lead uint64)
  802. updateLeadership func(newLeader bool)
  803. updateCommittedIndex func(uint64)
  804. }
  805. func (s *EtcdServer) run() {
  806. lg := s.getLogger()
  807. sn, err := s.r.raftStorage.Snapshot()
  808. if err != nil {
  809. if lg != nil {
  810. lg.Panic("failed to get snapshot from Raft storage", zap.Error(err))
  811. } else {
  812. plog.Panicf("get snapshot from raft storage error: %v", err)
  813. }
  814. }
  815. // asynchronously accept apply packets, dispatch progress in-order
  816. sched := schedule.NewFIFOScheduler()
  817. var (
  818. smu sync.RWMutex
  819. syncC <-chan time.Time
  820. )
  821. setSyncC := func(ch <-chan time.Time) {
  822. smu.Lock()
  823. syncC = ch
  824. smu.Unlock()
  825. }
  826. getSyncC := func() (ch <-chan time.Time) {
  827. smu.RLock()
  828. ch = syncC
  829. smu.RUnlock()
  830. return
  831. }
  832. rh := &raftReadyHandler{
  833. getLead: func() (lead uint64) { return s.getLead() },
  834. updateLead: func(lead uint64) { s.setLead(lead) },
  835. updateLeadership: func(newLeader bool) {
  836. if !s.isLeader() {
  837. if s.lessor != nil {
  838. s.lessor.Demote()
  839. }
  840. if s.compactor != nil {
  841. s.compactor.Pause()
  842. }
  843. setSyncC(nil)
  844. } else {
  845. if newLeader {
  846. t := time.Now()
  847. s.leadTimeMu.Lock()
  848. s.leadElectedTime = t
  849. s.leadTimeMu.Unlock()
  850. }
  851. setSyncC(s.SyncTicker.C)
  852. if s.compactor != nil {
  853. s.compactor.Resume()
  854. }
  855. }
  856. if newLeader {
  857. s.leaderChangedMu.Lock()
  858. lc := s.leaderChanged
  859. s.leaderChanged = make(chan struct{})
  860. close(lc)
  861. s.leaderChangedMu.Unlock()
  862. }
  863. // TODO: remove the nil checking
  864. // current test utility does not provide the stats
  865. if s.stats != nil {
  866. s.stats.BecomeLeader()
  867. }
  868. },
  869. updateCommittedIndex: func(ci uint64) {
  870. cci := s.getCommittedIndex()
  871. if ci > cci {
  872. s.setCommittedIndex(ci)
  873. }
  874. },
  875. }
  876. s.r.start(rh)
  877. ep := etcdProgress{
  878. confState: sn.Metadata.ConfState,
  879. snapi: sn.Metadata.Index,
  880. appliedt: sn.Metadata.Term,
  881. appliedi: sn.Metadata.Index,
  882. }
  883. defer func() {
  884. s.wgMu.Lock() // block concurrent waitgroup adds in goAttach while stopping
  885. close(s.stopping)
  886. s.wgMu.Unlock()
  887. s.cancel()
  888. sched.Stop()
  889. // wait for gouroutines before closing raft so wal stays open
  890. s.wg.Wait()
  891. s.SyncTicker.Stop()
  892. // must stop raft after scheduler-- etcdserver can leak rafthttp pipelines
  893. // by adding a peer after raft stops the transport
  894. s.r.stop()
  895. // kv, lessor and backend can be nil if running without v3 enabled
  896. // or running unit tests.
  897. if s.lessor != nil {
  898. s.lessor.Stop()
  899. }
  900. if s.kv != nil {
  901. s.kv.Close()
  902. }
  903. if s.authStore != nil {
  904. s.authStore.Close()
  905. }
  906. if s.be != nil {
  907. s.be.Close()
  908. }
  909. if s.compactor != nil {
  910. s.compactor.Stop()
  911. }
  912. close(s.done)
  913. }()
  914. var expiredLeaseC <-chan []*lease.Lease
  915. if s.lessor != nil {
  916. expiredLeaseC = s.lessor.ExpiredLeasesC()
  917. }
  918. for {
  919. select {
  920. case ap := <-s.r.apply():
  921. f := func(context.Context) { s.applyAll(&ep, &ap) }
  922. sched.Schedule(f)
  923. case leases := <-expiredLeaseC:
  924. s.goAttach(func() {
  925. // Increases throughput of expired leases deletion process through parallelization
  926. c := make(chan struct{}, maxPendingRevokes)
  927. for _, lease := range leases {
  928. select {
  929. case c <- struct{}{}:
  930. case <-s.stopping:
  931. return
  932. }
  933. lid := lease.ID
  934. s.goAttach(func() {
  935. ctx := s.authStore.WithRoot(s.ctx)
  936. _, lerr := s.LeaseRevoke(ctx, &pb.LeaseRevokeRequest{ID: int64(lid)})
  937. if lerr == nil {
  938. leaseExpired.Inc()
  939. } else {
  940. if lg != nil {
  941. lg.Warn(
  942. "failed to revoke lease",
  943. zap.String("lease-id", fmt.Sprintf("%016x", lid)),
  944. zap.Error(lerr),
  945. )
  946. } else {
  947. plog.Warningf("failed to revoke %016x (%q)", lid, lerr.Error())
  948. }
  949. }
  950. <-c
  951. })
  952. }
  953. })
  954. case err := <-s.errorc:
  955. if lg != nil {
  956. lg.Warn("server error", zap.Error(err))
  957. lg.Warn("data-dir used by this member must be removed")
  958. } else {
  959. plog.Errorf("%s", err)
  960. plog.Infof("the data-dir used by this member must be removed.")
  961. }
  962. return
  963. case <-getSyncC():
  964. if s.v2store.HasTTLKeys() {
  965. s.sync(s.Cfg.ReqTimeout())
  966. }
  967. case <-s.stop:
  968. return
  969. }
  970. }
  971. }
  972. func (s *EtcdServer) applyAll(ep *etcdProgress, apply *apply) {
  973. s.applySnapshot(ep, apply)
  974. s.applyEntries(ep, apply)
  975. proposalsApplied.Set(float64(ep.appliedi))
  976. s.applyWait.Trigger(ep.appliedi)
  977. // wait for the raft routine to finish the disk writes before triggering a
  978. // snapshot. or applied index might be greater than the last index in raft
  979. // storage, since the raft routine might be slower than apply routine.
  980. <-apply.notifyc
  981. s.triggerSnapshot(ep)
  982. select {
  983. // snapshot requested via send()
  984. case m := <-s.r.msgSnapC:
  985. merged := s.createMergedSnapshotMessage(m, ep.appliedt, ep.appliedi, ep.confState)
  986. s.sendMergedSnap(merged)
  987. default:
  988. }
  989. }
  990. func (s *EtcdServer) applySnapshot(ep *etcdProgress, apply *apply) {
  991. if raft.IsEmptySnap(apply.snapshot) {
  992. return
  993. }
  994. applySnapshotInProgress.Inc()
  995. lg := s.getLogger()
  996. if lg != nil {
  997. lg.Info(
  998. "applying snapshot",
  999. zap.Uint64("current-snapshot-index", ep.snapi),
  1000. zap.Uint64("current-applied-index", ep.appliedi),
  1001. zap.Uint64("incoming-leader-snapshot-index", apply.snapshot.Metadata.Index),
  1002. zap.Uint64("incoming-leader-snapshot-term", apply.snapshot.Metadata.Term),
  1003. )
  1004. } else {
  1005. plog.Infof("applying snapshot at index %d...", ep.snapi)
  1006. }
  1007. defer func() {
  1008. if lg != nil {
  1009. lg.Info(
  1010. "applied snapshot",
  1011. zap.Uint64("current-snapshot-index", ep.snapi),
  1012. zap.Uint64("current-applied-index", ep.appliedi),
  1013. zap.Uint64("incoming-leader-snapshot-index", apply.snapshot.Metadata.Index),
  1014. zap.Uint64("incoming-leader-snapshot-term", apply.snapshot.Metadata.Term),
  1015. )
  1016. } else {
  1017. plog.Infof("finished applying incoming snapshot at index %d", ep.snapi)
  1018. }
  1019. applySnapshotInProgress.Dec()
  1020. }()
  1021. if apply.snapshot.Metadata.Index <= ep.appliedi {
  1022. if lg != nil {
  1023. lg.Panic(
  1024. "unexpected leader snapshot from outdated index",
  1025. zap.Uint64("current-snapshot-index", ep.snapi),
  1026. zap.Uint64("current-applied-index", ep.appliedi),
  1027. zap.Uint64("incoming-leader-snapshot-index", apply.snapshot.Metadata.Index),
  1028. zap.Uint64("incoming-leader-snapshot-term", apply.snapshot.Metadata.Term),
  1029. )
  1030. } else {
  1031. plog.Panicf("snapshot index [%d] should > appliedi[%d] + 1",
  1032. apply.snapshot.Metadata.Index, ep.appliedi)
  1033. }
  1034. }
  1035. // wait for raftNode to persist snapshot onto the disk
  1036. <-apply.notifyc
  1037. newbe, err := openSnapshotBackend(s.Cfg, s.snapshotter, apply.snapshot)
  1038. if err != nil {
  1039. if lg != nil {
  1040. lg.Panic("failed to open snapshot backend", zap.Error(err))
  1041. } else {
  1042. plog.Panic(err)
  1043. }
  1044. }
  1045. // always recover lessor before kv. When we recover the mvcc.KV it will reattach keys to its leases.
  1046. // If we recover mvcc.KV first, it will attach the keys to the wrong lessor before it recovers.
  1047. if s.lessor != nil {
  1048. if lg != nil {
  1049. lg.Info("restoring lease store")
  1050. } else {
  1051. plog.Info("recovering lessor...")
  1052. }
  1053. s.lessor.Recover(newbe, func() lease.TxnDelete { return s.kv.Write(traceutil.TODO()) })
  1054. if lg != nil {
  1055. lg.Info("restored lease store")
  1056. } else {
  1057. plog.Info("finished recovering lessor")
  1058. }
  1059. }
  1060. if lg != nil {
  1061. lg.Info("restoring mvcc store")
  1062. } else {
  1063. plog.Info("restoring mvcc store...")
  1064. }
  1065. if err := s.kv.Restore(newbe); err != nil {
  1066. if lg != nil {
  1067. lg.Panic("failed to restore mvcc store", zap.Error(err))
  1068. } else {
  1069. plog.Panicf("restore KV error: %v", err)
  1070. }
  1071. }
  1072. s.consistIndex.setConsistentIndex(s.kv.ConsistentIndex())
  1073. if lg != nil {
  1074. lg.Info("restored mvcc store")
  1075. } else {
  1076. plog.Info("finished restoring mvcc store")
  1077. }
  1078. // Closing old backend might block until all the txns
  1079. // on the backend are finished.
  1080. // We do not want to wait on closing the old backend.
  1081. s.bemu.Lock()
  1082. oldbe := s.be
  1083. go func() {
  1084. if lg != nil {
  1085. lg.Info("closing old backend file")
  1086. } else {
  1087. plog.Info("closing old backend...")
  1088. }
  1089. defer func() {
  1090. if lg != nil {
  1091. lg.Info("closed old backend file")
  1092. } else {
  1093. plog.Info("finished closing old backend")
  1094. }
  1095. }()
  1096. if err := oldbe.Close(); err != nil {
  1097. if lg != nil {
  1098. lg.Panic("failed to close old backend", zap.Error(err))
  1099. } else {
  1100. plog.Panicf("close backend error: %v", err)
  1101. }
  1102. }
  1103. }()
  1104. s.be = newbe
  1105. s.bemu.Unlock()
  1106. if lg != nil {
  1107. lg.Info("restoring alarm store")
  1108. } else {
  1109. plog.Info("recovering alarms...")
  1110. }
  1111. if err := s.restoreAlarms(); err != nil {
  1112. if lg != nil {
  1113. lg.Panic("failed to restore alarm store", zap.Error(err))
  1114. } else {
  1115. plog.Panicf("restore alarms error: %v", err)
  1116. }
  1117. }
  1118. if lg != nil {
  1119. lg.Info("restored alarm store")
  1120. } else {
  1121. plog.Info("finished recovering alarms")
  1122. }
  1123. if s.authStore != nil {
  1124. if lg != nil {
  1125. lg.Info("restoring auth store")
  1126. } else {
  1127. plog.Info("recovering auth store...")
  1128. }
  1129. s.authStore.Recover(newbe)
  1130. if lg != nil {
  1131. lg.Info("restored auth store")
  1132. } else {
  1133. plog.Info("finished recovering auth store")
  1134. }
  1135. }
  1136. if lg != nil {
  1137. lg.Info("restoring v2 store")
  1138. } else {
  1139. plog.Info("recovering store v2...")
  1140. }
  1141. if err := s.v2store.Recovery(apply.snapshot.Data); err != nil {
  1142. if lg != nil {
  1143. lg.Panic("failed to restore v2 store", zap.Error(err))
  1144. } else {
  1145. plog.Panicf("recovery store error: %v", err)
  1146. }
  1147. }
  1148. if lg != nil {
  1149. lg.Info("restored v2 store")
  1150. } else {
  1151. plog.Info("finished recovering store v2")
  1152. }
  1153. s.cluster.SetBackend(newbe)
  1154. if lg != nil {
  1155. lg.Info("restoring cluster configuration")
  1156. } else {
  1157. plog.Info("recovering cluster configuration...")
  1158. }
  1159. s.cluster.Recover(api.UpdateCapability)
  1160. if lg != nil {
  1161. lg.Info("restored cluster configuration")
  1162. lg.Info("removing old peers from network")
  1163. } else {
  1164. plog.Info("finished recovering cluster configuration")
  1165. plog.Info("removing old peers from network...")
  1166. }
  1167. // recover raft transport
  1168. s.r.transport.RemoveAllPeers()
  1169. if lg != nil {
  1170. lg.Info("removed old peers from network")
  1171. lg.Info("adding peers from new cluster configuration")
  1172. } else {
  1173. plog.Info("finished removing old peers from network")
  1174. plog.Info("adding peers from new cluster configuration into network...")
  1175. }
  1176. for _, m := range s.cluster.Members() {
  1177. if m.ID == s.ID() {
  1178. continue
  1179. }
  1180. s.r.transport.AddPeer(m.ID, m.PeerURLs)
  1181. }
  1182. if lg != nil {
  1183. lg.Info("added peers from new cluster configuration")
  1184. } else {
  1185. plog.Info("finished adding peers from new cluster configuration into network...")
  1186. }
  1187. ep.appliedt = apply.snapshot.Metadata.Term
  1188. ep.appliedi = apply.snapshot.Metadata.Index
  1189. ep.snapi = ep.appliedi
  1190. ep.confState = apply.snapshot.Metadata.ConfState
  1191. }
  1192. func (s *EtcdServer) applyEntries(ep *etcdProgress, apply *apply) {
  1193. if len(apply.entries) == 0 {
  1194. return
  1195. }
  1196. firsti := apply.entries[0].Index
  1197. if firsti > ep.appliedi+1 {
  1198. if lg := s.getLogger(); lg != nil {
  1199. lg.Panic(
  1200. "unexpected committed entry index",
  1201. zap.Uint64("current-applied-index", ep.appliedi),
  1202. zap.Uint64("first-committed-entry-index", firsti),
  1203. )
  1204. } else {
  1205. plog.Panicf("first index of committed entry[%d] should <= appliedi[%d] + 1", firsti, ep.appliedi)
  1206. }
  1207. }
  1208. var ents []raftpb.Entry
  1209. if ep.appliedi+1-firsti < uint64(len(apply.entries)) {
  1210. ents = apply.entries[ep.appliedi+1-firsti:]
  1211. }
  1212. if len(ents) == 0 {
  1213. return
  1214. }
  1215. var shouldstop bool
  1216. if ep.appliedt, ep.appliedi, shouldstop = s.apply(ents, &ep.confState); shouldstop {
  1217. go s.stopWithDelay(10*100*time.Millisecond, fmt.Errorf("the member has been permanently removed from the cluster"))
  1218. }
  1219. }
  1220. func (s *EtcdServer) triggerSnapshot(ep *etcdProgress) {
  1221. if ep.appliedi-ep.snapi <= s.Cfg.SnapshotCount {
  1222. return
  1223. }
  1224. if lg := s.getLogger(); lg != nil {
  1225. lg.Info(
  1226. "triggering snapshot",
  1227. zap.String("local-member-id", s.ID().String()),
  1228. zap.Uint64("local-member-applied-index", ep.appliedi),
  1229. zap.Uint64("local-member-snapshot-index", ep.snapi),
  1230. zap.Uint64("local-member-snapshot-count", s.Cfg.SnapshotCount),
  1231. )
  1232. } else {
  1233. plog.Infof("start to snapshot (applied: %d, lastsnap: %d)", ep.appliedi, ep.snapi)
  1234. }
  1235. s.snapshot(ep.appliedi, ep.confState)
  1236. ep.snapi = ep.appliedi
  1237. }
  1238. func (s *EtcdServer) hasMultipleVotingMembers() bool {
  1239. return s.cluster != nil && len(s.cluster.VotingMemberIDs()) > 1
  1240. }
  1241. func (s *EtcdServer) isLeader() bool {
  1242. return uint64(s.ID()) == s.Lead()
  1243. }
  1244. // MoveLeader transfers the leader to the given transferee.
  1245. func (s *EtcdServer) MoveLeader(ctx context.Context, lead, transferee uint64) error {
  1246. if !s.cluster.IsMemberExist(types.ID(transferee)) || s.cluster.Member(types.ID(transferee)).IsLearner {
  1247. return ErrBadLeaderTransferee
  1248. }
  1249. now := time.Now()
  1250. interval := time.Duration(s.Cfg.TickMs) * time.Millisecond
  1251. if lg := s.getLogger(); lg != nil {
  1252. lg.Info(
  1253. "leadership transfer starting",
  1254. zap.String("local-member-id", s.ID().String()),
  1255. zap.String("current-leader-member-id", types.ID(lead).String()),
  1256. zap.String("transferee-member-id", types.ID(transferee).String()),
  1257. )
  1258. } else {
  1259. plog.Infof("%s starts leadership transfer from %s to %s", s.ID(), types.ID(lead), types.ID(transferee))
  1260. }
  1261. s.r.TransferLeadership(ctx, lead, transferee)
  1262. for s.Lead() != transferee {
  1263. select {
  1264. case <-ctx.Done(): // time out
  1265. return ErrTimeoutLeaderTransfer
  1266. case <-time.After(interval):
  1267. }
  1268. }
  1269. // TODO: drain all requests, or drop all messages to the old leader
  1270. if lg := s.getLogger(); lg != nil {
  1271. lg.Info(
  1272. "leadership transfer finished",
  1273. zap.String("local-member-id", s.ID().String()),
  1274. zap.String("old-leader-member-id", types.ID(lead).String()),
  1275. zap.String("new-leader-member-id", types.ID(transferee).String()),
  1276. zap.Duration("took", time.Since(now)),
  1277. )
  1278. } else {
  1279. plog.Infof("%s finished leadership transfer from %s to %s (took %v)", s.ID(), types.ID(lead), types.ID(transferee), time.Since(now))
  1280. }
  1281. return nil
  1282. }
  1283. // TransferLeadership transfers the leader to the chosen transferee.
  1284. func (s *EtcdServer) TransferLeadership() error {
  1285. if !s.isLeader() {
  1286. if lg := s.getLogger(); lg != nil {
  1287. lg.Info(
  1288. "skipped leadership transfer; local server is not leader",
  1289. zap.String("local-member-id", s.ID().String()),
  1290. zap.String("current-leader-member-id", types.ID(s.Lead()).String()),
  1291. )
  1292. } else {
  1293. plog.Printf("skipped leadership transfer for stopping non-leader member")
  1294. }
  1295. return nil
  1296. }
  1297. if !s.hasMultipleVotingMembers() {
  1298. if lg := s.getLogger(); lg != nil {
  1299. lg.Info(
  1300. "skipped leadership transfer for single voting member cluster",
  1301. zap.String("local-member-id", s.ID().String()),
  1302. zap.String("current-leader-member-id", types.ID(s.Lead()).String()),
  1303. )
  1304. } else {
  1305. plog.Printf("skipped leadership transfer for single voting member cluster")
  1306. }
  1307. return nil
  1308. }
  1309. transferee, ok := longestConnected(s.r.transport, s.cluster.VotingMemberIDs())
  1310. if !ok {
  1311. return ErrUnhealthy
  1312. }
  1313. tm := s.Cfg.ReqTimeout()
  1314. ctx, cancel := context.WithTimeout(s.ctx, tm)
  1315. err := s.MoveLeader(ctx, s.Lead(), uint64(transferee))
  1316. cancel()
  1317. return err
  1318. }
  1319. // HardStop stops the server without coordination with other members in the cluster.
  1320. func (s *EtcdServer) HardStop() {
  1321. select {
  1322. case s.stop <- struct{}{}:
  1323. case <-s.done:
  1324. return
  1325. }
  1326. <-s.done
  1327. }
  1328. // Stop stops the server gracefully, and shuts down the running goroutine.
  1329. // Stop should be called after a Start(s), otherwise it will block forever.
  1330. // When stopping leader, Stop transfers its leadership to one of its peers
  1331. // before stopping the server.
  1332. // Stop terminates the Server and performs any necessary finalization.
  1333. // Do and Process cannot be called after Stop has been invoked.
  1334. func (s *EtcdServer) Stop() {
  1335. if err := s.TransferLeadership(); err != nil {
  1336. if lg := s.getLogger(); lg != nil {
  1337. lg.Warn("leadership transfer failed", zap.String("local-member-id", s.ID().String()), zap.Error(err))
  1338. } else {
  1339. plog.Warningf("%s failed to transfer leadership (%v)", s.ID(), err)
  1340. }
  1341. }
  1342. s.HardStop()
  1343. }
  1344. // ReadyNotify returns a channel that will be closed when the server
  1345. // is ready to serve client requests
  1346. func (s *EtcdServer) ReadyNotify() <-chan struct{} { return s.readych }
  1347. func (s *EtcdServer) stopWithDelay(d time.Duration, err error) {
  1348. select {
  1349. case <-time.After(d):
  1350. case <-s.done:
  1351. }
  1352. select {
  1353. case s.errorc <- err:
  1354. default:
  1355. }
  1356. }
  1357. // StopNotify returns a channel that receives a empty struct
  1358. // when the server is stopped.
  1359. func (s *EtcdServer) StopNotify() <-chan struct{} { return s.done }
  1360. func (s *EtcdServer) SelfStats() []byte { return s.stats.JSON() }
  1361. func (s *EtcdServer) LeaderStats() []byte {
  1362. lead := s.getLead()
  1363. if lead != uint64(s.id) {
  1364. return nil
  1365. }
  1366. return s.lstats.JSON()
  1367. }
  1368. func (s *EtcdServer) StoreStats() []byte { return s.v2store.JsonStats() }
  1369. func (s *EtcdServer) checkMembershipOperationPermission(ctx context.Context) error {
  1370. if s.authStore == nil {
  1371. // In the context of ordinary etcd process, s.authStore will never be nil.
  1372. // This branch is for handling cases in server_test.go
  1373. return nil
  1374. }
  1375. // Note that this permission check is done in the API layer,
  1376. // so TOCTOU problem can be caused potentially in a schedule like this:
  1377. // update membership with user A -> revoke root role of A -> apply membership change
  1378. // in the state machine layer
  1379. // However, both of membership change and role management requires the root privilege.
  1380. // So careful operation by admins can prevent the problem.
  1381. authInfo, err := s.AuthInfoFromCtx(ctx)
  1382. if err != nil {
  1383. return err
  1384. }
  1385. return s.AuthStore().IsAdminPermitted(authInfo)
  1386. }
  1387. func (s *EtcdServer) AddMember(ctx context.Context, memb membership.Member) ([]*membership.Member, error) {
  1388. if err := s.checkMembershipOperationPermission(ctx); err != nil {
  1389. return nil, err
  1390. }
  1391. // TODO: move Member to protobuf type
  1392. b, err := json.Marshal(memb)
  1393. if err != nil {
  1394. return nil, err
  1395. }
  1396. // by default StrictReconfigCheck is enabled; reject new members if unhealthy.
  1397. if err := s.mayAddMember(memb); err != nil {
  1398. return nil, err
  1399. }
  1400. cc := raftpb.ConfChange{
  1401. Type: raftpb.ConfChangeAddNode,
  1402. NodeID: uint64(memb.ID),
  1403. Context: b,
  1404. }
  1405. if memb.IsLearner {
  1406. cc.Type = raftpb.ConfChangeAddLearnerNode
  1407. }
  1408. return s.configure(ctx, cc)
  1409. }
  1410. func (s *EtcdServer) mayAddMember(memb membership.Member) error {
  1411. if !s.Cfg.StrictReconfigCheck {
  1412. return nil
  1413. }
  1414. // protect quorum when adding voting member
  1415. if !memb.IsLearner && !s.cluster.IsReadyToAddVotingMember() {
  1416. if lg := s.getLogger(); lg != nil {
  1417. lg.Warn(
  1418. "rejecting member add request; not enough healthy members",
  1419. zap.String("local-member-id", s.ID().String()),
  1420. zap.String("requested-member-add", fmt.Sprintf("%+v", memb)),
  1421. zap.Error(ErrNotEnoughStartedMembers),
  1422. )
  1423. } else {
  1424. plog.Warningf("not enough started members, rejecting member add %+v", memb)
  1425. }
  1426. return ErrNotEnoughStartedMembers
  1427. }
  1428. if !isConnectedFullySince(s.r.transport, time.Now().Add(-HealthInterval), s.ID(), s.cluster.VotingMembers()) {
  1429. if lg := s.getLogger(); lg != nil {
  1430. lg.Warn(
  1431. "rejecting member add request; local member has not been connected to all peers, reconfigure breaks active quorum",
  1432. zap.String("local-member-id", s.ID().String()),
  1433. zap.String("requested-member-add", fmt.Sprintf("%+v", memb)),
  1434. zap.Error(ErrUnhealthy),
  1435. )
  1436. } else {
  1437. plog.Warningf("not healthy for reconfigure, rejecting member add %+v", memb)
  1438. }
  1439. return ErrUnhealthy
  1440. }
  1441. return nil
  1442. }
  1443. func (s *EtcdServer) RemoveMember(ctx context.Context, id uint64) ([]*membership.Member, error) {
  1444. if err := s.checkMembershipOperationPermission(ctx); err != nil {
  1445. return nil, err
  1446. }
  1447. // by default StrictReconfigCheck is enabled; reject removal if leads to quorum loss
  1448. if err := s.mayRemoveMember(types.ID(id)); err != nil {
  1449. return nil, err
  1450. }
  1451. cc := raftpb.ConfChange{
  1452. Type: raftpb.ConfChangeRemoveNode,
  1453. NodeID: id,
  1454. }
  1455. return s.configure(ctx, cc)
  1456. }
  1457. // PromoteMember promotes a learner node to a voting node.
  1458. func (s *EtcdServer) PromoteMember(ctx context.Context, id uint64) ([]*membership.Member, error) {
  1459. // only raft leader has information on whether the to-be-promoted learner node is ready. If promoteMember call
  1460. // fails with ErrNotLeader, forward the request to leader node via HTTP. If promoteMember call fails with error
  1461. // other than ErrNotLeader, return the error.
  1462. resp, err := s.promoteMember(ctx, id)
  1463. if err == nil {
  1464. learnerPromoteSucceed.Inc()
  1465. return resp, nil
  1466. }
  1467. if err != ErrNotLeader {
  1468. learnerPromoteFailed.WithLabelValues(err.Error()).Inc()
  1469. return resp, err
  1470. }
  1471. cctx, cancel := context.WithTimeout(ctx, s.Cfg.ReqTimeout())
  1472. defer cancel()
  1473. // forward to leader
  1474. for cctx.Err() == nil {
  1475. leader, err := s.waitLeader(cctx)
  1476. if err != nil {
  1477. return nil, err
  1478. }
  1479. for _, url := range leader.PeerURLs {
  1480. resp, err := promoteMemberHTTP(cctx, url, id, s.peerRt)
  1481. if err == nil {
  1482. return resp, nil
  1483. }
  1484. // If member promotion failed, return early. Otherwise keep retry.
  1485. if err == ErrLearnerNotReady || err == membership.ErrIDNotFound || err == membership.ErrMemberNotLearner {
  1486. return nil, err
  1487. }
  1488. }
  1489. }
  1490. if cctx.Err() == context.DeadlineExceeded {
  1491. return nil, ErrTimeout
  1492. }
  1493. return nil, ErrCanceled
  1494. }
  1495. // promoteMember checks whether the to-be-promoted learner node is ready before sending the promote
  1496. // request to raft.
  1497. // The function returns ErrNotLeader if the local node is not raft leader (therefore does not have
  1498. // enough information to determine if the learner node is ready), returns ErrLearnerNotReady if the
  1499. // local node is leader (therefore has enough information) but decided the learner node is not ready
  1500. // to be promoted.
  1501. func (s *EtcdServer) promoteMember(ctx context.Context, id uint64) ([]*membership.Member, error) {
  1502. if err := s.checkMembershipOperationPermission(ctx); err != nil {
  1503. return nil, err
  1504. }
  1505. // check if we can promote this learner.
  1506. if err := s.mayPromoteMember(types.ID(id)); err != nil {
  1507. return nil, err
  1508. }
  1509. // build the context for the promote confChange. mark IsLearner to false and IsPromote to true.
  1510. promoteChangeContext := membership.ConfigChangeContext{
  1511. Member: membership.Member{
  1512. ID: types.ID(id),
  1513. },
  1514. IsPromote: true,
  1515. }
  1516. b, err := json.Marshal(promoteChangeContext)
  1517. if err != nil {
  1518. return nil, err
  1519. }
  1520. cc := raftpb.ConfChange{
  1521. Type: raftpb.ConfChangeAddNode,
  1522. NodeID: id,
  1523. Context: b,
  1524. }
  1525. return s.configure(ctx, cc)
  1526. }
  1527. func (s *EtcdServer) mayPromoteMember(id types.ID) error {
  1528. err := s.isLearnerReady(uint64(id))
  1529. if err != nil {
  1530. return err
  1531. }
  1532. if !s.Cfg.StrictReconfigCheck {
  1533. return nil
  1534. }
  1535. if !s.cluster.IsReadyToPromoteMember(uint64(id)) {
  1536. if lg := s.getLogger(); lg != nil {
  1537. lg.Warn(
  1538. "rejecting member promote request; not enough healthy members",
  1539. zap.String("local-member-id", s.ID().String()),
  1540. zap.String("requested-member-remove-id", id.String()),
  1541. zap.Error(ErrNotEnoughStartedMembers),
  1542. )
  1543. } else {
  1544. plog.Warningf("not enough started members, rejecting promote member %s", id)
  1545. }
  1546. return ErrNotEnoughStartedMembers
  1547. }
  1548. return nil
  1549. }
  1550. // check whether the learner catches up with leader or not.
  1551. // Note: it will return nil if member is not found in cluster or if member is not learner.
  1552. // These two conditions will be checked before apply phase later.
  1553. func (s *EtcdServer) isLearnerReady(id uint64) error {
  1554. rs := s.raftStatus()
  1555. // leader's raftStatus.Progress is not nil
  1556. if rs.Progress == nil {
  1557. return ErrNotLeader
  1558. }
  1559. var learnerMatch uint64
  1560. isFound := false
  1561. leaderID := rs.ID
  1562. for memberID, progress := range rs.Progress {
  1563. if id == memberID {
  1564. // check its status
  1565. learnerMatch = progress.Match
  1566. isFound = true
  1567. break
  1568. }
  1569. }
  1570. if isFound {
  1571. leaderMatch := rs.Progress[leaderID].Match
  1572. // the learner's Match not caught up with leader yet
  1573. if float64(learnerMatch) < float64(leaderMatch)*readyPercent {
  1574. return ErrLearnerNotReady
  1575. }
  1576. }
  1577. return nil
  1578. }
  1579. func (s *EtcdServer) mayRemoveMember(id types.ID) error {
  1580. if !s.Cfg.StrictReconfigCheck {
  1581. return nil
  1582. }
  1583. isLearner := s.cluster.IsMemberExist(id) && s.cluster.Member(id).IsLearner
  1584. // no need to check quorum when removing non-voting member
  1585. if isLearner {
  1586. return nil
  1587. }
  1588. if !s.cluster.IsReadyToRemoveVotingMember(uint64(id)) {
  1589. if lg := s.getLogger(); lg != nil {
  1590. lg.Warn(
  1591. "rejecting member remove request; not enough healthy members",
  1592. zap.String("local-member-id", s.ID().String()),
  1593. zap.String("requested-member-remove-id", id.String()),
  1594. zap.Error(ErrNotEnoughStartedMembers),
  1595. )
  1596. } else {
  1597. plog.Warningf("not enough started members, rejecting remove member %s", id)
  1598. }
  1599. return ErrNotEnoughStartedMembers
  1600. }
  1601. // downed member is safe to remove since it's not part of the active quorum
  1602. if t := s.r.transport.ActiveSince(id); id != s.ID() && t.IsZero() {
  1603. return nil
  1604. }
  1605. // protect quorum if some members are down
  1606. m := s.cluster.VotingMembers()
  1607. active := numConnectedSince(s.r.transport, time.Now().Add(-HealthInterval), s.ID(), m)
  1608. if (active - 1) < 1+((len(m)-1)/2) {
  1609. if lg := s.getLogger(); lg != nil {
  1610. lg.Warn(
  1611. "rejecting member remove request; local member has not been connected to all peers, reconfigure breaks active quorum",
  1612. zap.String("local-member-id", s.ID().String()),
  1613. zap.String("requested-member-remove", id.String()),
  1614. zap.Int("active-peers", active),
  1615. zap.Error(ErrUnhealthy),
  1616. )
  1617. } else {
  1618. plog.Warningf("reconfigure breaks active quorum, rejecting remove member %s", id)
  1619. }
  1620. return ErrUnhealthy
  1621. }
  1622. return nil
  1623. }
  1624. func (s *EtcdServer) UpdateMember(ctx context.Context, memb membership.Member) ([]*membership.Member, error) {
  1625. b, merr := json.Marshal(memb)
  1626. if merr != nil {
  1627. return nil, merr
  1628. }
  1629. if err := s.checkMembershipOperationPermission(ctx); err != nil {
  1630. return nil, err
  1631. }
  1632. cc := raftpb.ConfChange{
  1633. Type: raftpb.ConfChangeUpdateNode,
  1634. NodeID: uint64(memb.ID),
  1635. Context: b,
  1636. }
  1637. return s.configure(ctx, cc)
  1638. }
  1639. func (s *EtcdServer) setCommittedIndex(v uint64) {
  1640. atomic.StoreUint64(&s.committedIndex, v)
  1641. }
  1642. func (s *EtcdServer) getCommittedIndex() uint64 {
  1643. return atomic.LoadUint64(&s.committedIndex)
  1644. }
  1645. func (s *EtcdServer) setAppliedIndex(v uint64) {
  1646. atomic.StoreUint64(&s.appliedIndex, v)
  1647. }
  1648. func (s *EtcdServer) getAppliedIndex() uint64 {
  1649. return atomic.LoadUint64(&s.appliedIndex)
  1650. }
  1651. func (s *EtcdServer) setTerm(v uint64) {
  1652. atomic.StoreUint64(&s.term, v)
  1653. }
  1654. func (s *EtcdServer) getTerm() uint64 {
  1655. return atomic.LoadUint64(&s.term)
  1656. }
  1657. func (s *EtcdServer) setLead(v uint64) {
  1658. atomic.StoreUint64(&s.lead, v)
  1659. }
  1660. func (s *EtcdServer) getLead() uint64 {
  1661. return atomic.LoadUint64(&s.lead)
  1662. }
  1663. func (s *EtcdServer) leaderChangedNotify() <-chan struct{} {
  1664. s.leaderChangedMu.RLock()
  1665. defer s.leaderChangedMu.RUnlock()
  1666. return s.leaderChanged
  1667. }
  1668. // RaftStatusGetter represents etcd server and Raft progress.
  1669. type RaftStatusGetter interface {
  1670. ID() types.ID
  1671. Leader() types.ID
  1672. CommittedIndex() uint64
  1673. AppliedIndex() uint64
  1674. Term() uint64
  1675. }
  1676. func (s *EtcdServer) ID() types.ID { return s.id }
  1677. func (s *EtcdServer) Leader() types.ID { return types.ID(s.getLead()) }
  1678. func (s *EtcdServer) Lead() uint64 { return s.getLead() }
  1679. func (s *EtcdServer) CommittedIndex() uint64 { return s.getCommittedIndex() }
  1680. func (s *EtcdServer) AppliedIndex() uint64 { return s.getAppliedIndex() }
  1681. func (s *EtcdServer) Term() uint64 { return s.getTerm() }
  1682. type confChangeResponse struct {
  1683. membs []*membership.Member
  1684. err error
  1685. }
  1686. // configure sends a configuration change through consensus and
  1687. // then waits for it to be applied to the server. It
  1688. // will block until the change is performed or there is an error.
  1689. func (s *EtcdServer) configure(ctx context.Context, cc raftpb.ConfChange) ([]*membership.Member, error) {
  1690. cc.ID = s.reqIDGen.Next()
  1691. ch := s.w.Register(cc.ID)
  1692. start := time.Now()
  1693. if err := s.r.ProposeConfChange(ctx, cc); err != nil {
  1694. s.w.Trigger(cc.ID, nil)
  1695. return nil, err
  1696. }
  1697. select {
  1698. case x := <-ch:
  1699. if x == nil {
  1700. if lg := s.getLogger(); lg != nil {
  1701. lg.Panic("failed to configure")
  1702. } else {
  1703. plog.Panicf("configure trigger value should never be nil")
  1704. }
  1705. }
  1706. resp := x.(*confChangeResponse)
  1707. if lg := s.getLogger(); lg != nil {
  1708. lg.Info(
  1709. "applied a configuration change through raft",
  1710. zap.String("local-member-id", s.ID().String()),
  1711. zap.String("raft-conf-change", cc.Type.String()),
  1712. zap.String("raft-conf-change-node-id", types.ID(cc.NodeID).String()),
  1713. )
  1714. }
  1715. return resp.membs, resp.err
  1716. case <-ctx.Done():
  1717. s.w.Trigger(cc.ID, nil) // GC wait
  1718. return nil, s.parseProposeCtxErr(ctx.Err(), start)
  1719. case <-s.stopping:
  1720. return nil, ErrStopped
  1721. }
  1722. }
  1723. // sync proposes a SYNC request and is non-blocking.
  1724. // This makes no guarantee that the request will be proposed or performed.
  1725. // The request will be canceled after the given timeout.
  1726. func (s *EtcdServer) sync(timeout time.Duration) {
  1727. req := pb.Request{
  1728. Method: "SYNC",
  1729. ID: s.reqIDGen.Next(),
  1730. Time: time.Now().UnixNano(),
  1731. }
  1732. data := pbutil.MustMarshal(&req)
  1733. // There is no promise that node has leader when do SYNC request,
  1734. // so it uses goroutine to propose.
  1735. ctx, cancel := context.WithTimeout(s.ctx, timeout)
  1736. s.goAttach(func() {
  1737. s.r.Propose(ctx, data)
  1738. cancel()
  1739. })
  1740. }
  1741. // publish registers server information into the cluster. The information
  1742. // is the JSON representation of this server's member struct, updated with the
  1743. // static clientURLs of the server.
  1744. // The function keeps attempting to register until it succeeds,
  1745. // or its server is stopped.
  1746. //
  1747. // Use v2 store to encode member attributes, and apply through Raft
  1748. // but does not go through v2 API endpoint, which means even with v2
  1749. // client handler disabled (e.g. --enable-v2=false), cluster can still
  1750. // process publish requests through rafthttp
  1751. // TODO: Deprecate v2 store
  1752. func (s *EtcdServer) publish(timeout time.Duration) {
  1753. b, err := json.Marshal(s.attributes)
  1754. if err != nil {
  1755. if lg := s.getLogger(); lg != nil {
  1756. lg.Panic("failed to marshal JSON", zap.Error(err))
  1757. } else {
  1758. plog.Panicf("json marshal error: %v", err)
  1759. }
  1760. return
  1761. }
  1762. req := pb.Request{
  1763. Method: "PUT",
  1764. Path: membership.MemberAttributesStorePath(s.id),
  1765. Val: string(b),
  1766. }
  1767. for {
  1768. ctx, cancel := context.WithTimeout(s.ctx, timeout)
  1769. _, err := s.Do(ctx, req)
  1770. cancel()
  1771. switch err {
  1772. case nil:
  1773. close(s.readych)
  1774. if lg := s.getLogger(); lg != nil {
  1775. lg.Info(
  1776. "published local member to cluster through raft",
  1777. zap.String("local-member-id", s.ID().String()),
  1778. zap.String("local-member-attributes", fmt.Sprintf("%+v", s.attributes)),
  1779. zap.String("request-path", req.Path),
  1780. zap.String("cluster-id", s.cluster.ID().String()),
  1781. zap.Duration("publish-timeout", timeout),
  1782. )
  1783. } else {
  1784. plog.Infof("published %+v to cluster %s", s.attributes, s.cluster.ID())
  1785. }
  1786. return
  1787. case ErrStopped:
  1788. if lg := s.getLogger(); lg != nil {
  1789. lg.Warn(
  1790. "stopped publish because server is stopped",
  1791. zap.String("local-member-id", s.ID().String()),
  1792. zap.String("local-member-attributes", fmt.Sprintf("%+v", s.attributes)),
  1793. zap.Duration("publish-timeout", timeout),
  1794. zap.Error(err),
  1795. )
  1796. } else {
  1797. plog.Infof("aborting publish because server is stopped")
  1798. }
  1799. return
  1800. default:
  1801. if lg := s.getLogger(); lg != nil {
  1802. lg.Warn(
  1803. "failed to publish local member to cluster through raft",
  1804. zap.String("local-member-id", s.ID().String()),
  1805. zap.String("local-member-attributes", fmt.Sprintf("%+v", s.attributes)),
  1806. zap.String("request-path", req.Path),
  1807. zap.Duration("publish-timeout", timeout),
  1808. zap.Error(err),
  1809. )
  1810. } else {
  1811. plog.Errorf("publish error: %v", err)
  1812. }
  1813. }
  1814. }
  1815. }
  1816. func (s *EtcdServer) sendMergedSnap(merged snap.Message) {
  1817. atomic.AddInt64(&s.inflightSnapshots, 1)
  1818. lg := s.getLogger()
  1819. fields := []zap.Field{
  1820. zap.String("from", s.ID().String()),
  1821. zap.String("to", types.ID(merged.To).String()),
  1822. zap.Int64("bytes", merged.TotalSize),
  1823. zap.String("size", humanize.Bytes(uint64(merged.TotalSize))),
  1824. }
  1825. now := time.Now()
  1826. s.r.transport.SendSnapshot(merged)
  1827. if lg != nil {
  1828. lg.Info("sending merged snapshot", fields...)
  1829. }
  1830. s.goAttach(func() {
  1831. select {
  1832. case ok := <-merged.CloseNotify():
  1833. // delay releasing inflight snapshot for another 30 seconds to
  1834. // block log compaction.
  1835. // If the follower still fails to catch up, it is probably just too slow
  1836. // to catch up. We cannot avoid the snapshot cycle anyway.
  1837. if ok {
  1838. select {
  1839. case <-time.After(releaseDelayAfterSnapshot):
  1840. case <-s.stopping:
  1841. }
  1842. }
  1843. atomic.AddInt64(&s.inflightSnapshots, -1)
  1844. if lg != nil {
  1845. lg.Info("sent merged snapshot", append(fields, zap.Duration("took", time.Since(now)))...)
  1846. }
  1847. case <-s.stopping:
  1848. if lg != nil {
  1849. lg.Warn("canceled sending merged snapshot; server stopping", fields...)
  1850. }
  1851. return
  1852. }
  1853. })
  1854. }
  1855. // apply takes entries received from Raft (after it has been committed) and
  1856. // applies them to the current state of the EtcdServer.
  1857. // The given entries should not be empty.
  1858. func (s *EtcdServer) apply(
  1859. es []raftpb.Entry,
  1860. confState *raftpb.ConfState,
  1861. ) (appliedt uint64, appliedi uint64, shouldStop bool) {
  1862. for i := range es {
  1863. e := es[i]
  1864. switch e.Type {
  1865. case raftpb.EntryNormal:
  1866. s.applyEntryNormal(&e)
  1867. s.setAppliedIndex(e.Index)
  1868. s.setTerm(e.Term)
  1869. case raftpb.EntryConfChange:
  1870. // set the consistent index of current executing entry
  1871. if e.Index > s.consistIndex.ConsistentIndex() {
  1872. s.consistIndex.setConsistentIndex(e.Index)
  1873. }
  1874. var cc raftpb.ConfChange
  1875. pbutil.MustUnmarshal(&cc, e.Data)
  1876. removedSelf, err := s.applyConfChange(cc, confState)
  1877. s.setAppliedIndex(e.Index)
  1878. s.setTerm(e.Term)
  1879. shouldStop = shouldStop || removedSelf
  1880. s.w.Trigger(cc.ID, &confChangeResponse{s.cluster.Members(), err})
  1881. default:
  1882. if lg := s.getLogger(); lg != nil {
  1883. lg.Panic(
  1884. "unknown entry type; must be either EntryNormal or EntryConfChange",
  1885. zap.String("type", e.Type.String()),
  1886. )
  1887. } else {
  1888. plog.Panicf("entry type should be either EntryNormal or EntryConfChange")
  1889. }
  1890. }
  1891. appliedi, appliedt = e.Index, e.Term
  1892. }
  1893. return appliedt, appliedi, shouldStop
  1894. }
  1895. // applyEntryNormal apples an EntryNormal type raftpb request to the EtcdServer
  1896. func (s *EtcdServer) applyEntryNormal(e *raftpb.Entry) {
  1897. shouldApplyV3 := false
  1898. if e.Index > s.consistIndex.ConsistentIndex() {
  1899. // set the consistent index of current executing entry
  1900. s.consistIndex.setConsistentIndex(e.Index)
  1901. shouldApplyV3 = true
  1902. }
  1903. // raft state machine may generate noop entry when leader confirmation.
  1904. // skip it in advance to avoid some potential bug in the future
  1905. if len(e.Data) == 0 {
  1906. select {
  1907. case s.forceVersionC <- struct{}{}:
  1908. default:
  1909. }
  1910. // promote lessor when the local member is leader and finished
  1911. // applying all entries from the last term.
  1912. if s.isLeader() {
  1913. s.lessor.Promote(s.Cfg.electionTimeout())
  1914. }
  1915. return
  1916. }
  1917. var raftReq pb.InternalRaftRequest
  1918. if !pbutil.MaybeUnmarshal(&raftReq, e.Data) { // backward compatible
  1919. var r pb.Request
  1920. rp := &r
  1921. pbutil.MustUnmarshal(rp, e.Data)
  1922. s.w.Trigger(r.ID, s.applyV2Request((*RequestV2)(rp)))
  1923. return
  1924. }
  1925. if raftReq.V2 != nil {
  1926. req := (*RequestV2)(raftReq.V2)
  1927. s.w.Trigger(req.ID, s.applyV2Request(req))
  1928. return
  1929. }
  1930. // do not re-apply applied entries.
  1931. if !shouldApplyV3 {
  1932. return
  1933. }
  1934. id := raftReq.ID
  1935. if id == 0 {
  1936. id = raftReq.Header.ID
  1937. }
  1938. var ar *applyResult
  1939. needResult := s.w.IsRegistered(id)
  1940. if needResult || !noSideEffect(&raftReq) {
  1941. if !needResult && raftReq.Txn != nil {
  1942. removeNeedlessRangeReqs(raftReq.Txn)
  1943. }
  1944. ar = s.applyV3.Apply(&raftReq)
  1945. }
  1946. if ar == nil {
  1947. return
  1948. }
  1949. if ar.err != ErrNoSpace || len(s.alarmStore.Get(pb.AlarmType_NOSPACE)) > 0 {
  1950. s.w.Trigger(id, ar)
  1951. return
  1952. }
  1953. if lg := s.getLogger(); lg != nil {
  1954. lg.Warn(
  1955. "message exceeded backend quota; raising alarm",
  1956. zap.Int64("quota-size-bytes", s.Cfg.QuotaBackendBytes),
  1957. zap.String("quota-size", humanize.Bytes(uint64(s.Cfg.QuotaBackendBytes))),
  1958. zap.Error(ar.err),
  1959. )
  1960. } else {
  1961. plog.Errorf("applying raft message exceeded backend quota")
  1962. }
  1963. s.goAttach(func() {
  1964. a := &pb.AlarmRequest{
  1965. MemberID: uint64(s.ID()),
  1966. Action: pb.AlarmRequest_ACTIVATE,
  1967. Alarm: pb.AlarmType_NOSPACE,
  1968. }
  1969. s.raftRequest(s.ctx, pb.InternalRaftRequest{Alarm: a})
  1970. s.w.Trigger(id, ar)
  1971. })
  1972. }
  1973. // applyConfChange applies a ConfChange to the server. It is only
  1974. // invoked with a ConfChange that has already passed through Raft
  1975. func (s *EtcdServer) applyConfChange(cc raftpb.ConfChange, confState *raftpb.ConfState) (bool, error) {
  1976. if err := s.cluster.ValidateConfigurationChange(cc); err != nil {
  1977. cc.NodeID = raft.None
  1978. s.r.ApplyConfChange(cc)
  1979. return false, err
  1980. }
  1981. lg := s.getLogger()
  1982. *confState = *s.r.ApplyConfChange(cc)
  1983. switch cc.Type {
  1984. case raftpb.ConfChangeAddNode, raftpb.ConfChangeAddLearnerNode:
  1985. confChangeContext := new(membership.ConfigChangeContext)
  1986. if err := json.Unmarshal(cc.Context, confChangeContext); err != nil {
  1987. if lg != nil {
  1988. lg.Panic("failed to unmarshal member", zap.Error(err))
  1989. } else {
  1990. plog.Panicf("unmarshal member should never fail: %v", err)
  1991. }
  1992. }
  1993. if cc.NodeID != uint64(confChangeContext.Member.ID) {
  1994. if lg != nil {
  1995. lg.Panic(
  1996. "got different member ID",
  1997. zap.String("member-id-from-config-change-entry", types.ID(cc.NodeID).String()),
  1998. zap.String("member-id-from-message", confChangeContext.Member.ID.String()),
  1999. )
  2000. } else {
  2001. plog.Panicf("nodeID should always be equal to member ID")
  2002. }
  2003. }
  2004. if confChangeContext.IsPromote {
  2005. s.cluster.PromoteMember(confChangeContext.Member.ID)
  2006. } else {
  2007. s.cluster.AddMember(&confChangeContext.Member)
  2008. if confChangeContext.Member.ID != s.id {
  2009. s.r.transport.AddPeer(confChangeContext.Member.ID, confChangeContext.PeerURLs)
  2010. }
  2011. }
  2012. // update the isLearner metric when this server id is equal to the id in raft member confChange
  2013. if confChangeContext.Member.ID == s.id {
  2014. if cc.Type == raftpb.ConfChangeAddLearnerNode {
  2015. isLearner.Set(1)
  2016. } else {
  2017. isLearner.Set(0)
  2018. }
  2019. }
  2020. case raftpb.ConfChangeRemoveNode:
  2021. id := types.ID(cc.NodeID)
  2022. s.cluster.RemoveMember(id)
  2023. if id == s.id {
  2024. return true, nil
  2025. }
  2026. s.r.transport.RemovePeer(id)
  2027. case raftpb.ConfChangeUpdateNode:
  2028. m := new(membership.Member)
  2029. if err := json.Unmarshal(cc.Context, m); err != nil {
  2030. if lg != nil {
  2031. lg.Panic("failed to unmarshal member", zap.Error(err))
  2032. } else {
  2033. plog.Panicf("unmarshal member should never fail: %v", err)
  2034. }
  2035. }
  2036. if cc.NodeID != uint64(m.ID) {
  2037. if lg != nil {
  2038. lg.Panic(
  2039. "got different member ID",
  2040. zap.String("member-id-from-config-change-entry", types.ID(cc.NodeID).String()),
  2041. zap.String("member-id-from-message", m.ID.String()),
  2042. )
  2043. } else {
  2044. plog.Panicf("nodeID should always be equal to member ID")
  2045. }
  2046. }
  2047. s.cluster.UpdateRaftAttributes(m.ID, m.RaftAttributes)
  2048. if m.ID != s.id {
  2049. s.r.transport.UpdatePeer(m.ID, m.PeerURLs)
  2050. }
  2051. }
  2052. return false, nil
  2053. }
  2054. // TODO: non-blocking snapshot
  2055. func (s *EtcdServer) snapshot(snapi uint64, confState raftpb.ConfState) {
  2056. clone := s.v2store.Clone()
  2057. // commit kv to write metadata (for example: consistent index) to disk.
  2058. // KV().commit() updates the consistent index in backend.
  2059. // All operations that update consistent index must be called sequentially
  2060. // from applyAll function.
  2061. // So KV().Commit() cannot run in parallel with apply. It has to be called outside
  2062. // the go routine created below.
  2063. s.KV().Commit()
  2064. s.goAttach(func() {
  2065. lg := s.getLogger()
  2066. d, err := clone.SaveNoCopy()
  2067. // TODO: current store will never fail to do a snapshot
  2068. // what should we do if the store might fail?
  2069. if err != nil {
  2070. if lg != nil {
  2071. lg.Panic("failed to save v2 store", zap.Error(err))
  2072. } else {
  2073. plog.Panicf("store save should never fail: %v", err)
  2074. }
  2075. }
  2076. snap, err := s.r.raftStorage.CreateSnapshot(snapi, &confState, d)
  2077. if err != nil {
  2078. // the snapshot was done asynchronously with the progress of raft.
  2079. // raft might have already got a newer snapshot.
  2080. if err == raft.ErrSnapOutOfDate {
  2081. return
  2082. }
  2083. if lg != nil {
  2084. lg.Panic("failed to create snapshot", zap.Error(err))
  2085. } else {
  2086. plog.Panicf("unexpected create snapshot error %v", err)
  2087. }
  2088. }
  2089. // SaveSnap saves the snapshot and releases the locked wal files
  2090. // to the snapshot index.
  2091. if err = s.r.storage.SaveSnap(snap); err != nil {
  2092. if lg != nil {
  2093. lg.Panic("failed to save snapshot", zap.Error(err))
  2094. } else {
  2095. plog.Fatalf("save snapshot error: %v", err)
  2096. }
  2097. }
  2098. if lg != nil {
  2099. lg.Info(
  2100. "saved snapshot",
  2101. zap.Uint64("snapshot-index", snap.Metadata.Index),
  2102. )
  2103. } else {
  2104. plog.Infof("saved snapshot at index %d", snap.Metadata.Index)
  2105. }
  2106. // When sending a snapshot, etcd will pause compaction.
  2107. // After receives a snapshot, the slow follower needs to get all the entries right after
  2108. // the snapshot sent to catch up. If we do not pause compaction, the log entries right after
  2109. // the snapshot sent might already be compacted. It happens when the snapshot takes long time
  2110. // to send and save. Pausing compaction avoids triggering a snapshot sending cycle.
  2111. if atomic.LoadInt64(&s.inflightSnapshots) != 0 {
  2112. if lg != nil {
  2113. lg.Info("skip compaction since there is an inflight snapshot")
  2114. } else {
  2115. plog.Infof("skip compaction since there is an inflight snapshot")
  2116. }
  2117. return
  2118. }
  2119. // keep some in memory log entries for slow followers.
  2120. compacti := uint64(1)
  2121. if snapi > s.Cfg.SnapshotCatchUpEntries {
  2122. compacti = snapi - s.Cfg.SnapshotCatchUpEntries
  2123. }
  2124. err = s.r.raftStorage.Compact(compacti)
  2125. if err != nil {
  2126. // the compaction was done asynchronously with the progress of raft.
  2127. // raft log might already been compact.
  2128. if err == raft.ErrCompacted {
  2129. return
  2130. }
  2131. if lg != nil {
  2132. lg.Panic("failed to compact", zap.Error(err))
  2133. } else {
  2134. plog.Panicf("unexpected compaction error %v", err)
  2135. }
  2136. }
  2137. if lg != nil {
  2138. lg.Info(
  2139. "compacted Raft logs",
  2140. zap.Uint64("compact-index", compacti),
  2141. )
  2142. } else {
  2143. plog.Infof("compacted raft log at %d", compacti)
  2144. }
  2145. })
  2146. }
  2147. // CutPeer drops messages to the specified peer.
  2148. func (s *EtcdServer) CutPeer(id types.ID) {
  2149. tr, ok := s.r.transport.(*rafthttp.Transport)
  2150. if ok {
  2151. tr.CutPeer(id)
  2152. }
  2153. }
  2154. // MendPeer recovers the message dropping behavior of the given peer.
  2155. func (s *EtcdServer) MendPeer(id types.ID) {
  2156. tr, ok := s.r.transport.(*rafthttp.Transport)
  2157. if ok {
  2158. tr.MendPeer(id)
  2159. }
  2160. }
  2161. func (s *EtcdServer) PauseSending() { s.r.pauseSending() }
  2162. func (s *EtcdServer) ResumeSending() { s.r.resumeSending() }
  2163. func (s *EtcdServer) ClusterVersion() *semver.Version {
  2164. if s.cluster == nil {
  2165. return nil
  2166. }
  2167. return s.cluster.Version()
  2168. }
  2169. // monitorVersions checks the member's version every monitorVersionInterval.
  2170. // It updates the cluster version if all members agrees on a higher one.
  2171. // It prints out log if there is a member with a higher version than the
  2172. // local version.
  2173. func (s *EtcdServer) monitorVersions() {
  2174. for {
  2175. select {
  2176. case <-s.forceVersionC:
  2177. case <-time.After(monitorVersionInterval):
  2178. case <-s.stopping:
  2179. return
  2180. }
  2181. if s.Leader() != s.ID() {
  2182. continue
  2183. }
  2184. v := decideClusterVersion(s.getLogger(), getVersions(s.getLogger(), s.cluster, s.id, s.peerRt))
  2185. if v != nil {
  2186. // only keep major.minor version for comparison
  2187. v = &semver.Version{
  2188. Major: v.Major,
  2189. Minor: v.Minor,
  2190. }
  2191. }
  2192. // if the current version is nil:
  2193. // 1. use the decided version if possible
  2194. // 2. or use the min cluster version
  2195. if s.cluster.Version() == nil {
  2196. verStr := version.MinClusterVersion
  2197. if v != nil {
  2198. verStr = v.String()
  2199. }
  2200. s.goAttach(func() { s.updateClusterVersion(verStr) })
  2201. continue
  2202. }
  2203. // update cluster version only if the decided version is greater than
  2204. // the current cluster version
  2205. if v != nil && s.cluster.Version().LessThan(*v) {
  2206. s.goAttach(func() { s.updateClusterVersion(v.String()) })
  2207. }
  2208. }
  2209. }
  2210. func (s *EtcdServer) updateClusterVersion(ver string) {
  2211. lg := s.getLogger()
  2212. if s.cluster.Version() == nil {
  2213. if lg != nil {
  2214. lg.Info(
  2215. "setting up initial cluster version",
  2216. zap.String("cluster-version", version.Cluster(ver)),
  2217. )
  2218. } else {
  2219. plog.Infof("setting up the initial cluster version to %s", version.Cluster(ver))
  2220. }
  2221. } else {
  2222. if lg != nil {
  2223. lg.Info(
  2224. "updating cluster version",
  2225. zap.String("from", version.Cluster(s.cluster.Version().String())),
  2226. zap.String("to", version.Cluster(ver)),
  2227. )
  2228. } else {
  2229. plog.Infof("updating the cluster version from %s to %s", version.Cluster(s.cluster.Version().String()), version.Cluster(ver))
  2230. }
  2231. }
  2232. req := pb.Request{
  2233. Method: "PUT",
  2234. Path: membership.StoreClusterVersionKey(),
  2235. Val: ver,
  2236. }
  2237. ctx, cancel := context.WithTimeout(s.ctx, s.Cfg.ReqTimeout())
  2238. _, err := s.Do(ctx, req)
  2239. cancel()
  2240. switch err {
  2241. case nil:
  2242. if lg != nil {
  2243. lg.Info("cluster version is updated", zap.String("cluster-version", version.Cluster(ver)))
  2244. }
  2245. return
  2246. case ErrStopped:
  2247. if lg != nil {
  2248. lg.Warn("aborting cluster version update; server is stopped", zap.Error(err))
  2249. } else {
  2250. plog.Infof("aborting update cluster version because server is stopped")
  2251. }
  2252. return
  2253. default:
  2254. if lg != nil {
  2255. lg.Warn("failed to update cluster version", zap.Error(err))
  2256. } else {
  2257. plog.Errorf("error updating cluster version (%v)", err)
  2258. }
  2259. }
  2260. }
  2261. func (s *EtcdServer) parseProposeCtxErr(err error, start time.Time) error {
  2262. switch err {
  2263. case context.Canceled:
  2264. return ErrCanceled
  2265. case context.DeadlineExceeded:
  2266. s.leadTimeMu.RLock()
  2267. curLeadElected := s.leadElectedTime
  2268. s.leadTimeMu.RUnlock()
  2269. prevLeadLost := curLeadElected.Add(-2 * time.Duration(s.Cfg.ElectionTicks) * time.Duration(s.Cfg.TickMs) * time.Millisecond)
  2270. if start.After(prevLeadLost) && start.Before(curLeadElected) {
  2271. return ErrTimeoutDueToLeaderFail
  2272. }
  2273. lead := types.ID(s.getLead())
  2274. switch lead {
  2275. case types.ID(raft.None):
  2276. // TODO: return error to specify it happens because the cluster does not have leader now
  2277. case s.ID():
  2278. if !isConnectedToQuorumSince(s.r.transport, start, s.ID(), s.cluster.Members()) {
  2279. return ErrTimeoutDueToConnectionLost
  2280. }
  2281. default:
  2282. if !isConnectedSince(s.r.transport, start, lead) {
  2283. return ErrTimeoutDueToConnectionLost
  2284. }
  2285. }
  2286. return ErrTimeout
  2287. default:
  2288. return err
  2289. }
  2290. }
  2291. func (s *EtcdServer) KV() mvcc.ConsistentWatchableKV { return s.kv }
  2292. func (s *EtcdServer) Backend() backend.Backend {
  2293. s.bemu.Lock()
  2294. defer s.bemu.Unlock()
  2295. return s.be
  2296. }
  2297. func (s *EtcdServer) AuthStore() auth.AuthStore { return s.authStore }
  2298. func (s *EtcdServer) restoreAlarms() error {
  2299. s.applyV3 = s.newApplierV3()
  2300. as, err := v3alarm.NewAlarmStore(s)
  2301. if err != nil {
  2302. return err
  2303. }
  2304. s.alarmStore = as
  2305. if len(as.Get(pb.AlarmType_NOSPACE)) > 0 {
  2306. s.applyV3 = newApplierV3Capped(s.applyV3)
  2307. }
  2308. if len(as.Get(pb.AlarmType_CORRUPT)) > 0 {
  2309. s.applyV3 = newApplierV3Corrupt(s.applyV3)
  2310. }
  2311. return nil
  2312. }
  2313. // goAttach creates a goroutine on a given function and tracks it using
  2314. // the etcdserver waitgroup.
  2315. func (s *EtcdServer) goAttach(f func()) {
  2316. s.wgMu.RLock() // this blocks with ongoing close(s.stopping)
  2317. defer s.wgMu.RUnlock()
  2318. select {
  2319. case <-s.stopping:
  2320. if lg := s.getLogger(); lg != nil {
  2321. lg.Warn("server has stopped; skipping goAttach")
  2322. } else {
  2323. plog.Warning("server has stopped (skipping goAttach)")
  2324. }
  2325. return
  2326. default:
  2327. }
  2328. // now safe to add since waitgroup wait has not started yet
  2329. s.wg.Add(1)
  2330. go func() {
  2331. defer s.wg.Done()
  2332. f()
  2333. }()
  2334. }
  2335. func (s *EtcdServer) Alarms() []*pb.AlarmMember {
  2336. return s.alarmStore.Get(pb.AlarmType_NONE)
  2337. }
  2338. func (s *EtcdServer) Logger() *zap.Logger {
  2339. return s.lg
  2340. }
  2341. // IsLearner returns if the local member is raft learner
  2342. func (s *EtcdServer) IsLearner() bool {
  2343. return s.cluster.IsLocalMemberLearner()
  2344. }
  2345. // IsMemberExist returns if the member with the given id exists in cluster.
  2346. func (s *EtcdServer) IsMemberExist(id types.ID) bool {
  2347. return s.cluster.IsMemberExist(id)
  2348. }
  2349. // raftStatus returns the raft status of this etcd node.
  2350. func (s *EtcdServer) raftStatus() raft.Status {
  2351. return s.r.Node.Status()
  2352. }