server.go 44 KB

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