server.go 51 KB

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