policies.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755
  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. "math"
  9. "math/rand"
  10. "net"
  11. "sync"
  12. "sync/atomic"
  13. "time"
  14. "github.com/hailocab/go-hostpool"
  15. )
  16. // cowHostList implements a copy on write host list, its equivalent type is []*HostInfo
  17. type cowHostList struct {
  18. list atomic.Value
  19. mu sync.Mutex
  20. }
  21. func (c *cowHostList) String() string {
  22. return fmt.Sprintf("%+v", c.get())
  23. }
  24. func (c *cowHostList) get() []*HostInfo {
  25. // TODO(zariel): should we replace this with []*HostInfo?
  26. l, ok := c.list.Load().(*[]*HostInfo)
  27. if !ok {
  28. return nil
  29. }
  30. return *l
  31. }
  32. func (c *cowHostList) set(list []*HostInfo) {
  33. c.mu.Lock()
  34. c.list.Store(&list)
  35. c.mu.Unlock()
  36. }
  37. // add will add a host if it not already in the list
  38. func (c *cowHostList) add(host *HostInfo) bool {
  39. c.mu.Lock()
  40. l := c.get()
  41. if n := len(l); n == 0 {
  42. l = []*HostInfo{host}
  43. } else {
  44. newL := make([]*HostInfo, n+1)
  45. for i := 0; i < n; i++ {
  46. if host.Equal(l[i]) {
  47. c.mu.Unlock()
  48. return false
  49. }
  50. newL[i] = l[i]
  51. }
  52. newL[n] = host
  53. l = newL
  54. }
  55. c.list.Store(&l)
  56. c.mu.Unlock()
  57. return true
  58. }
  59. func (c *cowHostList) update(host *HostInfo) {
  60. c.mu.Lock()
  61. l := c.get()
  62. if len(l) == 0 {
  63. c.mu.Unlock()
  64. return
  65. }
  66. found := false
  67. newL := make([]*HostInfo, len(l))
  68. for i := range l {
  69. if host.Equal(l[i]) {
  70. newL[i] = host
  71. found = true
  72. } else {
  73. newL[i] = l[i]
  74. }
  75. }
  76. if found {
  77. c.list.Store(&newL)
  78. }
  79. c.mu.Unlock()
  80. }
  81. func (c *cowHostList) remove(ip net.IP) bool {
  82. c.mu.Lock()
  83. l := c.get()
  84. size := len(l)
  85. if size == 0 {
  86. c.mu.Unlock()
  87. return false
  88. }
  89. found := false
  90. newL := make([]*HostInfo, 0, size)
  91. for i := 0; i < len(l); i++ {
  92. if !l[i].ConnectAddress().Equal(ip) {
  93. newL = append(newL, l[i])
  94. } else {
  95. found = true
  96. }
  97. }
  98. if !found {
  99. c.mu.Unlock()
  100. return false
  101. }
  102. newL = newL[:size-1 : size-1]
  103. c.list.Store(&newL)
  104. c.mu.Unlock()
  105. return true
  106. }
  107. // RetryableQuery is an interface that represents a query or batch statement that
  108. // exposes the correct functions for the retry policy logic to evaluate correctly.
  109. type RetryableQuery interface {
  110. Attempts() int
  111. GetConsistency() Consistency
  112. }
  113. // RetryPolicy interface is used by gocql to determine if a query can be attempted
  114. // again after a retryable error has been received. The interface allows gocql
  115. // users to implement their own logic to determine if a query can be attempted
  116. // again.
  117. //
  118. // See SimpleRetryPolicy as an example of implementing and using a RetryPolicy
  119. // interface.
  120. type RetryPolicy interface {
  121. Attempt(RetryableQuery) bool
  122. }
  123. // SimpleRetryPolicy has simple logic for attempting a query a fixed number of times.
  124. //
  125. // See below for examples of usage:
  126. //
  127. // //Assign to the cluster
  128. // cluster.RetryPolicy = &gocql.SimpleRetryPolicy{NumRetries: 3}
  129. //
  130. // //Assign to a query
  131. // query.RetryPolicy(&gocql.SimpleRetryPolicy{NumRetries: 1})
  132. //
  133. type SimpleRetryPolicy struct {
  134. NumRetries int //Number of times to retry a query
  135. }
  136. // Attempt tells gocql to attempt the query again based on query.Attempts being less
  137. // than the NumRetries defined in the policy.
  138. func (s *SimpleRetryPolicy) Attempt(q RetryableQuery) bool {
  139. return q.Attempts() <= s.NumRetries
  140. }
  141. // ExponentialBackoffRetryPolicy sleeps between attempts
  142. type ExponentialBackoffRetryPolicy struct {
  143. NumRetries int
  144. Min, Max time.Duration
  145. }
  146. func (e *ExponentialBackoffRetryPolicy) Attempt(q RetryableQuery) bool {
  147. if q.Attempts() > e.NumRetries {
  148. return false
  149. }
  150. time.Sleep(e.napTime(q.Attempts()))
  151. return true
  152. }
  153. // used to calculate exponentially growing time
  154. func getExponentialTime(min time.Duration, max time.Duration, attempts int) time.Duration {
  155. if min <= 0 {
  156. min = 100 * time.Millisecond
  157. }
  158. if max <= 0 {
  159. max = 10 * time.Second
  160. }
  161. minFloat := float64(min)
  162. napDuration := minFloat * math.Pow(2, float64(attempts-1))
  163. // add some jitter
  164. napDuration += rand.Float64()*minFloat - (minFloat / 2)
  165. if napDuration > float64(max) {
  166. return time.Duration(max)
  167. }
  168. return time.Duration(napDuration)
  169. }
  170. func (e *ExponentialBackoffRetryPolicy) napTime(attempts int) time.Duration {
  171. return getExponentialTime(e.Min, e.Max, attempts)
  172. }
  173. type HostStateNotifier interface {
  174. AddHost(host *HostInfo)
  175. RemoveHost(host *HostInfo)
  176. HostUp(host *HostInfo)
  177. HostDown(host *HostInfo)
  178. }
  179. type KeyspaceUpdateEvent struct {
  180. Keyspace string
  181. Change string
  182. }
  183. // HostSelectionPolicy is an interface for selecting
  184. // the most appropriate host to execute a given query.
  185. type HostSelectionPolicy interface {
  186. HostStateNotifier
  187. SetPartitioner
  188. KeyspaceChanged(KeyspaceUpdateEvent)
  189. Init(*Session)
  190. IsLocal(host *HostInfo) bool
  191. //Pick returns an iteration function over selected hosts
  192. Pick(ExecutableQuery) NextHost
  193. }
  194. // SelectedHost is an interface returned when picking a host from a host
  195. // selection policy.
  196. type SelectedHost interface {
  197. Info() *HostInfo
  198. Mark(error)
  199. }
  200. type selectedHost HostInfo
  201. func (host *selectedHost) Info() *HostInfo {
  202. return (*HostInfo)(host)
  203. }
  204. func (host *selectedHost) Mark(err error) {}
  205. // NextHost is an iteration function over picked hosts
  206. type NextHost func() SelectedHost
  207. // RoundRobinHostPolicy is a round-robin load balancing policy, where each host
  208. // is tried sequentially for each query.
  209. func RoundRobinHostPolicy() HostSelectionPolicy {
  210. return &roundRobinHostPolicy{}
  211. }
  212. type roundRobinHostPolicy struct {
  213. hosts cowHostList
  214. pos uint32
  215. mu sync.RWMutex
  216. }
  217. func (r *roundRobinHostPolicy) IsLocal(*HostInfo) bool { return true }
  218. func (r *roundRobinHostPolicy) KeyspaceChanged(KeyspaceUpdateEvent) {}
  219. func (r *roundRobinHostPolicy) SetPartitioner(partitioner string) {}
  220. func (r *roundRobinHostPolicy) Init(*Session) {}
  221. func (r *roundRobinHostPolicy) Pick(qry ExecutableQuery) NextHost {
  222. // i is used to limit the number of attempts to find a host
  223. // to the number of hosts known to this policy
  224. var i int
  225. return func() SelectedHost {
  226. hosts := r.hosts.get()
  227. if len(hosts) == 0 {
  228. return nil
  229. }
  230. // always increment pos to evenly distribute traffic in case of
  231. // failures
  232. pos := atomic.AddUint32(&r.pos, 1) - 1
  233. if i >= len(hosts) {
  234. return nil
  235. }
  236. host := hosts[(pos)%uint32(len(hosts))]
  237. i++
  238. return (*selectedHost)(host)
  239. }
  240. }
  241. func (r *roundRobinHostPolicy) AddHost(host *HostInfo) {
  242. r.hosts.add(host)
  243. }
  244. func (r *roundRobinHostPolicy) RemoveHost(host *HostInfo) {
  245. r.hosts.remove(host.ConnectAddress())
  246. }
  247. func (r *roundRobinHostPolicy) HostUp(host *HostInfo) {
  248. r.AddHost(host)
  249. }
  250. func (r *roundRobinHostPolicy) HostDown(host *HostInfo) {
  251. r.RemoveHost(host)
  252. }
  253. func ShuffleReplicas() func(*tokenAwareHostPolicy) {
  254. return func(t *tokenAwareHostPolicy) {
  255. t.shuffleReplicas = true
  256. }
  257. }
  258. // TokenAwareHostPolicy is a token aware host selection policy, where hosts are
  259. // selected based on the partition key, so queries are sent to the host which
  260. // owns the partition. Fallback is used when routing information is not available.
  261. func TokenAwareHostPolicy(fallback HostSelectionPolicy, opts ...func(*tokenAwareHostPolicy)) HostSelectionPolicy {
  262. p := &tokenAwareHostPolicy{fallback: fallback}
  263. for _, opt := range opts {
  264. opt(p)
  265. }
  266. return p
  267. }
  268. type keyspaceMeta struct {
  269. replicas map[string]map[token][]*HostInfo
  270. }
  271. type tokenAwareHostPolicy struct {
  272. hosts cowHostList
  273. mu sync.RWMutex
  274. partitioner string
  275. fallback HostSelectionPolicy
  276. session *Session
  277. tokenRing atomic.Value // *tokenRing
  278. keyspaces atomic.Value // *keyspaceMeta
  279. shuffleReplicas bool
  280. }
  281. func (t *tokenAwareHostPolicy) Init(s *Session) {
  282. t.session = s
  283. }
  284. func (t *tokenAwareHostPolicy) IsLocal(host *HostInfo) bool {
  285. return t.fallback.IsLocal(host)
  286. }
  287. func (t *tokenAwareHostPolicy) KeyspaceChanged(update KeyspaceUpdateEvent) {
  288. meta, _ := t.keyspaces.Load().(*keyspaceMeta)
  289. var size = 1
  290. if meta != nil {
  291. size = len(meta.replicas)
  292. }
  293. newMeta := &keyspaceMeta{
  294. replicas: make(map[string]map[token][]*HostInfo, size),
  295. }
  296. ks, err := t.session.KeyspaceMetadata(update.Keyspace)
  297. if err == nil {
  298. strat := getStrategy(ks)
  299. tr := t.tokenRing.Load().(*tokenRing)
  300. if tr != nil {
  301. newMeta.replicas[update.Keyspace] = strat.replicaMap(t.hosts.get(), tr.tokens)
  302. }
  303. }
  304. if meta != nil {
  305. for ks, replicas := range meta.replicas {
  306. if ks != update.Keyspace {
  307. newMeta.replicas[ks] = replicas
  308. }
  309. }
  310. }
  311. t.keyspaces.Store(newMeta)
  312. }
  313. func (t *tokenAwareHostPolicy) SetPartitioner(partitioner string) {
  314. t.mu.Lock()
  315. defer t.mu.Unlock()
  316. if t.partitioner != partitioner {
  317. t.fallback.SetPartitioner(partitioner)
  318. t.partitioner = partitioner
  319. t.resetTokenRing(partitioner)
  320. }
  321. }
  322. func (t *tokenAwareHostPolicy) AddHost(host *HostInfo) {
  323. t.hosts.add(host)
  324. t.fallback.AddHost(host)
  325. t.mu.RLock()
  326. partitioner := t.partitioner
  327. t.mu.RUnlock()
  328. t.resetTokenRing(partitioner)
  329. }
  330. func (t *tokenAwareHostPolicy) RemoveHost(host *HostInfo) {
  331. t.hosts.remove(host.ConnectAddress())
  332. t.fallback.RemoveHost(host)
  333. t.mu.RLock()
  334. partitioner := t.partitioner
  335. t.mu.RUnlock()
  336. t.resetTokenRing(partitioner)
  337. }
  338. func (t *tokenAwareHostPolicy) HostUp(host *HostInfo) {
  339. // TODO: need to avoid doing all the work on AddHost on hostup/down
  340. // because it now expensive to calculate the replica map for each
  341. // token
  342. t.AddHost(host)
  343. }
  344. func (t *tokenAwareHostPolicy) HostDown(host *HostInfo) {
  345. t.RemoveHost(host)
  346. }
  347. func (t *tokenAwareHostPolicy) resetTokenRing(partitioner string) {
  348. if partitioner == "" {
  349. // partitioner not yet set
  350. return
  351. }
  352. // create a new token ring
  353. hosts := t.hosts.get()
  354. tokenRing, err := newTokenRing(partitioner, hosts)
  355. if err != nil {
  356. Logger.Printf("Unable to update the token ring due to error: %s", err)
  357. return
  358. }
  359. // replace the token ring
  360. t.tokenRing.Store(tokenRing)
  361. }
  362. func (t *tokenAwareHostPolicy) getReplicas(keyspace string, token token) ([]*HostInfo, bool) {
  363. meta, _ := t.keyspaces.Load().(*keyspaceMeta)
  364. if meta == nil {
  365. return nil, false
  366. }
  367. tokens, ok := meta.replicas[keyspace][token]
  368. return tokens, ok
  369. }
  370. func (t *tokenAwareHostPolicy) Pick(qry ExecutableQuery) NextHost {
  371. if qry == nil {
  372. return t.fallback.Pick(qry)
  373. }
  374. routingKey, err := qry.GetRoutingKey()
  375. if err != nil {
  376. return t.fallback.Pick(qry)
  377. } else if routingKey == nil {
  378. return t.fallback.Pick(qry)
  379. }
  380. tr, _ := t.tokenRing.Load().(*tokenRing)
  381. if tr == nil {
  382. return t.fallback.Pick(qry)
  383. }
  384. token := tr.partitioner.Hash(routingKey)
  385. primaryEndpoint := tr.GetHostForToken(token)
  386. if primaryEndpoint == nil || token == nil {
  387. return t.fallback.Pick(qry)
  388. }
  389. replicas, ok := t.getReplicas(qry.Keyspace(), token)
  390. if !ok {
  391. replicas = []*HostInfo{primaryEndpoint}
  392. } else if t.shuffleReplicas {
  393. replicas = shuffleHosts(replicas)
  394. }
  395. var (
  396. fallbackIter NextHost
  397. i int
  398. )
  399. used := make(map[*HostInfo]bool, len(replicas))
  400. return func() SelectedHost {
  401. for i < len(replicas) {
  402. h := replicas[i]
  403. i++
  404. if h.IsUp() && t.fallback.IsLocal(h) {
  405. used[h] = true
  406. return (*selectedHost)(h)
  407. }
  408. }
  409. if fallbackIter == nil {
  410. // fallback
  411. fallbackIter = t.fallback.Pick(qry)
  412. }
  413. // filter the token aware selected hosts from the fallback hosts
  414. for fallbackHost := fallbackIter(); fallbackHost != nil; fallbackHost = fallbackIter() {
  415. if !used[fallbackHost.Info()] {
  416. return fallbackHost
  417. }
  418. }
  419. return nil
  420. }
  421. }
  422. // HostPoolHostPolicy is a host policy which uses the bitly/go-hostpool library
  423. // to distribute queries between hosts and prevent sending queries to
  424. // unresponsive hosts. When creating the host pool that is passed to the policy
  425. // use an empty slice of hosts as the hostpool will be populated later by gocql.
  426. // See below for examples of usage:
  427. //
  428. // // Create host selection policy using a simple host pool
  429. // cluster.PoolConfig.HostSelectionPolicy = HostPoolHostPolicy(hostpool.New(nil))
  430. //
  431. // // Create host selection policy using an epsilon greedy pool
  432. // cluster.PoolConfig.HostSelectionPolicy = HostPoolHostPolicy(
  433. // hostpool.NewEpsilonGreedy(nil, 0, &hostpool.LinearEpsilonValueCalculator{}),
  434. // )
  435. //
  436. func HostPoolHostPolicy(hp hostpool.HostPool) HostSelectionPolicy {
  437. return &hostPoolHostPolicy{hostMap: map[string]*HostInfo{}, hp: hp}
  438. }
  439. type hostPoolHostPolicy struct {
  440. hp hostpool.HostPool
  441. mu sync.RWMutex
  442. hostMap map[string]*HostInfo
  443. }
  444. func (r *hostPoolHostPolicy) Init(*Session) {}
  445. func (r *hostPoolHostPolicy) KeyspaceChanged(KeyspaceUpdateEvent) {}
  446. func (r *hostPoolHostPolicy) SetPartitioner(string) {}
  447. func (r *hostPoolHostPolicy) IsLocal(*HostInfo) bool { return true }
  448. func (r *hostPoolHostPolicy) SetHosts(hosts []*HostInfo) {
  449. peers := make([]string, len(hosts))
  450. hostMap := make(map[string]*HostInfo, len(hosts))
  451. for i, host := range hosts {
  452. ip := host.ConnectAddress().String()
  453. peers[i] = ip
  454. hostMap[ip] = host
  455. }
  456. r.mu.Lock()
  457. r.hp.SetHosts(peers)
  458. r.hostMap = hostMap
  459. r.mu.Unlock()
  460. }
  461. func (r *hostPoolHostPolicy) AddHost(host *HostInfo) {
  462. ip := host.ConnectAddress().String()
  463. r.mu.Lock()
  464. defer r.mu.Unlock()
  465. // If the host addr is present and isn't nil return
  466. if h, ok := r.hostMap[ip]; ok && h != nil {
  467. return
  468. }
  469. // otherwise, add the host to the map
  470. r.hostMap[ip] = host
  471. // and construct a new peer list to give to the HostPool
  472. hosts := make([]string, 0, len(r.hostMap))
  473. for addr := range r.hostMap {
  474. hosts = append(hosts, addr)
  475. }
  476. r.hp.SetHosts(hosts)
  477. }
  478. func (r *hostPoolHostPolicy) RemoveHost(host *HostInfo) {
  479. ip := host.ConnectAddress().String()
  480. r.mu.Lock()
  481. defer r.mu.Unlock()
  482. if _, ok := r.hostMap[ip]; !ok {
  483. return
  484. }
  485. delete(r.hostMap, ip)
  486. hosts := make([]string, 0, len(r.hostMap))
  487. for _, host := range r.hostMap {
  488. hosts = append(hosts, host.ConnectAddress().String())
  489. }
  490. r.hp.SetHosts(hosts)
  491. }
  492. func (r *hostPoolHostPolicy) HostUp(host *HostInfo) {
  493. r.AddHost(host)
  494. }
  495. func (r *hostPoolHostPolicy) HostDown(host *HostInfo) {
  496. r.RemoveHost(host)
  497. }
  498. func (r *hostPoolHostPolicy) Pick(qry ExecutableQuery) NextHost {
  499. return func() SelectedHost {
  500. r.mu.RLock()
  501. defer r.mu.RUnlock()
  502. if len(r.hostMap) == 0 {
  503. return nil
  504. }
  505. hostR := r.hp.Get()
  506. host, ok := r.hostMap[hostR.Host()]
  507. if !ok {
  508. return nil
  509. }
  510. return selectedHostPoolHost{
  511. policy: r,
  512. info: host,
  513. hostR: hostR,
  514. }
  515. }
  516. }
  517. // selectedHostPoolHost is a host returned by the hostPoolHostPolicy and
  518. // implements the SelectedHost interface
  519. type selectedHostPoolHost struct {
  520. policy *hostPoolHostPolicy
  521. info *HostInfo
  522. hostR hostpool.HostPoolResponse
  523. }
  524. func (host selectedHostPoolHost) Info() *HostInfo {
  525. return host.info
  526. }
  527. func (host selectedHostPoolHost) Mark(err error) {
  528. ip := host.info.ConnectAddress().String()
  529. host.policy.mu.RLock()
  530. defer host.policy.mu.RUnlock()
  531. if _, ok := host.policy.hostMap[ip]; !ok {
  532. // host was removed between pick and mark
  533. return
  534. }
  535. host.hostR.Mark(err)
  536. }
  537. type dcAwareRR struct {
  538. local string
  539. pos uint32
  540. mu sync.RWMutex
  541. localHosts cowHostList
  542. remoteHosts cowHostList
  543. }
  544. // DCAwareRoundRobinPolicy is a host selection policies which will prioritize and
  545. // return hosts which are in the local datacentre before returning hosts in all
  546. // other datercentres
  547. func DCAwareRoundRobinPolicy(localDC string) HostSelectionPolicy {
  548. return &dcAwareRR{local: localDC}
  549. }
  550. func (d *dcAwareRR) Init(*Session) {}
  551. func (d *dcAwareRR) KeyspaceChanged(KeyspaceUpdateEvent) {}
  552. func (d *dcAwareRR) SetPartitioner(p string) {}
  553. func (d *dcAwareRR) IsLocal(host *HostInfo) bool {
  554. return host.DataCenter() == d.local
  555. }
  556. func (d *dcAwareRR) AddHost(host *HostInfo) {
  557. if host.DataCenter() == d.local {
  558. d.localHosts.add(host)
  559. } else {
  560. d.remoteHosts.add(host)
  561. }
  562. }
  563. func (d *dcAwareRR) RemoveHost(host *HostInfo) {
  564. if host.DataCenter() == d.local {
  565. d.localHosts.remove(host.ConnectAddress())
  566. } else {
  567. d.remoteHosts.remove(host.ConnectAddress())
  568. }
  569. }
  570. func (d *dcAwareRR) HostUp(host *HostInfo) { d.AddHost(host) }
  571. func (d *dcAwareRR) HostDown(host *HostInfo) { d.RemoveHost(host) }
  572. func (d *dcAwareRR) Pick(q ExecutableQuery) NextHost {
  573. var i int
  574. return func() SelectedHost {
  575. var hosts []*HostInfo
  576. localHosts := d.localHosts.get()
  577. remoteHosts := d.remoteHosts.get()
  578. if len(localHosts) != 0 {
  579. hosts = localHosts
  580. } else {
  581. hosts = remoteHosts
  582. }
  583. if len(hosts) == 0 {
  584. return nil
  585. }
  586. // always increment pos to evenly distribute traffic in case of
  587. // failures
  588. pos := atomic.AddUint32(&d.pos, 1) - 1
  589. if i >= len(localHosts)+len(remoteHosts) {
  590. return nil
  591. }
  592. host := hosts[(pos)%uint32(len(hosts))]
  593. i++
  594. return (*selectedHost)(host)
  595. }
  596. }
  597. // ReconnectionPolicy interface is used by gocql to determine if reconnection
  598. // can be attempted after connection error. The interface allows gocql users
  599. // to implement their own logic to determine how to attempt reconnection.
  600. //
  601. type ReconnectionPolicy interface {
  602. GetInterval(currentRetry int) time.Duration
  603. GetMaxRetries() int
  604. }
  605. // ConstantReconnectionPolicy has simple logic for returning a fixed reconnection interval.
  606. //
  607. // Examples of usage:
  608. //
  609. // cluster.ReconnectionPolicy = &gocql.ConstantReconnectionPolicy{MaxRetries: 10, Interval: 8 * time.Second}
  610. //
  611. type ConstantReconnectionPolicy struct {
  612. MaxRetries int
  613. Interval time.Duration
  614. }
  615. func (c *ConstantReconnectionPolicy) GetInterval(currentRetry int) time.Duration {
  616. return c.Interval
  617. }
  618. func (c *ConstantReconnectionPolicy) GetMaxRetries() int {
  619. return c.MaxRetries
  620. }
  621. // ExponentialReconnectionPolicy returns a growing reconnection interval.
  622. type ExponentialReconnectionPolicy struct {
  623. MaxRetries int
  624. InitialInterval time.Duration
  625. }
  626. func (e *ExponentialReconnectionPolicy) GetInterval(currentRetry int) time.Duration {
  627. return getExponentialTime(e.InitialInterval, math.MaxInt16*time.Second, e.GetMaxRetries())
  628. }
  629. func (e *ExponentialReconnectionPolicy) GetMaxRetries() int {
  630. return e.MaxRetries
  631. }