policies.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  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. "fmt"
  8. "log"
  9. "sync"
  10. "sync/atomic"
  11. "github.com/hailocab/go-hostpool"
  12. )
  13. // cowHostList implements a copy on write host list, its equivilent type is []*HostInfo
  14. type cowHostList struct {
  15. list atomic.Value
  16. mu sync.Mutex
  17. }
  18. func (c *cowHostList) String() string {
  19. return fmt.Sprintf("%+v", c.get())
  20. }
  21. func (c *cowHostList) get() []*HostInfo {
  22. // TODO(zariel): should we replace this with []*HostInfo?
  23. l, ok := c.list.Load().(*[]*HostInfo)
  24. if !ok {
  25. return nil
  26. }
  27. return *l
  28. }
  29. func (c *cowHostList) set(list []*HostInfo) {
  30. c.mu.Lock()
  31. c.list.Store(&list)
  32. c.mu.Unlock()
  33. }
  34. // add will add a host if it not already in the list
  35. func (c *cowHostList) add(host *HostInfo) bool {
  36. c.mu.Lock()
  37. l := c.get()
  38. if n := len(l); n == 0 {
  39. l = []*HostInfo{host}
  40. } else {
  41. newL := make([]*HostInfo, n+1)
  42. for i := 0; i < n; i++ {
  43. if host.Equal(l[i]) {
  44. c.mu.Unlock()
  45. return false
  46. }
  47. newL[i] = l[i]
  48. }
  49. newL[n] = host
  50. l = newL
  51. }
  52. c.list.Store(&l)
  53. c.mu.Unlock()
  54. return true
  55. }
  56. func (c *cowHostList) update(host *HostInfo) {
  57. c.mu.Lock()
  58. l := c.get()
  59. if len(l) == 0 {
  60. c.mu.Unlock()
  61. return
  62. }
  63. found := false
  64. newL := make([]*HostInfo, len(l))
  65. for i := range l {
  66. if host.Equal(l[i]) {
  67. newL[i] = host
  68. found = true
  69. } else {
  70. newL[i] = l[i]
  71. }
  72. }
  73. if found {
  74. c.list.Store(&newL)
  75. }
  76. c.mu.Unlock()
  77. }
  78. func (c *cowHostList) remove(addr string) bool {
  79. c.mu.Lock()
  80. l := c.get()
  81. size := len(l)
  82. if size == 0 {
  83. c.mu.Unlock()
  84. return false
  85. }
  86. found := false
  87. newL := make([]*HostInfo, 0, size)
  88. for i := 0; i < len(l); i++ {
  89. if l[i].Peer() != addr {
  90. newL = append(newL, l[i])
  91. } else {
  92. found = true
  93. }
  94. }
  95. if !found {
  96. c.mu.Unlock()
  97. return false
  98. }
  99. newL = newL[:size-1 : size-1]
  100. c.list.Store(&newL)
  101. c.mu.Unlock()
  102. return true
  103. }
  104. // RetryableQuery is an interface that represents a query or batch statement that
  105. // exposes the correct functions for the retry policy logic to evaluate correctly.
  106. type RetryableQuery interface {
  107. Attempts() int
  108. GetConsistency() Consistency
  109. }
  110. // RetryPolicy interface is used by gocql to determine if a query can be attempted
  111. // again after a retryable error has been received. The interface allows gocql
  112. // users to implement their own logic to determine if a query can be attempted
  113. // again.
  114. //
  115. // See SimpleRetryPolicy as an example of implementing and using a RetryPolicy
  116. // interface.
  117. type RetryPolicy interface {
  118. Attempt(RetryableQuery) bool
  119. }
  120. // SimpleRetryPolicy has simple logic for attempting a query a fixed number of times.
  121. //
  122. // See below for examples of usage:
  123. //
  124. // //Assign to the cluster
  125. // cluster.RetryPolicy = &gocql.SimpleRetryPolicy{NumRetries: 3}
  126. //
  127. // //Assign to a query
  128. // query.RetryPolicy(&gocql.SimpleRetryPolicy{NumRetries: 1})
  129. //
  130. type SimpleRetryPolicy struct {
  131. NumRetries int //Number of times to retry a query
  132. }
  133. // Attempt tells gocql to attempt the query again based on query.Attempts being less
  134. // than the NumRetries defined in the policy.
  135. func (s *SimpleRetryPolicy) Attempt(q RetryableQuery) bool {
  136. return q.Attempts() <= s.NumRetries
  137. }
  138. type HostStateNotifier interface {
  139. AddHost(host *HostInfo)
  140. RemoveHost(addr string)
  141. HostUp(host *HostInfo)
  142. HostDown(addr string)
  143. }
  144. // HostSelectionPolicy is an interface for selecting
  145. // the most appropriate host to execute a given query.
  146. type HostSelectionPolicy interface {
  147. HostStateNotifier
  148. SetPartitioner
  149. //Pick returns an iteration function over selected hosts
  150. Pick(ExecutableQuery) NextHost
  151. }
  152. // SelectedHost is an interface returned when picking a host from a host
  153. // selection policy.
  154. type SelectedHost interface {
  155. Info() *HostInfo
  156. Mark(error)
  157. }
  158. type selectedHost HostInfo
  159. func (host *selectedHost) Info() *HostInfo {
  160. return (*HostInfo)(host)
  161. }
  162. func (host *selectedHost) Mark(err error) {}
  163. // NextHost is an iteration function over picked hosts
  164. type NextHost func() SelectedHost
  165. // RoundRobinHostPolicy is a round-robin load balancing policy, where each host
  166. // is tried sequentially for each query.
  167. func RoundRobinHostPolicy() HostSelectionPolicy {
  168. return &roundRobinHostPolicy{}
  169. }
  170. type roundRobinHostPolicy struct {
  171. hosts cowHostList
  172. pos uint32
  173. mu sync.RWMutex
  174. }
  175. func (r *roundRobinHostPolicy) SetPartitioner(partitioner string) {
  176. // noop
  177. }
  178. func (r *roundRobinHostPolicy) Pick(qry ExecutableQuery) NextHost {
  179. // i is used to limit the number of attempts to find a host
  180. // to the number of hosts known to this policy
  181. var i int
  182. return func() SelectedHost {
  183. hosts := r.hosts.get()
  184. if len(hosts) == 0 {
  185. return nil
  186. }
  187. // always increment pos to evenly distribute traffic in case of
  188. // failures
  189. pos := atomic.AddUint32(&r.pos, 1) - 1
  190. if i >= len(hosts) {
  191. return nil
  192. }
  193. host := hosts[(pos)%uint32(len(hosts))]
  194. i++
  195. return (*selectedHost)(host)
  196. }
  197. }
  198. func (r *roundRobinHostPolicy) AddHost(host *HostInfo) {
  199. r.hosts.add(host)
  200. }
  201. func (r *roundRobinHostPolicy) RemoveHost(addr string) {
  202. r.hosts.remove(addr)
  203. }
  204. func (r *roundRobinHostPolicy) HostUp(host *HostInfo) {
  205. r.AddHost(host)
  206. }
  207. func (r *roundRobinHostPolicy) HostDown(addr string) {
  208. r.RemoveHost(addr)
  209. }
  210. // TokenAwareHostPolicy is a token aware host selection policy, where hosts are
  211. // selected based on the partition key, so queries are sent to the host which
  212. // owns the partition. Fallback is used when routing information is not available.
  213. func TokenAwareHostPolicy(fallback HostSelectionPolicy) HostSelectionPolicy {
  214. return &tokenAwareHostPolicy{fallback: fallback}
  215. }
  216. type tokenAwareHostPolicy struct {
  217. hosts cowHostList
  218. mu sync.RWMutex
  219. partitioner string
  220. tokenRing *tokenRing
  221. fallback HostSelectionPolicy
  222. }
  223. func (t *tokenAwareHostPolicy) SetPartitioner(partitioner string) {
  224. t.mu.Lock()
  225. defer t.mu.Unlock()
  226. if t.partitioner != partitioner {
  227. t.fallback.SetPartitioner(partitioner)
  228. t.partitioner = partitioner
  229. t.resetTokenRing()
  230. }
  231. }
  232. func (t *tokenAwareHostPolicy) AddHost(host *HostInfo) {
  233. t.hosts.add(host)
  234. t.fallback.AddHost(host)
  235. t.mu.Lock()
  236. t.resetTokenRing()
  237. t.mu.Unlock()
  238. }
  239. func (t *tokenAwareHostPolicy) RemoveHost(addr string) {
  240. t.hosts.remove(addr)
  241. t.fallback.RemoveHost(addr)
  242. t.mu.Lock()
  243. t.resetTokenRing()
  244. t.mu.Unlock()
  245. }
  246. func (t *tokenAwareHostPolicy) HostUp(host *HostInfo) {
  247. t.AddHost(host)
  248. }
  249. func (t *tokenAwareHostPolicy) HostDown(addr string) {
  250. t.RemoveHost(addr)
  251. }
  252. func (t *tokenAwareHostPolicy) resetTokenRing() {
  253. if t.partitioner == "" {
  254. // partitioner not yet set
  255. return
  256. }
  257. // create a new token ring
  258. hosts := t.hosts.get()
  259. tokenRing, err := newTokenRing(t.partitioner, hosts)
  260. if err != nil {
  261. log.Printf("Unable to update the token ring due to error: %s", err)
  262. return
  263. }
  264. // replace the token ring
  265. t.tokenRing = tokenRing
  266. }
  267. func (t *tokenAwareHostPolicy) Pick(qry ExecutableQuery) NextHost {
  268. if qry == nil {
  269. return t.fallback.Pick(qry)
  270. }
  271. routingKey, err := qry.GetRoutingKey()
  272. if err != nil {
  273. return t.fallback.Pick(qry)
  274. }
  275. if routingKey == nil {
  276. return t.fallback.Pick(qry)
  277. }
  278. t.mu.RLock()
  279. // TODO retrieve a list of hosts based on the replication strategy
  280. host := t.tokenRing.GetHostForPartitionKey(routingKey)
  281. t.mu.RUnlock()
  282. if host == nil {
  283. return t.fallback.Pick(qry)
  284. }
  285. // scope these variables for the same lifetime as the iterator function
  286. var (
  287. hostReturned bool
  288. fallbackIter NextHost
  289. )
  290. return func() SelectedHost {
  291. if !hostReturned {
  292. hostReturned = true
  293. return (*selectedHost)(host)
  294. }
  295. // fallback
  296. if fallbackIter == nil {
  297. fallbackIter = t.fallback.Pick(qry)
  298. }
  299. fallbackHost := fallbackIter()
  300. // filter the token aware selected hosts from the fallback hosts
  301. if fallbackHost != nil && fallbackHost.Info() == host {
  302. fallbackHost = fallbackIter()
  303. }
  304. return fallbackHost
  305. }
  306. }
  307. // HostPoolHostPolicy is a host policy which uses the bitly/go-hostpool library
  308. // to distribute queries between hosts and prevent sending queries to
  309. // unresponsive hosts. When creating the host pool that is passed to the policy
  310. // use an empty slice of hosts as the hostpool will be populated later by gocql.
  311. // See below for examples of usage:
  312. //
  313. // // Create host selection policy using a simple host pool
  314. // cluster.PoolConfig.HostSelectionPolicy = HostPoolHostPolicy(hostpool.New(nil))
  315. //
  316. // // Create host selection policy using an epsilon greddy pool
  317. // cluster.PoolConfig.HostSelectionPolicy = HostPoolHostPolicy(
  318. // hostpool.NewEpsilonGreedy(nil, 0, &hostpool.LinearEpsilonValueCalculator{}),
  319. // )
  320. //
  321. func HostPoolHostPolicy(hp hostpool.HostPool) HostSelectionPolicy {
  322. return &hostPoolHostPolicy{hostMap: map[string]*HostInfo{}, hp: hp}
  323. }
  324. type hostPoolHostPolicy struct {
  325. hp hostpool.HostPool
  326. mu sync.RWMutex
  327. hostMap map[string]*HostInfo
  328. }
  329. func (r *hostPoolHostPolicy) SetHosts(hosts []*HostInfo) {
  330. peers := make([]string, len(hosts))
  331. hostMap := make(map[string]*HostInfo, len(hosts))
  332. for i, host := range hosts {
  333. peers[i] = host.Peer()
  334. hostMap[host.Peer()] = host
  335. }
  336. r.mu.Lock()
  337. r.hp.SetHosts(peers)
  338. r.hostMap = hostMap
  339. r.mu.Unlock()
  340. }
  341. func (r *hostPoolHostPolicy) AddHost(host *HostInfo) {
  342. r.mu.Lock()
  343. defer r.mu.Unlock()
  344. if _, ok := r.hostMap[host.Peer()]; ok {
  345. return
  346. }
  347. hosts := make([]string, 0, len(r.hostMap)+1)
  348. for addr := range r.hostMap {
  349. hosts = append(hosts, addr)
  350. }
  351. hosts = append(hosts, host.Peer())
  352. r.hp.SetHosts(hosts)
  353. r.hostMap[host.Peer()] = host
  354. }
  355. func (r *hostPoolHostPolicy) RemoveHost(addr string) {
  356. r.mu.Lock()
  357. defer r.mu.Unlock()
  358. if _, ok := r.hostMap[addr]; !ok {
  359. return
  360. }
  361. delete(r.hostMap, addr)
  362. hosts := make([]string, 0, len(r.hostMap))
  363. for addr := range r.hostMap {
  364. hosts = append(hosts, addr)
  365. }
  366. r.hp.SetHosts(hosts)
  367. }
  368. func (r *hostPoolHostPolicy) HostUp(host *HostInfo) {
  369. r.AddHost(host)
  370. }
  371. func (r *hostPoolHostPolicy) HostDown(addr string) {
  372. r.RemoveHost(addr)
  373. }
  374. func (r *hostPoolHostPolicy) SetPartitioner(partitioner string) {
  375. // noop
  376. }
  377. func (r *hostPoolHostPolicy) Pick(qry ExecutableQuery) NextHost {
  378. return func() SelectedHost {
  379. r.mu.RLock()
  380. defer r.mu.RUnlock()
  381. if len(r.hostMap) == 0 {
  382. return nil
  383. }
  384. hostR := r.hp.Get()
  385. host, ok := r.hostMap[hostR.Host()]
  386. if !ok {
  387. return nil
  388. }
  389. return selectedHostPoolHost{
  390. policy: r,
  391. info: host,
  392. hostR: hostR,
  393. }
  394. }
  395. }
  396. // selectedHostPoolHost is a host returned by the hostPoolHostPolicy and
  397. // implements the SelectedHost interface
  398. type selectedHostPoolHost struct {
  399. policy *hostPoolHostPolicy
  400. info *HostInfo
  401. hostR hostpool.HostPoolResponse
  402. }
  403. func (host selectedHostPoolHost) Info() *HostInfo {
  404. return host.info
  405. }
  406. func (host selectedHostPoolHost) Mark(err error) {
  407. host.policy.mu.RLock()
  408. defer host.policy.mu.RUnlock()
  409. if _, ok := host.policy.hostMap[host.info.Peer()]; !ok {
  410. // host was removed between pick and mark
  411. return
  412. }
  413. host.hostR.Mark(err)
  414. }