ring.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package gocql
  2. import (
  3. "sync"
  4. )
  5. type ring struct {
  6. // endpoints are the set of endpoints which the driver will attempt to connect
  7. // to in the case it can not reach any of its hosts. They are also used to boot
  8. // strap the initial connection.
  9. endpoints []string
  10. // hosts are the set of all hosts in the cassandra ring that we know of
  11. mu sync.RWMutex
  12. hosts map[string]*HostInfo
  13. // TODO: we should store the ring metadata here also.
  14. }
  15. func (r *ring) getHost(addr string) *HostInfo {
  16. r.mu.RLock()
  17. host := r.hosts[addr]
  18. r.mu.RUnlock()
  19. return host
  20. }
  21. func (r *ring) allHosts() []*HostInfo {
  22. r.mu.RLock()
  23. hosts := make([]*HostInfo, 0, len(r.hosts))
  24. for _, host := range r.hosts {
  25. hosts = append(hosts, host)
  26. }
  27. r.mu.RUnlock()
  28. return hosts
  29. }
  30. func (r *ring) addHost(host *HostInfo) bool {
  31. r.mu.Lock()
  32. if r.hosts == nil {
  33. r.hosts = make(map[string]*HostInfo)
  34. }
  35. addr := host.Peer()
  36. _, ok := r.hosts[addr]
  37. r.hosts[addr] = host
  38. r.mu.Unlock()
  39. return ok
  40. }
  41. func (r *ring) addHostIfMissing(host *HostInfo) (*HostInfo, bool) {
  42. r.mu.Lock()
  43. if r.hosts == nil {
  44. r.hosts = make(map[string]*HostInfo)
  45. }
  46. addr := host.Peer()
  47. existing, ok := r.hosts[addr]
  48. if !ok {
  49. r.hosts[addr] = host
  50. existing = host
  51. }
  52. r.mu.Unlock()
  53. return existing, ok
  54. }
  55. func (r *ring) removeHost(addr string) bool {
  56. r.mu.Lock()
  57. if r.hosts == nil {
  58. r.hosts = make(map[string]*HostInfo)
  59. }
  60. _, ok := r.hosts[addr]
  61. delete(r.hosts, addr)
  62. r.mu.Unlock()
  63. return ok
  64. }