server.go 68 KB

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