host_source.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. package gocql
  2. import (
  3. "net"
  4. "time"
  5. )
  6. type HostInfo struct {
  7. Peer string
  8. DataCenter string
  9. Rack string
  10. HostId string
  11. Tokens []string
  12. }
  13. // Polls system.peers at a specific interval to find new hosts
  14. type ringDescriber struct {
  15. dcFilter string
  16. rackFilter string
  17. previous []HostInfo
  18. session *Session
  19. }
  20. func (r *ringDescriber) GetHosts() []HostInfo {
  21. // we need conn to be the same because we need to query system.peers and system.local
  22. // on the same node to get the whole cluster
  23. conn := r.session.Pool.Pick(nil)
  24. if conn == nil {
  25. return r.previous
  26. }
  27. query := r.session.Query("SELECT data_center, rack, host_id, tokens FROM system.local")
  28. iter := conn.executeQuery(query)
  29. host := &HostInfo{}
  30. iter.Scan(&host.DataCenter, &host.Rack, &host.HostId, &host.Tokens)
  31. if err := iter.Close(); err != nil {
  32. return r.previous
  33. }
  34. addr, _, err := net.SplitHostPort(conn.Address())
  35. if err != nil {
  36. // this should not happen, ever, as this is the address that was dialed by conn, here
  37. // a panic makes sense, please report a bug if it occurs.
  38. panic(err)
  39. }
  40. host.Peer = addr
  41. hosts := []HostInfo{*host}
  42. query = r.session.Query("SELECT peer, data_center, rack, host_id, tokens FROM system.peers")
  43. iter = conn.executeQuery(query)
  44. for iter.Scan(&host.Peer, &host.DataCenter, &host.Rack, &host.HostId, &host.Tokens) {
  45. if r.matchFilter(host) {
  46. hosts = append(hosts, *host)
  47. }
  48. }
  49. if err := iter.Close(); err != nil {
  50. return r.previous
  51. }
  52. r.previous = hosts
  53. return hosts
  54. }
  55. func (r *ringDescriber) matchFilter(host *HostInfo) bool {
  56. if r.dcFilter == "" && r.rackFilter == "" {
  57. return true
  58. }
  59. if r.dcFilter != "" && r.dcFilter != host.DataCenter {
  60. return false
  61. }
  62. if r.rackFilter != "" && r.rackFilter != host.Rack {
  63. return false
  64. }
  65. return true
  66. }
  67. func (h *ringDescriber) run(sleep time.Duration) {
  68. if sleep == 0 {
  69. sleep = 30 * time.Second
  70. }
  71. for {
  72. // if we have 0 hosts this will return the previous list of hosts to
  73. // attempt to reconnect to the cluster otherwise we would never find
  74. // downed hosts again, could possibly have an optimisation to only
  75. // try to add new hosts if GetHosts didnt error and the hosts didnt change.
  76. h.session.Pool.SetHosts(h.GetHosts())
  77. time.Sleep(sleep)
  78. }
  79. }