client.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  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 GetFileSharesConfigResponse struct {
  108. Active bool `json:"active"`
  109. Compose struct {
  110. ManageBindMounts bool `json:"manageBindMounts"`
  111. }
  112. }
  113. func (c *Client) GetFileSharesConfig(ctx context.Context) (*GetFileSharesConfigResponse, error) {
  114. req, err := http.NewRequestWithContext(ctx, http.MethodGet, backendURL("/mutagen/file-shares/config"), http.NoBody)
  115. if err != nil {
  116. return nil, err
  117. }
  118. resp, err := c.client.Do(req)
  119. if err != nil {
  120. return nil, err
  121. }
  122. defer func() {
  123. _ = resp.Body.Close()
  124. }()
  125. if resp.StatusCode != http.StatusOK {
  126. return nil, newHTTPStatusCodeError(resp)
  127. }
  128. var ret GetFileSharesConfigResponse
  129. if err := json.NewDecoder(resp.Body).Decode(&ret); err != nil {
  130. return nil, err
  131. }
  132. return &ret, nil
  133. }
  134. type CreateFileShareRequest struct {
  135. HostPath string `json:"hostPath"`
  136. Labels map[string]string `json:"labels,omitempty"`
  137. }
  138. type CreateFileShareResponse struct {
  139. FileShareID string `json:"fileShareID"`
  140. }
  141. func (c *Client) CreateFileShare(ctx context.Context, r CreateFileShareRequest) (*CreateFileShareResponse, error) {
  142. rawBody, _ := json.Marshal(r)
  143. req, err := http.NewRequestWithContext(ctx, http.MethodPost, backendURL("/mutagen/file-shares"), bytes.NewReader(rawBody))
  144. if err != nil {
  145. return nil, err
  146. }
  147. req.Header.Set("Content-Type", "application/json")
  148. resp, err := c.client.Do(req)
  149. if err != nil {
  150. return nil, err
  151. }
  152. defer func() {
  153. _ = resp.Body.Close()
  154. }()
  155. if resp.StatusCode != http.StatusOK {
  156. errBody, _ := io.ReadAll(resp.Body)
  157. return nil, fmt.Errorf("unexpected status code %d: %s", resp.StatusCode, string(errBody))
  158. }
  159. var ret CreateFileShareResponse
  160. if err := json.NewDecoder(resp.Body).Decode(&ret); err != nil {
  161. return nil, err
  162. }
  163. return &ret, nil
  164. }
  165. type FileShareReceiverState struct {
  166. TotalReceivedSize uint64 `json:"totalReceivedSize"`
  167. }
  168. type FileShareEndpoint struct {
  169. Path string `json:"path"`
  170. TotalFileSize uint64 `json:"totalFileSize,omitempty"`
  171. StagingProgress *FileShareReceiverState `json:"stagingProgress"`
  172. }
  173. type FileShareSession struct {
  174. SessionID string `json:"identifier"`
  175. Alpha FileShareEndpoint `json:"alpha"`
  176. Beta FileShareEndpoint `json:"beta"`
  177. Labels map[string]string `json:"labels"`
  178. Status string `json:"status"`
  179. }
  180. func (c *Client) ListFileShares(ctx context.Context) ([]FileShareSession, error) {
  181. req, err := http.NewRequestWithContext(ctx, http.MethodGet, backendURL("/mutagen/file-shares"), http.NoBody)
  182. if err != nil {
  183. return nil, err
  184. }
  185. resp, err := c.client.Do(req)
  186. if err != nil {
  187. return nil, err
  188. }
  189. defer func() {
  190. _ = resp.Body.Close()
  191. }()
  192. if resp.StatusCode != http.StatusOK {
  193. return nil, newHTTPStatusCodeError(resp)
  194. }
  195. var ret []FileShareSession
  196. if err := json.NewDecoder(resp.Body).Decode(&ret); err != nil {
  197. return nil, err
  198. }
  199. return ret, nil
  200. }
  201. func (c *Client) DeleteFileShare(ctx context.Context, id string) error {
  202. req, err := http.NewRequestWithContext(ctx, http.MethodDelete, backendURL("/mutagen/file-shares/"+id), http.NoBody)
  203. if err != nil {
  204. return err
  205. }
  206. resp, err := c.client.Do(req)
  207. if err != nil {
  208. return err
  209. }
  210. defer func() {
  211. _ = resp.Body.Close()
  212. }()
  213. if resp.StatusCode < 200 || resp.StatusCode >= 300 {
  214. return newHTTPStatusCodeError(resp)
  215. }
  216. return nil
  217. }
  218. type EventMessage[T any] struct {
  219. Value T
  220. Error error
  221. }
  222. func newHTTPStatusCodeError(resp *http.Response) error {
  223. r := io.LimitReader(resp.Body, 2048)
  224. body, err := io.ReadAll(r)
  225. if err != nil {
  226. return fmt.Errorf("http status code %d", resp.StatusCode)
  227. }
  228. return fmt.Errorf("http status code %d: %s", resp.StatusCode, string(body))
  229. }
  230. func (c *Client) StreamFileShares(ctx context.Context) (<-chan EventMessage[[]FileShareSession], error) {
  231. req, err := http.NewRequestWithContext(ctx, http.MethodGet, backendURL("/mutagen/file-shares/stream"), http.NoBody)
  232. if err != nil {
  233. return nil, err
  234. }
  235. resp, err := c.client.Do(req)
  236. if err != nil {
  237. return nil, err
  238. }
  239. if resp.StatusCode < 200 || resp.StatusCode >= 300 {
  240. defer func() {
  241. _ = resp.Body.Close()
  242. }()
  243. return nil, newHTTPStatusCodeError(resp)
  244. }
  245. events := make(chan EventMessage[[]FileShareSession])
  246. go func(ctx context.Context) {
  247. defer func() {
  248. _ = resp.Body.Close()
  249. for range events {
  250. // drain the channel
  251. }
  252. close(events)
  253. }()
  254. if err := readEvents(ctx, resp.Body, events); err != nil {
  255. select {
  256. case <-ctx.Done():
  257. case events <- EventMessage[[]FileShareSession]{Error: err}:
  258. }
  259. }
  260. }(ctx)
  261. return events, nil
  262. }
  263. func readEvents[T any](ctx context.Context, r io.Reader, events chan<- EventMessage[T]) error {
  264. eventReader := sse.NewEventStreamReader(r)
  265. for {
  266. msg, err := eventReader.ReadEvent()
  267. if errors.Is(err, io.EOF) {
  268. return nil
  269. } else if err != nil {
  270. return fmt.Errorf("reading events: %w", err)
  271. }
  272. msg = bytes.TrimPrefix(msg, []byte("data: "))
  273. var event T
  274. if err := json.Unmarshal(msg, &event); err != nil {
  275. return err
  276. }
  277. select {
  278. case <-ctx.Done():
  279. return context.Cause(ctx)
  280. case events <- EventMessage[T]{Value: event}:
  281. // event was sent to channel, read next
  282. }
  283. }
  284. }
  285. // backendURL generates a URL for the given API path.
  286. //
  287. // NOTE: Custom transport handles communication. The host is to create a valid
  288. // URL for the Go http.Client that is also descriptive in error/logs.
  289. func backendURL(path string) string {
  290. return "http://docker-desktop/" + strings.TrimPrefix(path, "/")
  291. }