server.go 50 KB

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