server.go 66 KB

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