server.go 50 KB

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