server.go 39 KB

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