ring.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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) bool {
  42. r.mu.Lock()
  43. if r.hosts == nil {
  44. r.hosts = make(map[string]*HostInfo)
  45. }
  46. addr := host.Peer()
  47. _, ok := r.hosts[addr]
  48. if !ok {
  49. r.hosts[addr] = host
  50. }
  51. r.mu.Unlock()
  52. return ok
  53. }
  54. func (r *ring) removeHost(addr string) bool {
  55. r.mu.Lock()
  56. if r.hosts == nil {
  57. r.hosts = make(map[string]*HostInfo)
  58. }
  59. _, ok := r.hosts[addr]
  60. delete(r.hosts, addr)
  61. r.mu.Unlock()
  62. return ok
  63. }