hostpool.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  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. Close()
  35. }
  36. type standardHostPool struct {
  37. hosts map[string]HostEntry
  38. initialRetryDelay time.Duration
  39. maxRetryInterval time.Duration
  40. rrResults chan string
  41. closeChan chan struct{}
  42. wg sync.WaitGroup
  43. }
  44. // --- Value Calculators -----------------
  45. type EpsilonValueCalculator interface {
  46. CalcValueFromAvgResponseTime(float64) float64
  47. }
  48. type LinearEpsilonValueCalculator struct{}
  49. type LogEpsilonValueCalculator struct{ LinearEpsilonValueCalculator }
  50. type PolynomialEpsilonValueCalculator struct {
  51. LinearEpsilonValueCalculator
  52. exp float64 // the exponent to which we will raise the value to reweight
  53. }
  54. func New(hosts []string) HostPool {
  55. p := &standardHostPool{
  56. hosts: make(map[string]HostEntry, len(hosts)),
  57. initialRetryDelay: time.Duration(30) * time.Second,
  58. maxRetryInterval: time.Duration(900) * time.Second,
  59. rrResults: make(chan string),
  60. closeChan: make(chan struct{}),
  61. }
  62. for _, h := range hosts {
  63. e := newHostEntry(h, p.initialRetryDelay, p.maxRetryInterval)
  64. p.hosts[h] = e
  65. }
  66. p.wg.Add(1)
  67. go p.serveRoundRobin()
  68. return p
  69. }
  70. func (r *standardHostPoolResponse) Host() string {
  71. return r.host
  72. }
  73. func (r *standardHostPoolResponse) hostPool() HostPool {
  74. return r.pool
  75. }
  76. func (r *standardHostPoolResponse) Mark(err error) {
  77. r.Do(func() {
  78. doMark(err, r)
  79. })
  80. }
  81. func doMark(err error, r HostPoolResponse) {
  82. if err == nil {
  83. r.hostPool().markSuccess(r)
  84. } else {
  85. r.hostPool().markFailed(r)
  86. }
  87. }
  88. func (r *epsilonHostPoolResponse) Mark(err error) {
  89. r.Do(func() {
  90. r.ended = time.Now()
  91. doMark(err, r)
  92. })
  93. }
  94. func (rt *realTimer) between(start time.Time, end time.Time) time.Duration {
  95. return end.Sub(start)
  96. }
  97. // return an upstream entry from the HostPool
  98. func (p *standardHostPool) Get() HostPoolResponse {
  99. host := p.getRoundRobin()
  100. return &standardHostPoolResponse{host: host, pool: p}
  101. }
  102. func (p *epsilonGreedyHostPool) Get() HostPoolResponse {
  103. host := p.getEpsilonGreedy()
  104. started := time.Now()
  105. return &epsilonHostPoolResponse{
  106. standardHostPoolResponse: standardHostPoolResponse{host: host, pool: p},
  107. started: started,
  108. }
  109. }
  110. func (p *standardHostPool) getRoundRobin() string {
  111. return <-p.rrResults
  112. }
  113. func (p *standardHostPool) serveRoundRobin() {
  114. nextHostIndex := 0
  115. getHostToServe := func() string {
  116. hostCount := len(p.hosts)
  117. for i := range p.hostList() {
  118. // iterate via sequenece from where we last iterated
  119. currentIndex := (i + nextHostIndex) % hostCount
  120. h := p.hostList()[currentIndex]
  121. if h.canTryHost(time.Now()) {
  122. if h.IsDead() {
  123. h.willRetryHost()
  124. }
  125. nextHostIndex = currentIndex + 1
  126. return h.Host()
  127. }
  128. }
  129. // all hosts are down. re-add them
  130. p.ResetAll()
  131. nextHostIndex = 0
  132. return p.hostList()[0].Host()
  133. }
  134. for {
  135. select {
  136. case p.rrResults <- getHostToServe():
  137. case <-p.closeChan:
  138. p.wg.Done()
  139. return
  140. }
  141. }
  142. }
  143. func (p *standardHostPool) ResetAll() {
  144. // SetDead is threadsafe
  145. for _, h := range p.hosts {
  146. h.SetDead(false)
  147. }
  148. }
  149. func (p *standardHostPool) markSuccess(hostR HostPoolResponse) {
  150. host := hostR.Host()
  151. h, ok := p.hosts[host]
  152. if !ok {
  153. log.Fatalf("host %s not in HostPool %v", host, p.Hosts())
  154. }
  155. h.SetDead(false)
  156. }
  157. func (p *standardHostPool) markFailed(hostR HostPoolResponse) {
  158. host := hostR.Host()
  159. h, ok := p.hosts[host]
  160. if !ok {
  161. log.Fatalf("host %s not in HostPool %v", host, p.Hosts())
  162. }
  163. h.SetDead(true)
  164. }
  165. func (p *standardHostPool) Hosts() []string {
  166. hosts := make([]string, 0, len(p.hosts))
  167. for host, _ := range p.hosts {
  168. hosts = append(hosts, host)
  169. }
  170. return hosts
  171. }
  172. func (p *standardHostPool) lookupHost(hostname string) HostEntry {
  173. // We can do a "simple" lookup here because this map doesn't change once init'd
  174. h, ok := p.hosts[hostname]
  175. if !ok {
  176. log.Fatalf("host %s not in HostPool %v", hostname, p.Hosts())
  177. }
  178. return h
  179. }
  180. func (p *standardHostPool) hostList() []HostEntry {
  181. // This returns a sorted list of HostEntry's. We ought
  182. // to do some optimization so that this isn't computed every time
  183. keys := make([]string, 0, len(p.hosts))
  184. vals := make([]HostEntry, 0, len(p.hosts))
  185. for hostName := range p.hosts {
  186. keys = append(keys, hostName)
  187. }
  188. sort.Strings(keys)
  189. for _, k := range keys {
  190. vals = append(vals, p.hosts[k])
  191. }
  192. return vals
  193. }
  194. func (p *standardHostPool) Close() {
  195. p.closeChan <- struct{}{}
  196. for _, he := range p.hosts {
  197. he.Close()
  198. }
  199. p.wg.Wait()
  200. }
  201. // -------- Epsilon Value Calculators ----------
  202. func (c *LinearEpsilonValueCalculator) CalcValueFromAvgResponseTime(v float64) float64 {
  203. return 1.0 / v
  204. }
  205. func (c *LogEpsilonValueCalculator) CalcValueFromAvgResponseTime(v float64) float64 {
  206. return math.Log(c.LinearEpsilonValueCalculator.CalcValueFromAvgResponseTime(v))
  207. }
  208. func (c *PolynomialEpsilonValueCalculator) CalcValueFromAvgResponseTime(v float64) float64 {
  209. return math.Pow(c.LinearEpsilonValueCalculator.CalcValueFromAvgResponseTime(v), c.exp)
  210. }