host_source.go 2.4 KB

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