server.go 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344
  1. // Copyright 2015 CoreOS, Inc.
  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. "errors"
  18. "expvar"
  19. "fmt"
  20. "math/rand"
  21. "net/http"
  22. "os"
  23. "path"
  24. "regexp"
  25. "sync"
  26. "sync/atomic"
  27. "time"
  28. "github.com/coreos/etcd/Godeps/_workspace/src/github.com/coreos/go-semver/semver"
  29. "github.com/coreos/etcd/Godeps/_workspace/src/github.com/coreos/pkg/capnslog"
  30. "github.com/coreos/etcd/Godeps/_workspace/src/golang.org/x/net/context"
  31. "github.com/coreos/etcd/auth"
  32. "github.com/coreos/etcd/compactor"
  33. "github.com/coreos/etcd/discovery"
  34. "github.com/coreos/etcd/etcdserver/etcdhttp/httptypes"
  35. pb "github.com/coreos/etcd/etcdserver/etcdserverpb"
  36. "github.com/coreos/etcd/etcdserver/stats"
  37. "github.com/coreos/etcd/lease"
  38. "github.com/coreos/etcd/pkg/fileutil"
  39. "github.com/coreos/etcd/pkg/idutil"
  40. "github.com/coreos/etcd/pkg/pbutil"
  41. "github.com/coreos/etcd/pkg/runtime"
  42. "github.com/coreos/etcd/pkg/schedule"
  43. "github.com/coreos/etcd/pkg/types"
  44. "github.com/coreos/etcd/pkg/wait"
  45. "github.com/coreos/etcd/raft"
  46. "github.com/coreos/etcd/raft/raftpb"
  47. "github.com/coreos/etcd/rafthttp"
  48. "github.com/coreos/etcd/snap"
  49. dstorage "github.com/coreos/etcd/storage"
  50. "github.com/coreos/etcd/storage/backend"
  51. "github.com/coreos/etcd/store"
  52. "github.com/coreos/etcd/version"
  53. "github.com/coreos/etcd/wal"
  54. )
  55. const (
  56. // owner can make/remove files inside the directory
  57. privateDirMode = 0700
  58. DefaultSnapCount = 10000
  59. StoreClusterPrefix = "/0"
  60. StoreKeysPrefix = "/1"
  61. purgeFileInterval = 30 * time.Second
  62. // monitorVersionInterval should be smaller than the timeout
  63. // on the connection. Or we will not be able to reuse the connection
  64. // (since it will timeout).
  65. monitorVersionInterval = rafthttp.ConnWriteTimeout - time.Second
  66. databaseFilename = "db"
  67. // max number of in-flight snapshot messages etcdserver allows to have
  68. // This number is more than enough for most clusters with 5 machines.
  69. maxInFlightMsgSnap = 16
  70. releaseDelayAfterSnapshot = 30 * time.Second
  71. )
  72. var (
  73. plog = capnslog.NewPackageLogger("github.com/coreos/etcd", "etcdserver")
  74. storeMemberAttributeRegexp = regexp.MustCompile(path.Join(storeMembersPrefix, "[[:xdigit:]]{1,16}", attributesSuffix))
  75. )
  76. func init() {
  77. rand.Seed(time.Now().UnixNano())
  78. expvar.Publish(
  79. "file_descriptor_limit",
  80. expvar.Func(
  81. func() interface{} {
  82. n, _ := runtime.FDLimit()
  83. return n
  84. },
  85. ),
  86. )
  87. }
  88. type Response struct {
  89. Event *store.Event
  90. Watcher store.Watcher
  91. err error
  92. }
  93. type Server interface {
  94. // Start performs any initialization of the Server necessary for it to
  95. // begin serving requests. It must be called before Do or Process.
  96. // Start must be non-blocking; any long-running server functionality
  97. // should be implemented in goroutines.
  98. Start()
  99. // Stop terminates the Server and performs any necessary finalization.
  100. // Do and Process cannot be called after Stop has been invoked.
  101. Stop()
  102. // ID returns the ID of the Server.
  103. ID() types.ID
  104. // Leader returns the ID of the leader Server.
  105. Leader() types.ID
  106. // Do takes a request and attempts to fulfill it, returning a Response.
  107. Do(ctx context.Context, r pb.Request) (Response, error)
  108. // Process takes a raft message and applies it to the server's raft state
  109. // machine, respecting any timeout of the given context.
  110. Process(ctx context.Context, m raftpb.Message) error
  111. // AddMember attempts to add a member into the cluster. It will return
  112. // ErrIDRemoved if member ID is removed from the cluster, or return
  113. // ErrIDExists if member ID exists in the cluster.
  114. AddMember(ctx context.Context, memb Member) error
  115. // RemoveMember attempts to remove a member from the cluster. It will
  116. // return ErrIDRemoved if member ID is removed from the cluster, or return
  117. // ErrIDNotFound if member ID is not in the cluster.
  118. RemoveMember(ctx context.Context, id uint64) error
  119. // UpdateMember attempts to update an existing member in the cluster. It will
  120. // return ErrIDNotFound if the member ID does not exist.
  121. UpdateMember(ctx context.Context, updateMemb Member) error
  122. // ClusterVersion is the cluster-wide minimum major.minor version.
  123. // Cluster version is set to the min version that an etcd member is
  124. // compatible with when first bootstrap.
  125. //
  126. // ClusterVersion is nil until the cluster is bootstrapped (has a quorum).
  127. //
  128. // During a rolling upgrades, the ClusterVersion will be updated
  129. // automatically after a sync. (5 second by default)
  130. //
  131. // The API/raft component can utilize ClusterVersion to determine if
  132. // it can accept a client request or a raft RPC.
  133. // NOTE: ClusterVersion might be nil when etcd 2.1 works with etcd 2.0 and
  134. // the leader is etcd 2.0. etcd 2.0 leader will not update clusterVersion since
  135. // this feature is introduced post 2.0.
  136. ClusterVersion() *semver.Version
  137. }
  138. // EtcdServer is the production implementation of the Server interface
  139. type EtcdServer struct {
  140. // r must be the first element to keep 64-bit alignment for atomic
  141. // access to fields
  142. r raftNode
  143. cfg *ServerConfig
  144. snapCount uint64
  145. w wait.Wait
  146. stop chan struct{}
  147. done chan struct{}
  148. errorc chan error
  149. id types.ID
  150. attributes Attributes
  151. cluster *cluster
  152. store store.Store
  153. kv dstorage.ConsistentWatchableKV
  154. lessor lease.Lessor
  155. bemu sync.Mutex
  156. be backend.Backend
  157. authStore auth.AuthStore
  158. stats *stats.ServerStats
  159. lstats *stats.LeaderStats
  160. SyncTicker <-chan time.Time
  161. // compactor is used to auto-compact the KV.
  162. compactor *compactor.Periodic
  163. // consistent index used to hold the offset of current executing entry
  164. // It is initialized to 0 before executing any entry.
  165. consistIndex consistentIndex
  166. // peerRt used to send requests (version, lease) to peers.
  167. peerRt http.RoundTripper
  168. reqIDGen *idutil.Generator
  169. // forceVersionC is used to force the version monitor loop
  170. // to detect the cluster version immediately.
  171. forceVersionC chan struct{}
  172. msgSnapC chan raftpb.Message
  173. // count the number of inflight snapshots.
  174. // MUST use atomic operation to access this field.
  175. inflightSnapshots int64
  176. // wg is used to wait for the go routines that depends on the server state
  177. // to exit when stopping the server.
  178. wg sync.WaitGroup
  179. }
  180. // NewServer creates a new EtcdServer from the supplied configuration. The
  181. // configuration is considered static for the lifetime of the EtcdServer.
  182. func NewServer(cfg *ServerConfig) (*EtcdServer, error) {
  183. st := store.New(StoreClusterPrefix, StoreKeysPrefix)
  184. var (
  185. w *wal.WAL
  186. n raft.Node
  187. s *raft.MemoryStorage
  188. id types.ID
  189. cl *cluster
  190. )
  191. if terr := fileutil.TouchDirAll(cfg.DataDir); terr != nil {
  192. return nil, fmt.Errorf("cannot access data directory: %v", terr)
  193. }
  194. if !cfg.V3demo && fileutil.Exist(path.Join(cfg.SnapDir(), databaseFilename)) {
  195. return nil, errors.New("experimental-v3demo cannot be disabled once it is enabled")
  196. }
  197. // Run the migrations.
  198. dataVer, err := version.DetectDataDir(cfg.DataDir)
  199. if err != nil {
  200. return nil, err
  201. }
  202. if err := upgradeDataDir(cfg.DataDir, cfg.Name, dataVer); err != nil {
  203. return nil, err
  204. }
  205. haveWAL := wal.Exist(cfg.WALDir())
  206. ss := snap.New(cfg.SnapDir())
  207. prt, err := rafthttp.NewRoundTripper(cfg.PeerTLSInfo, cfg.peerDialTimeout())
  208. if err != nil {
  209. return nil, err
  210. }
  211. var remotes []*Member
  212. switch {
  213. case !haveWAL && !cfg.NewCluster:
  214. if err := cfg.VerifyJoinExisting(); err != nil {
  215. return nil, err
  216. }
  217. cl, err = newClusterFromURLsMap(cfg.InitialClusterToken, cfg.InitialPeerURLsMap)
  218. if err != nil {
  219. return nil, err
  220. }
  221. existingCluster, err := GetClusterFromRemotePeers(getRemotePeerURLs(cl, cfg.Name), prt)
  222. if err != nil {
  223. return nil, fmt.Errorf("cannot fetch cluster info from peer urls: %v", err)
  224. }
  225. if err := ValidateClusterAndAssignIDs(cl, existingCluster); err != nil {
  226. return nil, fmt.Errorf("error validating peerURLs %s: %v", existingCluster, err)
  227. }
  228. if !isCompatibleWithCluster(cl, cl.MemberByName(cfg.Name).ID, prt) {
  229. return nil, fmt.Errorf("incomptible with current running cluster")
  230. }
  231. remotes = existingCluster.Members()
  232. cl.SetID(existingCluster.id)
  233. cl.SetStore(st)
  234. cfg.Print()
  235. id, n, s, w = startNode(cfg, cl, nil)
  236. case !haveWAL && cfg.NewCluster:
  237. if err := cfg.VerifyBootstrap(); err != nil {
  238. return nil, err
  239. }
  240. cl, err = newClusterFromURLsMap(cfg.InitialClusterToken, cfg.InitialPeerURLsMap)
  241. if err != nil {
  242. return nil, err
  243. }
  244. m := cl.MemberByName(cfg.Name)
  245. if isMemberBootstrapped(cl, cfg.Name, prt, cfg.bootstrapTimeout()) {
  246. return nil, fmt.Errorf("member %s has already been bootstrapped", m.ID)
  247. }
  248. if cfg.ShouldDiscover() {
  249. var str string
  250. var err error
  251. str, err = discovery.JoinCluster(cfg.DiscoveryURL, cfg.DiscoveryProxy, m.ID, cfg.InitialPeerURLsMap.String())
  252. if err != nil {
  253. return nil, &DiscoveryError{Op: "join", Err: err}
  254. }
  255. urlsmap, err := types.NewURLsMap(str)
  256. if err != nil {
  257. return nil, err
  258. }
  259. if checkDuplicateURL(urlsmap) {
  260. return nil, fmt.Errorf("discovery cluster %s has duplicate url", urlsmap)
  261. }
  262. if cl, err = newClusterFromURLsMap(cfg.InitialClusterToken, urlsmap); err != nil {
  263. return nil, err
  264. }
  265. }
  266. cl.SetStore(st)
  267. cfg.PrintWithInitial()
  268. id, n, s, w = startNode(cfg, cl, cl.MemberIDs())
  269. case haveWAL:
  270. if err := fileutil.IsDirWriteable(cfg.MemberDir()); err != nil {
  271. return nil, fmt.Errorf("cannot write to member directory: %v", err)
  272. }
  273. if err := fileutil.IsDirWriteable(cfg.WALDir()); err != nil {
  274. return nil, fmt.Errorf("cannot write to WAL directory: %v", err)
  275. }
  276. if cfg.ShouldDiscover() {
  277. plog.Warningf("discovery token ignored since a cluster has already been initialized. Valid log found at %q", cfg.WALDir())
  278. }
  279. var snapshot *raftpb.Snapshot
  280. var err error
  281. snapshot, err = ss.Load()
  282. if err != nil && err != snap.ErrNoSnapshot {
  283. return nil, err
  284. }
  285. if snapshot != nil {
  286. if err := st.Recovery(snapshot.Data); err != nil {
  287. plog.Panicf("recovered store from snapshot error: %v", err)
  288. }
  289. plog.Infof("recovered store from snapshot at index %d", snapshot.Metadata.Index)
  290. }
  291. cfg.Print()
  292. if !cfg.ForceNewCluster {
  293. id, cl, n, s, w = restartNode(cfg, snapshot)
  294. } else {
  295. id, cl, n, s, w = restartAsStandaloneNode(cfg, snapshot)
  296. }
  297. cl.SetStore(st)
  298. cl.Recover()
  299. default:
  300. return nil, fmt.Errorf("unsupported bootstrap config")
  301. }
  302. if terr := fileutil.TouchDirAll(cfg.MemberDir()); terr != nil {
  303. return nil, fmt.Errorf("cannot access member directory: %v", terr)
  304. }
  305. sstats := &stats.ServerStats{
  306. Name: cfg.Name,
  307. ID: id.String(),
  308. }
  309. sstats.Initialize()
  310. lstats := stats.NewLeaderStats(id.String())
  311. srv := &EtcdServer{
  312. cfg: cfg,
  313. snapCount: cfg.SnapCount,
  314. errorc: make(chan error, 1),
  315. store: st,
  316. r: raftNode{
  317. Node: n,
  318. ticker: time.Tick(time.Duration(cfg.TickMs) * time.Millisecond),
  319. raftStorage: s,
  320. storage: NewStorage(w, ss),
  321. },
  322. id: id,
  323. attributes: Attributes{Name: cfg.Name, ClientURLs: cfg.ClientURLs.StringSlice()},
  324. cluster: cl,
  325. stats: sstats,
  326. lstats: lstats,
  327. SyncTicker: time.Tick(500 * time.Millisecond),
  328. peerRt: prt,
  329. reqIDGen: idutil.NewGenerator(uint16(id), time.Now()),
  330. forceVersionC: make(chan struct{}),
  331. msgSnapC: make(chan raftpb.Message, maxInFlightMsgSnap),
  332. }
  333. if cfg.V3demo {
  334. srv.be = backend.NewDefaultBackend(path.Join(cfg.SnapDir(), databaseFilename))
  335. srv.lessor = lease.NewLessor(srv.be)
  336. srv.kv = dstorage.New(srv.be, srv.lessor, &srv.consistIndex)
  337. srv.authStore = auth.NewAuthStore(srv)
  338. if h := cfg.AutoCompactionRetention; h != 0 {
  339. srv.compactor = compactor.NewPeriodic(h, srv.kv, srv)
  340. srv.compactor.Run()
  341. }
  342. }
  343. // TODO: move transport initialization near the definition of remote
  344. tr := &rafthttp.Transport{
  345. TLSInfo: cfg.PeerTLSInfo,
  346. DialTimeout: cfg.peerDialTimeout(),
  347. ID: id,
  348. URLs: cfg.PeerURLs,
  349. ClusterID: cl.ID(),
  350. Raft: srv,
  351. Snapshotter: ss,
  352. ServerStats: sstats,
  353. LeaderStats: lstats,
  354. ErrorC: srv.errorc,
  355. V3demo: cfg.V3demo,
  356. }
  357. if err := tr.Start(); err != nil {
  358. return nil, err
  359. }
  360. // add all remotes into transport
  361. for _, m := range remotes {
  362. if m.ID != id {
  363. tr.AddRemote(m.ID, m.PeerURLs)
  364. }
  365. }
  366. for _, m := range cl.Members() {
  367. if m.ID != id {
  368. tr.AddPeer(m.ID, m.PeerURLs)
  369. }
  370. }
  371. srv.r.transport = tr
  372. return srv, nil
  373. }
  374. // Start prepares and starts server in a new goroutine. It is no longer safe to
  375. // modify a server's fields after it has been sent to Start.
  376. // It also starts a goroutine to publish its server information.
  377. func (s *EtcdServer) Start() {
  378. s.start()
  379. go s.publish(s.cfg.ReqTimeout())
  380. go s.purgeFile()
  381. go monitorFileDescriptor(s.done)
  382. go s.monitorVersions()
  383. }
  384. // start prepares and starts server in a new goroutine. It is no longer safe to
  385. // modify a server's fields after it has been sent to Start.
  386. // This function is just used for testing.
  387. func (s *EtcdServer) start() {
  388. if s.snapCount == 0 {
  389. plog.Infof("set snapshot count to default %d", DefaultSnapCount)
  390. s.snapCount = DefaultSnapCount
  391. }
  392. s.w = wait.New()
  393. s.done = make(chan struct{})
  394. s.stop = make(chan struct{})
  395. if s.ClusterVersion() != nil {
  396. plog.Infof("starting server... [version: %v, cluster version: %v]", version.Version, version.Cluster(s.ClusterVersion().String()))
  397. } else {
  398. plog.Infof("starting server... [version: %v, cluster version: to_be_decided]", version.Version)
  399. }
  400. // TODO: if this is an empty log, writes all peer infos
  401. // into the first entry
  402. go s.run()
  403. }
  404. func (s *EtcdServer) purgeFile() {
  405. var serrc, werrc <-chan error
  406. if s.cfg.MaxSnapFiles > 0 {
  407. serrc = fileutil.PurgeFile(s.cfg.SnapDir(), "snap", s.cfg.MaxSnapFiles, purgeFileInterval, s.done)
  408. }
  409. if s.cfg.MaxWALFiles > 0 {
  410. werrc = fileutil.PurgeFile(s.cfg.WALDir(), "wal", s.cfg.MaxWALFiles, purgeFileInterval, s.done)
  411. }
  412. select {
  413. case e := <-werrc:
  414. plog.Fatalf("failed to purge wal file %v", e)
  415. case e := <-serrc:
  416. plog.Fatalf("failed to purge snap file %v", e)
  417. case <-s.done:
  418. return
  419. }
  420. }
  421. func (s *EtcdServer) ID() types.ID { return s.id }
  422. func (s *EtcdServer) Cluster() Cluster { return s.cluster }
  423. func (s *EtcdServer) RaftHandler() http.Handler { return s.r.transport.Handler() }
  424. func (s *EtcdServer) Lessor() lease.Lessor { return s.lessor }
  425. func (s *EtcdServer) Process(ctx context.Context, m raftpb.Message) error {
  426. if s.cluster.IsIDRemoved(types.ID(m.From)) {
  427. plog.Warningf("reject message from removed member %s", types.ID(m.From).String())
  428. return httptypes.NewHTTPError(http.StatusForbidden, "cannot process message from removed member")
  429. }
  430. if m.Type == raftpb.MsgApp {
  431. s.stats.RecvAppendReq(types.ID(m.From).String(), m.Size())
  432. }
  433. return s.r.Step(ctx, m)
  434. }
  435. func (s *EtcdServer) IsIDRemoved(id uint64) bool { return s.cluster.IsIDRemoved(types.ID(id)) }
  436. func (s *EtcdServer) ReportUnreachable(id uint64) { s.r.ReportUnreachable(id) }
  437. // ReportSnapshot reports snapshot sent status to the raft state machine,
  438. // and clears the used snapshot from the snapshot store.
  439. func (s *EtcdServer) ReportSnapshot(id uint64, status raft.SnapshotStatus) {
  440. s.r.ReportSnapshot(id, status)
  441. }
  442. type etcdProgress struct {
  443. confState raftpb.ConfState
  444. snapi uint64
  445. appliedi uint64
  446. }
  447. func (s *EtcdServer) run() {
  448. snap, err := s.r.raftStorage.Snapshot()
  449. if err != nil {
  450. plog.Panicf("get snapshot from raft storage error: %v", err)
  451. }
  452. s.r.start(s)
  453. // asynchronously accept apply packets, dispatch progress in-order
  454. sched := schedule.NewFIFOScheduler()
  455. ep := etcdProgress{
  456. confState: snap.Metadata.ConfState,
  457. snapi: snap.Metadata.Index,
  458. appliedi: snap.Metadata.Index,
  459. }
  460. defer func() {
  461. sched.Stop()
  462. // wait for snapshots before closing raft so wal stays open
  463. s.wg.Wait()
  464. // must stop raft after scheduler-- etcdserver can leak rafthttp pipelines
  465. // by adding a peer after raft stops the transport
  466. s.r.stop()
  467. // kv, lessor and backend can be nil if running without v3 enabled
  468. // or running unit tests.
  469. if s.lessor != nil {
  470. s.lessor.Stop()
  471. }
  472. if s.kv != nil {
  473. s.kv.Close()
  474. }
  475. if s.be != nil {
  476. s.be.Close()
  477. }
  478. if s.compactor != nil {
  479. s.compactor.Stop()
  480. }
  481. close(s.done)
  482. }()
  483. var expiredLeaseC <-chan []*lease.Lease
  484. if s.lessor != nil {
  485. expiredLeaseC = s.lessor.ExpiredLeasesC()
  486. }
  487. for {
  488. select {
  489. case ap := <-s.r.apply():
  490. f := func(context.Context) { s.applyAll(&ep, &ap) }
  491. sched.Schedule(f)
  492. case leases := <-expiredLeaseC:
  493. go func() {
  494. for _, l := range leases {
  495. s.LeaseRevoke(context.TODO(), &pb.LeaseRevokeRequest{ID: int64(l.ID)})
  496. }
  497. }()
  498. case err := <-s.errorc:
  499. plog.Errorf("%s", err)
  500. plog.Infof("the data-dir used by this member must be removed.")
  501. return
  502. case <-s.stop:
  503. return
  504. }
  505. }
  506. }
  507. func (s *EtcdServer) applyAll(ep *etcdProgress, apply *apply) {
  508. s.applySnapshot(ep, apply)
  509. s.applyEntries(ep, apply)
  510. // wait for the raft routine to finish the disk writes before triggering a
  511. // snapshot. or applied index might be greater than the last index in raft
  512. // storage, since the raft routine might be slower than apply routine.
  513. <-apply.raftDone
  514. s.triggerSnapshot(ep)
  515. select {
  516. // snapshot requested via send()
  517. case m := <-s.msgSnapC:
  518. merged := s.createMergedSnapshotMessage(m, ep.appliedi, ep.confState)
  519. s.sendMergedSnap(merged)
  520. default:
  521. }
  522. }
  523. func (s *EtcdServer) applySnapshot(ep *etcdProgress, apply *apply) {
  524. if raft.IsEmptySnap(apply.snapshot) {
  525. return
  526. }
  527. if apply.snapshot.Metadata.Index <= ep.appliedi {
  528. plog.Panicf("snapshot index [%d] should > appliedi[%d] + 1",
  529. apply.snapshot.Metadata.Index, ep.appliedi)
  530. }
  531. if s.cfg.V3demo {
  532. snapfn, err := s.r.storage.DBFilePath(apply.snapshot.Metadata.Index)
  533. if err != nil {
  534. plog.Panicf("get database snapshot file path error: %v", err)
  535. }
  536. fn := path.Join(s.cfg.SnapDir(), databaseFilename)
  537. if err := os.Rename(snapfn, fn); err != nil {
  538. plog.Panicf("rename snapshot file error: %v", err)
  539. }
  540. newbe := backend.NewDefaultBackend(fn)
  541. if err := s.kv.Restore(newbe); err != nil {
  542. plog.Panicf("restore KV error: %v", err)
  543. }
  544. // Closing old backend might block until all the txns
  545. // on the backend are finished.
  546. // We do not want to wait on closing the old backend.
  547. s.bemu.Lock()
  548. oldbe := s.be
  549. go func() {
  550. if err := oldbe.Close(); err != nil {
  551. plog.Panicf("close backend error: %v", err)
  552. }
  553. }()
  554. s.be = newbe
  555. s.bemu.Unlock()
  556. if s.lessor != nil {
  557. s.lessor.Recover(newbe, s.kv)
  558. }
  559. }
  560. if err := s.store.Recovery(apply.snapshot.Data); err != nil {
  561. plog.Panicf("recovery store error: %v", err)
  562. }
  563. s.cluster.Recover()
  564. // recover raft transport
  565. s.r.transport.RemoveAllPeers()
  566. for _, m := range s.cluster.Members() {
  567. if m.ID == s.ID() {
  568. continue
  569. }
  570. s.r.transport.AddPeer(m.ID, m.PeerURLs)
  571. }
  572. ep.appliedi = apply.snapshot.Metadata.Index
  573. ep.snapi = ep.appliedi
  574. ep.confState = apply.snapshot.Metadata.ConfState
  575. plog.Infof("recovered from incoming snapshot at index %d", ep.snapi)
  576. }
  577. func (s *EtcdServer) applyEntries(ep *etcdProgress, apply *apply) {
  578. if len(apply.entries) == 0 {
  579. return
  580. }
  581. firsti := apply.entries[0].Index
  582. if firsti > ep.appliedi+1 {
  583. plog.Panicf("first index of committed entry[%d] should <= appliedi[%d] + 1", firsti, ep.appliedi)
  584. }
  585. var ents []raftpb.Entry
  586. if ep.appliedi+1-firsti < uint64(len(apply.entries)) {
  587. ents = apply.entries[ep.appliedi+1-firsti:]
  588. }
  589. if len(ents) == 0 {
  590. return
  591. }
  592. var shouldstop bool
  593. if ep.appliedi, shouldstop = s.apply(ents, &ep.confState); shouldstop {
  594. go s.stopWithDelay(10*100*time.Millisecond, fmt.Errorf("the member has been permanently removed from the cluster"))
  595. }
  596. }
  597. func (s *EtcdServer) triggerSnapshot(ep *etcdProgress) {
  598. if ep.appliedi-ep.snapi <= s.snapCount {
  599. return
  600. }
  601. // When sending a snapshot, etcd will pause compaction.
  602. // After receives a snapshot, the slow follower needs to get all the entries right after
  603. // the snapshot sent to catch up. If we do not pause compaction, the log entries right after
  604. // the snapshot sent might already be compacted. It happens when the snapshot takes long time
  605. // to send and save. Pausing compaction avoids triggering a snapshot sending cycle.
  606. if atomic.LoadInt64(&s.inflightSnapshots) != 0 {
  607. return
  608. }
  609. plog.Infof("start to snapshot (applied: %d, lastsnap: %d)", ep.appliedi, ep.snapi)
  610. s.snapshot(ep.appliedi, ep.confState)
  611. ep.snapi = ep.appliedi
  612. }
  613. // Stop stops the server gracefully, and shuts down the running goroutine.
  614. // Stop should be called after a Start(s), otherwise it will block forever.
  615. func (s *EtcdServer) Stop() {
  616. select {
  617. case s.stop <- struct{}{}:
  618. case <-s.done:
  619. return
  620. }
  621. <-s.done
  622. }
  623. func (s *EtcdServer) stopWithDelay(d time.Duration, err error) {
  624. select {
  625. case <-time.After(d):
  626. case <-s.done:
  627. }
  628. select {
  629. case s.errorc <- err:
  630. default:
  631. }
  632. }
  633. // StopNotify returns a channel that receives a empty struct
  634. // when the server is stopped.
  635. func (s *EtcdServer) StopNotify() <-chan struct{} { return s.done }
  636. // Do interprets r and performs an operation on s.store according to r.Method
  637. // and other fields. If r.Method is "POST", "PUT", "DELETE", or a "GET" with
  638. // Quorum == true, r will be sent through consensus before performing its
  639. // respective operation. Do will block until an action is performed or there is
  640. // an error.
  641. func (s *EtcdServer) Do(ctx context.Context, r pb.Request) (Response, error) {
  642. r.ID = s.reqIDGen.Next()
  643. if r.Method == "GET" && r.Quorum {
  644. r.Method = "QGET"
  645. }
  646. switch r.Method {
  647. case "POST", "PUT", "DELETE", "QGET":
  648. data, err := r.Marshal()
  649. if err != nil {
  650. return Response{}, err
  651. }
  652. ch := s.w.Register(r.ID)
  653. // TODO: benchmark the cost of time.Now()
  654. // might be sampling?
  655. start := time.Now()
  656. s.r.Propose(ctx, data)
  657. proposePending.Inc()
  658. defer proposePending.Dec()
  659. select {
  660. case x := <-ch:
  661. proposeDurations.Observe(float64(time.Since(start)) / float64(time.Second))
  662. resp := x.(Response)
  663. return resp, resp.err
  664. case <-ctx.Done():
  665. proposeFailed.Inc()
  666. s.w.Trigger(r.ID, nil) // GC wait
  667. return Response{}, s.parseProposeCtxErr(ctx.Err(), start)
  668. case <-s.done:
  669. return Response{}, ErrStopped
  670. }
  671. case "GET":
  672. switch {
  673. case r.Wait:
  674. wc, err := s.store.Watch(r.Path, r.Recursive, r.Stream, r.Since)
  675. if err != nil {
  676. return Response{}, err
  677. }
  678. return Response{Watcher: wc}, nil
  679. default:
  680. ev, err := s.store.Get(r.Path, r.Recursive, r.Sorted)
  681. if err != nil {
  682. return Response{}, err
  683. }
  684. return Response{Event: ev}, nil
  685. }
  686. case "HEAD":
  687. ev, err := s.store.Get(r.Path, r.Recursive, r.Sorted)
  688. if err != nil {
  689. return Response{}, err
  690. }
  691. return Response{Event: ev}, nil
  692. default:
  693. return Response{}, ErrUnknownMethod
  694. }
  695. }
  696. func (s *EtcdServer) SelfStats() []byte { return s.stats.JSON() }
  697. func (s *EtcdServer) LeaderStats() []byte {
  698. lead := atomic.LoadUint64(&s.r.lead)
  699. if lead != uint64(s.id) {
  700. return nil
  701. }
  702. return s.lstats.JSON()
  703. }
  704. func (s *EtcdServer) StoreStats() []byte { return s.store.JsonStats() }
  705. func (s *EtcdServer) AddMember(ctx context.Context, memb Member) error {
  706. if s.cfg.StrictReconfigCheck && !s.cluster.isReadyToAddNewMember() {
  707. // If s.cfg.StrictReconfigCheck is false, it means the option -strict-reconfig-check isn't passed to etcd.
  708. // In such a case adding a new member is allowed unconditionally
  709. return ErrNotEnoughStartedMembers
  710. }
  711. // TODO: move Member to protobuf type
  712. b, err := json.Marshal(memb)
  713. if err != nil {
  714. return err
  715. }
  716. cc := raftpb.ConfChange{
  717. Type: raftpb.ConfChangeAddNode,
  718. NodeID: uint64(memb.ID),
  719. Context: b,
  720. }
  721. return s.configure(ctx, cc)
  722. }
  723. func (s *EtcdServer) RemoveMember(ctx context.Context, id uint64) error {
  724. if s.cfg.StrictReconfigCheck && !s.cluster.isReadyToRemoveMember(id) {
  725. // If s.cfg.StrictReconfigCheck is false, it means the option -strict-reconfig-check isn't passed to etcd.
  726. // In such a case removing a member is allowed unconditionally
  727. return ErrNotEnoughStartedMembers
  728. }
  729. cc := raftpb.ConfChange{
  730. Type: raftpb.ConfChangeRemoveNode,
  731. NodeID: id,
  732. }
  733. return s.configure(ctx, cc)
  734. }
  735. func (s *EtcdServer) UpdateMember(ctx context.Context, memb Member) error {
  736. b, err := json.Marshal(memb)
  737. if err != nil {
  738. return err
  739. }
  740. cc := raftpb.ConfChange{
  741. Type: raftpb.ConfChangeUpdateNode,
  742. NodeID: uint64(memb.ID),
  743. Context: b,
  744. }
  745. return s.configure(ctx, cc)
  746. }
  747. // Implement the RaftTimer interface
  748. func (s *EtcdServer) Index() uint64 { return atomic.LoadUint64(&s.r.index) }
  749. func (s *EtcdServer) Term() uint64 { return atomic.LoadUint64(&s.r.term) }
  750. // Lead is only for testing purposes.
  751. // TODO: add Raft server interface to expose raft related info:
  752. // Index, Term, Lead, Committed, Applied, LastIndex, etc.
  753. func (s *EtcdServer) Lead() uint64 { return atomic.LoadUint64(&s.r.lead) }
  754. func (s *EtcdServer) Leader() types.ID { return types.ID(s.Lead()) }
  755. func (s *EtcdServer) IsPprofEnabled() bool { return s.cfg.EnablePprof }
  756. // configure sends a configuration change through consensus and
  757. // then waits for it to be applied to the server. It
  758. // will block until the change is performed or there is an error.
  759. func (s *EtcdServer) configure(ctx context.Context, cc raftpb.ConfChange) error {
  760. cc.ID = s.reqIDGen.Next()
  761. ch := s.w.Register(cc.ID)
  762. start := time.Now()
  763. if err := s.r.ProposeConfChange(ctx, cc); err != nil {
  764. s.w.Trigger(cc.ID, nil)
  765. return err
  766. }
  767. select {
  768. case x := <-ch:
  769. if err, ok := x.(error); ok {
  770. return err
  771. }
  772. if x != nil {
  773. plog.Panicf("return type should always be error")
  774. }
  775. return nil
  776. case <-ctx.Done():
  777. s.w.Trigger(cc.ID, nil) // GC wait
  778. return s.parseProposeCtxErr(ctx.Err(), start)
  779. case <-s.done:
  780. return ErrStopped
  781. }
  782. }
  783. // sync proposes a SYNC request and is non-blocking.
  784. // This makes no guarantee that the request will be proposed or performed.
  785. // The request will be canceled after the given timeout.
  786. func (s *EtcdServer) sync(timeout time.Duration) {
  787. ctx, cancel := context.WithTimeout(context.Background(), timeout)
  788. req := pb.Request{
  789. Method: "SYNC",
  790. ID: s.reqIDGen.Next(),
  791. Time: time.Now().UnixNano(),
  792. }
  793. data := pbutil.MustMarshal(&req)
  794. // There is no promise that node has leader when do SYNC request,
  795. // so it uses goroutine to propose.
  796. go func() {
  797. s.r.Propose(ctx, data)
  798. cancel()
  799. }()
  800. }
  801. // publish registers server information into the cluster. The information
  802. // is the JSON representation of this server's member struct, updated with the
  803. // static clientURLs of the server.
  804. // The function keeps attempting to register until it succeeds,
  805. // or its server is stopped.
  806. func (s *EtcdServer) publish(timeout time.Duration) {
  807. b, err := json.Marshal(s.attributes)
  808. if err != nil {
  809. plog.Panicf("json marshal error: %v", err)
  810. return
  811. }
  812. req := pb.Request{
  813. Method: "PUT",
  814. Path: MemberAttributesStorePath(s.id),
  815. Val: string(b),
  816. }
  817. for {
  818. ctx, cancel := context.WithTimeout(context.Background(), timeout)
  819. _, err := s.Do(ctx, req)
  820. cancel()
  821. switch err {
  822. case nil:
  823. plog.Infof("published %+v to cluster %s", s.attributes, s.cluster.ID())
  824. return
  825. case ErrStopped:
  826. plog.Infof("aborting publish because server is stopped")
  827. return
  828. default:
  829. plog.Errorf("publish error: %v", err)
  830. }
  831. }
  832. }
  833. // TODO: move this function into raft.go
  834. func (s *EtcdServer) send(ms []raftpb.Message) {
  835. for i := range ms {
  836. if s.cluster.IsIDRemoved(types.ID(ms[i].To)) {
  837. ms[i].To = 0
  838. }
  839. if s.cfg.V3demo {
  840. if ms[i].Type == raftpb.MsgSnap {
  841. // There are two separate data store when v3 demo is enabled: the store for v2,
  842. // and the KV for v3.
  843. // The msgSnap only contains the most recent snapshot of store without KV.
  844. // So we need to redirect the msgSnap to etcd server main loop for merging in the
  845. // current store snapshot and KV snapshot.
  846. select {
  847. case s.msgSnapC <- ms[i]:
  848. default:
  849. // drop msgSnap if the inflight chan if full.
  850. }
  851. ms[i].To = 0
  852. }
  853. }
  854. if ms[i].Type == raftpb.MsgHeartbeat {
  855. ok, exceed := s.r.td.Observe(ms[i].To)
  856. if !ok {
  857. // TODO: limit request rate.
  858. plog.Warningf("failed to send out heartbeat on time (deadline exceeded for %v)", exceed)
  859. plog.Warningf("server is likely overloaded")
  860. }
  861. }
  862. }
  863. s.r.transport.Send(ms)
  864. }
  865. func (s *EtcdServer) sendMergedSnap(merged snap.Message) {
  866. atomic.AddInt64(&s.inflightSnapshots, 1)
  867. s.r.transport.SendSnapshot(merged)
  868. go func() {
  869. select {
  870. case ok := <-merged.CloseNotify():
  871. // delay releasing inflight snapshot for another 30 seconds to
  872. // block log compaction.
  873. // If the follower still fails to catch up, it is probably just too slow
  874. // to catch up. We cannot avoid the snapshot cycle anyway.
  875. if ok {
  876. select {
  877. case <-time.After(releaseDelayAfterSnapshot):
  878. case <-s.done:
  879. }
  880. }
  881. atomic.AddInt64(&s.inflightSnapshots, -1)
  882. case <-s.done:
  883. return
  884. }
  885. }()
  886. }
  887. // apply takes entries received from Raft (after it has been committed) and
  888. // applies them to the current state of the EtcdServer.
  889. // The given entries should not be empty.
  890. func (s *EtcdServer) apply(es []raftpb.Entry, confState *raftpb.ConfState) (uint64, bool) {
  891. var applied uint64
  892. var shouldstop bool
  893. for i := range es {
  894. e := es[i]
  895. // set the consistent index of current executing entry
  896. s.consistIndex.setConsistentIndex(e.Index)
  897. switch e.Type {
  898. case raftpb.EntryNormal:
  899. // raft state machine may generate noop entry when leader confirmation.
  900. // skip it in advance to avoid some potential bug in the future
  901. if len(e.Data) == 0 {
  902. select {
  903. case s.forceVersionC <- struct{}{}:
  904. default:
  905. }
  906. break
  907. }
  908. var raftReq pb.InternalRaftRequest
  909. if !pbutil.MaybeUnmarshal(&raftReq, e.Data) { // backward compatible
  910. var r pb.Request
  911. pbutil.MustUnmarshal(&r, e.Data)
  912. s.w.Trigger(r.ID, s.applyRequest(r))
  913. } else {
  914. switch {
  915. case raftReq.V2 != nil:
  916. req := raftReq.V2
  917. s.w.Trigger(req.ID, s.applyRequest(*req))
  918. default:
  919. s.w.Trigger(raftReq.ID, s.applyV3Request(&raftReq))
  920. }
  921. }
  922. case raftpb.EntryConfChange:
  923. var cc raftpb.ConfChange
  924. pbutil.MustUnmarshal(&cc, e.Data)
  925. removedSelf, err := s.applyConfChange(cc, confState)
  926. shouldstop = shouldstop || removedSelf
  927. s.w.Trigger(cc.ID, err)
  928. default:
  929. plog.Panicf("entry type should be either EntryNormal or EntryConfChange")
  930. }
  931. atomic.StoreUint64(&s.r.index, e.Index)
  932. atomic.StoreUint64(&s.r.term, e.Term)
  933. applied = e.Index
  934. }
  935. return applied, shouldstop
  936. }
  937. // applyRequest interprets r as a call to store.X and returns a Response interpreted
  938. // from store.Event
  939. func (s *EtcdServer) applyRequest(r pb.Request) Response {
  940. f := func(ev *store.Event, err error) Response {
  941. return Response{Event: ev, err: err}
  942. }
  943. refresh, _ := pbutil.GetBool(r.Refresh)
  944. ttlOptions := store.TTLOptionSet{Refresh: refresh}
  945. if r.Expiration != 0 {
  946. ttlOptions.ExpireTime = time.Unix(0, r.Expiration)
  947. }
  948. switch r.Method {
  949. case "POST":
  950. return f(s.store.Create(r.Path, r.Dir, r.Val, true, ttlOptions))
  951. case "PUT":
  952. exists, existsSet := pbutil.GetBool(r.PrevExist)
  953. switch {
  954. case existsSet:
  955. if exists {
  956. if r.PrevIndex == 0 && r.PrevValue == "" {
  957. return f(s.store.Update(r.Path, r.Val, ttlOptions))
  958. } else {
  959. return f(s.store.CompareAndSwap(r.Path, r.PrevValue, r.PrevIndex, r.Val, ttlOptions))
  960. }
  961. }
  962. return f(s.store.Create(r.Path, r.Dir, r.Val, false, ttlOptions))
  963. case r.PrevIndex > 0 || r.PrevValue != "":
  964. return f(s.store.CompareAndSwap(r.Path, r.PrevValue, r.PrevIndex, r.Val, ttlOptions))
  965. default:
  966. // TODO (yicheng): cluster should be the owner of cluster prefix store
  967. // we should not modify cluster store here.
  968. if storeMemberAttributeRegexp.MatchString(r.Path) {
  969. id := mustParseMemberIDFromKey(path.Dir(r.Path))
  970. var attr Attributes
  971. if err := json.Unmarshal([]byte(r.Val), &attr); err != nil {
  972. plog.Panicf("unmarshal %s should never fail: %v", r.Val, err)
  973. }
  974. ok := s.cluster.UpdateAttributes(id, attr)
  975. if !ok {
  976. return Response{}
  977. }
  978. }
  979. if r.Path == path.Join(StoreClusterPrefix, "version") {
  980. s.cluster.SetVersion(semver.Must(semver.NewVersion(r.Val)))
  981. }
  982. return f(s.store.Set(r.Path, r.Dir, r.Val, ttlOptions))
  983. }
  984. case "DELETE":
  985. switch {
  986. case r.PrevIndex > 0 || r.PrevValue != "":
  987. return f(s.store.CompareAndDelete(r.Path, r.PrevValue, r.PrevIndex))
  988. default:
  989. return f(s.store.Delete(r.Path, r.Dir, r.Recursive))
  990. }
  991. case "QGET":
  992. return f(s.store.Get(r.Path, r.Recursive, r.Sorted))
  993. case "SYNC":
  994. s.store.DeleteExpiredKeys(time.Unix(0, r.Time))
  995. return Response{}
  996. default:
  997. // This should never be reached, but just in case:
  998. return Response{err: ErrUnknownMethod}
  999. }
  1000. }
  1001. // applyConfChange applies a ConfChange to the server. It is only
  1002. // invoked with a ConfChange that has already passed through Raft
  1003. func (s *EtcdServer) applyConfChange(cc raftpb.ConfChange, confState *raftpb.ConfState) (bool, error) {
  1004. if err := s.cluster.ValidateConfigurationChange(cc); err != nil {
  1005. cc.NodeID = raft.None
  1006. s.r.ApplyConfChange(cc)
  1007. return false, err
  1008. }
  1009. *confState = *s.r.ApplyConfChange(cc)
  1010. switch cc.Type {
  1011. case raftpb.ConfChangeAddNode:
  1012. m := new(Member)
  1013. if err := json.Unmarshal(cc.Context, m); err != nil {
  1014. plog.Panicf("unmarshal member should never fail: %v", err)
  1015. }
  1016. if cc.NodeID != uint64(m.ID) {
  1017. plog.Panicf("nodeID should always be equal to member ID")
  1018. }
  1019. s.cluster.AddMember(m)
  1020. if m.ID == s.id {
  1021. plog.Noticef("added local member %s %v to cluster %s", m.ID, m.PeerURLs, s.cluster.ID())
  1022. } else {
  1023. s.r.transport.AddPeer(m.ID, m.PeerURLs)
  1024. plog.Noticef("added member %s %v to cluster %s", m.ID, m.PeerURLs, s.cluster.ID())
  1025. }
  1026. case raftpb.ConfChangeRemoveNode:
  1027. id := types.ID(cc.NodeID)
  1028. s.cluster.RemoveMember(id)
  1029. if id == s.id {
  1030. return true, nil
  1031. } else {
  1032. s.r.transport.RemovePeer(id)
  1033. plog.Noticef("removed member %s from cluster %s", id, s.cluster.ID())
  1034. }
  1035. case raftpb.ConfChangeUpdateNode:
  1036. m := new(Member)
  1037. if err := json.Unmarshal(cc.Context, m); err != nil {
  1038. plog.Panicf("unmarshal member should never fail: %v", err)
  1039. }
  1040. if cc.NodeID != uint64(m.ID) {
  1041. plog.Panicf("nodeID should always be equal to member ID")
  1042. }
  1043. s.cluster.UpdateRaftAttributes(m.ID, m.RaftAttributes)
  1044. if m.ID == s.id {
  1045. plog.Noticef("update local member %s %v in cluster %s", m.ID, m.PeerURLs, s.cluster.ID())
  1046. } else {
  1047. s.r.transport.UpdatePeer(m.ID, m.PeerURLs)
  1048. plog.Noticef("update member %s %v in cluster %s", m.ID, m.PeerURLs, s.cluster.ID())
  1049. }
  1050. }
  1051. return false, nil
  1052. }
  1053. // TODO: non-blocking snapshot
  1054. func (s *EtcdServer) snapshot(snapi uint64, confState raftpb.ConfState) {
  1055. clone := s.store.Clone()
  1056. s.wg.Add(1)
  1057. go func() {
  1058. defer s.wg.Done()
  1059. d, err := clone.SaveNoCopy()
  1060. // TODO: current store will never fail to do a snapshot
  1061. // what should we do if the store might fail?
  1062. if err != nil {
  1063. plog.Panicf("store save should never fail: %v", err)
  1064. }
  1065. snap, err := s.r.raftStorage.CreateSnapshot(snapi, &confState, d)
  1066. if err != nil {
  1067. // the snapshot was done asynchronously with the progress of raft.
  1068. // raft might have already got a newer snapshot.
  1069. if err == raft.ErrSnapOutOfDate {
  1070. return
  1071. }
  1072. plog.Panicf("unexpected create snapshot error %v", err)
  1073. }
  1074. if s.cfg.V3demo {
  1075. // commit v3 storage because WAL file before snapshot index
  1076. // could be removed after SaveSnap.
  1077. s.getKV().Commit()
  1078. }
  1079. // SaveSnap saves the snapshot and releases the locked wal files
  1080. // to the snapshot index.
  1081. if err = s.r.storage.SaveSnap(snap); err != nil {
  1082. plog.Fatalf("save snapshot error: %v", err)
  1083. }
  1084. plog.Infof("saved snapshot at index %d", snap.Metadata.Index)
  1085. // keep some in memory log entries for slow followers.
  1086. compacti := uint64(1)
  1087. if snapi > numberOfCatchUpEntries {
  1088. compacti = snapi - numberOfCatchUpEntries
  1089. }
  1090. err = s.r.raftStorage.Compact(compacti)
  1091. if err != nil {
  1092. // the compaction was done asynchronously with the progress of raft.
  1093. // raft log might already been compact.
  1094. if err == raft.ErrCompacted {
  1095. return
  1096. }
  1097. plog.Panicf("unexpected compaction error %v", err)
  1098. }
  1099. plog.Infof("compacted raft log at %d", compacti)
  1100. }()
  1101. }
  1102. func (s *EtcdServer) PauseSending() { s.r.pauseSending() }
  1103. func (s *EtcdServer) ResumeSending() { s.r.resumeSending() }
  1104. func (s *EtcdServer) ClusterVersion() *semver.Version {
  1105. if s.cluster == nil {
  1106. return nil
  1107. }
  1108. return s.cluster.Version()
  1109. }
  1110. // monitorVersions checks the member's version every monitorVersionInterval.
  1111. // It updates the cluster version if all members agrees on a higher one.
  1112. // It prints out log if there is a member with a higher version than the
  1113. // local version.
  1114. func (s *EtcdServer) monitorVersions() {
  1115. for {
  1116. select {
  1117. case <-s.forceVersionC:
  1118. case <-time.After(monitorVersionInterval):
  1119. case <-s.done:
  1120. return
  1121. }
  1122. if s.Leader() != s.ID() {
  1123. continue
  1124. }
  1125. v := decideClusterVersion(getVersions(s.cluster, s.id, s.peerRt))
  1126. if v != nil {
  1127. // only keep major.minor version for comparison
  1128. v = &semver.Version{
  1129. Major: v.Major,
  1130. Minor: v.Minor,
  1131. }
  1132. }
  1133. // if the current version is nil:
  1134. // 1. use the decided version if possible
  1135. // 2. or use the min cluster version
  1136. if s.cluster.Version() == nil {
  1137. if v != nil {
  1138. go s.updateClusterVersion(v.String())
  1139. } else {
  1140. go s.updateClusterVersion(version.MinClusterVersion)
  1141. }
  1142. continue
  1143. }
  1144. // update cluster version only if the decided version is greater than
  1145. // the current cluster version
  1146. if v != nil && s.cluster.Version().LessThan(*v) {
  1147. go s.updateClusterVersion(v.String())
  1148. }
  1149. }
  1150. }
  1151. func (s *EtcdServer) updateClusterVersion(ver string) {
  1152. if s.cluster.Version() == nil {
  1153. plog.Infof("setting up the initial cluster version to %s", version.Cluster(ver))
  1154. } else {
  1155. plog.Infof("updating the cluster version from %s to %s", version.Cluster(s.cluster.Version().String()), version.Cluster(ver))
  1156. }
  1157. req := pb.Request{
  1158. Method: "PUT",
  1159. Path: path.Join(StoreClusterPrefix, "version"),
  1160. Val: ver,
  1161. }
  1162. ctx, cancel := context.WithTimeout(context.Background(), s.cfg.ReqTimeout())
  1163. _, err := s.Do(ctx, req)
  1164. cancel()
  1165. switch err {
  1166. case nil:
  1167. return
  1168. case ErrStopped:
  1169. plog.Infof("aborting update cluster version because server is stopped")
  1170. return
  1171. default:
  1172. plog.Errorf("error updating cluster version (%v)", err)
  1173. }
  1174. }
  1175. func (s *EtcdServer) parseProposeCtxErr(err error, start time.Time) error {
  1176. switch err {
  1177. case context.Canceled:
  1178. return ErrCanceled
  1179. case context.DeadlineExceeded:
  1180. curLeadElected := s.r.leadElectedTime()
  1181. prevLeadLost := curLeadElected.Add(-2 * time.Duration(s.cfg.ElectionTicks) * time.Duration(s.cfg.TickMs) * time.Millisecond)
  1182. if start.After(prevLeadLost) && start.Before(curLeadElected) {
  1183. return ErrTimeoutDueToLeaderFail
  1184. }
  1185. lead := types.ID(atomic.LoadUint64(&s.r.lead))
  1186. switch lead {
  1187. case types.ID(raft.None):
  1188. // TODO: return error to specify it happens because the cluster does not have leader now
  1189. case s.ID():
  1190. if !isConnectedToQuorumSince(s.r.transport, start, s.ID(), s.cluster.Members()) {
  1191. return ErrTimeoutDueToConnectionLost
  1192. }
  1193. default:
  1194. if !isConnectedSince(s.r.transport, start, lead) {
  1195. return ErrTimeoutDueToConnectionLost
  1196. }
  1197. }
  1198. return ErrTimeout
  1199. default:
  1200. return err
  1201. }
  1202. }
  1203. func (s *EtcdServer) getKV() dstorage.ConsistentWatchableKV { return s.kv }
  1204. func (s *EtcdServer) Backend() backend.Backend {
  1205. s.bemu.Lock()
  1206. defer s.bemu.Unlock()
  1207. return s.be
  1208. }
  1209. func (s *EtcdServer) AuthStore() auth.AuthStore { return s.authStore }