backend.go 6.4 KB

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