server.go 51 KB

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