controller.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  1. package container
  2. import (
  3. "fmt"
  4. "os"
  5. "github.com/docker/docker/api/types"
  6. "github.com/docker/docker/api/types/events"
  7. executorpkg "github.com/docker/docker/daemon/cluster/executor"
  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, secrets exec.SecretGetter) (*controller, error) {
  31. adapter, err := newContainerAdapter(b, task, secrets)
  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. if err := r.adapter.activateServiceBinding(); err != nil {
  158. log.G(ctx).WithError(err).Errorf("failed to activate service binding for container %s which has no healthcheck config", r.adapter.container.name())
  159. return err
  160. }
  161. return nil
  162. }
  163. healthCmd := ctnr.Config.Healthcheck.Test
  164. if len(healthCmd) == 0 || healthCmd[0] == "NONE" {
  165. return nil
  166. }
  167. // wait for container to be healthy
  168. eventq := r.adapter.events(ctx)
  169. var healthErr error
  170. for {
  171. select {
  172. case event := <-eventq:
  173. if !r.matchevent(event) {
  174. continue
  175. }
  176. switch event.Action {
  177. case "die": // exit on terminal events
  178. ctnr, err := r.adapter.inspect(ctx)
  179. if err != nil {
  180. return errors.Wrap(err, "die event received")
  181. } else if ctnr.State.ExitCode != 0 {
  182. return &exitError{code: ctnr.State.ExitCode, cause: healthErr}
  183. }
  184. return nil
  185. case "destroy":
  186. // If we get here, something has gone wrong but we want to exit
  187. // and report anyways.
  188. return ErrContainerDestroyed
  189. case "health_status: unhealthy":
  190. // in this case, we stop the container and report unhealthy status
  191. if err := r.Shutdown(ctx); err != nil {
  192. return errors.Wrap(err, "unhealthy container shutdown failed")
  193. }
  194. // set health check error, and wait for container to fully exit ("die" event)
  195. healthErr = ErrContainerUnhealthy
  196. case "health_status: healthy":
  197. if err := r.adapter.activateServiceBinding(); err != nil {
  198. log.G(ctx).WithError(err).Errorf("failed to activate service binding for container %s after healthy event", r.adapter.container.name())
  199. return err
  200. }
  201. return nil
  202. }
  203. case <-ctx.Done():
  204. return ctx.Err()
  205. case <-r.closed:
  206. return r.err
  207. }
  208. }
  209. }
  210. // Wait on the container to exit.
  211. func (r *controller) Wait(pctx context.Context) error {
  212. if err := r.checkClosed(); err != nil {
  213. return err
  214. }
  215. ctx, cancel := context.WithCancel(pctx)
  216. defer cancel()
  217. healthErr := make(chan error, 1)
  218. go func() {
  219. ectx, cancel := context.WithCancel(ctx) // cancel event context on first event
  220. defer cancel()
  221. if err := r.checkHealth(ectx); err == ErrContainerUnhealthy {
  222. healthErr <- ErrContainerUnhealthy
  223. if err := r.Shutdown(ectx); err != nil {
  224. log.G(ectx).WithError(err).Debug("shutdown failed on unhealthy")
  225. }
  226. }
  227. }()
  228. err := r.adapter.wait(ctx)
  229. if ctx.Err() != nil {
  230. return ctx.Err()
  231. }
  232. if err != nil {
  233. ee := &exitError{}
  234. if ec, ok := err.(exec.ExitCoder); ok {
  235. ee.code = ec.ExitCode()
  236. }
  237. select {
  238. case e := <-healthErr:
  239. ee.cause = e
  240. default:
  241. if err.Error() != "" {
  242. ee.cause = err
  243. }
  244. }
  245. return ee
  246. }
  247. return nil
  248. }
  249. // Shutdown the container cleanly.
  250. func (r *controller) Shutdown(ctx context.Context) error {
  251. if err := r.checkClosed(); err != nil {
  252. return err
  253. }
  254. if r.cancelPull != nil {
  255. r.cancelPull()
  256. }
  257. // remove container from service binding
  258. if err := r.adapter.deactivateServiceBinding(); err != nil {
  259. log.G(ctx).WithError(err).Errorf("failed to deactivate service binding for container %s", r.adapter.container.name())
  260. return err
  261. }
  262. if err := r.adapter.shutdown(ctx); err != nil {
  263. if isUnknownContainer(err) || isStoppedContainer(err) {
  264. return nil
  265. }
  266. return err
  267. }
  268. return nil
  269. }
  270. // Terminate the container, with force.
  271. func (r *controller) Terminate(ctx context.Context) error {
  272. if err := r.checkClosed(); err != nil {
  273. return err
  274. }
  275. if r.cancelPull != nil {
  276. r.cancelPull()
  277. }
  278. if err := r.adapter.terminate(ctx); err != nil {
  279. if isUnknownContainer(err) {
  280. return nil
  281. }
  282. return err
  283. }
  284. return nil
  285. }
  286. // Remove the container and its resources.
  287. func (r *controller) Remove(ctx context.Context) error {
  288. if err := r.checkClosed(); err != nil {
  289. return err
  290. }
  291. if r.cancelPull != nil {
  292. r.cancelPull()
  293. }
  294. // It may be necessary to shut down the task before removing it.
  295. if err := r.Shutdown(ctx); err != nil {
  296. if isUnknownContainer(err) {
  297. return nil
  298. }
  299. // This may fail if the task was already shut down.
  300. log.G(ctx).WithError(err).Debug("shutdown failed on removal")
  301. }
  302. // Try removing networks referenced in this task in case this
  303. // task is the last one referencing it
  304. if err := r.adapter.removeNetworks(ctx); err != nil {
  305. if isUnknownContainer(err) {
  306. return nil
  307. }
  308. return err
  309. }
  310. if err := r.adapter.remove(ctx); err != nil {
  311. if isUnknownContainer(err) {
  312. return nil
  313. }
  314. return err
  315. }
  316. return nil
  317. }
  318. // Close the runner and clean up any ephemeral resources.
  319. func (r *controller) Close() error {
  320. select {
  321. case <-r.closed:
  322. return r.err
  323. default:
  324. if r.cancelPull != nil {
  325. r.cancelPull()
  326. }
  327. r.err = exec.ErrControllerClosed
  328. close(r.closed)
  329. }
  330. return nil
  331. }
  332. func (r *controller) matchevent(event events.Message) bool {
  333. if event.Type != events.ContainerEventType {
  334. return false
  335. }
  336. // TODO(stevvooe): Filter based on ID matching, in addition to name.
  337. // Make sure the events are for this container.
  338. if event.Actor.Attributes["name"] != r.adapter.container.name() {
  339. return false
  340. }
  341. return true
  342. }
  343. func (r *controller) checkClosed() error {
  344. select {
  345. case <-r.closed:
  346. return r.err
  347. default:
  348. return nil
  349. }
  350. }
  351. func parseContainerStatus(ctnr types.ContainerJSON) (*api.ContainerStatus, error) {
  352. status := &api.ContainerStatus{
  353. ContainerID: ctnr.ID,
  354. PID: int32(ctnr.State.Pid),
  355. ExitCode: int32(ctnr.State.ExitCode),
  356. }
  357. return status, nil
  358. }
  359. type exitError struct {
  360. code int
  361. cause error
  362. }
  363. func (e *exitError) Error() string {
  364. if e.cause != nil {
  365. return fmt.Sprintf("task: non-zero exit (%v): %v", e.code, e.cause)
  366. }
  367. return fmt.Sprintf("task: non-zero exit (%v)", e.code)
  368. }
  369. func (e *exitError) ExitCode() int {
  370. return int(e.code)
  371. }
  372. func (e *exitError) Cause() error {
  373. return e.cause
  374. }
  375. // checkHealth blocks until unhealthy container is detected or ctx exits
  376. func (r *controller) checkHealth(ctx context.Context) error {
  377. eventq := r.adapter.events(ctx)
  378. for {
  379. select {
  380. case <-ctx.Done():
  381. return nil
  382. case <-r.closed:
  383. return nil
  384. case event := <-eventq:
  385. if !r.matchevent(event) {
  386. continue
  387. }
  388. switch event.Action {
  389. case "health_status: unhealthy":
  390. return ErrContainerUnhealthy
  391. }
  392. }
  393. }
  394. }