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

queue_wrapped.go 5.5 kB

Graceful Queues: Issue Indexing and Tasks (#9363) * Queue: Add generic graceful queues with settings * Queue & Setting: Add worker pool implementation * Queue: Add worker settings * Queue: Make resizing worker pools * Queue: Add name variable to queues * Queue: Add monitoring * Queue: Improve logging * Issues: Gracefulise the issues indexer Remove the old now unused specific queues * Task: Move to generic queue and gracefulise * Issues: Standardise the issues indexer queue settings * Fix test * Queue: Allow Redis to connect to unix * Prevent deadlock during early shutdown of issue indexer * Add MaxWorker settings to queues * Merge branch 'master' into graceful-queues * Update modules/indexer/issues/indexer.go Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * Update modules/indexer/issues/indexer.go Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * Update modules/queue/queue_channel.go Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * Update modules/queue/queue_disk.go * Update modules/queue/queue_disk_channel.go Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * Rename queue.Description to queue.ManagedQueue as per @guillep2k * Cancel pool workers when removed * Remove dependency on queue from setting * Update modules/queue/queue_redis.go Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * As per @guillep2k add mutex locks on shutdown/terminate * move unlocking out of setInternal * Add warning if number of workers < 0 * Small changes as per @guillep2k * No redis host specified not found * Clean up documentation for queues * Update docs/content/doc/advanced/config-cheat-sheet.en-us.md * Update modules/indexer/issues/indexer_test.go * Ensure that persistable channel queue is added to manager * Rename QUEUE_NAME REDIS_QUEUE_NAME * Revert "Rename QUEUE_NAME REDIS_QUEUE_NAME" This reverts commit 1f83b4fc9b9dabda186257b38c265fe7012f90df. Co-authored-by: guillep2k <18600385+guillep2k@users.noreply.github.com> Co-authored-by: Lauris BH <lauris@nix.lv> Co-authored-by: techknowlogick <matti@mdranta.net> Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  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. "reflect"
  9. "sync"
  10. "time"
  11. "code.gitea.io/gitea/modules/log"
  12. )
  13. // WrappedQueueType is the type for a wrapped delayed starting queue
  14. const WrappedQueueType Type = "wrapped"
  15. // WrappedQueueConfiguration is the configuration for a WrappedQueue
  16. type WrappedQueueConfiguration struct {
  17. Underlying Type
  18. Timeout time.Duration
  19. MaxAttempts int
  20. Config interface{}
  21. QueueLength int
  22. Name string
  23. }
  24. type delayedStarter struct {
  25. lock sync.Mutex
  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. return fmt.Errorf("Timedout creating queue %v with cfg %v in %s", q.underlying, q.cfg, q.name)
  52. default:
  53. queue, err := NewQueue(q.underlying, handle, q.cfg, exemplar)
  54. if err == nil {
  55. q.internal = queue
  56. q.lock.Unlock()
  57. break
  58. }
  59. if err.Error() != "resource temporarily unavailable" {
  60. log.Warn("[Attempt: %d] Failed to create queue: %v for %s cfg: %v error: %v", i, q.underlying, q.name, q.cfg, err)
  61. }
  62. i++
  63. if q.maxAttempts > 0 && i > q.maxAttempts {
  64. 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)
  65. }
  66. sleepTime := 100 * time.Millisecond
  67. if q.timeout > 0 && q.maxAttempts > 0 {
  68. sleepTime = (q.timeout - 200*time.Millisecond) / time.Duration(q.maxAttempts)
  69. }
  70. t := time.NewTimer(sleepTime)
  71. select {
  72. case <-ctx.Done():
  73. t.Stop()
  74. case <-t.C:
  75. }
  76. }
  77. }
  78. return nil
  79. }
  80. // WrappedQueue wraps a delayed starting queue
  81. type WrappedQueue struct {
  82. delayedStarter
  83. handle HandlerFunc
  84. exemplar interface{}
  85. channel chan Data
  86. }
  87. // NewWrappedQueue will attempt to create a queue of the provided type,
  88. // but if there is a problem creating this queue it will instead create
  89. // a WrappedQueue with delayed startup of the queue instead and a
  90. // channel which will be redirected to the queue
  91. func NewWrappedQueue(handle HandlerFunc, cfg, exemplar interface{}) (Queue, error) {
  92. configInterface, err := toConfig(WrappedQueueConfiguration{}, cfg)
  93. if err != nil {
  94. return nil, err
  95. }
  96. config := configInterface.(WrappedQueueConfiguration)
  97. queue, err := NewQueue(config.Underlying, handle, config.Config, exemplar)
  98. if err == nil {
  99. // Just return the queue there is no need to wrap
  100. return queue, nil
  101. }
  102. if IsErrInvalidConfiguration(err) {
  103. // Retrying ain't gonna make this any better...
  104. return nil, ErrInvalidConfiguration{cfg: cfg}
  105. }
  106. queue = &WrappedQueue{
  107. handle: handle,
  108. channel: make(chan Data, config.QueueLength),
  109. exemplar: exemplar,
  110. delayedStarter: delayedStarter{
  111. cfg: config.Config,
  112. underlying: config.Underlying,
  113. timeout: config.Timeout,
  114. maxAttempts: config.MaxAttempts,
  115. name: config.Name,
  116. },
  117. }
  118. _ = GetManager().Add(queue, WrappedQueueType, config, exemplar, nil)
  119. return queue, nil
  120. }
  121. // Name returns the name of the queue
  122. func (q *WrappedQueue) Name() string {
  123. return q.name + "-wrapper"
  124. }
  125. // Push will push the data to the internal channel checking it against the exemplar
  126. func (q *WrappedQueue) Push(data Data) error {
  127. if q.exemplar != nil {
  128. // Assert data is of same type as r.exemplar
  129. value := reflect.ValueOf(data)
  130. t := value.Type()
  131. exemplarType := reflect.ValueOf(q.exemplar).Type()
  132. if !t.AssignableTo(exemplarType) || data == nil {
  133. return fmt.Errorf("Unable to assign data: %v to same type as exemplar: %v in %s", data, q.exemplar, q.name)
  134. }
  135. }
  136. q.channel <- data
  137. return nil
  138. }
  139. // Run starts to run the queue and attempts to create the internal queue
  140. func (q *WrappedQueue) Run(atShutdown, atTerminate func(context.Context, func())) {
  141. q.lock.Lock()
  142. if q.internal == nil {
  143. err := q.setInternal(atShutdown, q.handle, q.exemplar)
  144. q.lock.Unlock()
  145. if err != nil {
  146. log.Fatal("Unable to set the internal queue for %s Error: %v", q.Name(), err)
  147. return
  148. }
  149. go func() {
  150. for data := range q.channel {
  151. _ = q.internal.Push(data)
  152. }
  153. }()
  154. } else {
  155. q.lock.Unlock()
  156. }
  157. q.internal.Run(atShutdown, atTerminate)
  158. log.Trace("WrappedQueue: %s Done", q.name)
  159. }
  160. // Shutdown this queue and stop processing
  161. func (q *WrappedQueue) Shutdown() {
  162. log.Trace("WrappedQueue: %s Shutdown", q.name)
  163. q.lock.Lock()
  164. defer q.lock.Unlock()
  165. if q.internal == nil {
  166. return
  167. }
  168. if shutdownable, ok := q.internal.(Shutdownable); ok {
  169. shutdownable.Shutdown()
  170. }
  171. }
  172. // Terminate this queue and close the queue
  173. func (q *WrappedQueue) Terminate() {
  174. log.Trace("WrappedQueue: %s Terminating", q.name)
  175. q.lock.Lock()
  176. defer q.lock.Unlock()
  177. if q.internal == nil {
  178. return
  179. }
  180. if shutdownable, ok := q.internal.(Shutdownable); ok {
  181. shutdownable.Terminate()
  182. }
  183. }
  184. func init() {
  185. queuesMap[WrappedQueueType] = NewWrappedQueue
  186. }