containers.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  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. )
  32. type containerService struct {
  33. apiClient *client.Client
  34. }
  35. func (cs *containerService) Inspect(ctx context.Context, id string) (containers.Container, error) {
  36. c, err := cs.apiClient.ContainerInspect(ctx, id)
  37. if err != nil {
  38. return containers.Container{}, err
  39. }
  40. status := ""
  41. if c.State != nil {
  42. status = c.State.Status
  43. }
  44. command := ""
  45. if c.Config != nil &&
  46. c.Config.Cmd != nil {
  47. command = strings.Join(c.Config.Cmd, " ")
  48. }
  49. rc := toRuntimeConfig(&c)
  50. hc := toHostConfig(&c)
  51. return containers.Container{
  52. ID: stringid.TruncateID(c.ID),
  53. Status: status,
  54. Image: c.Image,
  55. Command: command,
  56. Platform: c.Platform,
  57. Config: rc,
  58. HostConfig: hc,
  59. }, nil
  60. }
  61. func (cs *containerService) List(ctx context.Context, all bool) ([]containers.Container, error) {
  62. css, err := cs.apiClient.ContainerList(ctx, types.ContainerListOptions{
  63. All: all,
  64. })
  65. if err != nil {
  66. return []containers.Container{}, err
  67. }
  68. var result []containers.Container
  69. for _, container := range css {
  70. result = append(result, containers.Container{
  71. ID: stringid.TruncateID(container.ID),
  72. Image: container.Image,
  73. // TODO: `Status` is a human readable string ("Up 24 minutes"),
  74. // we need to return the `State` instead but first we need to
  75. // define an enum on the proto side with all the possible container
  76. // statuses. We also need to add a `Created` property on the gRPC side.
  77. Status: container.Status,
  78. Command: container.Command,
  79. Ports: toPorts(container.Ports),
  80. })
  81. }
  82. return result, nil
  83. }
  84. func (cs *containerService) Run(ctx context.Context, r containers.ContainerConfig) error {
  85. exposedPorts, hostBindings, err := fromPorts(r.Ports)
  86. if err != nil {
  87. return err
  88. }
  89. var mounts []mount.Mount
  90. for _, v := range r.Volumes {
  91. tokens := strings.Split(v, ":")
  92. if len(tokens) != 2 {
  93. return errors.Wrapf(errdefs.ErrParsingFailed, "volume %q has invalid format", v)
  94. }
  95. src := tokens[0]
  96. tgt := tokens[1]
  97. mounts = append(mounts, mount.Mount{Type: "volume", Source: src, Target: tgt})
  98. }
  99. containerConfig := &container.Config{
  100. Image: r.Image,
  101. Cmd: r.Command,
  102. Labels: r.Labels,
  103. Env: r.Environment,
  104. ExposedPorts: exposedPorts,
  105. }
  106. hostConfig := &container.HostConfig{
  107. PortBindings: hostBindings,
  108. Mounts: mounts,
  109. AutoRemove: r.AutoRemove,
  110. RestartPolicy: toRestartPolicy(r.RestartPolicyCondition),
  111. Resources: container.Resources{
  112. NanoCPUs: int64(r.CPULimit * 1e9),
  113. Memory: int64(r.MemLimit),
  114. },
  115. }
  116. id, err := cs.create(ctx, containerConfig, hostConfig, nil, r.Platform, r.ID)
  117. if err != nil {
  118. return err
  119. }
  120. return cs.apiClient.ContainerStart(ctx, id, types.ContainerStartOptions{})
  121. }
  122. func (cs *containerService) create(ctx context.Context,
  123. containerConfig *container.Config,
  124. hostConfig *container.HostConfig,
  125. networkingConfig *network.NetworkingConfig,
  126. platform *specs.Platform, name string) (string, error) {
  127. created, err := cs.apiClient.ContainerCreate(ctx, containerConfig, hostConfig, networkingConfig, platform, name)
  128. if err != nil {
  129. if client.IsErrNotFound(err) {
  130. io, err := cs.apiClient.ImagePull(ctx, containerConfig.Image, types.ImagePullOptions{})
  131. if err != nil {
  132. return "", err
  133. }
  134. scanner := bufio.NewScanner(io)
  135. // Read the whole body, otherwise the pulling stops
  136. for scanner.Scan() {
  137. }
  138. if err = scanner.Err(); err != nil {
  139. return "", err
  140. }
  141. if err = io.Close(); err != nil {
  142. return "", err
  143. }
  144. created, err = cs.apiClient.ContainerCreate(ctx, containerConfig, hostConfig, networkingConfig, platform, name)
  145. if err != nil {
  146. return "", err
  147. }
  148. } else {
  149. return "", err
  150. }
  151. }
  152. return created.ID, nil
  153. }
  154. func (cs *containerService) Start(ctx context.Context, containerID string) error {
  155. return cs.apiClient.ContainerStart(ctx, containerID, types.ContainerStartOptions{})
  156. }
  157. func (cs *containerService) Stop(ctx context.Context, containerID string, timeout *uint32) error {
  158. var t *time.Duration
  159. if timeout != nil {
  160. timeoutValue := time.Duration(*timeout) * time.Second
  161. t = &timeoutValue
  162. }
  163. return cs.apiClient.ContainerStop(ctx, containerID, t)
  164. }
  165. func (cs *containerService) Kill(ctx context.Context, containerID string, signal string) error {
  166. return cs.apiClient.ContainerKill(ctx, containerID, signal)
  167. }
  168. func (cs *containerService) Exec(ctx context.Context, name string, request containers.ExecRequest) error {
  169. cec, err := cs.apiClient.ContainerExecCreate(ctx, name, types.ExecConfig{
  170. Cmd: []string{request.Command},
  171. Tty: true,
  172. AttachStdin: true,
  173. AttachStdout: true,
  174. AttachStderr: true,
  175. })
  176. if err != nil {
  177. return err
  178. }
  179. resp, err := cs.apiClient.ContainerExecAttach(ctx, cec.ID, types.ExecStartCheck{
  180. Tty: true,
  181. })
  182. if err != nil {
  183. return err
  184. }
  185. defer resp.Close()
  186. readChannel := make(chan error, 10)
  187. writeChannel := make(chan error, 10)
  188. go func() {
  189. _, err := io.Copy(request.Stdout, resp.Reader)
  190. readChannel <- err
  191. }()
  192. go func() {
  193. _, err := io.Copy(resp.Conn, request.Stdin)
  194. writeChannel <- err
  195. }()
  196. for {
  197. select {
  198. case err := <-readChannel:
  199. return err
  200. case err := <-writeChannel:
  201. return err
  202. }
  203. }
  204. }
  205. func (cs *containerService) Logs(ctx context.Context, containerName string, request containers.LogsRequest) error {
  206. c, err := cs.apiClient.ContainerInspect(ctx, containerName)
  207. if err != nil {
  208. return err
  209. }
  210. r, err := cs.apiClient.ContainerLogs(ctx, containerName, types.ContainerLogsOptions{
  211. ShowStdout: true,
  212. ShowStderr: true,
  213. Follow: request.Follow,
  214. })
  215. if err != nil {
  216. return err
  217. }
  218. // nolint errcheck
  219. defer r.Close()
  220. if c.Config.Tty {
  221. _, err = io.Copy(request.Writer, r)
  222. } else {
  223. _, err = stdcopy.StdCopy(request.Writer, request.Writer, r)
  224. }
  225. return err
  226. }
  227. func (cs *containerService) Delete(ctx context.Context, containerID string, request containers.DeleteRequest) error {
  228. err := cs.apiClient.ContainerRemove(ctx, containerID, types.ContainerRemoveOptions{
  229. Force: request.Force,
  230. })
  231. if client.IsErrNotFound(err) {
  232. return errors.Wrapf(errdefs.ErrNotFound, "container %q", containerID)
  233. }
  234. return err
  235. }