epsilon_greedy.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  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) epsilonGreedyDecay() {
  65. durationPerBucket := p.decayDuration / epsilonBuckets
  66. ticker := time.Tick(durationPerBucket)
  67. for {
  68. <-ticker
  69. p.performEpsilonGreedyDecay()
  70. }
  71. }
  72. func (p *epsilonGreedyHostPool) performEpsilonGreedyDecay() {
  73. p.Lock()
  74. for _, h := range p.hostList {
  75. h.epsilonIndex += 1
  76. h.epsilonIndex = h.epsilonIndex % epsilonBuckets
  77. h.epsilonCounts[h.epsilonIndex] = 0
  78. h.epsilonValues[h.epsilonIndex] = 0
  79. }
  80. p.Unlock()
  81. }
  82. func (p *epsilonGreedyHostPool) Get() HostPoolResponse {
  83. p.Lock()
  84. defer p.Unlock()
  85. host := p.getEpsilonGreedy()
  86. started := time.Now()
  87. return &epsilonHostPoolResponse{
  88. standardHostPoolResponse: standardHostPoolResponse{host: host, pool: p},
  89. started: started,
  90. }
  91. }
  92. func (p *epsilonGreedyHostPool) getEpsilonGreedy() string {
  93. var hostToUse *hostEntry
  94. // this is our exploration phase
  95. if rand.Float32() < p.epsilon {
  96. p.epsilon = p.epsilon * epsilonDecay
  97. if p.epsilon < minEpsilon {
  98. p.epsilon = minEpsilon
  99. }
  100. return p.getRoundRobin()
  101. }
  102. // calculate values for each host in the 0..1 range (but not ormalized)
  103. var possibleHosts []*hostEntry
  104. now := time.Now()
  105. var sumValues float64
  106. for _, h := range p.hostList {
  107. if h.canTryHost(now) {
  108. v := h.getWeightedAverageResponseTime()
  109. if v > 0 {
  110. ev := p.CalcValueFromAvgResponseTime(v)
  111. h.epsilonValue = ev
  112. sumValues += ev
  113. possibleHosts = append(possibleHosts, h)
  114. }
  115. }
  116. }
  117. if len(possibleHosts) != 0 {
  118. // now normalize to the 0..1 range to get a percentage
  119. for _, h := range possibleHosts {
  120. h.epsilonPercentage = h.epsilonValue / sumValues
  121. }
  122. // do a weighted random choice among hosts
  123. ceiling := 0.0
  124. pickPercentage := rand.Float64()
  125. for _, h := range possibleHosts {
  126. ceiling += h.epsilonPercentage
  127. if pickPercentage <= ceiling {
  128. hostToUse = h
  129. break
  130. }
  131. }
  132. }
  133. if hostToUse == nil {
  134. if len(possibleHosts) != 0 {
  135. log.Println("Failed to randomly choose a host, Dan loses")
  136. }
  137. return p.getRoundRobin()
  138. }
  139. if hostToUse.dead {
  140. hostToUse.willRetryHost(p.maxRetryInterval)
  141. }
  142. return hostToUse.host
  143. }
  144. func (p *epsilonGreedyHostPool) markSuccess(hostR HostPoolResponse) {
  145. // first do the base markSuccess - a little redundant with host lookup but cleaner than repeating logic
  146. p.standardHostPool.markSuccess(hostR)
  147. eHostR, ok := hostR.(*epsilonHostPoolResponse)
  148. if !ok {
  149. log.Printf("Incorrect type in eps markSuccess!") // TODO reflection to print out offending type
  150. return
  151. }
  152. host := eHostR.host
  153. duration := p.between(eHostR.started, eHostR.ended)
  154. p.Lock()
  155. defer p.Unlock()
  156. h, ok := p.hosts[host]
  157. if !ok {
  158. log.Fatalf("host %s not in HostPool %v", host, p.Hosts())
  159. }
  160. h.epsilonCounts[h.epsilonIndex]++
  161. h.epsilonValues[h.epsilonIndex] += int64(duration.Seconds() * 1000)
  162. }
  163. // --- timer: this just exists for testing
  164. type timer interface {
  165. between(time.Time, time.Time) time.Duration
  166. }
  167. type realTimer struct{}
  168. func (rt *realTimer) between(start time.Time, end time.Time) time.Duration {
  169. return end.Sub(start)
  170. }