policies.go 11 KB

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