containers.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  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/api/types/network"
  25. "github.com/docker/docker/client"
  26. "github.com/docker/docker/pkg/stdcopy"
  27. "github.com/docker/docker/pkg/stringid"
  28. specs "github.com/opencontainers/image-spec/specs-go/v1"
  29. "github.com/pkg/errors"
  30. "github.com/docker/compose-cli/api/containers"
  31. "github.com/docker/compose-cli/errdefs"
  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 := toRuntimeConfig(&c)
  51. hc := 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: 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 := 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: 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, containerConfig *container.Config, hostConfig *container.HostConfig, networkingConfig *network.NetworkingConfig, platform *specs.Platform, name string) (string, error) {
  124. created, err := cs.apiClient.ContainerCreate(ctx, containerConfig, hostConfig, networkingConfig, platform, name)
  125. if err != nil {
  126. if client.IsErrNotFound(err) {
  127. io, err := cs.apiClient.ImagePull(ctx, containerConfig.Image, types.ImagePullOptions{})
  128. if err != nil {
  129. return "", err
  130. }
  131. scanner := bufio.NewScanner(io)
  132. // Read the whole body, otherwise the pulling stops
  133. for scanner.Scan() {
  134. }
  135. if err = scanner.Err(); err != nil {
  136. return "", err
  137. }
  138. if err = io.Close(); err != nil {
  139. return "", err
  140. }
  141. created, err = cs.apiClient.ContainerCreate(ctx, containerConfig, hostConfig, networkingConfig, platform, name)
  142. if err != nil {
  143. return "", err
  144. }
  145. } else {
  146. return "", err
  147. }
  148. }
  149. return created.ID, nil
  150. }
  151. func (cs *containerService) Start(ctx context.Context, containerID string) error {
  152. return cs.apiClient.ContainerStart(ctx, containerID, types.ContainerStartOptions{})
  153. }
  154. func (cs *containerService) Stop(ctx context.Context, containerID string, timeout *uint32) error {
  155. var t *time.Duration
  156. if timeout != nil {
  157. timeoutValue := time.Duration(*timeout) * time.Second
  158. t = &timeoutValue
  159. }
  160. return cs.apiClient.ContainerStop(ctx, containerID, t)
  161. }
  162. func (cs *containerService) Kill(ctx context.Context, containerID string, signal string) error {
  163. return cs.apiClient.ContainerKill(ctx, containerID, signal)
  164. }
  165. func (cs *containerService) Exec(ctx context.Context, name string, request containers.ExecRequest) error {
  166. cec, err := cs.apiClient.ContainerExecCreate(ctx, name, types.ExecConfig{
  167. Cmd: []string{request.Command},
  168. Tty: true,
  169. AttachStdin: true,
  170. AttachStdout: true,
  171. AttachStderr: true,
  172. })
  173. if err != nil {
  174. return err
  175. }
  176. resp, err := cs.apiClient.ContainerExecAttach(ctx, cec.ID, types.ExecStartCheck{
  177. Tty: true,
  178. })
  179. if err != nil {
  180. return err
  181. }
  182. defer resp.Close()
  183. readChannel := make(chan error, 10)
  184. writeChannel := make(chan error, 10)
  185. go func() {
  186. _, err := io.Copy(request.Stdout, resp.Reader)
  187. readChannel <- err
  188. }()
  189. go func() {
  190. _, err := io.Copy(resp.Conn, request.Stdin)
  191. writeChannel <- err
  192. }()
  193. for {
  194. select {
  195. case err := <-readChannel:
  196. return err
  197. case err := <-writeChannel:
  198. return err
  199. }
  200. }
  201. }
  202. func (cs *containerService) Logs(ctx context.Context, containerName string, request containers.LogsRequest) error {
  203. c, err := cs.apiClient.ContainerInspect(ctx, containerName)
  204. if err != nil {
  205. return err
  206. }
  207. r, err := cs.apiClient.ContainerLogs(ctx, containerName, types.ContainerLogsOptions{
  208. ShowStdout: true,
  209. ShowStderr: true,
  210. Follow: request.Follow,
  211. })
  212. if err != nil {
  213. return err
  214. }
  215. // nolint errcheck
  216. defer r.Close()
  217. if c.Config.Tty {
  218. _, err = io.Copy(request.Writer, r)
  219. } else {
  220. _, err = stdcopy.StdCopy(request.Writer, request.Writer, r)
  221. }
  222. return err
  223. }
  224. func (cs *containerService) Delete(ctx context.Context, containerID string, request containers.DeleteRequest) error {
  225. err := cs.apiClient.ContainerRemove(ctx, containerID, types.ContainerRemoveOptions{
  226. Force: request.Force,
  227. })
  228. if client.IsErrNotFound(err) {
  229. return errors.Wrapf(errdefs.ErrNotFound, "container %q", containerID)
  230. }
  231. return err
  232. }