discovery.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. "context"
  16. "fmt"
  17. "strings"
  18. "time"
  19. "github.com/docker/cli/cli/command"
  20. )
  21. // engineLabelDesktopAddress is used to detect that Compose is running with a
  22. // Docker Desktop context. When this label is present, the value is an endpoint
  23. // address for an in-memory socket (AF_UNIX or named pipe).
  24. const engineLabelDesktopAddress = "com.docker.desktop.address"
  25. // NewFromDockerClient creates a Desktop Client using the Docker CLI client to
  26. // auto-discover the Desktop CLI socket endpoint (if available).
  27. //
  28. // An error is returned if there is a failure communicating with Docker Desktop,
  29. // but even on success, a nil Client can be returned if the active Docker Engine
  30. // is not a Desktop instance.
  31. func NewFromDockerClient(ctx context.Context, dockerCli command.Cli) (*Client, error) {
  32. // safeguard to make sure this doesn't get stuck indefinitely
  33. ctx, cancel := context.WithTimeout(ctx, time.Second)
  34. defer cancel()
  35. info, err := dockerCli.Client().Info(ctx)
  36. if err != nil {
  37. return nil, fmt.Errorf("querying server info: %w", err)
  38. }
  39. for _, l := range info.Labels {
  40. k, v, ok := strings.Cut(l, "=")
  41. if !ok || k != engineLabelDesktopAddress {
  42. continue
  43. }
  44. desktopCli := NewClient(v)
  45. _, err := desktopCli.Ping(ctx)
  46. if err != nil {
  47. return nil, fmt.Errorf("pinging Desktop API: %w", err)
  48. }
  49. return desktopCli, nil
  50. }
  51. return nil, nil
  52. }