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
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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  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. internal Queue
  26. underlying Type
  27. cfg interface{}
  28. timeout time.Duration
  29. maxAttempts int
  30. name string
  31. }
  32. // setInternal must be called with the lock locked.
  33. func (q *delayedStarter) setInternal(atShutdown func(context.Context, func()), handle HandlerFunc, exemplar interface{}) error {
  34. var ctx context.Context
  35. var cancel context.CancelFunc
  36. if q.timeout > 0 {
  37. ctx, cancel = context.WithTimeout(context.Background(), q.timeout)
  38. } else {
  39. ctx, cancel = context.WithCancel(context.Background())
  40. }
  41. defer cancel()
  42. // Ensure we also stop at shutdown
  43. atShutdown(ctx, func() {
  44. cancel()
  45. })
  46. i := 1
  47. for q.internal == nil {
  48. select {
  49. case <-ctx.Done():
  50. return fmt.Errorf("Timedout creating queue %v with cfg %v in %s", q.underlying, q.cfg, q.name)
  51. default:
  52. queue, err := NewQueue(q.underlying, handle, q.cfg, exemplar)
  53. if err == nil {
  54. q.internal = queue
  55. break
  56. }
  57. if err.Error() != "resource temporarily unavailable" {
  58. log.Warn("[Attempt: %d] Failed to create queue: %v for %s cfg: %v error: %v", i, q.underlying, q.name, q.cfg, err)
  59. }
  60. i++
  61. if q.maxAttempts > 0 && i > q.maxAttempts {
  62. 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)
  63. }
  64. sleepTime := 100 * time.Millisecond
  65. if q.timeout > 0 && q.maxAttempts > 0 {
  66. sleepTime = (q.timeout - 200*time.Millisecond) / time.Duration(q.maxAttempts)
  67. }
  68. t := time.NewTimer(sleepTime)
  69. select {
  70. case <-ctx.Done():
  71. t.Stop()
  72. case <-t.C:
  73. }
  74. }
  75. }
  76. return nil
  77. }
  78. // WrappedQueue wraps a delayed starting queue
  79. type WrappedQueue struct {
  80. delayedStarter
  81. lock sync.Mutex
  82. handle HandlerFunc
  83. exemplar interface{}
  84. channel chan Data
  85. }
  86. // NewWrappedQueue will attempt to create a queue of the provided type,
  87. // but if there is a problem creating this queue it will instead create
  88. // a WrappedQueue with delayed startup of the queue instead and a
  89. // channel which will be redirected to the queue
  90. func NewWrappedQueue(handle HandlerFunc, cfg, exemplar interface{}) (Queue, error) {
  91. configInterface, err := toConfig(WrappedQueueConfiguration{}, cfg)
  92. if err != nil {
  93. return nil, err
  94. }
  95. config := configInterface.(WrappedQueueConfiguration)
  96. queue, err := NewQueue(config.Underlying, handle, config.Config, exemplar)
  97. if err == nil {
  98. // Just return the queue there is no need to wrap
  99. return queue, nil
  100. }
  101. if IsErrInvalidConfiguration(err) {
  102. // Retrying ain't gonna make this any better...
  103. return nil, ErrInvalidConfiguration{cfg: cfg}
  104. }
  105. queue = &WrappedQueue{
  106. handle: handle,
  107. channel: make(chan Data, config.QueueLength),
  108. exemplar: exemplar,
  109. delayedStarter: delayedStarter{
  110. cfg: config.Config,
  111. underlying: config.Underlying,
  112. timeout: config.Timeout,
  113. maxAttempts: config.MaxAttempts,
  114. name: config.Name,
  115. },
  116. }
  117. _ = GetManager().Add(queue, WrappedQueueType, config, exemplar, nil)
  118. return queue, nil
  119. }
  120. // Name returns the name of the queue
  121. func (q *WrappedQueue) Name() string {
  122. return q.name + "-wrapper"
  123. }
  124. // Push will push the data to the internal channel checking it against the exemplar
  125. func (q *WrappedQueue) Push(data Data) error {
  126. if q.exemplar != nil {
  127. // Assert data is of same type as r.exemplar
  128. value := reflect.ValueOf(data)
  129. t := value.Type()
  130. exemplarType := reflect.ValueOf(q.exemplar).Type()
  131. if !t.AssignableTo(exemplarType) || data == nil {
  132. return fmt.Errorf("Unable to assign data: %v to same type as exemplar: %v in %s", data, q.exemplar, q.name)
  133. }
  134. }
  135. q.channel <- data
  136. return nil
  137. }
  138. // Run starts to run the queue and attempts to create the internal queue
  139. func (q *WrappedQueue) Run(atShutdown, atTerminate func(context.Context, func())) {
  140. q.lock.Lock()
  141. if q.internal == nil {
  142. err := q.setInternal(atShutdown, q.handle, q.exemplar)
  143. q.lock.Unlock()
  144. if err != nil {
  145. log.Fatal("Unable to set the internal queue for %s Error: %v", q.Name(), err)
  146. return
  147. }
  148. go func() {
  149. for data := range q.channel {
  150. _ = q.internal.Push(data)
  151. }
  152. }()
  153. } else {
  154. q.lock.Unlock()
  155. }
  156. q.internal.Run(atShutdown, atTerminate)
  157. log.Trace("WrappedQueue: %s Done", q.name)
  158. }
  159. // Shutdown this queue and stop processing
  160. func (q *WrappedQueue) Shutdown() {
  161. log.Trace("WrappedQueue: %s Shutdown", q.name)
  162. q.lock.Lock()
  163. defer q.lock.Unlock()
  164. if q.internal == nil {
  165. return
  166. }
  167. if shutdownable, ok := q.internal.(Shutdownable); ok {
  168. shutdownable.Shutdown()
  169. }
  170. }
  171. // Terminate this queue and close the queue
  172. func (q *WrappedQueue) Terminate() {
  173. log.Trace("WrappedQueue: %s Terminating", q.name)
  174. q.lock.Lock()
  175. defer q.lock.Unlock()
  176. if q.internal == nil {
  177. return
  178. }
  179. if shutdownable, ok := q.internal.(Shutdownable); ok {
  180. shutdownable.Terminate()
  181. }
  182. }
  183. func init() {
  184. queuesMap[WrappedQueueType] = NewWrappedQueue
  185. }