You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

queue_wrapped.go 7.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. // Copyright 2019 The Gitea Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package queue
  5. import (
  6. "context"
  7. "fmt"
  8. "sync"
  9. "sync/atomic"
  10. "time"
  11. "code.gitea.io/gitea/modules/log"
  12. "code.gitea.io/gitea/modules/util"
  13. )
  14. // WrappedQueueType is the type for a wrapped delayed starting queue
  15. const WrappedQueueType Type = "wrapped"
  16. // WrappedQueueConfiguration is the configuration for a WrappedQueue
  17. type WrappedQueueConfiguration struct {
  18. Underlying Type
  19. Timeout time.Duration
  20. MaxAttempts int
  21. Config interface{}
  22. QueueLength int
  23. Name string
  24. }
  25. type delayedStarter struct {
  26. internal Queue
  27. underlying Type
  28. cfg interface{}
  29. timeout time.Duration
  30. maxAttempts int
  31. name string
  32. }
  33. // setInternal must be called with the lock locked.
  34. func (q *delayedStarter) setInternal(atShutdown func(func()), handle HandlerFunc, exemplar interface{}) error {
  35. var ctx context.Context
  36. var cancel context.CancelFunc
  37. if q.timeout > 0 {
  38. ctx, cancel = context.WithTimeout(context.Background(), q.timeout)
  39. } else {
  40. ctx, cancel = context.WithCancel(context.Background())
  41. }
  42. defer cancel()
  43. // Ensure we also stop at shutdown
  44. atShutdown(cancel)
  45. i := 1
  46. for q.internal == nil {
  47. select {
  48. case <-ctx.Done():
  49. var cfg = q.cfg
  50. if s, ok := cfg.([]byte); ok {
  51. cfg = string(s)
  52. }
  53. return fmt.Errorf("Timedout creating queue %v with cfg %#v in %s", q.underlying, cfg, q.name)
  54. default:
  55. queue, err := NewQueue(q.underlying, handle, q.cfg, exemplar)
  56. if err == nil {
  57. q.internal = queue
  58. break
  59. }
  60. if err.Error() != "resource temporarily unavailable" {
  61. if bs, ok := q.cfg.([]byte); ok {
  62. log.Warn("[Attempt: %d] Failed to create queue: %v for %s cfg: %s error: %v", i, q.underlying, q.name, string(bs), err)
  63. } else {
  64. log.Warn("[Attempt: %d] Failed to create queue: %v for %s cfg: %#v error: %v", i, q.underlying, q.name, q.cfg, err)
  65. }
  66. }
  67. i++
  68. if q.maxAttempts > 0 && i > q.maxAttempts {
  69. if bs, ok := q.cfg.([]byte); ok {
  70. return fmt.Errorf("Unable to create queue %v for %s with cfg %s by max attempts: error: %v", q.underlying, q.name, string(bs), err)
  71. }
  72. return fmt.Errorf("Unable to create queue %v for %s with cfg %#v by max attempts: error: %v", q.underlying, q.name, q.cfg, err)
  73. }
  74. sleepTime := 100 * time.Millisecond
  75. if q.timeout > 0 && q.maxAttempts > 0 {
  76. sleepTime = (q.timeout - 200*time.Millisecond) / time.Duration(q.maxAttempts)
  77. }
  78. t := time.NewTimer(sleepTime)
  79. select {
  80. case <-ctx.Done():
  81. util.StopTimer(t)
  82. case <-t.C:
  83. }
  84. }
  85. }
  86. return nil
  87. }
  88. // WrappedQueue wraps a delayed starting queue
  89. type WrappedQueue struct {
  90. delayedStarter
  91. lock sync.Mutex
  92. handle HandlerFunc
  93. exemplar interface{}
  94. channel chan Data
  95. numInQueue int64
  96. }
  97. // NewWrappedQueue will attempt to create a queue of the provided type,
  98. // but if there is a problem creating this queue it will instead create
  99. // a WrappedQueue with delayed startup of the queue instead and a
  100. // channel which will be redirected to the queue
  101. func NewWrappedQueue(handle HandlerFunc, cfg, exemplar interface{}) (Queue, error) {
  102. configInterface, err := toConfig(WrappedQueueConfiguration{}, cfg)
  103. if err != nil {
  104. return nil, err
  105. }
  106. config := configInterface.(WrappedQueueConfiguration)
  107. queue, err := NewQueue(config.Underlying, handle, config.Config, exemplar)
  108. if err == nil {
  109. // Just return the queue there is no need to wrap
  110. return queue, nil
  111. }
  112. if IsErrInvalidConfiguration(err) {
  113. // Retrying ain't gonna make this any better...
  114. return nil, ErrInvalidConfiguration{cfg: cfg}
  115. }
  116. queue = &WrappedQueue{
  117. handle: handle,
  118. channel: make(chan Data, config.QueueLength),
  119. exemplar: exemplar,
  120. delayedStarter: delayedStarter{
  121. cfg: config.Config,
  122. underlying: config.Underlying,
  123. timeout: config.Timeout,
  124. maxAttempts: config.MaxAttempts,
  125. name: config.Name,
  126. },
  127. }
  128. _ = GetManager().Add(queue, WrappedQueueType, config, exemplar)
  129. return queue, nil
  130. }
  131. // Name returns the name of the queue
  132. func (q *WrappedQueue) Name() string {
  133. return q.name + "-wrapper"
  134. }
  135. // Push will push the data to the internal channel checking it against the exemplar
  136. func (q *WrappedQueue) Push(data Data) error {
  137. if !assignableTo(data, q.exemplar) {
  138. return fmt.Errorf("unable to assign data: %v to same type as exemplar: %v in %s", data, q.exemplar, q.name)
  139. }
  140. atomic.AddInt64(&q.numInQueue, 1)
  141. q.channel <- data
  142. return nil
  143. }
  144. func (q *WrappedQueue) flushInternalWithContext(ctx context.Context) error {
  145. q.lock.Lock()
  146. if q.internal == nil {
  147. q.lock.Unlock()
  148. return fmt.Errorf("not ready to flush wrapped queue %s yet", q.Name())
  149. }
  150. q.lock.Unlock()
  151. select {
  152. case <-ctx.Done():
  153. return ctx.Err()
  154. default:
  155. }
  156. return q.internal.FlushWithContext(ctx)
  157. }
  158. // Flush flushes the queue and blocks till the queue is empty
  159. func (q *WrappedQueue) Flush(timeout time.Duration) error {
  160. var ctx context.Context
  161. var cancel context.CancelFunc
  162. if timeout > 0 {
  163. ctx, cancel = context.WithTimeout(context.Background(), timeout)
  164. } else {
  165. ctx, cancel = context.WithCancel(context.Background())
  166. }
  167. defer cancel()
  168. return q.FlushWithContext(ctx)
  169. }
  170. // FlushWithContext implements the final part of Flushable
  171. func (q *WrappedQueue) FlushWithContext(ctx context.Context) error {
  172. log.Trace("WrappedQueue: %s FlushWithContext", q.Name())
  173. errChan := make(chan error, 1)
  174. go func() {
  175. errChan <- q.flushInternalWithContext(ctx)
  176. close(errChan)
  177. }()
  178. select {
  179. case err := <-errChan:
  180. return err
  181. case <-ctx.Done():
  182. go func() {
  183. <-errChan
  184. }()
  185. return ctx.Err()
  186. }
  187. }
  188. // IsEmpty checks whether the queue is empty
  189. func (q *WrappedQueue) IsEmpty() bool {
  190. if atomic.LoadInt64(&q.numInQueue) != 0 {
  191. return false
  192. }
  193. q.lock.Lock()
  194. defer q.lock.Unlock()
  195. if q.internal == nil {
  196. return false
  197. }
  198. return q.internal.IsEmpty()
  199. }
  200. // Run starts to run the queue and attempts to create the internal queue
  201. func (q *WrappedQueue) Run(atShutdown, atTerminate func(func())) {
  202. log.Debug("WrappedQueue: %s Starting", q.name)
  203. q.lock.Lock()
  204. if q.internal == nil {
  205. err := q.setInternal(atShutdown, q.handle, q.exemplar)
  206. q.lock.Unlock()
  207. if err != nil {
  208. log.Fatal("Unable to set the internal queue for %s Error: %v", q.Name(), err)
  209. return
  210. }
  211. go func() {
  212. for data := range q.channel {
  213. _ = q.internal.Push(data)
  214. atomic.AddInt64(&q.numInQueue, -1)
  215. }
  216. }()
  217. } else {
  218. q.lock.Unlock()
  219. }
  220. q.internal.Run(atShutdown, atTerminate)
  221. log.Trace("WrappedQueue: %s Done", q.name)
  222. }
  223. // Shutdown this queue and stop processing
  224. func (q *WrappedQueue) Shutdown() {
  225. log.Trace("WrappedQueue: %s Shutting down", q.name)
  226. q.lock.Lock()
  227. defer q.lock.Unlock()
  228. if q.internal == nil {
  229. return
  230. }
  231. if shutdownable, ok := q.internal.(Shutdownable); ok {
  232. shutdownable.Shutdown()
  233. }
  234. log.Debug("WrappedQueue: %s Shutdown", q.name)
  235. }
  236. // Terminate this queue and close the queue
  237. func (q *WrappedQueue) Terminate() {
  238. log.Trace("WrappedQueue: %s Terminating", q.name)
  239. q.lock.Lock()
  240. defer q.lock.Unlock()
  241. if q.internal == nil {
  242. return
  243. }
  244. if shutdownable, ok := q.internal.(Shutdownable); ok {
  245. shutdownable.Terminate()
  246. }
  247. log.Debug("WrappedQueue: %s Terminated", q.name)
  248. }
  249. func init() {
  250. queuesMap[WrappedQueueType] = NewWrappedQueue
  251. }