server.go 39 KB

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