server.go 38 KB

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