server.go 65 KB

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