backend.go 7.6 KB

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