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.3KB

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