policies.go 11 KB

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