hostpool.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  1. package hostpool
  2. import (
  3. "log"
  4. "math"
  5. "sort"
  6. "sync"
  7. "time"
  8. )
  9. // --- timer: this just exists for testing
  10. type timer interface {
  11. between(time.Time, time.Time) time.Duration
  12. }
  13. type realTimer struct{}
  14. // --- Response interfaces and structs ----
  15. type HostPoolResponse interface {
  16. Host() string
  17. Mark(error)
  18. hostPool() HostPool
  19. }
  20. type standardHostPoolResponse struct {
  21. host string
  22. sync.Once
  23. pool HostPool
  24. }
  25. // --- HostPool structs and interfaces ----
  26. type HostPool interface {
  27. Get() HostPoolResponse
  28. // keep the marks separate so we can override independently
  29. markSuccess(HostPoolResponse)
  30. markFailed(HostPoolResponse)
  31. ResetAll()
  32. Hosts() []string
  33. lookupHost(string) HostEntry
  34. }
  35. type standardHostPool struct {
  36. sync.RWMutex
  37. hosts map[string]HostEntry
  38. initialRetryDelay time.Duration
  39. maxRetryInterval time.Duration
  40. nextHostIndex int
  41. }
  42. // --- Value Calculators -----------------
  43. type EpsilonValueCalculator interface {
  44. CalcValueFromAvgResponseTime(float64) float64
  45. }
  46. type LinearEpsilonValueCalculator struct{}
  47. type LogEpsilonValueCalculator struct{ LinearEpsilonValueCalculator }
  48. type PolynomialEpsilonValueCalculator struct {
  49. LinearEpsilonValueCalculator
  50. exp float64 // the exponent to which we will raise the value to reweight
  51. }
  52. func New(hosts []string) HostPool {
  53. p := &standardHostPool{
  54. hosts: make(map[string]HostEntry, len(hosts)),
  55. initialRetryDelay: time.Duration(30) * time.Second,
  56. maxRetryInterval: time.Duration(900) * time.Second,
  57. }
  58. for _, h := range hosts {
  59. e := newHostEntry(h, p.initialRetryDelay, p.maxRetryInterval)
  60. p.hosts[h] = e
  61. }
  62. return p
  63. }
  64. func (r *standardHostPoolResponse) Host() string {
  65. return r.host
  66. }
  67. func (r *standardHostPoolResponse) hostPool() HostPool {
  68. return r.pool
  69. }
  70. func (r *standardHostPoolResponse) Mark(err error) {
  71. r.Do(func() {
  72. doMark(err, r)
  73. })
  74. }
  75. func doMark(err error, r HostPoolResponse) {
  76. if err == nil {
  77. r.hostPool().markSuccess(r)
  78. } else {
  79. r.hostPool().markFailed(r)
  80. }
  81. }
  82. func (r *epsilonHostPoolResponse) Mark(err error) {
  83. r.Do(func() {
  84. r.ended = time.Now()
  85. doMark(err, r)
  86. })
  87. }
  88. func (rt *realTimer) between(start time.Time, end time.Time) time.Duration {
  89. return end.Sub(start)
  90. }
  91. // return an upstream entry from the HostPool
  92. func (p *standardHostPool) Get() HostPoolResponse {
  93. p.Lock()
  94. defer p.Unlock()
  95. host := p.getRoundRobin()
  96. return &standardHostPoolResponse{host: host, pool: p}
  97. }
  98. func (p *epsilonGreedyHostPool) Get() HostPoolResponse {
  99. host := p.getEpsilonGreedy()
  100. started := time.Now()
  101. return &epsilonHostPoolResponse{
  102. standardHostPoolResponse: standardHostPoolResponse{host: host, pool: p},
  103. started: started,
  104. }
  105. }
  106. func (p *standardHostPool) getRoundRobin() string {
  107. // TODO - will want to replace this with something that runs in a
  108. // goroutine and receives requests on a channel.
  109. // The state being protected in that case is really just the currentIdx
  110. // Question - should I just skip the goroutine shit and select randomly?
  111. // Maybe
  112. now := time.Now()
  113. hostCount := len(p.hosts)
  114. for i := range p.hostList() {
  115. // iterate via sequenece from where we last iterated
  116. currentIndex := (i + p.nextHostIndex) % hostCount
  117. h := p.hostList()[currentIndex]
  118. if h.canTryHost(now) {
  119. if h.IsDead() {
  120. h.willRetryHost()
  121. }
  122. p.nextHostIndex = currentIndex + 1
  123. return h.Host()
  124. }
  125. }
  126. // all hosts are down. re-add them
  127. p.ResetAll()
  128. p.nextHostIndex = 0
  129. return p.hostList()[0].Host()
  130. }
  131. func (p *standardHostPool) ResetAll() {
  132. // SetDead is threadsafe
  133. for _, h := range p.hosts {
  134. h.SetDead(false)
  135. }
  136. }
  137. func (p *standardHostPool) markSuccess(hostR HostPoolResponse) {
  138. host := hostR.Host()
  139. h, ok := p.hosts[host]
  140. if !ok {
  141. log.Fatalf("host %s not in HostPool %v", host, p.Hosts())
  142. }
  143. h.SetDead(false)
  144. }
  145. func (p *standardHostPool) markFailed(hostR HostPoolResponse) {
  146. host := hostR.Host()
  147. h, ok := p.hosts[host]
  148. if !ok {
  149. log.Fatalf("host %s not in HostPool %v", host, p.Hosts())
  150. }
  151. h.SetDead(true)
  152. }
  153. func (p *standardHostPool) Hosts() []string {
  154. hosts := make([]string, 0, len(p.hosts))
  155. for host, _ := range p.hosts {
  156. hosts = append(hosts, host)
  157. }
  158. return hosts
  159. }
  160. func (p *standardHostPool) lookupHost(hostname string) HostEntry {
  161. // We can do a "simple" lookup here because this map doesn't change once init'd
  162. h, ok := p.hosts[hostname]
  163. if !ok {
  164. log.Fatalf("host %s not in HostPool %v", hostname, p.Hosts())
  165. }
  166. return h
  167. }
  168. func (p *standardHostPool) hostList() []HostEntry {
  169. // This returns a sorted list of HostEntry's. We ought
  170. // to do some optimization so that this isn't computed every time
  171. // TODO can totally use Hosts above to accomplish this
  172. keys := make([]string, 0, len(p.hosts))
  173. vals := make([]HostEntry, 0, len(p.hosts))
  174. for hostName := range p.hosts {
  175. keys = append(keys, hostName)
  176. }
  177. sort.Strings(keys)
  178. for _, k := range keys {
  179. vals = append(vals, p.hosts[k])
  180. }
  181. return vals
  182. }
  183. // -------- Epsilon Value Calculators ----------
  184. func (c *LinearEpsilonValueCalculator) CalcValueFromAvgResponseTime(v float64) float64 {
  185. return 1.0 / v
  186. }
  187. func (c *LogEpsilonValueCalculator) CalcValueFromAvgResponseTime(v float64) float64 {
  188. return math.Log(c.LinearEpsilonValueCalculator.CalcValueFromAvgResponseTime(v))
  189. }
  190. func (c *PolynomialEpsilonValueCalculator) CalcValueFromAvgResponseTime(v float64) float64 {
  191. return math.Pow(c.LinearEpsilonValueCalculator.CalcValueFromAvgResponseTime(v), c.exp)
  192. }