status.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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 "go.etcd.io/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. func getProgressCopy(r *raft) map[uint64]Progress {
  28. prs := make(map[uint64]Progress)
  29. for id, p := range r.prs {
  30. prs[id] = *p
  31. }
  32. for id, p := range r.learnerPrs {
  33. prs[id] = *p
  34. }
  35. return prs
  36. }
  37. func getStatusWithoutProgress(r *raft) Status {
  38. s := Status{
  39. ID: r.id,
  40. LeadTransferee: r.leadTransferee,
  41. }
  42. s.HardState = r.hardState()
  43. s.SoftState = *r.softState()
  44. s.Applied = r.raftLog.applied
  45. return s
  46. }
  47. // getStatus gets a copy of the current raft status.
  48. func getStatus(r *raft) Status {
  49. s := getStatusWithoutProgress(r)
  50. if s.RaftState == StateLeader {
  51. s.Progress = getProgressCopy(r)
  52. }
  53. return s
  54. }
  55. // MarshalJSON translates the raft status into JSON.
  56. // TODO: try to simplify this by introducing ID type into raft
  57. func (s Status) MarshalJSON() ([]byte, error) {
  58. j := fmt.Sprintf(`{"id":"%x","term":%d,"vote":"%x","commit":%d,"lead":"%x","raftState":%q,"applied":%d,"progress":{`,
  59. s.ID, s.Term, s.Vote, s.Commit, s.Lead, s.RaftState, s.Applied)
  60. if len(s.Progress) == 0 {
  61. j += "},"
  62. } else {
  63. for k, v := range s.Progress {
  64. subj := fmt.Sprintf(`"%x":{"match":%d,"next":%d,"state":%q},`, k, v.Match, v.Next, v.State)
  65. j += subj
  66. }
  67. // remove the trailing ","
  68. j = j[:len(j)-1] + "},"
  69. }
  70. j += fmt.Sprintf(`"leadtransferee":"%x"}`, s.LeadTransferee)
  71. return []byte(j), nil
  72. }
  73. func (s Status) String() string {
  74. b, err := s.MarshalJSON()
  75. if err != nil {
  76. raftLogger.Panicf("unexpected error: %v", err)
  77. }
  78. return string(b)
  79. }