server.go 39 KB

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