server.go 68 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419
  1. // Copyright 2015 The etcd Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package etcdserver
  15. import (
  16. "context"
  17. "encoding/json"
  18. "expvar"
  19. "fmt"
  20. "math"
  21. "math/rand"
  22. "net/http"
  23. "os"
  24. "path"
  25. "regexp"
  26. "sync"
  27. "sync/atomic"
  28. "time"
  29. "github.com/coreos/etcd/auth"
  30. "github.com/coreos/etcd/etcdserver/api"
  31. "github.com/coreos/etcd/etcdserver/api/membership"
  32. "github.com/coreos/etcd/etcdserver/api/rafthttp"
  33. "github.com/coreos/etcd/etcdserver/api/snap"
  34. "github.com/coreos/etcd/etcdserver/api/v2discovery"
  35. "github.com/coreos/etcd/etcdserver/api/v2http/httptypes"
  36. stats "github.com/coreos/etcd/etcdserver/api/v2stats"
  37. "github.com/coreos/etcd/etcdserver/api/v2store"
  38. "github.com/coreos/etcd/etcdserver/api/v3alarm"
  39. "github.com/coreos/etcd/etcdserver/api/v3compactor"
  40. pb "github.com/coreos/etcd/etcdserver/etcdserverpb"
  41. "github.com/coreos/etcd/lease"
  42. "github.com/coreos/etcd/lease/leasehttp"
  43. "github.com/coreos/etcd/mvcc"
  44. "github.com/coreos/etcd/mvcc/backend"
  45. "github.com/coreos/etcd/pkg/fileutil"
  46. "github.com/coreos/etcd/pkg/idutil"
  47. "github.com/coreos/etcd/pkg/pbutil"
  48. "github.com/coreos/etcd/pkg/runtime"
  49. "github.com/coreos/etcd/pkg/schedule"
  50. "github.com/coreos/etcd/pkg/types"
  51. "github.com/coreos/etcd/pkg/wait"
  52. "github.com/coreos/etcd/raft"
  53. "github.com/coreos/etcd/raft/raftpb"
  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. humanize "github.com/dustin/go-humanize"
  59. "github.com/prometheus/client_golang/prometheus"
  60. "go.uber.org/zap"
  61. )
  62. const (
  63. DefaultSnapshotCount = 100000
  64. // DefaultSnapshotCatchUpEntries is the number of entries for a slow follower
  65. // to catch-up after compacting the raft storage entries.
  66. // We expect the follower has a millisecond level latency with the leader.
  67. // The max throughput is around 10K. Keep a 5K entries is enough for helping
  68. // follower to catch up.
  69. DefaultSnapshotCatchUpEntries uint64 = 5000
  70. StoreClusterPrefix = "/0"
  71. StoreKeysPrefix = "/1"
  72. // HealthInterval is the minimum time the cluster should be healthy
  73. // before accepting add member requests.
  74. HealthInterval = 5 * time.Second
  75. purgeFileInterval = 30 * time.Second
  76. // monitorVersionInterval should be smaller than the timeout
  77. // on the connection. Or we will not be able to reuse the connection
  78. // (since it will timeout).
  79. monitorVersionInterval = rafthttp.ConnWriteTimeout - time.Second
  80. // max number of in-flight snapshot messages etcdserver allows to have
  81. // This number is more than enough for most clusters with 5 machines.
  82. maxInFlightMsgSnap = 16
  83. releaseDelayAfterSnapshot = 30 * time.Second
  84. // maxPendingRevokes is the maximum number of outstanding expired lease revocations.
  85. maxPendingRevokes = 16
  86. recommendedMaxRequestBytes = 10 * 1024 * 1024
  87. )
  88. var (
  89. plog = capnslog.NewPackageLogger("github.com/coreos/etcd", "etcdserver")
  90. storeMemberAttributeRegexp = regexp.MustCompile(path.Join(membership.StoreMembersPrefix, "[[:xdigit:]]{1,16}", "attributes"))
  91. )
  92. func init() {
  93. rand.Seed(time.Now().UnixNano())
  94. expvar.Publish(
  95. "file_descriptor_limit",
  96. expvar.Func(
  97. func() interface{} {
  98. n, _ := runtime.FDLimit()
  99. return n
  100. },
  101. ),
  102. )
  103. }
  104. type Response struct {
  105. Term uint64
  106. Index uint64
  107. Event *v2store.Event
  108. Watcher v2store.Watcher
  109. Err error
  110. }
  111. type ServerV2 interface {
  112. Server
  113. Leader() types.ID
  114. // Do takes a V2 request and attempts to fulfill it, returning a Response.
  115. Do(ctx context.Context, r pb.Request) (Response, error)
  116. stats.Stats
  117. ClientCertAuthEnabled() bool
  118. }
  119. type ServerV3 interface {
  120. Server
  121. RaftStatusGetter
  122. }
  123. func (s *EtcdServer) ClientCertAuthEnabled() bool { return s.Cfg.ClientCertAuthEnabled }
  124. type Server interface {
  125. // AddMember attempts to add a member into the cluster. It will return
  126. // ErrIDRemoved if member ID is removed from the cluster, or return
  127. // ErrIDExists if member ID exists in the cluster.
  128. AddMember(ctx context.Context, memb membership.Member) ([]*membership.Member, error)
  129. // RemoveMember attempts to remove a member from the cluster. It will
  130. // return ErrIDRemoved if member ID is removed from the cluster, or return
  131. // ErrIDNotFound if member ID is not in the cluster.
  132. RemoveMember(ctx context.Context, id uint64) ([]*membership.Member, error)
  133. // UpdateMember attempts to update an existing member in the cluster. It will
  134. // return ErrIDNotFound if the member ID does not exist.
  135. UpdateMember(ctx context.Context, updateMemb membership.Member) ([]*membership.Member, error)
  136. // ClusterVersion is the cluster-wide minimum major.minor version.
  137. // Cluster version is set to the min version that an etcd member is
  138. // compatible with when first bootstrap.
  139. //
  140. // ClusterVersion is nil until the cluster is bootstrapped (has a quorum).
  141. //
  142. // During a rolling upgrades, the ClusterVersion will be updated
  143. // automatically after a sync. (5 second by default)
  144. //
  145. // The API/raft component can utilize ClusterVersion to determine if
  146. // it can accept a client request or a raft RPC.
  147. // NOTE: ClusterVersion might be nil when etcd 2.1 works with etcd 2.0 and
  148. // the leader is etcd 2.0. etcd 2.0 leader will not update clusterVersion since
  149. // this feature is introduced post 2.0.
  150. ClusterVersion() *semver.Version
  151. Cluster() api.Cluster
  152. Alarms() []*pb.AlarmMember
  153. }
  154. // EtcdServer is the production implementation of the Server interface
  155. type EtcdServer struct {
  156. // inflightSnapshots holds count the number of snapshots currently inflight.
  157. inflightSnapshots int64 // must use atomic operations to access; keep 64-bit aligned.
  158. appliedIndex uint64 // must use atomic operations to access; keep 64-bit aligned.
  159. committedIndex uint64 // must use atomic operations to access; keep 64-bit aligned.
  160. term uint64 // must use atomic operations to access; keep 64-bit aligned.
  161. lead uint64 // must use atomic operations to access; keep 64-bit aligned.
  162. // consistIndex used to hold the offset of current executing entry
  163. // It is initialized to 0 before executing any entry.
  164. consistIndex consistentIndex // must use atomic operations to access; keep 64-bit aligned.
  165. r raftNode // uses 64-bit atomics; keep 64-bit aligned.
  166. readych chan struct{}
  167. Cfg ServerConfig
  168. lgMu *sync.RWMutex
  169. lg *zap.Logger
  170. w wait.Wait
  171. readMu sync.RWMutex
  172. // read routine notifies etcd server that it waits for reading by sending an empty struct to
  173. // readwaitC
  174. readwaitc chan struct{}
  175. // readNotifier is used to notify the read routine that it can process the request
  176. // when there is no error
  177. readNotifier *notifier
  178. // stop signals the run goroutine should shutdown.
  179. stop chan struct{}
  180. // stopping is closed by run goroutine on shutdown.
  181. stopping chan struct{}
  182. // done is closed when all goroutines from start() complete.
  183. done chan struct{}
  184. errorc chan error
  185. id types.ID
  186. attributes membership.Attributes
  187. cluster *membership.RaftCluster
  188. v2store v2store.Store
  189. snapshotter *snap.Snapshotter
  190. applyV2 ApplierV2
  191. // applyV3 is the applier with auth and quotas
  192. applyV3 applierV3
  193. // applyV3Base is the core applier without auth or quotas
  194. applyV3Base applierV3
  195. applyWait wait.WaitTime
  196. kv mvcc.ConsistentWatchableKV
  197. lessor lease.Lessor
  198. bemu sync.Mutex
  199. be backend.Backend
  200. authStore auth.AuthStore
  201. alarmStore *v3alarm.AlarmStore
  202. stats *stats.ServerStats
  203. lstats *stats.LeaderStats
  204. SyncTicker *time.Ticker
  205. // compactor is used to auto-compact the KV.
  206. compactor v3compactor.Compactor
  207. // peerRt used to send requests (version, lease) to peers.
  208. peerRt http.RoundTripper
  209. reqIDGen *idutil.Generator
  210. // forceVersionC is used to force the version monitor loop
  211. // to detect the cluster version immediately.
  212. forceVersionC chan struct{}
  213. // wgMu blocks concurrent waitgroup mutation while server stopping
  214. wgMu sync.RWMutex
  215. // wg is used to wait for the go routines that depends on the server state
  216. // to exit when stopping the server.
  217. wg sync.WaitGroup
  218. // ctx is used for etcd-initiated requests that may need to be canceled
  219. // on etcd server shutdown.
  220. ctx context.Context
  221. cancel context.CancelFunc
  222. leadTimeMu sync.RWMutex
  223. leadElectedTime time.Time
  224. *AccessController
  225. }
  226. // NewServer creates a new EtcdServer from the supplied configuration. The
  227. // configuration is considered static for the lifetime of the EtcdServer.
  228. func NewServer(cfg ServerConfig) (srv *EtcdServer, err error) {
  229. st := v2store.New(StoreClusterPrefix, StoreKeysPrefix)
  230. var (
  231. w *wal.WAL
  232. n raft.Node
  233. s *raft.MemoryStorage
  234. id types.ID
  235. cl *membership.RaftCluster
  236. )
  237. if cfg.MaxRequestBytes > recommendedMaxRequestBytes {
  238. if cfg.Logger != nil {
  239. cfg.Logger.Warn(
  240. "exceeded recommended requet limit",
  241. zap.Uint("max-request-bytes", cfg.MaxRequestBytes),
  242. zap.String("max-request-size", humanize.Bytes(uint64(cfg.MaxRequestBytes))),
  243. zap.Int("recommended-request-bytes", recommendedMaxRequestBytes),
  244. zap.String("recommended-request-size", humanize.Bytes(uint64(recommendedMaxRequestBytes))),
  245. )
  246. } else {
  247. plog.Warningf("MaxRequestBytes %v exceeds maximum recommended size %v", cfg.MaxRequestBytes, recommendedMaxRequestBytes)
  248. }
  249. }
  250. if terr := fileutil.TouchDirAll(cfg.DataDir); terr != nil {
  251. return nil, fmt.Errorf("cannot access data directory: %v", terr)
  252. }
  253. haveWAL := wal.Exist(cfg.WALDir())
  254. if err = fileutil.TouchDirAll(cfg.SnapDir()); err != nil {
  255. if cfg.Logger != nil {
  256. cfg.Logger.Fatal(
  257. "failed to create snapshot directory",
  258. zap.String("path", cfg.SnapDir()),
  259. zap.Error(err),
  260. )
  261. } else {
  262. plog.Fatalf("create snapshot directory error: %v", err)
  263. }
  264. }
  265. ss := snap.New(cfg.Logger, cfg.SnapDir())
  266. bepath := cfg.backendPath()
  267. beExist := fileutil.Exist(bepath)
  268. be := openBackend(cfg)
  269. defer func() {
  270. if err != nil {
  271. be.Close()
  272. }
  273. }()
  274. prt, err := rafthttp.NewRoundTripper(cfg.PeerTLSInfo, cfg.peerDialTimeout())
  275. if err != nil {
  276. return nil, err
  277. }
  278. var (
  279. remotes []*membership.Member
  280. snapshot *raftpb.Snapshot
  281. )
  282. switch {
  283. case !haveWAL && !cfg.NewCluster:
  284. if err = cfg.VerifyJoinExisting(); err != nil {
  285. return nil, err
  286. }
  287. cl, err = membership.NewClusterFromURLsMap(cfg.Logger, cfg.InitialClusterToken, cfg.InitialPeerURLsMap)
  288. if err != nil {
  289. return nil, err
  290. }
  291. existingCluster, gerr := GetClusterFromRemotePeers(cfg.Logger, getRemotePeerURLs(cl, cfg.Name), prt)
  292. if gerr != nil {
  293. return nil, fmt.Errorf("cannot fetch cluster info from peer urls: %v", gerr)
  294. }
  295. if err = membership.ValidateClusterAndAssignIDs(cfg.Logger, cl, existingCluster); err != nil {
  296. return nil, fmt.Errorf("error validating peerURLs %s: %v", existingCluster, err)
  297. }
  298. if !isCompatibleWithCluster(cfg.Logger, cl, cl.MemberByName(cfg.Name).ID, prt) {
  299. return nil, fmt.Errorf("incompatible with current running cluster")
  300. }
  301. remotes = existingCluster.Members()
  302. cl.SetID(types.ID(0), existingCluster.ID())
  303. cl.SetStore(st)
  304. cl.SetBackend(be)
  305. id, n, s, w = startNode(cfg, cl, nil)
  306. cl.SetID(id, existingCluster.ID())
  307. case !haveWAL && cfg.NewCluster:
  308. if err = cfg.VerifyBootstrap(); err != nil {
  309. return nil, err
  310. }
  311. cl, err = membership.NewClusterFromURLsMap(cfg.Logger, cfg.InitialClusterToken, cfg.InitialPeerURLsMap)
  312. if err != nil {
  313. return nil, err
  314. }
  315. m := cl.MemberByName(cfg.Name)
  316. if isMemberBootstrapped(cfg.Logger, cl, cfg.Name, prt, cfg.bootstrapTimeout()) {
  317. return nil, fmt.Errorf("member %s has already been bootstrapped", m.ID)
  318. }
  319. if cfg.ShouldDiscover() {
  320. var str string
  321. str, err = v2discovery.JoinCluster(cfg.Logger, cfg.DiscoveryURL, cfg.DiscoveryProxy, m.ID, cfg.InitialPeerURLsMap.String())
  322. if err != nil {
  323. return nil, &DiscoveryError{Op: "join", Err: err}
  324. }
  325. var urlsmap types.URLsMap
  326. urlsmap, err = types.NewURLsMap(str)
  327. if err != nil {
  328. return nil, err
  329. }
  330. if checkDuplicateURL(urlsmap) {
  331. return nil, fmt.Errorf("discovery cluster %s has duplicate url", urlsmap)
  332. }
  333. if cl, err = membership.NewClusterFromURLsMap(cfg.Logger, cfg.InitialClusterToken, urlsmap); err != nil {
  334. return nil, err
  335. }
  336. }
  337. cl.SetStore(st)
  338. cl.SetBackend(be)
  339. id, n, s, w = startNode(cfg, cl, cl.MemberIDs())
  340. cl.SetID(id, cl.ID())
  341. case haveWAL:
  342. if err = fileutil.IsDirWriteable(cfg.MemberDir()); err != nil {
  343. return nil, fmt.Errorf("cannot write to member directory: %v", err)
  344. }
  345. if err = fileutil.IsDirWriteable(cfg.WALDir()); err != nil {
  346. return nil, fmt.Errorf("cannot write to WAL directory: %v", err)
  347. }
  348. if cfg.ShouldDiscover() {
  349. if cfg.Logger != nil {
  350. cfg.Logger.Warn(
  351. "discovery token is ignored since cluster already initialized; valid logs are found",
  352. zap.String("wal-dir", cfg.WALDir()),
  353. )
  354. } else {
  355. plog.Warningf("discovery token ignored since a cluster has already been initialized. Valid log found at %q", cfg.WALDir())
  356. }
  357. }
  358. snapshot, err = ss.Load()
  359. if err != nil && err != snap.ErrNoSnapshot {
  360. return nil, err
  361. }
  362. if snapshot != nil {
  363. if err = st.Recovery(snapshot.Data); err != nil {
  364. if cfg.Logger != nil {
  365. cfg.Logger.Panic("failed to recover from snapshot")
  366. } else {
  367. plog.Panicf("recovered store from snapshot error: %v", err)
  368. }
  369. }
  370. if cfg.Logger != nil {
  371. cfg.Logger.Info(
  372. "recovered v2 store from snapshot",
  373. zap.Uint64("snapshot-index", snapshot.Metadata.Index),
  374. zap.String("snapshot-size", humanize.Bytes(uint64(snapshot.Size()))),
  375. )
  376. } else {
  377. plog.Infof("recovered store from snapshot at index %d", snapshot.Metadata.Index)
  378. }
  379. if be, err = recoverSnapshotBackend(cfg, be, *snapshot); err != nil {
  380. if cfg.Logger != nil {
  381. cfg.Logger.Panic("failed to recover v3 backend from snapshot", zap.Error(err))
  382. } else {
  383. plog.Panicf("recovering backend from snapshot error: %v", err)
  384. }
  385. }
  386. if cfg.Logger != nil {
  387. s1, s2 := be.Size(), be.SizeInUse()
  388. cfg.Logger.Info(
  389. "recovered v3 backend from snapshot",
  390. zap.Int64("backend-size-bytes", s1),
  391. zap.String("backend-size", humanize.Bytes(uint64(s1))),
  392. zap.Int64("backend-size-in-use-bytes", s2),
  393. zap.String("backend-size-in-use", humanize.Bytes(uint64(s2))),
  394. )
  395. }
  396. }
  397. if !cfg.ForceNewCluster {
  398. id, cl, n, s, w = restartNode(cfg, snapshot)
  399. } else {
  400. id, cl, n, s, w = restartAsStandaloneNode(cfg, snapshot)
  401. }
  402. cl.SetStore(st)
  403. cl.SetBackend(be)
  404. cl.Recover(api.UpdateCapability)
  405. if cl.Version() != nil && !cl.Version().LessThan(semver.Version{Major: 3}) && !beExist {
  406. os.RemoveAll(bepath)
  407. return nil, fmt.Errorf("database file (%v) of the backend is missing", bepath)
  408. }
  409. default:
  410. return nil, fmt.Errorf("unsupported bootstrap config")
  411. }
  412. if terr := fileutil.TouchDirAll(cfg.MemberDir()); terr != nil {
  413. return nil, fmt.Errorf("cannot access member directory: %v", terr)
  414. }
  415. sstats := stats.NewServerStats(cfg.Name, id.String())
  416. lstats := stats.NewLeaderStats(id.String())
  417. heartbeat := time.Duration(cfg.TickMs) * time.Millisecond
  418. srv = &EtcdServer{
  419. readych: make(chan struct{}),
  420. Cfg: cfg,
  421. lgMu: new(sync.RWMutex),
  422. lg: cfg.Logger,
  423. errorc: make(chan error, 1),
  424. v2store: st,
  425. snapshotter: ss,
  426. r: *newRaftNode(
  427. raftNodeConfig{
  428. lg: cfg.Logger,
  429. isIDRemoved: func(id uint64) bool { return cl.IsIDRemoved(types.ID(id)) },
  430. Node: n,
  431. heartbeat: heartbeat,
  432. raftStorage: s,
  433. storage: NewStorage(w, ss),
  434. },
  435. ),
  436. id: id,
  437. attributes: membership.Attributes{Name: cfg.Name, ClientURLs: cfg.ClientURLs.StringSlice()},
  438. cluster: cl,
  439. stats: sstats,
  440. lstats: lstats,
  441. SyncTicker: time.NewTicker(500 * time.Millisecond),
  442. peerRt: prt,
  443. reqIDGen: idutil.NewGenerator(uint16(id), time.Now()),
  444. forceVersionC: make(chan struct{}),
  445. AccessController: &AccessController{CORS: cfg.CORS, HostWhitelist: cfg.HostWhitelist},
  446. }
  447. serverID.With(prometheus.Labels{"server_id": id.String()}).Set(1)
  448. srv.applyV2 = &applierV2store{store: srv.v2store, cluster: srv.cluster}
  449. srv.be = be
  450. minTTL := time.Duration((3*cfg.ElectionTicks)/2) * heartbeat
  451. // always recover lessor before kv. When we recover the mvcc.KV it will reattach keys to its leases.
  452. // If we recover mvcc.KV first, it will attach the keys to the wrong lessor before it recovers.
  453. srv.lessor = lease.NewLessor(srv.getLogger(), srv.be, lease.LessorConfig{MinLeaseTTL: int64(math.Ceil(minTTL.Seconds())), CheckpointInterval: cfg.LeaseCheckpointInterval})
  454. srv.kv = mvcc.New(srv.getLogger(), srv.be, srv.lessor, &srv.consistIndex)
  455. if beExist {
  456. kvindex := srv.kv.ConsistentIndex()
  457. // TODO: remove kvindex != 0 checking when we do not expect users to upgrade
  458. // etcd from pre-3.0 release.
  459. if snapshot != nil && kvindex < snapshot.Metadata.Index {
  460. if kvindex != 0 {
  461. return nil, fmt.Errorf("database file (%v index %d) does not match with snapshot (index %d)", bepath, kvindex, snapshot.Metadata.Index)
  462. }
  463. if cfg.Logger != nil {
  464. cfg.Logger.Warn(
  465. "consistent index was never saved",
  466. zap.Uint64("snapshot-index", snapshot.Metadata.Index),
  467. )
  468. } else {
  469. plog.Warningf("consistent index never saved (snapshot index=%d)", snapshot.Metadata.Index)
  470. }
  471. }
  472. }
  473. newSrv := srv // since srv == nil in defer if srv is returned as nil
  474. defer func() {
  475. // closing backend without first closing kv can cause
  476. // resumed compactions to fail with closed tx errors
  477. if err != nil {
  478. newSrv.kv.Close()
  479. }
  480. }()
  481. srv.consistIndex.setConsistentIndex(srv.kv.ConsistentIndex())
  482. tp, err := auth.NewTokenProvider(cfg.Logger, cfg.AuthToken,
  483. func(index uint64) <-chan struct{} {
  484. return srv.applyWait.Wait(index)
  485. },
  486. )
  487. if err != nil {
  488. if cfg.Logger != nil {
  489. cfg.Logger.Warn("failed to create token provider", zap.Error(err))
  490. } else {
  491. plog.Errorf("failed to create token provider: %s", err)
  492. }
  493. return nil, err
  494. }
  495. srv.authStore = auth.NewAuthStore(srv.getLogger(), srv.be, tp, int(cfg.BcryptCost))
  496. if num := cfg.AutoCompactionRetention; num != 0 {
  497. srv.compactor, err = v3compactor.New(cfg.Logger, cfg.AutoCompactionMode, num, srv.kv, srv)
  498. if err != nil {
  499. return nil, err
  500. }
  501. srv.compactor.Run()
  502. }
  503. srv.applyV3Base = srv.newApplierV3Backend()
  504. if err = srv.restoreAlarms(); err != nil {
  505. return nil, err
  506. }
  507. srv.lessor.SetCheckpointer(func(ctx context.Context, cp *pb.LeaseCheckpointRequest) {
  508. srv.raftRequestOnce(ctx, pb.InternalRaftRequest{LeaseCheckpoint: cp})
  509. })
  510. // TODO: move transport initialization near the definition of remote
  511. tr := &rafthttp.Transport{
  512. Logger: cfg.Logger,
  513. TLSInfo: cfg.PeerTLSInfo,
  514. DialTimeout: cfg.peerDialTimeout(),
  515. ID: id,
  516. URLs: cfg.PeerURLs,
  517. ClusterID: cl.ID(),
  518. Raft: srv,
  519. Snapshotter: ss,
  520. ServerStats: sstats,
  521. LeaderStats: lstats,
  522. ErrorC: srv.errorc,
  523. }
  524. if err = tr.Start(); err != nil {
  525. return nil, err
  526. }
  527. // add all remotes into transport
  528. for _, m := range remotes {
  529. if m.ID != id {
  530. tr.AddRemote(m.ID, m.PeerURLs)
  531. }
  532. }
  533. for _, m := range cl.Members() {
  534. if m.ID != id {
  535. tr.AddPeer(m.ID, m.PeerURLs)
  536. }
  537. }
  538. srv.r.transport = tr
  539. return srv, nil
  540. }
  541. func (s *EtcdServer) getLogger() *zap.Logger {
  542. s.lgMu.RLock()
  543. l := s.lg
  544. s.lgMu.RUnlock()
  545. return l
  546. }
  547. func tickToDur(ticks int, tickMs uint) string {
  548. return fmt.Sprintf("%v", time.Duration(ticks)*time.Duration(tickMs)*time.Millisecond)
  549. }
  550. func (s *EtcdServer) adjustTicks() {
  551. lg := s.getLogger()
  552. clusterN := len(s.cluster.Members())
  553. // single-node fresh start, or single-node recovers from snapshot
  554. if clusterN == 1 {
  555. ticks := s.Cfg.ElectionTicks - 1
  556. if lg != nil {
  557. lg.Info(
  558. "started as single-node; fast-forwarding election ticks",
  559. zap.String("local-member-id", s.ID().String()),
  560. zap.Int("forward-ticks", ticks),
  561. zap.String("forward-duration", tickToDur(ticks, s.Cfg.TickMs)),
  562. zap.Int("election-ticks", s.Cfg.ElectionTicks),
  563. zap.String("election-timeout", tickToDur(s.Cfg.ElectionTicks, s.Cfg.TickMs)),
  564. )
  565. } else {
  566. plog.Infof("%s as single-node; fast-forwarding %d ticks (election ticks %d)", s.ID(), ticks, s.Cfg.ElectionTicks)
  567. }
  568. s.r.advanceTicks(ticks)
  569. return
  570. }
  571. if !s.Cfg.InitialElectionTickAdvance {
  572. if lg != nil {
  573. lg.Info("skipping initial election tick advance", zap.Int("election-ticks", s.Cfg.ElectionTicks))
  574. }
  575. return
  576. }
  577. if lg != nil {
  578. lg.Info("starting initial election tick advance", zap.Int("election-ticks", s.Cfg.ElectionTicks))
  579. }
  580. // retry up to "rafthttp.ConnReadTimeout", which is 5-sec
  581. // until peer connection reports; otherwise:
  582. // 1. all connections failed, or
  583. // 2. no active peers, or
  584. // 3. restarted single-node with no snapshot
  585. // then, do nothing, because advancing ticks would have no effect
  586. waitTime := rafthttp.ConnReadTimeout
  587. itv := 50 * time.Millisecond
  588. for i := int64(0); i < int64(waitTime/itv); i++ {
  589. select {
  590. case <-time.After(itv):
  591. case <-s.stopping:
  592. return
  593. }
  594. peerN := s.r.transport.ActivePeers()
  595. if peerN > 1 {
  596. // multi-node received peer connection reports
  597. // adjust ticks, in case slow leader message receive
  598. ticks := s.Cfg.ElectionTicks - 2
  599. if lg != nil {
  600. lg.Info(
  601. "initialized peer connections; fast-forwarding election ticks",
  602. zap.String("local-member-id", s.ID().String()),
  603. zap.Int("forward-ticks", ticks),
  604. zap.String("forward-duration", tickToDur(ticks, s.Cfg.TickMs)),
  605. zap.Int("election-ticks", s.Cfg.ElectionTicks),
  606. zap.String("election-timeout", tickToDur(s.Cfg.ElectionTicks, s.Cfg.TickMs)),
  607. zap.Int("active-remote-members", peerN),
  608. )
  609. } else {
  610. plog.Infof("%s initialized peer connection; fast-forwarding %d ticks (election ticks %d) with %d active peer(s)", s.ID(), ticks, s.Cfg.ElectionTicks, peerN)
  611. }
  612. s.r.advanceTicks(ticks)
  613. return
  614. }
  615. }
  616. }
  617. // Start performs any initialization of the Server necessary for it to
  618. // begin serving requests. It must be called before Do or Process.
  619. // Start must be non-blocking; any long-running server functionality
  620. // should be implemented in goroutines.
  621. func (s *EtcdServer) Start() {
  622. s.start()
  623. s.goAttach(func() { s.adjustTicks() })
  624. s.goAttach(func() { s.publish(s.Cfg.ReqTimeout()) })
  625. s.goAttach(s.purgeFile)
  626. s.goAttach(func() { monitorFileDescriptor(s.getLogger(), s.stopping) })
  627. s.goAttach(s.monitorVersions)
  628. s.goAttach(s.linearizableReadLoop)
  629. s.goAttach(s.monitorKVHash)
  630. }
  631. // start prepares and starts server in a new goroutine. It is no longer safe to
  632. // modify a server's fields after it has been sent to Start.
  633. // This function is just used for testing.
  634. func (s *EtcdServer) start() {
  635. lg := s.getLogger()
  636. if s.Cfg.SnapshotCount == 0 {
  637. if lg != nil {
  638. lg.Info(
  639. "updating snapshot-count to default",
  640. zap.Uint64("given-snapshot-count", s.Cfg.SnapshotCount),
  641. zap.Uint64("updated-snapshot-count", DefaultSnapshotCount),
  642. )
  643. } else {
  644. plog.Infof("set snapshot count to default %d", DefaultSnapshotCount)
  645. }
  646. s.Cfg.SnapshotCount = DefaultSnapshotCount
  647. }
  648. if s.Cfg.SnapshotCatchUpEntries == 0 {
  649. if lg != nil {
  650. lg.Info(
  651. "updating snapshot catch-up entries to default",
  652. zap.Uint64("given-snapshot-catchup-entries", s.Cfg.SnapshotCatchUpEntries),
  653. zap.Uint64("updated-snapshot-catchup-entries", DefaultSnapshotCatchUpEntries),
  654. )
  655. }
  656. s.Cfg.SnapshotCatchUpEntries = DefaultSnapshotCatchUpEntries
  657. }
  658. s.w = wait.New()
  659. s.applyWait = wait.NewTimeList()
  660. s.done = make(chan struct{})
  661. s.stop = make(chan struct{})
  662. s.stopping = make(chan struct{})
  663. s.ctx, s.cancel = context.WithCancel(context.Background())
  664. s.readwaitc = make(chan struct{}, 1)
  665. s.readNotifier = newNotifier()
  666. if s.ClusterVersion() != nil {
  667. if lg != nil {
  668. lg.Info(
  669. "starting etcd server",
  670. zap.String("local-member-id", s.ID().String()),
  671. zap.String("local-server-version", version.Version),
  672. zap.String("cluster-id", s.Cluster().ID().String()),
  673. zap.String("cluster-version", version.Cluster(s.ClusterVersion().String())),
  674. )
  675. } else {
  676. plog.Infof("starting server... [version: %v, cluster version: %v]", version.Version, version.Cluster(s.ClusterVersion().String()))
  677. }
  678. } else {
  679. if lg != nil {
  680. lg.Info(
  681. "starting etcd server",
  682. zap.String("local-member-id", s.ID().String()),
  683. zap.String("local-server-version", version.Version),
  684. zap.String("cluster-version", "to_be_decided"),
  685. )
  686. } else {
  687. plog.Infof("starting server... [version: %v, cluster version: to_be_decided]", version.Version)
  688. }
  689. }
  690. // TODO: if this is an empty log, writes all peer infos
  691. // into the first entry
  692. go s.run()
  693. }
  694. func (s *EtcdServer) purgeFile() {
  695. var dberrc, serrc, werrc <-chan error
  696. if s.Cfg.MaxSnapFiles > 0 {
  697. dberrc = fileutil.PurgeFile(s.getLogger(), s.Cfg.SnapDir(), "snap.db", s.Cfg.MaxSnapFiles, purgeFileInterval, s.done)
  698. serrc = fileutil.PurgeFile(s.getLogger(), s.Cfg.SnapDir(), "snap", s.Cfg.MaxSnapFiles, purgeFileInterval, s.done)
  699. }
  700. if s.Cfg.MaxWALFiles > 0 {
  701. werrc = fileutil.PurgeFile(s.getLogger(), s.Cfg.WALDir(), "wal", s.Cfg.MaxWALFiles, purgeFileInterval, s.done)
  702. }
  703. lg := s.getLogger()
  704. select {
  705. case e := <-dberrc:
  706. if lg != nil {
  707. lg.Fatal("failed to purge snap db file", zap.Error(e))
  708. } else {
  709. plog.Fatalf("failed to purge snap db file %v", e)
  710. }
  711. case e := <-serrc:
  712. if lg != nil {
  713. lg.Fatal("failed to purge snap file", zap.Error(e))
  714. } else {
  715. plog.Fatalf("failed to purge snap file %v", e)
  716. }
  717. case e := <-werrc:
  718. if lg != nil {
  719. lg.Fatal("failed to purge wal file", zap.Error(e))
  720. } else {
  721. plog.Fatalf("failed to purge wal file %v", e)
  722. }
  723. case <-s.stopping:
  724. return
  725. }
  726. }
  727. func (s *EtcdServer) Cluster() api.Cluster { return s.cluster }
  728. func (s *EtcdServer) ApplyWait() <-chan struct{} { return s.applyWait.Wait(s.getCommittedIndex()) }
  729. type ServerPeer interface {
  730. ServerV2
  731. RaftHandler() http.Handler
  732. LeaseHandler() http.Handler
  733. }
  734. func (s *EtcdServer) LeaseHandler() http.Handler {
  735. if s.lessor == nil {
  736. return nil
  737. }
  738. return leasehttp.NewHandler(s.lessor, s.ApplyWait)
  739. }
  740. func (s *EtcdServer) RaftHandler() http.Handler { return s.r.transport.Handler() }
  741. // Process takes a raft message and applies it to the server's raft state
  742. // machine, respecting any timeout of the given context.
  743. func (s *EtcdServer) Process(ctx context.Context, m raftpb.Message) error {
  744. if s.cluster.IsIDRemoved(types.ID(m.From)) {
  745. if lg := s.getLogger(); lg != nil {
  746. lg.Warn(
  747. "rejected Raft message from removed member",
  748. zap.String("local-member-id", s.ID().String()),
  749. zap.String("removed-member-id", types.ID(m.From).String()),
  750. )
  751. } else {
  752. plog.Warningf("reject message from removed member %s", types.ID(m.From).String())
  753. }
  754. return httptypes.NewHTTPError(http.StatusForbidden, "cannot process message from removed member")
  755. }
  756. if m.Type == raftpb.MsgApp {
  757. s.stats.RecvAppendReq(types.ID(m.From).String(), m.Size())
  758. }
  759. return s.r.Step(ctx, m)
  760. }
  761. func (s *EtcdServer) IsIDRemoved(id uint64) bool { return s.cluster.IsIDRemoved(types.ID(id)) }
  762. func (s *EtcdServer) ReportUnreachable(id uint64) { s.r.ReportUnreachable(id) }
  763. // ReportSnapshot reports snapshot sent status to the raft state machine,
  764. // and clears the used snapshot from the snapshot store.
  765. func (s *EtcdServer) ReportSnapshot(id uint64, status raft.SnapshotStatus) {
  766. s.r.ReportSnapshot(id, status)
  767. }
  768. type etcdProgress struct {
  769. confState raftpb.ConfState
  770. snapi uint64
  771. appliedt uint64
  772. appliedi uint64
  773. }
  774. // raftReadyHandler contains a set of EtcdServer operations to be called by raftNode,
  775. // and helps decouple state machine logic from Raft algorithms.
  776. // TODO: add a state machine interface to apply the commit entries and do snapshot/recover
  777. type raftReadyHandler struct {
  778. getLead func() (lead uint64)
  779. updateLead func(lead uint64)
  780. updateLeadership func(newLeader bool)
  781. updateCommittedIndex func(uint64)
  782. }
  783. func (s *EtcdServer) run() {
  784. lg := s.getLogger()
  785. sn, err := s.r.raftStorage.Snapshot()
  786. if err != nil {
  787. if lg != nil {
  788. lg.Panic("failed to get snapshot from Raft storage", zap.Error(err))
  789. } else {
  790. plog.Panicf("get snapshot from raft storage error: %v", err)
  791. }
  792. }
  793. // asynchronously accept apply packets, dispatch progress in-order
  794. sched := schedule.NewFIFOScheduler()
  795. var (
  796. smu sync.RWMutex
  797. syncC <-chan time.Time
  798. )
  799. setSyncC := func(ch <-chan time.Time) {
  800. smu.Lock()
  801. syncC = ch
  802. smu.Unlock()
  803. }
  804. getSyncC := func() (ch <-chan time.Time) {
  805. smu.RLock()
  806. ch = syncC
  807. smu.RUnlock()
  808. return
  809. }
  810. rh := &raftReadyHandler{
  811. getLead: func() (lead uint64) { return s.getLead() },
  812. updateLead: func(lead uint64) { s.setLead(lead) },
  813. updateLeadership: func(newLeader bool) {
  814. if !s.isLeader() {
  815. if s.lessor != nil {
  816. s.lessor.Demote()
  817. }
  818. if s.compactor != nil {
  819. s.compactor.Pause()
  820. }
  821. setSyncC(nil)
  822. } else {
  823. if newLeader {
  824. t := time.Now()
  825. s.leadTimeMu.Lock()
  826. s.leadElectedTime = t
  827. s.leadTimeMu.Unlock()
  828. }
  829. setSyncC(s.SyncTicker.C)
  830. if s.compactor != nil {
  831. s.compactor.Resume()
  832. }
  833. }
  834. // TODO: remove the nil checking
  835. // current test utility does not provide the stats
  836. if s.stats != nil {
  837. s.stats.BecomeLeader()
  838. }
  839. },
  840. updateCommittedIndex: func(ci uint64) {
  841. cci := s.getCommittedIndex()
  842. if ci > cci {
  843. s.setCommittedIndex(ci)
  844. }
  845. },
  846. }
  847. s.r.start(rh)
  848. ep := etcdProgress{
  849. confState: sn.Metadata.ConfState,
  850. snapi: sn.Metadata.Index,
  851. appliedt: sn.Metadata.Term,
  852. appliedi: sn.Metadata.Index,
  853. }
  854. defer func() {
  855. s.wgMu.Lock() // block concurrent waitgroup adds in goAttach while stopping
  856. close(s.stopping)
  857. s.wgMu.Unlock()
  858. s.cancel()
  859. sched.Stop()
  860. // wait for gouroutines before closing raft so wal stays open
  861. s.wg.Wait()
  862. s.SyncTicker.Stop()
  863. // must stop raft after scheduler-- etcdserver can leak rafthttp pipelines
  864. // by adding a peer after raft stops the transport
  865. s.r.stop()
  866. // kv, lessor and backend can be nil if running without v3 enabled
  867. // or running unit tests.
  868. if s.lessor != nil {
  869. s.lessor.Stop()
  870. }
  871. if s.kv != nil {
  872. s.kv.Close()
  873. }
  874. if s.authStore != nil {
  875. s.authStore.Close()
  876. }
  877. if s.be != nil {
  878. s.be.Close()
  879. }
  880. if s.compactor != nil {
  881. s.compactor.Stop()
  882. }
  883. close(s.done)
  884. }()
  885. var expiredLeaseC <-chan []*lease.Lease
  886. if s.lessor != nil {
  887. expiredLeaseC = s.lessor.ExpiredLeasesC()
  888. }
  889. for {
  890. select {
  891. case ap := <-s.r.apply():
  892. f := func(context.Context) { s.applyAll(&ep, &ap) }
  893. sched.Schedule(f)
  894. case leases := <-expiredLeaseC:
  895. s.goAttach(func() {
  896. // Increases throughput of expired leases deletion process through parallelization
  897. c := make(chan struct{}, maxPendingRevokes)
  898. for _, lease := range leases {
  899. select {
  900. case c <- struct{}{}:
  901. case <-s.stopping:
  902. return
  903. }
  904. lid := lease.ID
  905. s.goAttach(func() {
  906. ctx := s.authStore.WithRoot(s.ctx)
  907. _, lerr := s.LeaseRevoke(ctx, &pb.LeaseRevokeRequest{ID: int64(lid)})
  908. if lerr == nil {
  909. leaseExpired.Inc()
  910. } else {
  911. if lg != nil {
  912. lg.Warn(
  913. "failed to revoke lease",
  914. zap.String("lease-id", fmt.Sprintf("%016x", lid)),
  915. zap.Error(lerr),
  916. )
  917. } else {
  918. plog.Warningf("failed to revoke %016x (%q)", lid, lerr.Error())
  919. }
  920. }
  921. <-c
  922. })
  923. }
  924. })
  925. case err := <-s.errorc:
  926. if lg != nil {
  927. lg.Warn("server error", zap.Error(err))
  928. lg.Warn("data-dir used by this member must be removed")
  929. } else {
  930. plog.Errorf("%s", err)
  931. plog.Infof("the data-dir used by this member must be removed.")
  932. }
  933. return
  934. case <-getSyncC():
  935. if s.v2store.HasTTLKeys() {
  936. s.sync(s.Cfg.ReqTimeout())
  937. }
  938. case <-s.stop:
  939. return
  940. }
  941. }
  942. }
  943. func (s *EtcdServer) applyAll(ep *etcdProgress, apply *apply) {
  944. s.applySnapshot(ep, apply)
  945. s.applyEntries(ep, apply)
  946. proposalsApplied.Set(float64(ep.appliedi))
  947. s.applyWait.Trigger(ep.appliedi)
  948. // wait for the raft routine to finish the disk writes before triggering a
  949. // snapshot. or applied index might be greater than the last index in raft
  950. // storage, since the raft routine might be slower than apply routine.
  951. <-apply.notifyc
  952. s.triggerSnapshot(ep)
  953. select {
  954. // snapshot requested via send()
  955. case m := <-s.r.msgSnapC:
  956. merged := s.createMergedSnapshotMessage(m, ep.appliedt, ep.appliedi, ep.confState)
  957. s.sendMergedSnap(merged)
  958. default:
  959. }
  960. }
  961. func (s *EtcdServer) applySnapshot(ep *etcdProgress, apply *apply) {
  962. if raft.IsEmptySnap(apply.snapshot) {
  963. return
  964. }
  965. lg := s.getLogger()
  966. if lg != nil {
  967. lg.Info(
  968. "applying snapshot",
  969. zap.Uint64("current-snapshot-index", ep.snapi),
  970. zap.Uint64("current-applied-index", ep.appliedi),
  971. zap.Uint64("incoming-leader-snapshot-index", apply.snapshot.Metadata.Index),
  972. zap.Uint64("incoming-leader-snapshot-term", apply.snapshot.Metadata.Term),
  973. )
  974. } else {
  975. plog.Infof("applying snapshot at index %d...", ep.snapi)
  976. }
  977. defer func() {
  978. if lg != nil {
  979. lg.Info(
  980. "applied snapshot",
  981. zap.Uint64("current-snapshot-index", ep.snapi),
  982. zap.Uint64("current-applied-index", ep.appliedi),
  983. zap.Uint64("incoming-leader-snapshot-index", apply.snapshot.Metadata.Index),
  984. zap.Uint64("incoming-leader-snapshot-term", apply.snapshot.Metadata.Term),
  985. )
  986. } else {
  987. plog.Infof("finished applying incoming snapshot at index %d", ep.snapi)
  988. }
  989. }()
  990. if apply.snapshot.Metadata.Index <= ep.appliedi {
  991. if lg != nil {
  992. lg.Panic(
  993. "unexpected leader snapshot from outdated index",
  994. zap.Uint64("current-snapshot-index", ep.snapi),
  995. zap.Uint64("current-applied-index", ep.appliedi),
  996. zap.Uint64("incoming-leader-snapshot-index", apply.snapshot.Metadata.Index),
  997. zap.Uint64("incoming-leader-snapshot-term", apply.snapshot.Metadata.Term),
  998. )
  999. } else {
  1000. plog.Panicf("snapshot index [%d] should > appliedi[%d] + 1",
  1001. apply.snapshot.Metadata.Index, ep.appliedi)
  1002. }
  1003. }
  1004. // wait for raftNode to persist snapshot onto the disk
  1005. <-apply.notifyc
  1006. newbe, err := openSnapshotBackend(s.Cfg, s.snapshotter, apply.snapshot)
  1007. if err != nil {
  1008. if lg != nil {
  1009. lg.Panic("failed to open snapshot backend", zap.Error(err))
  1010. } else {
  1011. plog.Panic(err)
  1012. }
  1013. }
  1014. // always recover lessor before kv. When we recover the mvcc.KV it will reattach keys to its leases.
  1015. // If we recover mvcc.KV first, it will attach the keys to the wrong lessor before it recovers.
  1016. if s.lessor != nil {
  1017. if lg != nil {
  1018. lg.Info("restoring lease store")
  1019. } else {
  1020. plog.Info("recovering lessor...")
  1021. }
  1022. s.lessor.Recover(newbe, func() lease.TxnDelete { return s.kv.Write() })
  1023. if lg != nil {
  1024. lg.Info("restored lease store")
  1025. } else {
  1026. plog.Info("finished recovering lessor")
  1027. }
  1028. }
  1029. if lg != nil {
  1030. lg.Info("restoring mvcc store")
  1031. } else {
  1032. plog.Info("restoring mvcc store...")
  1033. }
  1034. if err := s.kv.Restore(newbe); err != nil {
  1035. if lg != nil {
  1036. lg.Panic("failed to restore mvcc store", zap.Error(err))
  1037. } else {
  1038. plog.Panicf("restore KV error: %v", err)
  1039. }
  1040. }
  1041. s.consistIndex.setConsistentIndex(s.kv.ConsistentIndex())
  1042. if lg != nil {
  1043. lg.Info("restored mvcc store")
  1044. } else {
  1045. plog.Info("finished restoring mvcc store")
  1046. }
  1047. // Closing old backend might block until all the txns
  1048. // on the backend are finished.
  1049. // We do not want to wait on closing the old backend.
  1050. s.bemu.Lock()
  1051. oldbe := s.be
  1052. go func() {
  1053. if lg != nil {
  1054. lg.Info("closing old backend file")
  1055. } else {
  1056. plog.Info("closing old backend...")
  1057. }
  1058. defer func() {
  1059. if lg != nil {
  1060. lg.Info("closed old backend file")
  1061. } else {
  1062. plog.Info("finished closing old backend")
  1063. }
  1064. }()
  1065. if err := oldbe.Close(); err != nil {
  1066. if lg != nil {
  1067. lg.Panic("failed to close old backend", zap.Error(err))
  1068. } else {
  1069. plog.Panicf("close backend error: %v", err)
  1070. }
  1071. }
  1072. }()
  1073. s.be = newbe
  1074. s.bemu.Unlock()
  1075. if lg != nil {
  1076. lg.Info("restoring alarm store")
  1077. } else {
  1078. plog.Info("recovering alarms...")
  1079. }
  1080. if err := s.restoreAlarms(); err != nil {
  1081. if lg != nil {
  1082. lg.Panic("failed to restore alarm store", zap.Error(err))
  1083. } else {
  1084. plog.Panicf("restore alarms error: %v", err)
  1085. }
  1086. }
  1087. if lg != nil {
  1088. lg.Info("restored alarm store")
  1089. } else {
  1090. plog.Info("finished recovering alarms")
  1091. }
  1092. if s.authStore != nil {
  1093. if lg != nil {
  1094. lg.Info("restoring auth store")
  1095. } else {
  1096. plog.Info("recovering auth store...")
  1097. }
  1098. s.authStore.Recover(newbe)
  1099. if lg != nil {
  1100. lg.Info("restored auth store")
  1101. } else {
  1102. plog.Info("finished recovering auth store")
  1103. }
  1104. }
  1105. if lg != nil {
  1106. lg.Info("restoring v2 store")
  1107. } else {
  1108. plog.Info("recovering store v2...")
  1109. }
  1110. if err := s.v2store.Recovery(apply.snapshot.Data); err != nil {
  1111. if lg != nil {
  1112. lg.Panic("failed to restore v2 store", zap.Error(err))
  1113. } else {
  1114. plog.Panicf("recovery store error: %v", err)
  1115. }
  1116. }
  1117. if lg != nil {
  1118. lg.Info("restored v2 store")
  1119. } else {
  1120. plog.Info("finished recovering store v2")
  1121. }
  1122. s.cluster.SetBackend(s.be)
  1123. if lg != nil {
  1124. lg.Info("restoring cluster configuration")
  1125. } else {
  1126. plog.Info("recovering cluster configuration...")
  1127. }
  1128. s.cluster.Recover(api.UpdateCapability)
  1129. if lg != nil {
  1130. lg.Info("restored cluster configuration")
  1131. lg.Info("removing old peers from network")
  1132. } else {
  1133. plog.Info("finished recovering cluster configuration")
  1134. plog.Info("removing old peers from network...")
  1135. }
  1136. // recover raft transport
  1137. s.r.transport.RemoveAllPeers()
  1138. if lg != nil {
  1139. lg.Info("removed old peers from network")
  1140. lg.Info("adding peers from new cluster configuration")
  1141. } else {
  1142. plog.Info("finished removing old peers from network")
  1143. plog.Info("adding peers from new cluster configuration into network...")
  1144. }
  1145. for _, m := range s.cluster.Members() {
  1146. if m.ID == s.ID() {
  1147. continue
  1148. }
  1149. s.r.transport.AddPeer(m.ID, m.PeerURLs)
  1150. }
  1151. if lg != nil {
  1152. lg.Info("added peers from new cluster configuration")
  1153. } else {
  1154. plog.Info("finished adding peers from new cluster configuration into network...")
  1155. }
  1156. ep.appliedt = apply.snapshot.Metadata.Term
  1157. ep.appliedi = apply.snapshot.Metadata.Index
  1158. ep.snapi = ep.appliedi
  1159. ep.confState = apply.snapshot.Metadata.ConfState
  1160. }
  1161. func (s *EtcdServer) applyEntries(ep *etcdProgress, apply *apply) {
  1162. if len(apply.entries) == 0 {
  1163. return
  1164. }
  1165. firsti := apply.entries[0].Index
  1166. if firsti > ep.appliedi+1 {
  1167. if lg := s.getLogger(); lg != nil {
  1168. lg.Panic(
  1169. "unexpected committed entry index",
  1170. zap.Uint64("current-applied-index", ep.appliedi),
  1171. zap.Uint64("first-committed-entry-index", firsti),
  1172. )
  1173. } else {
  1174. plog.Panicf("first index of committed entry[%d] should <= appliedi[%d] + 1", firsti, ep.appliedi)
  1175. }
  1176. }
  1177. var ents []raftpb.Entry
  1178. if ep.appliedi+1-firsti < uint64(len(apply.entries)) {
  1179. ents = apply.entries[ep.appliedi+1-firsti:]
  1180. }
  1181. if len(ents) == 0 {
  1182. return
  1183. }
  1184. var shouldstop bool
  1185. if ep.appliedt, ep.appliedi, shouldstop = s.apply(ents, &ep.confState); shouldstop {
  1186. go s.stopWithDelay(10*100*time.Millisecond, fmt.Errorf("the member has been permanently removed from the cluster"))
  1187. }
  1188. }
  1189. func (s *EtcdServer) triggerSnapshot(ep *etcdProgress) {
  1190. if ep.appliedi-ep.snapi <= s.Cfg.SnapshotCount {
  1191. return
  1192. }
  1193. if lg := s.getLogger(); lg != nil {
  1194. lg.Info(
  1195. "triggering snapshot",
  1196. zap.String("local-member-id", s.ID().String()),
  1197. zap.Uint64("local-member-applied-index", ep.appliedi),
  1198. zap.Uint64("local-member-snapshot-index", ep.snapi),
  1199. zap.Uint64("local-member-snapshot-count", s.Cfg.SnapshotCount),
  1200. )
  1201. } else {
  1202. plog.Infof("start to snapshot (applied: %d, lastsnap: %d)", ep.appliedi, ep.snapi)
  1203. }
  1204. s.snapshot(ep.appliedi, ep.confState)
  1205. ep.snapi = ep.appliedi
  1206. }
  1207. func (s *EtcdServer) isMultiNode() bool {
  1208. return s.cluster != nil && len(s.cluster.MemberIDs()) > 1
  1209. }
  1210. func (s *EtcdServer) isLeader() bool {
  1211. return uint64(s.ID()) == s.Lead()
  1212. }
  1213. // MoveLeader transfers the leader to the given transferee.
  1214. func (s *EtcdServer) MoveLeader(ctx context.Context, lead, transferee uint64) error {
  1215. now := time.Now()
  1216. interval := time.Duration(s.Cfg.TickMs) * time.Millisecond
  1217. if lg := s.getLogger(); lg != nil {
  1218. lg.Info(
  1219. "leadership transfer starting",
  1220. zap.String("local-member-id", s.ID().String()),
  1221. zap.String("current-leader-member-id", types.ID(lead).String()),
  1222. zap.String("transferee-member-id", types.ID(transferee).String()),
  1223. )
  1224. } else {
  1225. plog.Infof("%s starts leadership transfer from %s to %s", s.ID(), types.ID(lead), types.ID(transferee))
  1226. }
  1227. s.r.TransferLeadership(ctx, lead, transferee)
  1228. for s.Lead() != transferee {
  1229. select {
  1230. case <-ctx.Done(): // time out
  1231. return ErrTimeoutLeaderTransfer
  1232. case <-time.After(interval):
  1233. }
  1234. }
  1235. // TODO: drain all requests, or drop all messages to the old leader
  1236. if lg := s.getLogger(); lg != nil {
  1237. lg.Info(
  1238. "leadership transfer finished",
  1239. zap.String("local-member-id", s.ID().String()),
  1240. zap.String("old-leader-member-id", types.ID(lead).String()),
  1241. zap.String("new-leader-member-id", types.ID(transferee).String()),
  1242. zap.Duration("took", time.Since(now)),
  1243. )
  1244. } else {
  1245. plog.Infof("%s finished leadership transfer from %s to %s (took %v)", s.ID(), types.ID(lead), types.ID(transferee), time.Since(now))
  1246. }
  1247. return nil
  1248. }
  1249. // TransferLeadership transfers the leader to the chosen transferee.
  1250. func (s *EtcdServer) TransferLeadership() error {
  1251. if !s.isLeader() {
  1252. if lg := s.getLogger(); lg != nil {
  1253. lg.Info(
  1254. "skipped leadership transfer; local server is not leader",
  1255. zap.String("local-member-id", s.ID().String()),
  1256. zap.String("current-leader-member-id", types.ID(s.Lead()).String()),
  1257. )
  1258. } else {
  1259. plog.Printf("skipped leadership transfer for stopping non-leader member")
  1260. }
  1261. return nil
  1262. }
  1263. if !s.isMultiNode() {
  1264. if lg := s.getLogger(); lg != nil {
  1265. lg.Info(
  1266. "skipped leadership transfer; it's a single-node cluster",
  1267. zap.String("local-member-id", s.ID().String()),
  1268. zap.String("current-leader-member-id", types.ID(s.Lead()).String()),
  1269. )
  1270. } else {
  1271. plog.Printf("skipped leadership transfer for single member cluster")
  1272. }
  1273. return nil
  1274. }
  1275. transferee, ok := longestConnected(s.r.transport, s.cluster.MemberIDs())
  1276. if !ok {
  1277. return ErrUnhealthy
  1278. }
  1279. tm := s.Cfg.ReqTimeout()
  1280. ctx, cancel := context.WithTimeout(s.ctx, tm)
  1281. err := s.MoveLeader(ctx, s.Lead(), uint64(transferee))
  1282. cancel()
  1283. return err
  1284. }
  1285. // HardStop stops the server without coordination with other members in the cluster.
  1286. func (s *EtcdServer) HardStop() {
  1287. select {
  1288. case s.stop <- struct{}{}:
  1289. case <-s.done:
  1290. return
  1291. }
  1292. <-s.done
  1293. }
  1294. // Stop stops the server gracefully, and shuts down the running goroutine.
  1295. // Stop should be called after a Start(s), otherwise it will block forever.
  1296. // When stopping leader, Stop transfers its leadership to one of its peers
  1297. // before stopping the server.
  1298. // Stop terminates the Server and performs any necessary finalization.
  1299. // Do and Process cannot be called after Stop has been invoked.
  1300. func (s *EtcdServer) Stop() {
  1301. if err := s.TransferLeadership(); err != nil {
  1302. if lg := s.getLogger(); lg != nil {
  1303. lg.Warn("leadership transfer failed", zap.String("local-member-id", s.ID().String()), zap.Error(err))
  1304. } else {
  1305. plog.Warningf("%s failed to transfer leadership (%v)", s.ID(), err)
  1306. }
  1307. }
  1308. s.HardStop()
  1309. }
  1310. // ReadyNotify returns a channel that will be closed when the server
  1311. // is ready to serve client requests
  1312. func (s *EtcdServer) ReadyNotify() <-chan struct{} { return s.readych }
  1313. func (s *EtcdServer) stopWithDelay(d time.Duration, err error) {
  1314. select {
  1315. case <-time.After(d):
  1316. case <-s.done:
  1317. }
  1318. select {
  1319. case s.errorc <- err:
  1320. default:
  1321. }
  1322. }
  1323. // StopNotify returns a channel that receives a empty struct
  1324. // when the server is stopped.
  1325. func (s *EtcdServer) StopNotify() <-chan struct{} { return s.done }
  1326. func (s *EtcdServer) SelfStats() []byte { return s.stats.JSON() }
  1327. func (s *EtcdServer) LeaderStats() []byte {
  1328. lead := s.getLead()
  1329. if lead != uint64(s.id) {
  1330. return nil
  1331. }
  1332. return s.lstats.JSON()
  1333. }
  1334. func (s *EtcdServer) StoreStats() []byte { return s.v2store.JsonStats() }
  1335. func (s *EtcdServer) checkMembershipOperationPermission(ctx context.Context) error {
  1336. if s.authStore == nil {
  1337. // In the context of ordinary etcd process, s.authStore will never be nil.
  1338. // This branch is for handling cases in server_test.go
  1339. return nil
  1340. }
  1341. // Note that this permission check is done in the API layer,
  1342. // so TOCTOU problem can be caused potentially in a schedule like this:
  1343. // update membership with user A -> revoke root role of A -> apply membership change
  1344. // in the state machine layer
  1345. // However, both of membership change and role management requires the root privilege.
  1346. // So careful operation by admins can prevent the problem.
  1347. authInfo, err := s.AuthInfoFromCtx(ctx)
  1348. if err != nil {
  1349. return err
  1350. }
  1351. return s.AuthStore().IsAdminPermitted(authInfo)
  1352. }
  1353. func (s *EtcdServer) AddMember(ctx context.Context, memb membership.Member) ([]*membership.Member, error) {
  1354. if err := s.checkMembershipOperationPermission(ctx); err != nil {
  1355. return nil, err
  1356. }
  1357. if s.Cfg.StrictReconfigCheck {
  1358. // by default StrictReconfigCheck is enabled; reject new members if unhealthy
  1359. if !s.cluster.IsReadyToAddNewMember() {
  1360. if lg := s.getLogger(); lg != nil {
  1361. lg.Warn(
  1362. "rejecting member add request; not enough healthy members",
  1363. zap.String("local-member-id", s.ID().String()),
  1364. zap.String("requested-member-add", fmt.Sprintf("%+v", memb)),
  1365. zap.Error(ErrNotEnoughStartedMembers),
  1366. )
  1367. } else {
  1368. plog.Warningf("not enough started members, rejecting member add %+v", memb)
  1369. }
  1370. return nil, ErrNotEnoughStartedMembers
  1371. }
  1372. if !isConnectedFullySince(s.r.transport, time.Now().Add(-HealthInterval), s.ID(), s.cluster.Members()) {
  1373. if lg := s.getLogger(); lg != nil {
  1374. lg.Warn(
  1375. "rejecting member add request; local member has not been connected to all peers, reconfigure breaks active quorum",
  1376. zap.String("local-member-id", s.ID().String()),
  1377. zap.String("requested-member-add", fmt.Sprintf("%+v", memb)),
  1378. zap.Error(ErrUnhealthy),
  1379. )
  1380. } else {
  1381. plog.Warningf("not healthy for reconfigure, rejecting member add %+v", memb)
  1382. }
  1383. return nil, ErrUnhealthy
  1384. }
  1385. }
  1386. // TODO: move Member to protobuf type
  1387. b, err := json.Marshal(memb)
  1388. if err != nil {
  1389. return nil, err
  1390. }
  1391. cc := raftpb.ConfChange{
  1392. Type: raftpb.ConfChangeAddNode,
  1393. NodeID: uint64(memb.ID),
  1394. Context: b,
  1395. }
  1396. return s.configure(ctx, cc)
  1397. }
  1398. func (s *EtcdServer) RemoveMember(ctx context.Context, id uint64) ([]*membership.Member, error) {
  1399. if err := s.checkMembershipOperationPermission(ctx); err != nil {
  1400. return nil, err
  1401. }
  1402. // by default StrictReconfigCheck is enabled; reject removal if leads to quorum loss
  1403. if err := s.mayRemoveMember(types.ID(id)); err != nil {
  1404. return nil, err
  1405. }
  1406. cc := raftpb.ConfChange{
  1407. Type: raftpb.ConfChangeRemoveNode,
  1408. NodeID: id,
  1409. }
  1410. return s.configure(ctx, cc)
  1411. }
  1412. func (s *EtcdServer) mayRemoveMember(id types.ID) error {
  1413. if !s.Cfg.StrictReconfigCheck {
  1414. return nil
  1415. }
  1416. if !s.cluster.IsReadyToRemoveMember(uint64(id)) {
  1417. if lg := s.getLogger(); lg != nil {
  1418. lg.Warn(
  1419. "rejecting member remove request; not enough healthy members",
  1420. zap.String("local-member-id", s.ID().String()),
  1421. zap.String("requested-member-remove-id", id.String()),
  1422. zap.Error(ErrNotEnoughStartedMembers),
  1423. )
  1424. } else {
  1425. plog.Warningf("not enough started members, rejecting remove member %s", id)
  1426. }
  1427. return ErrNotEnoughStartedMembers
  1428. }
  1429. // downed member is safe to remove since it's not part of the active quorum
  1430. if t := s.r.transport.ActiveSince(id); id != s.ID() && t.IsZero() {
  1431. return nil
  1432. }
  1433. // protect quorum if some members are down
  1434. m := s.cluster.Members()
  1435. active := numConnectedSince(s.r.transport, time.Now().Add(-HealthInterval), s.ID(), m)
  1436. if (active - 1) < 1+((len(m)-1)/2) {
  1437. if lg := s.getLogger(); lg != nil {
  1438. lg.Warn(
  1439. "rejecting member remove request; local member has not been connected to all peers, reconfigure breaks active quorum",
  1440. zap.String("local-member-id", s.ID().String()),
  1441. zap.String("requested-member-remove", id.String()),
  1442. zap.Int("active-peers", active),
  1443. zap.Error(ErrUnhealthy),
  1444. )
  1445. } else {
  1446. plog.Warningf("reconfigure breaks active quorum, rejecting remove member %s", id)
  1447. }
  1448. return ErrUnhealthy
  1449. }
  1450. return nil
  1451. }
  1452. func (s *EtcdServer) UpdateMember(ctx context.Context, memb membership.Member) ([]*membership.Member, error) {
  1453. b, merr := json.Marshal(memb)
  1454. if merr != nil {
  1455. return nil, merr
  1456. }
  1457. if err := s.checkMembershipOperationPermission(ctx); err != nil {
  1458. return nil, err
  1459. }
  1460. cc := raftpb.ConfChange{
  1461. Type: raftpb.ConfChangeUpdateNode,
  1462. NodeID: uint64(memb.ID),
  1463. Context: b,
  1464. }
  1465. return s.configure(ctx, cc)
  1466. }
  1467. func (s *EtcdServer) setCommittedIndex(v uint64) {
  1468. atomic.StoreUint64(&s.committedIndex, v)
  1469. }
  1470. func (s *EtcdServer) getCommittedIndex() uint64 {
  1471. return atomic.LoadUint64(&s.committedIndex)
  1472. }
  1473. func (s *EtcdServer) setAppliedIndex(v uint64) {
  1474. atomic.StoreUint64(&s.appliedIndex, v)
  1475. }
  1476. func (s *EtcdServer) getAppliedIndex() uint64 {
  1477. return atomic.LoadUint64(&s.appliedIndex)
  1478. }
  1479. func (s *EtcdServer) setTerm(v uint64) {
  1480. atomic.StoreUint64(&s.term, v)
  1481. }
  1482. func (s *EtcdServer) getTerm() uint64 {
  1483. return atomic.LoadUint64(&s.term)
  1484. }
  1485. func (s *EtcdServer) setLead(v uint64) {
  1486. atomic.StoreUint64(&s.lead, v)
  1487. }
  1488. func (s *EtcdServer) getLead() uint64 {
  1489. return atomic.LoadUint64(&s.lead)
  1490. }
  1491. // RaftStatusGetter represents etcd server and Raft progress.
  1492. type RaftStatusGetter interface {
  1493. ID() types.ID
  1494. Leader() types.ID
  1495. CommittedIndex() uint64
  1496. AppliedIndex() uint64
  1497. Term() uint64
  1498. }
  1499. func (s *EtcdServer) ID() types.ID { return s.id }
  1500. func (s *EtcdServer) Leader() types.ID { return types.ID(s.getLead()) }
  1501. func (s *EtcdServer) Lead() uint64 { return s.getLead() }
  1502. func (s *EtcdServer) CommittedIndex() uint64 { return s.getCommittedIndex() }
  1503. func (s *EtcdServer) AppliedIndex() uint64 { return s.getAppliedIndex() }
  1504. func (s *EtcdServer) Term() uint64 { return s.getTerm() }
  1505. type confChangeResponse struct {
  1506. membs []*membership.Member
  1507. err error
  1508. }
  1509. // configure sends a configuration change through consensus and
  1510. // then waits for it to be applied to the server. It
  1511. // will block until the change is performed or there is an error.
  1512. func (s *EtcdServer) configure(ctx context.Context, cc raftpb.ConfChange) ([]*membership.Member, error) {
  1513. cc.ID = s.reqIDGen.Next()
  1514. ch := s.w.Register(cc.ID)
  1515. start := time.Now()
  1516. if err := s.r.ProposeConfChange(ctx, cc); err != nil {
  1517. s.w.Trigger(cc.ID, nil)
  1518. return nil, err
  1519. }
  1520. select {
  1521. case x := <-ch:
  1522. if x == nil {
  1523. if lg := s.getLogger(); lg != nil {
  1524. lg.Panic("failed to configure")
  1525. } else {
  1526. plog.Panicf("configure trigger value should never be nil")
  1527. }
  1528. }
  1529. resp := x.(*confChangeResponse)
  1530. if lg := s.getLogger(); lg != nil {
  1531. lg.Info(
  1532. "applied a configuration change through raft",
  1533. zap.String("local-member-id", s.ID().String()),
  1534. zap.String("raft-conf-change", cc.Type.String()),
  1535. zap.String("raft-conf-change-node-id", types.ID(cc.NodeID).String()),
  1536. )
  1537. }
  1538. return resp.membs, resp.err
  1539. case <-ctx.Done():
  1540. s.w.Trigger(cc.ID, nil) // GC wait
  1541. return nil, s.parseProposeCtxErr(ctx.Err(), start)
  1542. case <-s.stopping:
  1543. return nil, ErrStopped
  1544. }
  1545. }
  1546. // sync proposes a SYNC request and is non-blocking.
  1547. // This makes no guarantee that the request will be proposed or performed.
  1548. // The request will be canceled after the given timeout.
  1549. func (s *EtcdServer) sync(timeout time.Duration) {
  1550. req := pb.Request{
  1551. Method: "SYNC",
  1552. ID: s.reqIDGen.Next(),
  1553. Time: time.Now().UnixNano(),
  1554. }
  1555. data := pbutil.MustMarshal(&req)
  1556. // There is no promise that node has leader when do SYNC request,
  1557. // so it uses goroutine to propose.
  1558. ctx, cancel := context.WithTimeout(s.ctx, timeout)
  1559. s.goAttach(func() {
  1560. s.r.Propose(ctx, data)
  1561. cancel()
  1562. })
  1563. }
  1564. // publish registers server information into the cluster. The information
  1565. // is the JSON representation of this server's member struct, updated with the
  1566. // static clientURLs of the server.
  1567. // The function keeps attempting to register until it succeeds,
  1568. // or its server is stopped.
  1569. func (s *EtcdServer) publish(timeout time.Duration) {
  1570. b, err := json.Marshal(s.attributes)
  1571. if err != nil {
  1572. if lg := s.getLogger(); lg != nil {
  1573. lg.Panic("failed to marshal JSON", zap.Error(err))
  1574. } else {
  1575. plog.Panicf("json marshal error: %v", err)
  1576. }
  1577. return
  1578. }
  1579. req := pb.Request{
  1580. Method: "PUT",
  1581. Path: membership.MemberAttributesStorePath(s.id),
  1582. Val: string(b),
  1583. }
  1584. for {
  1585. ctx, cancel := context.WithTimeout(s.ctx, timeout)
  1586. _, err := s.Do(ctx, req)
  1587. cancel()
  1588. switch err {
  1589. case nil:
  1590. close(s.readych)
  1591. if lg := s.getLogger(); lg != nil {
  1592. lg.Info(
  1593. "published local member to cluster through raft",
  1594. zap.String("local-member-id", s.ID().String()),
  1595. zap.String("local-member-attributes", fmt.Sprintf("%+v", s.attributes)),
  1596. zap.String("request-path", req.Path),
  1597. zap.String("cluster-id", s.cluster.ID().String()),
  1598. zap.Duration("publish-timeout", timeout),
  1599. )
  1600. } else {
  1601. plog.Infof("published %+v to cluster %s", s.attributes, s.cluster.ID())
  1602. }
  1603. return
  1604. case ErrStopped:
  1605. if lg := s.getLogger(); lg != nil {
  1606. lg.Warn(
  1607. "stopped publish because server is stopped",
  1608. zap.String("local-member-id", s.ID().String()),
  1609. zap.String("local-member-attributes", fmt.Sprintf("%+v", s.attributes)),
  1610. zap.Duration("publish-timeout", timeout),
  1611. zap.Error(err),
  1612. )
  1613. } else {
  1614. plog.Infof("aborting publish because server is stopped")
  1615. }
  1616. return
  1617. default:
  1618. if lg := s.getLogger(); lg != nil {
  1619. lg.Warn(
  1620. "failed to publish local member to cluster through raft",
  1621. zap.String("local-member-id", s.ID().String()),
  1622. zap.String("local-member-attributes", fmt.Sprintf("%+v", s.attributes)),
  1623. zap.String("request-path", req.Path),
  1624. zap.Duration("publish-timeout", timeout),
  1625. zap.Error(err),
  1626. )
  1627. } else {
  1628. plog.Errorf("publish error: %v", err)
  1629. }
  1630. }
  1631. }
  1632. }
  1633. func (s *EtcdServer) sendMergedSnap(merged snap.Message) {
  1634. atomic.AddInt64(&s.inflightSnapshots, 1)
  1635. lg := s.getLogger()
  1636. fields := []zap.Field{
  1637. zap.String("from", s.ID().String()),
  1638. zap.String("to", types.ID(merged.To).String()),
  1639. zap.Int64("bytes", merged.TotalSize),
  1640. zap.String("size", humanize.Bytes(uint64(merged.TotalSize))),
  1641. }
  1642. now := time.Now()
  1643. s.r.transport.SendSnapshot(merged)
  1644. if lg != nil {
  1645. lg.Info("sending merged snapshot", fields...)
  1646. }
  1647. s.goAttach(func() {
  1648. select {
  1649. case ok := <-merged.CloseNotify():
  1650. // delay releasing inflight snapshot for another 30 seconds to
  1651. // block log compaction.
  1652. // If the follower still fails to catch up, it is probably just too slow
  1653. // to catch up. We cannot avoid the snapshot cycle anyway.
  1654. if ok {
  1655. select {
  1656. case <-time.After(releaseDelayAfterSnapshot):
  1657. case <-s.stopping:
  1658. }
  1659. }
  1660. atomic.AddInt64(&s.inflightSnapshots, -1)
  1661. if lg != nil {
  1662. lg.Info("sent merged snapshot", append(fields, zap.Duration("took", time.Since(now)))...)
  1663. }
  1664. case <-s.stopping:
  1665. if lg != nil {
  1666. lg.Warn("canceled sending merged snapshot; server stopping", fields...)
  1667. }
  1668. return
  1669. }
  1670. })
  1671. }
  1672. // apply takes entries received from Raft (after it has been committed) and
  1673. // applies them to the current state of the EtcdServer.
  1674. // The given entries should not be empty.
  1675. func (s *EtcdServer) apply(
  1676. es []raftpb.Entry,
  1677. confState *raftpb.ConfState,
  1678. ) (appliedt uint64, appliedi uint64, shouldStop bool) {
  1679. for i := range es {
  1680. e := es[i]
  1681. switch e.Type {
  1682. case raftpb.EntryNormal:
  1683. s.applyEntryNormal(&e)
  1684. s.setAppliedIndex(e.Index)
  1685. s.setTerm(e.Term)
  1686. case raftpb.EntryConfChange:
  1687. // set the consistent index of current executing entry
  1688. if e.Index > s.consistIndex.ConsistentIndex() {
  1689. s.consistIndex.setConsistentIndex(e.Index)
  1690. }
  1691. var cc raftpb.ConfChange
  1692. pbutil.MustUnmarshal(&cc, e.Data)
  1693. removedSelf, err := s.applyConfChange(cc, confState)
  1694. s.setAppliedIndex(e.Index)
  1695. s.setTerm(e.Term)
  1696. shouldStop = shouldStop || removedSelf
  1697. s.w.Trigger(cc.ID, &confChangeResponse{s.cluster.Members(), err})
  1698. default:
  1699. if lg := s.getLogger(); lg != nil {
  1700. lg.Panic(
  1701. "unknown entry type; must be either EntryNormal or EntryConfChange",
  1702. zap.String("type", e.Type.String()),
  1703. )
  1704. } else {
  1705. plog.Panicf("entry type should be either EntryNormal or EntryConfChange")
  1706. }
  1707. }
  1708. appliedi, appliedt = e.Index, e.Term
  1709. }
  1710. return appliedt, appliedi, shouldStop
  1711. }
  1712. // applyEntryNormal apples an EntryNormal type raftpb request to the EtcdServer
  1713. func (s *EtcdServer) applyEntryNormal(e *raftpb.Entry) {
  1714. shouldApplyV3 := false
  1715. if e.Index > s.consistIndex.ConsistentIndex() {
  1716. // set the consistent index of current executing entry
  1717. s.consistIndex.setConsistentIndex(e.Index)
  1718. shouldApplyV3 = true
  1719. }
  1720. // raft state machine may generate noop entry when leader confirmation.
  1721. // skip it in advance to avoid some potential bug in the future
  1722. if len(e.Data) == 0 {
  1723. select {
  1724. case s.forceVersionC <- struct{}{}:
  1725. default:
  1726. }
  1727. // promote lessor when the local member is leader and finished
  1728. // applying all entries from the last term.
  1729. if s.isLeader() {
  1730. s.lessor.Promote(s.Cfg.electionTimeout())
  1731. }
  1732. return
  1733. }
  1734. var raftReq pb.InternalRaftRequest
  1735. if !pbutil.MaybeUnmarshal(&raftReq, e.Data) { // backward compatible
  1736. var r pb.Request
  1737. rp := &r
  1738. pbutil.MustUnmarshal(rp, e.Data)
  1739. s.w.Trigger(r.ID, s.applyV2Request((*RequestV2)(rp)))
  1740. return
  1741. }
  1742. if raftReq.V2 != nil {
  1743. req := (*RequestV2)(raftReq.V2)
  1744. s.w.Trigger(req.ID, s.applyV2Request(req))
  1745. return
  1746. }
  1747. // do not re-apply applied entries.
  1748. if !shouldApplyV3 {
  1749. return
  1750. }
  1751. id := raftReq.ID
  1752. if id == 0 {
  1753. id = raftReq.Header.ID
  1754. }
  1755. var ar *applyResult
  1756. needResult := s.w.IsRegistered(id)
  1757. if needResult || !noSideEffect(&raftReq) {
  1758. if !needResult && raftReq.Txn != nil {
  1759. removeNeedlessRangeReqs(raftReq.Txn)
  1760. }
  1761. ar = s.applyV3.Apply(&raftReq)
  1762. }
  1763. if ar == nil {
  1764. return
  1765. }
  1766. if ar.err != ErrNoSpace || len(s.alarmStore.Get(pb.AlarmType_NOSPACE)) > 0 {
  1767. s.w.Trigger(id, ar)
  1768. return
  1769. }
  1770. if lg := s.getLogger(); lg != nil {
  1771. lg.Warn(
  1772. "message exceeded backend quota; raising alarm",
  1773. zap.Int64("quota-size-bytes", s.Cfg.QuotaBackendBytes),
  1774. zap.String("quota-size", humanize.Bytes(uint64(s.Cfg.QuotaBackendBytes))),
  1775. zap.Error(ar.err),
  1776. )
  1777. } else {
  1778. plog.Errorf("applying raft message exceeded backend quota")
  1779. }
  1780. s.goAttach(func() {
  1781. a := &pb.AlarmRequest{
  1782. MemberID: uint64(s.ID()),
  1783. Action: pb.AlarmRequest_ACTIVATE,
  1784. Alarm: pb.AlarmType_NOSPACE,
  1785. }
  1786. s.raftRequest(s.ctx, pb.InternalRaftRequest{Alarm: a})
  1787. s.w.Trigger(id, ar)
  1788. })
  1789. }
  1790. // applyConfChange applies a ConfChange to the server. It is only
  1791. // invoked with a ConfChange that has already passed through Raft
  1792. func (s *EtcdServer) applyConfChange(cc raftpb.ConfChange, confState *raftpb.ConfState) (bool, error) {
  1793. if err := s.cluster.ValidateConfigurationChange(cc); err != nil {
  1794. cc.NodeID = raft.None
  1795. s.r.ApplyConfChange(cc)
  1796. return false, err
  1797. }
  1798. lg := s.getLogger()
  1799. *confState = *s.r.ApplyConfChange(cc)
  1800. switch cc.Type {
  1801. case raftpb.ConfChangeAddNode:
  1802. m := new(membership.Member)
  1803. if err := json.Unmarshal(cc.Context, m); err != nil {
  1804. if lg != nil {
  1805. lg.Panic("failed to unmarshal member", zap.Error(err))
  1806. } else {
  1807. plog.Panicf("unmarshal member should never fail: %v", err)
  1808. }
  1809. }
  1810. if cc.NodeID != uint64(m.ID) {
  1811. if lg != nil {
  1812. lg.Panic(
  1813. "got different member ID",
  1814. zap.String("member-id-from-config-change-entry", types.ID(cc.NodeID).String()),
  1815. zap.String("member-id-from-message", m.ID.String()),
  1816. )
  1817. } else {
  1818. plog.Panicf("nodeID should always be equal to member ID")
  1819. }
  1820. }
  1821. s.cluster.AddMember(m)
  1822. if m.ID != s.id {
  1823. s.r.transport.AddPeer(m.ID, m.PeerURLs)
  1824. }
  1825. case raftpb.ConfChangeRemoveNode:
  1826. id := types.ID(cc.NodeID)
  1827. s.cluster.RemoveMember(id)
  1828. if id == s.id {
  1829. return true, nil
  1830. }
  1831. s.r.transport.RemovePeer(id)
  1832. case raftpb.ConfChangeUpdateNode:
  1833. m := new(membership.Member)
  1834. if err := json.Unmarshal(cc.Context, m); err != nil {
  1835. if lg != nil {
  1836. lg.Panic("failed to unmarshal member", zap.Error(err))
  1837. } else {
  1838. plog.Panicf("unmarshal member should never fail: %v", err)
  1839. }
  1840. }
  1841. if cc.NodeID != uint64(m.ID) {
  1842. if lg != nil {
  1843. lg.Panic(
  1844. "got different member ID",
  1845. zap.String("member-id-from-config-change-entry", types.ID(cc.NodeID).String()),
  1846. zap.String("member-id-from-message", m.ID.String()),
  1847. )
  1848. } else {
  1849. plog.Panicf("nodeID should always be equal to member ID")
  1850. }
  1851. }
  1852. s.cluster.UpdateRaftAttributes(m.ID, m.RaftAttributes)
  1853. if m.ID != s.id {
  1854. s.r.transport.UpdatePeer(m.ID, m.PeerURLs)
  1855. }
  1856. }
  1857. return false, nil
  1858. }
  1859. // TODO: non-blocking snapshot
  1860. func (s *EtcdServer) snapshot(snapi uint64, confState raftpb.ConfState) {
  1861. clone := s.v2store.Clone()
  1862. // commit kv to write metadata (for example: consistent index) to disk.
  1863. // KV().commit() updates the consistent index in backend.
  1864. // All operations that update consistent index must be called sequentially
  1865. // from applyAll function.
  1866. // So KV().Commit() cannot run in parallel with apply. It has to be called outside
  1867. // the go routine created below.
  1868. s.KV().Commit()
  1869. s.goAttach(func() {
  1870. lg := s.getLogger()
  1871. d, err := clone.SaveNoCopy()
  1872. // TODO: current store will never fail to do a snapshot
  1873. // what should we do if the store might fail?
  1874. if err != nil {
  1875. if lg != nil {
  1876. lg.Panic("failed to save v2 store", zap.Error(err))
  1877. } else {
  1878. plog.Panicf("store save should never fail: %v", err)
  1879. }
  1880. }
  1881. snap, err := s.r.raftStorage.CreateSnapshot(snapi, &confState, d)
  1882. if err != nil {
  1883. // the snapshot was done asynchronously with the progress of raft.
  1884. // raft might have already got a newer snapshot.
  1885. if err == raft.ErrSnapOutOfDate {
  1886. return
  1887. }
  1888. if lg != nil {
  1889. lg.Panic("failed to create snapshot", zap.Error(err))
  1890. } else {
  1891. plog.Panicf("unexpected create snapshot error %v", err)
  1892. }
  1893. }
  1894. // SaveSnap saves the snapshot and releases the locked wal files
  1895. // to the snapshot index.
  1896. if err = s.r.storage.SaveSnap(snap); err != nil {
  1897. if lg != nil {
  1898. lg.Panic("failed to save snapshot", zap.Error(err))
  1899. } else {
  1900. plog.Fatalf("save snapshot error: %v", err)
  1901. }
  1902. }
  1903. if lg != nil {
  1904. lg.Info(
  1905. "saved snapshot",
  1906. zap.Uint64("snapshot-index", snap.Metadata.Index),
  1907. )
  1908. } else {
  1909. plog.Infof("saved snapshot at index %d", snap.Metadata.Index)
  1910. }
  1911. // When sending a snapshot, etcd will pause compaction.
  1912. // After receives a snapshot, the slow follower needs to get all the entries right after
  1913. // the snapshot sent to catch up. If we do not pause compaction, the log entries right after
  1914. // the snapshot sent might already be compacted. It happens when the snapshot takes long time
  1915. // to send and save. Pausing compaction avoids triggering a snapshot sending cycle.
  1916. if atomic.LoadInt64(&s.inflightSnapshots) != 0 {
  1917. if lg != nil {
  1918. lg.Info("skip compaction since there is an inflight snapshot")
  1919. } else {
  1920. plog.Infof("skip compaction since there is an inflight snapshot")
  1921. }
  1922. return
  1923. }
  1924. // keep some in memory log entries for slow followers.
  1925. compacti := uint64(1)
  1926. if snapi > s.Cfg.SnapshotCatchUpEntries {
  1927. compacti = snapi - s.Cfg.SnapshotCatchUpEntries
  1928. }
  1929. err = s.r.raftStorage.Compact(compacti)
  1930. if err != nil {
  1931. // the compaction was done asynchronously with the progress of raft.
  1932. // raft log might already been compact.
  1933. if err == raft.ErrCompacted {
  1934. return
  1935. }
  1936. if lg != nil {
  1937. lg.Panic("failed to compact", zap.Error(err))
  1938. } else {
  1939. plog.Panicf("unexpected compaction error %v", err)
  1940. }
  1941. }
  1942. if lg != nil {
  1943. lg.Info(
  1944. "compacted Raft logs",
  1945. zap.Uint64("compact-index", compacti),
  1946. )
  1947. } else {
  1948. plog.Infof("compacted raft log at %d", compacti)
  1949. }
  1950. })
  1951. }
  1952. // CutPeer drops messages to the specified peer.
  1953. func (s *EtcdServer) CutPeer(id types.ID) {
  1954. tr, ok := s.r.transport.(*rafthttp.Transport)
  1955. if ok {
  1956. tr.CutPeer(id)
  1957. }
  1958. }
  1959. // MendPeer recovers the message dropping behavior of the given peer.
  1960. func (s *EtcdServer) MendPeer(id types.ID) {
  1961. tr, ok := s.r.transport.(*rafthttp.Transport)
  1962. if ok {
  1963. tr.MendPeer(id)
  1964. }
  1965. }
  1966. func (s *EtcdServer) PauseSending() { s.r.pauseSending() }
  1967. func (s *EtcdServer) ResumeSending() { s.r.resumeSending() }
  1968. func (s *EtcdServer) ClusterVersion() *semver.Version {
  1969. if s.cluster == nil {
  1970. return nil
  1971. }
  1972. return s.cluster.Version()
  1973. }
  1974. // monitorVersions checks the member's version every monitorVersionInterval.
  1975. // It updates the cluster version if all members agrees on a higher one.
  1976. // It prints out log if there is a member with a higher version than the
  1977. // local version.
  1978. func (s *EtcdServer) monitorVersions() {
  1979. for {
  1980. select {
  1981. case <-s.forceVersionC:
  1982. case <-time.After(monitorVersionInterval):
  1983. case <-s.stopping:
  1984. return
  1985. }
  1986. if s.Leader() != s.ID() {
  1987. continue
  1988. }
  1989. v := decideClusterVersion(s.getLogger(), getVersions(s.getLogger(), s.cluster, s.id, s.peerRt))
  1990. if v != nil {
  1991. // only keep major.minor version for comparison
  1992. v = &semver.Version{
  1993. Major: v.Major,
  1994. Minor: v.Minor,
  1995. }
  1996. }
  1997. // if the current version is nil:
  1998. // 1. use the decided version if possible
  1999. // 2. or use the min cluster version
  2000. if s.cluster.Version() == nil {
  2001. verStr := version.MinClusterVersion
  2002. if v != nil {
  2003. verStr = v.String()
  2004. }
  2005. s.goAttach(func() { s.updateClusterVersion(verStr) })
  2006. continue
  2007. }
  2008. // update cluster version only if the decided version is greater than
  2009. // the current cluster version
  2010. if v != nil && s.cluster.Version().LessThan(*v) {
  2011. s.goAttach(func() { s.updateClusterVersion(v.String()) })
  2012. }
  2013. }
  2014. }
  2015. func (s *EtcdServer) updateClusterVersion(ver string) {
  2016. lg := s.getLogger()
  2017. if s.cluster.Version() == nil {
  2018. if lg != nil {
  2019. lg.Info(
  2020. "setting up initial cluster version",
  2021. zap.String("cluster-version", version.Cluster(ver)),
  2022. )
  2023. } else {
  2024. plog.Infof("setting up the initial cluster version to %s", version.Cluster(ver))
  2025. }
  2026. } else {
  2027. if lg != nil {
  2028. lg.Info(
  2029. "updating cluster version",
  2030. zap.String("from", version.Cluster(s.cluster.Version().String())),
  2031. zap.String("to", version.Cluster(ver)),
  2032. )
  2033. } else {
  2034. plog.Infof("updating the cluster version from %s to %s", version.Cluster(s.cluster.Version().String()), version.Cluster(ver))
  2035. }
  2036. }
  2037. req := pb.Request{
  2038. Method: "PUT",
  2039. Path: membership.StoreClusterVersionKey(),
  2040. Val: ver,
  2041. }
  2042. ctx, cancel := context.WithTimeout(s.ctx, s.Cfg.ReqTimeout())
  2043. _, err := s.Do(ctx, req)
  2044. cancel()
  2045. switch err {
  2046. case nil:
  2047. if lg != nil {
  2048. lg.Info("cluster version is updated", zap.String("cluster-version", version.Cluster(ver)))
  2049. }
  2050. return
  2051. case ErrStopped:
  2052. if lg != nil {
  2053. lg.Warn("aborting cluster version update; server is stopped", zap.Error(err))
  2054. } else {
  2055. plog.Infof("aborting update cluster version because server is stopped")
  2056. }
  2057. return
  2058. default:
  2059. if lg != nil {
  2060. lg.Warn("failed to update cluster version", zap.Error(err))
  2061. } else {
  2062. plog.Errorf("error updating cluster version (%v)", err)
  2063. }
  2064. }
  2065. }
  2066. func (s *EtcdServer) parseProposeCtxErr(err error, start time.Time) error {
  2067. switch err {
  2068. case context.Canceled:
  2069. return ErrCanceled
  2070. case context.DeadlineExceeded:
  2071. s.leadTimeMu.RLock()
  2072. curLeadElected := s.leadElectedTime
  2073. s.leadTimeMu.RUnlock()
  2074. prevLeadLost := curLeadElected.Add(-2 * time.Duration(s.Cfg.ElectionTicks) * time.Duration(s.Cfg.TickMs) * time.Millisecond)
  2075. if start.After(prevLeadLost) && start.Before(curLeadElected) {
  2076. return ErrTimeoutDueToLeaderFail
  2077. }
  2078. lead := types.ID(s.getLead())
  2079. switch lead {
  2080. case types.ID(raft.None):
  2081. // TODO: return error to specify it happens because the cluster does not have leader now
  2082. case s.ID():
  2083. if !isConnectedToQuorumSince(s.r.transport, start, s.ID(), s.cluster.Members()) {
  2084. return ErrTimeoutDueToConnectionLost
  2085. }
  2086. default:
  2087. if !isConnectedSince(s.r.transport, start, lead) {
  2088. return ErrTimeoutDueToConnectionLost
  2089. }
  2090. }
  2091. return ErrTimeout
  2092. default:
  2093. return err
  2094. }
  2095. }
  2096. func (s *EtcdServer) KV() mvcc.ConsistentWatchableKV { return s.kv }
  2097. func (s *EtcdServer) Backend() backend.Backend {
  2098. s.bemu.Lock()
  2099. defer s.bemu.Unlock()
  2100. return s.be
  2101. }
  2102. func (s *EtcdServer) AuthStore() auth.AuthStore { return s.authStore }
  2103. func (s *EtcdServer) restoreAlarms() error {
  2104. s.applyV3 = s.newApplierV3()
  2105. as, err := v3alarm.NewAlarmStore(s)
  2106. if err != nil {
  2107. return err
  2108. }
  2109. s.alarmStore = as
  2110. if len(as.Get(pb.AlarmType_NOSPACE)) > 0 {
  2111. s.applyV3 = newApplierV3Capped(s.applyV3)
  2112. }
  2113. if len(as.Get(pb.AlarmType_CORRUPT)) > 0 {
  2114. s.applyV3 = newApplierV3Corrupt(s.applyV3)
  2115. }
  2116. return nil
  2117. }
  2118. // goAttach creates a goroutine on a given function and tracks it using
  2119. // the etcdserver waitgroup.
  2120. func (s *EtcdServer) goAttach(f func()) {
  2121. s.wgMu.RLock() // this blocks with ongoing close(s.stopping)
  2122. defer s.wgMu.RUnlock()
  2123. select {
  2124. case <-s.stopping:
  2125. if lg := s.getLogger(); lg != nil {
  2126. lg.Warn("server has stopped; skipping goAttach")
  2127. } else {
  2128. plog.Warning("server has stopped (skipping goAttach)")
  2129. }
  2130. return
  2131. default:
  2132. }
  2133. // now safe to add since waitgroup wait has not started yet
  2134. s.wg.Add(1)
  2135. go func() {
  2136. defer s.wg.Done()
  2137. f()
  2138. }()
  2139. }
  2140. func (s *EtcdServer) Alarms() []*pb.AlarmMember {
  2141. return s.alarmStore.Get(pb.AlarmType_NONE)
  2142. }
  2143. func (s *EtcdServer) Logger() *zap.Logger {
  2144. return s.lg
  2145. }