policies.go 11 KB

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