server.go 48 KB

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