policies.go 12 KB

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