policies.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  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.fallback.AddHost(host)
  242. t.mu.Lock()
  243. t.resetTokenRing()
  244. t.mu.Unlock()
  245. }
  246. func (t *tokenAwareHostPolicy) RemoveHost(addr string) {
  247. t.hosts.remove(addr)
  248. t.mu.Lock()
  249. t.resetTokenRing()
  250. t.mu.Unlock()
  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 *Query) NextHost {
  268. if qry == nil {
  269. return t.fallback.Pick(qry)
  270. } else if qry.binding != nil && len(qry.values) == 0 {
  271. // If this query was created using session.Bind we wont have the query
  272. // values yet, so we have to pass down to the next policy.
  273. // TODO: Remove this and handle this case
  274. return t.fallback.Pick(qry)
  275. }
  276. routingKey, err := qry.GetRoutingKey()
  277. if err != nil {
  278. return t.fallback.Pick(qry)
  279. }
  280. if routingKey == nil {
  281. return t.fallback.Pick(qry)
  282. }
  283. t.mu.RLock()
  284. // TODO retrieve a list of hosts based on the replication strategy
  285. host := t.tokenRing.GetHostForPartitionKey(routingKey)
  286. t.mu.RUnlock()
  287. if host == nil {
  288. return t.fallback.Pick(qry)
  289. }
  290. // scope these variables for the same lifetime as the iterator function
  291. var (
  292. hostReturned bool
  293. fallbackIter NextHost
  294. )
  295. return func() SelectedHost {
  296. if !hostReturned {
  297. hostReturned = true
  298. return selectedTokenAwareHost{host}
  299. }
  300. // fallback
  301. if fallbackIter == nil {
  302. fallbackIter = t.fallback.Pick(qry)
  303. }
  304. fallbackHost := fallbackIter()
  305. // filter the token aware selected hosts from the fallback hosts
  306. if fallbackHost.Info() == host {
  307. fallbackHost = fallbackIter()
  308. }
  309. return fallbackHost
  310. }
  311. }
  312. // selectedTokenAwareHost is a host returned by the tokenAwareHostPolicy and
  313. // implements the SelectedHost interface
  314. type selectedTokenAwareHost struct {
  315. info *HostInfo
  316. }
  317. func (host selectedTokenAwareHost) Info() *HostInfo {
  318. return host.info
  319. }
  320. func (host selectedTokenAwareHost) Mark(err error) {
  321. // noop
  322. }
  323. // HostPoolHostPolicy is a host policy which uses the bitly/go-hostpool library
  324. // to distribute queries between hosts and prevent sending queries to
  325. // unresponsive hosts. When creating the host pool that is passed to the policy
  326. // use an empty slice of hosts as the hostpool will be populated later by gocql.
  327. // See below for examples of usage:
  328. //
  329. // // Create host selection policy using a simple host pool
  330. // cluster.PoolConfig.HostSelectionPolicy = HostPoolHostPolicy(hostpool.New(nil))
  331. //
  332. // // Create host selection policy using an epsilon greddy pool
  333. // cluster.PoolConfig.HostSelectionPolicy = HostPoolHostPolicy(
  334. // hostpool.NewEpsilonGreedy(nil, 0, &hostpool.LinearEpsilonValueCalculator{}),
  335. // )
  336. //
  337. func HostPoolHostPolicy(hp hostpool.HostPool) HostSelectionPolicy {
  338. return &hostPoolHostPolicy{hostMap: map[string]*HostInfo{}, hp: hp}
  339. }
  340. type hostPoolHostPolicy struct {
  341. hp hostpool.HostPool
  342. mu sync.RWMutex
  343. hostMap map[string]*HostInfo
  344. }
  345. func (r *hostPoolHostPolicy) SetHosts(hosts []*HostInfo) {
  346. peers := make([]string, len(hosts))
  347. hostMap := make(map[string]*HostInfo, len(hosts))
  348. for i, host := range hosts {
  349. peers[i] = host.Peer()
  350. hostMap[host.Peer()] = host
  351. }
  352. r.mu.Lock()
  353. r.hp.SetHosts(peers)
  354. r.hostMap = hostMap
  355. r.mu.Unlock()
  356. }
  357. func (r *hostPoolHostPolicy) AddHost(host *HostInfo) {
  358. r.mu.Lock()
  359. defer r.mu.Unlock()
  360. if _, ok := r.hostMap[host.Peer()]; ok {
  361. return
  362. }
  363. hosts := make([]string, 0, len(r.hostMap)+1)
  364. for addr := range r.hostMap {
  365. hosts = append(hosts, addr)
  366. }
  367. hosts = append(hosts, host.Peer())
  368. r.hp.SetHosts(hosts)
  369. r.hostMap[host.Peer()] = host
  370. }
  371. func (r *hostPoolHostPolicy) RemoveHost(addr string) {
  372. r.mu.Unlock()
  373. defer r.mu.Unlock()
  374. if _, ok := r.hostMap[addr]; !ok {
  375. return
  376. }
  377. delete(r.hostMap, addr)
  378. hosts := make([]string, 0, len(r.hostMap))
  379. for addr := range r.hostMap {
  380. hosts = append(hosts, addr)
  381. }
  382. r.hp.SetHosts(hosts)
  383. }
  384. func (r *hostPoolHostPolicy) SetPartitioner(partitioner string) {
  385. // noop
  386. }
  387. func (r *hostPoolHostPolicy) Pick(qry *Query) NextHost {
  388. return func() SelectedHost {
  389. r.mu.RLock()
  390. defer r.mu.RUnlock()
  391. if len(r.hostMap) == 0 {
  392. return nil
  393. }
  394. hostR := r.hp.Get()
  395. host, ok := r.hostMap[hostR.Host()]
  396. if !ok {
  397. return nil
  398. }
  399. return selectedHostPoolHost{host, hostR}
  400. }
  401. }
  402. // selectedHostPoolHost is a host returned by the hostPoolHostPolicy and
  403. // implements the SelectedHost interface
  404. type selectedHostPoolHost struct {
  405. info *HostInfo
  406. hostR hostpool.HostPoolResponse
  407. }
  408. func (host selectedHostPoolHost) Info() *HostInfo {
  409. return host.info
  410. }
  411. func (host selectedHostPoolHost) Mark(err error) {
  412. host.hostR.Mark(err)
  413. }
  414. //ConnSelectionPolicy is an interface for selecting an
  415. //appropriate connection for executing a query
  416. type ConnSelectionPolicy interface {
  417. SetConns(conns []*Conn)
  418. Pick(*Query) *Conn
  419. }
  420. type roundRobinConnPolicy struct {
  421. conns []*Conn
  422. pos uint32
  423. mu sync.RWMutex
  424. }
  425. func RoundRobinConnPolicy() func() ConnSelectionPolicy {
  426. return func() ConnSelectionPolicy {
  427. return &roundRobinConnPolicy{}
  428. }
  429. }
  430. func (r *roundRobinConnPolicy) SetConns(conns []*Conn) {
  431. r.mu.Lock()
  432. r.conns = conns
  433. r.mu.Unlock()
  434. }
  435. func (r *roundRobinConnPolicy) Pick(qry *Query) *Conn {
  436. pos := int(atomic.AddUint32(&r.pos, 1) - 1)
  437. r.mu.RLock()
  438. defer r.mu.RUnlock()
  439. if len(r.conns) == 0 {
  440. return nil
  441. }
  442. for i := 0; i < len(r.conns); i++ {
  443. conn := r.conns[(pos+i)%len(r.conns)]
  444. if conn.AvailableStreams() > 0 {
  445. return conn
  446. }
  447. }
  448. return nil
  449. }