backend.go 6.9 KB

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