controller.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  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/libnetwork"
  9. "github.com/docker/swarmkit/agent/exec"
  10. "github.com/docker/swarmkit/api"
  11. "github.com/docker/swarmkit/log"
  12. "github.com/pkg/errors"
  13. "golang.org/x/net/context"
  14. )
  15. // controller implements agent.Controller against docker's API.
  16. //
  17. // Most operations against docker's API are done through the container name,
  18. // which is unique to the task.
  19. type controller struct {
  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 docker exec 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. 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); err != nil {
  75. return err
  76. }
  77. if os.Getenv("DOCKER_SERVICE_PREFER_OFFLINE_IMAGE") != "1" {
  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. }
  111. if err := r.adapter.create(ctx); err != nil {
  112. if isContainerCreateNameConflict(err) {
  113. if _, err := r.adapter.inspect(ctx); err != nil {
  114. return err
  115. }
  116. // container is already created. success!
  117. return exec.ErrTaskPrepared
  118. }
  119. return err
  120. }
  121. return nil
  122. }
  123. // Start the container. An error will be returned if the container is already started.
  124. func (r *controller) Start(ctx context.Context) error {
  125. if err := r.checkClosed(); err != nil {
  126. return err
  127. }
  128. ctnr, err := r.adapter.inspect(ctx)
  129. if err != nil {
  130. return err
  131. }
  132. // Detect whether the container has *ever* been started. If so, we don't
  133. // issue the start.
  134. //
  135. // TODO(stevvooe): This is very racy. While reading inspect, another could
  136. // start the process and we could end up starting it twice.
  137. if ctnr.State.Status != "created" {
  138. return exec.ErrTaskStarted
  139. }
  140. for {
  141. if err := r.adapter.start(ctx); err != nil {
  142. if _, ok := err.(libnetwork.ErrNoSuchNetwork); ok {
  143. // Retry network creation again if we
  144. // failed because some of the networks
  145. // were not found.
  146. if err := r.adapter.createNetworks(ctx); err != nil {
  147. return err
  148. }
  149. continue
  150. }
  151. return errors.Wrap(err, "starting container failed")
  152. }
  153. break
  154. }
  155. // no health check
  156. if ctnr.Config == nil || ctnr.Config.Healthcheck == nil {
  157. return nil
  158. }
  159. healthCmd := ctnr.Config.Healthcheck.Test
  160. if len(healthCmd) == 0 || healthCmd[0] == "NONE" {
  161. return nil
  162. }
  163. // wait for container to be healthy
  164. eventq := r.adapter.events(ctx)
  165. var healthErr error
  166. for {
  167. select {
  168. case event := <-eventq:
  169. if !r.matchevent(event) {
  170. continue
  171. }
  172. switch event.Action {
  173. case "die": // exit on terminal events
  174. ctnr, err := r.adapter.inspect(ctx)
  175. if err != nil {
  176. return errors.Wrap(err, "die event received")
  177. } else if ctnr.State.ExitCode != 0 {
  178. return &exitError{code: ctnr.State.ExitCode, cause: healthErr}
  179. }
  180. return nil
  181. case "destroy":
  182. // If we get here, something has gone wrong but we want to exit
  183. // and report anyways.
  184. return ErrContainerDestroyed
  185. case "health_status: unhealthy":
  186. // in this case, we stop the container and report unhealthy status
  187. if err := r.Shutdown(ctx); err != nil {
  188. return errors.Wrap(err, "unhealthy container shutdown failed")
  189. }
  190. // set health check error, and wait for container to fully exit ("die" event)
  191. healthErr = ErrContainerUnhealthy
  192. case "health_status: healthy":
  193. return nil
  194. }
  195. case <-ctx.Done():
  196. return ctx.Err()
  197. case <-r.closed:
  198. return r.err
  199. }
  200. }
  201. }
  202. // Wait on the container to exit.
  203. func (r *controller) Wait(pctx context.Context) error {
  204. if err := r.checkClosed(); err != nil {
  205. return err
  206. }
  207. ctx, cancel := context.WithCancel(pctx)
  208. defer cancel()
  209. healthErr := make(chan error, 1)
  210. go func() {
  211. ectx, cancel := context.WithCancel(ctx) // cancel event context on first event
  212. defer cancel()
  213. if err := r.checkHealth(ectx); err == ErrContainerUnhealthy {
  214. healthErr <- ErrContainerUnhealthy
  215. if err := r.Shutdown(ectx); err != nil {
  216. log.G(ectx).WithError(err).Debug("shutdown failed on unhealthy")
  217. }
  218. }
  219. }()
  220. err := r.adapter.wait(ctx)
  221. if ctx.Err() != nil {
  222. return ctx.Err()
  223. }
  224. if err != nil {
  225. ee := &exitError{}
  226. if ec, ok := err.(exec.ExitCoder); ok {
  227. ee.code = ec.ExitCode()
  228. }
  229. select {
  230. case e := <-healthErr:
  231. ee.cause = e
  232. default:
  233. if err.Error() != "" {
  234. ee.cause = err
  235. }
  236. }
  237. return ee
  238. }
  239. return nil
  240. }
  241. // Shutdown the container cleanly.
  242. func (r *controller) Shutdown(ctx context.Context) error {
  243. if err := r.checkClosed(); err != nil {
  244. return err
  245. }
  246. if r.cancelPull != nil {
  247. r.cancelPull()
  248. }
  249. if err := r.adapter.shutdown(ctx); err != nil {
  250. if isUnknownContainer(err) || isStoppedContainer(err) {
  251. return nil
  252. }
  253. return err
  254. }
  255. return nil
  256. }
  257. // Terminate the container, with force.
  258. func (r *controller) Terminate(ctx context.Context) error {
  259. if err := r.checkClosed(); err != nil {
  260. return err
  261. }
  262. if r.cancelPull != nil {
  263. r.cancelPull()
  264. }
  265. if err := r.adapter.terminate(ctx); err != nil {
  266. if isUnknownContainer(err) {
  267. return nil
  268. }
  269. return err
  270. }
  271. return nil
  272. }
  273. // Remove the container and its resources.
  274. func (r *controller) Remove(ctx context.Context) error {
  275. if err := r.checkClosed(); err != nil {
  276. return err
  277. }
  278. if r.cancelPull != nil {
  279. r.cancelPull()
  280. }
  281. // It may be necessary to shut down the task before removing it.
  282. if err := r.Shutdown(ctx); err != nil {
  283. if isUnknownContainer(err) {
  284. return nil
  285. }
  286. // This may fail if the task was already shut down.
  287. log.G(ctx).WithError(err).Debug("shutdown failed on removal")
  288. }
  289. // Try removing networks referenced in this task in case this
  290. // task is the last one referencing it
  291. if err := r.adapter.removeNetworks(ctx); err != nil {
  292. if isUnknownContainer(err) {
  293. return nil
  294. }
  295. return err
  296. }
  297. if err := r.adapter.remove(ctx); err != nil {
  298. if isUnknownContainer(err) {
  299. return nil
  300. }
  301. return err
  302. }
  303. return nil
  304. }
  305. // Close the runner and clean up any ephemeral resources.
  306. func (r *controller) Close() error {
  307. select {
  308. case <-r.closed:
  309. return r.err
  310. default:
  311. if r.cancelPull != nil {
  312. r.cancelPull()
  313. }
  314. r.err = exec.ErrControllerClosed
  315. close(r.closed)
  316. }
  317. return nil
  318. }
  319. func (r *controller) matchevent(event events.Message) bool {
  320. if event.Type != events.ContainerEventType {
  321. return false
  322. }
  323. // TODO(stevvooe): Filter based on ID matching, in addition to name.
  324. // Make sure the events are for this container.
  325. if event.Actor.Attributes["name"] != r.adapter.container.name() {
  326. return false
  327. }
  328. return true
  329. }
  330. func (r *controller) checkClosed() error {
  331. select {
  332. case <-r.closed:
  333. return r.err
  334. default:
  335. return nil
  336. }
  337. }
  338. func parseContainerStatus(ctnr types.ContainerJSON) (*api.ContainerStatus, error) {
  339. status := &api.ContainerStatus{
  340. ContainerID: ctnr.ID,
  341. PID: int32(ctnr.State.Pid),
  342. ExitCode: int32(ctnr.State.ExitCode),
  343. }
  344. return status, nil
  345. }
  346. type exitError struct {
  347. code int
  348. cause error
  349. }
  350. func (e *exitError) Error() string {
  351. if e.cause != nil {
  352. return fmt.Sprintf("task: non-zero exit (%v): %v", e.code, e.cause)
  353. }
  354. return fmt.Sprintf("task: non-zero exit (%v)", e.code)
  355. }
  356. func (e *exitError) ExitCode() int {
  357. return int(e.code)
  358. }
  359. func (e *exitError) Cause() error {
  360. return e.cause
  361. }
  362. // checkHealth blocks until unhealthy container is detected or ctx exits
  363. func (r *controller) checkHealth(ctx context.Context) error {
  364. eventq := r.adapter.events(ctx)
  365. for {
  366. select {
  367. case <-ctx.Done():
  368. return nil
  369. case <-r.closed:
  370. return nil
  371. case event := <-eventq:
  372. if !r.matchevent(event) {
  373. continue
  374. }
  375. switch event.Action {
  376. case "health_status: unhealthy":
  377. return ErrContainerUnhealthy
  378. }
  379. }
  380. }
  381. }