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. var lnErr libnetwork.ErrNoSuchNetwork
  179. for {
  180. if err := r.adapter.start(ctx); err != nil {
  181. if errors.As(err, &lnErr) {
  182. // Retry network creation again if we
  183. // failed because some of the networks
  184. // were not found.
  185. if err := r.adapter.createNetworks(ctx); err != nil {
  186. return err
  187. }
  188. continue
  189. }
  190. return errors.Wrap(err, "starting container failed")
  191. }
  192. break
  193. }
  194. // no health check
  195. if ctnr.Config == nil || ctnr.Config.Healthcheck == nil || len(ctnr.Config.Healthcheck.Test) == 0 || ctnr.Config.Healthcheck.Test[0] == "NONE" {
  196. if err := r.adapter.activateServiceBinding(); err != nil {
  197. log.G(ctx).WithError(err).Errorf("failed to activate service binding for container %s which has no healthcheck config", r.adapter.container.name())
  198. return err
  199. }
  200. return nil
  201. }
  202. // wait for container to be healthy
  203. eventq := r.adapter.events(ctx)
  204. var healthErr error
  205. for {
  206. select {
  207. case event := <-eventq:
  208. if !r.matchevent(event) {
  209. continue
  210. }
  211. switch event.Action {
  212. case "die": // exit on terminal events
  213. ctnr, err := r.adapter.inspect(ctx)
  214. if err != nil {
  215. return errors.Wrap(err, "die event received")
  216. } else if ctnr.State.ExitCode != 0 {
  217. return &exitError{code: ctnr.State.ExitCode, cause: healthErr}
  218. }
  219. return nil
  220. case "destroy":
  221. // If we get here, something has gone wrong but we want to exit
  222. // and report anyways.
  223. return ErrContainerDestroyed
  224. case "health_status: unhealthy":
  225. // in this case, we stop the container and report unhealthy status
  226. if err := r.Shutdown(ctx); err != nil {
  227. return errors.Wrap(err, "unhealthy container shutdown failed")
  228. }
  229. // set health check error, and wait for container to fully exit ("die" event)
  230. healthErr = ErrContainerUnhealthy
  231. case "health_status: healthy":
  232. if err := r.adapter.activateServiceBinding(); err != nil {
  233. log.G(ctx).WithError(err).Errorf("failed to activate service binding for container %s after healthy event", r.adapter.container.name())
  234. return err
  235. }
  236. return nil
  237. }
  238. case <-ctx.Done():
  239. return ctx.Err()
  240. case <-r.closed:
  241. return r.err
  242. }
  243. }
  244. }
  245. // Wait on the container to exit.
  246. func (r *controller) Wait(pctx context.Context) error {
  247. if err := r.checkClosed(); err != nil {
  248. return err
  249. }
  250. ctx, cancel := context.WithCancel(pctx)
  251. defer cancel()
  252. healthErr := make(chan error, 1)
  253. go func() {
  254. ectx, cancel := context.WithCancel(ctx) // cancel event context on first event
  255. defer cancel()
  256. if err := r.checkHealth(ectx); err == ErrContainerUnhealthy {
  257. healthErr <- ErrContainerUnhealthy
  258. if err := r.Shutdown(ectx); err != nil {
  259. log.G(ectx).WithError(err).Debug("shutdown failed on unhealthy")
  260. }
  261. }
  262. }()
  263. waitC, err := r.adapter.wait(ctx)
  264. if err != nil {
  265. return err
  266. }
  267. if status := <-waitC; status.ExitCode() != 0 {
  268. exitErr := &exitError{
  269. code: status.ExitCode(),
  270. }
  271. // Set the cause if it is knowable.
  272. select {
  273. case e := <-healthErr:
  274. exitErr.cause = e
  275. default:
  276. if status.Err() != nil {
  277. exitErr.cause = status.Err()
  278. }
  279. }
  280. return exitErr
  281. }
  282. return nil
  283. }
  284. func (r *controller) hasServiceBinding() bool {
  285. if r.task == nil {
  286. return false
  287. }
  288. // service is attached to a network besides the default bridge
  289. for _, na := range r.task.Networks {
  290. if na.Network == nil ||
  291. na.Network.DriverState == nil ||
  292. na.Network.DriverState.Name == "bridge" && na.Network.Spec.Annotations.Name == "bridge" {
  293. continue
  294. }
  295. return true
  296. }
  297. return false
  298. }
  299. // Shutdown the container cleanly.
  300. func (r *controller) Shutdown(ctx context.Context) error {
  301. if err := r.checkClosed(); err != nil {
  302. return err
  303. }
  304. if r.cancelPull != nil {
  305. r.cancelPull()
  306. }
  307. if r.hasServiceBinding() {
  308. // remove container from service binding
  309. if err := r.adapter.deactivateServiceBinding(); err != nil {
  310. log.G(ctx).WithError(err).Warningf("failed to deactivate service binding for container %s", r.adapter.container.name())
  311. // Don't return an error here, because failure to deactivate
  312. // the service binding is expected if the container was never
  313. // started.
  314. }
  315. // add a delay for gossip converge
  316. // TODO(dongluochen): this delay should be configurable to fit different cluster size and network delay.
  317. time.Sleep(defaultGossipConvergeDelay)
  318. }
  319. if err := r.adapter.shutdown(ctx); err != nil {
  320. if !(isUnknownContainer(err) || isStoppedContainer(err)) {
  321. return err
  322. }
  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 err
  329. }
  330. }
  331. return nil
  332. }
  333. // Terminate the container, with force.
  334. func (r *controller) Terminate(ctx context.Context) error {
  335. if err := r.checkClosed(); err != nil {
  336. return err
  337. }
  338. if r.cancelPull != nil {
  339. r.cancelPull()
  340. }
  341. if err := r.adapter.terminate(ctx); err != nil {
  342. if isUnknownContainer(err) {
  343. return nil
  344. }
  345. return err
  346. }
  347. return nil
  348. }
  349. // Remove the container and its resources.
  350. func (r *controller) Remove(ctx context.Context) error {
  351. if err := r.checkClosed(); err != nil {
  352. return err
  353. }
  354. if r.cancelPull != nil {
  355. r.cancelPull()
  356. }
  357. // It may be necessary to shut down the task before removing it.
  358. if err := r.Shutdown(ctx); err != nil {
  359. if isUnknownContainer(err) {
  360. return nil
  361. }
  362. // This may fail if the task was already shut down.
  363. log.G(ctx).WithError(err).Debug("shutdown failed on removal")
  364. }
  365. if err := r.adapter.remove(ctx); err != nil {
  366. if isUnknownContainer(err) {
  367. return nil
  368. }
  369. return err
  370. }
  371. return nil
  372. }
  373. // waitReady waits for a container to be "ready".
  374. // Ready means it's past the started state.
  375. func (r *controller) waitReady(pctx context.Context) error {
  376. if err := r.checkClosed(); err != nil {
  377. return err
  378. }
  379. ctx, cancel := context.WithCancel(pctx)
  380. defer cancel()
  381. eventq := r.adapter.events(ctx)
  382. ctnr, err := r.adapter.inspect(ctx)
  383. if err != nil {
  384. if !isUnknownContainer(err) {
  385. return errors.Wrap(err, "inspect container failed")
  386. }
  387. } else {
  388. switch ctnr.State.Status {
  389. case "running", "exited", "dead":
  390. return nil
  391. }
  392. }
  393. for {
  394. select {
  395. case event := <-eventq:
  396. if !r.matchevent(event) {
  397. continue
  398. }
  399. switch event.Action {
  400. case "start":
  401. return nil
  402. }
  403. case <-ctx.Done():
  404. return ctx.Err()
  405. case <-r.closed:
  406. return r.err
  407. }
  408. }
  409. }
  410. func (r *controller) Logs(ctx context.Context, publisher exec.LogPublisher, options api.LogSubscriptionOptions) error {
  411. if err := r.checkClosed(); err != nil {
  412. return err
  413. }
  414. // if we're following, wait for this container to be ready. there is a
  415. // problem here: if the container will never be ready (for example, it has
  416. // been totally deleted) then this will wait forever. however, this doesn't
  417. // actually cause any UI issues, and shouldn't be a problem. the stuck wait
  418. // will go away when the follow (context) is canceled.
  419. if options.Follow {
  420. if err := r.waitReady(ctx); err != nil {
  421. return errors.Wrap(err, "container not ready for logs")
  422. }
  423. }
  424. // if we're not following, we're not gonna wait for the container to be
  425. // ready. just call logs. if the container isn't ready, the call will fail
  426. // and return an error. no big deal, we don't care, we only want the logs
  427. // we can get RIGHT NOW with no follow
  428. logsContext, cancel := context.WithCancel(ctx)
  429. msgs, err := r.adapter.logs(logsContext, options)
  430. defer cancel()
  431. if err != nil {
  432. return errors.Wrap(err, "failed getting container logs")
  433. }
  434. var (
  435. // use a rate limiter to keep things under control but also provides some
  436. // ability coalesce messages.
  437. // this will implement a "token bucket" of size 10 MB, initially full and refilled
  438. // at rate 10 MB tokens per second.
  439. limiter = rate.NewLimiter(10<<20, 10<<20) // 10 MB/s
  440. msgctx = api.LogContext{
  441. NodeID: r.task.NodeID,
  442. ServiceID: r.task.ServiceID,
  443. TaskID: r.task.ID,
  444. }
  445. )
  446. for {
  447. msg, ok := <-msgs
  448. if !ok {
  449. // we're done here, no more messages
  450. return nil
  451. }
  452. if msg.Err != nil {
  453. // the deferred cancel closes the adapter's log stream
  454. return msg.Err
  455. }
  456. // wait here for the limiter to catch up
  457. if err := limiter.WaitN(ctx, len(msg.Line)); err != nil {
  458. return errors.Wrap(err, "failed rate limiter")
  459. }
  460. tsp, err := gogotypes.TimestampProto(msg.Timestamp)
  461. if err != nil {
  462. return errors.Wrap(err, "failed to convert timestamp")
  463. }
  464. var stream api.LogStream
  465. if msg.Source == "stdout" {
  466. stream = api.LogStreamStdout
  467. } else if msg.Source == "stderr" {
  468. stream = api.LogStreamStderr
  469. }
  470. // parse the details out of the Attrs map
  471. var attrs []api.LogAttr
  472. if len(msg.Attrs) != 0 {
  473. attrs = make([]api.LogAttr, 0, len(msg.Attrs))
  474. for _, attr := range msg.Attrs {
  475. attrs = append(attrs, api.LogAttr{Key: attr.Key, Value: attr.Value})
  476. }
  477. }
  478. if err := publisher.Publish(ctx, api.LogMessage{
  479. Context: msgctx,
  480. Timestamp: tsp,
  481. Stream: stream,
  482. Attrs: attrs,
  483. Data: msg.Line,
  484. }); err != nil {
  485. return errors.Wrap(err, "failed to publish log message")
  486. }
  487. }
  488. }
  489. // Close the runner and clean up any ephemeral resources.
  490. func (r *controller) Close() error {
  491. select {
  492. case <-r.closed:
  493. return r.err
  494. default:
  495. if r.cancelPull != nil {
  496. r.cancelPull()
  497. }
  498. r.err = exec.ErrControllerClosed
  499. close(r.closed)
  500. }
  501. return nil
  502. }
  503. func (r *controller) matchevent(event events.Message) bool {
  504. if event.Type != events.ContainerEventType {
  505. return false
  506. }
  507. // we can't filter using id since it will have huge chances to introduce a deadlock. see #33377.
  508. return event.Actor.Attributes["name"] == r.adapter.container.name()
  509. }
  510. func (r *controller) checkClosed() error {
  511. select {
  512. case <-r.closed:
  513. return r.err
  514. default:
  515. return nil
  516. }
  517. }
  518. func parseContainerStatus(ctnr types.ContainerJSON) (*api.ContainerStatus, error) {
  519. status := &api.ContainerStatus{
  520. ContainerID: ctnr.ID,
  521. PID: int32(ctnr.State.Pid),
  522. ExitCode: int32(ctnr.State.ExitCode),
  523. }
  524. return status, nil
  525. }
  526. func parsePortStatus(ctnr types.ContainerJSON) (*api.PortStatus, error) {
  527. status := &api.PortStatus{}
  528. if ctnr.NetworkSettings != nil && len(ctnr.NetworkSettings.Ports) > 0 {
  529. exposedPorts, err := parsePortMap(ctnr.NetworkSettings.Ports)
  530. if err != nil {
  531. return nil, err
  532. }
  533. status.Ports = exposedPorts
  534. }
  535. return status, nil
  536. }
  537. func parsePortMap(portMap nat.PortMap) ([]*api.PortConfig, error) {
  538. exposedPorts := make([]*api.PortConfig, 0, len(portMap))
  539. for portProtocol, mapping := range portMap {
  540. parts := strings.SplitN(string(portProtocol), "/", 2)
  541. if len(parts) != 2 {
  542. return nil, fmt.Errorf("invalid port mapping: %s", portProtocol)
  543. }
  544. port, err := strconv.ParseUint(parts[0], 10, 16)
  545. if err != nil {
  546. return nil, err
  547. }
  548. var protocol api.PortConfig_Protocol
  549. switch strings.ToLower(parts[1]) {
  550. case "tcp":
  551. protocol = api.ProtocolTCP
  552. case "udp":
  553. protocol = api.ProtocolUDP
  554. case "sctp":
  555. protocol = api.ProtocolSCTP
  556. default:
  557. return nil, fmt.Errorf("invalid protocol: %s", parts[1])
  558. }
  559. for _, binding := range mapping {
  560. hostPort, err := strconv.ParseUint(binding.HostPort, 10, 16)
  561. if err != nil {
  562. return nil, err
  563. }
  564. // TODO(aluzzardi): We're losing the port `name` here since
  565. // there's no way to retrieve it back from the Engine.
  566. exposedPorts = append(exposedPorts, &api.PortConfig{
  567. PublishMode: api.PublishModeHost,
  568. Protocol: protocol,
  569. TargetPort: uint32(port),
  570. PublishedPort: uint32(hostPort),
  571. })
  572. }
  573. }
  574. return exposedPorts, nil
  575. }
  576. type exitError struct {
  577. code int
  578. cause error
  579. }
  580. func (e *exitError) Error() string {
  581. if e.cause != nil {
  582. return fmt.Sprintf("task: non-zero exit (%v): %v", e.code, e.cause)
  583. }
  584. return fmt.Sprintf("task: non-zero exit (%v)", e.code)
  585. }
  586. func (e *exitError) ExitCode() int {
  587. return e.code
  588. }
  589. func (e *exitError) Cause() error {
  590. return e.cause
  591. }
  592. // checkHealth blocks until unhealthy container is detected or ctx exits
  593. func (r *controller) checkHealth(ctx context.Context) error {
  594. eventq := r.adapter.events(ctx)
  595. for {
  596. select {
  597. case <-ctx.Done():
  598. return nil
  599. case <-r.closed:
  600. return nil
  601. case event := <-eventq:
  602. if !r.matchevent(event) {
  603. continue
  604. }
  605. switch event.Action {
  606. case "health_status: unhealthy":
  607. return ErrContainerUnhealthy
  608. }
  609. }
  610. }
  611. }