controller.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  1. package container
  2. import (
  3. "fmt"
  4. executorpkg "github.com/docker/docker/daemon/cluster/executor"
  5. "github.com/docker/engine-api/types"
  6. "github.com/docker/engine-api/types/events"
  7. "github.com/docker/swarmkit/agent/exec"
  8. "github.com/docker/swarmkit/api"
  9. "github.com/docker/swarmkit/log"
  10. "github.com/pkg/errors"
  11. "golang.org/x/net/context"
  12. )
  13. // controller implements agent.Controller against docker's API.
  14. //
  15. // Most operations against docker's API are done through the container name,
  16. // which is unique to the task.
  17. type controller struct {
  18. backend executorpkg.Backend
  19. task *api.Task
  20. adapter *containerAdapter
  21. closed chan struct{}
  22. err error
  23. }
  24. var _ exec.Controller = &controller{}
  25. // NewController returns a dockerexec runner for the provided task.
  26. func newController(b executorpkg.Backend, task *api.Task) (*controller, error) {
  27. adapter, err := newContainerAdapter(b, task)
  28. if err != nil {
  29. return nil, err
  30. }
  31. return &controller{
  32. backend: b,
  33. task: task,
  34. adapter: adapter,
  35. closed: make(chan struct{}),
  36. }, nil
  37. }
  38. func (r *controller) Task() (*api.Task, error) {
  39. return r.task, nil
  40. }
  41. // ContainerStatus returns the container-specific status for the task.
  42. func (r *controller) ContainerStatus(ctx context.Context) (*api.ContainerStatus, error) {
  43. ctnr, err := r.adapter.inspect(ctx)
  44. if err != nil {
  45. if isUnknownContainer(err) {
  46. return nil, nil
  47. }
  48. return nil, err
  49. }
  50. return parseContainerStatus(ctnr)
  51. }
  52. // Update tasks a recent task update and applies it to the container.
  53. func (r *controller) Update(ctx context.Context, t *api.Task) error {
  54. // TODO(stevvooe): While assignment of tasks is idempotent, we do allow
  55. // updates of metadata, such as labelling, as well as any other properties
  56. // that make sense.
  57. return nil
  58. }
  59. // Prepare creates a container and ensures the image is pulled.
  60. //
  61. // If the container has already be created, exec.ErrTaskPrepared is returned.
  62. func (r *controller) Prepare(ctx context.Context) error {
  63. if err := r.checkClosed(); err != nil {
  64. return err
  65. }
  66. // Make sure all the networks that the task needs are created.
  67. if err := r.adapter.createNetworks(ctx); err != nil {
  68. return err
  69. }
  70. // Make sure all the volumes that the task needs are created.
  71. if err := r.adapter.createVolumes(ctx, r.backend); err != nil {
  72. return err
  73. }
  74. if err := r.adapter.pullImage(ctx); err != nil {
  75. // NOTE(stevvooe): We always try to pull the image to make sure we have
  76. // the most up to date version. This will return an error, but we only
  77. // log it. If the image truly doesn't exist, the create below will
  78. // error out.
  79. //
  80. // This gives us some nice behavior where we use up to date versions of
  81. // mutable tags, but will still run if the old image is available but a
  82. // registry is down.
  83. //
  84. // If you don't want this behavior, lock down your image to an
  85. // immutable tag or digest.
  86. log.G(ctx).WithError(err).Error("pulling image failed")
  87. }
  88. if err := r.adapter.create(ctx, r.backend); err != nil {
  89. if isContainerCreateNameConflict(err) {
  90. if _, err := r.adapter.inspect(ctx); err != nil {
  91. return err
  92. }
  93. // container is already created. success!
  94. return exec.ErrTaskPrepared
  95. }
  96. return err
  97. }
  98. return nil
  99. }
  100. // Start the container. An error will be returned if the container is already started.
  101. func (r *controller) Start(ctx context.Context) error {
  102. if err := r.checkClosed(); err != nil {
  103. return err
  104. }
  105. ctnr, err := r.adapter.inspect(ctx)
  106. if err != nil {
  107. return err
  108. }
  109. // Detect whether the container has *ever* been started. If so, we don't
  110. // issue the start.
  111. //
  112. // TODO(stevvooe): This is very racy. While reading inspect, another could
  113. // start the process and we could end up starting it twice.
  114. if ctnr.State.Status != "created" {
  115. return exec.ErrTaskStarted
  116. }
  117. if err := r.adapter.start(ctx); err != nil {
  118. return errors.Wrap(err, "starting container failed")
  119. }
  120. return nil
  121. }
  122. // Wait on the container to exit.
  123. func (r *controller) Wait(pctx context.Context) error {
  124. if err := r.checkClosed(); err != nil {
  125. return err
  126. }
  127. ctx, cancel := context.WithCancel(pctx)
  128. defer cancel()
  129. healthErr := make(chan error, 1)
  130. go func() {
  131. ectx, cancel := context.WithCancel(ctx) // cancel event context on first event
  132. defer cancel()
  133. if err := r.checkHealth(ectx); err == ErrContainerUnhealthy {
  134. healthErr <- ErrContainerUnhealthy
  135. if err := r.Shutdown(ectx); err != nil {
  136. log.G(ectx).WithError(err).Debug("shutdown failed on unhealthy")
  137. }
  138. }
  139. }()
  140. err := r.adapter.wait(ctx)
  141. if ctx.Err() != nil {
  142. return ctx.Err()
  143. }
  144. if err != nil {
  145. ee := &exitError{}
  146. if ec, ok := err.(exec.ExitCoder); ok {
  147. ee.code = ec.ExitCode()
  148. }
  149. select {
  150. case e := <-healthErr:
  151. ee.cause = e
  152. default:
  153. if err.Error() != "" {
  154. ee.cause = err
  155. }
  156. }
  157. return ee
  158. }
  159. return nil
  160. }
  161. // Shutdown the container cleanly.
  162. func (r *controller) Shutdown(ctx context.Context) error {
  163. if err := r.checkClosed(); err != nil {
  164. return err
  165. }
  166. if err := r.adapter.shutdown(ctx); err != nil {
  167. if isUnknownContainer(err) || isStoppedContainer(err) {
  168. return nil
  169. }
  170. return err
  171. }
  172. return nil
  173. }
  174. // Terminate the container, with force.
  175. func (r *controller) Terminate(ctx context.Context) error {
  176. if err := r.checkClosed(); err != nil {
  177. return err
  178. }
  179. if err := r.adapter.terminate(ctx); err != nil {
  180. if isUnknownContainer(err) {
  181. return nil
  182. }
  183. return err
  184. }
  185. return nil
  186. }
  187. // Remove the container and its resources.
  188. func (r *controller) Remove(ctx context.Context) error {
  189. if err := r.checkClosed(); err != nil {
  190. return err
  191. }
  192. // It may be necessary to shut down the task before removing it.
  193. if err := r.Shutdown(ctx); err != nil {
  194. if isUnknownContainer(err) {
  195. return nil
  196. }
  197. // This may fail if the task was already shut down.
  198. log.G(ctx).WithError(err).Debug("shutdown failed on removal")
  199. }
  200. // Try removing networks referenced in this task in case this
  201. // task is the last one referencing it
  202. if err := r.adapter.removeNetworks(ctx); err != nil {
  203. if isUnknownContainer(err) {
  204. return nil
  205. }
  206. return err
  207. }
  208. if err := r.adapter.remove(ctx); err != nil {
  209. if isUnknownContainer(err) {
  210. return nil
  211. }
  212. return err
  213. }
  214. return nil
  215. }
  216. // Close the runner and clean up any ephemeral resources.
  217. func (r *controller) Close() error {
  218. select {
  219. case <-r.closed:
  220. return r.err
  221. default:
  222. r.err = exec.ErrControllerClosed
  223. close(r.closed)
  224. }
  225. return nil
  226. }
  227. func (r *controller) matchevent(event events.Message) bool {
  228. if event.Type != events.ContainerEventType {
  229. return false
  230. }
  231. // TODO(stevvooe): Filter based on ID matching, in addition to name.
  232. // Make sure the events are for this container.
  233. if event.Actor.Attributes["name"] != r.adapter.container.name() {
  234. return false
  235. }
  236. return true
  237. }
  238. func (r *controller) checkClosed() error {
  239. select {
  240. case <-r.closed:
  241. return r.err
  242. default:
  243. return nil
  244. }
  245. }
  246. func parseContainerStatus(ctnr types.ContainerJSON) (*api.ContainerStatus, error) {
  247. status := &api.ContainerStatus{
  248. ContainerID: ctnr.ID,
  249. PID: int32(ctnr.State.Pid),
  250. ExitCode: int32(ctnr.State.ExitCode),
  251. }
  252. return status, nil
  253. }
  254. type exitError struct {
  255. code int
  256. cause error
  257. }
  258. func (e *exitError) Error() string {
  259. if e.cause != nil {
  260. return fmt.Sprintf("task: non-zero exit (%v): %v", e.code, e.cause)
  261. }
  262. return fmt.Sprintf("task: non-zero exit (%v)", e.code)
  263. }
  264. func (e *exitError) ExitCode() int {
  265. return int(e.code)
  266. }
  267. func (e *exitError) Cause() error {
  268. return e.cause
  269. }
  270. // checkHealth blocks until unhealthy container is detected or ctx exits
  271. func (r *controller) checkHealth(ctx context.Context) error {
  272. eventq := r.adapter.events(ctx)
  273. for {
  274. select {
  275. case <-ctx.Done():
  276. return nil
  277. case <-r.closed:
  278. return nil
  279. case event := <-eventq:
  280. if !r.matchevent(event) {
  281. continue
  282. }
  283. switch event.Action {
  284. case "health_status: unhealthy":
  285. return ErrContainerUnhealthy
  286. }
  287. }
  288. }
  289. }