server.go 51 KB

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