server.go 49 KB

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