policies.go 8.5 KB

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