topology.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. // Copyright (c) 2012 The gocql Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package gocql
  5. import (
  6. "sync"
  7. "sync/atomic"
  8. )
  9. type Node interface {
  10. ExecuteQuery(qry *Query) (*Iter, error)
  11. ExecuteBatch(batch *Batch) error
  12. Close()
  13. }
  14. type RoundRobin struct {
  15. pool []Node
  16. pos uint32
  17. mu sync.RWMutex
  18. }
  19. func NewRoundRobin() *RoundRobin {
  20. return &RoundRobin{}
  21. }
  22. func (r *RoundRobin) AddNode(node Node) {
  23. r.mu.Lock()
  24. r.pool = append(r.pool, node)
  25. r.mu.Unlock()
  26. }
  27. func (r *RoundRobin) RemoveNode(node Node) {
  28. r.mu.Lock()
  29. n := len(r.pool)
  30. for i := 0; i < n; i++ {
  31. if r.pool[i] == node {
  32. r.pool[i], r.pool[n-1] = r.pool[n-1], r.pool[i]
  33. r.pool = r.pool[:n-1]
  34. break
  35. }
  36. }
  37. r.mu.Unlock()
  38. }
  39. func (r *RoundRobin) Size() int {
  40. r.mu.RLock()
  41. n := len(r.pool)
  42. r.mu.RUnlock()
  43. return n
  44. }
  45. func (r *RoundRobin) ExecuteQuery(qry *Query) (*Iter, error) {
  46. node := r.pick()
  47. if node == nil {
  48. return nil, ErrNoHostAvailable
  49. }
  50. return node.ExecuteQuery(qry)
  51. }
  52. func (r *RoundRobin) ExecuteBatch(batch *Batch) error {
  53. node := r.pick()
  54. if node == nil {
  55. return ErrNoHostAvailable
  56. }
  57. return node.ExecuteBatch(batch)
  58. }
  59. func (r *RoundRobin) pick() Node {
  60. pos := atomic.AddUint32(&r.pos, 1)
  61. var node Node
  62. r.mu.RLock()
  63. if len(r.pool) > 0 {
  64. node = r.pool[pos%uint32(len(r.pool))]
  65. }
  66. r.mu.RUnlock()
  67. return node
  68. }
  69. func (r *RoundRobin) Close() {
  70. r.mu.Lock()
  71. for i := 0; i < len(r.pool); i++ {
  72. r.pool[i].Close()
  73. }
  74. r.pool = nil
  75. r.mu.Unlock()
  76. }