server.go 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021
  1. // Copyright 2015 CoreOS, Inc.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package etcdserver
  15. import (
  16. "encoding/json"
  17. "expvar"
  18. "fmt"
  19. "math/rand"
  20. "net/http"
  21. "path"
  22. "regexp"
  23. "sync/atomic"
  24. "time"
  25. "github.com/coreos/etcd/Godeps/_workspace/src/github.com/coreos/go-semver/semver"
  26. "github.com/coreos/etcd/Godeps/_workspace/src/github.com/coreos/pkg/capnslog"
  27. "github.com/coreos/etcd/Godeps/_workspace/src/golang.org/x/net/context"
  28. "github.com/coreos/etcd/discovery"
  29. "github.com/coreos/etcd/etcdserver/etcdhttp/httptypes"
  30. pb "github.com/coreos/etcd/etcdserver/etcdserverpb"
  31. "github.com/coreos/etcd/etcdserver/stats"
  32. "github.com/coreos/etcd/pkg/fileutil"
  33. "github.com/coreos/etcd/pkg/idutil"
  34. "github.com/coreos/etcd/pkg/pbutil"
  35. "github.com/coreos/etcd/pkg/runtime"
  36. "github.com/coreos/etcd/pkg/timeutil"
  37. "github.com/coreos/etcd/pkg/types"
  38. "github.com/coreos/etcd/pkg/wait"
  39. "github.com/coreos/etcd/raft"
  40. "github.com/coreos/etcd/raft/raftpb"
  41. "github.com/coreos/etcd/rafthttp"
  42. "github.com/coreos/etcd/snap"
  43. "github.com/coreos/etcd/store"
  44. "github.com/coreos/etcd/version"
  45. "github.com/coreos/etcd/wal"
  46. )
  47. const (
  48. // owner can make/remove files inside the directory
  49. privateDirMode = 0700
  50. defaultSyncTimeout = time.Second
  51. DefaultSnapCount = 10000
  52. // TODO: calculate based on heartbeat interval
  53. defaultPublishRetryInterval = 5 * time.Second
  54. StoreClusterPrefix = "/0"
  55. StoreKeysPrefix = "/1"
  56. purgeFileInterval = 30 * time.Second
  57. monitorVersionInterval = 5 * time.Second
  58. versionUpdateTimeout = 1 * time.Second
  59. )
  60. var (
  61. plog = capnslog.NewPackageLogger("github.com/coreos/etcd", "etcdserver")
  62. storeMemberAttributeRegexp = regexp.MustCompile(path.Join(storeMembersPrefix, "[[:xdigit:]]{1,16}", attributesSuffix))
  63. )
  64. func init() {
  65. rand.Seed(time.Now().UnixNano())
  66. expvar.Publish(
  67. "file_descriptor_limit",
  68. expvar.Func(
  69. func() interface{} {
  70. n, _ := runtime.FDLimit()
  71. return n
  72. },
  73. ),
  74. )
  75. }
  76. type Response struct {
  77. Event *store.Event
  78. Watcher store.Watcher
  79. err error
  80. }
  81. type Server interface {
  82. // Start performs any initialization of the Server necessary for it to
  83. // begin serving requests. It must be called before Do or Process.
  84. // Start must be non-blocking; any long-running server functionality
  85. // should be implemented in goroutines.
  86. Start()
  87. // Stop terminates the Server and performs any necessary finalization.
  88. // Do and Process cannot be called after Stop has been invoked.
  89. Stop()
  90. // ID returns the ID of the Server.
  91. ID() types.ID
  92. // Leader returns the ID of the leader Server.
  93. Leader() types.ID
  94. // Do takes a request and attempts to fulfill it, returning a Response.
  95. Do(ctx context.Context, r pb.Request) (Response, error)
  96. // Process takes a raft message and applies it to the server's raft state
  97. // machine, respecting any timeout of the given context.
  98. Process(ctx context.Context, m raftpb.Message) error
  99. // AddMember attempts to add a member into the cluster. It will return
  100. // ErrIDRemoved if member ID is removed from the cluster, or return
  101. // ErrIDExists if member ID exists in the cluster.
  102. AddMember(ctx context.Context, memb Member) error
  103. // RemoveMember attempts to remove a member from the cluster. It will
  104. // return ErrIDRemoved if member ID is removed from the cluster, or return
  105. // ErrIDNotFound if member ID is not in the cluster.
  106. RemoveMember(ctx context.Context, id uint64) error
  107. // UpdateMember attempts to update a existing member in the cluster. It will
  108. // return ErrIDNotFound if the member ID does not exist.
  109. UpdateMember(ctx context.Context, updateMemb Member) error
  110. // ClusterVersion is the cluster-wide minimum major.minor version.
  111. // Cluster version is set to the min version that a etcd member is
  112. // compatible with when first bootstrap.
  113. //
  114. // ClusterVersion is nil until the cluster is bootstrapped (has a quorum).
  115. //
  116. // During a rolling upgrades, the ClusterVersion will be updated
  117. // automatically after a sync. (5 second by default)
  118. //
  119. // The API/raft component can utilize ClusterVersion to determine if
  120. // it can accept a client request or a raft RPC.
  121. // NOTE: ClusterVersion might be nil when etcd 2.1 works with etcd 2.0 and
  122. // the leader is etcd 2.0. etcd 2.0 leader will not update clusterVersion since
  123. // this feature is introduced post 2.0.
  124. ClusterVersion() *semver.Version
  125. }
  126. // EtcdServer is the production implementation of the Server interface
  127. type EtcdServer struct {
  128. // r must be the first element to keep 64-bit alignment for atomic
  129. // access to fields
  130. r raftNode
  131. cfg *ServerConfig
  132. snapCount uint64
  133. w wait.Wait
  134. stop chan struct{}
  135. done chan struct{}
  136. errorc chan error
  137. id types.ID
  138. attributes Attributes
  139. cluster *cluster
  140. store store.Store
  141. stats *stats.ServerStats
  142. lstats *stats.LeaderStats
  143. SyncTicker <-chan time.Time
  144. reqIDGen *idutil.Generator
  145. // forceVersionC is used to force the version monitor loop
  146. // to detect the cluster version immediately.
  147. forceVersionC chan struct{}
  148. }
  149. // NewServer creates a new EtcdServer from the supplied configuration. The
  150. // configuration is considered static for the lifetime of the EtcdServer.
  151. func NewServer(cfg *ServerConfig) (*EtcdServer, error) {
  152. st := store.New(StoreClusterPrefix, StoreKeysPrefix)
  153. var w *wal.WAL
  154. var n raft.Node
  155. var s *raft.MemoryStorage
  156. var id types.ID
  157. var cl *cluster
  158. // Run the migrations.
  159. dataVer, err := version.DetectDataDir(cfg.DataDir)
  160. if err != nil {
  161. return nil, err
  162. }
  163. if err := upgradeDataDir(cfg.DataDir, cfg.Name, dataVer); err != nil {
  164. return nil, err
  165. }
  166. haveWAL := wal.Exist(cfg.WALDir())
  167. ss := snap.New(cfg.SnapDir())
  168. var remotes []*Member
  169. switch {
  170. case !haveWAL && !cfg.NewCluster:
  171. if err := cfg.VerifyJoinExisting(); err != nil {
  172. return nil, err
  173. }
  174. cl, err = newClusterFromURLsMap(cfg.InitialClusterToken, cfg.InitialPeerURLsMap)
  175. if err != nil {
  176. return nil, err
  177. }
  178. existingCluster, err := GetClusterFromRemotePeers(getRemotePeerURLs(cl, cfg.Name), cfg.Transport)
  179. if err != nil {
  180. return nil, fmt.Errorf("cannot fetch cluster info from peer urls: %v", err)
  181. }
  182. if err := ValidateClusterAndAssignIDs(cl, existingCluster); err != nil {
  183. return nil, fmt.Errorf("error validating peerURLs %s: %v", existingCluster, err)
  184. }
  185. if !isCompatibleWithCluster(cl, cl.MemberByName(cfg.Name).ID, cfg.Transport) {
  186. return nil, fmt.Errorf("incomptible with current running cluster")
  187. }
  188. remotes = existingCluster.Members()
  189. cl.SetID(existingCluster.id)
  190. cl.SetStore(st)
  191. cfg.Print()
  192. id, n, s, w = startNode(cfg, cl, nil)
  193. case !haveWAL && cfg.NewCluster:
  194. if err := cfg.VerifyBootstrap(); err != nil {
  195. return nil, err
  196. }
  197. cl, err = newClusterFromURLsMap(cfg.InitialClusterToken, cfg.InitialPeerURLsMap)
  198. if err != nil {
  199. return nil, err
  200. }
  201. m := cl.MemberByName(cfg.Name)
  202. if isMemberBootstrapped(cl, cfg.Name, cfg.Transport) {
  203. return nil, fmt.Errorf("member %s has already been bootstrapped", m.ID)
  204. }
  205. if cfg.ShouldDiscover() {
  206. str, err := discovery.JoinCluster(cfg.DiscoveryURL, cfg.DiscoveryProxy, m.ID, cfg.InitialPeerURLsMap.String())
  207. if err != nil {
  208. return nil, err
  209. }
  210. urlsmap, err := types.NewURLsMap(str)
  211. if err != nil {
  212. return nil, err
  213. }
  214. if checkDuplicateURL(urlsmap) {
  215. return nil, fmt.Errorf("discovery cluster %s has duplicate url", urlsmap)
  216. }
  217. if cl, err = newClusterFromURLsMap(cfg.InitialClusterToken, urlsmap); err != nil {
  218. return nil, err
  219. }
  220. }
  221. cl.SetStore(st)
  222. cfg.PrintWithInitial()
  223. id, n, s, w = startNode(cfg, cl, cl.MemberIDs())
  224. case haveWAL:
  225. if err := fileutil.IsDirWriteable(cfg.DataDir); err != nil {
  226. return nil, fmt.Errorf("cannot write to data directory: %v", err)
  227. }
  228. if err := fileutil.IsDirWriteable(cfg.MemberDir()); err != nil {
  229. return nil, fmt.Errorf("cannot write to member directory: %v", err)
  230. }
  231. if cfg.ShouldDiscover() {
  232. plog.Warningf("discovery token ignored since a cluster has already been initialized. Valid log found at %q", cfg.WALDir())
  233. }
  234. snapshot, err := ss.Load()
  235. if err != nil && err != snap.ErrNoSnapshot {
  236. return nil, err
  237. }
  238. if snapshot != nil {
  239. if err := st.Recovery(snapshot.Data); err != nil {
  240. plog.Panicf("recovered store from snapshot error: %v", err)
  241. }
  242. plog.Infof("recovered store from snapshot at index %d", snapshot.Metadata.Index)
  243. }
  244. cfg.Print()
  245. if snapshot != nil {
  246. plog.Infof("loaded cluster information from store: %s", cl)
  247. }
  248. if !cfg.ForceNewCluster {
  249. id, cl, n, s, w = restartNode(cfg, snapshot)
  250. } else {
  251. id, cl, n, s, w = restartAsStandaloneNode(cfg, snapshot)
  252. }
  253. cl.SetStore(st)
  254. cl.Recover()
  255. default:
  256. return nil, fmt.Errorf("unsupported bootstrap config")
  257. }
  258. sstats := &stats.ServerStats{
  259. Name: cfg.Name,
  260. ID: id.String(),
  261. }
  262. sstats.Initialize()
  263. lstats := stats.NewLeaderStats(id.String())
  264. srv := &EtcdServer{
  265. cfg: cfg,
  266. snapCount: cfg.SnapCount,
  267. errorc: make(chan error, 1),
  268. store: st,
  269. r: raftNode{
  270. Node: n,
  271. ticker: time.Tick(time.Duration(cfg.TickMs) * time.Millisecond),
  272. raftStorage: s,
  273. storage: NewStorage(w, ss),
  274. },
  275. id: id,
  276. attributes: Attributes{Name: cfg.Name, ClientURLs: cfg.ClientURLs.StringSlice()},
  277. cluster: cl,
  278. stats: sstats,
  279. lstats: lstats,
  280. SyncTicker: time.Tick(500 * time.Millisecond),
  281. reqIDGen: idutil.NewGenerator(uint8(id), time.Now()),
  282. forceVersionC: make(chan struct{}),
  283. }
  284. // TODO: move transport initialization near the definition of remote
  285. tr := rafthttp.NewTransporter(cfg.Transport, id, cl.ID(), srv, srv.errorc, sstats, lstats)
  286. // add all remotes into transport
  287. for _, m := range remotes {
  288. if m.ID != id {
  289. tr.AddRemote(m.ID, m.PeerURLs)
  290. }
  291. }
  292. for _, m := range cl.Members() {
  293. if m.ID != id {
  294. tr.AddPeer(m.ID, m.PeerURLs)
  295. }
  296. }
  297. srv.r.transport = tr
  298. return srv, nil
  299. }
  300. // Start prepares and starts server in a new goroutine. It is no longer safe to
  301. // modify a server's fields after it has been sent to Start.
  302. // It also starts a goroutine to publish its server information.
  303. func (s *EtcdServer) Start() {
  304. s.start()
  305. go s.publish(defaultPublishRetryInterval)
  306. go s.purgeFile()
  307. go monitorFileDescriptor(s.done)
  308. go s.monitorVersions()
  309. }
  310. // start prepares and starts server in a new goroutine. It is no longer safe to
  311. // modify a server's fields after it has been sent to Start.
  312. // This function is just used for testing.
  313. func (s *EtcdServer) start() {
  314. if s.snapCount == 0 {
  315. plog.Infof("set snapshot count to default %d", DefaultSnapCount)
  316. s.snapCount = DefaultSnapCount
  317. }
  318. s.w = wait.New()
  319. s.done = make(chan struct{})
  320. s.stop = make(chan struct{})
  321. if s.ClusterVersion() != nil {
  322. plog.Infof("starting server... [version: %v, cluster version: %v]", version.Version, s.ClusterVersion())
  323. } else {
  324. plog.Infof("starting server... [version: %v, cluster version: to_be_decided]", version.Version)
  325. }
  326. // TODO: if this is an empty log, writes all peer infos
  327. // into the first entry
  328. go s.run()
  329. }
  330. func (s *EtcdServer) purgeFile() {
  331. var serrc, werrc <-chan error
  332. if s.cfg.MaxSnapFiles > 0 {
  333. serrc = fileutil.PurgeFile(s.cfg.SnapDir(), "snap", s.cfg.MaxSnapFiles, purgeFileInterval, s.done)
  334. }
  335. if s.cfg.MaxWALFiles > 0 {
  336. werrc = fileutil.PurgeFile(s.cfg.WALDir(), "wal", s.cfg.MaxWALFiles, purgeFileInterval, s.done)
  337. }
  338. select {
  339. case e := <-werrc:
  340. plog.Fatalf("failed to purge wal file %v", e)
  341. case e := <-serrc:
  342. plog.Fatalf("failed to purge snap file %v", e)
  343. case <-s.done:
  344. return
  345. }
  346. }
  347. func (s *EtcdServer) ID() types.ID { return s.id }
  348. func (s *EtcdServer) Cluster() Cluster { return s.cluster }
  349. func (s *EtcdServer) RaftHandler() http.Handler { return s.r.transport.Handler() }
  350. func (s *EtcdServer) Process(ctx context.Context, m raftpb.Message) error {
  351. if s.cluster.IsIDRemoved(types.ID(m.From)) {
  352. plog.Warningf("reject message from removed member %s", types.ID(m.From).String())
  353. return httptypes.NewHTTPError(http.StatusForbidden, "cannot process message from removed member")
  354. }
  355. if m.Type == raftpb.MsgApp {
  356. s.stats.RecvAppendReq(types.ID(m.From).String(), m.Size())
  357. }
  358. return s.r.Step(ctx, m)
  359. }
  360. func (s *EtcdServer) IsIDRemoved(id uint64) bool { return s.cluster.IsIDRemoved(types.ID(id)) }
  361. func (s *EtcdServer) ReportUnreachable(id uint64) { s.r.ReportUnreachable(id) }
  362. func (s *EtcdServer) ReportSnapshot(id uint64, status raft.SnapshotStatus) {
  363. s.r.ReportSnapshot(id, status)
  364. }
  365. func (s *EtcdServer) run() {
  366. snap, err := s.r.raftStorage.Snapshot()
  367. if err != nil {
  368. plog.Panicf("get snapshot from raft storage error: %v", err)
  369. }
  370. confState := snap.Metadata.ConfState
  371. snapi := snap.Metadata.Index
  372. appliedi := snapi
  373. // TODO: get rid of the raft initialization in etcd server
  374. s.r.s = s
  375. s.r.applyc = make(chan apply)
  376. s.r.stopped = make(chan struct{})
  377. s.r.done = make(chan struct{})
  378. go s.r.run()
  379. defer func() {
  380. s.r.stopped <- struct{}{}
  381. <-s.r.done
  382. close(s.done)
  383. }()
  384. var shouldstop bool
  385. for {
  386. select {
  387. case apply := <-s.r.apply():
  388. // apply snapshot
  389. if !raft.IsEmptySnap(apply.snapshot) {
  390. if apply.snapshot.Metadata.Index <= appliedi {
  391. plog.Panicf("snapshot index [%d] should > appliedi[%d] + 1",
  392. apply.snapshot.Metadata.Index, appliedi)
  393. }
  394. if err := s.store.Recovery(apply.snapshot.Data); err != nil {
  395. plog.Panicf("recovery store error: %v", err)
  396. }
  397. s.cluster.Recover()
  398. // recover raft transport
  399. s.r.transport.RemoveAllPeers()
  400. for _, m := range s.cluster.Members() {
  401. if m.ID == s.ID() {
  402. continue
  403. }
  404. s.r.transport.AddPeer(m.ID, m.PeerURLs)
  405. }
  406. appliedi = apply.snapshot.Metadata.Index
  407. snapi = appliedi
  408. confState = apply.snapshot.Metadata.ConfState
  409. plog.Infof("recovered from incoming snapshot at index %d", snapi)
  410. }
  411. // apply entries
  412. if len(apply.entries) != 0 {
  413. firsti := apply.entries[0].Index
  414. if firsti > appliedi+1 {
  415. plog.Panicf("first index of committed entry[%d] should <= appliedi[%d] + 1", firsti, appliedi)
  416. }
  417. var ents []raftpb.Entry
  418. if appliedi+1-firsti < uint64(len(apply.entries)) {
  419. ents = apply.entries[appliedi+1-firsti:]
  420. }
  421. if appliedi, shouldstop = s.apply(ents, &confState); shouldstop {
  422. go s.stopWithDelay(10*100*time.Millisecond, fmt.Errorf("the member has been permanently removed from the cluster"))
  423. }
  424. }
  425. // wait for the raft routine to finish the disk writes before triggering a
  426. // snapshot. or applied index might be greater than the last index in raft
  427. // storage, since the raft routine might be slower than apply routine.
  428. apply.done <- struct{}{}
  429. // trigger snapshot
  430. if appliedi-snapi > s.snapCount {
  431. plog.Infof("start to snapshot (applied: %d, lastsnap: %d)", appliedi, snapi)
  432. s.snapshot(appliedi, confState)
  433. snapi = appliedi
  434. }
  435. case err := <-s.errorc:
  436. plog.Errorf("%s", err)
  437. plog.Infof("the data-dir used by this member must be removed.")
  438. return
  439. case <-s.stop:
  440. return
  441. }
  442. }
  443. }
  444. // Stop stops the server gracefully, and shuts down the running goroutine.
  445. // Stop should be called after a Start(s), otherwise it will block forever.
  446. func (s *EtcdServer) Stop() {
  447. select {
  448. case s.stop <- struct{}{}:
  449. case <-s.done:
  450. return
  451. }
  452. <-s.done
  453. }
  454. func (s *EtcdServer) stopWithDelay(d time.Duration, err error) {
  455. time.Sleep(d)
  456. select {
  457. case s.errorc <- err:
  458. default:
  459. }
  460. }
  461. // StopNotify returns a channel that receives a empty struct
  462. // when the server is stopped.
  463. func (s *EtcdServer) StopNotify() <-chan struct{} { return s.done }
  464. // Do interprets r and performs an operation on s.store according to r.Method
  465. // and other fields. If r.Method is "POST", "PUT", "DELETE", or a "GET" with
  466. // Quorum == true, r will be sent through consensus before performing its
  467. // respective operation. Do will block until an action is performed or there is
  468. // an error.
  469. func (s *EtcdServer) Do(ctx context.Context, r pb.Request) (Response, error) {
  470. r.ID = s.reqIDGen.Next()
  471. if r.Method == "GET" && r.Quorum {
  472. r.Method = "QGET"
  473. }
  474. switch r.Method {
  475. case "POST", "PUT", "DELETE", "QGET":
  476. data, err := r.Marshal()
  477. if err != nil {
  478. return Response{}, err
  479. }
  480. ch := s.w.Register(r.ID)
  481. // TODO: benchmark the cost of time.Now()
  482. // might be sampling?
  483. start := time.Now()
  484. s.r.Propose(ctx, data)
  485. proposePending.Inc()
  486. defer proposePending.Dec()
  487. select {
  488. case x := <-ch:
  489. proposeDurations.Observe(float64(time.Since(start).Nanoseconds() / int64(time.Millisecond)))
  490. resp := x.(Response)
  491. return resp, resp.err
  492. case <-ctx.Done():
  493. proposeFailed.Inc()
  494. s.w.Trigger(r.ID, nil) // GC wait
  495. return Response{}, s.parseProposeCtxErr(ctx.Err(), start)
  496. case <-s.done:
  497. return Response{}, ErrStopped
  498. }
  499. case "GET":
  500. switch {
  501. case r.Wait:
  502. wc, err := s.store.Watch(r.Path, r.Recursive, r.Stream, r.Since)
  503. if err != nil {
  504. return Response{}, err
  505. }
  506. return Response{Watcher: wc}, nil
  507. default:
  508. ev, err := s.store.Get(r.Path, r.Recursive, r.Sorted)
  509. if err != nil {
  510. return Response{}, err
  511. }
  512. return Response{Event: ev}, nil
  513. }
  514. case "HEAD":
  515. ev, err := s.store.Get(r.Path, r.Recursive, r.Sorted)
  516. if err != nil {
  517. return Response{}, err
  518. }
  519. return Response{Event: ev}, nil
  520. default:
  521. return Response{}, ErrUnknownMethod
  522. }
  523. }
  524. func (s *EtcdServer) SelfStats() []byte { return s.stats.JSON() }
  525. func (s *EtcdServer) LeaderStats() []byte {
  526. lead := atomic.LoadUint64(&s.r.lead)
  527. if lead != uint64(s.id) {
  528. return nil
  529. }
  530. return s.lstats.JSON()
  531. }
  532. func (s *EtcdServer) StoreStats() []byte { return s.store.JsonStats() }
  533. func (s *EtcdServer) AddMember(ctx context.Context, memb Member) error {
  534. // TODO: move Member to protobuf type
  535. b, err := json.Marshal(memb)
  536. if err != nil {
  537. return err
  538. }
  539. cc := raftpb.ConfChange{
  540. Type: raftpb.ConfChangeAddNode,
  541. NodeID: uint64(memb.ID),
  542. Context: b,
  543. }
  544. return s.configure(ctx, cc)
  545. }
  546. func (s *EtcdServer) RemoveMember(ctx context.Context, id uint64) error {
  547. cc := raftpb.ConfChange{
  548. Type: raftpb.ConfChangeRemoveNode,
  549. NodeID: id,
  550. }
  551. return s.configure(ctx, cc)
  552. }
  553. func (s *EtcdServer) UpdateMember(ctx context.Context, memb Member) error {
  554. b, err := json.Marshal(memb)
  555. if err != nil {
  556. return err
  557. }
  558. cc := raftpb.ConfChange{
  559. Type: raftpb.ConfChangeUpdateNode,
  560. NodeID: uint64(memb.ID),
  561. Context: b,
  562. }
  563. return s.configure(ctx, cc)
  564. }
  565. // Implement the RaftTimer interface
  566. func (s *EtcdServer) Index() uint64 { return atomic.LoadUint64(&s.r.index) }
  567. func (s *EtcdServer) Term() uint64 { return atomic.LoadUint64(&s.r.term) }
  568. // Only for testing purpose
  569. // TODO: add Raft server interface to expose raft related info:
  570. // Index, Term, Lead, Committed, Applied, LastIndex, etc.
  571. func (s *EtcdServer) Lead() uint64 { return atomic.LoadUint64(&s.r.lead) }
  572. func (s *EtcdServer) Leader() types.ID { return types.ID(s.Lead()) }
  573. // configure sends a configuration change through consensus and
  574. // then waits for it to be applied to the server. It
  575. // will block until the change is performed or there is an error.
  576. func (s *EtcdServer) configure(ctx context.Context, cc raftpb.ConfChange) error {
  577. cc.ID = s.reqIDGen.Next()
  578. ch := s.w.Register(cc.ID)
  579. start := time.Now()
  580. if err := s.r.ProposeConfChange(ctx, cc); err != nil {
  581. s.w.Trigger(cc.ID, nil)
  582. return err
  583. }
  584. select {
  585. case x := <-ch:
  586. if err, ok := x.(error); ok {
  587. return err
  588. }
  589. if x != nil {
  590. plog.Panicf("return type should always be error")
  591. }
  592. return nil
  593. case <-ctx.Done():
  594. s.w.Trigger(cc.ID, nil) // GC wait
  595. return s.parseProposeCtxErr(ctx.Err(), start)
  596. case <-s.done:
  597. return ErrStopped
  598. }
  599. }
  600. // sync proposes a SYNC request and is non-blocking.
  601. // This makes no guarantee that the request will be proposed or performed.
  602. // The request will be cancelled after the given timeout.
  603. func (s *EtcdServer) sync(timeout time.Duration) {
  604. ctx, cancel := context.WithTimeout(context.Background(), timeout)
  605. req := pb.Request{
  606. Method: "SYNC",
  607. ID: s.reqIDGen.Next(),
  608. Time: time.Now().UnixNano(),
  609. }
  610. data := pbutil.MustMarshal(&req)
  611. // There is no promise that node has leader when do SYNC request,
  612. // so it uses goroutine to propose.
  613. go func() {
  614. s.r.Propose(ctx, data)
  615. cancel()
  616. }()
  617. }
  618. // publish registers server information into the cluster. The information
  619. // is the JSON representation of this server's member struct, updated with the
  620. // static clientURLs of the server.
  621. // The function keeps attempting to register until it succeeds,
  622. // or its server is stopped.
  623. func (s *EtcdServer) publish(retryInterval time.Duration) {
  624. b, err := json.Marshal(s.attributes)
  625. if err != nil {
  626. plog.Panicf("json marshal error: %v", err)
  627. return
  628. }
  629. req := pb.Request{
  630. Method: "PUT",
  631. Path: MemberAttributesStorePath(s.id),
  632. Val: string(b),
  633. }
  634. for {
  635. ctx, cancel := context.WithTimeout(context.Background(), retryInterval)
  636. _, err := s.Do(ctx, req)
  637. cancel()
  638. switch err {
  639. case nil:
  640. plog.Infof("published %+v to cluster %s", s.attributes, s.cluster.ID())
  641. return
  642. case ErrStopped:
  643. plog.Infof("aborting publish because server is stopped")
  644. return
  645. default:
  646. plog.Errorf("publish error: %v", err)
  647. }
  648. }
  649. }
  650. func (s *EtcdServer) send(ms []raftpb.Message) {
  651. for i, _ := range ms {
  652. if s.cluster.IsIDRemoved(types.ID(ms[i].To)) {
  653. ms[i].To = 0
  654. }
  655. }
  656. s.r.transport.Send(ms)
  657. }
  658. // apply takes entries received from Raft (after it has been committed) and
  659. // applies them to the current state of the EtcdServer.
  660. // The given entries should not be empty.
  661. func (s *EtcdServer) apply(es []raftpb.Entry, confState *raftpb.ConfState) (uint64, bool) {
  662. var applied uint64
  663. var shouldstop bool
  664. var err error
  665. for i := range es {
  666. e := es[i]
  667. switch e.Type {
  668. case raftpb.EntryNormal:
  669. // raft state machine may generate noop entry when leader confirmation.
  670. // skip it in advance to avoid some potential bug in the future
  671. if len(e.Data) == 0 {
  672. select {
  673. case s.forceVersionC <- struct{}{}:
  674. default:
  675. }
  676. break
  677. }
  678. var r pb.Request
  679. pbutil.MustUnmarshal(&r, e.Data)
  680. s.w.Trigger(r.ID, s.applyRequest(r))
  681. case raftpb.EntryConfChange:
  682. var cc raftpb.ConfChange
  683. pbutil.MustUnmarshal(&cc, e.Data)
  684. shouldstop, err = s.applyConfChange(cc, confState)
  685. s.w.Trigger(cc.ID, err)
  686. default:
  687. plog.Panicf("entry type should be either EntryNormal or EntryConfChange")
  688. }
  689. atomic.StoreUint64(&s.r.index, e.Index)
  690. atomic.StoreUint64(&s.r.term, e.Term)
  691. applied = e.Index
  692. }
  693. return applied, shouldstop
  694. }
  695. // applyRequest interprets r as a call to store.X and returns a Response interpreted
  696. // from store.Event
  697. func (s *EtcdServer) applyRequest(r pb.Request) Response {
  698. f := func(ev *store.Event, err error) Response {
  699. return Response{Event: ev, err: err}
  700. }
  701. expr := timeutil.UnixNanoToTime(r.Expiration)
  702. switch r.Method {
  703. case "POST":
  704. return f(s.store.Create(r.Path, r.Dir, r.Val, true, expr))
  705. case "PUT":
  706. exists, existsSet := pbutil.GetBool(r.PrevExist)
  707. switch {
  708. case existsSet:
  709. if exists {
  710. if r.PrevIndex == 0 && r.PrevValue == "" {
  711. return f(s.store.Update(r.Path, r.Val, expr))
  712. } else {
  713. return f(s.store.CompareAndSwap(r.Path, r.PrevValue, r.PrevIndex, r.Val, expr))
  714. }
  715. }
  716. return f(s.store.Create(r.Path, r.Dir, r.Val, false, expr))
  717. case r.PrevIndex > 0 || r.PrevValue != "":
  718. return f(s.store.CompareAndSwap(r.Path, r.PrevValue, r.PrevIndex, r.Val, expr))
  719. default:
  720. // TODO (yicheng): cluster should be the owner of cluster prefix store
  721. // we should not modify cluster store here.
  722. if storeMemberAttributeRegexp.MatchString(r.Path) {
  723. id := mustParseMemberIDFromKey(path.Dir(r.Path))
  724. var attr Attributes
  725. if err := json.Unmarshal([]byte(r.Val), &attr); err != nil {
  726. plog.Panicf("unmarshal %s should never fail: %v", r.Val, err)
  727. }
  728. s.cluster.UpdateAttributes(id, attr)
  729. }
  730. if r.Path == path.Join(StoreClusterPrefix, "version") {
  731. s.cluster.SetVersion(semver.Must(semver.NewVersion(r.Val)))
  732. }
  733. return f(s.store.Set(r.Path, r.Dir, r.Val, expr))
  734. }
  735. case "DELETE":
  736. switch {
  737. case r.PrevIndex > 0 || r.PrevValue != "":
  738. return f(s.store.CompareAndDelete(r.Path, r.PrevValue, r.PrevIndex))
  739. default:
  740. return f(s.store.Delete(r.Path, r.Dir, r.Recursive))
  741. }
  742. case "QGET":
  743. return f(s.store.Get(r.Path, r.Recursive, r.Sorted))
  744. case "SYNC":
  745. s.store.DeleteExpiredKeys(time.Unix(0, r.Time))
  746. return Response{}
  747. default:
  748. // This should never be reached, but just in case:
  749. return Response{err: ErrUnknownMethod}
  750. }
  751. }
  752. // applyConfChange applies a ConfChange to the server. It is only
  753. // invoked with a ConfChange that has already passed through Raft
  754. func (s *EtcdServer) applyConfChange(cc raftpb.ConfChange, confState *raftpb.ConfState) (bool, error) {
  755. if err := s.cluster.ValidateConfigurationChange(cc); err != nil {
  756. cc.NodeID = raft.None
  757. s.r.ApplyConfChange(cc)
  758. return false, err
  759. }
  760. *confState = *s.r.ApplyConfChange(cc)
  761. switch cc.Type {
  762. case raftpb.ConfChangeAddNode:
  763. m := new(Member)
  764. if err := json.Unmarshal(cc.Context, m); err != nil {
  765. plog.Panicf("unmarshal member should never fail: %v", err)
  766. }
  767. if cc.NodeID != uint64(m.ID) {
  768. plog.Panicf("nodeID should always be equal to member ID")
  769. }
  770. s.cluster.AddMember(m)
  771. if m.ID == s.id {
  772. plog.Noticef("added local member %s %v to cluster %s", m.ID, m.PeerURLs, s.cluster.ID())
  773. } else {
  774. s.r.transport.AddPeer(m.ID, m.PeerURLs)
  775. plog.Noticef("added member %s %v to cluster %s", m.ID, m.PeerURLs, s.cluster.ID())
  776. }
  777. case raftpb.ConfChangeRemoveNode:
  778. id := types.ID(cc.NodeID)
  779. s.cluster.RemoveMember(id)
  780. if id == s.id {
  781. return true, nil
  782. } else {
  783. s.r.transport.RemovePeer(id)
  784. plog.Noticef("removed member %s from cluster %s", id, s.cluster.ID())
  785. }
  786. case raftpb.ConfChangeUpdateNode:
  787. m := new(Member)
  788. if err := json.Unmarshal(cc.Context, m); err != nil {
  789. plog.Panicf("unmarshal member should never fail: %v", err)
  790. }
  791. if cc.NodeID != uint64(m.ID) {
  792. plog.Panicf("nodeID should always be equal to member ID")
  793. }
  794. s.cluster.UpdateRaftAttributes(m.ID, m.RaftAttributes)
  795. if m.ID == s.id {
  796. plog.Noticef("update local member %s %v in cluster %s", m.ID, m.PeerURLs, s.cluster.ID())
  797. } else {
  798. s.r.transport.UpdatePeer(m.ID, m.PeerURLs)
  799. plog.Noticef("update member %s %v in cluster %s", m.ID, m.PeerURLs, s.cluster.ID())
  800. }
  801. }
  802. return false, nil
  803. }
  804. // TODO: non-blocking snapshot
  805. func (s *EtcdServer) snapshot(snapi uint64, confState raftpb.ConfState) {
  806. clone := s.store.Clone()
  807. go func() {
  808. d, err := clone.SaveNoCopy()
  809. // TODO: current store will never fail to do a snapshot
  810. // what should we do if the store might fail?
  811. if err != nil {
  812. plog.Panicf("store save should never fail: %v", err)
  813. }
  814. snap, err := s.r.raftStorage.CreateSnapshot(snapi, &confState, d)
  815. if err != nil {
  816. // the snapshot was done asynchronously with the progress of raft.
  817. // raft might have already got a newer snapshot.
  818. if err == raft.ErrSnapOutOfDate {
  819. return
  820. }
  821. plog.Panicf("unexpected create snapshot error %v", err)
  822. }
  823. if err := s.r.storage.SaveSnap(snap); err != nil {
  824. plog.Fatalf("save snapshot error: %v", err)
  825. }
  826. plog.Infof("saved snapshot at index %d", snap.Metadata.Index)
  827. // keep some in memory log entries for slow followers.
  828. compacti := uint64(1)
  829. if snapi > numberOfCatchUpEntries {
  830. compacti = snapi - numberOfCatchUpEntries
  831. }
  832. err = s.r.raftStorage.Compact(compacti)
  833. if err != nil {
  834. // the compaction was done asynchronously with the progress of raft.
  835. // raft log might already been compact.
  836. if err == raft.ErrCompacted {
  837. return
  838. }
  839. plog.Panicf("unexpected compaction error %v", err)
  840. }
  841. plog.Infof("compacted raft log at %d", compacti)
  842. }()
  843. }
  844. func (s *EtcdServer) PauseSending() { s.r.pauseSending() }
  845. func (s *EtcdServer) ResumeSending() { s.r.resumeSending() }
  846. func (s *EtcdServer) ClusterVersion() *semver.Version {
  847. if s.cluster == nil {
  848. return nil
  849. }
  850. return s.cluster.Version()
  851. }
  852. // monitorVersions checks the member's version every monitorVersion interval.
  853. // It updates the cluster version if all members agrees on a higher one.
  854. // It prints out log if there is a member with a higher version than the
  855. // local version.
  856. func (s *EtcdServer) monitorVersions() {
  857. for {
  858. select {
  859. case <-s.forceVersionC:
  860. case <-time.After(monitorVersionInterval):
  861. case <-s.done:
  862. return
  863. }
  864. if s.Leader() != s.ID() {
  865. continue
  866. }
  867. v := decideClusterVersion(getVersions(s.cluster, s.id, s.cfg.Transport))
  868. if v != nil {
  869. // only keep major.minor version for comparasion
  870. v = &semver.Version{
  871. Major: v.Major,
  872. Minor: v.Minor,
  873. }
  874. }
  875. // if the current version is nil:
  876. // 1. use the decided version if possible
  877. // 2. or use the min cluster version
  878. if s.cluster.Version() == nil {
  879. if v != nil {
  880. go s.updateClusterVersion(v.String())
  881. } else {
  882. go s.updateClusterVersion(version.MinClusterVersion)
  883. }
  884. continue
  885. }
  886. // update cluster version only if the decided version is greater than
  887. // the current cluster version
  888. if v != nil && s.cluster.Version().LessThan(*v) {
  889. go s.updateClusterVersion(v.String())
  890. }
  891. }
  892. }
  893. func (s *EtcdServer) updateClusterVersion(ver string) {
  894. if s.cluster.Version() == nil {
  895. plog.Infof("setting up the initial cluster version to %v", ver)
  896. } else {
  897. plog.Infof("updating the cluster version from %v to %v", s.cluster.Version(), ver)
  898. }
  899. req := pb.Request{
  900. Method: "PUT",
  901. Path: path.Join(StoreClusterPrefix, "version"),
  902. Val: ver,
  903. }
  904. ctx, cancel := context.WithTimeout(context.Background(), versionUpdateTimeout)
  905. _, err := s.Do(ctx, req)
  906. cancel()
  907. switch err {
  908. case nil:
  909. return
  910. case ErrStopped:
  911. plog.Infof("aborting update cluster version because server is stopped")
  912. return
  913. default:
  914. plog.Errorf("error updating cluster version (%v)", err)
  915. }
  916. }
  917. func (s *EtcdServer) parseProposeCtxErr(err error, start time.Time) error {
  918. switch err {
  919. case context.Canceled:
  920. return ErrCanceled
  921. case context.DeadlineExceeded:
  922. curLeadElected := s.r.leadElectedTime()
  923. prevLeadLost := curLeadElected.Add(-2 * time.Duration(s.cfg.ElectionTicks) * time.Duration(s.cfg.TickMs) * time.Millisecond)
  924. if start.After(prevLeadLost) && start.Before(curLeadElected) {
  925. return ErrTimeoutDueToLeaderFail
  926. }
  927. return ErrTimeout
  928. default:
  929. return err
  930. }
  931. }