hostpool.go 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  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. // Version 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. // Close the hostpool and release all resources.
  41. Close()
  42. }
  43. type standardHostPool struct {
  44. sync.RWMutex
  45. hosts map[string]*hostEntry
  46. hostList []*hostEntry
  47. initialRetryDelay time.Duration
  48. maxRetryInterval time.Duration
  49. nextHostIndex int
  50. }
  51. // ------ constants -------------------
  52. const epsilonBuckets = 120
  53. const epsilonDecay = 0.90 // decay the exploration rate
  54. const minEpsilon = 0.01 // explore one percent of the time
  55. const initialEpsilon = 0.3
  56. const defaultDecayDuration = time.Duration(5) * time.Minute
  57. // Construct a basic HostPool using the hostnames provided
  58. func New(hosts []string) HostPool {
  59. p := &standardHostPool{
  60. hosts: make(map[string]*hostEntry, len(hosts)),
  61. hostList: make([]*hostEntry, len(hosts)),
  62. initialRetryDelay: time.Duration(30) * time.Second,
  63. maxRetryInterval: time.Duration(900) * time.Second,
  64. }
  65. for i, h := range hosts {
  66. e := &hostEntry{
  67. host: h,
  68. retryDelay: p.initialRetryDelay,
  69. }
  70. p.hosts[h] = e
  71. p.hostList[i] = e
  72. }
  73. return p
  74. }
  75. func (r *standardHostPoolResponse) Host() string {
  76. return r.host
  77. }
  78. func (r *standardHostPoolResponse) hostPool() HostPool {
  79. return r.pool
  80. }
  81. func (r *standardHostPoolResponse) Mark(err error) {
  82. r.Do(func() {
  83. doMark(err, r)
  84. })
  85. }
  86. func doMark(err error, r HostPoolResponse) {
  87. if err == nil {
  88. r.hostPool().markSuccess(r)
  89. } else {
  90. r.hostPool().markFailed(r)
  91. }
  92. }
  93. // Get returns an entry from the HostPool
  94. func (p *standardHostPool) Get() HostPoolResponse {
  95. p.Lock()
  96. defer p.Unlock()
  97. host := p.getRoundRobin()
  98. return &standardHostPoolResponse{host: host, pool: p}
  99. }
  100. func (p *standardHostPool) getRoundRobin() string {
  101. now := time.Now()
  102. hostCount := len(p.hostList)
  103. for i := range p.hostList {
  104. // iterate via sequenece from where we last iterated
  105. currentIndex := (i + p.nextHostIndex) % hostCount
  106. h := p.hostList[currentIndex]
  107. if !h.dead {
  108. p.nextHostIndex = currentIndex + 1
  109. return h.host
  110. }
  111. if h.nextRetry.Before(now) {
  112. h.willRetryHost(p.maxRetryInterval)
  113. p.nextHostIndex = currentIndex + 1
  114. return h.host
  115. }
  116. }
  117. // all hosts are down. re-add them
  118. p.doResetAll()
  119. p.nextHostIndex = 0
  120. return p.hostList[0].host
  121. }
  122. func (p *standardHostPool) ResetAll() {
  123. p.Lock()
  124. defer p.Unlock()
  125. p.doResetAll()
  126. }
  127. // this actually performs the logic to reset,
  128. // and should only be called when the lock has
  129. // already been acquired
  130. func (p *standardHostPool) doResetAll() {
  131. for _, h := range p.hosts {
  132. h.dead = false
  133. }
  134. }
  135. func (p *standardHostPool) Close() {
  136. for _, h := range p.hosts {
  137. h.dead = true
  138. }
  139. }
  140. func (p *standardHostPool) markSuccess(hostR HostPoolResponse) {
  141. host := hostR.Host()
  142. p.Lock()
  143. defer p.Unlock()
  144. h, ok := p.hosts[host]
  145. if !ok {
  146. log.Fatalf("host %s not in HostPool %v", host, p.Hosts())
  147. }
  148. h.dead = false
  149. }
  150. func (p *standardHostPool) markFailed(hostR HostPoolResponse) {
  151. host := hostR.Host()
  152. p.Lock()
  153. defer p.Unlock()
  154. h, ok := p.hosts[host]
  155. if !ok {
  156. log.Fatalf("host %s not in HostPool %v", host, p.Hosts())
  157. }
  158. if !h.dead {
  159. h.dead = true
  160. h.retryCount = 0
  161. h.retryDelay = p.initialRetryDelay
  162. h.nextRetry = time.Now().Add(h.retryDelay)
  163. }
  164. }
  165. func (p *standardHostPool) Hosts() []string {
  166. hosts := make([]string, 0, len(p.hosts))
  167. for host := range p.hosts {
  168. hosts = append(hosts, host)
  169. }
  170. return hosts
  171. }