pool.go 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  1. package guerrilla
  2. import (
  3. "errors"
  4. "github.com/flashmob/go-guerrilla/log"
  5. "github.com/flashmob/go-guerrilla/mail"
  6. "net"
  7. "sync"
  8. "sync/atomic"
  9. "time"
  10. )
  11. var (
  12. ErrPoolShuttingDown = errors.New("server pool: shutting down")
  13. )
  14. // a struct can be pooled if it has the following interface
  15. type Poolable interface {
  16. // ability to set read/write timeout
  17. setTimeout(t time.Duration)
  18. // set a new connection and client id
  19. init(c net.Conn, clientID uint64, ep *mail.Pool)
  20. // get a unique id
  21. getID() uint64
  22. }
  23. // Pool holds Clients.
  24. type Pool struct {
  25. // clients that are ready to be borrowed
  26. pool chan Poolable
  27. // semaphore to control number of maximum borrowed clients
  28. sem chan bool
  29. // book-keeping of clients that have been lent
  30. activeClients lentClients
  31. isShuttingDownFlg atomic.Value
  32. poolGuard sync.Mutex
  33. ShutdownChan chan int
  34. }
  35. type lentClients struct {
  36. m map[uint64]Poolable
  37. mu sync.Mutex // guards access to this struct
  38. wg sync.WaitGroup
  39. }
  40. // maps the callback on all lentClients
  41. func (c *lentClients) mapAll(callback func(p Poolable)) {
  42. defer c.mu.Unlock()
  43. c.mu.Lock()
  44. for _, item := range c.m {
  45. callback(item)
  46. }
  47. }
  48. // operation performs an operation on a Poolable item using the callback
  49. func (c *lentClients) operation(callback func(p Poolable), item Poolable) {
  50. defer c.mu.Unlock()
  51. c.mu.Lock()
  52. callback(item)
  53. }
  54. // NewPool creates a new pool of Clients.
  55. func NewPool(poolSize int) *Pool {
  56. return &Pool{
  57. pool: make(chan Poolable, poolSize),
  58. sem: make(chan bool, poolSize),
  59. activeClients: lentClients{m: make(map[uint64]Poolable, poolSize)},
  60. ShutdownChan: make(chan int, 1),
  61. }
  62. }
  63. func (p *Pool) Start() {
  64. p.isShuttingDownFlg.Store(true)
  65. }
  66. // Lock the pool from borrowing then remove all active clients
  67. // each active client's timeout is lowered to 1 sec and notified
  68. // to stop accepting commands
  69. func (p *Pool) ShutdownState() {
  70. const aVeryLowTimeout = 1
  71. p.poolGuard.Lock() // ensure no other thread is in the borrowing now
  72. defer p.poolGuard.Unlock()
  73. p.isShuttingDownFlg.Store(true) // no more borrowing
  74. p.ShutdownChan <- 1 // release any waiting p.sem
  75. // set a low timeout
  76. p.activeClients.mapAll(func(p Poolable) {
  77. p.setTimeout(time.Duration(int64(aVeryLowTimeout)))
  78. })
  79. }
  80. func (p *Pool) ShutdownWait() {
  81. p.poolGuard.Lock() // ensure no other thread is in the borrowing now
  82. defer p.poolGuard.Unlock()
  83. p.activeClients.wg.Wait() // wait for clients to finish
  84. if len(p.ShutdownChan) > 0 {
  85. // drain
  86. <-p.ShutdownChan
  87. }
  88. p.isShuttingDownFlg.Store(false)
  89. }
  90. // returns true if the pool is shutting down
  91. func (p *Pool) IsShuttingDown() bool {
  92. if value, ok := p.isShuttingDownFlg.Load().(bool); ok {
  93. return value
  94. }
  95. return false
  96. }
  97. // set a timeout for all lent clients
  98. func (p *Pool) SetTimeout(duration time.Duration) {
  99. p.activeClients.mapAll(func(p Poolable) {
  100. p.setTimeout(duration)
  101. })
  102. }
  103. // Gets the number of active clients that are currently
  104. // out of the pool and busy serving
  105. func (p *Pool) GetActiveClientsCount() int {
  106. return len(p.sem)
  107. }
  108. // Borrow a Client from the pool. Will block if len(activeClients) > maxClients
  109. func (p *Pool) Borrow(conn net.Conn, clientID uint64, logger log.Logger, ep *mail.Pool) (Poolable, error) {
  110. p.poolGuard.Lock()
  111. defer p.poolGuard.Unlock()
  112. var c Poolable
  113. if yes, really := p.isShuttingDownFlg.Load().(bool); yes && really {
  114. // pool is shutting down.
  115. return c, ErrPoolShuttingDown
  116. }
  117. select {
  118. case p.sem <- true: // block the client from serving until there is room
  119. select {
  120. case c = <-p.pool:
  121. c.init(conn, clientID, ep)
  122. default:
  123. c = NewClient(conn, clientID, logger, ep)
  124. }
  125. p.activeClientsAdd(c)
  126. case <-p.ShutdownChan: // unblock p.sem when shutting down
  127. // pool is shutting down.
  128. return c, ErrPoolShuttingDown
  129. }
  130. return c, nil
  131. }
  132. // Return returns a Client back to the pool.
  133. func (p *Pool) Return(c Poolable) {
  134. p.activeClientsRemove(c)
  135. select {
  136. case p.pool <- c:
  137. default:
  138. // hasta la vista, baby...
  139. }
  140. <-p.sem // make room for the next serving client
  141. }
  142. func (p *Pool) activeClientsAdd(c Poolable) {
  143. p.activeClients.operation(func(item Poolable) {
  144. p.activeClients.wg.Add(1)
  145. p.activeClients.m[c.getID()] = item
  146. }, c)
  147. }
  148. func (p *Pool) activeClientsRemove(c Poolable) {
  149. p.activeClients.operation(func(item Poolable) {
  150. delete(p.activeClients.m, item.getID())
  151. p.activeClients.wg.Done()
  152. }, c)
  153. }