server.go 65 KB

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