controller.go 10 KB

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