server.go 50 KB

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