epsilon_greedy.go 5.5 KB

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