policies.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  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. // TODO(zariel): add host up/down
  142. }
  143. // HostSelectionPolicy is an interface for selecting
  144. // the most appropriate host to execute a given query.
  145. type HostSelectionPolicy interface {
  146. HostStateNotifier
  147. SetHosts
  148. SetPartitioner
  149. //Pick returns an iteration function over selected hosts
  150. Pick(*Query) 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. // NextHost is an iteration function over picked hosts
  159. type NextHost func() SelectedHost
  160. // RoundRobinHostPolicy is a round-robin load balancing policy, where each host
  161. // is tried sequentially for each query.
  162. func RoundRobinHostPolicy() HostSelectionPolicy {
  163. return &roundRobinHostPolicy{}
  164. }
  165. type roundRobinHostPolicy struct {
  166. hosts cowHostList
  167. pos uint32
  168. mu sync.RWMutex
  169. }
  170. func (r *roundRobinHostPolicy) SetHosts(hosts []*HostInfo) {
  171. r.hosts.set(hosts)
  172. }
  173. func (r *roundRobinHostPolicy) SetPartitioner(partitioner string) {
  174. // noop
  175. }
  176. func (r *roundRobinHostPolicy) Pick(qry *Query) NextHost {
  177. // i is used to limit the number of attempts to find a host
  178. // to the number of hosts known to this policy
  179. var i int
  180. return func() SelectedHost {
  181. hosts := r.hosts.get()
  182. if len(hosts) == 0 {
  183. return nil
  184. }
  185. // always increment pos to evenly distribute traffic in case of
  186. // failures
  187. pos := atomic.AddUint32(&r.pos, 1) - 1
  188. if i >= len(hosts) {
  189. return nil
  190. }
  191. host := hosts[(pos)%uint32(len(hosts))]
  192. i++
  193. return selectedRoundRobinHost{host}
  194. }
  195. }
  196. func (r *roundRobinHostPolicy) AddHost(host *HostInfo) {
  197. r.hosts.add(host)
  198. }
  199. func (r *roundRobinHostPolicy) RemoveHost(addr string) {
  200. r.hosts.remove(addr)
  201. }
  202. // selectedRoundRobinHost is a host returned by the roundRobinHostPolicy and
  203. // implements the SelectedHost interface
  204. type selectedRoundRobinHost struct {
  205. info *HostInfo
  206. }
  207. func (host selectedRoundRobinHost) Info() *HostInfo {
  208. return host.info
  209. }
  210. func (host selectedRoundRobinHost) Mark(err error) {
  211. // noop
  212. }
  213. // TokenAwareHostPolicy is a token aware host selection policy, where hosts are
  214. // selected based on the partition key, so queries are sent to the host which
  215. // owns the partition. Fallback is used when routing information is not available.
  216. func TokenAwareHostPolicy(fallback HostSelectionPolicy) HostSelectionPolicy {
  217. return &tokenAwareHostPolicy{fallback: fallback}
  218. }
  219. type tokenAwareHostPolicy struct {
  220. hosts cowHostList
  221. mu sync.RWMutex
  222. partitioner string
  223. tokenRing *tokenRing
  224. fallback HostSelectionPolicy
  225. }
  226. func (t *tokenAwareHostPolicy) SetHosts(hosts []*HostInfo) {
  227. t.hosts.set(hosts)
  228. t.mu.Lock()
  229. defer t.mu.Unlock()
  230. // always update the fallback
  231. t.fallback.SetHosts(hosts)
  232. t.resetTokenRing()
  233. }
  234. func (t *tokenAwareHostPolicy) SetPartitioner(partitioner string) {
  235. t.mu.Lock()
  236. defer t.mu.Unlock()
  237. if t.partitioner != partitioner {
  238. t.fallback.SetPartitioner(partitioner)
  239. t.partitioner = partitioner
  240. t.resetTokenRing()
  241. }
  242. }
  243. func (t *tokenAwareHostPolicy) AddHost(host *HostInfo) {
  244. t.hosts.add(host)
  245. t.fallback.AddHost(host)
  246. t.mu.Lock()
  247. t.resetTokenRing()
  248. t.mu.Unlock()
  249. }
  250. func (t *tokenAwareHostPolicy) RemoveHost(addr string) {
  251. t.hosts.remove(addr)
  252. t.mu.Lock()
  253. t.resetTokenRing()
  254. t.mu.Unlock()
  255. }
  256. func (t *tokenAwareHostPolicy) resetTokenRing() {
  257. if t.partitioner == "" {
  258. // partitioner not yet set
  259. return
  260. }
  261. // create a new token ring
  262. hosts := t.hosts.get()
  263. tokenRing, err := newTokenRing(t.partitioner, hosts)
  264. if err != nil {
  265. log.Printf("Unable to update the token ring due to error: %s", err)
  266. return
  267. }
  268. // replace the token ring
  269. t.tokenRing = tokenRing
  270. }
  271. func (t *tokenAwareHostPolicy) Pick(qry *Query) NextHost {
  272. if qry == nil {
  273. return t.fallback.Pick(qry)
  274. } else if qry.binding != nil && len(qry.values) == 0 {
  275. // If this query was created using session.Bind we wont have the query
  276. // values yet, so we have to pass down to the next policy.
  277. // TODO: Remove this and handle this case
  278. return t.fallback.Pick(qry)
  279. }
  280. routingKey, err := qry.GetRoutingKey()
  281. if err != nil {
  282. return t.fallback.Pick(qry)
  283. }
  284. if routingKey == nil {
  285. return t.fallback.Pick(qry)
  286. }
  287. t.mu.RLock()
  288. // TODO retrieve a list of hosts based on the replication strategy
  289. host := t.tokenRing.GetHostForPartitionKey(routingKey)
  290. t.mu.RUnlock()
  291. if host == nil {
  292. return t.fallback.Pick(qry)
  293. }
  294. // scope these variables for the same lifetime as the iterator function
  295. var (
  296. hostReturned bool
  297. fallbackIter NextHost
  298. )
  299. return func() SelectedHost {
  300. if !hostReturned {
  301. hostReturned = true
  302. return selectedTokenAwareHost{host}
  303. }
  304. // fallback
  305. if fallbackIter == nil {
  306. fallbackIter = t.fallback.Pick(qry)
  307. }
  308. fallbackHost := fallbackIter()
  309. // filter the token aware selected hosts from the fallback hosts
  310. if fallbackHost != nil && fallbackHost.Info() == host {
  311. fallbackHost = fallbackIter()
  312. }
  313. return fallbackHost
  314. }
  315. }
  316. // selectedTokenAwareHost is a host returned by the tokenAwareHostPolicy and
  317. // implements the SelectedHost interface
  318. type selectedTokenAwareHost struct {
  319. info *HostInfo
  320. }
  321. func (host selectedTokenAwareHost) Info() *HostInfo {
  322. return host.info
  323. }
  324. func (host selectedTokenAwareHost) Mark(err error) {
  325. // noop
  326. }
  327. // HostPoolHostPolicy is a host policy which uses the bitly/go-hostpool library
  328. // to distribute queries between hosts and prevent sending queries to
  329. // unresponsive hosts. When creating the host pool that is passed to the policy
  330. // use an empty slice of hosts as the hostpool will be populated later by gocql.
  331. // See below for examples of usage:
  332. //
  333. // // Create host selection policy using a simple host pool
  334. // cluster.PoolConfig.HostSelectionPolicy = HostPoolHostPolicy(hostpool.New(nil))
  335. //
  336. // // Create host selection policy using an epsilon greddy pool
  337. // cluster.PoolConfig.HostSelectionPolicy = HostPoolHostPolicy(
  338. // hostpool.NewEpsilonGreedy(nil, 0, &hostpool.LinearEpsilonValueCalculator{}),
  339. // )
  340. //
  341. func HostPoolHostPolicy(hp hostpool.HostPool) HostSelectionPolicy {
  342. return &hostPoolHostPolicy{hostMap: map[string]*HostInfo{}, hp: hp}
  343. }
  344. type hostPoolHostPolicy struct {
  345. hp hostpool.HostPool
  346. mu sync.RWMutex
  347. hostMap map[string]*HostInfo
  348. }
  349. func (r *hostPoolHostPolicy) SetHosts(hosts []*HostInfo) {
  350. peers := make([]string, len(hosts))
  351. hostMap := make(map[string]*HostInfo, len(hosts))
  352. for i, host := range hosts {
  353. peers[i] = host.Peer()
  354. hostMap[host.Peer()] = host
  355. }
  356. r.mu.Lock()
  357. r.hp.SetHosts(peers)
  358. r.hostMap = hostMap
  359. r.mu.Unlock()
  360. }
  361. func (r *hostPoolHostPolicy) AddHost(host *HostInfo) {
  362. r.mu.Lock()
  363. defer r.mu.Unlock()
  364. if _, ok := r.hostMap[host.Peer()]; ok {
  365. return
  366. }
  367. hosts := make([]string, 0, len(r.hostMap)+1)
  368. for addr := range r.hostMap {
  369. hosts = append(hosts, addr)
  370. }
  371. hosts = append(hosts, host.Peer())
  372. r.hp.SetHosts(hosts)
  373. r.hostMap[host.Peer()] = host
  374. }
  375. func (r *hostPoolHostPolicy) RemoveHost(addr string) {
  376. r.mu.Lock()
  377. defer r.mu.Unlock()
  378. if _, ok := r.hostMap[addr]; !ok {
  379. return
  380. }
  381. delete(r.hostMap, addr)
  382. hosts := make([]string, 0, len(r.hostMap))
  383. for addr := range r.hostMap {
  384. hosts = append(hosts, addr)
  385. }
  386. r.hp.SetHosts(hosts)
  387. }
  388. func (r *hostPoolHostPolicy) SetPartitioner(partitioner string) {
  389. // noop
  390. }
  391. func (r *hostPoolHostPolicy) Pick(qry *Query) NextHost {
  392. return func() SelectedHost {
  393. r.mu.RLock()
  394. defer r.mu.RUnlock()
  395. if len(r.hostMap) == 0 {
  396. return nil
  397. }
  398. hostR := r.hp.Get()
  399. host, ok := r.hostMap[hostR.Host()]
  400. if !ok {
  401. return nil
  402. }
  403. return selectedHostPoolHost{host, hostR}
  404. }
  405. }
  406. // selectedHostPoolHost is a host returned by the hostPoolHostPolicy and
  407. // implements the SelectedHost interface
  408. type selectedHostPoolHost struct {
  409. info *HostInfo
  410. hostR hostpool.HostPoolResponse
  411. }
  412. func (host selectedHostPoolHost) Info() *HostInfo {
  413. return host.info
  414. }
  415. func (host selectedHostPoolHost) Mark(err error) {
  416. host.hostR.Mark(err)
  417. }
  418. //ConnSelectionPolicy is an interface for selecting an
  419. //appropriate connection for executing a query
  420. type ConnSelectionPolicy interface {
  421. SetConns(conns []*Conn)
  422. Pick(*Query) *Conn
  423. }
  424. type roundRobinConnPolicy struct {
  425. conns []*Conn
  426. pos uint32
  427. mu sync.RWMutex
  428. }
  429. func RoundRobinConnPolicy() func() ConnSelectionPolicy {
  430. return func() ConnSelectionPolicy {
  431. return &roundRobinConnPolicy{}
  432. }
  433. }
  434. func (r *roundRobinConnPolicy) SetConns(conns []*Conn) {
  435. r.mu.Lock()
  436. r.conns = conns
  437. r.mu.Unlock()
  438. }
  439. func (r *roundRobinConnPolicy) Pick(qry *Query) *Conn {
  440. pos := int(atomic.AddUint32(&r.pos, 1) - 1)
  441. r.mu.RLock()
  442. defer r.mu.RUnlock()
  443. if len(r.conns) == 0 {
  444. return nil
  445. }
  446. for i := 0; i < len(r.conns); i++ {
  447. conn := r.conns[(pos+i)%len(r.conns)]
  448. if conn.AvailableStreams() > 0 {
  449. return conn
  450. }
  451. }
  452. return nil
  453. }