server.go 47 KB

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