server.go 48 KB

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