server.go 44 KB

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