policies.go 9.0 KB

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