controller.go 10 KB

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