|
1 | 1 | package docker |
2 | 2 |
|
3 | 3 | import ( |
| 4 | + "bytes" |
4 | 5 | "context" |
| 6 | + "encoding/json" |
5 | 7 | "errors" |
6 | 8 | "fmt" |
7 | 9 | "io" |
8 | 10 | "net" |
9 | 11 | "os" |
| 12 | + "os/exec" |
10 | 13 | "strconv" |
11 | 14 | "strings" |
12 | 15 |
|
@@ -42,6 +45,21 @@ func NewAPIClient(ctx context.Context, opts ...Option) (*apiClient, error) { |
42 | 45 | opt(clientOptions) |
43 | 46 | } |
44 | 47 |
|
| 48 | + // Check to see if we need to override docker host |
| 49 | + host := os.Getenv("DOCKER_HOST") |
| 50 | + if host == "" { |
| 51 | + inspects, err := findDockerHost() |
| 52 | + if err == nil { |
| 53 | + for _, inspect := range inspects { |
| 54 | + endpoint, ok := inspect.Endpoints["docker"] |
| 55 | + if ok { |
| 56 | + os.Setenv("DOCKER_HOST", endpoint.Host) |
| 57 | + break |
| 58 | + } |
| 59 | + } |
| 60 | + } |
| 61 | + } |
| 62 | + |
45 | 63 | // TODO[md]: we create a client at the top of each cli invocation, the sdk client hits an api which |
46 | 64 | // adds (a tiny biy of) overead. swap this with a handle that'll lazily initialize a client and ping for health. |
47 | 65 | // ditto for fetching registry credentials. |
@@ -610,3 +628,25 @@ func shouldAttachStdin(stdin io.Reader) (attach bool, tty bool) { |
610 | 628 | // the container to attach stdin and keep open |
611 | 629 | return true, true |
612 | 630 | } |
| 631 | + |
| 632 | +func findDockerHost() ([]command.ContextInspect, error) { |
| 633 | + dockerCmd := DockerCommandFromEnvironment() |
| 634 | + cmd := exec.Command(dockerCmd, "context", "inspect") |
| 635 | + |
| 636 | + // Create a buffer to capture the standard output |
| 637 | + var out bytes.Buffer |
| 638 | + cmd.Stdout = &out |
| 639 | + |
| 640 | + // Run the command |
| 641 | + err := cmd.Run() |
| 642 | + if err != nil { |
| 643 | + return nil, err |
| 644 | + } |
| 645 | + |
| 646 | + var resp []command.ContextInspect |
| 647 | + if err := json.Unmarshal(out.Bytes(), &resp); err != nil { |
| 648 | + return nil, fmt.Errorf("error unmarshaling inspect response: %w", err) |
| 649 | + } |
| 650 | + |
| 651 | + return resp, nil |
| 652 | +} |
0 commit comments