server.go 40 KB

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