containers.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  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. Cmd: r.Command,
  101. Labels: r.Labels,
  102. Env: r.Environment,
  103. ExposedPorts: exposedPorts,
  104. }
  105. hostConfig := &container.HostConfig{
  106. PortBindings: hostBindings,
  107. Mounts: mounts,
  108. AutoRemove: r.AutoRemove,
  109. RestartPolicy: toRestartPolicy(r.RestartPolicyCondition),
  110. Resources: container.Resources{
  111. NanoCPUs: int64(r.CPULimit * 1e9),
  112. Memory: int64(r.MemLimit),
  113. },
  114. }
  115. created, err := cs.apiClient.ContainerCreate(ctx, containerConfig, hostConfig, nil, r.ID)
  116. if err != nil {
  117. if client.IsErrNotFound(err) {
  118. io, err := cs.apiClient.ImagePull(ctx, r.Image, types.ImagePullOptions{})
  119. if err != nil {
  120. return err
  121. }
  122. scanner := bufio.NewScanner(io)
  123. // Read the whole body, otherwise the pulling stops
  124. for scanner.Scan() {
  125. }
  126. if err = scanner.Err(); err != nil {
  127. return err
  128. }
  129. if err = io.Close(); err != nil {
  130. return err
  131. }
  132. created, err = cs.apiClient.ContainerCreate(ctx, containerConfig, hostConfig, nil, r.ID)
  133. if err != nil {
  134. return err
  135. }
  136. } else {
  137. return err
  138. }
  139. }
  140. return cs.apiClient.ContainerStart(ctx, created.ID, types.ContainerStartOptions{})
  141. }
  142. func (cs *containerService) Start(ctx context.Context, containerID string) error {
  143. return cs.apiClient.ContainerStart(ctx, containerID, types.ContainerStartOptions{})
  144. }
  145. func (cs *containerService) Stop(ctx context.Context, containerID string, timeout *uint32) error {
  146. var t *time.Duration
  147. if timeout != nil {
  148. timeoutValue := time.Duration(*timeout) * time.Second
  149. t = &timeoutValue
  150. }
  151. return cs.apiClient.ContainerStop(ctx, containerID, t)
  152. }
  153. func (cs *containerService) Kill(ctx context.Context, containerID string, signal string) error {
  154. return cs.apiClient.ContainerKill(ctx, containerID, signal)
  155. }
  156. func (cs *containerService) Exec(ctx context.Context, name string, request containers.ExecRequest) error {
  157. cec, err := cs.apiClient.ContainerExecCreate(ctx, name, types.ExecConfig{
  158. Cmd: []string{request.Command},
  159. Tty: true,
  160. AttachStdin: true,
  161. AttachStdout: true,
  162. AttachStderr: true,
  163. })
  164. if err != nil {
  165. return err
  166. }
  167. resp, err := cs.apiClient.ContainerExecAttach(ctx, cec.ID, types.ExecStartCheck{
  168. Tty: true,
  169. })
  170. if err != nil {
  171. return err
  172. }
  173. defer resp.Close()
  174. readChannel := make(chan error, 10)
  175. writeChannel := make(chan error, 10)
  176. go func() {
  177. _, err := io.Copy(request.Stdout, resp.Reader)
  178. readChannel <- err
  179. }()
  180. go func() {
  181. _, err := io.Copy(resp.Conn, request.Stdin)
  182. writeChannel <- err
  183. }()
  184. for {
  185. select {
  186. case err := <-readChannel:
  187. return err
  188. case err := <-writeChannel:
  189. return err
  190. }
  191. }
  192. }
  193. func (cs *containerService) Logs(ctx context.Context, containerName string, request containers.LogsRequest) error {
  194. c, err := cs.apiClient.ContainerInspect(ctx, containerName)
  195. if err != nil {
  196. return err
  197. }
  198. r, err := cs.apiClient.ContainerLogs(ctx, containerName, types.ContainerLogsOptions{
  199. ShowStdout: true,
  200. ShowStderr: true,
  201. Follow: request.Follow,
  202. })
  203. if err != nil {
  204. return err
  205. }
  206. // nolint errcheck
  207. defer r.Close()
  208. if c.Config.Tty {
  209. _, err = io.Copy(request.Writer, r)
  210. } else {
  211. _, err = stdcopy.StdCopy(request.Writer, request.Writer, r)
  212. }
  213. return err
  214. }
  215. func (cs *containerService) Delete(ctx context.Context, containerID string, request containers.DeleteRequest) error {
  216. err := cs.apiClient.ContainerRemove(ctx, containerID, types.ContainerRemoveOptions{
  217. Force: request.Force,
  218. })
  219. if client.IsErrNotFound(err) {
  220. return errors.Wrapf(errdefs.ErrNotFound, "container %q", containerID)
  221. }
  222. return err
  223. }