hostpool.go 4.4 KB

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