khenaidoo | 2672188 | 2021-08-11 17:42:52 -0400 | [diff] [blame] | 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 | |
| 15 | package raft |
| 16 | |
| 17 | import ( |
| 18 | "fmt" |
| 19 | |
| 20 | pb "github.com/coreos/etcd/raft/raftpb" |
| 21 | ) |
| 22 | |
| 23 | type Status struct { |
| 24 | ID uint64 |
| 25 | |
| 26 | pb.HardState |
| 27 | SoftState |
| 28 | |
| 29 | Applied uint64 |
| 30 | Progress map[uint64]Progress |
| 31 | |
| 32 | LeadTransferee uint64 |
| 33 | } |
| 34 | |
| 35 | // getStatus gets a copy of the current raft status. |
| 36 | func getStatus(r *raft) Status { |
| 37 | s := Status{ |
| 38 | ID: r.id, |
| 39 | LeadTransferee: r.leadTransferee, |
| 40 | } |
| 41 | |
| 42 | s.HardState = r.hardState() |
| 43 | s.SoftState = *r.softState() |
| 44 | |
| 45 | s.Applied = r.raftLog.applied |
| 46 | |
| 47 | if s.RaftState == StateLeader { |
| 48 | s.Progress = make(map[uint64]Progress) |
| 49 | for id, p := range r.prs { |
| 50 | s.Progress[id] = *p |
| 51 | } |
| 52 | |
| 53 | for id, p := range r.learnerPrs { |
| 54 | s.Progress[id] = *p |
| 55 | } |
| 56 | } |
| 57 | |
| 58 | return s |
| 59 | } |
| 60 | |
| 61 | // MarshalJSON translates the raft status into JSON. |
| 62 | // TODO: try to simplify this by introducing ID type into raft |
| 63 | func (s Status) MarshalJSON() ([]byte, error) { |
| 64 | j := fmt.Sprintf(`{"id":"%x","term":%d,"vote":"%x","commit":%d,"lead":"%x","raftState":%q,"applied":%d,"progress":{`, |
| 65 | s.ID, s.Term, s.Vote, s.Commit, s.Lead, s.RaftState, s.Applied) |
| 66 | |
| 67 | if len(s.Progress) == 0 { |
| 68 | j += "}," |
| 69 | } else { |
| 70 | for k, v := range s.Progress { |
| 71 | subj := fmt.Sprintf(`"%x":{"match":%d,"next":%d,"state":%q},`, k, v.Match, v.Next, v.State) |
| 72 | j += subj |
| 73 | } |
| 74 | // remove the trailing "," |
| 75 | j = j[:len(j)-1] + "}," |
| 76 | } |
| 77 | |
| 78 | j += fmt.Sprintf(`"leadtransferee":"%x"}`, s.LeadTransferee) |
| 79 | return []byte(j), nil |
| 80 | } |
| 81 | |
| 82 | func (s Status) String() string { |
| 83 | b, err := s.MarshalJSON() |
| 84 | if err != nil { |
| 85 | raftLogger.Panicf("unexpected error: %v", err) |
| 86 | } |
| 87 | return string(b) |
| 88 | } |