controller.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672
  1. package container
  2. import (
  3. "bufio"
  4. "bytes"
  5. "encoding/binary"
  6. "fmt"
  7. "io"
  8. "os"
  9. "strconv"
  10. "strings"
  11. "time"
  12. "github.com/docker/docker/api/types"
  13. "github.com/docker/docker/api/types/events"
  14. executorpkg "github.com/docker/docker/daemon/cluster/executor"
  15. "github.com/docker/go-connections/nat"
  16. "github.com/docker/libnetwork"
  17. "github.com/docker/swarmkit/agent/exec"
  18. "github.com/docker/swarmkit/api"
  19. "github.com/docker/swarmkit/log"
  20. "github.com/docker/swarmkit/protobuf/ptypes"
  21. "github.com/pkg/errors"
  22. "golang.org/x/net/context"
  23. "golang.org/x/time/rate"
  24. )
  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, task *api.Task, secrets exec.SecretGetter) (*controller, error) {
  41. adapter, err := newContainerAdapter(b, task, secrets)
  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. // Make sure all the networks that the task needs are created.
  90. if err := r.adapter.createNetworks(ctx); err != nil {
  91. return err
  92. }
  93. // Make sure all the volumes that the task needs are created.
  94. if err := r.adapter.createVolumes(ctx); err != nil {
  95. return err
  96. }
  97. if os.Getenv("DOCKER_SERVICE_PREFER_OFFLINE_IMAGE") != "1" {
  98. if r.pulled == nil {
  99. // Fork the pull to a different context to allow pull to continue
  100. // on re-entrant calls to Prepare. This ensures that Prepare can be
  101. // idempotent and not incur the extra cost of pulling when
  102. // cancelled on updates.
  103. var pctx context.Context
  104. r.pulled = make(chan struct{})
  105. pctx, r.cancelPull = context.WithCancel(context.Background()) // TODO(stevvooe): Bind a context to the entire controller.
  106. go func() {
  107. defer close(r.pulled)
  108. r.pullErr = r.adapter.pullImage(pctx) // protected by closing r.pulled
  109. }()
  110. }
  111. select {
  112. case <-ctx.Done():
  113. return ctx.Err()
  114. case <-r.pulled:
  115. if r.pullErr != nil {
  116. // NOTE(stevvooe): We always try to pull the image to make sure we have
  117. // the most up to date version. This will return an error, but we only
  118. // log it. If the image truly doesn't exist, the create below will
  119. // error out.
  120. //
  121. // This gives us some nice behavior where we use up to date versions of
  122. // mutable tags, but will still run if the old image is available but a
  123. // registry is down.
  124. //
  125. // If you don't want this behavior, lock down your image to an
  126. // immutable tag or digest.
  127. log.G(ctx).WithError(r.pullErr).Error("pulling image failed")
  128. }
  129. }
  130. }
  131. if err := r.adapter.create(ctx); err != nil {
  132. if isContainerCreateNameConflict(err) {
  133. if _, err := r.adapter.inspect(ctx); err != nil {
  134. return err
  135. }
  136. // container is already created. success!
  137. return exec.ErrTaskPrepared
  138. }
  139. return err
  140. }
  141. return nil
  142. }
  143. // Start the container. An error will be returned if the container is already started.
  144. func (r *controller) Start(ctx context.Context) error {
  145. if err := r.checkClosed(); err != nil {
  146. return err
  147. }
  148. ctnr, err := r.adapter.inspect(ctx)
  149. if err != nil {
  150. return err
  151. }
  152. // Detect whether the container has *ever* been started. If so, we don't
  153. // issue the start.
  154. //
  155. // TODO(stevvooe): This is very racy. While reading inspect, another could
  156. // start the process and we could end up starting it twice.
  157. if ctnr.State.Status != "created" {
  158. return exec.ErrTaskStarted
  159. }
  160. for {
  161. if err := r.adapter.start(ctx); err != nil {
  162. if _, ok := err.(libnetwork.ErrNoSuchNetwork); ok {
  163. // Retry network creation again if we
  164. // failed because some of the networks
  165. // were not found.
  166. if err := r.adapter.createNetworks(ctx); err != nil {
  167. return err
  168. }
  169. continue
  170. }
  171. return errors.Wrap(err, "starting container failed")
  172. }
  173. break
  174. }
  175. // no health check
  176. if ctnr.Config == nil || ctnr.Config.Healthcheck == nil {
  177. if err := r.adapter.activateServiceBinding(); err != nil {
  178. log.G(ctx).WithError(err).Errorf("failed to activate service binding for container %s which has no healthcheck config", r.adapter.container.name())
  179. return err
  180. }
  181. return nil
  182. }
  183. healthCmd := ctnr.Config.Healthcheck.Test
  184. if len(healthCmd) == 0 || healthCmd[0] == "NONE" {
  185. return nil
  186. }
  187. // wait for container to be healthy
  188. eventq := r.adapter.events(ctx)
  189. var healthErr error
  190. for {
  191. select {
  192. case event := <-eventq:
  193. if !r.matchevent(event) {
  194. continue
  195. }
  196. switch event.Action {
  197. case "die": // exit on terminal events
  198. ctnr, err := r.adapter.inspect(ctx)
  199. if err != nil {
  200. return errors.Wrap(err, "die event received")
  201. } else if ctnr.State.ExitCode != 0 {
  202. return &exitError{code: ctnr.State.ExitCode, cause: healthErr}
  203. }
  204. return nil
  205. case "destroy":
  206. // If we get here, something has gone wrong but we want to exit
  207. // and report anyways.
  208. return ErrContainerDestroyed
  209. case "health_status: unhealthy":
  210. // in this case, we stop the container and report unhealthy status
  211. if err := r.Shutdown(ctx); err != nil {
  212. return errors.Wrap(err, "unhealthy container shutdown failed")
  213. }
  214. // set health check error, and wait for container to fully exit ("die" event)
  215. healthErr = ErrContainerUnhealthy
  216. case "health_status: healthy":
  217. if err := r.adapter.activateServiceBinding(); err != nil {
  218. log.G(ctx).WithError(err).Errorf("failed to activate service binding for container %s after healthy event", r.adapter.container.name())
  219. return err
  220. }
  221. return nil
  222. }
  223. case <-ctx.Done():
  224. return ctx.Err()
  225. case <-r.closed:
  226. return r.err
  227. }
  228. }
  229. }
  230. // Wait on the container to exit.
  231. func (r *controller) Wait(pctx context.Context) error {
  232. if err := r.checkClosed(); err != nil {
  233. return err
  234. }
  235. ctx, cancel := context.WithCancel(pctx)
  236. defer cancel()
  237. healthErr := make(chan error, 1)
  238. go func() {
  239. ectx, cancel := context.WithCancel(ctx) // cancel event context on first event
  240. defer cancel()
  241. if err := r.checkHealth(ectx); err == ErrContainerUnhealthy {
  242. healthErr <- ErrContainerUnhealthy
  243. if err := r.Shutdown(ectx); err != nil {
  244. log.G(ectx).WithError(err).Debug("shutdown failed on unhealthy")
  245. }
  246. }
  247. }()
  248. err := r.adapter.wait(ctx)
  249. if ctx.Err() != nil {
  250. return ctx.Err()
  251. }
  252. if err != nil {
  253. ee := &exitError{}
  254. if ec, ok := err.(exec.ExitCoder); ok {
  255. ee.code = ec.ExitCode()
  256. }
  257. select {
  258. case e := <-healthErr:
  259. ee.cause = e
  260. default:
  261. if err.Error() != "" {
  262. ee.cause = err
  263. }
  264. }
  265. return ee
  266. }
  267. return nil
  268. }
  269. // Shutdown the container cleanly.
  270. func (r *controller) Shutdown(ctx context.Context) error {
  271. if err := r.checkClosed(); err != nil {
  272. return err
  273. }
  274. if r.cancelPull != nil {
  275. r.cancelPull()
  276. }
  277. // remove container from service binding
  278. if err := r.adapter.deactivateServiceBinding(); err != nil {
  279. log.G(ctx).WithError(err).Errorf("failed to deactivate service binding for container %s", r.adapter.container.name())
  280. return err
  281. }
  282. if err := r.adapter.shutdown(ctx); err != nil {
  283. if isUnknownContainer(err) || isStoppedContainer(err) {
  284. return nil
  285. }
  286. return err
  287. }
  288. return nil
  289. }
  290. // Terminate the container, with force.
  291. func (r *controller) Terminate(ctx context.Context) error {
  292. if err := r.checkClosed(); err != nil {
  293. return err
  294. }
  295. if r.cancelPull != nil {
  296. r.cancelPull()
  297. }
  298. if err := r.adapter.terminate(ctx); err != nil {
  299. if isUnknownContainer(err) {
  300. return nil
  301. }
  302. return err
  303. }
  304. return nil
  305. }
  306. // Remove the container and its resources.
  307. func (r *controller) Remove(ctx context.Context) error {
  308. if err := r.checkClosed(); err != nil {
  309. return err
  310. }
  311. if r.cancelPull != nil {
  312. r.cancelPull()
  313. }
  314. // It may be necessary to shut down the task before removing it.
  315. if err := r.Shutdown(ctx); err != nil {
  316. if isUnknownContainer(err) {
  317. return nil
  318. }
  319. // This may fail if the task was already shut down.
  320. log.G(ctx).WithError(err).Debug("shutdown failed on removal")
  321. }
  322. // Try removing networks referenced in this task in case this
  323. // task is the last one referencing it
  324. if err := r.adapter.removeNetworks(ctx); err != nil {
  325. if isUnknownContainer(err) {
  326. return nil
  327. }
  328. return err
  329. }
  330. if err := r.adapter.remove(ctx); err != nil {
  331. if isUnknownContainer(err) {
  332. return nil
  333. }
  334. return err
  335. }
  336. return nil
  337. }
  338. // waitReady waits for a container to be "ready".
  339. // Ready means it's past the started state.
  340. func (r *controller) waitReady(pctx context.Context) error {
  341. if err := r.checkClosed(); err != nil {
  342. return err
  343. }
  344. ctx, cancel := context.WithCancel(pctx)
  345. defer cancel()
  346. eventq := r.adapter.events(ctx)
  347. ctnr, err := r.adapter.inspect(ctx)
  348. if err != nil {
  349. if !isUnknownContainer(err) {
  350. return errors.Wrap(err, "inspect container failed")
  351. }
  352. } else {
  353. switch ctnr.State.Status {
  354. case "running", "exited", "dead":
  355. return nil
  356. }
  357. }
  358. for {
  359. select {
  360. case event := <-eventq:
  361. if !r.matchevent(event) {
  362. continue
  363. }
  364. switch event.Action {
  365. case "start":
  366. return nil
  367. }
  368. case <-ctx.Done():
  369. return ctx.Err()
  370. case <-r.closed:
  371. return r.err
  372. }
  373. }
  374. }
  375. func (r *controller) Logs(ctx context.Context, publisher exec.LogPublisher, options api.LogSubscriptionOptions) error {
  376. if err := r.checkClosed(); err != nil {
  377. return err
  378. }
  379. if err := r.waitReady(ctx); err != nil {
  380. return errors.Wrap(err, "container not ready for logs")
  381. }
  382. rc, err := r.adapter.logs(ctx, options)
  383. if err != nil {
  384. return errors.Wrap(err, "failed getting container logs")
  385. }
  386. defer rc.Close()
  387. var (
  388. // use a rate limiter to keep things under control but also provides some
  389. // ability coalesce messages.
  390. limiter = rate.NewLimiter(rate.Every(time.Second), 10<<20) // 10 MB/s
  391. msgctx = api.LogContext{
  392. NodeID: r.task.NodeID,
  393. ServiceID: r.task.ServiceID,
  394. TaskID: r.task.ID,
  395. }
  396. )
  397. brd := bufio.NewReader(rc)
  398. for {
  399. // so, message header is 8 bytes, treat as uint64, pull stream off MSB
  400. var header uint64
  401. if err := binary.Read(brd, binary.BigEndian, &header); err != nil {
  402. if err == io.EOF {
  403. return nil
  404. }
  405. return errors.Wrap(err, "failed reading log header")
  406. }
  407. stream, size := (header>>(7<<3))&0xFF, header & ^(uint64(0xFF)<<(7<<3))
  408. // limit here to decrease allocation back pressure.
  409. if err := limiter.WaitN(ctx, int(size)); err != nil {
  410. return errors.Wrap(err, "failed rate limiter")
  411. }
  412. buf := make([]byte, size)
  413. _, err := io.ReadFull(brd, buf)
  414. if err != nil {
  415. return errors.Wrap(err, "failed reading buffer")
  416. }
  417. // Timestamp is RFC3339Nano with 1 space after. Lop, parse, publish
  418. parts := bytes.SplitN(buf, []byte(" "), 2)
  419. if len(parts) != 2 {
  420. return fmt.Errorf("invalid timestamp in log message: %v", buf)
  421. }
  422. ts, err := time.Parse(time.RFC3339Nano, string(parts[0]))
  423. if err != nil {
  424. return errors.Wrap(err, "failed to parse timestamp")
  425. }
  426. tsp, err := ptypes.TimestampProto(ts)
  427. if err != nil {
  428. return errors.Wrap(err, "failed to convert timestamp")
  429. }
  430. if err := publisher.Publish(ctx, api.LogMessage{
  431. Context: msgctx,
  432. Timestamp: tsp,
  433. Stream: api.LogStream(stream),
  434. Data: parts[1],
  435. }); err != nil {
  436. return errors.Wrap(err, "failed to publish log message")
  437. }
  438. }
  439. }
  440. // Close the runner and clean up any ephemeral resources.
  441. func (r *controller) Close() error {
  442. select {
  443. case <-r.closed:
  444. return r.err
  445. default:
  446. if r.cancelPull != nil {
  447. r.cancelPull()
  448. }
  449. r.err = exec.ErrControllerClosed
  450. close(r.closed)
  451. }
  452. return nil
  453. }
  454. func (r *controller) matchevent(event events.Message) bool {
  455. if event.Type != events.ContainerEventType {
  456. return false
  457. }
  458. // TODO(stevvooe): Filter based on ID matching, in addition to name.
  459. // Make sure the events are for this container.
  460. if event.Actor.Attributes["name"] != r.adapter.container.name() {
  461. return false
  462. }
  463. return true
  464. }
  465. func (r *controller) checkClosed() error {
  466. select {
  467. case <-r.closed:
  468. return r.err
  469. default:
  470. return nil
  471. }
  472. }
  473. func parseContainerStatus(ctnr types.ContainerJSON) (*api.ContainerStatus, error) {
  474. status := &api.ContainerStatus{
  475. ContainerID: ctnr.ID,
  476. PID: int32(ctnr.State.Pid),
  477. ExitCode: int32(ctnr.State.ExitCode),
  478. }
  479. return status, nil
  480. }
  481. func parsePortStatus(ctnr types.ContainerJSON) (*api.PortStatus, error) {
  482. status := &api.PortStatus{}
  483. if ctnr.NetworkSettings != nil && len(ctnr.NetworkSettings.Ports) > 0 {
  484. exposedPorts, err := parsePortMap(ctnr.NetworkSettings.Ports)
  485. if err != nil {
  486. return nil, err
  487. }
  488. status.Ports = exposedPorts
  489. }
  490. return status, nil
  491. }
  492. func parsePortMap(portMap nat.PortMap) ([]*api.PortConfig, error) {
  493. exposedPorts := make([]*api.PortConfig, 0, len(portMap))
  494. for portProtocol, mapping := range portMap {
  495. parts := strings.SplitN(string(portProtocol), "/", 2)
  496. if len(parts) != 2 {
  497. return nil, fmt.Errorf("invalid port mapping: %s", portProtocol)
  498. }
  499. port, err := strconv.ParseUint(parts[0], 10, 16)
  500. if err != nil {
  501. return nil, err
  502. }
  503. protocol := api.ProtocolTCP
  504. switch strings.ToLower(parts[1]) {
  505. case "tcp":
  506. protocol = api.ProtocolTCP
  507. case "udp":
  508. protocol = api.ProtocolUDP
  509. default:
  510. return nil, fmt.Errorf("invalid protocol: %s", parts[1])
  511. }
  512. for _, binding := range mapping {
  513. hostPort, err := strconv.ParseUint(binding.HostPort, 10, 16)
  514. if err != nil {
  515. return nil, err
  516. }
  517. // TODO(aluzzardi): We're losing the port `name` here since
  518. // there's no way to retrieve it back from the Engine.
  519. exposedPorts = append(exposedPorts, &api.PortConfig{
  520. PublishMode: api.PublishModeHost,
  521. Protocol: protocol,
  522. TargetPort: uint32(port),
  523. PublishedPort: uint32(hostPort),
  524. })
  525. }
  526. }
  527. return exposedPorts, nil
  528. }
  529. type exitError struct {
  530. code int
  531. cause error
  532. }
  533. func (e *exitError) Error() string {
  534. if e.cause != nil {
  535. return fmt.Sprintf("task: non-zero exit (%v): %v", e.code, e.cause)
  536. }
  537. return fmt.Sprintf("task: non-zero exit (%v)", e.code)
  538. }
  539. func (e *exitError) ExitCode() int {
  540. return int(e.code)
  541. }
  542. func (e *exitError) Cause() error {
  543. return e.cause
  544. }
  545. // checkHealth blocks until unhealthy container is detected or ctx exits
  546. func (r *controller) checkHealth(ctx context.Context) error {
  547. eventq := r.adapter.events(ctx)
  548. for {
  549. select {
  550. case <-ctx.Done():
  551. return nil
  552. case <-r.closed:
  553. return nil
  554. case event := <-eventq:
  555. if !r.matchevent(event) {
  556. continue
  557. }
  558. switch event.Action {
  559. case "health_status: unhealthy":
  560. return ErrContainerUnhealthy
  561. }
  562. }
  563. }
  564. }