server.go 45 KB

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