epsilon_greedy.go 5.1 KB

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