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.

manager.go 9.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  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. "sort"
  10. "sync"
  11. "time"
  12. "code.gitea.io/gitea/modules/log"
  13. jsoniter "github.com/json-iterator/go"
  14. )
  15. var manager *Manager
  16. // Manager is a queue manager
  17. type Manager struct {
  18. mutex sync.Mutex
  19. counter int64
  20. Queues map[int64]*ManagedQueue
  21. }
  22. // ManagedQueue represents a working queue with a Pool of workers.
  23. //
  24. // Although a ManagedQueue should really represent a Queue this does not
  25. // necessarily have to be the case. This could be used to describe any queue.WorkerPool.
  26. type ManagedQueue struct {
  27. mutex sync.Mutex
  28. QID int64
  29. Type Type
  30. Name string
  31. Configuration interface{}
  32. ExemplarType string
  33. Managed interface{}
  34. counter int64
  35. PoolWorkers map[int64]*PoolWorkers
  36. }
  37. // Flushable represents a pool or queue that is flushable
  38. type Flushable interface {
  39. // Flush will add a flush worker to the pool - the worker should be autoregistered with the manager
  40. Flush(time.Duration) error
  41. // FlushWithContext is very similar to Flush
  42. // NB: The worker will not be registered with the manager.
  43. FlushWithContext(ctx context.Context) error
  44. // IsEmpty will return if the managed pool is empty and has no work
  45. IsEmpty() bool
  46. }
  47. // ManagedPool is a simple interface to get certain details from a worker pool
  48. type ManagedPool interface {
  49. // AddWorkers adds a number of worker as group to the pool with the provided timeout. A CancelFunc is provided to cancel the group
  50. AddWorkers(number int, timeout time.Duration) context.CancelFunc
  51. // NumberOfWorkers returns the total number of workers in the pool
  52. NumberOfWorkers() int
  53. // MaxNumberOfWorkers returns the maximum number of workers the pool can dynamically grow to
  54. MaxNumberOfWorkers() int
  55. // SetMaxNumberOfWorkers sets the maximum number of workers the pool can dynamically grow to
  56. SetMaxNumberOfWorkers(int)
  57. // BoostTimeout returns the current timeout for worker groups created during a boost
  58. BoostTimeout() time.Duration
  59. // BlockTimeout returns the timeout the internal channel can block for before a boost would occur
  60. BlockTimeout() time.Duration
  61. // BoostWorkers sets the number of workers to be created during a boost
  62. BoostWorkers() int
  63. // SetPoolSettings sets the user updatable settings for the pool
  64. SetPoolSettings(maxNumberOfWorkers, boostWorkers int, timeout time.Duration)
  65. }
  66. // ManagedQueueList implements the sort.Interface
  67. type ManagedQueueList []*ManagedQueue
  68. // PoolWorkers represents a group of workers working on a queue
  69. type PoolWorkers struct {
  70. PID int64
  71. Workers int
  72. Start time.Time
  73. Timeout time.Time
  74. HasTimeout bool
  75. Cancel context.CancelFunc
  76. IsFlusher bool
  77. }
  78. // PoolWorkersList implements the sort.Interface for PoolWorkers
  79. type PoolWorkersList []*PoolWorkers
  80. func init() {
  81. _ = GetManager()
  82. }
  83. // GetManager returns a Manager and initializes one as singleton if there's none yet
  84. func GetManager() *Manager {
  85. if manager == nil {
  86. manager = &Manager{
  87. Queues: make(map[int64]*ManagedQueue),
  88. }
  89. }
  90. return manager
  91. }
  92. // Add adds a queue to this manager
  93. func (m *Manager) Add(managed interface{},
  94. t Type,
  95. configuration,
  96. exemplar interface{}) int64 {
  97. json := jsoniter.ConfigCompatibleWithStandardLibrary
  98. cfg, _ := json.Marshal(configuration)
  99. mq := &ManagedQueue{
  100. Type: t,
  101. Configuration: string(cfg),
  102. ExemplarType: reflect.TypeOf(exemplar).String(),
  103. PoolWorkers: make(map[int64]*PoolWorkers),
  104. Managed: managed,
  105. }
  106. m.mutex.Lock()
  107. m.counter++
  108. mq.QID = m.counter
  109. mq.Name = fmt.Sprintf("queue-%d", mq.QID)
  110. if named, ok := managed.(Named); ok {
  111. name := named.Name()
  112. if len(name) > 0 {
  113. mq.Name = name
  114. }
  115. }
  116. m.Queues[mq.QID] = mq
  117. m.mutex.Unlock()
  118. log.Trace("Queue Manager registered: %s (QID: %d)", mq.Name, mq.QID)
  119. return mq.QID
  120. }
  121. // Remove a queue from the Manager
  122. func (m *Manager) Remove(qid int64) {
  123. m.mutex.Lock()
  124. delete(m.Queues, qid)
  125. m.mutex.Unlock()
  126. log.Trace("Queue Manager removed: QID: %d", qid)
  127. }
  128. // GetManagedQueue by qid
  129. func (m *Manager) GetManagedQueue(qid int64) *ManagedQueue {
  130. m.mutex.Lock()
  131. defer m.mutex.Unlock()
  132. return m.Queues[qid]
  133. }
  134. // FlushAll flushes all the flushable queues attached to this manager
  135. func (m *Manager) FlushAll(baseCtx context.Context, timeout time.Duration) error {
  136. var ctx context.Context
  137. var cancel context.CancelFunc
  138. start := time.Now()
  139. end := start
  140. hasTimeout := false
  141. if timeout > 0 {
  142. ctx, cancel = context.WithTimeout(baseCtx, timeout)
  143. end = start.Add(timeout)
  144. hasTimeout = true
  145. } else {
  146. ctx, cancel = context.WithCancel(baseCtx)
  147. }
  148. defer cancel()
  149. for {
  150. select {
  151. case <-ctx.Done():
  152. return ctx.Err()
  153. default:
  154. }
  155. mqs := m.ManagedQueues()
  156. log.Debug("Found %d Managed Queues", len(mqs))
  157. wg := sync.WaitGroup{}
  158. wg.Add(len(mqs))
  159. allEmpty := true
  160. for _, mq := range mqs {
  161. if mq.IsEmpty() {
  162. wg.Done()
  163. continue
  164. }
  165. allEmpty = false
  166. if flushable, ok := mq.Managed.(Flushable); ok {
  167. log.Debug("Flushing (flushable) queue: %s", mq.Name)
  168. go func(q *ManagedQueue) {
  169. localCtx, localCancel := context.WithCancel(ctx)
  170. pid := q.RegisterWorkers(1, start, hasTimeout, end, localCancel, true)
  171. err := flushable.FlushWithContext(localCtx)
  172. if err != nil && err != ctx.Err() {
  173. cancel()
  174. }
  175. q.CancelWorkers(pid)
  176. localCancel()
  177. wg.Done()
  178. }(mq)
  179. } else {
  180. log.Debug("Queue: %s is non-empty but is not flushable - adding 100 millisecond wait", mq.Name)
  181. go func() {
  182. <-time.After(100 * time.Millisecond)
  183. wg.Done()
  184. }()
  185. }
  186. }
  187. if allEmpty {
  188. break
  189. }
  190. wg.Wait()
  191. }
  192. return nil
  193. }
  194. // ManagedQueues returns the managed queues
  195. func (m *Manager) ManagedQueues() []*ManagedQueue {
  196. m.mutex.Lock()
  197. mqs := make([]*ManagedQueue, 0, len(m.Queues))
  198. for _, mq := range m.Queues {
  199. mqs = append(mqs, mq)
  200. }
  201. m.mutex.Unlock()
  202. sort.Sort(ManagedQueueList(mqs))
  203. return mqs
  204. }
  205. // Workers returns the poolworkers
  206. func (q *ManagedQueue) Workers() []*PoolWorkers {
  207. q.mutex.Lock()
  208. workers := make([]*PoolWorkers, 0, len(q.PoolWorkers))
  209. for _, worker := range q.PoolWorkers {
  210. workers = append(workers, worker)
  211. }
  212. q.mutex.Unlock()
  213. sort.Sort(PoolWorkersList(workers))
  214. return workers
  215. }
  216. // RegisterWorkers registers workers to this queue
  217. func (q *ManagedQueue) RegisterWorkers(number int, start time.Time, hasTimeout bool, timeout time.Time, cancel context.CancelFunc, isFlusher bool) int64 {
  218. q.mutex.Lock()
  219. defer q.mutex.Unlock()
  220. q.counter++
  221. q.PoolWorkers[q.counter] = &PoolWorkers{
  222. PID: q.counter,
  223. Workers: number,
  224. Start: start,
  225. Timeout: timeout,
  226. HasTimeout: hasTimeout,
  227. Cancel: cancel,
  228. IsFlusher: isFlusher,
  229. }
  230. return q.counter
  231. }
  232. // CancelWorkers cancels pooled workers with pid
  233. func (q *ManagedQueue) CancelWorkers(pid int64) {
  234. q.mutex.Lock()
  235. pw, ok := q.PoolWorkers[pid]
  236. q.mutex.Unlock()
  237. if !ok {
  238. return
  239. }
  240. pw.Cancel()
  241. }
  242. // RemoveWorkers deletes pooled workers with pid
  243. func (q *ManagedQueue) RemoveWorkers(pid int64) {
  244. q.mutex.Lock()
  245. pw, ok := q.PoolWorkers[pid]
  246. delete(q.PoolWorkers, pid)
  247. q.mutex.Unlock()
  248. if ok && pw.Cancel != nil {
  249. pw.Cancel()
  250. }
  251. }
  252. // AddWorkers adds workers to the queue if it has registered an add worker function
  253. func (q *ManagedQueue) AddWorkers(number int, timeout time.Duration) context.CancelFunc {
  254. if pool, ok := q.Managed.(ManagedPool); ok {
  255. // the cancel will be added to the pool workers description above
  256. return pool.AddWorkers(number, timeout)
  257. }
  258. return nil
  259. }
  260. // Flush flushes the queue with a timeout
  261. func (q *ManagedQueue) Flush(timeout time.Duration) error {
  262. if flushable, ok := q.Managed.(Flushable); ok {
  263. // the cancel will be added to the pool workers description above
  264. return flushable.Flush(timeout)
  265. }
  266. return nil
  267. }
  268. // IsEmpty returns if the queue is empty
  269. func (q *ManagedQueue) IsEmpty() bool {
  270. if flushable, ok := q.Managed.(Flushable); ok {
  271. return flushable.IsEmpty()
  272. }
  273. return true
  274. }
  275. // NumberOfWorkers returns the number of workers in the queue
  276. func (q *ManagedQueue) NumberOfWorkers() int {
  277. if pool, ok := q.Managed.(ManagedPool); ok {
  278. return pool.NumberOfWorkers()
  279. }
  280. return -1
  281. }
  282. // MaxNumberOfWorkers returns the maximum number of workers for the pool
  283. func (q *ManagedQueue) MaxNumberOfWorkers() int {
  284. if pool, ok := q.Managed.(ManagedPool); ok {
  285. return pool.MaxNumberOfWorkers()
  286. }
  287. return 0
  288. }
  289. // BoostWorkers returns the number of workers for a boost
  290. func (q *ManagedQueue) BoostWorkers() int {
  291. if pool, ok := q.Managed.(ManagedPool); ok {
  292. return pool.BoostWorkers()
  293. }
  294. return -1
  295. }
  296. // BoostTimeout returns the timeout of the next boost
  297. func (q *ManagedQueue) BoostTimeout() time.Duration {
  298. if pool, ok := q.Managed.(ManagedPool); ok {
  299. return pool.BoostTimeout()
  300. }
  301. return 0
  302. }
  303. // BlockTimeout returns the timeout til the next boost
  304. func (q *ManagedQueue) BlockTimeout() time.Duration {
  305. if pool, ok := q.Managed.(ManagedPool); ok {
  306. return pool.BlockTimeout()
  307. }
  308. return 0
  309. }
  310. // SetPoolSettings sets the setable boost values
  311. func (q *ManagedQueue) SetPoolSettings(maxNumberOfWorkers, boostWorkers int, timeout time.Duration) {
  312. if pool, ok := q.Managed.(ManagedPool); ok {
  313. pool.SetPoolSettings(maxNumberOfWorkers, boostWorkers, timeout)
  314. }
  315. }
  316. func (l ManagedQueueList) Len() int {
  317. return len(l)
  318. }
  319. func (l ManagedQueueList) Less(i, j int) bool {
  320. return l[i].Name < l[j].Name
  321. }
  322. func (l ManagedQueueList) Swap(i, j int) {
  323. l[i], l[j] = l[j], l[i]
  324. }
  325. func (l PoolWorkersList) Len() int {
  326. return len(l)
  327. }
  328. func (l PoolWorkersList) Less(i, j int) bool {
  329. return l[i].Start.Before(l[j].Start)
  330. }
  331. func (l PoolWorkersList) Swap(i, j int) {
  332. l[i], l[j] = l[j], l[i]
  333. }