controller.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715
  1. package container // import "github.com/docker/docker/daemon/cluster/executor/container"
  2. import (
  3. "context"
  4. "fmt"
  5. "os"
  6. "strconv"
  7. "strings"
  8. "time"
  9. "github.com/docker/docker/api/types"
  10. "github.com/docker/docker/api/types/events"
  11. executorpkg "github.com/docker/docker/daemon/cluster/executor"
  12. "github.com/docker/go-connections/nat"
  13. "github.com/docker/libnetwork"
  14. "github.com/docker/swarmkit/agent/exec"
  15. "github.com/docker/swarmkit/api"
  16. "github.com/docker/swarmkit/log"
  17. gogotypes "github.com/gogo/protobuf/types"
  18. "github.com/pkg/errors"
  19. "golang.org/x/time/rate"
  20. )
  21. const defaultGossipConvergeDelay = 2 * time.Second
  22. // waitNodeAttachmentsTimeout defines the total period of time we should wait
  23. // for node attachments to be ready before giving up on starting a task
  24. const waitNodeAttachmentsTimeout = 30 * time.Second
  25. // controller implements agent.Controller against docker's API.
  26. //
  27. // Most operations against docker's API are done through the container name,
  28. // which is unique to the task.
  29. type controller struct {
  30. task *api.Task
  31. adapter *containerAdapter
  32. closed chan struct{}
  33. err error
  34. pulled chan struct{} // closed after pull
  35. cancelPull func() // cancels pull context if not nil
  36. pullErr error // pull error, only read after pulled closed
  37. }
  38. var _ exec.Controller = &controller{}
  39. // NewController returns a docker exec runner for the provided task.
  40. func newController(b executorpkg.Backend, i executorpkg.ImageBackend, v executorpkg.VolumeBackend, task *api.Task, node *api.NodeDescription, dependencies exec.DependencyGetter) (*controller, error) {
  41. adapter, err := newContainerAdapter(b, i, v, task, node, dependencies)
  42. if err != nil {
  43. return nil, err
  44. }
  45. return &controller{
  46. task: task,
  47. adapter: adapter,
  48. closed: make(chan struct{}),
  49. }, nil
  50. }
  51. func (r *controller) Task() (*api.Task, error) {
  52. return r.task, nil
  53. }
  54. // ContainerStatus returns the container-specific status for the task.
  55. func (r *controller) ContainerStatus(ctx context.Context) (*api.ContainerStatus, error) {
  56. ctnr, err := r.adapter.inspect(ctx)
  57. if err != nil {
  58. if isUnknownContainer(err) {
  59. return nil, nil
  60. }
  61. return nil, err
  62. }
  63. return parseContainerStatus(ctnr)
  64. }
  65. func (r *controller) PortStatus(ctx context.Context) (*api.PortStatus, error) {
  66. ctnr, err := r.adapter.inspect(ctx)
  67. if err != nil {
  68. if isUnknownContainer(err) {
  69. return nil, nil
  70. }
  71. return nil, err
  72. }
  73. return parsePortStatus(ctnr)
  74. }
  75. // Update tasks a recent task update and applies it to the container.
  76. func (r *controller) Update(ctx context.Context, t *api.Task) error {
  77. // TODO(stevvooe): While assignment of tasks is idempotent, we do allow
  78. // updates of metadata, such as labelling, as well as any other properties
  79. // that make sense.
  80. return nil
  81. }
  82. // Prepare creates a container and ensures the image is pulled.
  83. //
  84. // If the container has already be created, exec.ErrTaskPrepared is returned.
  85. func (r *controller) Prepare(ctx context.Context) error {
  86. if err := r.checkClosed(); err != nil {
  87. return err
  88. }
  89. // Before we create networks, we need to make sure that the node has all of
  90. // the network attachments that the task needs. This will block until that
  91. // is the case or the context has expired.
  92. // NOTE(dperny): Prepare doesn't time out on its own (that is, the context
  93. // passed in does not expire after any period of time), which means if the
  94. // node attachment never arrives (for example, if the network's IP address
  95. // space is exhausted), then the tasks on the node will park in PREPARING
  96. // forever (or until the node dies). To avoid this case, we create a new
  97. // context with a fixed deadline, and give up. In normal operation, a node
  98. // update with the node IP address should come in hot on the tail of the
  99. // task being assigned to the node, and this should exit on the order of
  100. // milliseconds, but to be extra conservative we'll give it 30 seconds to
  101. // time out before giving up.
  102. waitNodeAttachmentsContext, waitCancel := context.WithTimeout(ctx, waitNodeAttachmentsTimeout)
  103. defer waitCancel()
  104. if err := r.adapter.waitNodeAttachments(waitNodeAttachmentsContext); err != nil {
  105. return err
  106. }
  107. // Make sure all the networks that the task needs are created.
  108. if err := r.adapter.createNetworks(ctx); err != nil {
  109. return err
  110. }
  111. // Make sure all the volumes that the task needs are created.
  112. if err := r.adapter.createVolumes(ctx); err != nil {
  113. return err
  114. }
  115. if os.Getenv("DOCKER_SERVICE_PREFER_OFFLINE_IMAGE") != "1" {
  116. if r.pulled == nil {
  117. // Fork the pull to a different context to allow pull to continue
  118. // on re-entrant calls to Prepare. This ensures that Prepare can be
  119. // idempotent and not incur the extra cost of pulling when
  120. // cancelled on updates.
  121. var pctx context.Context
  122. r.pulled = make(chan struct{})
  123. pctx, r.cancelPull = context.WithCancel(context.Background()) // TODO(stevvooe): Bind a context to the entire controller.
  124. go func() {
  125. defer close(r.pulled)
  126. r.pullErr = r.adapter.pullImage(pctx) // protected by closing r.pulled
  127. }()
  128. }
  129. select {
  130. case <-ctx.Done():
  131. return ctx.Err()
  132. case <-r.pulled:
  133. if r.pullErr != nil {
  134. // NOTE(stevvooe): We always try to pull the image to make sure we have
  135. // the most up to date version. This will return an error, but we only
  136. // log it. If the image truly doesn't exist, the create below will
  137. // error out.
  138. //
  139. // This gives us some nice behavior where we use up to date versions of
  140. // mutable tags, but will still run if the old image is available but a
  141. // registry is down.
  142. //
  143. // If you don't want this behavior, lock down your image to an
  144. // immutable tag or digest.
  145. log.G(ctx).WithError(r.pullErr).Error("pulling image failed")
  146. }
  147. }
  148. }
  149. if err := r.adapter.create(ctx); err != nil {
  150. if isContainerCreateNameConflict(err) {
  151. if _, err := r.adapter.inspect(ctx); err != nil {
  152. return err
  153. }
  154. // container is already created. success!
  155. return exec.ErrTaskPrepared
  156. }
  157. return err
  158. }
  159. return nil
  160. }
  161. // Start the container. An error will be returned if the container is already started.
  162. func (r *controller) Start(ctx context.Context) error {
  163. if err := r.checkClosed(); err != nil {
  164. return err
  165. }
  166. ctnr, err := r.adapter.inspect(ctx)
  167. if err != nil {
  168. return err
  169. }
  170. // Detect whether the container has *ever* been started. If so, we don't
  171. // issue the start.
  172. //
  173. // TODO(stevvooe): This is very racy. While reading inspect, another could
  174. // start the process and we could end up starting it twice.
  175. if ctnr.State.Status != "created" {
  176. return exec.ErrTaskStarted
  177. }
  178. for {
  179. if err := r.adapter.start(ctx); err != nil {
  180. if _, ok := errors.Cause(err).(libnetwork.ErrNoSuchNetwork); ok {
  181. // Retry network creation again if we
  182. // failed because some of the networks
  183. // were not found.
  184. if err := r.adapter.createNetworks(ctx); err != nil {
  185. return err
  186. }
  187. continue
  188. }
  189. return errors.Wrap(err, "starting container failed")
  190. }
  191. break
  192. }
  193. // no health check
  194. if ctnr.Config == nil || ctnr.Config.Healthcheck == nil || len(ctnr.Config.Healthcheck.Test) == 0 || ctnr.Config.Healthcheck.Test[0] == "NONE" {
  195. if err := r.adapter.activateServiceBinding(); err != nil {
  196. log.G(ctx).WithError(err).Errorf("failed to activate service binding for container %s which has no healthcheck config", r.adapter.container.name())
  197. return err
  198. }
  199. return nil
  200. }
  201. // wait for container to be healthy
  202. eventq := r.adapter.events(ctx)
  203. var healthErr error
  204. for {
  205. select {
  206. case event := <-eventq:
  207. if !r.matchevent(event) {
  208. continue
  209. }
  210. switch event.Action {
  211. case "die": // exit on terminal events
  212. ctnr, err := r.adapter.inspect(ctx)
  213. if err != nil {
  214. return errors.Wrap(err, "die event received")
  215. } else if ctnr.State.ExitCode != 0 {
  216. return &exitError{code: ctnr.State.ExitCode, cause: healthErr}
  217. }
  218. return nil
  219. case "destroy":
  220. // If we get here, something has gone wrong but we want to exit
  221. // and report anyways.
  222. return ErrContainerDestroyed
  223. case "health_status: unhealthy":
  224. // in this case, we stop the container and report unhealthy status
  225. if err := r.Shutdown(ctx); err != nil {
  226. return errors.Wrap(err, "unhealthy container shutdown failed")
  227. }
  228. // set health check error, and wait for container to fully exit ("die" event)
  229. healthErr = ErrContainerUnhealthy
  230. case "health_status: healthy":
  231. if err := r.adapter.activateServiceBinding(); err != nil {
  232. log.G(ctx).WithError(err).Errorf("failed to activate service binding for container %s after healthy event", r.adapter.container.name())
  233. return err
  234. }
  235. return nil
  236. }
  237. case <-ctx.Done():
  238. return ctx.Err()
  239. case <-r.closed:
  240. return r.err
  241. }
  242. }
  243. }
  244. // Wait on the container to exit.
  245. func (r *controller) Wait(pctx context.Context) error {
  246. if err := r.checkClosed(); err != nil {
  247. return err
  248. }
  249. ctx, cancel := context.WithCancel(pctx)
  250. defer cancel()
  251. healthErr := make(chan error, 1)
  252. go func() {
  253. ectx, cancel := context.WithCancel(ctx) // cancel event context on first event
  254. defer cancel()
  255. if err := r.checkHealth(ectx); err == ErrContainerUnhealthy {
  256. healthErr <- ErrContainerUnhealthy
  257. if err := r.Shutdown(ectx); err != nil {
  258. log.G(ectx).WithError(err).Debug("shutdown failed on unhealthy")
  259. }
  260. }
  261. }()
  262. waitC, err := r.adapter.wait(ctx)
  263. if err != nil {
  264. return err
  265. }
  266. if status := <-waitC; status.ExitCode() != 0 {
  267. exitErr := &exitError{
  268. code: status.ExitCode(),
  269. }
  270. // Set the cause if it is knowable.
  271. select {
  272. case e := <-healthErr:
  273. exitErr.cause = e
  274. default:
  275. if status.Err() != nil {
  276. exitErr.cause = status.Err()
  277. }
  278. }
  279. return exitErr
  280. }
  281. return nil
  282. }
  283. func (r *controller) hasServiceBinding() bool {
  284. if r.task == nil {
  285. return false
  286. }
  287. // service is attached to a network besides the default bridge
  288. for _, na := range r.task.Networks {
  289. if na.Network == nil ||
  290. na.Network.DriverState == nil ||
  291. na.Network.DriverState.Name == "bridge" && na.Network.Spec.Annotations.Name == "bridge" {
  292. continue
  293. }
  294. return true
  295. }
  296. return false
  297. }
  298. // Shutdown the container cleanly.
  299. func (r *controller) Shutdown(ctx context.Context) error {
  300. if err := r.checkClosed(); err != nil {
  301. return err
  302. }
  303. if r.cancelPull != nil {
  304. r.cancelPull()
  305. }
  306. if r.hasServiceBinding() {
  307. // remove container from service binding
  308. if err := r.adapter.deactivateServiceBinding(); err != nil {
  309. log.G(ctx).WithError(err).Warningf("failed to deactivate service binding for container %s", r.adapter.container.name())
  310. // Don't return an error here, because failure to deactivate
  311. // the service binding is expected if the container was never
  312. // started.
  313. }
  314. // add a delay for gossip converge
  315. // TODO(dongluochen): this delay should be configurable to fit different cluster size and network delay.
  316. time.Sleep(defaultGossipConvergeDelay)
  317. }
  318. if err := r.adapter.shutdown(ctx); err != nil {
  319. if isUnknownContainer(err) || isStoppedContainer(err) {
  320. return nil
  321. }
  322. return err
  323. }
  324. // Try removing networks referenced in this task in case this
  325. // task is the last one referencing it
  326. if err := r.adapter.removeNetworks(ctx); err != nil {
  327. if isUnknownContainer(err) {
  328. return nil
  329. }
  330. return err
  331. }
  332. return nil
  333. }
  334. // Terminate the container, with force.
  335. func (r *controller) Terminate(ctx context.Context) error {
  336. if err := r.checkClosed(); err != nil {
  337. return err
  338. }
  339. if r.cancelPull != nil {
  340. r.cancelPull()
  341. }
  342. if err := r.adapter.terminate(ctx); err != nil {
  343. if isUnknownContainer(err) {
  344. return nil
  345. }
  346. return err
  347. }
  348. return nil
  349. }
  350. // Remove the container and its resources.
  351. func (r *controller) Remove(ctx context.Context) error {
  352. if err := r.checkClosed(); err != nil {
  353. return err
  354. }
  355. if r.cancelPull != nil {
  356. r.cancelPull()
  357. }
  358. // It may be necessary to shut down the task before removing it.
  359. if err := r.Shutdown(ctx); err != nil {
  360. if isUnknownContainer(err) {
  361. return nil
  362. }
  363. // This may fail if the task was already shut down.
  364. log.G(ctx).WithError(err).Debug("shutdown failed on removal")
  365. }
  366. if err := r.adapter.remove(ctx); err != nil {
  367. if isUnknownContainer(err) {
  368. return nil
  369. }
  370. return err
  371. }
  372. return nil
  373. }
  374. // waitReady waits for a container to be "ready".
  375. // Ready means it's past the started state.
  376. func (r *controller) waitReady(pctx context.Context) error {
  377. if err := r.checkClosed(); err != nil {
  378. return err
  379. }
  380. ctx, cancel := context.WithCancel(pctx)
  381. defer cancel()
  382. eventq := r.adapter.events(ctx)
  383. ctnr, err := r.adapter.inspect(ctx)
  384. if err != nil {
  385. if !isUnknownContainer(err) {
  386. return errors.Wrap(err, "inspect container failed")
  387. }
  388. } else {
  389. switch ctnr.State.Status {
  390. case "running", "exited", "dead":
  391. return nil
  392. }
  393. }
  394. for {
  395. select {
  396. case event := <-eventq:
  397. if !r.matchevent(event) {
  398. continue
  399. }
  400. switch event.Action {
  401. case "start":
  402. return nil
  403. }
  404. case <-ctx.Done():
  405. return ctx.Err()
  406. case <-r.closed:
  407. return r.err
  408. }
  409. }
  410. }
  411. func (r *controller) Logs(ctx context.Context, publisher exec.LogPublisher, options api.LogSubscriptionOptions) error {
  412. if err := r.checkClosed(); err != nil {
  413. return err
  414. }
  415. // if we're following, wait for this container to be ready. there is a
  416. // problem here: if the container will never be ready (for example, it has
  417. // been totally deleted) then this will wait forever. however, this doesn't
  418. // actually cause any UI issues, and shouldn't be a problem. the stuck wait
  419. // will go away when the follow (context) is canceled.
  420. if options.Follow {
  421. if err := r.waitReady(ctx); err != nil {
  422. return errors.Wrap(err, "container not ready for logs")
  423. }
  424. }
  425. // if we're not following, we're not gonna wait for the container to be
  426. // ready. just call logs. if the container isn't ready, the call will fail
  427. // and return an error. no big deal, we don't care, we only want the logs
  428. // we can get RIGHT NOW with no follow
  429. logsContext, cancel := context.WithCancel(ctx)
  430. msgs, err := r.adapter.logs(logsContext, options)
  431. defer cancel()
  432. if err != nil {
  433. return errors.Wrap(err, "failed getting container logs")
  434. }
  435. var (
  436. // use a rate limiter to keep things under control but also provides some
  437. // ability coalesce messages.
  438. limiter = rate.NewLimiter(rate.Every(time.Second), 10<<20) // 10 MB/s
  439. msgctx = api.LogContext{
  440. NodeID: r.task.NodeID,
  441. ServiceID: r.task.ServiceID,
  442. TaskID: r.task.ID,
  443. }
  444. )
  445. for {
  446. msg, ok := <-msgs
  447. if !ok {
  448. // we're done here, no more messages
  449. return nil
  450. }
  451. if msg.Err != nil {
  452. // the deferred cancel closes the adapter's log stream
  453. return msg.Err
  454. }
  455. // wait here for the limiter to catch up
  456. if err := limiter.WaitN(ctx, len(msg.Line)); err != nil {
  457. return errors.Wrap(err, "failed rate limiter")
  458. }
  459. tsp, err := gogotypes.TimestampProto(msg.Timestamp)
  460. if err != nil {
  461. return errors.Wrap(err, "failed to convert timestamp")
  462. }
  463. var stream api.LogStream
  464. if msg.Source == "stdout" {
  465. stream = api.LogStreamStdout
  466. } else if msg.Source == "stderr" {
  467. stream = api.LogStreamStderr
  468. }
  469. // parse the details out of the Attrs map
  470. var attrs []api.LogAttr
  471. if len(msg.Attrs) != 0 {
  472. attrs = make([]api.LogAttr, 0, len(msg.Attrs))
  473. for _, attr := range msg.Attrs {
  474. attrs = append(attrs, api.LogAttr{Key: attr.Key, Value: attr.Value})
  475. }
  476. }
  477. if err := publisher.Publish(ctx, api.LogMessage{
  478. Context: msgctx,
  479. Timestamp: tsp,
  480. Stream: stream,
  481. Attrs: attrs,
  482. Data: msg.Line,
  483. }); err != nil {
  484. return errors.Wrap(err, "failed to publish log message")
  485. }
  486. }
  487. }
  488. // Close the runner and clean up any ephemeral resources.
  489. func (r *controller) Close() error {
  490. select {
  491. case <-r.closed:
  492. return r.err
  493. default:
  494. if r.cancelPull != nil {
  495. r.cancelPull()
  496. }
  497. r.err = exec.ErrControllerClosed
  498. close(r.closed)
  499. }
  500. return nil
  501. }
  502. func (r *controller) matchevent(event events.Message) bool {
  503. if event.Type != events.ContainerEventType {
  504. return false
  505. }
  506. // we can't filter using id since it will have huge chances to introduce a deadlock. see #33377.
  507. return event.Actor.Attributes["name"] == r.adapter.container.name()
  508. }
  509. func (r *controller) checkClosed() error {
  510. select {
  511. case <-r.closed:
  512. return r.err
  513. default:
  514. return nil
  515. }
  516. }
  517. func parseContainerStatus(ctnr types.ContainerJSON) (*api.ContainerStatus, error) {
  518. status := &api.ContainerStatus{
  519. ContainerID: ctnr.ID,
  520. PID: int32(ctnr.State.Pid),
  521. ExitCode: int32(ctnr.State.ExitCode),
  522. }
  523. return status, nil
  524. }
  525. func parsePortStatus(ctnr types.ContainerJSON) (*api.PortStatus, error) {
  526. status := &api.PortStatus{}
  527. if ctnr.NetworkSettings != nil && len(ctnr.NetworkSettings.Ports) > 0 {
  528. exposedPorts, err := parsePortMap(ctnr.NetworkSettings.Ports)
  529. if err != nil {
  530. return nil, err
  531. }
  532. status.Ports = exposedPorts
  533. }
  534. return status, nil
  535. }
  536. func parsePortMap(portMap nat.PortMap) ([]*api.PortConfig, error) {
  537. exposedPorts := make([]*api.PortConfig, 0, len(portMap))
  538. for portProtocol, mapping := range portMap {
  539. parts := strings.SplitN(string(portProtocol), "/", 2)
  540. if len(parts) != 2 {
  541. return nil, fmt.Errorf("invalid port mapping: %s", portProtocol)
  542. }
  543. port, err := strconv.ParseUint(parts[0], 10, 16)
  544. if err != nil {
  545. return nil, err
  546. }
  547. protocol := api.ProtocolTCP
  548. switch strings.ToLower(parts[1]) {
  549. case "tcp":
  550. protocol = api.ProtocolTCP
  551. case "udp":
  552. protocol = api.ProtocolUDP
  553. case "sctp":
  554. protocol = api.ProtocolSCTP
  555. default:
  556. return nil, fmt.Errorf("invalid protocol: %s", parts[1])
  557. }
  558. for _, binding := range mapping {
  559. hostPort, err := strconv.ParseUint(binding.HostPort, 10, 16)
  560. if err != nil {
  561. return nil, err
  562. }
  563. // TODO(aluzzardi): We're losing the port `name` here since
  564. // there's no way to retrieve it back from the Engine.
  565. exposedPorts = append(exposedPorts, &api.PortConfig{
  566. PublishMode: api.PublishModeHost,
  567. Protocol: protocol,
  568. TargetPort: uint32(port),
  569. PublishedPort: uint32(hostPort),
  570. })
  571. }
  572. }
  573. return exposedPorts, nil
  574. }
  575. type exitError struct {
  576. code int
  577. cause error
  578. }
  579. func (e *exitError) Error() string {
  580. if e.cause != nil {
  581. return fmt.Sprintf("task: non-zero exit (%v): %v", e.code, e.cause)
  582. }
  583. return fmt.Sprintf("task: non-zero exit (%v)", e.code)
  584. }
  585. func (e *exitError) ExitCode() int {
  586. return e.code
  587. }
  588. func (e *exitError) Cause() error {
  589. return e.cause
  590. }
  591. // checkHealth blocks until unhealthy container is detected or ctx exits
  592. func (r *controller) checkHealth(ctx context.Context) error {
  593. eventq := r.adapter.events(ctx)
  594. for {
  595. select {
  596. case <-ctx.Done():
  597. return nil
  598. case <-r.closed:
  599. return nil
  600. case event := <-eventq:
  601. if !r.matchevent(event) {
  602. continue
  603. }
  604. switch event.Action {
  605. case "health_status: unhealthy":
  606. return ErrContainerUnhealthy
  607. }
  608. }
  609. }
  610. }