server.go 50 KB

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