containers.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. // +build local
  2. /*
  3. Copyright 2020 Docker Compose CLI authors
  4. Licensed under the Apache License, Version 2.0 (the "License");
  5. you may not use this file except in compliance with the License.
  6. You may obtain a copy of the License at
  7. http://www.apache.org/licenses/LICENSE-2.0
  8. Unless required by applicable law or agreed to in writing, software
  9. distributed under the License is distributed on an "AS IS" BASIS,
  10. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. See the License for the specific language governing permissions and
  12. limitations under the License.
  13. */
  14. package local
  15. import (
  16. "bufio"
  17. "context"
  18. "io"
  19. "strings"
  20. "time"
  21. "github.com/docker/docker/api/types"
  22. "github.com/docker/docker/api/types/container"
  23. "github.com/docker/docker/api/types/mount"
  24. "github.com/docker/docker/client"
  25. "github.com/docker/docker/pkg/stdcopy"
  26. "github.com/docker/docker/pkg/stringid"
  27. "github.com/pkg/errors"
  28. "github.com/docker/compose-cli/api/containers"
  29. "github.com/docker/compose-cli/errdefs"
  30. )
  31. type containerService struct {
  32. apiClient *client.Client
  33. }
  34. func (cs *containerService) Inspect(ctx context.Context, id string) (containers.Container, error) {
  35. c, err := cs.apiClient.ContainerInspect(ctx, id)
  36. if err != nil {
  37. return containers.Container{}, err
  38. }
  39. status := ""
  40. if c.State != nil {
  41. status = c.State.Status
  42. }
  43. command := ""
  44. if c.Config != nil &&
  45. c.Config.Cmd != nil {
  46. command = strings.Join(c.Config.Cmd, " ")
  47. }
  48. rc := toRuntimeConfig(&c)
  49. hc := toHostConfig(&c)
  50. return containers.Container{
  51. ID: stringid.TruncateID(c.ID),
  52. Status: status,
  53. Image: c.Image,
  54. Command: command,
  55. Platform: c.Platform,
  56. Config: rc,
  57. HostConfig: hc,
  58. }, nil
  59. }
  60. func (cs *containerService) List(ctx context.Context, all bool) ([]containers.Container, error) {
  61. css, err := cs.apiClient.ContainerList(ctx, types.ContainerListOptions{
  62. All: all,
  63. })
  64. if err != nil {
  65. return []containers.Container{}, err
  66. }
  67. var result []containers.Container
  68. for _, container := range css {
  69. result = append(result, containers.Container{
  70. ID: stringid.TruncateID(container.ID),
  71. Image: container.Image,
  72. // TODO: `Status` is a human readable string ("Up 24 minutes"),
  73. // we need to return the `State` instead but first we need to
  74. // define an enum on the proto side with all the possible container
  75. // statuses. We also need to add a `Created` property on the gRPC side.
  76. Status: container.Status,
  77. Command: container.Command,
  78. Ports: toPorts(container.Ports),
  79. })
  80. }
  81. return result, nil
  82. }
  83. func (cs *containerService) Run(ctx context.Context, r containers.ContainerConfig) error {
  84. exposedPorts, hostBindings, err := fromPorts(r.Ports)
  85. if err != nil {
  86. return err
  87. }
  88. var mounts []mount.Mount
  89. for _, v := range r.Volumes {
  90. tokens := strings.Split(v, ":")
  91. if len(tokens) != 2 {
  92. return errors.Wrapf(errdefs.ErrParsingFailed, "volume %q has invalid format", v)
  93. }
  94. src := tokens[0]
  95. tgt := tokens[1]
  96. mounts = append(mounts, mount.Mount{Type: "volume", Source: src, Target: tgt})
  97. }
  98. containerConfig := &container.Config{
  99. Image: r.Image,
  100. Labels: r.Labels,
  101. Env: r.Environment,
  102. ExposedPorts: exposedPorts,
  103. }
  104. hostConfig := &container.HostConfig{
  105. PortBindings: hostBindings,
  106. Mounts: mounts,
  107. AutoRemove: r.AutoRemove,
  108. RestartPolicy: toRestartPolicy(r.RestartPolicyCondition),
  109. Resources: container.Resources{
  110. NanoCPUs: int64(r.CPULimit * 1e9),
  111. Memory: int64(r.MemLimit),
  112. },
  113. }
  114. created, err := cs.apiClient.ContainerCreate(ctx, containerConfig, hostConfig, nil, r.ID)
  115. if err != nil {
  116. if client.IsErrNotFound(err) {
  117. io, err := cs.apiClient.ImagePull(ctx, r.Image, types.ImagePullOptions{})
  118. if err != nil {
  119. return err
  120. }
  121. scanner := bufio.NewScanner(io)
  122. // Read the whole body, otherwise the pulling stops
  123. for scanner.Scan() {
  124. }
  125. if err = scanner.Err(); err != nil {
  126. return err
  127. }
  128. if err = io.Close(); err != nil {
  129. return err
  130. }
  131. created, err = cs.apiClient.ContainerCreate(ctx, containerConfig, hostConfig, nil, r.ID)
  132. if err != nil {
  133. return err
  134. }
  135. } else {
  136. return err
  137. }
  138. }
  139. return cs.apiClient.ContainerStart(ctx, created.ID, types.ContainerStartOptions{})
  140. }
  141. func (cs *containerService) Start(ctx context.Context, containerID string) error {
  142. return cs.apiClient.ContainerStart(ctx, containerID, types.ContainerStartOptions{})
  143. }
  144. func (cs *containerService) Stop(ctx context.Context, containerID string, timeout *uint32) error {
  145. var t *time.Duration
  146. if timeout != nil {
  147. timeoutValue := time.Duration(*timeout) * time.Second
  148. t = &timeoutValue
  149. }
  150. return cs.apiClient.ContainerStop(ctx, containerID, t)
  151. }
  152. func (cs *containerService) Kill(ctx context.Context, containerID string, signal string) error {
  153. return cs.apiClient.ContainerKill(ctx, containerID, signal)
  154. }
  155. func (cs *containerService) Exec(ctx context.Context, name string, request containers.ExecRequest) error {
  156. cec, err := cs.apiClient.ContainerExecCreate(ctx, name, types.ExecConfig{
  157. Cmd: []string{request.Command},
  158. Tty: true,
  159. AttachStdin: true,
  160. AttachStdout: true,
  161. AttachStderr: true,
  162. })
  163. if err != nil {
  164. return err
  165. }
  166. resp, err := cs.apiClient.ContainerExecAttach(ctx, cec.ID, types.ExecStartCheck{
  167. Tty: true,
  168. })
  169. if err != nil {
  170. return err
  171. }
  172. defer resp.Close()
  173. readChannel := make(chan error, 10)
  174. writeChannel := make(chan error, 10)
  175. go func() {
  176. _, err := io.Copy(request.Stdout, resp.Reader)
  177. readChannel <- err
  178. }()
  179. go func() {
  180. _, err := io.Copy(resp.Conn, request.Stdin)
  181. writeChannel <- err
  182. }()
  183. for {
  184. select {
  185. case err := <-readChannel:
  186. return err
  187. case err := <-writeChannel:
  188. return err
  189. }
  190. }
  191. }
  192. func (cs *containerService) Logs(ctx context.Context, containerName string, request containers.LogsRequest) error {
  193. c, err := cs.apiClient.ContainerInspect(ctx, containerName)
  194. if err != nil {
  195. return err
  196. }
  197. r, err := cs.apiClient.ContainerLogs(ctx, containerName, types.ContainerLogsOptions{
  198. ShowStdout: true,
  199. ShowStderr: true,
  200. Follow: request.Follow,
  201. })
  202. if err != nil {
  203. return err
  204. }
  205. // nolint errcheck
  206. defer r.Close()
  207. if c.Config.Tty {
  208. _, err = io.Copy(request.Writer, r)
  209. } else {
  210. _, err = stdcopy.StdCopy(request.Writer, request.Writer, r)
  211. }
  212. return err
  213. }
  214. func (cs *containerService) Delete(ctx context.Context, containerID string, request containers.DeleteRequest) error {
  215. err := cs.apiClient.ContainerRemove(ctx, containerID, types.ContainerRemoveOptions{
  216. Force: request.Force,
  217. })
  218. if client.IsErrNotFound(err) {
  219. return errors.Wrapf(errdefs.ErrNotFound, "container %q", containerID)
  220. }
  221. return err
  222. }