server.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  1. package etcdserver
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "log"
  6. "math/rand"
  7. "os"
  8. "sync/atomic"
  9. "time"
  10. "github.com/coreos/etcd/discovery"
  11. pb "github.com/coreos/etcd/etcdserver/etcdserverpb"
  12. "github.com/coreos/etcd/raft"
  13. "github.com/coreos/etcd/raft/raftpb"
  14. "github.com/coreos/etcd/snap"
  15. "github.com/coreos/etcd/store"
  16. "github.com/coreos/etcd/third_party/code.google.com/p/go.net/context"
  17. "github.com/coreos/etcd/wait"
  18. "github.com/coreos/etcd/wal"
  19. )
  20. const (
  21. // owner can make/remove files inside the directory
  22. privateDirMode = 0700
  23. defaultSyncTimeout = time.Second
  24. DefaultSnapCount = 10000
  25. // TODO: calculate based on heartbeat interval
  26. defaultPublishRetryInterval = 5 * time.Second
  27. )
  28. var (
  29. ErrUnknownMethod = errors.New("etcdserver: unknown method")
  30. ErrStopped = errors.New("etcdserver: server stopped")
  31. )
  32. func init() {
  33. rand.Seed(time.Now().UnixNano())
  34. }
  35. type sendFunc func(m []raftpb.Message)
  36. type Response struct {
  37. Event *store.Event
  38. Watcher store.Watcher
  39. err error
  40. }
  41. type Storage interface {
  42. // Save function saves ents and state to the underlying stable storage.
  43. // Save MUST block until st and ents are on stable storage.
  44. Save(st raftpb.HardState, ents []raftpb.Entry)
  45. // SaveSnap function saves snapshot to the underlying stable storage.
  46. SaveSnap(snap raftpb.Snapshot)
  47. // TODO: WAL should be able to control cut itself. After implement self-controled cut,
  48. // remove it in this interface.
  49. // Cut cuts out a new wal file for saving new state and entries.
  50. Cut() error
  51. }
  52. type Server interface {
  53. // Start performs any initialization of the Server necessary for it to
  54. // begin serving requests. It must be called before Do or Process.
  55. // Start must be non-blocking; any long-running server functionality
  56. // should be implemented in goroutines.
  57. Start()
  58. // Stop terminates the Server and performs any necessary finalization.
  59. // Do and Process cannot be called after Stop has been invoked.
  60. Stop()
  61. // Do takes a request and attempts to fulfil it, returning a Response.
  62. Do(ctx context.Context, r pb.Request) (Response, error)
  63. // Process takes a raft message and applies it to the server's raft state
  64. // machine, respecting any timeout of the given context.
  65. Process(ctx context.Context, m raftpb.Message) error
  66. }
  67. type RaftTimer interface {
  68. Index() uint64
  69. Term() uint64
  70. }
  71. // EtcdServer is the production implementation of the Server interface
  72. type EtcdServer struct {
  73. w wait.Wait
  74. done chan struct{}
  75. id uint64
  76. attributes Attributes
  77. ClusterStore ClusterStore
  78. node raft.Node
  79. store store.Store
  80. // send specifies the send function for sending msgs to members. send
  81. // MUST NOT block. It is okay to drop messages, since clients should
  82. // timeout and reissue their messages. If send is nil, server will
  83. // panic.
  84. send sendFunc
  85. storage Storage
  86. ticker <-chan time.Time
  87. syncTicker <-chan time.Time
  88. snapCount uint64 // number of entries to trigger a snapshot
  89. // Cache of the latest raft index and raft term the server has seen
  90. raftIndex uint64
  91. raftTerm uint64
  92. }
  93. // NewServer creates a new EtcdServer from the supplied configuration. The
  94. // configuration is considered static for the lifetime of the EtcdServer.
  95. func NewServer(cfg *ServerConfig) *EtcdServer {
  96. if err := cfg.Verify(); err != nil {
  97. log.Fatalln(err)
  98. }
  99. if err := os.MkdirAll(cfg.SnapDir(), privateDirMode); err != nil {
  100. log.Fatalf("etcdserver: cannot create snapshot directory: %v", err)
  101. }
  102. ss := snap.New(cfg.SnapDir())
  103. st := store.New()
  104. var w *wal.WAL
  105. var n raft.Node
  106. if !wal.Exist(cfg.WALDir()) {
  107. if !cfg.IsBootstrap() {
  108. log.Fatalf("etcd: initial cluster state unset and no wal or discovery URL found")
  109. }
  110. if cfg.ShouldDiscover() {
  111. d, err := discovery.New(cfg.DiscoveryURL, cfg.ID(), cfg.Cluster.String())
  112. if err != nil {
  113. log.Fatalf("etcd: cannot init discovery %v", err)
  114. }
  115. s, err := d.Discover()
  116. if err != nil {
  117. log.Fatalf("etcd: %v", err)
  118. }
  119. if err = cfg.Cluster.Set(s); err != nil {
  120. log.Fatalf("etcd: %v", err)
  121. }
  122. }
  123. n, w = startNode(cfg)
  124. } else {
  125. if cfg.ShouldDiscover() {
  126. log.Printf("etcd: warn: ignoring discovery: etcd has already been initialized and has a valid log in %q", cfg.WALDir())
  127. }
  128. var index uint64
  129. snapshot, err := ss.Load()
  130. if err != nil && err != snap.ErrNoSnapshot {
  131. log.Fatal(err)
  132. }
  133. if snapshot != nil {
  134. log.Printf("etcdserver: restart from snapshot at index %d", snapshot.Index)
  135. st.Recovery(snapshot.Data)
  136. index = snapshot.Index
  137. }
  138. n, w = restartNode(cfg, index, snapshot)
  139. }
  140. cls := &clusterStore{Store: st}
  141. s := &EtcdServer{
  142. store: st,
  143. node: n,
  144. id: cfg.ID(),
  145. attributes: Attributes{Name: cfg.Name, ClientURLs: cfg.ClientURLs.StringSlice()},
  146. storage: struct {
  147. *wal.WAL
  148. *snap.Snapshotter
  149. }{w, ss},
  150. send: Sender(cfg.Transport, cls),
  151. ticker: time.Tick(100 * time.Millisecond),
  152. syncTicker: time.Tick(500 * time.Millisecond),
  153. snapCount: cfg.SnapCount,
  154. ClusterStore: cls,
  155. }
  156. return s
  157. }
  158. // Start prepares and starts server in a new goroutine. It is no longer safe to
  159. // modify a server's fields after it has been sent to Start.
  160. // It also starts a goroutine to publish its server information.
  161. func (s *EtcdServer) Start() {
  162. s.start()
  163. go s.publish(defaultPublishRetryInterval)
  164. }
  165. // start prepares and starts server in a new goroutine. It is no longer safe to
  166. // modify a server's fields after it has been sent to Start.
  167. // This function is just used for testing.
  168. func (s *EtcdServer) start() {
  169. if s.snapCount == 0 {
  170. log.Printf("etcdserver: set snapshot count to default %d", DefaultSnapCount)
  171. s.snapCount = DefaultSnapCount
  172. }
  173. s.w = wait.New()
  174. s.done = make(chan struct{})
  175. // TODO: if this is an empty log, writes all peer infos
  176. // into the first entry
  177. go s.run()
  178. }
  179. func (s *EtcdServer) Process(ctx context.Context, m raftpb.Message) error {
  180. return s.node.Step(ctx, m)
  181. }
  182. func (s *EtcdServer) run() {
  183. var syncC <-chan time.Time
  184. // snapi indicates the index of the last submitted snapshot request
  185. var snapi, appliedi uint64
  186. var nodes []uint64
  187. for {
  188. select {
  189. case <-s.ticker:
  190. s.node.Tick()
  191. case rd := <-s.node.Ready():
  192. s.storage.Save(rd.HardState, rd.Entries)
  193. s.storage.SaveSnap(rd.Snapshot)
  194. s.send(rd.Messages)
  195. // TODO(bmizerany): do this in the background, but take
  196. // care to apply entries in a single goroutine, and not
  197. // race them.
  198. // TODO: apply configuration change into ClusterStore.
  199. if len(rd.CommittedEntries) != 0 {
  200. appliedi = s.apply(rd.CommittedEntries)
  201. }
  202. if rd.SoftState != nil {
  203. nodes = rd.SoftState.Nodes
  204. if rd.RaftState == raft.StateLeader {
  205. syncC = s.syncTicker
  206. } else {
  207. syncC = nil
  208. }
  209. if rd.SoftState.ShouldStop {
  210. s.Stop()
  211. return
  212. }
  213. }
  214. if rd.Snapshot.Index > snapi {
  215. snapi = rd.Snapshot.Index
  216. }
  217. // recover from snapshot if it is more updated than current applied
  218. if rd.Snapshot.Index > appliedi {
  219. if err := s.store.Recovery(rd.Snapshot.Data); err != nil {
  220. panic("TODO: this is bad, what do we do about it?")
  221. }
  222. appliedi = rd.Snapshot.Index
  223. }
  224. if appliedi-snapi > s.snapCount {
  225. s.snapshot(appliedi, nodes)
  226. snapi = appliedi
  227. }
  228. case <-syncC:
  229. s.sync(defaultSyncTimeout)
  230. case <-s.done:
  231. return
  232. }
  233. }
  234. }
  235. // Stop stops the server, and shuts down the running goroutine. Stop should be
  236. // called after a Start(s), otherwise it will block forever.
  237. func (s *EtcdServer) Stop() {
  238. s.node.Stop()
  239. close(s.done)
  240. }
  241. // Do interprets r and performs an operation on s.store according to r.Method
  242. // and other fields. If r.Method is "POST", "PUT", "DELETE", or a "GET" with
  243. // Quorum == true, r will be sent through consensus before performing its
  244. // respective operation. Do will block until an action is performed or there is
  245. // an error.
  246. func (s *EtcdServer) Do(ctx context.Context, r pb.Request) (Response, error) {
  247. if r.ID == 0 {
  248. panic("r.ID cannot be 0")
  249. }
  250. if r.Method == "GET" && r.Quorum {
  251. r.Method = "QGET"
  252. }
  253. switch r.Method {
  254. case "POST", "PUT", "DELETE", "QGET":
  255. data, err := r.Marshal()
  256. if err != nil {
  257. return Response{}, err
  258. }
  259. ch := s.w.Register(r.ID)
  260. s.node.Propose(ctx, data)
  261. select {
  262. case x := <-ch:
  263. resp := x.(Response)
  264. return resp, resp.err
  265. case <-ctx.Done():
  266. s.w.Trigger(r.ID, nil) // GC wait
  267. return Response{}, ctx.Err()
  268. case <-s.done:
  269. return Response{}, ErrStopped
  270. }
  271. case "GET":
  272. switch {
  273. case r.Wait:
  274. wc, err := s.store.Watch(r.Path, r.Recursive, r.Stream, r.Since)
  275. if err != nil {
  276. return Response{}, err
  277. }
  278. return Response{Watcher: wc}, nil
  279. default:
  280. ev, err := s.store.Get(r.Path, r.Recursive, r.Sorted)
  281. if err != nil {
  282. return Response{}, err
  283. }
  284. return Response{Event: ev}, nil
  285. }
  286. default:
  287. return Response{}, ErrUnknownMethod
  288. }
  289. }
  290. func (s *EtcdServer) AddMember(ctx context.Context, memb Member) error {
  291. // TODO: move Member to protobuf type
  292. b, err := json.Marshal(memb)
  293. if err != nil {
  294. return err
  295. }
  296. cc := raftpb.ConfChange{
  297. ID: GenID(),
  298. Type: raftpb.ConfChangeAddNode,
  299. NodeID: memb.ID,
  300. Context: b,
  301. }
  302. return s.configure(ctx, cc)
  303. }
  304. func (s *EtcdServer) RemoveMember(ctx context.Context, id uint64) error {
  305. cc := raftpb.ConfChange{
  306. ID: GenID(),
  307. Type: raftpb.ConfChangeRemoveNode,
  308. NodeID: id,
  309. }
  310. return s.configure(ctx, cc)
  311. }
  312. // Implement the RaftTimer interface
  313. func (s *EtcdServer) Index() uint64 {
  314. return atomic.LoadUint64(&s.raftIndex)
  315. }
  316. func (s *EtcdServer) Term() uint64 {
  317. return atomic.LoadUint64(&s.raftTerm)
  318. }
  319. // configure sends configuration change through consensus then performs it.
  320. // It will block until the change is performed or there is an error.
  321. func (s *EtcdServer) configure(ctx context.Context, cc raftpb.ConfChange) error {
  322. ch := s.w.Register(cc.ID)
  323. if err := s.node.ProposeConfChange(ctx, cc); err != nil {
  324. log.Printf("configure error: %v", err)
  325. s.w.Trigger(cc.ID, nil)
  326. return err
  327. }
  328. select {
  329. case <-ch:
  330. return nil
  331. case <-ctx.Done():
  332. s.w.Trigger(cc.ID, nil) // GC wait
  333. return ctx.Err()
  334. case <-s.done:
  335. return ErrStopped
  336. }
  337. }
  338. // sync proposes a SYNC request and is non-blocking.
  339. // This makes no guarantee that the request will be proposed or performed.
  340. // The request will be cancelled after the given timeout.
  341. func (s *EtcdServer) sync(timeout time.Duration) {
  342. ctx, cancel := context.WithTimeout(context.Background(), timeout)
  343. req := pb.Request{
  344. Method: "SYNC",
  345. ID: GenID(),
  346. Time: time.Now().UnixNano(),
  347. }
  348. data, err := req.Marshal()
  349. if err != nil {
  350. log.Printf("marshal request %#v error: %v", req, err)
  351. return
  352. }
  353. // There is no promise that node has leader when do SYNC request,
  354. // so it uses goroutine to propose.
  355. go func() {
  356. s.node.Propose(ctx, data)
  357. cancel()
  358. }()
  359. }
  360. // publish registers server information into the cluster. The information
  361. // is the JSON representation of this server's member struct, updated with the
  362. // static clientURLs of the server.
  363. // The function keeps attempting to register until it succeeds,
  364. // or its server is stopped.
  365. func (s *EtcdServer) publish(retryInterval time.Duration) {
  366. b, err := json.Marshal(s.attributes)
  367. if err != nil {
  368. log.Printf("etcdserver: json marshal error: %v", err)
  369. return
  370. }
  371. req := pb.Request{
  372. ID: GenID(),
  373. Method: "PUT",
  374. Path: Member{ID: s.id}.storeKey() + attributesSuffix,
  375. Val: string(b),
  376. }
  377. for {
  378. ctx, cancel := context.WithTimeout(context.Background(), retryInterval)
  379. _, err := s.Do(ctx, req)
  380. cancel()
  381. switch err {
  382. case nil:
  383. log.Printf("etcdserver: published %+v to the cluster", s.attributes)
  384. return
  385. case ErrStopped:
  386. log.Printf("etcdserver: aborting publish because server is stopped")
  387. return
  388. default:
  389. log.Printf("etcdserver: publish error: %v", err)
  390. }
  391. }
  392. }
  393. func getExpirationTime(r *pb.Request) time.Time {
  394. var t time.Time
  395. if r.Expiration != 0 {
  396. t = time.Unix(0, r.Expiration)
  397. }
  398. return t
  399. }
  400. func (s *EtcdServer) apply(es []raftpb.Entry) uint64 {
  401. var applied uint64
  402. for i := range es {
  403. e := es[i]
  404. switch e.Type {
  405. case raftpb.EntryNormal:
  406. var r pb.Request
  407. if err := r.Unmarshal(e.Data); err != nil {
  408. panic("TODO: this is bad, what do we do about it?")
  409. }
  410. s.w.Trigger(r.ID, s.applyRequest(r))
  411. case raftpb.EntryConfChange:
  412. var cc raftpb.ConfChange
  413. if err := cc.Unmarshal(e.Data); err != nil {
  414. panic("TODO: this is bad, what do we do about it?")
  415. }
  416. s.applyConfChange(cc)
  417. s.w.Trigger(cc.ID, nil)
  418. default:
  419. panic("unexpected entry type")
  420. }
  421. atomic.StoreUint64(&s.raftIndex, e.Index)
  422. atomic.StoreUint64(&s.raftTerm, e.Term)
  423. applied = e.Index
  424. }
  425. return applied
  426. }
  427. // applyRequest interprets r as a call to store.X and returns a Response interpreted
  428. // from store.Event
  429. func (s *EtcdServer) applyRequest(r pb.Request) Response {
  430. f := func(ev *store.Event, err error) Response {
  431. return Response{Event: ev, err: err}
  432. }
  433. expr := getExpirationTime(&r)
  434. switch r.Method {
  435. case "POST":
  436. return f(s.store.Create(r.Path, r.Dir, r.Val, true, expr))
  437. case "PUT":
  438. exists, existsSet := getBool(r.PrevExist)
  439. switch {
  440. case existsSet:
  441. if exists {
  442. return f(s.store.Update(r.Path, r.Val, expr))
  443. }
  444. return f(s.store.Create(r.Path, r.Dir, r.Val, false, expr))
  445. case r.PrevIndex > 0 || r.PrevValue != "":
  446. return f(s.store.CompareAndSwap(r.Path, r.PrevValue, r.PrevIndex, r.Val, expr))
  447. default:
  448. return f(s.store.Set(r.Path, r.Dir, r.Val, expr))
  449. }
  450. case "DELETE":
  451. switch {
  452. case r.PrevIndex > 0 || r.PrevValue != "":
  453. return f(s.store.CompareAndDelete(r.Path, r.PrevValue, r.PrevIndex))
  454. default:
  455. return f(s.store.Delete(r.Path, r.Dir, r.Recursive))
  456. }
  457. case "QGET":
  458. return f(s.store.Get(r.Path, r.Recursive, r.Sorted))
  459. case "SYNC":
  460. s.store.DeleteExpiredKeys(time.Unix(0, r.Time))
  461. return Response{}
  462. default:
  463. // This should never be reached, but just in case:
  464. return Response{err: ErrUnknownMethod}
  465. }
  466. }
  467. func (s *EtcdServer) applyConfChange(cc raftpb.ConfChange) {
  468. s.node.ApplyConfChange(cc)
  469. switch cc.Type {
  470. case raftpb.ConfChangeAddNode:
  471. var m Member
  472. if err := json.Unmarshal(cc.Context, &m); err != nil {
  473. panic("unexpected unmarshal error")
  474. }
  475. if cc.NodeID != m.ID {
  476. panic("unexpected nodeID mismatch")
  477. }
  478. s.ClusterStore.Add(m)
  479. case raftpb.ConfChangeRemoveNode:
  480. s.ClusterStore.Remove(cc.NodeID)
  481. default:
  482. panic("unexpected ConfChange type")
  483. }
  484. }
  485. // TODO: non-blocking snapshot
  486. func (s *EtcdServer) snapshot(snapi uint64, snapnodes []uint64) {
  487. d, err := s.store.Save()
  488. // TODO: current store will never fail to do a snapshot
  489. // what should we do if the store might fail?
  490. if err != nil {
  491. panic("TODO: this is bad, what do we do about it?")
  492. }
  493. s.node.Compact(snapi, snapnodes, d)
  494. s.storage.Cut()
  495. }
  496. func startNode(cfg *ServerConfig) (n raft.Node, w *wal.WAL) {
  497. i := pb.Info{ID: cfg.ID()}
  498. b, err := i.Marshal()
  499. if err != nil {
  500. log.Fatal(err)
  501. }
  502. if w, err = wal.Create(cfg.WALDir(), b); err != nil {
  503. log.Fatal(err)
  504. }
  505. ids := cfg.Cluster.IDs()
  506. peers := make([]raft.Peer, len(ids))
  507. for i, id := range ids {
  508. ctx, err := json.Marshal((*cfg.Cluster)[id])
  509. if err != nil {
  510. log.Fatal(err)
  511. }
  512. peers[i] = raft.Peer{ID: id, Context: ctx}
  513. }
  514. n = raft.StartNode(cfg.ID(), peers, 10, 1)
  515. return
  516. }
  517. func restartNode(cfg *ServerConfig, index uint64, snapshot *raftpb.Snapshot) (n raft.Node, w *wal.WAL) {
  518. var err error
  519. // restart a node from previous wal
  520. if w, err = wal.OpenAtIndex(cfg.WALDir(), index); err != nil {
  521. log.Fatal(err)
  522. }
  523. md, st, ents, err := w.ReadAll()
  524. if err != nil {
  525. log.Fatal(err)
  526. }
  527. var info pb.Info
  528. if err := info.Unmarshal(md); err != nil {
  529. log.Fatal(err)
  530. }
  531. n = raft.RestartNode(info.ID, 10, 1, snapshot, st, ents)
  532. return
  533. }
  534. // TODO: move the function to /id pkg maybe?
  535. // GenID generates a random id that is not equal to 0.
  536. func GenID() (n uint64) {
  537. for n == 0 {
  538. n = uint64(rand.Int63())
  539. }
  540. return
  541. }
  542. func getBool(v *bool) (vv bool, set bool) {
  543. if v == nil {
  544. return false, false
  545. }
  546. return *v, true
  547. }