controller.go 9.1 KB

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