policies.go 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  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 int
  84. return func() SelectedHost {
  85. r.mu.RLock()
  86. defer r.mu.RUnlock()
  87. if len(r.hosts) == 0 {
  88. return nil
  89. }
  90. // always increment pos to evenly distribute traffic in case of
  91. // failures
  92. pos := atomic.AddUint32(&r.pos, 1)
  93. if i >= len(r.hosts) {
  94. return nil
  95. }
  96. host := &r.hosts[(pos)%uint32(len(r.hosts))]
  97. i++
  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. t.mu.RLock()
  173. // TODO retrieve a list of hosts based on the replication strategy
  174. host := t.tokenRing.GetHostForPartitionKey(routingKey)
  175. t.mu.RUnlock()
  176. if host == nil {
  177. return t.fallback.Pick(qry)
  178. }
  179. // scope these variables for the same lifetime as the iterator function
  180. var (
  181. hostReturned bool
  182. fallbackIter NextHost
  183. )
  184. return func() SelectedHost {
  185. if !hostReturned {
  186. hostReturned = true
  187. return selectedTokenAwareHost{host}
  188. }
  189. // fallback
  190. if fallbackIter == nil {
  191. fallbackIter = t.fallback.Pick(qry)
  192. }
  193. fallbackHost := fallbackIter()
  194. // filter the token aware selected hosts from the fallback hosts
  195. if fallbackHost.Info() == host {
  196. fallbackHost = fallbackIter()
  197. }
  198. return fallbackHost
  199. }
  200. }
  201. // selectedTokenAwareHost is a host returned by the tokenAwareHostPolicy and
  202. // implements the SelectedHost interface
  203. type selectedTokenAwareHost struct {
  204. info *HostInfo
  205. }
  206. func (host selectedTokenAwareHost) Info() *HostInfo {
  207. return host.info
  208. }
  209. func (host selectedTokenAwareHost) Mark(err error) {
  210. // noop
  211. }
  212. // HostPoolHostPolicy is a host policy which uses the bitly/go-hostpool library
  213. // to distribute queries between hosts and prevent sending queries to
  214. // unresponsive hosts. When creating the host pool that is passed to the policy
  215. // use an empty slice of hosts as the hostpool will be populated later by gocql.
  216. // See below for examples of usage:
  217. //
  218. // // Create host selection policy using a simple host pool
  219. // cluster.PoolConfig.HostSelectionPolicy = HostPoolHostPolicy(hostpool.New(nil))
  220. //
  221. // // Create host selection policy using an epsilon greddy pool
  222. // cluster.PoolConfig.HostSelectionPolicy = HostPoolHostPolicy(
  223. // hostpool.NewEpsilonGreedy(nil, 0, &hostpool.LinearEpsilonValueCalculator{}),
  224. // )
  225. //
  226. func HostPoolHostPolicy(hp hostpool.HostPool) HostSelectionPolicy {
  227. return &hostPoolHostPolicy{hostMap: map[string]HostInfo{}, hp: hp}
  228. }
  229. type hostPoolHostPolicy struct {
  230. hp hostpool.HostPool
  231. hostMap map[string]HostInfo
  232. mu sync.RWMutex
  233. }
  234. func (r *hostPoolHostPolicy) SetHosts(hosts []HostInfo) {
  235. peers := make([]string, len(hosts))
  236. hostMap := make(map[string]HostInfo, len(hosts))
  237. for i, host := range hosts {
  238. peers[i] = host.Peer
  239. hostMap[host.Peer] = host
  240. }
  241. r.mu.Lock()
  242. r.hp.SetHosts(peers)
  243. r.hostMap = hostMap
  244. r.mu.Unlock()
  245. }
  246. func (r *hostPoolHostPolicy) SetPartitioner(partitioner string) {
  247. // noop
  248. }
  249. func (r *hostPoolHostPolicy) Pick(qry *Query) NextHost {
  250. return func() SelectedHost {
  251. r.mu.RLock()
  252. defer r.mu.RUnlock()
  253. if len(r.hostMap) == 0 {
  254. return nil
  255. }
  256. hostR := r.hp.Get()
  257. host, ok := r.hostMap[hostR.Host()]
  258. if !ok {
  259. return nil
  260. }
  261. return selectedHostPoolHost{&host, hostR}
  262. }
  263. }
  264. // selectedHostPoolHost is a host returned by the hostPoolHostPolicy and
  265. // implements the SelectedHost interface
  266. type selectedHostPoolHost struct {
  267. info *HostInfo
  268. hostR hostpool.HostPoolResponse
  269. }
  270. func (host selectedHostPoolHost) Info() *HostInfo {
  271. return host.info
  272. }
  273. func (host selectedHostPoolHost) Mark(err error) {
  274. host.hostR.Mark(err)
  275. }
  276. //ConnSelectionPolicy is an interface for selecting an
  277. //appropriate connection for executing a query
  278. type ConnSelectionPolicy interface {
  279. SetConns(conns []*Conn)
  280. Pick(*Query) *Conn
  281. }
  282. type roundRobinConnPolicy struct {
  283. conns []*Conn
  284. pos uint32
  285. mu sync.RWMutex
  286. }
  287. func RoundRobinConnPolicy() func() ConnSelectionPolicy {
  288. return func() ConnSelectionPolicy {
  289. return &roundRobinConnPolicy{}
  290. }
  291. }
  292. func (r *roundRobinConnPolicy) SetConns(conns []*Conn) {
  293. r.mu.Lock()
  294. r.conns = conns
  295. r.mu.Unlock()
  296. }
  297. func (r *roundRobinConnPolicy) Pick(qry *Query) *Conn {
  298. pos := int(atomic.AddUint32(&r.pos, 1) - 1)
  299. r.mu.RLock()
  300. defer r.mu.RUnlock()
  301. if len(r.conns) == 0 {
  302. return nil
  303. }
  304. for i := 0; i < len(r.conns); i++ {
  305. conn := r.conns[(pos+i)%len(r.conns)]
  306. if conn.AvailableStreams() > 0 {
  307. return conn
  308. }
  309. }
  310. return nil
  311. }