policies.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  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. "net"
  9. "sync"
  10. "sync/atomic"
  11. "github.com/hailocab/go-hostpool"
  12. )
  13. // cowHostList implements a copy on write host list, its equivalent 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(ip net.IP) 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().Equal(ip) {
  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(host *HostInfo)
  141. HostUp(host *HostInfo)
  142. HostDown(host *HostInfo)
  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(host *HostInfo) {
  202. r.hosts.remove(host.Peer())
  203. }
  204. func (r *roundRobinHostPolicy) HostUp(host *HostInfo) {
  205. r.AddHost(host)
  206. }
  207. func (r *roundRobinHostPolicy) HostDown(host *HostInfo) {
  208. r.RemoveHost(host)
  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. if t.partitioner != partitioner {
  225. t.fallback.SetPartitioner(partitioner)
  226. t.partitioner = partitioner
  227. t.resetTokenRing()
  228. }
  229. }
  230. func (t *tokenAwareHostPolicy) AddHost(host *HostInfo) {
  231. t.hosts.add(host)
  232. t.fallback.AddHost(host)
  233. t.resetTokenRing()
  234. }
  235. func (t *tokenAwareHostPolicy) RemoveHost(host *HostInfo) {
  236. t.hosts.remove(host.Peer())
  237. t.fallback.RemoveHost(host)
  238. t.resetTokenRing()
  239. }
  240. func (t *tokenAwareHostPolicy) HostUp(host *HostInfo) {
  241. t.AddHost(host)
  242. }
  243. func (t *tokenAwareHostPolicy) HostDown(host *HostInfo) {
  244. t.RemoveHost(host)
  245. }
  246. func (t *tokenAwareHostPolicy) resetTokenRing() {
  247. t.mu.Lock()
  248. defer t.mu.Unlock()
  249. if t.partitioner == "" {
  250. // partitioner not yet set
  251. return
  252. }
  253. // create a new token ring
  254. hosts := t.hosts.get()
  255. tokenRing, err := newTokenRing(t.partitioner, hosts)
  256. if err != nil {
  257. Logger.Printf("Unable to update the token ring due to error: %s", err)
  258. return
  259. }
  260. // replace the token ring
  261. t.tokenRing = tokenRing
  262. }
  263. func (t *tokenAwareHostPolicy) Pick(qry ExecutableQuery) NextHost {
  264. if qry == nil {
  265. return t.fallback.Pick(qry)
  266. }
  267. routingKey, err := qry.GetRoutingKey()
  268. if err != nil {
  269. return t.fallback.Pick(qry)
  270. }
  271. if routingKey == nil {
  272. return t.fallback.Pick(qry)
  273. }
  274. t.mu.RLock()
  275. // TODO retrieve a list of hosts based on the replication strategy
  276. host := t.tokenRing.GetHostForPartitionKey(routingKey)
  277. t.mu.RUnlock()
  278. if host == nil {
  279. return t.fallback.Pick(qry)
  280. }
  281. // scope these variables for the same lifetime as the iterator function
  282. var (
  283. hostReturned bool
  284. fallbackIter NextHost
  285. )
  286. return func() SelectedHost {
  287. if !hostReturned {
  288. hostReturned = true
  289. return (*selectedHost)(host)
  290. }
  291. // fallback
  292. if fallbackIter == nil {
  293. fallbackIter = t.fallback.Pick(qry)
  294. }
  295. fallbackHost := fallbackIter()
  296. // filter the token aware selected hosts from the fallback hosts
  297. if fallbackHost != nil && fallbackHost.Info() == host {
  298. fallbackHost = fallbackIter()
  299. }
  300. return fallbackHost
  301. }
  302. }
  303. // HostPoolHostPolicy is a host policy which uses the bitly/go-hostpool library
  304. // to distribute queries between hosts and prevent sending queries to
  305. // unresponsive hosts. When creating the host pool that is passed to the policy
  306. // use an empty slice of hosts as the hostpool will be populated later by gocql.
  307. // See below for examples of usage:
  308. //
  309. // // Create host selection policy using a simple host pool
  310. // cluster.PoolConfig.HostSelectionPolicy = HostPoolHostPolicy(hostpool.New(nil))
  311. //
  312. // // Create host selection policy using an epsilon greedy pool
  313. // cluster.PoolConfig.HostSelectionPolicy = HostPoolHostPolicy(
  314. // hostpool.NewEpsilonGreedy(nil, 0, &hostpool.LinearEpsilonValueCalculator{}),
  315. // )
  316. //
  317. func HostPoolHostPolicy(hp hostpool.HostPool) HostSelectionPolicy {
  318. return &hostPoolHostPolicy{hostMap: map[string]*HostInfo{}, hp: hp}
  319. }
  320. type hostPoolHostPolicy struct {
  321. hp hostpool.HostPool
  322. mu sync.RWMutex
  323. hostMap map[string]*HostInfo
  324. }
  325. func (r *hostPoolHostPolicy) SetHosts(hosts []*HostInfo) {
  326. peers := make([]string, len(hosts))
  327. hostMap := make(map[string]*HostInfo, len(hosts))
  328. for i, host := range hosts {
  329. ip := host.Peer().String()
  330. peers[i] = ip
  331. hostMap[ip] = host
  332. }
  333. r.mu.Lock()
  334. r.hp.SetHosts(peers)
  335. r.hostMap = hostMap
  336. r.mu.Unlock()
  337. }
  338. func (r *hostPoolHostPolicy) AddHost(host *HostInfo) {
  339. ip := host.Peer().String()
  340. r.mu.Lock()
  341. defer r.mu.Unlock()
  342. // If the host addr is present and isn't nil return
  343. if h, ok := r.hostMap[ip]; ok && h != nil {
  344. return
  345. }
  346. // otherwise, add the host to the map
  347. r.hostMap[ip] = host
  348. // and construct a new peer list to give to the HostPool
  349. hosts := make([]string, 0, len(r.hostMap))
  350. for addr := range r.hostMap {
  351. hosts = append(hosts, addr)
  352. }
  353. r.hp.SetHosts(hosts)
  354. }
  355. func (r *hostPoolHostPolicy) RemoveHost(host *HostInfo) {
  356. ip := host.Peer().String()
  357. r.mu.Lock()
  358. defer r.mu.Unlock()
  359. if _, ok := r.hostMap[ip]; !ok {
  360. return
  361. }
  362. delete(r.hostMap, ip)
  363. hosts := make([]string, 0, len(r.hostMap))
  364. for _, host := range r.hostMap {
  365. hosts = append(hosts, host.Peer().String())
  366. }
  367. r.hp.SetHosts(hosts)
  368. }
  369. func (r *hostPoolHostPolicy) HostUp(host *HostInfo) {
  370. r.AddHost(host)
  371. }
  372. func (r *hostPoolHostPolicy) HostDown(host *HostInfo) {
  373. r.RemoveHost(host)
  374. }
  375. func (r *hostPoolHostPolicy) SetPartitioner(partitioner string) {
  376. // noop
  377. }
  378. func (r *hostPoolHostPolicy) Pick(qry ExecutableQuery) NextHost {
  379. return func() SelectedHost {
  380. r.mu.RLock()
  381. defer r.mu.RUnlock()
  382. if len(r.hostMap) == 0 {
  383. return nil
  384. }
  385. hostR := r.hp.Get()
  386. host, ok := r.hostMap[hostR.Host()]
  387. if !ok {
  388. return nil
  389. }
  390. return selectedHostPoolHost{
  391. policy: r,
  392. info: host,
  393. hostR: hostR,
  394. }
  395. }
  396. }
  397. // selectedHostPoolHost is a host returned by the hostPoolHostPolicy and
  398. // implements the SelectedHost interface
  399. type selectedHostPoolHost struct {
  400. policy *hostPoolHostPolicy
  401. info *HostInfo
  402. hostR hostpool.HostPoolResponse
  403. }
  404. func (host selectedHostPoolHost) Info() *HostInfo {
  405. return host.info
  406. }
  407. func (host selectedHostPoolHost) Mark(err error) {
  408. ip := host.info.Peer().String()
  409. host.policy.mu.RLock()
  410. defer host.policy.mu.RUnlock()
  411. if _, ok := host.policy.hostMap[ip]; !ok {
  412. // host was removed between pick and mark
  413. return
  414. }
  415. host.hostR.Mark(err)
  416. }