lock_nodes.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package v2
  2. import (
  3. "path"
  4. "sort"
  5. "strconv"
  6. "github.com/coreos/etcd/third_party/github.com/coreos/go-etcd/etcd"
  7. )
  8. // lockNodes is a wrapper for go-etcd's Nodes to allow for sorting by numeric key.
  9. type lockNodes struct {
  10. etcd.Nodes
  11. }
  12. // Less sorts the nodes by key (numerically).
  13. func (s lockNodes) Less(i, j int) bool {
  14. a, _ := strconv.Atoi(path.Base(s.Nodes[i].Key))
  15. b, _ := strconv.Atoi(path.Base(s.Nodes[j].Key))
  16. return a < b
  17. }
  18. // Retrieves the first node in the set of lock nodes.
  19. func (s lockNodes) First() *etcd.Node {
  20. sort.Sort(s)
  21. if len(s.Nodes) > 0 {
  22. return &s.Nodes[0]
  23. }
  24. return nil
  25. }
  26. // Retrieves the first node with a given value.
  27. func (s lockNodes) FindByValue(value string) (*etcd.Node, int) {
  28. sort.Sort(s)
  29. for i, node := range s.Nodes {
  30. if node.Value == value {
  31. return &node, i
  32. }
  33. }
  34. return nil, 0
  35. }
  36. // Find the node with the largest index in the lockNodes that is smaller than the given index. Also return the lastModified index of that node.
  37. func (s lockNodes) PrevIndex(index int) (int, int) {
  38. sort.Sort(s)
  39. // Iterate over each node to find the given index. We keep track of the
  40. // previous index on each iteration so we can return it when we match the
  41. // index we're looking for.
  42. var prevIndex int
  43. for _, node := range s.Nodes {
  44. idx, _ := strconv.Atoi(path.Base(node.Key))
  45. if index == idx {
  46. return prevIndex, int(node.ModifiedIndex)
  47. }
  48. prevIndex = idx
  49. }
  50. return 0, 0
  51. }