status.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. // Copyright 2015 The etcd Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package raft
  15. import (
  16. "fmt"
  17. pb "github.com/coreos/etcd/raft/raftpb"
  18. )
  19. type Status struct {
  20. ID uint64
  21. pb.HardState
  22. SoftState
  23. Applied uint64
  24. Progress map[uint64]Progress
  25. LeadTransferee uint64
  26. }
  27. // getStatus gets a copy of the current raft status.
  28. func getStatus(r *raft) Status {
  29. s := Status{
  30. ID: r.id,
  31. LeadTransferee: r.leadTransferee,
  32. }
  33. s.HardState = r.hardState()
  34. s.SoftState = *r.softState()
  35. s.Applied = r.raftLog.applied
  36. if s.RaftState == StateLeader {
  37. s.Progress = make(map[uint64]Progress)
  38. for id, p := range r.prs {
  39. s.Progress[id] = *p
  40. }
  41. }
  42. return s
  43. }
  44. // MarshalJSON translates the raft status into JSON.
  45. // TODO: try to simplify this by introducing ID type into raft
  46. func (s Status) MarshalJSON() ([]byte, error) {
  47. j := fmt.Sprintf(`{"id":"%x","term":%d,"vote":"%x","commit":%d,"lead":"%x","raftState":%q,"applied":%d,"progress":{`,
  48. s.ID, s.Term, s.Vote, s.Commit, s.Lead, s.RaftState, s.Applied)
  49. if len(s.Progress) == 0 {
  50. j += "},"
  51. } else {
  52. for k, v := range s.Progress {
  53. subj := fmt.Sprintf(`"%x":{"match":%d,"next":%d,"state":%q},`, k, v.Match, v.Next, v.State)
  54. j += subj
  55. }
  56. // remove the trailing ","
  57. j = j[:len(j)-1] + "},"
  58. }
  59. j += fmt.Sprintf(`"leadtransferee":"%x"}`, s.LeadTransferee)
  60. return []byte(j), nil
  61. }
  62. func (s Status) String() string {
  63. b, err := s.MarshalJSON()
  64. if err != nil {
  65. raftLogger.Panicf("unexpected error: %v", err)
  66. }
  67. return string(b)
  68. }