containers.go 7.0 KB

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