policies.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  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. //This file will be the future home for more policies
  5. package gocql
  6. import (
  7. "log"
  8. "sync"
  9. "sync/atomic"
  10. )
  11. // RetryableQuery is an interface that represents a query or batch statement that
  12. // exposes the correct functions for the retry policy logic to evaluate correctly.
  13. type RetryableQuery interface {
  14. Attempts() int
  15. GetConsistency() Consistency
  16. }
  17. // RetryPolicy interface is used by gocql to determine if a query can be attempted
  18. // again after a retryable error has been received. The interface allows gocql
  19. // users to implement their own logic to determine if a query can be attempted
  20. // again.
  21. //
  22. // See SimpleRetryPolicy as an example of implementing and using a RetryPolicy
  23. // interface.
  24. type RetryPolicy interface {
  25. Attempt(RetryableQuery) bool
  26. }
  27. // SimpleRetryPolicy has simple logic for attempting a query a fixed number of times.
  28. //
  29. // See below for examples of usage:
  30. //
  31. // //Assign to the cluster
  32. // cluster.RetryPolicy = &gocql.SimpleRetryPolicy{NumRetries: 3}
  33. //
  34. // //Assign to a query
  35. // query.RetryPolicy(&gocql.SimpleRetryPolicy{NumRetries: 1})
  36. //
  37. type SimpleRetryPolicy struct {
  38. NumRetries int //Number of times to retry a query
  39. }
  40. // Attempt tells gocql to attempt the query again based on query.Attempts being less
  41. // than the NumRetries defined in the policy.
  42. func (s *SimpleRetryPolicy) Attempt(q RetryableQuery) bool {
  43. return q.Attempts() <= s.NumRetries
  44. }
  45. // HostSelectionPolicy is an interface for selecting
  46. // the most appropriate host to execute a given query.
  47. type HostSelectionPolicy interface {
  48. SetHosts
  49. SetPartitioner
  50. //Pick returns an iteration function over selected hosts
  51. Pick(*Query) NextHost
  52. }
  53. // SelectedHost is an interface returned when picking a host from a host
  54. // selection policy.
  55. type SelectedHost interface {
  56. Info() *HostInfo
  57. Mark(error)
  58. }
  59. // NextHost is an iteration function over picked hosts
  60. type NextHost func() SelectedHost
  61. // RoundRobinHostPolicy is a round-robin load balancing policy, where each host
  62. // is tried sequentially for each query.
  63. func RoundRobinHostPolicy() HostSelectionPolicy {
  64. return &roundRobinHostPolicy{hosts: []HostInfo{}}
  65. }
  66. type roundRobinHostPolicy struct {
  67. hosts []HostInfo
  68. pos uint32
  69. mu sync.RWMutex
  70. }
  71. func (r *roundRobinHostPolicy) SetHosts(hosts []HostInfo) {
  72. r.mu.Lock()
  73. r.hosts = hosts
  74. r.mu.Unlock()
  75. }
  76. func (r *roundRobinHostPolicy) SetPartitioner(partitioner string) {
  77. // noop
  78. }
  79. func (r *roundRobinHostPolicy) Pick(qry *Query) NextHost {
  80. // i is used to limit the number of attempts to find a host
  81. // to the number of hosts known to this policy
  82. var i uint32 = 0
  83. return func() SelectedHost {
  84. r.mu.RLock()
  85. if len(r.hosts) == 0 {
  86. r.mu.RUnlock()
  87. return nil
  88. }
  89. var host *HostInfo
  90. // always increment pos to evenly distribute traffic in case of
  91. // failures
  92. pos := atomic.AddUint32(&r.pos, 1)
  93. if int(i) < len(r.hosts) {
  94. host = &r.hosts[(pos)%uint32(len(r.hosts))]
  95. i++
  96. }
  97. r.mu.RUnlock()
  98. return selectedRoundRobinHost{host}
  99. }
  100. }
  101. // selectedRoundRobinHost is a host returned by the roundRobinHostPolicy and
  102. // implements the SelectedHost interface
  103. type selectedRoundRobinHost struct {
  104. info *HostInfo
  105. }
  106. func (host selectedRoundRobinHost) Info() *HostInfo {
  107. return host.info
  108. }
  109. func (host selectedRoundRobinHost) Mark(err error) {
  110. // noop
  111. }
  112. // TokenAwareHostPolicy is a token aware host selection policy, where hosts are
  113. // selected based on the partition key, so queries are sent to the host which
  114. // owns the partition. Fallback is used when routing information is not available.
  115. func TokenAwareHostPolicy(fallback HostSelectionPolicy) HostSelectionPolicy {
  116. return &tokenAwareHostPolicy{fallback: fallback, hosts: []HostInfo{}}
  117. }
  118. type tokenAwareHostPolicy struct {
  119. mu sync.RWMutex
  120. hosts []HostInfo
  121. partitioner string
  122. tokenRing *tokenRing
  123. fallback HostSelectionPolicy
  124. }
  125. func (t *tokenAwareHostPolicy) SetHosts(hosts []HostInfo) {
  126. t.mu.Lock()
  127. defer t.mu.Unlock()
  128. // always update the fallback
  129. t.fallback.SetHosts(hosts)
  130. t.hosts = hosts
  131. t.resetTokenRing()
  132. }
  133. func (t *tokenAwareHostPolicy) SetPartitioner(partitioner string) {
  134. t.mu.Lock()
  135. defer t.mu.Unlock()
  136. if t.partitioner != partitioner {
  137. t.fallback.SetPartitioner(partitioner)
  138. t.partitioner = partitioner
  139. t.resetTokenRing()
  140. }
  141. }
  142. func (t *tokenAwareHostPolicy) resetTokenRing() {
  143. if t.partitioner == "" {
  144. // partitioner not yet set
  145. return
  146. }
  147. // create a new token ring
  148. tokenRing, err := newTokenRing(t.partitioner, t.hosts)
  149. if err != nil {
  150. log.Printf("Unable to update the token ring due to error: %s", err)
  151. return
  152. }
  153. // replace the token ring
  154. t.tokenRing = tokenRing
  155. }
  156. func (t *tokenAwareHostPolicy) Pick(qry *Query) NextHost {
  157. if qry == nil {
  158. return t.fallback.Pick(qry)
  159. } else if qry.binding != nil && len(qry.values) == 0 {
  160. // If this query was created using session.Bind we wont have the query
  161. // values yet, so we have to pass down to the next policy.
  162. // TODO: Remove this and handle this case
  163. return t.fallback.Pick(qry)
  164. }
  165. routingKey, err := qry.GetRoutingKey()
  166. if err != nil {
  167. return t.fallback.Pick(qry)
  168. }
  169. if routingKey == nil {
  170. return t.fallback.Pick(qry)
  171. }
  172. var host *HostInfo
  173. t.mu.RLock()
  174. // TODO retrieve a list of hosts based on the replication strategy
  175. host = t.tokenRing.GetHostForPartitionKey(routingKey)
  176. t.mu.RUnlock()
  177. if host == nil {
  178. return t.fallback.Pick(qry)
  179. }
  180. // scope these variables for the same lifetime as the iterator function
  181. var (
  182. hostReturned bool
  183. fallbackIter NextHost
  184. )
  185. return func() SelectedHost {
  186. if !hostReturned {
  187. hostReturned = true
  188. return selectedTokenAwareHost{host}
  189. }
  190. // fallback
  191. if fallbackIter == nil {
  192. fallbackIter = t.fallback.Pick(qry)
  193. }
  194. fallbackHost := fallbackIter()
  195. // filter the token aware selected hosts from the fallback hosts
  196. if fallbackHost.Info() == host {
  197. fallbackHost = fallbackIter()
  198. }
  199. return fallbackHost
  200. }
  201. }
  202. // selectedTokenAwareHost is a host returned by the tokenAwareHostPolicy and
  203. // implements the SelectedHost interface
  204. type selectedTokenAwareHost struct {
  205. info *HostInfo
  206. }
  207. func (host selectedTokenAwareHost) Info() *HostInfo {
  208. return host.info
  209. }
  210. func (host selectedTokenAwareHost) Mark(err error) {
  211. // noop
  212. }
  213. //ConnSelectionPolicy is an interface for selecting an
  214. //appropriate connection for executing a query
  215. type ConnSelectionPolicy interface {
  216. SetConns(conns []*Conn)
  217. Pick(*Query) *Conn
  218. }
  219. type roundRobinConnPolicy struct {
  220. conns []*Conn
  221. pos uint32
  222. mu sync.RWMutex
  223. }
  224. func RoundRobinConnPolicy() func() ConnSelectionPolicy {
  225. return func() ConnSelectionPolicy {
  226. return &roundRobinConnPolicy{}
  227. }
  228. }
  229. func (r *roundRobinConnPolicy) SetConns(conns []*Conn) {
  230. r.mu.Lock()
  231. r.conns = conns
  232. r.mu.Unlock()
  233. }
  234. func (r *roundRobinConnPolicy) Pick(qry *Query) *Conn {
  235. pos := atomic.AddUint32(&r.pos, 1)
  236. var conn *Conn
  237. r.mu.RLock()
  238. if len(r.conns) > 0 {
  239. conn = r.conns[pos%uint32(len(r.conns))]
  240. }
  241. r.mu.RUnlock()
  242. return conn
  243. }