lock_nodes.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package v2
  2. import (
  3. "path"
  4. "sort"
  5. "strconv"
  6. "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. // Retrieves the index that occurs before a given index.
  37. func (s lockNodes) PrevIndex(index int) int {
  38. sort.Sort(s)
  39. var prevIndex int
  40. for _, node := range s.Nodes {
  41. idx, _ := strconv.Atoi(path.Base(node.Key))
  42. if index == idx {
  43. return prevIndex
  44. }
  45. prevIndex = idx
  46. }
  47. return 0
  48. }