server.go 50 KB

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