controller.go 10 KB

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