server.go 51 KB

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