server.go 49 KB

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