backend.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. // +build local
  2. /*
  3. Copyright 2020 Docker, Inc.
  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. "strconv"
  20. "strings"
  21. "time"
  22. "github.com/docker/docker/pkg/stringid"
  23. "github.com/docker/go-connections/nat"
  24. "github.com/docker/docker/api/types"
  25. "github.com/docker/docker/api/types/container"
  26. "github.com/docker/docker/client"
  27. "github.com/docker/docker/pkg/stdcopy"
  28. "github.com/pkg/errors"
  29. "github.com/docker/compose-cli/backend"
  30. "github.com/docker/compose-cli/compose"
  31. "github.com/docker/compose-cli/containers"
  32. "github.com/docker/compose-cli/context/cloud"
  33. "github.com/docker/compose-cli/errdefs"
  34. "github.com/docker/compose-cli/secrets"
  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) Inspect(ctx context.Context, id string) (containers.Container, error) {
  61. c, err := ms.apiClient.ContainerInspect(ctx, id)
  62. if err != nil {
  63. return containers.Container{}, err
  64. }
  65. status := ""
  66. if c.State != nil {
  67. status = c.State.Status
  68. }
  69. command := ""
  70. if c.Config != nil &&
  71. c.Config.Cmd != nil {
  72. command = strings.Join(c.Config.Cmd, " ")
  73. }
  74. return containers.Container{
  75. ID: stringid.TruncateID(c.ID),
  76. Status: status,
  77. Image: c.Image,
  78. Command: command,
  79. Platform: c.Platform,
  80. }, nil
  81. }
  82. func (ms *local) List(ctx context.Context, all bool) ([]containers.Container, error) {
  83. css, err := ms.apiClient.ContainerList(ctx, types.ContainerListOptions{
  84. All: all,
  85. })
  86. if err != nil {
  87. return []containers.Container{}, err
  88. }
  89. var result []containers.Container
  90. for _, container := range css {
  91. result = append(result, containers.Container{
  92. ID: stringid.TruncateID(container.ID),
  93. Image: container.Image,
  94. // TODO: `Status` is a human readable string ("Up 24 minutes"),
  95. // we need to return the `State` instead but first we need to
  96. // define an enum on the proto side with all the possible container
  97. // statuses. We also need to add a `Created` property on the gRPC side.
  98. Status: container.Status,
  99. Command: container.Command,
  100. Ports: toPorts(container.Ports),
  101. })
  102. }
  103. return result, nil
  104. }
  105. func (ms *local) Run(ctx context.Context, r containers.ContainerConfig) error {
  106. exposedPorts, hostBindings, err := fromPorts(r.Ports)
  107. if err != nil {
  108. return err
  109. }
  110. containerConfig := &container.Config{
  111. Image: r.Image,
  112. Labels: r.Labels,
  113. ExposedPorts: exposedPorts,
  114. }
  115. hostConfig := &container.HostConfig{
  116. PortBindings: hostBindings,
  117. }
  118. created, err := ms.apiClient.ContainerCreate(ctx, containerConfig, hostConfig, nil, r.ID)
  119. if err != nil {
  120. if client.IsErrNotFound(err) {
  121. io, err := ms.apiClient.ImagePull(ctx, r.Image, types.ImagePullOptions{})
  122. if err != nil {
  123. return err
  124. }
  125. scanner := bufio.NewScanner(io)
  126. // Read the whole body, otherwise the pulling stops
  127. for scanner.Scan() {
  128. }
  129. if err = scanner.Err(); err != nil {
  130. return err
  131. }
  132. if err = io.Close(); err != nil {
  133. return err
  134. }
  135. created, err = ms.apiClient.ContainerCreate(ctx, containerConfig, hostConfig, nil, r.ID)
  136. if err != nil {
  137. return err
  138. }
  139. } else {
  140. return err
  141. }
  142. }
  143. return ms.apiClient.ContainerStart(ctx, created.ID, types.ContainerStartOptions{})
  144. }
  145. func (ms *local) Start(ctx context.Context, containerID string) error {
  146. return ms.apiClient.ContainerStart(ctx, containerID, types.ContainerStartOptions{})
  147. }
  148. func (ms *local) Stop(ctx context.Context, containerID string, timeout *uint32) error {
  149. var t *time.Duration
  150. if timeout != nil {
  151. timeoutValue := time.Duration(*timeout) * time.Second
  152. t = &timeoutValue
  153. }
  154. return ms.apiClient.ContainerStop(ctx, containerID, t)
  155. }
  156. func (ms *local) Exec(ctx context.Context, name string, request containers.ExecRequest) error {
  157. cec, err := ms.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 := ms.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 (ms *local) Logs(ctx context.Context, containerName string, request containers.LogsRequest) error {
  194. c, err := ms.apiClient.ContainerInspect(ctx, containerName)
  195. if err != nil {
  196. return err
  197. }
  198. r, err := ms.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 (ms *local) Delete(ctx context.Context, containerID string, request containers.DeleteRequest) error {
  216. err := ms.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. }
  224. func toPorts(ports []types.Port) []containers.Port {
  225. result := []containers.Port{}
  226. for _, port := range ports {
  227. result = append(result, containers.Port{
  228. ContainerPort: uint32(port.PrivatePort),
  229. HostPort: uint32(port.PublicPort),
  230. HostIP: port.IP,
  231. Protocol: port.Type,
  232. })
  233. }
  234. return result
  235. }
  236. func fromPorts(ports []containers.Port) (map[nat.Port]struct{}, map[nat.Port][]nat.PortBinding, error) {
  237. var (
  238. exposedPorts = make(map[nat.Port]struct{}, len(ports))
  239. bindings = make(map[nat.Port][]nat.PortBinding)
  240. )
  241. for _, port := range ports {
  242. p, err := nat.NewPort(port.Protocol, strconv.Itoa(int(port.ContainerPort)))
  243. if err != nil {
  244. return nil, nil, err
  245. }
  246. if _, exists := exposedPorts[p]; !exists {
  247. exposedPorts[p] = struct{}{}
  248. }
  249. portBinding := nat.PortBinding{
  250. HostIP: port.HostIP,
  251. HostPort: strconv.Itoa(int(port.HostPort)),
  252. }
  253. bslice, exists := bindings[p]
  254. if !exists {
  255. bslice = []nat.PortBinding{}
  256. }
  257. bindings[p] = append(bslice, portBinding)
  258. }
  259. return exposedPorts, bindings, nil
  260. }