policies.go 12 KB

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