server.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854
  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. "log"
  20. "math/rand"
  21. "net/http"
  22. "path"
  23. "regexp"
  24. "sync/atomic"
  25. "time"
  26. "github.com/coreos/etcd/discovery"
  27. "github.com/coreos/etcd/etcdserver/etcdhttp/httptypes"
  28. pb "github.com/coreos/etcd/etcdserver/etcdserverpb"
  29. "github.com/coreos/etcd/etcdserver/stats"
  30. "github.com/coreos/etcd/pkg/fileutil"
  31. "github.com/coreos/etcd/pkg/idutil"
  32. "github.com/coreos/etcd/pkg/metrics"
  33. "github.com/coreos/etcd/pkg/pbutil"
  34. "github.com/coreos/etcd/pkg/timeutil"
  35. "github.com/coreos/etcd/pkg/types"
  36. "github.com/coreos/etcd/pkg/wait"
  37. "github.com/coreos/etcd/raft"
  38. "github.com/coreos/etcd/raft/raftpb"
  39. "github.com/coreos/etcd/rafthttp"
  40. "github.com/coreos/etcd/snap"
  41. "github.com/coreos/etcd/store"
  42. "github.com/coreos/etcd/version"
  43. "github.com/coreos/etcd/wal"
  44. "github.com/coreos/etcd/Godeps/_workspace/src/golang.org/x/net/context"
  45. )
  46. const (
  47. // owner can make/remove files inside the directory
  48. privateDirMode = 0700
  49. defaultSyncTimeout = time.Second
  50. DefaultSnapCount = 10000
  51. // TODO: calculate based on heartbeat interval
  52. defaultPublishRetryInterval = 5 * time.Second
  53. StoreAdminPrefix = "/0"
  54. StoreKeysPrefix = "/1"
  55. purgeFileInterval = 30 * time.Second
  56. )
  57. var (
  58. storeMembersPrefix = path.Join(StoreAdminPrefix, "members")
  59. storeRemovedMembersPrefix = path.Join(StoreAdminPrefix, "removed_members")
  60. storeMemberAttributeRegexp = regexp.MustCompile(path.Join(storeMembersPrefix, "[[:xdigit:]]{1,16}", attributesSuffix))
  61. )
  62. func init() {
  63. rand.Seed(time.Now().UnixNano())
  64. }
  65. type Response struct {
  66. Event *store.Event
  67. Watcher store.Watcher
  68. err error
  69. }
  70. type Server interface {
  71. // Start performs any initialization of the Server necessary for it to
  72. // begin serving requests. It must be called before Do or Process.
  73. // Start must be non-blocking; any long-running server functionality
  74. // should be implemented in goroutines.
  75. Start()
  76. // Stop terminates the Server and performs any necessary finalization.
  77. // Do and Process cannot be called after Stop has been invoked.
  78. Stop()
  79. // ID returns the ID of the Server.
  80. ID() types.ID
  81. // Leader returns the ID of the leader Server.
  82. Leader() types.ID
  83. // Do takes a request and attempts to fulfill it, returning a Response.
  84. Do(ctx context.Context, r pb.Request) (Response, error)
  85. // Process takes a raft message and applies it to the server's raft state
  86. // machine, respecting any timeout of the given context.
  87. Process(ctx context.Context, m raftpb.Message) error
  88. // AddMember attempts to add a member into the cluster. It will return
  89. // ErrIDRemoved if member ID is removed from the cluster, or return
  90. // ErrIDExists if member ID exists in the cluster.
  91. AddMember(ctx context.Context, memb Member) error
  92. // RemoveMember attempts to remove a member from the cluster. It will
  93. // return ErrIDRemoved if member ID is removed from the cluster, or return
  94. // ErrIDNotFound if member ID is not in the cluster.
  95. RemoveMember(ctx context.Context, id uint64) error
  96. // UpdateMember attempts to update a existing member in the cluster. It will
  97. // return ErrIDNotFound if the member ID does not exist.
  98. UpdateMember(ctx context.Context, updateMemb Member) error
  99. }
  100. // EtcdServer is the production implementation of the Server interface
  101. type EtcdServer struct {
  102. cfg *ServerConfig
  103. r raftNode
  104. w wait.Wait
  105. stop chan struct{}
  106. done chan struct{}
  107. errorc chan error
  108. id types.ID
  109. attributes Attributes
  110. Cluster *Cluster
  111. store store.Store
  112. stats *stats.ServerStats
  113. lstats *stats.LeaderStats
  114. SyncTicker <-chan time.Time
  115. reqIDGen *idutil.Generator
  116. }
  117. // NewServer creates a new EtcdServer from the supplied configuration. The
  118. // configuration is considered static for the lifetime of the EtcdServer.
  119. func NewServer(cfg *ServerConfig) (*EtcdServer, error) {
  120. st := store.New(StoreAdminPrefix, StoreKeysPrefix)
  121. var w *wal.WAL
  122. var n raft.Node
  123. var s *raft.MemoryStorage
  124. var id types.ID
  125. // Run the migrations.
  126. dataVer, err := version.DetectDataDir(cfg.DataDir)
  127. if err != nil {
  128. return nil, err
  129. }
  130. if err := upgradeDataDir(cfg.DataDir, cfg.Name, dataVer); err != nil {
  131. return nil, err
  132. }
  133. haveWAL := wal.Exist(cfg.WALDir())
  134. ss := snap.New(cfg.SnapDir())
  135. var remotes []*Member
  136. switch {
  137. case !haveWAL && !cfg.NewCluster:
  138. if err := cfg.VerifyJoinExisting(); err != nil {
  139. return nil, err
  140. }
  141. existingCluster, err := GetClusterFromRemotePeers(getRemotePeerURLs(cfg.Cluster, cfg.Name), cfg.Transport)
  142. if err != nil {
  143. return nil, fmt.Errorf("cannot fetch cluster info from peer urls: %v", err)
  144. }
  145. if err := ValidateClusterAndAssignIDs(cfg.Cluster, existingCluster); err != nil {
  146. return nil, fmt.Errorf("error validating peerURLs %s: %v", existingCluster, err)
  147. }
  148. remotes = existingCluster.Members()
  149. cfg.Cluster.SetID(existingCluster.id)
  150. cfg.Cluster.SetStore(st)
  151. cfg.Print()
  152. id, n, s, w = startNode(cfg, nil)
  153. case !haveWAL && cfg.NewCluster:
  154. if err := cfg.VerifyBootstrap(); err != nil {
  155. return nil, err
  156. }
  157. m := cfg.Cluster.MemberByName(cfg.Name)
  158. if isMemberBootstrapped(cfg.Cluster, cfg.Name, cfg.Transport) {
  159. return nil, fmt.Errorf("member %s has already been bootstrapped", m.ID)
  160. }
  161. if cfg.ShouldDiscover() {
  162. str, err := discovery.JoinCluster(cfg.DiscoveryURL, cfg.DiscoveryProxy, m.ID, cfg.Cluster.String())
  163. if err != nil {
  164. return nil, err
  165. }
  166. if cfg.Cluster, err = NewClusterFromString(cfg.Cluster.token, str); err != nil {
  167. return nil, err
  168. }
  169. if err := cfg.Cluster.Validate(); err != nil {
  170. return nil, fmt.Errorf("bad discovery cluster: %v", err)
  171. }
  172. }
  173. cfg.Cluster.SetStore(st)
  174. cfg.PrintWithInitial()
  175. id, n, s, w = startNode(cfg, cfg.Cluster.MemberIDs())
  176. case haveWAL:
  177. if err := fileutil.IsDirWriteable(cfg.DataDir); err != nil {
  178. return nil, fmt.Errorf("cannot write to data directory: %v", err)
  179. }
  180. if err := fileutil.IsDirWriteable(cfg.MemberDir()); err != nil {
  181. return nil, fmt.Errorf("cannot write to member directory: %v", err)
  182. }
  183. if cfg.ShouldDiscover() {
  184. log.Printf("etcdserver: discovery token ignored since a cluster has already been initialized. Valid log found at %q", cfg.WALDir())
  185. }
  186. snapshot, err := ss.Load()
  187. if err != nil && err != snap.ErrNoSnapshot {
  188. return nil, err
  189. }
  190. if snapshot != nil {
  191. if err := st.Recovery(snapshot.Data); err != nil {
  192. log.Panicf("etcdserver: recovered store from snapshot error: %v", err)
  193. }
  194. log.Printf("etcdserver: recovered store from snapshot at index %d", snapshot.Metadata.Index)
  195. }
  196. cfg.Cluster = NewClusterFromStore(cfg.Cluster.token, st)
  197. cfg.Print()
  198. if snapshot != nil {
  199. log.Printf("etcdserver: loaded cluster information from store: %s", cfg.Cluster)
  200. }
  201. if !cfg.ForceNewCluster {
  202. id, n, s, w = restartNode(cfg, snapshot)
  203. } else {
  204. id, n, s, w = restartAsStandaloneNode(cfg, snapshot)
  205. }
  206. default:
  207. return nil, fmt.Errorf("unsupported bootstrap config")
  208. }
  209. sstats := &stats.ServerStats{
  210. Name: cfg.Name,
  211. ID: id.String(),
  212. }
  213. sstats.Initialize()
  214. lstats := stats.NewLeaderStats(id.String())
  215. srv := &EtcdServer{
  216. cfg: cfg,
  217. errorc: make(chan error, 1),
  218. store: st,
  219. r: raftNode{
  220. Node: n,
  221. snapCount: cfg.SnapCount,
  222. ticker: time.Tick(time.Duration(cfg.TickMs) * time.Millisecond),
  223. raftStorage: s,
  224. storage: NewStorage(w, ss),
  225. },
  226. id: id,
  227. attributes: Attributes{Name: cfg.Name, ClientURLs: cfg.ClientURLs.StringSlice()},
  228. Cluster: cfg.Cluster,
  229. stats: sstats,
  230. lstats: lstats,
  231. SyncTicker: time.Tick(500 * time.Millisecond),
  232. reqIDGen: idutil.NewGenerator(uint8(id), time.Now()),
  233. }
  234. // TODO: move transport initialization near the definition of remote
  235. tr := rafthttp.NewTransporter(cfg.Transport, id, cfg.Cluster.ID(), srv, srv.errorc, sstats, lstats)
  236. // add all remotes into transport
  237. for _, m := range remotes {
  238. if m.ID != id {
  239. tr.AddRemote(m.ID, m.PeerURLs)
  240. }
  241. }
  242. for _, m := range cfg.Cluster.Members() {
  243. if m.ID != id {
  244. tr.AddPeer(m.ID, m.PeerURLs)
  245. }
  246. }
  247. srv.r.transport = tr
  248. return srv, nil
  249. }
  250. // Start prepares and starts server in a new goroutine. It is no longer safe to
  251. // modify a server's fields after it has been sent to Start.
  252. // It also starts a goroutine to publish its server information.
  253. func (s *EtcdServer) Start() {
  254. s.start()
  255. go s.publish(defaultPublishRetryInterval)
  256. go s.purgeFile()
  257. metrics.Publish("raft.status", expvar.Func(s.raftStatus))
  258. }
  259. // start prepares and starts server in a new goroutine. It is no longer safe to
  260. // modify a server's fields after it has been sent to Start.
  261. // This function is just used for testing.
  262. func (s *EtcdServer) start() {
  263. if s.r.snapCount == 0 {
  264. log.Printf("etcdserver: set snapshot count to default %d", DefaultSnapCount)
  265. s.r.snapCount = DefaultSnapCount
  266. }
  267. s.w = wait.New()
  268. s.done = make(chan struct{})
  269. s.stop = make(chan struct{})
  270. // TODO: if this is an empty log, writes all peer infos
  271. // into the first entry
  272. go s.run()
  273. }
  274. func (s *EtcdServer) purgeFile() {
  275. var serrc, werrc <-chan error
  276. if s.cfg.MaxSnapFiles > 0 {
  277. serrc = fileutil.PurgeFile(s.cfg.SnapDir(), "snap", s.cfg.MaxSnapFiles, purgeFileInterval, s.done)
  278. }
  279. if s.cfg.MaxWALFiles > 0 {
  280. werrc = fileutil.PurgeFile(s.cfg.WALDir(), "wal", s.cfg.MaxWALFiles, purgeFileInterval, s.done)
  281. }
  282. select {
  283. case e := <-werrc:
  284. log.Fatalf("etcdserver: failed to purge wal file %v", e)
  285. case e := <-serrc:
  286. log.Fatalf("etcdserver: failed to purge snap file %v", e)
  287. case <-s.done:
  288. return
  289. }
  290. }
  291. func (s *EtcdServer) ID() types.ID { return s.id }
  292. func (s *EtcdServer) RaftHandler() http.Handler { return s.r.transport.Handler() }
  293. func (s *EtcdServer) Process(ctx context.Context, m raftpb.Message) error {
  294. if s.Cluster.IsIDRemoved(types.ID(m.From)) {
  295. log.Printf("etcdserver: reject message from removed member %s", types.ID(m.From).String())
  296. return httptypes.NewHTTPError(http.StatusForbidden, "cannot process message from removed member")
  297. }
  298. if m.Type == raftpb.MsgApp {
  299. s.stats.RecvAppendReq(types.ID(m.From).String(), m.Size())
  300. }
  301. return s.r.Step(ctx, m)
  302. }
  303. func (s *EtcdServer) run() {
  304. var syncC <-chan time.Time
  305. var shouldstop bool
  306. // load initial state from raft storage
  307. snap, err := s.r.raftStorage.Snapshot()
  308. if err != nil {
  309. log.Panicf("etcdserver: get snapshot from raft storage error: %v", err)
  310. }
  311. // snapi indicates the index of the last submitted snapshot request
  312. snapi := snap.Metadata.Index
  313. appliedi := snap.Metadata.Index
  314. confState := snap.Metadata.ConfState
  315. defer func() {
  316. s.r.Stop()
  317. s.r.transport.Stop()
  318. if err := s.r.storage.Close(); err != nil {
  319. log.Panicf("etcdserver: close storage error: %v", err)
  320. }
  321. close(s.done)
  322. }()
  323. // TODO: make raft loop a method on raftNode
  324. for {
  325. select {
  326. case <-s.r.ticker:
  327. s.r.Tick()
  328. case rd := <-s.r.Ready():
  329. if rd.SoftState != nil {
  330. atomic.StoreUint64(&s.r.lead, rd.SoftState.Lead)
  331. if rd.RaftState == raft.StateLeader {
  332. syncC = s.SyncTicker
  333. // TODO: remove the nil checking
  334. // current test utility does not provide the stats
  335. if s.stats != nil {
  336. s.stats.BecomeLeader()
  337. }
  338. } else {
  339. syncC = nil
  340. }
  341. }
  342. // apply snapshot to storage if it is more updated than current snapi
  343. if !raft.IsEmptySnap(rd.Snapshot) && rd.Snapshot.Metadata.Index > snapi {
  344. if err := s.r.storage.SaveSnap(rd.Snapshot); err != nil {
  345. log.Fatalf("etcdserver: save snapshot error: %v", err)
  346. }
  347. s.r.raftStorage.ApplySnapshot(rd.Snapshot)
  348. snapi = rd.Snapshot.Metadata.Index
  349. log.Printf("etcdserver: saved incoming snapshot at index %d", snapi)
  350. }
  351. if err := s.r.storage.Save(rd.HardState, rd.Entries); err != nil {
  352. log.Fatalf("etcdserver: save state and entries error: %v", err)
  353. }
  354. s.r.raftStorage.Append(rd.Entries)
  355. s.send(rd.Messages)
  356. // recover from snapshot if it is more updated than current applied
  357. if !raft.IsEmptySnap(rd.Snapshot) && rd.Snapshot.Metadata.Index > appliedi {
  358. if err := s.store.Recovery(rd.Snapshot.Data); err != nil {
  359. log.Panicf("recovery store error: %v", err)
  360. }
  361. s.Cluster.Recover()
  362. // recover raft transport
  363. s.r.transport.RemoveAllPeers()
  364. for _, m := range s.Cluster.Members() {
  365. if m.ID == s.ID() {
  366. continue
  367. }
  368. s.r.transport.AddPeer(m.ID, m.PeerURLs)
  369. }
  370. appliedi = rd.Snapshot.Metadata.Index
  371. confState = rd.Snapshot.Metadata.ConfState
  372. log.Printf("etcdserver: recovered from incoming snapshot at index %d", snapi)
  373. }
  374. // TODO(bmizerany): do this in the background, but take
  375. // care to apply entries in a single goroutine, and not
  376. // race them.
  377. if len(rd.CommittedEntries) != 0 {
  378. firsti := rd.CommittedEntries[0].Index
  379. if firsti > appliedi+1 {
  380. log.Panicf("etcdserver: first index of committed entry[%d] should <= appliedi[%d] + 1", firsti, appliedi)
  381. }
  382. var ents []raftpb.Entry
  383. if appliedi+1-firsti < uint64(len(rd.CommittedEntries)) {
  384. ents = rd.CommittedEntries[appliedi+1-firsti:]
  385. }
  386. if len(ents) > 0 {
  387. if appliedi, shouldstop = s.apply(ents, &confState); shouldstop {
  388. go s.stopWithDelay(10*100*time.Millisecond, fmt.Errorf("the member has been permanently removed from the cluster"))
  389. }
  390. }
  391. }
  392. s.r.Advance()
  393. if appliedi-snapi > s.r.snapCount {
  394. log.Printf("etcdserver: start to snapshot (applied: %d, lastsnap: %d)", appliedi, snapi)
  395. s.snapshot(appliedi, &confState)
  396. snapi = appliedi
  397. }
  398. case <-syncC:
  399. s.sync(defaultSyncTimeout)
  400. case err := <-s.errorc:
  401. log.Printf("etcdserver: %s", err)
  402. log.Printf("etcdserver: the data-dir used by this member must be removed.")
  403. return
  404. case <-s.stop:
  405. return
  406. }
  407. }
  408. }
  409. // Stop stops the server gracefully, and shuts down the running goroutine.
  410. // Stop should be called after a Start(s), otherwise it will block forever.
  411. func (s *EtcdServer) Stop() {
  412. select {
  413. case s.stop <- struct{}{}:
  414. case <-s.done:
  415. return
  416. }
  417. <-s.done
  418. }
  419. func (s *EtcdServer) stopWithDelay(d time.Duration, err error) {
  420. time.Sleep(d)
  421. select {
  422. case s.errorc <- err:
  423. default:
  424. }
  425. }
  426. // StopNotify returns a channel that receives a empty struct
  427. // when the server is stopped.
  428. func (s *EtcdServer) StopNotify() <-chan struct{} { return s.done }
  429. // Do interprets r and performs an operation on s.store according to r.Method
  430. // and other fields. If r.Method is "POST", "PUT", "DELETE", or a "GET" with
  431. // Quorum == true, r will be sent through consensus before performing its
  432. // respective operation. Do will block until an action is performed or there is
  433. // an error.
  434. func (s *EtcdServer) Do(ctx context.Context, r pb.Request) (Response, error) {
  435. r.ID = s.reqIDGen.Next()
  436. if r.Method == "GET" && r.Quorum {
  437. r.Method = "QGET"
  438. }
  439. switch r.Method {
  440. case "POST", "PUT", "DELETE", "QGET":
  441. data, err := r.Marshal()
  442. if err != nil {
  443. return Response{}, err
  444. }
  445. ch := s.w.Register(r.ID)
  446. s.r.Propose(ctx, data)
  447. select {
  448. case x := <-ch:
  449. resp := x.(Response)
  450. return resp, resp.err
  451. case <-ctx.Done():
  452. s.w.Trigger(r.ID, nil) // GC wait
  453. return Response{}, parseCtxErr(ctx.Err())
  454. case <-s.done:
  455. return Response{}, ErrStopped
  456. }
  457. case "GET":
  458. switch {
  459. case r.Wait:
  460. wc, err := s.store.Watch(r.Path, r.Recursive, r.Stream, r.Since)
  461. if err != nil {
  462. return Response{}, err
  463. }
  464. return Response{Watcher: wc}, nil
  465. default:
  466. ev, err := s.store.Get(r.Path, r.Recursive, r.Sorted)
  467. if err != nil {
  468. return Response{}, err
  469. }
  470. return Response{Event: ev}, nil
  471. }
  472. case "HEAD":
  473. ev, err := s.store.Get(r.Path, r.Recursive, r.Sorted)
  474. if err != nil {
  475. return Response{}, err
  476. }
  477. return Response{Event: ev}, nil
  478. default:
  479. return Response{}, ErrUnknownMethod
  480. }
  481. }
  482. func (s *EtcdServer) SelfStats() []byte { return s.stats.JSON() }
  483. func (s *EtcdServer) LeaderStats() []byte {
  484. lead := atomic.LoadUint64(&s.r.lead)
  485. if lead != uint64(s.id) {
  486. return nil
  487. }
  488. return s.lstats.JSON()
  489. }
  490. func (s *EtcdServer) StoreStats() []byte { return s.store.JsonStats() }
  491. func (s *EtcdServer) raftStatus() interface{} { return s.r.Status() }
  492. func (s *EtcdServer) AddMember(ctx context.Context, memb Member) error {
  493. // TODO: move Member to protobuf type
  494. b, err := json.Marshal(memb)
  495. if err != nil {
  496. return err
  497. }
  498. cc := raftpb.ConfChange{
  499. Type: raftpb.ConfChangeAddNode,
  500. NodeID: uint64(memb.ID),
  501. Context: b,
  502. }
  503. return s.configure(ctx, cc)
  504. }
  505. func (s *EtcdServer) RemoveMember(ctx context.Context, id uint64) error {
  506. cc := raftpb.ConfChange{
  507. Type: raftpb.ConfChangeRemoveNode,
  508. NodeID: id,
  509. }
  510. return s.configure(ctx, cc)
  511. }
  512. func (s *EtcdServer) UpdateMember(ctx context.Context, memb Member) error {
  513. b, err := json.Marshal(memb)
  514. if err != nil {
  515. return err
  516. }
  517. cc := raftpb.ConfChange{
  518. Type: raftpb.ConfChangeUpdateNode,
  519. NodeID: uint64(memb.ID),
  520. Context: b,
  521. }
  522. return s.configure(ctx, cc)
  523. }
  524. // Implement the RaftTimer interface
  525. func (s *EtcdServer) Index() uint64 { return atomic.LoadUint64(&s.r.index) }
  526. func (s *EtcdServer) Term() uint64 { return atomic.LoadUint64(&s.r.term) }
  527. // Only for testing purpose
  528. // TODO: add Raft server interface to expose raft related info:
  529. // Index, Term, Lead, Committed, Applied, LastIndex, etc.
  530. func (s *EtcdServer) Lead() uint64 { return atomic.LoadUint64(&s.r.lead) }
  531. func (s *EtcdServer) Leader() types.ID { return types.ID(s.Lead()) }
  532. // configure sends a configuration change through consensus and
  533. // then waits for it to be applied to the server. It
  534. // will block until the change is performed or there is an error.
  535. func (s *EtcdServer) configure(ctx context.Context, cc raftpb.ConfChange) error {
  536. cc.ID = s.reqIDGen.Next()
  537. ch := s.w.Register(cc.ID)
  538. if err := s.r.ProposeConfChange(ctx, cc); err != nil {
  539. s.w.Trigger(cc.ID, nil)
  540. return err
  541. }
  542. select {
  543. case x := <-ch:
  544. if err, ok := x.(error); ok {
  545. return err
  546. }
  547. if x != nil {
  548. log.Panicf("return type should always be error")
  549. }
  550. return nil
  551. case <-ctx.Done():
  552. s.w.Trigger(cc.ID, nil) // GC wait
  553. return parseCtxErr(ctx.Err())
  554. case <-s.done:
  555. return ErrStopped
  556. }
  557. }
  558. // sync proposes a SYNC request and is non-blocking.
  559. // This makes no guarantee that the request will be proposed or performed.
  560. // The request will be cancelled after the given timeout.
  561. func (s *EtcdServer) sync(timeout time.Duration) {
  562. ctx, cancel := context.WithTimeout(context.Background(), timeout)
  563. req := pb.Request{
  564. Method: "SYNC",
  565. ID: s.reqIDGen.Next(),
  566. Time: time.Now().UnixNano(),
  567. }
  568. data := pbutil.MustMarshal(&req)
  569. // There is no promise that node has leader when do SYNC request,
  570. // so it uses goroutine to propose.
  571. go func() {
  572. s.r.Propose(ctx, data)
  573. cancel()
  574. }()
  575. }
  576. // publish registers server information into the cluster. The information
  577. // is the JSON representation of this server's member struct, updated with the
  578. // static clientURLs of the server.
  579. // The function keeps attempting to register until it succeeds,
  580. // or its server is stopped.
  581. func (s *EtcdServer) publish(retryInterval time.Duration) {
  582. b, err := json.Marshal(s.attributes)
  583. if err != nil {
  584. log.Printf("etcdserver: json marshal error: %v", err)
  585. return
  586. }
  587. req := pb.Request{
  588. Method: "PUT",
  589. Path: MemberAttributesStorePath(s.id),
  590. Val: string(b),
  591. }
  592. for {
  593. ctx, cancel := context.WithTimeout(context.Background(), retryInterval)
  594. _, err := s.Do(ctx, req)
  595. cancel()
  596. switch err {
  597. case nil:
  598. log.Printf("etcdserver: published %+v to cluster %s", s.attributes, s.Cluster.ID())
  599. return
  600. case ErrStopped:
  601. log.Printf("etcdserver: aborting publish because server is stopped")
  602. return
  603. default:
  604. log.Printf("etcdserver: publish error: %v", err)
  605. }
  606. }
  607. }
  608. func (s *EtcdServer) send(ms []raftpb.Message) {
  609. for i, _ := range ms {
  610. if s.Cluster.IsIDRemoved(types.ID(ms[i].To)) {
  611. ms[i].To = 0
  612. }
  613. }
  614. s.r.transport.Send(ms)
  615. }
  616. // apply takes entries received from Raft (after it has been committed) and
  617. // applies them to the current state of the EtcdServer.
  618. // The given entries should not be empty.
  619. func (s *EtcdServer) apply(es []raftpb.Entry, confState *raftpb.ConfState) (uint64, bool) {
  620. var applied uint64
  621. var shouldstop bool
  622. var err error
  623. for i := range es {
  624. e := es[i]
  625. switch e.Type {
  626. case raftpb.EntryNormal:
  627. var r pb.Request
  628. pbutil.MustUnmarshal(&r, e.Data)
  629. s.w.Trigger(r.ID, s.applyRequest(r))
  630. case raftpb.EntryConfChange:
  631. var cc raftpb.ConfChange
  632. pbutil.MustUnmarshal(&cc, e.Data)
  633. shouldstop, err = s.applyConfChange(cc, confState)
  634. s.w.Trigger(cc.ID, err)
  635. default:
  636. log.Panicf("entry type should be either EntryNormal or EntryConfChange")
  637. }
  638. atomic.StoreUint64(&s.r.index, e.Index)
  639. atomic.StoreUint64(&s.r.term, e.Term)
  640. applied = e.Index
  641. }
  642. return applied, shouldstop
  643. }
  644. // applyRequest interprets r as a call to store.X and returns a Response interpreted
  645. // from store.Event
  646. func (s *EtcdServer) applyRequest(r pb.Request) Response {
  647. f := func(ev *store.Event, err error) Response {
  648. return Response{Event: ev, err: err}
  649. }
  650. expr := timeutil.UnixNanoToTime(r.Expiration)
  651. switch r.Method {
  652. case "POST":
  653. return f(s.store.Create(r.Path, r.Dir, r.Val, true, expr))
  654. case "PUT":
  655. exists, existsSet := pbutil.GetBool(r.PrevExist)
  656. switch {
  657. case existsSet:
  658. if exists {
  659. if r.PrevIndex == 0 && r.PrevValue == "" {
  660. return f(s.store.Update(r.Path, r.Val, expr))
  661. } else {
  662. return f(s.store.CompareAndSwap(r.Path, r.PrevValue, r.PrevIndex, r.Val, expr))
  663. }
  664. }
  665. return f(s.store.Create(r.Path, r.Dir, r.Val, false, expr))
  666. case r.PrevIndex > 0 || r.PrevValue != "":
  667. return f(s.store.CompareAndSwap(r.Path, r.PrevValue, r.PrevIndex, r.Val, expr))
  668. default:
  669. if storeMemberAttributeRegexp.MatchString(r.Path) {
  670. id := mustParseMemberIDFromKey(path.Dir(r.Path))
  671. var attr Attributes
  672. if err := json.Unmarshal([]byte(r.Val), &attr); err != nil {
  673. log.Panicf("unmarshal %s should never fail: %v", r.Val, err)
  674. }
  675. s.Cluster.UpdateAttributes(id, attr)
  676. }
  677. return f(s.store.Set(r.Path, r.Dir, r.Val, expr))
  678. }
  679. case "DELETE":
  680. switch {
  681. case r.PrevIndex > 0 || r.PrevValue != "":
  682. return f(s.store.CompareAndDelete(r.Path, r.PrevValue, r.PrevIndex))
  683. default:
  684. return f(s.store.Delete(r.Path, r.Dir, r.Recursive))
  685. }
  686. case "QGET":
  687. return f(s.store.Get(r.Path, r.Recursive, r.Sorted))
  688. case "SYNC":
  689. s.store.DeleteExpiredKeys(time.Unix(0, r.Time))
  690. return Response{}
  691. default:
  692. // This should never be reached, but just in case:
  693. return Response{err: ErrUnknownMethod}
  694. }
  695. }
  696. // applyConfChange applies a ConfChange to the server. It is only
  697. // invoked with a ConfChange that has already passed through Raft
  698. func (s *EtcdServer) applyConfChange(cc raftpb.ConfChange, confState *raftpb.ConfState) (bool, error) {
  699. if err := s.Cluster.ValidateConfigurationChange(cc); err != nil {
  700. cc.NodeID = raft.None
  701. s.r.ApplyConfChange(cc)
  702. return false, err
  703. }
  704. *confState = *s.r.ApplyConfChange(cc)
  705. switch cc.Type {
  706. case raftpb.ConfChangeAddNode:
  707. m := new(Member)
  708. if err := json.Unmarshal(cc.Context, m); err != nil {
  709. log.Panicf("unmarshal member should never fail: %v", err)
  710. }
  711. if cc.NodeID != uint64(m.ID) {
  712. log.Panicf("nodeID should always be equal to member ID")
  713. }
  714. s.Cluster.AddMember(m)
  715. if m.ID == s.id {
  716. log.Printf("etcdserver: added local member %s %v to cluster %s", m.ID, m.PeerURLs, s.Cluster.ID())
  717. } else {
  718. s.r.transport.AddPeer(m.ID, m.PeerURLs)
  719. log.Printf("etcdserver: added member %s %v to cluster %s", m.ID, m.PeerURLs, s.Cluster.ID())
  720. }
  721. case raftpb.ConfChangeRemoveNode:
  722. id := types.ID(cc.NodeID)
  723. s.Cluster.RemoveMember(id)
  724. if id == s.id {
  725. return true, nil
  726. } else {
  727. s.r.transport.RemovePeer(id)
  728. log.Printf("etcdserver: removed member %s from cluster %s", id, s.Cluster.ID())
  729. }
  730. case raftpb.ConfChangeUpdateNode:
  731. m := new(Member)
  732. if err := json.Unmarshal(cc.Context, m); err != nil {
  733. log.Panicf("unmarshal member should never fail: %v", err)
  734. }
  735. if cc.NodeID != uint64(m.ID) {
  736. log.Panicf("nodeID should always be equal to member ID")
  737. }
  738. s.Cluster.UpdateRaftAttributes(m.ID, m.RaftAttributes)
  739. if m.ID == s.id {
  740. log.Printf("etcdserver: update local member %s %v in cluster %s", m.ID, m.PeerURLs, s.Cluster.ID())
  741. } else {
  742. s.r.transport.UpdatePeer(m.ID, m.PeerURLs)
  743. log.Printf("etcdserver: update member %s %v in cluster %s", m.ID, m.PeerURLs, s.Cluster.ID())
  744. }
  745. }
  746. return false, nil
  747. }
  748. // TODO: non-blocking snapshot
  749. func (s *EtcdServer) snapshot(snapi uint64, confState *raftpb.ConfState) {
  750. d, err := s.store.Save()
  751. // TODO: current store will never fail to do a snapshot
  752. // what should we do if the store might fail?
  753. if err != nil {
  754. log.Panicf("etcdserver: store save should never fail: %v", err)
  755. }
  756. err = s.r.raftStorage.Compact(snapi, confState, d)
  757. if err != nil {
  758. // the snapshot was done asynchronously with the progress of raft.
  759. // raft might have already got a newer snapshot and called compact.
  760. if err == raft.ErrCompacted {
  761. return
  762. }
  763. log.Panicf("etcdserver: unexpected compaction error %v", err)
  764. }
  765. log.Printf("etcdserver: compacted log at index %d", snapi)
  766. if err := s.r.storage.Cut(); err != nil {
  767. log.Panicf("etcdserver: rotate wal file should never fail: %v", err)
  768. }
  769. snap, err := s.r.raftStorage.Snapshot()
  770. if err != nil {
  771. log.Panicf("etcdserver: snapshot error: %v", err)
  772. }
  773. if err := s.r.storage.SaveSnap(snap); err != nil {
  774. log.Fatalf("etcdserver: save snapshot error: %v", err)
  775. }
  776. log.Printf("etcdserver: saved snapshot at index %d", snap.Metadata.Index)
  777. }
  778. func (s *EtcdServer) PauseSending() { s.r.pauseSending() }
  779. func (s *EtcdServer) ResumeSending() { s.r.resumeSending() }