server.go 39 KB

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