status.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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 raft
  15. import (
  16. "fmt"
  17. "log"
  18. pb "github.com/coreos/etcd/raft/raftpb"
  19. )
  20. type Status struct {
  21. ID uint64
  22. pb.HardState
  23. SoftState
  24. Applied uint64
  25. Progress map[uint64]Progress
  26. }
  27. // getStatus gets a copy of the current raft status.
  28. func getStatus(r *raft) Status {
  29. s := Status{ID: r.id}
  30. s.HardState = r.HardState
  31. s.SoftState = *r.softState()
  32. s.Applied = r.raftLog.applied
  33. if s.RaftState == StateLeader {
  34. s.Progress = make(map[uint64]Progress)
  35. for id, p := range r.prs {
  36. s.Progress[id] = *p
  37. }
  38. }
  39. return s
  40. }
  41. // TODO: try to simplify this by introducing ID type into raft
  42. func (s Status) MarshalJSON() ([]byte, error) {
  43. j := fmt.Sprintf(`{"id":"%x","term":%d,"vote":"%x","commit":%d,"lead":"%x","raftState":"%s","progress":{`,
  44. s.ID, s.Term, s.Vote, s.Commit, s.Lead, s.RaftState)
  45. if len(s.Progress) == 0 {
  46. j += "}}"
  47. } else {
  48. for k, v := range s.Progress {
  49. subj := fmt.Sprintf(`"%x":{"match":%d,"next":%d},`, k, v.Match, v.Next)
  50. j += subj
  51. }
  52. // remove the trailing ","
  53. j = j[:len(j)-1] + "}}"
  54. }
  55. return []byte(j), nil
  56. }
  57. func (s Status) String() string {
  58. b, err := s.MarshalJSON()
  59. if err != nil {
  60. log.Panicf("unexpected error: %v", err)
  61. }
  62. return string(b)
  63. }