epsilon_greedy.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  1. package hostpool
  2. import (
  3. "log"
  4. "math/rand"
  5. "time"
  6. )
  7. type epsilonHostPoolResponse struct {
  8. standardHostPoolResponse
  9. started time.Time
  10. ended time.Time
  11. }
  12. func (r *epsilonHostPoolResponse) Mark(err error) {
  13. r.Do(func() {
  14. r.ended = time.Now()
  15. doMark(err, r)
  16. })
  17. }
  18. type epsilonGreedyHostPool struct {
  19. standardHostPool // TODO - would be nifty if we could embed HostPool and Locker interfaces
  20. epsilon float32 // this is our exploration factor
  21. decayDuration time.Duration
  22. EpsilonValueCalculator // embed the epsilonValueCalculator
  23. timer
  24. }
  25. // Construct an Epsilon Greedy HostPool
  26. //
  27. // Epsilon Greedy is an algorithm that allows HostPool not only to track failure state,
  28. // but also to learn about "better" options in terms of speed, and to pick from available hosts
  29. // based on how well they perform. This gives a weighted request rate to better
  30. // performing hosts, while still distributing requests to all hosts (proportionate to their performance).
  31. // The interface is the same as the standard HostPool, but be sure to mark the HostResponse immediately
  32. // after executing the request to the host, as that will stop the implicitly running request timer.
  33. //
  34. // A good overview of Epsilon Greedy is here http://stevehanov.ca/blog/index.php?id=132
  35. //
  36. // To compute the weighting scores, we perform a weighted average of recent response times, over the course of
  37. // `decayDuration`. decayDuration may be set to 0 to use the default value of 5 minutes
  38. // We then use the supplied EpsilonValueCalculator to calculate a score from that weighted average response time.
  39. func NewEpsilonGreedy(hosts []string, decayDuration time.Duration, calc EpsilonValueCalculator) HostPool {
  40. if decayDuration <= 0 {
  41. decayDuration = defaultDecayDuration
  42. }
  43. stdHP := New(hosts).(*standardHostPool)
  44. p := &epsilonGreedyHostPool{
  45. standardHostPool: *stdHP,
  46. epsilon: float32(initialEpsilon),
  47. decayDuration: decayDuration,
  48. EpsilonValueCalculator: calc,
  49. timer: &realTimer{},
  50. }
  51. // allocate structures
  52. for _, h := range p.hostList {
  53. h.epsilonCounts = make([]int64, epsilonBuckets)
  54. h.epsilonValues = make([]int64, epsilonBuckets)
  55. }
  56. go p.epsilonGreedyDecay()
  57. return p
  58. }
  59. func (p *epsilonGreedyHostPool) SetEpsilon(newEpsilon float32) {
  60. p.Lock()
  61. defer p.Unlock()
  62. p.epsilon = newEpsilon
  63. }
  64. func (p *epsilonGreedyHostPool) SetHosts(hosts []string) {
  65. p.Lock()
  66. defer p.Unlock()
  67. p.standardHostPool.setHosts(hosts)
  68. for _, h := range p.hostList {
  69. h.epsilonCounts = make([]int64, epsilonBuckets)
  70. h.epsilonValues = make([]int64, epsilonBuckets)
  71. }
  72. }
  73. func (p *epsilonGreedyHostPool) epsilonGreedyDecay() {
  74. durationPerBucket := p.decayDuration / epsilonBuckets
  75. ticker := time.Tick(durationPerBucket)
  76. for {
  77. <-ticker
  78. p.performEpsilonGreedyDecay()
  79. }
  80. }
  81. func (p *epsilonGreedyHostPool) performEpsilonGreedyDecay() {
  82. p.Lock()
  83. for _, h := range p.hostList {
  84. h.epsilonIndex += 1
  85. h.epsilonIndex = h.epsilonIndex % epsilonBuckets
  86. h.epsilonCounts[h.epsilonIndex] = 0
  87. h.epsilonValues[h.epsilonIndex] = 0
  88. }
  89. p.Unlock()
  90. }
  91. func (p *epsilonGreedyHostPool) Get() HostPoolResponse {
  92. p.Lock()
  93. defer p.Unlock()
  94. host := p.getEpsilonGreedy()
  95. started := time.Now()
  96. return &epsilonHostPoolResponse{
  97. standardHostPoolResponse: standardHostPoolResponse{host: host, pool: p},
  98. started: started,
  99. }
  100. }
  101. func (p *epsilonGreedyHostPool) getEpsilonGreedy() string {
  102. var hostToUse *hostEntry
  103. // this is our exploration phase
  104. if rand.Float32() < p.epsilon {
  105. p.epsilon = p.epsilon * epsilonDecay
  106. if p.epsilon < minEpsilon {
  107. p.epsilon = minEpsilon
  108. }
  109. return p.getRoundRobin()
  110. }
  111. // calculate values for each host in the 0..1 range (but not ormalized)
  112. var possibleHosts []*hostEntry
  113. now := time.Now()
  114. var sumValues float64
  115. for _, h := range p.hostList {
  116. if h.canTryHost(now) {
  117. v := h.getWeightedAverageResponseTime()
  118. if v > 0 {
  119. ev := p.CalcValueFromAvgResponseTime(v)
  120. h.epsilonValue = ev
  121. sumValues += ev
  122. possibleHosts = append(possibleHosts, h)
  123. }
  124. }
  125. }
  126. if len(possibleHosts) != 0 {
  127. // now normalize to the 0..1 range to get a percentage
  128. for _, h := range possibleHosts {
  129. h.epsilonPercentage = h.epsilonValue / sumValues
  130. }
  131. // do a weighted random choice among hosts
  132. ceiling := 0.0
  133. pickPercentage := rand.Float64()
  134. for _, h := range possibleHosts {
  135. ceiling += h.epsilonPercentage
  136. if pickPercentage <= ceiling {
  137. hostToUse = h
  138. break
  139. }
  140. }
  141. }
  142. if hostToUse == nil {
  143. if len(possibleHosts) != 0 {
  144. log.Println("Failed to randomly choose a host, Dan loses")
  145. }
  146. return p.getRoundRobin()
  147. }
  148. if hostToUse.dead {
  149. hostToUse.willRetryHost(p.maxRetryInterval)
  150. }
  151. return hostToUse.host
  152. }
  153. func (p *epsilonGreedyHostPool) markSuccess(hostR HostPoolResponse) {
  154. // first do the base markSuccess - a little redundant with host lookup but cleaner than repeating logic
  155. p.standardHostPool.markSuccess(hostR)
  156. eHostR, ok := hostR.(*epsilonHostPoolResponse)
  157. if !ok {
  158. log.Printf("Incorrect type in eps markSuccess!") // TODO reflection to print out offending type
  159. return
  160. }
  161. host := eHostR.host
  162. duration := p.between(eHostR.started, eHostR.ended)
  163. p.Lock()
  164. defer p.Unlock()
  165. h, ok := p.hosts[host]
  166. if !ok {
  167. log.Fatalf("host %s not in HostPool %v", host, p.Hosts())
  168. }
  169. h.epsilonCounts[h.epsilonIndex]++
  170. h.epsilonValues[h.epsilonIndex] += int64(duration.Seconds() * 1000)
  171. }
  172. // --- timer: this just exists for testing
  173. type timer interface {
  174. between(time.Time, time.Time) time.Duration
  175. }
  176. type realTimer struct{}
  177. func (rt *realTimer) between(start time.Time, end time.Time) time.Duration {
  178. return end.Sub(start)
  179. }