server.go 50 KB

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