client.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. /*
  2. Copyright 2024 Docker Compose CLI authors
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package desktop
  14. import (
  15. "bytes"
  16. "context"
  17. "encoding/json"
  18. "errors"
  19. "fmt"
  20. "io"
  21. "net"
  22. "net/http"
  23. "strings"
  24. "github.com/docker/compose/v2/internal/memnet"
  25. "github.com/r3labs/sse"
  26. "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
  27. )
  28. // Client for integration with Docker Desktop features.
  29. type Client struct {
  30. apiEndpoint string
  31. client *http.Client
  32. }
  33. // NewClient creates a Desktop integration client for the provided in-memory
  34. // socket address (AF_UNIX or named pipe).
  35. func NewClient(apiEndpoint string) *Client {
  36. var transport http.RoundTripper = &http.Transport{
  37. DisableCompression: true,
  38. DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {
  39. return memnet.DialEndpoint(ctx, apiEndpoint)
  40. },
  41. }
  42. transport = otelhttp.NewTransport(transport)
  43. c := &Client{
  44. apiEndpoint: apiEndpoint,
  45. client: &http.Client{Transport: transport},
  46. }
  47. return c
  48. }
  49. func (c *Client) Endpoint() string {
  50. return c.apiEndpoint
  51. }
  52. // Close releases any open connections.
  53. func (c *Client) Close() error {
  54. c.client.CloseIdleConnections()
  55. return nil
  56. }
  57. type PingResponse struct {
  58. ServerTime int64 `json:"serverTime"`
  59. }
  60. // Ping is a minimal API used to ensure that the server is available.
  61. func (c *Client) Ping(ctx context.Context) (*PingResponse, error) {
  62. req, err := http.NewRequestWithContext(ctx, http.MethodGet, backendURL("/ping"), http.NoBody)
  63. if err != nil {
  64. return nil, err
  65. }
  66. resp, err := c.client.Do(req)
  67. if err != nil {
  68. return nil, err
  69. }
  70. defer func() {
  71. _ = resp.Body.Close()
  72. }()
  73. if resp.StatusCode != http.StatusOK {
  74. return nil, fmt.Errorf("unexpected status code: %d", resp.StatusCode)
  75. }
  76. var ret PingResponse
  77. if err := json.NewDecoder(resp.Body).Decode(&ret); err != nil {
  78. return nil, err
  79. }
  80. return &ret, nil
  81. }
  82. type FeatureFlagResponse map[string]FeatureFlagValue
  83. type FeatureFlagValue struct {
  84. Enabled bool `json:"enabled"`
  85. }
  86. func (c *Client) FeatureFlags(ctx context.Context) (FeatureFlagResponse, error) {
  87. req, err := http.NewRequestWithContext(ctx, http.MethodGet, backendURL("/features"), http.NoBody)
  88. if err != nil {
  89. return nil, err
  90. }
  91. resp, err := c.client.Do(req)
  92. if err != nil {
  93. return nil, err
  94. }
  95. defer func() {
  96. _ = resp.Body.Close()
  97. }()
  98. if resp.StatusCode != http.StatusOK {
  99. return nil, fmt.Errorf("unexpected status code: %d", resp.StatusCode)
  100. }
  101. var ret FeatureFlagResponse
  102. if err := json.NewDecoder(resp.Body).Decode(&ret); err != nil {
  103. return nil, err
  104. }
  105. return ret, nil
  106. }
  107. type CreateFileShareRequest struct {
  108. HostPath string `json:"hostPath"`
  109. Labels map[string]string `json:"labels,omitempty"`
  110. }
  111. type CreateFileShareResponse struct {
  112. FileShareID string `json:"fileShareID"`
  113. }
  114. func (c *Client) CreateFileShare(ctx context.Context, r CreateFileShareRequest) (*CreateFileShareResponse, error) {
  115. rawBody, _ := json.Marshal(r)
  116. req, err := http.NewRequestWithContext(ctx, http.MethodPost, backendURL("/mutagen/file-shares"), bytes.NewReader(rawBody))
  117. req.Header.Set("Content-Type", "application/json")
  118. if err != nil {
  119. return nil, err
  120. }
  121. resp, err := c.client.Do(req)
  122. if err != nil {
  123. return nil, err
  124. }
  125. defer func() {
  126. _ = resp.Body.Close()
  127. }()
  128. if resp.StatusCode != http.StatusOK {
  129. errBody, _ := io.ReadAll(resp.Body)
  130. return nil, fmt.Errorf("unexpected status code %d: %s", resp.StatusCode, string(errBody))
  131. }
  132. var ret CreateFileShareResponse
  133. if err := json.NewDecoder(resp.Body).Decode(&ret); err != nil {
  134. return nil, err
  135. }
  136. return &ret, nil
  137. }
  138. type FileShareReceiverState struct {
  139. TotalReceivedSize uint64 `json:"totalReceivedSize"`
  140. }
  141. type FileShareEndpoint struct {
  142. Path string `json:"path"`
  143. TotalFileSize uint64 `json:"totalFileSize,omitempty"`
  144. StagingProgress *FileShareReceiverState `json:"stagingProgress"`
  145. }
  146. type FileShareSession struct {
  147. SessionID string `json:"identifier"`
  148. Alpha FileShareEndpoint `json:"alpha"`
  149. Beta FileShareEndpoint `json:"beta"`
  150. Labels map[string]string `json:"labels"`
  151. Status string `json:"status"`
  152. }
  153. func (c *Client) ListFileShares(ctx context.Context) ([]FileShareSession, error) {
  154. req, err := http.NewRequestWithContext(ctx, http.MethodGet, backendURL("/mutagen/file-shares"), http.NoBody)
  155. if err != nil {
  156. return nil, err
  157. }
  158. resp, err := c.client.Do(req)
  159. if err != nil {
  160. return nil, err
  161. }
  162. defer func() {
  163. _ = resp.Body.Close()
  164. }()
  165. if resp.StatusCode != http.StatusOK {
  166. return nil, newHTTPStatusCodeError(resp)
  167. }
  168. var ret []FileShareSession
  169. if err := json.NewDecoder(resp.Body).Decode(&ret); err != nil {
  170. return nil, err
  171. }
  172. return ret, nil
  173. }
  174. func (c *Client) DeleteFileShare(ctx context.Context, id string) error {
  175. req, err := http.NewRequestWithContext(ctx, http.MethodDelete, backendURL("/mutagen/file-shares/"+id), http.NoBody)
  176. if err != nil {
  177. return err
  178. }
  179. resp, err := c.client.Do(req)
  180. if err != nil {
  181. return err
  182. }
  183. defer func() {
  184. _ = resp.Body.Close()
  185. }()
  186. if resp.StatusCode < 200 || resp.StatusCode >= 300 {
  187. return newHTTPStatusCodeError(resp)
  188. }
  189. return nil
  190. }
  191. type EventMessage[T any] struct {
  192. Value T
  193. Error error
  194. }
  195. func newHTTPStatusCodeError(resp *http.Response) error {
  196. r := io.LimitReader(resp.Body, 2048)
  197. body, err := io.ReadAll(r)
  198. if err != nil {
  199. return fmt.Errorf("http status code %d", resp.StatusCode)
  200. }
  201. return fmt.Errorf("http status code %d: %s", resp.StatusCode, string(body))
  202. }
  203. func (c *Client) StreamFileShares(ctx context.Context) (<-chan EventMessage[[]FileShareSession], error) {
  204. req, err := http.NewRequestWithContext(ctx, http.MethodGet, backendURL("/mutagen/file-shares/stream"), http.NoBody)
  205. if err != nil {
  206. return nil, err
  207. }
  208. resp, err := c.client.Do(req)
  209. if err != nil {
  210. return nil, err
  211. }
  212. if resp.StatusCode < 200 || resp.StatusCode >= 300 {
  213. defer func() {
  214. _ = resp.Body.Close()
  215. }()
  216. return nil, newHTTPStatusCodeError(resp)
  217. }
  218. events := make(chan EventMessage[[]FileShareSession])
  219. go func(ctx context.Context) {
  220. defer func() {
  221. _ = resp.Body.Close()
  222. for range events {
  223. // drain the channel
  224. }
  225. close(events)
  226. }()
  227. if err := readEvents(ctx, resp.Body, events); err != nil {
  228. select {
  229. case <-ctx.Done():
  230. case events <- EventMessage[[]FileShareSession]{Error: err}:
  231. }
  232. }
  233. }(ctx)
  234. return events, nil
  235. }
  236. func readEvents[T any](ctx context.Context, r io.Reader, events chan<- EventMessage[T]) error {
  237. eventReader := sse.NewEventStreamReader(r)
  238. for {
  239. msg, err := eventReader.ReadEvent()
  240. if errors.Is(err, io.EOF) {
  241. return nil
  242. } else if err != nil {
  243. return fmt.Errorf("reading events: %w", err)
  244. }
  245. msg = bytes.TrimPrefix(msg, []byte("data: "))
  246. var event T
  247. if err := json.Unmarshal(msg, &event); err != nil {
  248. return err
  249. }
  250. select {
  251. case <-ctx.Done():
  252. return context.Cause(ctx)
  253. case events <- EventMessage[T]{Value: event}:
  254. // event was sent to channel, read next
  255. }
  256. }
  257. }
  258. // backendURL generates a URL for the given API path.
  259. //
  260. // NOTE: Custom transport handles communication. The host is to create a valid
  261. // URL for the Go http.Client that is also descriptive in error/logs.
  262. func backendURL(path string) string {
  263. return "http://docker-desktop/" + strings.TrimPrefix(path, "/")
  264. }