server.go 40 KB

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