server.go 50 KB

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