server.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  1. package etcdserver
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "log"
  6. "math/rand"
  7. "sync/atomic"
  8. "time"
  9. pb "github.com/coreos/etcd/etcdserver/etcdserverpb"
  10. "github.com/coreos/etcd/pkg/types"
  11. "github.com/coreos/etcd/raft"
  12. "github.com/coreos/etcd/raft/raftpb"
  13. "github.com/coreos/etcd/store"
  14. "github.com/coreos/etcd/third_party/code.google.com/p/go.net/context"
  15. "github.com/coreos/etcd/wait"
  16. )
  17. const (
  18. defaultSyncTimeout = time.Second
  19. DefaultSnapCount = 10000
  20. // TODO: calculated based on heartbeat interval
  21. defaultPublishRetryInterval = 5 * time.Second
  22. )
  23. var (
  24. ErrUnknownMethod = errors.New("etcdserver: unknown method")
  25. ErrStopped = errors.New("etcdserver: server stopped")
  26. )
  27. func init() {
  28. rand.Seed(time.Now().UnixNano())
  29. }
  30. type SendFunc func(m []raftpb.Message)
  31. type SaveFunc func(st raftpb.HardState, ents []raftpb.Entry)
  32. type Response struct {
  33. Event *store.Event
  34. Watcher store.Watcher
  35. err error
  36. }
  37. type Storage interface {
  38. // Save function saves ents and state to the underlying stable storage.
  39. // Save MUST block until st and ents are on stable storage.
  40. Save(st raftpb.HardState, ents []raftpb.Entry)
  41. // SaveSnap function saves snapshot to the underlying stable storage.
  42. SaveSnap(snap raftpb.Snapshot)
  43. // TODO: WAL should be able to control cut itself. After implement self-controled cut,
  44. // remove it in this interface.
  45. // Cut cuts out a new wal file for saving new state and entries.
  46. Cut() error
  47. }
  48. type Server interface {
  49. // Start performs any initialization of the Server necessary for it to
  50. // begin serving requests. It must be called before Do or Process.
  51. // Start must be non-blocking; any long-running server functionality
  52. // should be implemented in goroutines.
  53. Start()
  54. // Stop terminates the Server and performs any necessary finalization.
  55. // Do and Process cannot be called after Stop has been invoked.
  56. Stop()
  57. // Do takes a request and attempts to fulfil it, returning a Response.
  58. Do(ctx context.Context, r pb.Request) (Response, error)
  59. // Process takes a raft message and applies it to the server's raft state
  60. // machine, respecting any timeout of the given context.
  61. Process(ctx context.Context, m raftpb.Message) error
  62. }
  63. type RaftTimer interface {
  64. Index() int64
  65. Term() int64
  66. }
  67. // EtcdServer is the production implementation of the Server interface
  68. type EtcdServer struct {
  69. w wait.Wait
  70. done chan struct{}
  71. Name string
  72. ClientURLs types.URLs
  73. Node raft.Node
  74. Store store.Store
  75. // Send specifies the send function for sending msgs to members. Send
  76. // MUST NOT block. It is okay to drop messages, since clients should
  77. // timeout and reissue their messages. If Send is nil, server will
  78. // panic.
  79. Send SendFunc
  80. Storage Storage
  81. Ticker <-chan time.Time
  82. SyncTicker <-chan time.Time
  83. SnapCount int64 // number of entries to trigger a snapshot
  84. // Cache of the latest raft index and raft term the server has seen
  85. raftIndex int64
  86. raftTerm int64
  87. ClusterStore ClusterStore
  88. }
  89. // Start prepares and starts server in a new goroutine. It is no longer safe to
  90. // modify a server's fields after it has been sent to Start.
  91. // It also starts a goroutine to publish its server information.
  92. func (s *EtcdServer) Start() {
  93. s.start()
  94. go s.publish(defaultPublishRetryInterval)
  95. }
  96. // start prepares and starts server in a new goroutine. It is no longer safe to
  97. // modify a server's fields after it has been sent to Start.
  98. // This function is just used for testing.
  99. func (s *EtcdServer) start() {
  100. if s.SnapCount == 0 {
  101. log.Printf("etcdserver: set snapshot count to default %d", DefaultSnapCount)
  102. s.SnapCount = DefaultSnapCount
  103. }
  104. s.w = wait.New()
  105. s.done = make(chan struct{})
  106. // TODO: if this is an empty log, writes all peer infos
  107. // into the first entry
  108. go s.run()
  109. }
  110. func (s *EtcdServer) Process(ctx context.Context, m raftpb.Message) error {
  111. return s.Node.Step(ctx, m)
  112. }
  113. func (s *EtcdServer) run() {
  114. var syncC <-chan time.Time
  115. // snapi indicates the index of the last submitted snapshot request
  116. var snapi, appliedi int64
  117. for {
  118. select {
  119. case <-s.Ticker:
  120. s.Node.Tick()
  121. case rd := <-s.Node.Ready():
  122. s.Storage.Save(rd.HardState, rd.Entries)
  123. s.Storage.SaveSnap(rd.Snapshot)
  124. s.Send(rd.Messages)
  125. // TODO(bmizerany): do this in the background, but take
  126. // care to apply entries in a single goroutine, and not
  127. // race them.
  128. // TODO: apply configuration change into ClusterStore.
  129. for _, e := range rd.CommittedEntries {
  130. switch e.Type {
  131. case raftpb.EntryNormal:
  132. var r pb.Request
  133. if err := r.Unmarshal(e.Data); err != nil {
  134. panic("TODO: this is bad, what do we do about it?")
  135. }
  136. s.w.Trigger(r.ID, s.apply(r))
  137. case raftpb.EntryConfChange:
  138. var cc raftpb.ConfChange
  139. if err := cc.Unmarshal(e.Data); err != nil {
  140. panic("TODO: this is bad, what do we do about it?")
  141. }
  142. s.Node.ApplyConfChange(cc)
  143. s.w.Trigger(cc.ID, nil)
  144. default:
  145. panic("unexpected entry type")
  146. }
  147. atomic.StoreInt64(&s.raftIndex, e.Index)
  148. atomic.StoreInt64(&s.raftTerm, e.Term)
  149. appliedi = e.Index
  150. }
  151. if rd.Snapshot.Index > snapi {
  152. snapi = rd.Snapshot.Index
  153. }
  154. // recover from snapshot if it is more updated than current applied
  155. if rd.Snapshot.Index > appliedi {
  156. if err := s.Store.Recovery(rd.Snapshot.Data); err != nil {
  157. panic("TODO: this is bad, what do we do about it?")
  158. }
  159. appliedi = rd.Snapshot.Index
  160. }
  161. if appliedi-snapi > s.SnapCount {
  162. s.snapshot()
  163. snapi = appliedi
  164. }
  165. if rd.SoftState != nil {
  166. if rd.RaftState == raft.StateLeader {
  167. syncC = s.SyncTicker
  168. } else {
  169. syncC = nil
  170. }
  171. if rd.SoftState.ShouldStop {
  172. s.Stop()
  173. return
  174. }
  175. }
  176. case <-syncC:
  177. s.sync(defaultSyncTimeout)
  178. case <-s.done:
  179. return
  180. }
  181. }
  182. }
  183. // Stop stops the server, and shuts down the running goroutine. Stop should be
  184. // called after a Start(s), otherwise it will block forever.
  185. func (s *EtcdServer) Stop() {
  186. s.Node.Stop()
  187. close(s.done)
  188. }
  189. // Do interprets r and performs an operation on s.Store according to r.Method
  190. // and other fields. If r.Method is "POST", "PUT", "DELETE", or a "GET" with
  191. // Quorum == true, r will be sent through consensus before performing its
  192. // respective operation. Do will block until an action is performed or there is
  193. // an error.
  194. func (s *EtcdServer) Do(ctx context.Context, r pb.Request) (Response, error) {
  195. if r.ID == 0 {
  196. panic("r.Id cannot be 0")
  197. }
  198. if r.Method == "GET" && r.Quorum {
  199. r.Method = "QGET"
  200. }
  201. switch r.Method {
  202. case "POST", "PUT", "DELETE", "QGET":
  203. data, err := r.Marshal()
  204. if err != nil {
  205. return Response{}, err
  206. }
  207. ch := s.w.Register(r.ID)
  208. s.Node.Propose(ctx, data)
  209. select {
  210. case x := <-ch:
  211. resp := x.(Response)
  212. return resp, resp.err
  213. case <-ctx.Done():
  214. s.w.Trigger(r.ID, nil) // GC wait
  215. return Response{}, ctx.Err()
  216. case <-s.done:
  217. return Response{}, ErrStopped
  218. }
  219. case "GET":
  220. switch {
  221. case r.Wait:
  222. wc, err := s.Store.Watch(r.Path, r.Recursive, r.Stream, r.Since)
  223. if err != nil {
  224. return Response{}, err
  225. }
  226. return Response{Watcher: wc}, nil
  227. default:
  228. ev, err := s.Store.Get(r.Path, r.Recursive, r.Sorted)
  229. if err != nil {
  230. return Response{}, err
  231. }
  232. return Response{Event: ev}, nil
  233. }
  234. default:
  235. return Response{}, ErrUnknownMethod
  236. }
  237. }
  238. func (s *EtcdServer) AddNode(ctx context.Context, id int64, context []byte) error {
  239. cc := raftpb.ConfChange{
  240. ID: GenID(),
  241. Type: raftpb.ConfChangeAddNode,
  242. NodeID: id,
  243. Context: context,
  244. }
  245. return s.configure(ctx, cc)
  246. }
  247. func (s *EtcdServer) RemoveNode(ctx context.Context, id int64) error {
  248. cc := raftpb.ConfChange{
  249. ID: GenID(),
  250. Type: raftpb.ConfChangeRemoveNode,
  251. NodeID: id,
  252. }
  253. return s.configure(ctx, cc)
  254. }
  255. // Implement the RaftTimer interface
  256. func (s *EtcdServer) Index() int64 {
  257. return atomic.LoadInt64(&s.raftIndex)
  258. }
  259. func (s *EtcdServer) Term() int64 {
  260. return atomic.LoadInt64(&s.raftTerm)
  261. }
  262. // configure sends configuration change through consensus then performs it.
  263. // It will block until the change is performed or there is an error.
  264. func (s *EtcdServer) configure(ctx context.Context, cc raftpb.ConfChange) error {
  265. ch := s.w.Register(cc.ID)
  266. if err := s.Node.ProposeConfChange(ctx, cc); err != nil {
  267. log.Printf("configure error: %v", err)
  268. s.w.Trigger(cc.ID, nil)
  269. return err
  270. }
  271. select {
  272. case <-ch:
  273. return nil
  274. case <-ctx.Done():
  275. s.w.Trigger(cc.ID, nil) // GC wait
  276. return ctx.Err()
  277. case <-s.done:
  278. return ErrStopped
  279. }
  280. }
  281. // sync proposes a SYNC request and is non-blocking.
  282. // This makes no guarantee that the request will be proposed or performed.
  283. // The request will be cancelled after the given timeout.
  284. func (s *EtcdServer) sync(timeout time.Duration) {
  285. ctx, cancel := context.WithTimeout(context.Background(), timeout)
  286. req := pb.Request{
  287. Method: "SYNC",
  288. ID: GenID(),
  289. Time: time.Now().UnixNano(),
  290. }
  291. data, err := req.Marshal()
  292. if err != nil {
  293. log.Printf("marshal request %#v error: %v", req, err)
  294. return
  295. }
  296. // There is no promise that node has leader when do SYNC request,
  297. // so it uses goroutine to propose.
  298. go func() {
  299. s.Node.Propose(ctx, data)
  300. cancel()
  301. }()
  302. }
  303. // publish registers server information into the cluster. The information
  304. // is the json format of its self member struct, whose ClientURLs may be
  305. // updated.
  306. // The function keeps attempting to register until it succeeds,
  307. // or its server is stopped.
  308. // TODO: take care of info fetched from cluster store after having reconfig.
  309. func (s *EtcdServer) publish(retryInterval time.Duration) {
  310. m := *s.ClusterStore.Get().FindName(s.Name)
  311. m.ClientURLs = s.ClientURLs.StringSlice()
  312. b, err := json.Marshal(m)
  313. if err != nil {
  314. log.Printf("etcdserver: json marshal error: %v", err)
  315. return
  316. }
  317. req := pb.Request{
  318. ID: GenID(),
  319. Method: "PUT",
  320. Path: m.storeKey(),
  321. Val: string(b),
  322. }
  323. for {
  324. ctx, cancel := context.WithTimeout(context.Background(), retryInterval)
  325. _, err := s.Do(ctx, req)
  326. cancel()
  327. switch err {
  328. case nil:
  329. log.Printf("etcdserver: published %+v to the cluster", m)
  330. return
  331. case ErrStopped:
  332. log.Printf("etcdserver: aborting publish because server is stopped")
  333. return
  334. default:
  335. log.Printf("etcdserver: publish error: %v", err)
  336. }
  337. }
  338. }
  339. func getExpirationTime(r *pb.Request) time.Time {
  340. var t time.Time
  341. if r.Expiration != 0 {
  342. t = time.Unix(0, r.Expiration)
  343. }
  344. return t
  345. }
  346. // apply interprets r as a call to store.X and returns a Response interpreted
  347. // from store.Event
  348. func (s *EtcdServer) apply(r pb.Request) Response {
  349. f := func(ev *store.Event, err error) Response {
  350. return Response{Event: ev, err: err}
  351. }
  352. expr := getExpirationTime(&r)
  353. switch r.Method {
  354. case "POST":
  355. return f(s.Store.Create(r.Path, r.Dir, r.Val, true, expr))
  356. case "PUT":
  357. exists, existsSet := getBool(r.PrevExist)
  358. switch {
  359. case existsSet:
  360. if exists {
  361. return f(s.Store.Update(r.Path, r.Val, expr))
  362. }
  363. return f(s.Store.Create(r.Path, r.Dir, r.Val, false, expr))
  364. case r.PrevIndex > 0 || r.PrevValue != "":
  365. return f(s.Store.CompareAndSwap(r.Path, r.PrevValue, r.PrevIndex, r.Val, expr))
  366. default:
  367. return f(s.Store.Set(r.Path, r.Dir, r.Val, expr))
  368. }
  369. case "DELETE":
  370. switch {
  371. case r.PrevIndex > 0 || r.PrevValue != "":
  372. return f(s.Store.CompareAndDelete(r.Path, r.PrevValue, r.PrevIndex))
  373. default:
  374. return f(s.Store.Delete(r.Path, r.Dir, r.Recursive))
  375. }
  376. case "QGET":
  377. return f(s.Store.Get(r.Path, r.Recursive, r.Sorted))
  378. case "SYNC":
  379. s.Store.DeleteExpiredKeys(time.Unix(0, r.Time))
  380. return Response{}
  381. default:
  382. // This should never be reached, but just in case:
  383. return Response{err: ErrUnknownMethod}
  384. }
  385. }
  386. // TODO: non-blocking snapshot
  387. func (s *EtcdServer) snapshot() {
  388. d, err := s.Store.Save()
  389. // TODO: current store will never fail to do a snapshot
  390. // what should we do if the store might fail?
  391. if err != nil {
  392. panic("TODO: this is bad, what do we do about it?")
  393. }
  394. s.Node.Compact(d)
  395. s.Storage.Cut()
  396. }
  397. // TODO: move the function to /id pkg maybe?
  398. // GenID generates a random id that is not equal to 0.
  399. func GenID() (n int64) {
  400. for n == 0 {
  401. n = rand.Int63()
  402. }
  403. return
  404. }
  405. func getBool(v *bool) (vv bool, set bool) {
  406. if v == nil {
  407. return false, false
  408. }
  409. return *v, true
  410. }