containers.go 7.2 KB

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