backend.go 5.6 KB

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