backend.go 7.0 KB

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