hostpool.go 5.2 KB

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