policies.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  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
  84. return func() SelectedHost {
  85. r.mu.RLock()
  86. defer r.mu.RUnlock()
  87. if len(r.hosts) == 0 {
  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. 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. // HostPoolHostPolicy is a host policy which uses the bitly/go-hostpool library
  214. // to distribute queries between hosts and prevent sending queries to
  215. // unresponsive hosts. When creating the host pool that is passed to the policy
  216. // use an empty slice of hosts as the hostpool will be populated later by gocql.
  217. // See below for examples of usage:
  218. //
  219. // // Create host selection policy using a simple host pool
  220. // cluster.PoolConfig.HostSelectionPolicy = HostPoolHostPolicy(hostpool.New(nil))
  221. //
  222. // // Create host selection policy using an epsilon greddy pool
  223. // cluster.PoolConfig.HostSelectionPolicy = HostPoolHostPolicy(
  224. // hostpool.NewEpsilonGreedy(nil, 0, &hostpool.LinearEpsilonValueCalculator{}),
  225. // )
  226. //
  227. func HostPoolHostPolicy(hp hostpool.HostPool) HostSelectionPolicy {
  228. return &hostPoolHostPolicy{hostMap: map[string]HostInfo{}, hp: hp}
  229. }
  230. type hostPoolHostPolicy struct {
  231. hp hostpool.HostPool
  232. hostMap map[string]HostInfo
  233. mu sync.RWMutex
  234. }
  235. func (r *hostPoolHostPolicy) SetHosts(hosts []HostInfo) {
  236. peers := make([]string, len(hosts))
  237. hostMap := make(map[string]HostInfo, len(hosts))
  238. for i, host := range hosts {
  239. peers[i] = host.Peer
  240. hostMap[host.Peer] = host
  241. }
  242. r.mu.Lock()
  243. r.hp.SetHosts(peers)
  244. r.hostMap = hostMap
  245. r.mu.Unlock()
  246. }
  247. func (r *hostPoolHostPolicy) SetPartitioner(partitioner string) {
  248. // noop
  249. }
  250. func (r *hostPoolHostPolicy) Pick(qry *Query) NextHost {
  251. return func() SelectedHost {
  252. r.mu.RLock()
  253. defer r.mu.RUnlock()
  254. if len(r.hostMap) == 0 {
  255. return nil
  256. }
  257. hostR := r.hp.Get()
  258. host, ok := r.hostMap[hostR.Host()]
  259. if !ok {
  260. return nil
  261. }
  262. return selectedHostPoolHost{&host, hostR}
  263. }
  264. }
  265. // selectedHostPoolHost is a host returned by the hostPoolHostPolicy and
  266. // implements the SelectedHost interface
  267. type selectedHostPoolHost struct {
  268. info *HostInfo
  269. hostR hostpool.HostPoolResponse
  270. }
  271. func (host selectedHostPoolHost) Info() *HostInfo {
  272. return host.info
  273. }
  274. func (host selectedHostPoolHost) Mark(err error) {
  275. host.hostR.Mark(err)
  276. }
  277. //ConnSelectionPolicy is an interface for selecting an
  278. //appropriate connection for executing a query
  279. type ConnSelectionPolicy interface {
  280. SetConns(conns []*Conn)
  281. Pick(*Query) *Conn
  282. }
  283. type roundRobinConnPolicy struct {
  284. conns []*Conn
  285. pos uint32
  286. mu sync.RWMutex
  287. }
  288. func RoundRobinConnPolicy() func() ConnSelectionPolicy {
  289. return func() ConnSelectionPolicy {
  290. return &roundRobinConnPolicy{}
  291. }
  292. }
  293. func (r *roundRobinConnPolicy) SetConns(conns []*Conn) {
  294. r.mu.Lock()
  295. r.conns = conns
  296. r.mu.Unlock()
  297. }
  298. func (r *roundRobinConnPolicy) Pick(qry *Query) *Conn {
  299. pos := atomic.AddUint32(&r.pos, 1)
  300. var conn *Conn
  301. r.mu.RLock()
  302. if len(r.conns) > 0 {
  303. conn = r.conns[pos%uint32(len(r.conns))]
  304. }
  305. r.mu.RUnlock()
  306. return conn
  307. }