task.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. package agent
  2. import (
  3. "sync"
  4. "time"
  5. "github.com/docker/swarmkit/agent/exec"
  6. "github.com/docker/swarmkit/api"
  7. "github.com/docker/swarmkit/api/equality"
  8. "github.com/docker/swarmkit/log"
  9. "golang.org/x/net/context"
  10. )
  11. // taskManager manages all aspects of task execution and reporting for an agent
  12. // through state management.
  13. type taskManager struct {
  14. task *api.Task
  15. ctlr exec.Controller
  16. reporter StatusReporter
  17. updateq chan *api.Task
  18. shutdown chan struct{}
  19. shutdownOnce sync.Once
  20. closed chan struct{}
  21. closeOnce sync.Once
  22. }
  23. func newTaskManager(ctx context.Context, task *api.Task, ctlr exec.Controller, reporter StatusReporter) *taskManager {
  24. t := &taskManager{
  25. task: task.Copy(),
  26. ctlr: ctlr,
  27. reporter: reporter,
  28. updateq: make(chan *api.Task),
  29. shutdown: make(chan struct{}),
  30. closed: make(chan struct{}),
  31. }
  32. go t.run(ctx)
  33. return t
  34. }
  35. // Update the task data.
  36. func (tm *taskManager) Update(ctx context.Context, task *api.Task) error {
  37. select {
  38. case tm.updateq <- task:
  39. return nil
  40. case <-tm.closed:
  41. return ErrClosed
  42. case <-ctx.Done():
  43. return ctx.Err()
  44. }
  45. }
  46. // Close shuts down the task manager, blocking until it is closed.
  47. func (tm *taskManager) Close() error {
  48. tm.shutdownOnce.Do(func() {
  49. close(tm.shutdown)
  50. })
  51. <-tm.closed
  52. return nil
  53. }
  54. func (tm *taskManager) Logs(ctx context.Context, options api.LogSubscriptionOptions, publisher exec.LogPublisher) {
  55. ctx = log.WithModule(ctx, "taskmanager")
  56. logCtlr, ok := tm.ctlr.(exec.ControllerLogs)
  57. if !ok {
  58. return // no logs available
  59. }
  60. if err := logCtlr.Logs(ctx, publisher, options); err != nil {
  61. log.G(ctx).WithError(err).Errorf("logs call failed")
  62. }
  63. }
  64. func (tm *taskManager) run(ctx context.Context) {
  65. ctx, cancelAll := context.WithCancel(ctx)
  66. defer cancelAll() // cancel all child operations on exit.
  67. ctx = log.WithModule(ctx, "taskmanager")
  68. var (
  69. opctx context.Context
  70. cancel context.CancelFunc
  71. run = make(chan struct{}, 1)
  72. statusq = make(chan *api.TaskStatus)
  73. errs = make(chan error)
  74. shutdown = tm.shutdown
  75. updated bool // true if the task was updated.
  76. )
  77. defer func() {
  78. // closure picks up current value of cancel.
  79. if cancel != nil {
  80. cancel()
  81. }
  82. }()
  83. run <- struct{}{} // prime the pump
  84. for {
  85. select {
  86. case <-run:
  87. // always check for shutdown before running.
  88. select {
  89. case <-tm.shutdown:
  90. shutdown = tm.shutdown // a little questionable
  91. continue // ignore run request and handle shutdown
  92. case <-tm.closed:
  93. continue
  94. default:
  95. }
  96. opctx, cancel = context.WithCancel(ctx)
  97. // Several variables need to be snapshotted for the closure below.
  98. opcancel := cancel // fork for the closure
  99. running := tm.task.Copy() // clone the task before dispatch
  100. statusqLocal := statusq
  101. updatedLocal := updated // capture state of update for goroutine
  102. updated = false
  103. go runctx(ctx, tm.closed, errs, func(ctx context.Context) error {
  104. defer opcancel()
  105. if updatedLocal {
  106. // before we do anything, update the task for the controller.
  107. // always update the controller before running.
  108. if err := tm.ctlr.Update(opctx, running); err != nil {
  109. log.G(ctx).WithError(err).Error("updating task controller failed")
  110. return err
  111. }
  112. }
  113. status, err := exec.Do(opctx, running, tm.ctlr)
  114. if status != nil {
  115. // always report the status if we get one back. This
  116. // returns to the manager loop, then reports the status
  117. // upstream.
  118. select {
  119. case statusqLocal <- status:
  120. case <-ctx.Done(): // not opctx, since that may have been cancelled.
  121. }
  122. if err := tm.reporter.UpdateTaskStatus(ctx, running.ID, status); err != nil {
  123. log.G(ctx).WithError(err).Error("task manager failed to report status to agent")
  124. }
  125. }
  126. return err
  127. })
  128. case err := <-errs:
  129. // This branch is always executed when an operations completes. The
  130. // goal is to decide whether or not we re-dispatch the operation.
  131. cancel = nil
  132. select {
  133. case <-tm.shutdown:
  134. shutdown = tm.shutdown // re-enable the shutdown branch
  135. continue // no dispatch if we are in shutdown.
  136. default:
  137. }
  138. switch err {
  139. case exec.ErrTaskNoop:
  140. if !updated {
  141. continue // wait till getting pumped via update.
  142. }
  143. case exec.ErrTaskRetry:
  144. // TODO(stevvooe): Add exponential backoff with random jitter
  145. // here. For now, this backoff is enough to keep the task
  146. // manager from running away with the CPU.
  147. time.AfterFunc(time.Second, func() {
  148. errs <- nil // repump this branch, with no err
  149. })
  150. continue
  151. case nil, context.Canceled, context.DeadlineExceeded:
  152. // no log in this case
  153. default:
  154. log.G(ctx).WithError(err).Error("task operation failed")
  155. }
  156. select {
  157. case run <- struct{}{}:
  158. default:
  159. }
  160. case status := <-statusq:
  161. tm.task.Status = *status
  162. case task := <-tm.updateq:
  163. if equality.TasksEqualStable(task, tm.task) {
  164. continue // ignore the update
  165. }
  166. if task.ID != tm.task.ID {
  167. log.G(ctx).WithField("task.update.id", task.ID).Error("received update for incorrect task")
  168. continue
  169. }
  170. if task.DesiredState < tm.task.DesiredState {
  171. log.G(ctx).WithField("task.update.desiredstate", task.DesiredState).
  172. Error("ignoring task update with invalid desired state")
  173. continue
  174. }
  175. task = task.Copy()
  176. task.Status = tm.task.Status // overwrite our status, as it is canonical.
  177. tm.task = task
  178. updated = true
  179. // we have accepted the task update
  180. if cancel != nil {
  181. cancel() // cancel outstanding if necessary.
  182. } else {
  183. // If this channel op fails, it means there is already a
  184. // message on the run queue.
  185. select {
  186. case run <- struct{}{}:
  187. default:
  188. }
  189. }
  190. case <-shutdown:
  191. if cancel != nil {
  192. // cancel outstanding operation.
  193. cancel()
  194. // subtle: after a cancellation, we want to avoid busy wait
  195. // here. this gets renabled in the errs branch and we'll come
  196. // back around and try shutdown again.
  197. shutdown = nil // turn off this branch until op proceeds
  198. continue // wait until operation actually exits.
  199. }
  200. // disable everything, and prepare for closing.
  201. statusq = nil
  202. errs = nil
  203. shutdown = nil
  204. tm.closeOnce.Do(func() {
  205. close(tm.closed)
  206. })
  207. case <-tm.closed:
  208. return
  209. case <-ctx.Done():
  210. tm.closeOnce.Do(func() {
  211. close(tm.closed)
  212. })
  213. return
  214. }
  215. }
  216. }