policies.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940
  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. "context"
  8. "errors"
  9. "fmt"
  10. "math"
  11. "math/rand"
  12. "net"
  13. "sync"
  14. "sync/atomic"
  15. "time"
  16. "github.com/hailocab/go-hostpool"
  17. )
  18. // cowHostList implements a copy on write host list, its equivalent type is []*HostInfo
  19. type cowHostList struct {
  20. list atomic.Value
  21. mu sync.Mutex
  22. }
  23. func (c *cowHostList) String() string {
  24. return fmt.Sprintf("%+v", c.get())
  25. }
  26. func (c *cowHostList) get() []*HostInfo {
  27. // TODO(zariel): should we replace this with []*HostInfo?
  28. l, ok := c.list.Load().(*[]*HostInfo)
  29. if !ok {
  30. return nil
  31. }
  32. return *l
  33. }
  34. func (c *cowHostList) set(list []*HostInfo) {
  35. c.mu.Lock()
  36. c.list.Store(&list)
  37. c.mu.Unlock()
  38. }
  39. // add will add a host if it not already in the list
  40. func (c *cowHostList) add(host *HostInfo) bool {
  41. c.mu.Lock()
  42. l := c.get()
  43. if n := len(l); n == 0 {
  44. l = []*HostInfo{host}
  45. } else {
  46. newL := make([]*HostInfo, n+1)
  47. for i := 0; i < n; i++ {
  48. if host.Equal(l[i]) {
  49. c.mu.Unlock()
  50. return false
  51. }
  52. newL[i] = l[i]
  53. }
  54. newL[n] = host
  55. l = newL
  56. }
  57. c.list.Store(&l)
  58. c.mu.Unlock()
  59. return true
  60. }
  61. func (c *cowHostList) update(host *HostInfo) {
  62. c.mu.Lock()
  63. l := c.get()
  64. if len(l) == 0 {
  65. c.mu.Unlock()
  66. return
  67. }
  68. found := false
  69. newL := make([]*HostInfo, len(l))
  70. for i := range l {
  71. if host.Equal(l[i]) {
  72. newL[i] = host
  73. found = true
  74. } else {
  75. newL[i] = l[i]
  76. }
  77. }
  78. if found {
  79. c.list.Store(&newL)
  80. }
  81. c.mu.Unlock()
  82. }
  83. func (c *cowHostList) remove(ip net.IP) bool {
  84. c.mu.Lock()
  85. l := c.get()
  86. size := len(l)
  87. if size == 0 {
  88. c.mu.Unlock()
  89. return false
  90. }
  91. found := false
  92. newL := make([]*HostInfo, 0, size)
  93. for i := 0; i < len(l); i++ {
  94. if !l[i].ConnectAddress().Equal(ip) {
  95. newL = append(newL, l[i])
  96. } else {
  97. found = true
  98. }
  99. }
  100. if !found {
  101. c.mu.Unlock()
  102. return false
  103. }
  104. newL = newL[: size-1 : size-1]
  105. c.list.Store(&newL)
  106. c.mu.Unlock()
  107. return true
  108. }
  109. // RetryableQuery is an interface that represents a query or batch statement that
  110. // exposes the correct functions for the retry policy logic to evaluate correctly.
  111. type RetryableQuery interface {
  112. Attempts() int
  113. SetConsistency(c Consistency)
  114. GetConsistency() Consistency
  115. Context() context.Context
  116. }
  117. type RetryType uint16
  118. const (
  119. Retry RetryType = 0x00 // retry on same connection
  120. RetryNextHost RetryType = 0x01 // retry on another connection
  121. Ignore RetryType = 0x02 // ignore error and return result
  122. Rethrow RetryType = 0x03 // raise error and stop retrying
  123. )
  124. // ErrUnknownRetryType is returned if the retry policy returns a retry type
  125. // unknown to the query executor.
  126. var ErrUnknownRetryType = errors.New("unknown retry type returned by retry policy")
  127. // RetryPolicy interface is used by gocql to determine if a query can be attempted
  128. // again after a retryable error has been received. The interface allows gocql
  129. // users to implement their own logic to determine if a query can be attempted
  130. // again.
  131. //
  132. // See SimpleRetryPolicy as an example of implementing and using a RetryPolicy
  133. // interface.
  134. type RetryPolicy interface {
  135. Attempt(RetryableQuery) bool
  136. GetRetryType(error) RetryType
  137. }
  138. // SimpleRetryPolicy has simple logic for attempting a query a fixed number of times.
  139. //
  140. // See below for examples of usage:
  141. //
  142. // //Assign to the cluster
  143. // cluster.RetryPolicy = &gocql.SimpleRetryPolicy{NumRetries: 3}
  144. //
  145. // //Assign to a query
  146. // query.RetryPolicy(&gocql.SimpleRetryPolicy{NumRetries: 1})
  147. //
  148. type SimpleRetryPolicy struct {
  149. NumRetries int //Number of times to retry a query
  150. }
  151. // Attempt tells gocql to attempt the query again based on query.Attempts being less
  152. // than the NumRetries defined in the policy.
  153. func (s *SimpleRetryPolicy) Attempt(q RetryableQuery) bool {
  154. return q.Attempts() <= s.NumRetries
  155. }
  156. func (s *SimpleRetryPolicy) GetRetryType(err error) RetryType {
  157. return RetryNextHost
  158. }
  159. // ExponentialBackoffRetryPolicy sleeps between attempts
  160. type ExponentialBackoffRetryPolicy struct {
  161. NumRetries int
  162. Min, Max time.Duration
  163. }
  164. func (e *ExponentialBackoffRetryPolicy) Attempt(q RetryableQuery) bool {
  165. if q.Attempts() > e.NumRetries {
  166. return false
  167. }
  168. time.Sleep(e.napTime(q.Attempts()))
  169. return true
  170. }
  171. // used to calculate exponentially growing time
  172. func getExponentialTime(min time.Duration, max time.Duration, attempts int) time.Duration {
  173. if min <= 0 {
  174. min = 100 * time.Millisecond
  175. }
  176. if max <= 0 {
  177. max = 10 * time.Second
  178. }
  179. minFloat := float64(min)
  180. napDuration := minFloat * math.Pow(2, float64(attempts-1))
  181. // add some jitter
  182. napDuration += rand.Float64()*minFloat - (minFloat / 2)
  183. if napDuration > float64(max) {
  184. return time.Duration(max)
  185. }
  186. return time.Duration(napDuration)
  187. }
  188. func (e *ExponentialBackoffRetryPolicy) GetRetryType(err error) RetryType {
  189. return RetryNextHost
  190. }
  191. // DowngradingConsistencyRetryPolicy: Next retry will be with the next consistency level
  192. // provided in the slice
  193. //
  194. // On a read timeout: the operation is retried with the next provided consistency
  195. // level.
  196. //
  197. // On a write timeout: if the operation is an :attr:`~.UNLOGGED_BATCH`
  198. // and at least one replica acknowledged the write, the operation is
  199. // retried with the next consistency level. Furthermore, for other
  200. // write types, if at least one replica acknowledged the write, the
  201. // timeout is ignored.
  202. //
  203. // On an unavailable exception: if at least one replica is alive, the
  204. // operation is retried with the next provided consistency level.
  205. type DowngradingConsistencyRetryPolicy struct {
  206. ConsistencyLevelsToTry []Consistency
  207. }
  208. func (d *DowngradingConsistencyRetryPolicy) Attempt(q RetryableQuery) bool {
  209. currentAttempt := q.Attempts()
  210. if currentAttempt > len(d.ConsistencyLevelsToTry) {
  211. return false
  212. } else if currentAttempt > 0 {
  213. q.SetConsistency(d.ConsistencyLevelsToTry[currentAttempt-1])
  214. if gocqlDebug {
  215. Logger.Printf("%T: set consistency to %q\n",
  216. d,
  217. d.ConsistencyLevelsToTry[currentAttempt-1])
  218. }
  219. }
  220. return true
  221. }
  222. func (d *DowngradingConsistencyRetryPolicy) GetRetryType(err error) RetryType {
  223. switch t := err.(type) {
  224. case *RequestErrUnavailable:
  225. if t.Alive > 0 {
  226. return Retry
  227. }
  228. return Rethrow
  229. case *RequestErrWriteTimeout:
  230. if t.WriteType == "SIMPLE" || t.WriteType == "BATCH" || t.WriteType == "COUNTER" {
  231. if t.Received > 0 {
  232. return Ignore
  233. }
  234. return Rethrow
  235. }
  236. if t.WriteType == "UNLOGGED_BATCH" {
  237. return Retry
  238. }
  239. return Rethrow
  240. case *RequestErrReadTimeout:
  241. return Retry
  242. default:
  243. return RetryNextHost
  244. }
  245. }
  246. func (e *ExponentialBackoffRetryPolicy) napTime(attempts int) time.Duration {
  247. return getExponentialTime(e.Min, e.Max, attempts)
  248. }
  249. type HostStateNotifier interface {
  250. AddHost(host *HostInfo)
  251. RemoveHost(host *HostInfo)
  252. HostUp(host *HostInfo)
  253. HostDown(host *HostInfo)
  254. }
  255. type KeyspaceUpdateEvent struct {
  256. Keyspace string
  257. Change string
  258. }
  259. // HostSelectionPolicy is an interface for selecting
  260. // the most appropriate host to execute a given query.
  261. type HostSelectionPolicy interface {
  262. HostStateNotifier
  263. SetPartitioner
  264. KeyspaceChanged(KeyspaceUpdateEvent)
  265. Init(*Session)
  266. IsLocal(host *HostInfo) bool
  267. //Pick returns an iteration function over selected hosts
  268. Pick(ExecutableQuery) NextHost
  269. }
  270. // SelectedHost is an interface returned when picking a host from a host
  271. // selection policy.
  272. type SelectedHost interface {
  273. Info() *HostInfo
  274. Mark(error)
  275. }
  276. type selectedHost HostInfo
  277. func (host *selectedHost) Info() *HostInfo {
  278. return (*HostInfo)(host)
  279. }
  280. func (host *selectedHost) Mark(err error) {}
  281. // NextHost is an iteration function over picked hosts
  282. type NextHost func() SelectedHost
  283. // RoundRobinHostPolicy is a round-robin load balancing policy, where each host
  284. // is tried sequentially for each query.
  285. func RoundRobinHostPolicy() HostSelectionPolicy {
  286. return &roundRobinHostPolicy{}
  287. }
  288. type roundRobinHostPolicy struct {
  289. hosts cowHostList
  290. pos uint32
  291. mu sync.RWMutex
  292. }
  293. func (r *roundRobinHostPolicy) IsLocal(*HostInfo) bool { return true }
  294. func (r *roundRobinHostPolicy) KeyspaceChanged(KeyspaceUpdateEvent) {}
  295. func (r *roundRobinHostPolicy) SetPartitioner(partitioner string) {}
  296. func (r *roundRobinHostPolicy) Init(*Session) {}
  297. func (r *roundRobinHostPolicy) Pick(qry ExecutableQuery) NextHost {
  298. // i is used to limit the number of attempts to find a host
  299. // to the number of hosts known to this policy
  300. var i int
  301. return func() SelectedHost {
  302. hosts := r.hosts.get()
  303. if len(hosts) == 0 {
  304. return nil
  305. }
  306. // always increment pos to evenly distribute traffic in case of
  307. // failures
  308. pos := atomic.AddUint32(&r.pos, 1) - 1
  309. if i >= len(hosts) {
  310. return nil
  311. }
  312. host := hosts[(pos)%uint32(len(hosts))]
  313. i++
  314. return (*selectedHost)(host)
  315. }
  316. }
  317. func (r *roundRobinHostPolicy) AddHost(host *HostInfo) {
  318. r.hosts.add(host)
  319. }
  320. func (r *roundRobinHostPolicy) RemoveHost(host *HostInfo) {
  321. r.hosts.remove(host.ConnectAddress())
  322. }
  323. func (r *roundRobinHostPolicy) HostUp(host *HostInfo) {
  324. r.AddHost(host)
  325. }
  326. func (r *roundRobinHostPolicy) HostDown(host *HostInfo) {
  327. r.RemoveHost(host)
  328. }
  329. func ShuffleReplicas() func(*tokenAwareHostPolicy) {
  330. return func(t *tokenAwareHostPolicy) {
  331. t.shuffleReplicas = true
  332. }
  333. }
  334. // NonLocalReplicasFallback enables fallback to replicas that are not considered local.
  335. //
  336. // TokenAwareHostPolicy used with DCAwareHostPolicy fallback first selects replicas by partition key in local DC, then
  337. // falls back to other nodes in the local DC. Enabling NonLocalReplicasFallback causes TokenAwareHostPolicy
  338. // to first select replicas by partition key in local DC, then replicas by partition key in remote DCs and fall back
  339. // to other nodes in local DC.
  340. func NonLocalReplicasFallback() func(policy *tokenAwareHostPolicy) {
  341. return func(t *tokenAwareHostPolicy) {
  342. t.nonLocalReplicasFallback = true
  343. }
  344. }
  345. // TokenAwareHostPolicy is a token aware host selection policy, where hosts are
  346. // selected based on the partition key, so queries are sent to the host which
  347. // owns the partition. Fallback is used when routing information is not available.
  348. func TokenAwareHostPolicy(fallback HostSelectionPolicy, opts ...func(*tokenAwareHostPolicy)) HostSelectionPolicy {
  349. p := &tokenAwareHostPolicy{fallback: fallback}
  350. for _, opt := range opts {
  351. opt(p)
  352. }
  353. return p
  354. }
  355. // clusterMeta holds metadata about cluster topology.
  356. // It is used inside atomic.Value and shallow copies are used when replacing it,
  357. // so fields should not be modified in-place. Instead, to modify a field a copy of the field should be made
  358. // and the pointer in clusterMeta updated to point to the new value.
  359. type clusterMeta struct {
  360. // replicas is map[keyspace]map[token]hosts
  361. replicas map[string]tokenRingReplicas
  362. tokenRing *tokenRing
  363. }
  364. type tokenAwareHostPolicy struct {
  365. fallback HostSelectionPolicy
  366. getKeyspaceMetadata func(keyspace string) (*KeyspaceMetadata, error)
  367. getKeyspaceName func() string
  368. shuffleReplicas bool
  369. nonLocalReplicasFallback bool
  370. // mu protects writes to hosts, partitioner, metadata.
  371. // reads can be unlocked as long as they are not used for updating state later.
  372. mu sync.Mutex
  373. hosts cowHostList
  374. partitioner string
  375. metadata atomic.Value // *clusterMeta
  376. }
  377. func (t *tokenAwareHostPolicy) Init(s *Session) {
  378. t.getKeyspaceMetadata = s.KeyspaceMetadata
  379. t.getKeyspaceName = func() string { return s.cfg.Keyspace }
  380. }
  381. func (t *tokenAwareHostPolicy) IsLocal(host *HostInfo) bool {
  382. return t.fallback.IsLocal(host)
  383. }
  384. func (t *tokenAwareHostPolicy) KeyspaceChanged(update KeyspaceUpdateEvent) {
  385. t.mu.Lock()
  386. defer t.mu.Unlock()
  387. meta := t.getMetadataForUpdate()
  388. t.updateReplicas(meta, update.Keyspace)
  389. t.metadata.Store(meta)
  390. }
  391. // updateReplicas updates replicas in clusterMeta.
  392. // It must be called with t.mu mutex locked.
  393. // meta must not be nil and it's replicas field will be updated.
  394. func (t *tokenAwareHostPolicy) updateReplicas(meta *clusterMeta, keyspace string) {
  395. newReplicas := make(map[string]tokenRingReplicas, len(meta.replicas))
  396. ks, err := t.getKeyspaceMetadata(keyspace)
  397. if err == nil {
  398. strat := getStrategy(ks)
  399. if strat != nil {
  400. if meta != nil && meta.tokenRing != nil {
  401. newReplicas[keyspace] = strat.replicaMap(meta.tokenRing)
  402. }
  403. }
  404. }
  405. for ks, replicas := range meta.replicas {
  406. if ks != keyspace {
  407. newReplicas[ks] = replicas
  408. }
  409. }
  410. meta.replicas = newReplicas
  411. }
  412. func (t *tokenAwareHostPolicy) SetPartitioner(partitioner string) {
  413. t.mu.Lock()
  414. defer t.mu.Unlock()
  415. if t.partitioner != partitioner {
  416. t.fallback.SetPartitioner(partitioner)
  417. t.partitioner = partitioner
  418. meta := t.getMetadataForUpdate()
  419. meta.resetTokenRing(t.partitioner, t.hosts.get())
  420. t.updateReplicas(meta, t.getKeyspaceName())
  421. t.metadata.Store(meta)
  422. }
  423. }
  424. func (t *tokenAwareHostPolicy) AddHost(host *HostInfo) {
  425. t.mu.Lock()
  426. if t.hosts.add(host) {
  427. meta := t.getMetadataForUpdate()
  428. meta.resetTokenRing(t.partitioner, t.hosts.get())
  429. t.updateReplicas(meta, t.getKeyspaceName())
  430. t.metadata.Store(meta)
  431. }
  432. t.mu.Unlock()
  433. t.fallback.AddHost(host)
  434. }
  435. func (t *tokenAwareHostPolicy) RemoveHost(host *HostInfo) {
  436. t.mu.Lock()
  437. if t.hosts.remove(host.ConnectAddress()) {
  438. meta := t.getMetadataForUpdate()
  439. meta.resetTokenRing(t.partitioner, t.hosts.get())
  440. t.updateReplicas(meta, t.getKeyspaceName())
  441. t.metadata.Store(meta)
  442. }
  443. t.mu.Unlock()
  444. t.fallback.RemoveHost(host)
  445. }
  446. func (t *tokenAwareHostPolicy) HostUp(host *HostInfo) {
  447. t.fallback.HostUp(host)
  448. }
  449. func (t *tokenAwareHostPolicy) HostDown(host *HostInfo) {
  450. t.fallback.HostDown(host)
  451. }
  452. // getMetadataReadOnly returns current cluster metadata.
  453. // Metadata uses copy on write, so the returned value should be only used for reading.
  454. // To obtain a copy that could be updated, use getMetadataForUpdate instead.
  455. func (t *tokenAwareHostPolicy) getMetadataReadOnly() *clusterMeta {
  456. meta, _ := t.metadata.Load().(*clusterMeta)
  457. return meta
  458. }
  459. // getMetadataForUpdate returns clusterMeta suitable for updating.
  460. // It is a SHALLOW copy of current metadata in case it was already set or new empty clusterMeta otherwise.
  461. // This function should be called with t.mu mutex locked and the mutex should not be released before
  462. // storing the new metadata.
  463. func (t *tokenAwareHostPolicy) getMetadataForUpdate() *clusterMeta {
  464. metaReadOnly := t.getMetadataReadOnly()
  465. meta := new(clusterMeta)
  466. if metaReadOnly != nil {
  467. *meta = *metaReadOnly
  468. }
  469. return meta
  470. }
  471. // resetTokenRing creates a new tokenRing.
  472. // It must be called with t.mu locked.
  473. func (m *clusterMeta) resetTokenRing(partitioner string, hosts []*HostInfo) {
  474. if partitioner == "" {
  475. // partitioner not yet set
  476. return
  477. }
  478. // create a new token ring
  479. tokenRing, err := newTokenRing(partitioner, hosts)
  480. if err != nil {
  481. Logger.Printf("Unable to update the token ring due to error: %s", err)
  482. return
  483. }
  484. // replace the token ring
  485. m.tokenRing = tokenRing
  486. }
  487. func (t *tokenAwareHostPolicy) Pick(qry ExecutableQuery) NextHost {
  488. if qry == nil {
  489. return t.fallback.Pick(qry)
  490. }
  491. routingKey, err := qry.GetRoutingKey()
  492. if err != nil {
  493. return t.fallback.Pick(qry)
  494. } else if routingKey == nil {
  495. return t.fallback.Pick(qry)
  496. }
  497. meta := t.getMetadataReadOnly()
  498. if meta == nil || meta.tokenRing == nil {
  499. return t.fallback.Pick(qry)
  500. }
  501. token := meta.tokenRing.partitioner.Hash(routingKey)
  502. ht := meta.replicas[qry.Keyspace()].replicasFor(token)
  503. var replicas []*HostInfo
  504. if ht == nil {
  505. host, _ := meta.tokenRing.GetHostForToken(token)
  506. replicas = []*HostInfo{host}
  507. } else if t.shuffleReplicas {
  508. replicas = shuffleHosts(replicas)
  509. } else {
  510. replicas = ht.hosts
  511. }
  512. var (
  513. fallbackIter NextHost
  514. i, j int
  515. remote []*HostInfo
  516. )
  517. used := make(map[*HostInfo]bool, len(replicas))
  518. return func() SelectedHost {
  519. for i < len(replicas) {
  520. h := replicas[i]
  521. i++
  522. if !t.fallback.IsLocal(h) {
  523. remote = append(remote, h)
  524. continue
  525. }
  526. if h.IsUp() {
  527. used[h] = true
  528. return (*selectedHost)(h)
  529. }
  530. }
  531. if t.nonLocalReplicasFallback {
  532. for j < len(remote) {
  533. h := remote[j]
  534. j++
  535. if h.IsUp() {
  536. used[h] = true
  537. return (*selectedHost)(h)
  538. }
  539. }
  540. }
  541. if fallbackIter == nil {
  542. // fallback
  543. fallbackIter = t.fallback.Pick(qry)
  544. }
  545. // filter the token aware selected hosts from the fallback hosts
  546. for fallbackHost := fallbackIter(); fallbackHost != nil; fallbackHost = fallbackIter() {
  547. if !used[fallbackHost.Info()] {
  548. used[fallbackHost.Info()] = true
  549. return fallbackHost
  550. }
  551. }
  552. return nil
  553. }
  554. }
  555. // HostPoolHostPolicy is a host policy which uses the bitly/go-hostpool library
  556. // to distribute queries between hosts and prevent sending queries to
  557. // unresponsive hosts. When creating the host pool that is passed to the policy
  558. // use an empty slice of hosts as the hostpool will be populated later by gocql.
  559. // See below for examples of usage:
  560. //
  561. // // Create host selection policy using a simple host pool
  562. // cluster.PoolConfig.HostSelectionPolicy = HostPoolHostPolicy(hostpool.New(nil))
  563. //
  564. // // Create host selection policy using an epsilon greedy pool
  565. // cluster.PoolConfig.HostSelectionPolicy = HostPoolHostPolicy(
  566. // hostpool.NewEpsilonGreedy(nil, 0, &hostpool.LinearEpsilonValueCalculator{}),
  567. // )
  568. //
  569. func HostPoolHostPolicy(hp hostpool.HostPool) HostSelectionPolicy {
  570. return &hostPoolHostPolicy{hostMap: map[string]*HostInfo{}, hp: hp}
  571. }
  572. type hostPoolHostPolicy struct {
  573. hp hostpool.HostPool
  574. mu sync.RWMutex
  575. hostMap map[string]*HostInfo
  576. }
  577. func (r *hostPoolHostPolicy) Init(*Session) {}
  578. func (r *hostPoolHostPolicy) KeyspaceChanged(KeyspaceUpdateEvent) {}
  579. func (r *hostPoolHostPolicy) SetPartitioner(string) {}
  580. func (r *hostPoolHostPolicy) IsLocal(*HostInfo) bool { return true }
  581. func (r *hostPoolHostPolicy) SetHosts(hosts []*HostInfo) {
  582. peers := make([]string, len(hosts))
  583. hostMap := make(map[string]*HostInfo, len(hosts))
  584. for i, host := range hosts {
  585. ip := host.ConnectAddress().String()
  586. peers[i] = ip
  587. hostMap[ip] = host
  588. }
  589. r.mu.Lock()
  590. r.hp.SetHosts(peers)
  591. r.hostMap = hostMap
  592. r.mu.Unlock()
  593. }
  594. func (r *hostPoolHostPolicy) AddHost(host *HostInfo) {
  595. ip := host.ConnectAddress().String()
  596. r.mu.Lock()
  597. defer r.mu.Unlock()
  598. // If the host addr is present and isn't nil return
  599. if h, ok := r.hostMap[ip]; ok && h != nil {
  600. return
  601. }
  602. // otherwise, add the host to the map
  603. r.hostMap[ip] = host
  604. // and construct a new peer list to give to the HostPool
  605. hosts := make([]string, 0, len(r.hostMap))
  606. for addr := range r.hostMap {
  607. hosts = append(hosts, addr)
  608. }
  609. r.hp.SetHosts(hosts)
  610. }
  611. func (r *hostPoolHostPolicy) RemoveHost(host *HostInfo) {
  612. ip := host.ConnectAddress().String()
  613. r.mu.Lock()
  614. defer r.mu.Unlock()
  615. if _, ok := r.hostMap[ip]; !ok {
  616. return
  617. }
  618. delete(r.hostMap, ip)
  619. hosts := make([]string, 0, len(r.hostMap))
  620. for _, host := range r.hostMap {
  621. hosts = append(hosts, host.ConnectAddress().String())
  622. }
  623. r.hp.SetHosts(hosts)
  624. }
  625. func (r *hostPoolHostPolicy) HostUp(host *HostInfo) {
  626. r.AddHost(host)
  627. }
  628. func (r *hostPoolHostPolicy) HostDown(host *HostInfo) {
  629. r.RemoveHost(host)
  630. }
  631. func (r *hostPoolHostPolicy) Pick(qry ExecutableQuery) NextHost {
  632. return func() SelectedHost {
  633. r.mu.RLock()
  634. defer r.mu.RUnlock()
  635. if len(r.hostMap) == 0 {
  636. return nil
  637. }
  638. hostR := r.hp.Get()
  639. host, ok := r.hostMap[hostR.Host()]
  640. if !ok {
  641. return nil
  642. }
  643. return selectedHostPoolHost{
  644. policy: r,
  645. info: host,
  646. hostR: hostR,
  647. }
  648. }
  649. }
  650. // selectedHostPoolHost is a host returned by the hostPoolHostPolicy and
  651. // implements the SelectedHost interface
  652. type selectedHostPoolHost struct {
  653. policy *hostPoolHostPolicy
  654. info *HostInfo
  655. hostR hostpool.HostPoolResponse
  656. }
  657. func (host selectedHostPoolHost) Info() *HostInfo {
  658. return host.info
  659. }
  660. func (host selectedHostPoolHost) Mark(err error) {
  661. ip := host.info.ConnectAddress().String()
  662. host.policy.mu.RLock()
  663. defer host.policy.mu.RUnlock()
  664. if _, ok := host.policy.hostMap[ip]; !ok {
  665. // host was removed between pick and mark
  666. return
  667. }
  668. host.hostR.Mark(err)
  669. }
  670. type dcAwareRR struct {
  671. local string
  672. pos uint32
  673. mu sync.RWMutex
  674. localHosts cowHostList
  675. remoteHosts cowHostList
  676. }
  677. // DCAwareRoundRobinPolicy is a host selection policies which will prioritize and
  678. // return hosts which are in the local datacentre before returning hosts in all
  679. // other datercentres
  680. func DCAwareRoundRobinPolicy(localDC string) HostSelectionPolicy {
  681. return &dcAwareRR{local: localDC}
  682. }
  683. func (d *dcAwareRR) Init(*Session) {}
  684. func (d *dcAwareRR) KeyspaceChanged(KeyspaceUpdateEvent) {}
  685. func (d *dcAwareRR) SetPartitioner(p string) {}
  686. func (d *dcAwareRR) IsLocal(host *HostInfo) bool {
  687. return host.DataCenter() == d.local
  688. }
  689. func (d *dcAwareRR) AddHost(host *HostInfo) {
  690. if host.DataCenter() == d.local {
  691. d.localHosts.add(host)
  692. } else {
  693. d.remoteHosts.add(host)
  694. }
  695. }
  696. func (d *dcAwareRR) RemoveHost(host *HostInfo) {
  697. if host.DataCenter() == d.local {
  698. d.localHosts.remove(host.ConnectAddress())
  699. } else {
  700. d.remoteHosts.remove(host.ConnectAddress())
  701. }
  702. }
  703. func (d *dcAwareRR) HostUp(host *HostInfo) { d.AddHost(host) }
  704. func (d *dcAwareRR) HostDown(host *HostInfo) { d.RemoveHost(host) }
  705. func (d *dcAwareRR) Pick(q ExecutableQuery) NextHost {
  706. var i int
  707. return func() SelectedHost {
  708. var hosts []*HostInfo
  709. localHosts := d.localHosts.get()
  710. remoteHosts := d.remoteHosts.get()
  711. if len(localHosts) != 0 {
  712. hosts = localHosts
  713. } else {
  714. hosts = remoteHosts
  715. }
  716. if len(hosts) == 0 {
  717. return nil
  718. }
  719. // always increment pos to evenly distribute traffic in case of
  720. // failures
  721. pos := atomic.AddUint32(&d.pos, 1) - 1
  722. if i >= len(localHosts)+len(remoteHosts) {
  723. return nil
  724. }
  725. host := hosts[(pos)%uint32(len(hosts))]
  726. i++
  727. return (*selectedHost)(host)
  728. }
  729. }
  730. // ConvictionPolicy interface is used by gocql to determine if a host should be
  731. // marked as DOWN based on the error and host info
  732. type ConvictionPolicy interface {
  733. // Implementations should return `true` if the host should be convicted, `false` otherwise.
  734. AddFailure(error error, host *HostInfo) bool
  735. //Implementations should clear out any convictions or state regarding the host.
  736. Reset(host *HostInfo)
  737. }
  738. // SimpleConvictionPolicy implements a ConvictionPolicy which convicts all hosts
  739. // regardless of error
  740. type SimpleConvictionPolicy struct {
  741. }
  742. func (e *SimpleConvictionPolicy) AddFailure(error error, host *HostInfo) bool {
  743. return true
  744. }
  745. func (e *SimpleConvictionPolicy) Reset(host *HostInfo) {}
  746. // ReconnectionPolicy interface is used by gocql to determine if reconnection
  747. // can be attempted after connection error. The interface allows gocql users
  748. // to implement their own logic to determine how to attempt reconnection.
  749. //
  750. type ReconnectionPolicy interface {
  751. GetInterval(currentRetry int) time.Duration
  752. GetMaxRetries() int
  753. }
  754. // ConstantReconnectionPolicy has simple logic for returning a fixed reconnection interval.
  755. //
  756. // Examples of usage:
  757. //
  758. // cluster.ReconnectionPolicy = &gocql.ConstantReconnectionPolicy{MaxRetries: 10, Interval: 8 * time.Second}
  759. //
  760. type ConstantReconnectionPolicy struct {
  761. MaxRetries int
  762. Interval time.Duration
  763. }
  764. func (c *ConstantReconnectionPolicy) GetInterval(currentRetry int) time.Duration {
  765. return c.Interval
  766. }
  767. func (c *ConstantReconnectionPolicy) GetMaxRetries() int {
  768. return c.MaxRetries
  769. }
  770. // ExponentialReconnectionPolicy returns a growing reconnection interval.
  771. type ExponentialReconnectionPolicy struct {
  772. MaxRetries int
  773. InitialInterval time.Duration
  774. }
  775. func (e *ExponentialReconnectionPolicy) GetInterval(currentRetry int) time.Duration {
  776. return getExponentialTime(e.InitialInterval, math.MaxInt16*time.Second, e.GetMaxRetries())
  777. }
  778. func (e *ExponentialReconnectionPolicy) GetMaxRetries() int {
  779. return e.MaxRetries
  780. }
  781. type SpeculativeExecutionPolicy interface {
  782. Attempts() int
  783. Delay() time.Duration
  784. }
  785. type NonSpeculativeExecution struct{}
  786. func (sp NonSpeculativeExecution) Attempts() int { return 0 } // No additional attempts
  787. func (sp NonSpeculativeExecution) Delay() time.Duration { return 1 } // The delay. Must be positive to be used in a ticker.
  788. type SimpleSpeculativeExecution struct {
  789. NumAttempts int
  790. TimeoutDelay time.Duration
  791. }
  792. func (sp *SimpleSpeculativeExecution) Attempts() int { return sp.NumAttempts }
  793. func (sp *SimpleSpeculativeExecution) Delay() time.Duration { return sp.TimeoutDelay }