util.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /*
  2. Copyright 2014 CoreOS, Inc.
  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. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package raft
  14. import (
  15. "bytes"
  16. "fmt"
  17. pb "github.com/coreos/etcd/raft/raftpb"
  18. )
  19. // uint64Slice implements sort interface
  20. type uint64Slice []uint64
  21. func (p uint64Slice) Len() int { return len(p) }
  22. func (p uint64Slice) Less(i, j int) bool { return p[i] < p[j] }
  23. func (p uint64Slice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  24. func min(a, b uint64) uint64 {
  25. if a > b {
  26. return b
  27. }
  28. return a
  29. }
  30. func max(a, b uint64) uint64 {
  31. if a > b {
  32. return a
  33. }
  34. return b
  35. }
  36. // DescribeMessage returns a concise human-readable description of a
  37. // Message for debugging.
  38. func DescribeMessage(m pb.Message) string {
  39. var buf bytes.Buffer
  40. fmt.Fprintf(&buf, "%d->%d %s Term:%d Log:%d/%d", m.From, m.To, m.Type, m.Term, m.LogTerm, m.Index)
  41. if m.Reject {
  42. fmt.Fprintf(&buf, " Rejected")
  43. }
  44. if m.Commit != 0 {
  45. fmt.Fprintf(&buf, " Commit:%d", m.Commit)
  46. }
  47. if len(m.Entries) > 0 {
  48. fmt.Fprintf(&buf, " Entries:[")
  49. for _, e := range m.Entries {
  50. buf.WriteString(DescribeEntry(e))
  51. }
  52. fmt.Fprintf(&buf, "]")
  53. }
  54. if !IsEmptySnap(m.Snapshot) {
  55. fmt.Fprintf(&buf, " Snapshot:%v", m.Snapshot)
  56. }
  57. return buf.String()
  58. }
  59. // DescribeEntry returns a concise human-readable description of an
  60. // Entry for debugging.
  61. func DescribeEntry(e pb.Entry) string {
  62. return fmt.Sprintf("%d/%d %s %q", e.Term, e.Index, e.Type, string(e.Data))
  63. }