server.go 37 KB

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