server.go 43 KB

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