server.go 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699
  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/internal/mvcc"
  39. "github.com/coreos/etcd/internal/mvcc/backend"
  40. "github.com/coreos/etcd/internal/raftsnap"
  41. "github.com/coreos/etcd/internal/store"
  42. "github.com/coreos/etcd/lease"
  43. "github.com/coreos/etcd/lease/leasehttp"
  44. "github.com/coreos/etcd/pkg/fileutil"
  45. "github.com/coreos/etcd/pkg/idutil"
  46. "github.com/coreos/etcd/pkg/pbutil"
  47. "github.com/coreos/etcd/pkg/runtime"
  48. "github.com/coreos/etcd/pkg/schedule"
  49. "github.com/coreos/etcd/pkg/types"
  50. "github.com/coreos/etcd/pkg/wait"
  51. "github.com/coreos/etcd/raft"
  52. "github.com/coreos/etcd/raft/raftpb"
  53. "github.com/coreos/etcd/rafthttp"
  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 *raftsnap.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 := raftsnap.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 != raftsnap.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. // Start performs any initialization of the Server necessary for it to
  460. // begin serving requests. It must be called before Do or Process.
  461. // Start must be non-blocking; any long-running server functionality
  462. // should be implemented in goroutines.
  463. func (s *EtcdServer) Start() {
  464. s.start()
  465. s.goAttach(func() { s.publish(s.Cfg.ReqTimeout()) })
  466. s.goAttach(s.purgeFile)
  467. s.goAttach(func() { monitorFileDescriptor(s.stopping) })
  468. s.goAttach(s.monitorVersions)
  469. s.goAttach(s.linearizableReadLoop)
  470. s.goAttach(s.monitorKVHash)
  471. }
  472. // start prepares and starts server in a new goroutine. It is no longer safe to
  473. // modify a server's fields after it has been sent to Start.
  474. // This function is just used for testing.
  475. func (s *EtcdServer) start() {
  476. if s.Cfg.SnapCount == 0 {
  477. plog.Infof("set snapshot count to default %d", DefaultSnapCount)
  478. s.Cfg.SnapCount = DefaultSnapCount
  479. }
  480. s.w = wait.New()
  481. s.applyWait = wait.NewTimeList()
  482. s.done = make(chan struct{})
  483. s.stop = make(chan struct{})
  484. s.stopping = make(chan struct{})
  485. s.ctx, s.cancel = context.WithCancel(context.Background())
  486. s.readwaitc = make(chan struct{}, 1)
  487. s.readNotifier = newNotifier()
  488. if s.ClusterVersion() != nil {
  489. plog.Infof("starting server... [version: %v, cluster version: %v]", version.Version, version.Cluster(s.ClusterVersion().String()))
  490. } else {
  491. plog.Infof("starting server... [version: %v, cluster version: to_be_decided]", version.Version)
  492. }
  493. // TODO: if this is an empty log, writes all peer infos
  494. // into the first entry
  495. go s.run()
  496. }
  497. func (s *EtcdServer) purgeFile() {
  498. var dberrc, serrc, werrc <-chan error
  499. if s.Cfg.MaxSnapFiles > 0 {
  500. dberrc = fileutil.PurgeFile(s.Cfg.SnapDir(), "snap.db", s.Cfg.MaxSnapFiles, purgeFileInterval, s.done)
  501. serrc = fileutil.PurgeFile(s.Cfg.SnapDir(), "snap", s.Cfg.MaxSnapFiles, purgeFileInterval, s.done)
  502. }
  503. if s.Cfg.MaxWALFiles > 0 {
  504. werrc = fileutil.PurgeFile(s.Cfg.WALDir(), "wal", s.Cfg.MaxWALFiles, purgeFileInterval, s.done)
  505. }
  506. select {
  507. case e := <-dberrc:
  508. plog.Fatalf("failed to purge snap db file %v", e)
  509. case e := <-serrc:
  510. plog.Fatalf("failed to purge snap file %v", e)
  511. case e := <-werrc:
  512. plog.Fatalf("failed to purge wal file %v", e)
  513. case <-s.stopping:
  514. return
  515. }
  516. }
  517. func (s *EtcdServer) ID() types.ID { return s.id }
  518. func (s *EtcdServer) Cluster() api.Cluster { return s.cluster }
  519. func (s *EtcdServer) ApplyWait() <-chan struct{} { return s.applyWait.Wait(s.getCommittedIndex()) }
  520. type ServerPeer interface {
  521. ServerV2
  522. RaftHandler() http.Handler
  523. LeaseHandler() http.Handler
  524. }
  525. func (s *EtcdServer) LeaseHandler() http.Handler {
  526. if s.lessor == nil {
  527. return nil
  528. }
  529. return leasehttp.NewHandler(s.lessor, s.ApplyWait)
  530. }
  531. func (s *EtcdServer) RaftHandler() http.Handler { return s.r.transport.Handler() }
  532. // Process takes a raft message and applies it to the server's raft state
  533. // machine, respecting any timeout of the given context.
  534. func (s *EtcdServer) Process(ctx context.Context, m raftpb.Message) error {
  535. if s.cluster.IsIDRemoved(types.ID(m.From)) {
  536. plog.Warningf("reject message from removed member %s", types.ID(m.From).String())
  537. return httptypes.NewHTTPError(http.StatusForbidden, "cannot process message from removed member")
  538. }
  539. if m.Type == raftpb.MsgApp {
  540. s.stats.RecvAppendReq(types.ID(m.From).String(), m.Size())
  541. }
  542. return s.r.Step(ctx, m)
  543. }
  544. func (s *EtcdServer) IsIDRemoved(id uint64) bool { return s.cluster.IsIDRemoved(types.ID(id)) }
  545. func (s *EtcdServer) ReportUnreachable(id uint64) { s.r.ReportUnreachable(id) }
  546. // ReportSnapshot reports snapshot sent status to the raft state machine,
  547. // and clears the used snapshot from the snapshot store.
  548. func (s *EtcdServer) ReportSnapshot(id uint64, status raft.SnapshotStatus) {
  549. s.r.ReportSnapshot(id, status)
  550. }
  551. type etcdProgress struct {
  552. confState raftpb.ConfState
  553. snapi uint64
  554. appliedt uint64
  555. appliedi uint64
  556. }
  557. // raftReadyHandler contains a set of EtcdServer operations to be called by raftNode,
  558. // and helps decouple state machine logic from Raft algorithms.
  559. // TODO: add a state machine interface to apply the commit entries and do snapshot/recover
  560. type raftReadyHandler struct {
  561. updateLeadership func(newLeader bool)
  562. updateCommittedIndex func(uint64)
  563. }
  564. func (s *EtcdServer) run() {
  565. sn, err := s.r.raftStorage.Snapshot()
  566. if err != nil {
  567. plog.Panicf("get snapshot from raft storage error: %v", err)
  568. }
  569. // asynchronously accept apply packets, dispatch progress in-order
  570. sched := schedule.NewFIFOScheduler()
  571. var (
  572. smu sync.RWMutex
  573. syncC <-chan time.Time
  574. )
  575. setSyncC := func(ch <-chan time.Time) {
  576. smu.Lock()
  577. syncC = ch
  578. smu.Unlock()
  579. }
  580. getSyncC := func() (ch <-chan time.Time) {
  581. smu.RLock()
  582. ch = syncC
  583. smu.RUnlock()
  584. return
  585. }
  586. rh := &raftReadyHandler{
  587. updateLeadership: func(newLeader bool) {
  588. if !s.isLeader() {
  589. if s.lessor != nil {
  590. s.lessor.Demote()
  591. }
  592. if s.compactor != nil {
  593. s.compactor.Pause()
  594. }
  595. setSyncC(nil)
  596. } else {
  597. if newLeader {
  598. t := time.Now()
  599. s.leadTimeMu.Lock()
  600. s.leadElectedTime = t
  601. s.leadTimeMu.Unlock()
  602. }
  603. setSyncC(s.SyncTicker.C)
  604. if s.compactor != nil {
  605. s.compactor.Resume()
  606. }
  607. }
  608. // TODO: remove the nil checking
  609. // current test utility does not provide the stats
  610. if s.stats != nil {
  611. s.stats.BecomeLeader()
  612. }
  613. },
  614. updateCommittedIndex: func(ci uint64) {
  615. cci := s.getCommittedIndex()
  616. if ci > cci {
  617. s.setCommittedIndex(ci)
  618. }
  619. },
  620. }
  621. s.r.start(rh)
  622. ep := etcdProgress{
  623. confState: sn.Metadata.ConfState,
  624. snapi: sn.Metadata.Index,
  625. appliedt: sn.Metadata.Term,
  626. appliedi: sn.Metadata.Index,
  627. }
  628. defer func() {
  629. s.wgMu.Lock() // block concurrent waitgroup adds in goAttach while stopping
  630. close(s.stopping)
  631. s.wgMu.Unlock()
  632. s.cancel()
  633. sched.Stop()
  634. // wait for gouroutines before closing raft so wal stays open
  635. s.wg.Wait()
  636. s.SyncTicker.Stop()
  637. // must stop raft after scheduler-- etcdserver can leak rafthttp pipelines
  638. // by adding a peer after raft stops the transport
  639. s.r.stop()
  640. // kv, lessor and backend can be nil if running without v3 enabled
  641. // or running unit tests.
  642. if s.lessor != nil {
  643. s.lessor.Stop()
  644. }
  645. if s.kv != nil {
  646. s.kv.Close()
  647. }
  648. if s.authStore != nil {
  649. s.authStore.Close()
  650. }
  651. if s.be != nil {
  652. s.be.Close()
  653. }
  654. if s.compactor != nil {
  655. s.compactor.Stop()
  656. }
  657. close(s.done)
  658. }()
  659. var expiredLeaseC <-chan []*lease.Lease
  660. if s.lessor != nil {
  661. expiredLeaseC = s.lessor.ExpiredLeasesC()
  662. }
  663. for {
  664. select {
  665. case ap := <-s.r.apply():
  666. f := func(context.Context) { s.applyAll(&ep, &ap) }
  667. sched.Schedule(f)
  668. case leases := <-expiredLeaseC:
  669. s.goAttach(func() {
  670. // Increases throughput of expired leases deletion process through parallelization
  671. c := make(chan struct{}, maxPendingRevokes)
  672. for _, lease := range leases {
  673. select {
  674. case c <- struct{}{}:
  675. case <-s.stopping:
  676. return
  677. }
  678. lid := lease.ID
  679. s.goAttach(func() {
  680. ctx := s.authStore.WithRoot(s.ctx)
  681. if _, lerr := s.LeaseRevoke(ctx, &pb.LeaseRevokeRequest{ID: int64(lid)}); lerr != nil {
  682. plog.Warningf("failed to revoke %016x (%q)", lid, lerr.Error())
  683. }
  684. leaseExpired.Inc()
  685. <-c
  686. })
  687. }
  688. })
  689. case err := <-s.errorc:
  690. plog.Errorf("%s", err)
  691. plog.Infof("the data-dir used by this member must be removed.")
  692. return
  693. case <-getSyncC():
  694. if s.store.HasTTLKeys() {
  695. s.sync(s.Cfg.ReqTimeout())
  696. }
  697. case <-s.stop:
  698. return
  699. }
  700. }
  701. }
  702. func (s *EtcdServer) applyAll(ep *etcdProgress, apply *apply) {
  703. s.applySnapshot(ep, apply)
  704. s.applyEntries(ep, apply)
  705. proposalsApplied.Set(float64(ep.appliedi))
  706. s.applyWait.Trigger(ep.appliedi)
  707. // wait for the raft routine to finish the disk writes before triggering a
  708. // snapshot. or applied index might be greater than the last index in raft
  709. // storage, since the raft routine might be slower than apply routine.
  710. <-apply.notifyc
  711. s.triggerSnapshot(ep)
  712. select {
  713. // snapshot requested via send()
  714. case m := <-s.r.msgSnapC:
  715. merged := s.createMergedSnapshotMessage(m, ep.appliedt, ep.appliedi, ep.confState)
  716. s.sendMergedSnap(merged)
  717. default:
  718. }
  719. }
  720. func (s *EtcdServer) applySnapshot(ep *etcdProgress, apply *apply) {
  721. if raft.IsEmptySnap(apply.snapshot) {
  722. return
  723. }
  724. plog.Infof("applying snapshot at index %d...", ep.snapi)
  725. defer plog.Infof("finished applying incoming snapshot at index %d", ep.snapi)
  726. if apply.snapshot.Metadata.Index <= ep.appliedi {
  727. plog.Panicf("snapshot index [%d] should > appliedi[%d] + 1",
  728. apply.snapshot.Metadata.Index, ep.appliedi)
  729. }
  730. // wait for raftNode to persist snapshot onto the disk
  731. <-apply.notifyc
  732. newbe, err := openSnapshotBackend(s.Cfg, s.snapshotter, apply.snapshot)
  733. if err != nil {
  734. plog.Panic(err)
  735. }
  736. // always recover lessor before kv. When we recover the mvcc.KV it will reattach keys to its leases.
  737. // If we recover mvcc.KV first, it will attach the keys to the wrong lessor before it recovers.
  738. if s.lessor != nil {
  739. plog.Info("recovering lessor...")
  740. s.lessor.Recover(newbe, func() lease.TxnDelete { return s.kv.Write() })
  741. plog.Info("finished recovering lessor")
  742. }
  743. plog.Info("restoring mvcc store...")
  744. if err := s.kv.Restore(newbe); err != nil {
  745. plog.Panicf("restore KV error: %v", err)
  746. }
  747. s.consistIndex.setConsistentIndex(s.kv.ConsistentIndex())
  748. plog.Info("finished restoring mvcc store")
  749. // Closing old backend might block until all the txns
  750. // on the backend are finished.
  751. // We do not want to wait on closing the old backend.
  752. s.bemu.Lock()
  753. oldbe := s.be
  754. go func() {
  755. plog.Info("closing old backend...")
  756. defer plog.Info("finished closing old backend")
  757. if err := oldbe.Close(); err != nil {
  758. plog.Panicf("close backend error: %v", err)
  759. }
  760. }()
  761. s.be = newbe
  762. s.bemu.Unlock()
  763. plog.Info("recovering alarms...")
  764. if err := s.restoreAlarms(); err != nil {
  765. plog.Panicf("restore alarms error: %v", err)
  766. }
  767. plog.Info("finished recovering alarms")
  768. if s.authStore != nil {
  769. plog.Info("recovering auth store...")
  770. s.authStore.Recover(newbe)
  771. plog.Info("finished recovering auth store")
  772. }
  773. plog.Info("recovering store v2...")
  774. if err := s.store.Recovery(apply.snapshot.Data); err != nil {
  775. plog.Panicf("recovery store error: %v", err)
  776. }
  777. plog.Info("finished recovering store v2")
  778. s.cluster.SetBackend(s.be)
  779. plog.Info("recovering cluster configuration...")
  780. s.cluster.Recover(api.UpdateCapability)
  781. plog.Info("finished recovering cluster configuration")
  782. plog.Info("removing old peers from network...")
  783. // recover raft transport
  784. s.r.transport.RemoveAllPeers()
  785. plog.Info("finished removing old peers from network")
  786. plog.Info("adding peers from new cluster configuration into network...")
  787. for _, m := range s.cluster.Members() {
  788. if m.ID == s.ID() {
  789. continue
  790. }
  791. s.r.transport.AddPeer(m.ID, m.PeerURLs)
  792. }
  793. plog.Info("finished adding peers from new cluster configuration into network...")
  794. ep.appliedt = apply.snapshot.Metadata.Term
  795. ep.appliedi = apply.snapshot.Metadata.Index
  796. ep.snapi = ep.appliedi
  797. ep.confState = apply.snapshot.Metadata.ConfState
  798. }
  799. func (s *EtcdServer) applyEntries(ep *etcdProgress, apply *apply) {
  800. if len(apply.entries) == 0 {
  801. return
  802. }
  803. firsti := apply.entries[0].Index
  804. if firsti > ep.appliedi+1 {
  805. plog.Panicf("first index of committed entry[%d] should <= appliedi[%d] + 1", firsti, ep.appliedi)
  806. }
  807. var ents []raftpb.Entry
  808. if ep.appliedi+1-firsti < uint64(len(apply.entries)) {
  809. ents = apply.entries[ep.appliedi+1-firsti:]
  810. }
  811. if len(ents) == 0 {
  812. return
  813. }
  814. var shouldstop bool
  815. if ep.appliedt, ep.appliedi, shouldstop = s.apply(ents, &ep.confState); shouldstop {
  816. go s.stopWithDelay(10*100*time.Millisecond, fmt.Errorf("the member has been permanently removed from the cluster"))
  817. }
  818. }
  819. func (s *EtcdServer) triggerSnapshot(ep *etcdProgress) {
  820. if ep.appliedi-ep.snapi <= s.Cfg.SnapCount {
  821. return
  822. }
  823. plog.Infof("start to snapshot (applied: %d, lastsnap: %d)", ep.appliedi, ep.snapi)
  824. s.snapshot(ep.appliedi, ep.confState)
  825. ep.snapi = ep.appliedi
  826. }
  827. func (s *EtcdServer) isMultiNode() bool {
  828. return s.cluster != nil && len(s.cluster.MemberIDs()) > 1
  829. }
  830. func (s *EtcdServer) isLeader() bool {
  831. return uint64(s.ID()) == s.Lead()
  832. }
  833. // MoveLeader transfers the leader to the given transferee.
  834. func (s *EtcdServer) MoveLeader(ctx context.Context, lead, transferee uint64) error {
  835. now := time.Now()
  836. interval := time.Duration(s.Cfg.TickMs) * time.Millisecond
  837. plog.Infof("%s starts leadership transfer from %s to %s", s.ID(), types.ID(lead), types.ID(transferee))
  838. s.r.TransferLeadership(ctx, lead, transferee)
  839. for s.Lead() != transferee {
  840. select {
  841. case <-ctx.Done(): // time out
  842. return ErrTimeoutLeaderTransfer
  843. case <-time.After(interval):
  844. }
  845. }
  846. // TODO: drain all requests, or drop all messages to the old leader
  847. plog.Infof("%s finished leadership transfer from %s to %s (took %v)", s.ID(), types.ID(lead), types.ID(transferee), time.Since(now))
  848. return nil
  849. }
  850. // TransferLeadership transfers the leader to the chosen transferee.
  851. func (s *EtcdServer) TransferLeadership() error {
  852. if !s.isLeader() {
  853. plog.Printf("skipped leadership transfer for stopping non-leader member")
  854. return nil
  855. }
  856. if !s.isMultiNode() {
  857. plog.Printf("skipped leadership transfer for single member cluster")
  858. return nil
  859. }
  860. transferee, ok := longestConnected(s.r.transport, s.cluster.MemberIDs())
  861. if !ok {
  862. return ErrUnhealthy
  863. }
  864. tm := s.Cfg.ReqTimeout()
  865. ctx, cancel := context.WithTimeout(s.ctx, tm)
  866. err := s.MoveLeader(ctx, s.Lead(), uint64(transferee))
  867. cancel()
  868. return err
  869. }
  870. // HardStop stops the server without coordination with other members in the cluster.
  871. func (s *EtcdServer) HardStop() {
  872. select {
  873. case s.stop <- struct{}{}:
  874. case <-s.done:
  875. return
  876. }
  877. <-s.done
  878. }
  879. // Stop stops the server gracefully, and shuts down the running goroutine.
  880. // Stop should be called after a Start(s), otherwise it will block forever.
  881. // When stopping leader, Stop transfers its leadership to one of its peers
  882. // before stopping the server.
  883. // Stop terminates the Server and performs any necessary finalization.
  884. // Do and Process cannot be called after Stop has been invoked.
  885. func (s *EtcdServer) Stop() {
  886. if err := s.TransferLeadership(); err != nil {
  887. plog.Warningf("%s failed to transfer leadership (%v)", s.ID(), err)
  888. }
  889. s.HardStop()
  890. }
  891. // ReadyNotify returns a channel that will be closed when the server
  892. // is ready to serve client requests
  893. func (s *EtcdServer) ReadyNotify() <-chan struct{} { return s.readych }
  894. func (s *EtcdServer) stopWithDelay(d time.Duration, err error) {
  895. select {
  896. case <-time.After(d):
  897. case <-s.done:
  898. }
  899. select {
  900. case s.errorc <- err:
  901. default:
  902. }
  903. }
  904. // StopNotify returns a channel that receives a empty struct
  905. // when the server is stopped.
  906. func (s *EtcdServer) StopNotify() <-chan struct{} { return s.done }
  907. func (s *EtcdServer) SelfStats() []byte { return s.stats.JSON() }
  908. func (s *EtcdServer) LeaderStats() []byte {
  909. lead := atomic.LoadUint64(&s.r.lead)
  910. if lead != uint64(s.id) {
  911. return nil
  912. }
  913. return s.lstats.JSON()
  914. }
  915. func (s *EtcdServer) StoreStats() []byte { return s.store.JsonStats() }
  916. func (s *EtcdServer) checkMembershipOperationPermission(ctx context.Context) error {
  917. if s.authStore == nil {
  918. // In the context of ordinary etcd process, s.authStore will never be nil.
  919. // This branch is for handling cases in server_test.go
  920. return nil
  921. }
  922. // Note that this permission check is done in the API layer,
  923. // so TOCTOU problem can be caused potentially in a schedule like this:
  924. // update membership with user A -> revoke root role of A -> apply membership change
  925. // in the state machine layer
  926. // However, both of membership change and role management requires the root privilege.
  927. // So careful operation by admins can prevent the problem.
  928. authInfo, err := s.AuthInfoFromCtx(ctx)
  929. if err != nil {
  930. return err
  931. }
  932. return s.AuthStore().IsAdminPermitted(authInfo)
  933. }
  934. func (s *EtcdServer) AddMember(ctx context.Context, memb membership.Member) ([]*membership.Member, error) {
  935. if err := s.checkMembershipOperationPermission(ctx); err != nil {
  936. return nil, err
  937. }
  938. if s.Cfg.StrictReconfigCheck {
  939. // by default StrictReconfigCheck is enabled; reject new members if unhealthy
  940. if !s.cluster.IsReadyToAddNewMember() {
  941. plog.Warningf("not enough started members, rejecting member add %+v", memb)
  942. return nil, ErrNotEnoughStartedMembers
  943. }
  944. if !isConnectedFullySince(s.r.transport, time.Now().Add(-HealthInterval), s.ID(), s.cluster.Members()) {
  945. plog.Warningf("not healthy for reconfigure, rejecting member add %+v", memb)
  946. return nil, ErrUnhealthy
  947. }
  948. }
  949. // TODO: move Member to protobuf type
  950. b, err := json.Marshal(memb)
  951. if err != nil {
  952. return nil, err
  953. }
  954. cc := raftpb.ConfChange{
  955. Type: raftpb.ConfChangeAddNode,
  956. NodeID: uint64(memb.ID),
  957. Context: b,
  958. }
  959. return s.configure(ctx, cc)
  960. }
  961. func (s *EtcdServer) RemoveMember(ctx context.Context, id uint64) ([]*membership.Member, error) {
  962. if err := s.checkMembershipOperationPermission(ctx); err != nil {
  963. return nil, err
  964. }
  965. // by default StrictReconfigCheck is enabled; reject removal if leads to quorum loss
  966. if err := s.mayRemoveMember(types.ID(id)); err != nil {
  967. return nil, err
  968. }
  969. cc := raftpb.ConfChange{
  970. Type: raftpb.ConfChangeRemoveNode,
  971. NodeID: id,
  972. }
  973. return s.configure(ctx, cc)
  974. }
  975. func (s *EtcdServer) mayRemoveMember(id types.ID) error {
  976. if !s.Cfg.StrictReconfigCheck {
  977. return nil
  978. }
  979. if !s.cluster.IsReadyToRemoveMember(uint64(id)) {
  980. plog.Warningf("not enough started members, rejecting remove member %s", id)
  981. return ErrNotEnoughStartedMembers
  982. }
  983. // downed member is safe to remove since it's not part of the active quorum
  984. if t := s.r.transport.ActiveSince(id); id != s.ID() && t.IsZero() {
  985. return nil
  986. }
  987. // protect quorum if some members are down
  988. m := s.cluster.Members()
  989. active := numConnectedSince(s.r.transport, time.Now().Add(-HealthInterval), s.ID(), m)
  990. if (active - 1) < 1+((len(m)-1)/2) {
  991. plog.Warningf("reconfigure breaks active quorum, rejecting remove member %s", id)
  992. return ErrUnhealthy
  993. }
  994. return nil
  995. }
  996. func (s *EtcdServer) UpdateMember(ctx context.Context, memb membership.Member) ([]*membership.Member, error) {
  997. b, merr := json.Marshal(memb)
  998. if merr != nil {
  999. return nil, merr
  1000. }
  1001. if err := s.checkMembershipOperationPermission(ctx); err != nil {
  1002. return nil, err
  1003. }
  1004. cc := raftpb.ConfChange{
  1005. Type: raftpb.ConfChangeUpdateNode,
  1006. NodeID: uint64(memb.ID),
  1007. Context: b,
  1008. }
  1009. return s.configure(ctx, cc)
  1010. }
  1011. // Implement the RaftTimer interface
  1012. func (s *EtcdServer) Index() uint64 { return atomic.LoadUint64(&s.r.index) }
  1013. func (s *EtcdServer) AppliedIndex() uint64 { return atomic.LoadUint64(&s.r.appliedindex) }
  1014. func (s *EtcdServer) Term() uint64 { return atomic.LoadUint64(&s.r.term) }
  1015. // Lead is only for testing purposes.
  1016. // TODO: add Raft server interface to expose raft related info:
  1017. // Index, Term, Lead, Committed, Applied, LastIndex, etc.
  1018. func (s *EtcdServer) Lead() uint64 { return atomic.LoadUint64(&s.r.lead) }
  1019. func (s *EtcdServer) Leader() types.ID { return types.ID(s.Lead()) }
  1020. type confChangeResponse struct {
  1021. membs []*membership.Member
  1022. err error
  1023. }
  1024. // configure sends a configuration change through consensus and
  1025. // then waits for it to be applied to the server. It
  1026. // will block until the change is performed or there is an error.
  1027. func (s *EtcdServer) configure(ctx context.Context, cc raftpb.ConfChange) ([]*membership.Member, error) {
  1028. cc.ID = s.reqIDGen.Next()
  1029. ch := s.w.Register(cc.ID)
  1030. start := time.Now()
  1031. if err := s.r.ProposeConfChange(ctx, cc); err != nil {
  1032. s.w.Trigger(cc.ID, nil)
  1033. return nil, err
  1034. }
  1035. select {
  1036. case x := <-ch:
  1037. if x == nil {
  1038. plog.Panicf("configure trigger value should never be nil")
  1039. }
  1040. resp := x.(*confChangeResponse)
  1041. return resp.membs, resp.err
  1042. case <-ctx.Done():
  1043. s.w.Trigger(cc.ID, nil) // GC wait
  1044. return nil, s.parseProposeCtxErr(ctx.Err(), start)
  1045. case <-s.stopping:
  1046. return nil, ErrStopped
  1047. }
  1048. }
  1049. // sync proposes a SYNC request and is non-blocking.
  1050. // This makes no guarantee that the request will be proposed or performed.
  1051. // The request will be canceled after the given timeout.
  1052. func (s *EtcdServer) sync(timeout time.Duration) {
  1053. req := pb.Request{
  1054. Method: "SYNC",
  1055. ID: s.reqIDGen.Next(),
  1056. Time: time.Now().UnixNano(),
  1057. }
  1058. data := pbutil.MustMarshal(&req)
  1059. // There is no promise that node has leader when do SYNC request,
  1060. // so it uses goroutine to propose.
  1061. ctx, cancel := context.WithTimeout(s.ctx, timeout)
  1062. s.goAttach(func() {
  1063. s.r.Propose(ctx, data)
  1064. cancel()
  1065. })
  1066. }
  1067. // publish registers server information into the cluster. The information
  1068. // is the JSON representation of this server's member struct, updated with the
  1069. // static clientURLs of the server.
  1070. // The function keeps attempting to register until it succeeds,
  1071. // or its server is stopped.
  1072. func (s *EtcdServer) publish(timeout time.Duration) {
  1073. b, err := json.Marshal(s.attributes)
  1074. if err != nil {
  1075. plog.Panicf("json marshal error: %v", err)
  1076. return
  1077. }
  1078. req := pb.Request{
  1079. Method: "PUT",
  1080. Path: membership.MemberAttributesStorePath(s.id),
  1081. Val: string(b),
  1082. }
  1083. for {
  1084. ctx, cancel := context.WithTimeout(s.ctx, timeout)
  1085. _, err := s.Do(ctx, req)
  1086. cancel()
  1087. switch err {
  1088. case nil:
  1089. close(s.readych)
  1090. plog.Infof("published %+v to cluster %s", s.attributes, s.cluster.ID())
  1091. return
  1092. case ErrStopped:
  1093. plog.Infof("aborting publish because server is stopped")
  1094. return
  1095. default:
  1096. plog.Errorf("publish error: %v", err)
  1097. }
  1098. }
  1099. }
  1100. func (s *EtcdServer) sendMergedSnap(merged raftsnap.Message) {
  1101. atomic.AddInt64(&s.inflightSnapshots, 1)
  1102. s.r.transport.SendSnapshot(merged)
  1103. s.goAttach(func() {
  1104. select {
  1105. case ok := <-merged.CloseNotify():
  1106. // delay releasing inflight snapshot for another 30 seconds to
  1107. // block log compaction.
  1108. // If the follower still fails to catch up, it is probably just too slow
  1109. // to catch up. We cannot avoid the snapshot cycle anyway.
  1110. if ok {
  1111. select {
  1112. case <-time.After(releaseDelayAfterSnapshot):
  1113. case <-s.stopping:
  1114. }
  1115. }
  1116. atomic.AddInt64(&s.inflightSnapshots, -1)
  1117. case <-s.stopping:
  1118. return
  1119. }
  1120. })
  1121. }
  1122. // apply takes entries received from Raft (after it has been committed) and
  1123. // applies them to the current state of the EtcdServer.
  1124. // The given entries should not be empty.
  1125. func (s *EtcdServer) apply(es []raftpb.Entry, confState *raftpb.ConfState) (appliedt uint64, appliedi uint64, shouldStop bool) {
  1126. for i := range es {
  1127. e := es[i]
  1128. switch e.Type {
  1129. case raftpb.EntryNormal:
  1130. s.applyEntryNormal(&e)
  1131. case raftpb.EntryConfChange:
  1132. // set the consistent index of current executing entry
  1133. if e.Index > s.consistIndex.ConsistentIndex() {
  1134. s.consistIndex.setConsistentIndex(e.Index)
  1135. }
  1136. var cc raftpb.ConfChange
  1137. pbutil.MustUnmarshal(&cc, e.Data)
  1138. removedSelf, err := s.applyConfChange(cc, confState)
  1139. s.setAppliedIndex(e.Index)
  1140. shouldStop = shouldStop || removedSelf
  1141. s.w.Trigger(cc.ID, &confChangeResponse{s.cluster.Members(), err})
  1142. default:
  1143. plog.Panicf("entry type should be either EntryNormal or EntryConfChange")
  1144. }
  1145. atomic.StoreUint64(&s.r.index, e.Index)
  1146. atomic.StoreUint64(&s.r.term, e.Term)
  1147. appliedt = e.Term
  1148. appliedi = e.Index
  1149. }
  1150. return appliedt, appliedi, shouldStop
  1151. }
  1152. // applyEntryNormal apples an EntryNormal type raftpb request to the EtcdServer
  1153. func (s *EtcdServer) applyEntryNormal(e *raftpb.Entry) {
  1154. shouldApplyV3 := false
  1155. if e.Index > s.consistIndex.ConsistentIndex() {
  1156. // set the consistent index of current executing entry
  1157. s.consistIndex.setConsistentIndex(e.Index)
  1158. shouldApplyV3 = true
  1159. }
  1160. defer s.setAppliedIndex(e.Index)
  1161. // raft state machine may generate noop entry when leader confirmation.
  1162. // skip it in advance to avoid some potential bug in the future
  1163. if len(e.Data) == 0 {
  1164. select {
  1165. case s.forceVersionC <- struct{}{}:
  1166. default:
  1167. }
  1168. // promote lessor when the local member is leader and finished
  1169. // applying all entries from the last term.
  1170. if s.isLeader() {
  1171. s.lessor.Promote(s.Cfg.electionTimeout())
  1172. }
  1173. return
  1174. }
  1175. var raftReq pb.InternalRaftRequest
  1176. if !pbutil.MaybeUnmarshal(&raftReq, e.Data) { // backward compatible
  1177. var r pb.Request
  1178. rp := &r
  1179. pbutil.MustUnmarshal(rp, e.Data)
  1180. s.w.Trigger(r.ID, s.applyV2Request((*RequestV2)(rp)))
  1181. return
  1182. }
  1183. if raftReq.V2 != nil {
  1184. req := (*RequestV2)(raftReq.V2)
  1185. s.w.Trigger(req.ID, s.applyV2Request(req))
  1186. return
  1187. }
  1188. // do not re-apply applied entries.
  1189. if !shouldApplyV3 {
  1190. return
  1191. }
  1192. id := raftReq.ID
  1193. if id == 0 {
  1194. id = raftReq.Header.ID
  1195. }
  1196. var ar *applyResult
  1197. needResult := s.w.IsRegistered(id)
  1198. if needResult || !noSideEffect(&raftReq) {
  1199. if !needResult && raftReq.Txn != nil {
  1200. removeNeedlessRangeReqs(raftReq.Txn)
  1201. }
  1202. ar = s.applyV3.Apply(&raftReq)
  1203. }
  1204. if ar == nil {
  1205. return
  1206. }
  1207. if ar.err != ErrNoSpace || len(s.alarmStore.Get(pb.AlarmType_NOSPACE)) > 0 {
  1208. s.w.Trigger(id, ar)
  1209. return
  1210. }
  1211. plog.Errorf("applying raft message exceeded backend quota")
  1212. s.goAttach(func() {
  1213. a := &pb.AlarmRequest{
  1214. MemberID: uint64(s.ID()),
  1215. Action: pb.AlarmRequest_ACTIVATE,
  1216. Alarm: pb.AlarmType_NOSPACE,
  1217. }
  1218. s.raftRequest(s.ctx, pb.InternalRaftRequest{Alarm: a})
  1219. s.w.Trigger(id, ar)
  1220. })
  1221. }
  1222. // applyConfChange applies a ConfChange to the server. It is only
  1223. // invoked with a ConfChange that has already passed through Raft
  1224. func (s *EtcdServer) applyConfChange(cc raftpb.ConfChange, confState *raftpb.ConfState) (bool, error) {
  1225. if err := s.cluster.ValidateConfigurationChange(cc); err != nil {
  1226. cc.NodeID = raft.None
  1227. s.r.ApplyConfChange(cc)
  1228. return false, err
  1229. }
  1230. *confState = *s.r.ApplyConfChange(cc)
  1231. switch cc.Type {
  1232. case raftpb.ConfChangeAddNode:
  1233. m := new(membership.Member)
  1234. if err := json.Unmarshal(cc.Context, m); err != nil {
  1235. plog.Panicf("unmarshal member should never fail: %v", err)
  1236. }
  1237. if cc.NodeID != uint64(m.ID) {
  1238. plog.Panicf("nodeID should always be equal to member ID")
  1239. }
  1240. s.cluster.AddMember(m)
  1241. if m.ID != s.id {
  1242. s.r.transport.AddPeer(m.ID, m.PeerURLs)
  1243. }
  1244. case raftpb.ConfChangeRemoveNode:
  1245. id := types.ID(cc.NodeID)
  1246. s.cluster.RemoveMember(id)
  1247. if id == s.id {
  1248. return true, nil
  1249. }
  1250. s.r.transport.RemovePeer(id)
  1251. case raftpb.ConfChangeUpdateNode:
  1252. m := new(membership.Member)
  1253. if err := json.Unmarshal(cc.Context, m); err != nil {
  1254. plog.Panicf("unmarshal member should never fail: %v", err)
  1255. }
  1256. if cc.NodeID != uint64(m.ID) {
  1257. plog.Panicf("nodeID should always be equal to member ID")
  1258. }
  1259. s.cluster.UpdateRaftAttributes(m.ID, m.RaftAttributes)
  1260. if m.ID != s.id {
  1261. s.r.transport.UpdatePeer(m.ID, m.PeerURLs)
  1262. }
  1263. }
  1264. return false, nil
  1265. }
  1266. // TODO: non-blocking snapshot
  1267. func (s *EtcdServer) snapshot(snapi uint64, confState raftpb.ConfState) {
  1268. clone := s.store.Clone()
  1269. // commit kv to write metadata (for example: consistent index) to disk.
  1270. // KV().commit() updates the consistent index in backend.
  1271. // All operations that update consistent index must be called sequentially
  1272. // from applyAll function.
  1273. // So KV().Commit() cannot run in parallel with apply. It has to be called outside
  1274. // the go routine created below.
  1275. s.KV().Commit()
  1276. s.goAttach(func() {
  1277. d, err := clone.SaveNoCopy()
  1278. // TODO: current store will never fail to do a snapshot
  1279. // what should we do if the store might fail?
  1280. if err != nil {
  1281. plog.Panicf("store save should never fail: %v", err)
  1282. }
  1283. snap, err := s.r.raftStorage.CreateSnapshot(snapi, &confState, d)
  1284. if err != nil {
  1285. // the snapshot was done asynchronously with the progress of raft.
  1286. // raft might have already got a newer snapshot.
  1287. if err == raft.ErrSnapOutOfDate {
  1288. return
  1289. }
  1290. plog.Panicf("unexpected create snapshot error %v", err)
  1291. }
  1292. // SaveSnap saves the snapshot and releases the locked wal files
  1293. // to the snapshot index.
  1294. if err = s.r.storage.SaveSnap(snap); err != nil {
  1295. plog.Fatalf("save snapshot error: %v", err)
  1296. }
  1297. plog.Infof("saved snapshot at index %d", snap.Metadata.Index)
  1298. // When sending a snapshot, etcd will pause compaction.
  1299. // After receives a snapshot, the slow follower needs to get all the entries right after
  1300. // the snapshot sent to catch up. If we do not pause compaction, the log entries right after
  1301. // the snapshot sent might already be compacted. It happens when the snapshot takes long time
  1302. // to send and save. Pausing compaction avoids triggering a snapshot sending cycle.
  1303. if atomic.LoadInt64(&s.inflightSnapshots) != 0 {
  1304. plog.Infof("skip compaction since there is an inflight snapshot")
  1305. return
  1306. }
  1307. // keep some in memory log entries for slow followers.
  1308. compacti := uint64(1)
  1309. if snapi > numberOfCatchUpEntries {
  1310. compacti = snapi - numberOfCatchUpEntries
  1311. }
  1312. err = s.r.raftStorage.Compact(compacti)
  1313. if err != nil {
  1314. // the compaction was done asynchronously with the progress of raft.
  1315. // raft log might already been compact.
  1316. if err == raft.ErrCompacted {
  1317. return
  1318. }
  1319. plog.Panicf("unexpected compaction error %v", err)
  1320. }
  1321. plog.Infof("compacted raft log at %d", compacti)
  1322. })
  1323. }
  1324. // CutPeer drops messages to the specified peer.
  1325. func (s *EtcdServer) CutPeer(id types.ID) {
  1326. tr, ok := s.r.transport.(*rafthttp.Transport)
  1327. if ok {
  1328. tr.CutPeer(id)
  1329. }
  1330. }
  1331. // MendPeer recovers the message dropping behavior of the given peer.
  1332. func (s *EtcdServer) MendPeer(id types.ID) {
  1333. tr, ok := s.r.transport.(*rafthttp.Transport)
  1334. if ok {
  1335. tr.MendPeer(id)
  1336. }
  1337. }
  1338. func (s *EtcdServer) PauseSending() { s.r.pauseSending() }
  1339. func (s *EtcdServer) ResumeSending() { s.r.resumeSending() }
  1340. func (s *EtcdServer) ClusterVersion() *semver.Version {
  1341. if s.cluster == nil {
  1342. return nil
  1343. }
  1344. return s.cluster.Version()
  1345. }
  1346. // monitorVersions checks the member's version every monitorVersionInterval.
  1347. // It updates the cluster version if all members agrees on a higher one.
  1348. // It prints out log if there is a member with a higher version than the
  1349. // local version.
  1350. func (s *EtcdServer) monitorVersions() {
  1351. for {
  1352. select {
  1353. case <-s.forceVersionC:
  1354. case <-time.After(monitorVersionInterval):
  1355. case <-s.stopping:
  1356. return
  1357. }
  1358. if s.Leader() != s.ID() {
  1359. continue
  1360. }
  1361. v := decideClusterVersion(getVersions(s.cluster, s.id, s.peerRt))
  1362. if v != nil {
  1363. // only keep major.minor version for comparison
  1364. v = &semver.Version{
  1365. Major: v.Major,
  1366. Minor: v.Minor,
  1367. }
  1368. }
  1369. // if the current version is nil:
  1370. // 1. use the decided version if possible
  1371. // 2. or use the min cluster version
  1372. if s.cluster.Version() == nil {
  1373. verStr := version.MinClusterVersion
  1374. if v != nil {
  1375. verStr = v.String()
  1376. }
  1377. s.goAttach(func() { s.updateClusterVersion(verStr) })
  1378. continue
  1379. }
  1380. // update cluster version only if the decided version is greater than
  1381. // the current cluster version
  1382. if v != nil && s.cluster.Version().LessThan(*v) {
  1383. s.goAttach(func() { s.updateClusterVersion(v.String()) })
  1384. }
  1385. }
  1386. }
  1387. func (s *EtcdServer) updateClusterVersion(ver string) {
  1388. if s.cluster.Version() == nil {
  1389. plog.Infof("setting up the initial cluster version to %s", version.Cluster(ver))
  1390. } else {
  1391. plog.Infof("updating the cluster version from %s to %s", version.Cluster(s.cluster.Version().String()), version.Cluster(ver))
  1392. }
  1393. req := pb.Request{
  1394. Method: "PUT",
  1395. Path: membership.StoreClusterVersionKey(),
  1396. Val: ver,
  1397. }
  1398. ctx, cancel := context.WithTimeout(s.ctx, s.Cfg.ReqTimeout())
  1399. _, err := s.Do(ctx, req)
  1400. cancel()
  1401. switch err {
  1402. case nil:
  1403. return
  1404. case ErrStopped:
  1405. plog.Infof("aborting update cluster version because server is stopped")
  1406. return
  1407. default:
  1408. plog.Errorf("error updating cluster version (%v)", err)
  1409. }
  1410. }
  1411. func (s *EtcdServer) parseProposeCtxErr(err error, start time.Time) error {
  1412. switch err {
  1413. case context.Canceled:
  1414. return ErrCanceled
  1415. case context.DeadlineExceeded:
  1416. s.leadTimeMu.RLock()
  1417. curLeadElected := s.leadElectedTime
  1418. s.leadTimeMu.RUnlock()
  1419. prevLeadLost := curLeadElected.Add(-2 * time.Duration(s.Cfg.ElectionTicks) * time.Duration(s.Cfg.TickMs) * time.Millisecond)
  1420. if start.After(prevLeadLost) && start.Before(curLeadElected) {
  1421. return ErrTimeoutDueToLeaderFail
  1422. }
  1423. lead := types.ID(atomic.LoadUint64(&s.r.lead))
  1424. switch lead {
  1425. case types.ID(raft.None):
  1426. // TODO: return error to specify it happens because the cluster does not have leader now
  1427. case s.ID():
  1428. if !isConnectedToQuorumSince(s.r.transport, start, s.ID(), s.cluster.Members()) {
  1429. return ErrTimeoutDueToConnectionLost
  1430. }
  1431. default:
  1432. if !isConnectedSince(s.r.transport, start, lead) {
  1433. return ErrTimeoutDueToConnectionLost
  1434. }
  1435. }
  1436. return ErrTimeout
  1437. default:
  1438. return err
  1439. }
  1440. }
  1441. func (s *EtcdServer) KV() mvcc.ConsistentWatchableKV { return s.kv }
  1442. func (s *EtcdServer) Backend() backend.Backend {
  1443. s.bemu.Lock()
  1444. defer s.bemu.Unlock()
  1445. return s.be
  1446. }
  1447. func (s *EtcdServer) AuthStore() auth.AuthStore { return s.authStore }
  1448. func (s *EtcdServer) restoreAlarms() error {
  1449. s.applyV3 = s.newApplierV3()
  1450. as, err := alarm.NewAlarmStore(s)
  1451. if err != nil {
  1452. return err
  1453. }
  1454. s.alarmStore = as
  1455. if len(as.Get(pb.AlarmType_NOSPACE)) > 0 {
  1456. s.applyV3 = newApplierV3Capped(s.applyV3)
  1457. }
  1458. if len(as.Get(pb.AlarmType_CORRUPT)) > 0 {
  1459. s.applyV3 = newApplierV3Corrupt(s.applyV3)
  1460. }
  1461. return nil
  1462. }
  1463. func (s *EtcdServer) getAppliedIndex() uint64 {
  1464. return atomic.LoadUint64(&s.appliedIndex)
  1465. }
  1466. func (s *EtcdServer) setAppliedIndex(v uint64) {
  1467. atomic.StoreUint64(&s.appliedIndex, v)
  1468. atomic.StoreUint64(&s.r.appliedindex, v)
  1469. }
  1470. func (s *EtcdServer) getCommittedIndex() uint64 {
  1471. return atomic.LoadUint64(&s.committedIndex)
  1472. }
  1473. func (s *EtcdServer) setCommittedIndex(v uint64) {
  1474. atomic.StoreUint64(&s.committedIndex, v)
  1475. }
  1476. // goAttach creates a goroutine on a given function and tracks it using
  1477. // the etcdserver waitgroup.
  1478. func (s *EtcdServer) goAttach(f func()) {
  1479. s.wgMu.RLock() // this blocks with ongoing close(s.stopping)
  1480. defer s.wgMu.RUnlock()
  1481. select {
  1482. case <-s.stopping:
  1483. plog.Warning("server has stopped (skipping goAttach)")
  1484. return
  1485. default:
  1486. }
  1487. // now safe to add since waitgroup wait has not started yet
  1488. s.wg.Add(1)
  1489. go func() {
  1490. defer s.wg.Done()
  1491. f()
  1492. }()
  1493. }
  1494. func (s *EtcdServer) Alarms() []*pb.AlarmMember {
  1495. return s.alarmStore.Get(pb.AlarmType_NONE)
  1496. }