backend.go 7.7 KB

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