hostpool.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. // A Go package to intelligently and flexibly pool among multiple hosts from your Go application.
  2. // Host selection can operate in round robin or epsilon greedy mode, and unresponsive hosts are
  3. // avoided. A good overview of Epsilon Greedy is here http://stevehanov.ca/blog/index.php?id=132
  4. package hostpool
  5. import (
  6. "log"
  7. "sync"
  8. "time"
  9. )
  10. // Returns current version
  11. func Version() string {
  12. return "0.1"
  13. }
  14. // --- Response interfaces and structs ----
  15. // This interface represents the response from HostPool. You can retrieve the
  16. // hostname by calling Host(), and after making a request to the host you should
  17. // call Mark with any error encountered, which will inform the HostPool issuing
  18. // the HostPoolResponse of what happened to the request and allow it to update.
  19. type HostPoolResponse interface {
  20. Host() string
  21. Mark(error)
  22. hostPool() HostPool
  23. }
  24. type standardHostPoolResponse struct {
  25. host string
  26. sync.Once
  27. pool HostPool
  28. }
  29. // --- HostPool structs and interfaces ----
  30. // This is the main HostPool interface. Structs implementing this interface
  31. // allow you to Get a HostPoolResponse (which includes a hostname to use),
  32. // get the list of all Hosts, and use ResetAll to reset state.
  33. type HostPool interface {
  34. Get() HostPoolResponse
  35. // keep the marks separate so we can override independently
  36. markSuccess(HostPoolResponse)
  37. markFailed(HostPoolResponse)
  38. ResetAll()
  39. Hosts() []string
  40. }
  41. type standardHostPool struct {
  42. sync.RWMutex
  43. hosts map[string]*hostEntry
  44. hostList []*hostEntry
  45. initialRetryDelay time.Duration
  46. maxRetryInterval time.Duration
  47. nextHostIndex int
  48. }
  49. // ------ constants -------------------
  50. const epsilonBuckets = 120
  51. const epsilonDecay = 0.90 // decay the exploration rate
  52. const minEpsilon = 0.01 // explore one percent of the time
  53. const initialEpsilon = 0.3
  54. const defaultDecayDuration = time.Duration(5) * time.Minute
  55. // Construct a basic HostPool using the hostnames provided
  56. func New(hosts []string) HostPool {
  57. p := &standardHostPool{
  58. hosts: make(map[string]*hostEntry, len(hosts)),
  59. hostList: make([]*hostEntry, len(hosts)),
  60. initialRetryDelay: time.Duration(30) * time.Second,
  61. maxRetryInterval: time.Duration(900) * time.Second,
  62. }
  63. for i, h := range hosts {
  64. e := &hostEntry{
  65. host: h,
  66. retryDelay: p.initialRetryDelay,
  67. }
  68. p.hosts[h] = e
  69. p.hostList[i] = e
  70. }
  71. return p
  72. }
  73. func (r *standardHostPoolResponse) Host() string {
  74. return r.host
  75. }
  76. func (r *standardHostPoolResponse) hostPool() HostPool {
  77. return r.pool
  78. }
  79. func (r *standardHostPoolResponse) Mark(err error) {
  80. r.Do(func() {
  81. doMark(err, r)
  82. })
  83. }
  84. func doMark(err error, r HostPoolResponse) {
  85. if err == nil {
  86. r.hostPool().markSuccess(r)
  87. } else {
  88. r.hostPool().markFailed(r)
  89. }
  90. }
  91. // return an entry from the HostPool
  92. func (p *standardHostPool) Get() HostPoolResponse {
  93. p.Lock()
  94. defer p.Unlock()
  95. host := p.getRoundRobin()
  96. return &standardHostPoolResponse{host: host, pool: p}
  97. }
  98. func (p *standardHostPool) getRoundRobin() string {
  99. now := time.Now()
  100. hostCount := len(p.hostList)
  101. for i := range p.hostList {
  102. // iterate via sequenece from where we last iterated
  103. currentIndex := (i + p.nextHostIndex) % hostCount
  104. h := p.hostList[currentIndex]
  105. if !h.dead {
  106. p.nextHostIndex = currentIndex + 1
  107. return h.host
  108. }
  109. if h.nextRetry.Before(now) {
  110. h.willRetryHost(p.maxRetryInterval)
  111. p.nextHostIndex = currentIndex + 1
  112. return h.host
  113. }
  114. }
  115. // all hosts are down. re-add them
  116. p.doResetAll()
  117. p.nextHostIndex = 0
  118. return p.hostList[0].host
  119. }
  120. func (p *standardHostPool) ResetAll() {
  121. p.Lock()
  122. defer p.Unlock()
  123. p.doResetAll()
  124. }
  125. // this actually performs the logic to reset,
  126. // and should only be called when the lock has
  127. // already been acquired
  128. func (p *standardHostPool) doResetAll() {
  129. for _, h := range p.hosts {
  130. h.dead = false
  131. }
  132. }
  133. func (p *standardHostPool) markSuccess(hostR HostPoolResponse) {
  134. host := hostR.Host()
  135. p.Lock()
  136. defer p.Unlock()
  137. h, ok := p.hosts[host]
  138. if !ok {
  139. log.Fatalf("host %s not in HostPool %v", host, p.Hosts())
  140. }
  141. h.dead = false
  142. }
  143. func (p *standardHostPool) markFailed(hostR HostPoolResponse) {
  144. host := hostR.Host()
  145. p.Lock()
  146. defer p.Unlock()
  147. h, ok := p.hosts[host]
  148. if !ok {
  149. log.Fatalf("host %s not in HostPool %v", host, p.Hosts())
  150. }
  151. if !h.dead {
  152. h.dead = true
  153. h.retryCount = 0
  154. h.retryDelay = p.initialRetryDelay
  155. h.nextRetry = time.Now().Add(h.retryDelay)
  156. }
  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. }