server.go 37 KB

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