server.go 50 KB

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