Skip to content

Commit b16c1b0

Browse files
authored
Handle overriding docker host if required (#2436)
* Handle overriding docker host if required * Use docker context inspect to find endpoints * Assign these endpoints to the environment variable * Fix lint
1 parent 93be60d commit b16c1b0

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

pkg/docker/api_client.go

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,15 @@
11
package docker
22

33
import (
4+
"bytes"
45
"context"
6+
"encoding/json"
57
"errors"
68
"fmt"
79
"io"
810
"net"
911
"os"
12+
"os/exec"
1013
"strconv"
1114
"strings"
1215

@@ -42,6 +45,21 @@ func NewAPIClient(ctx context.Context, opts ...Option) (*apiClient, error) {
4245
opt(clientOptions)
4346
}
4447

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+
4563
// TODO[md]: we create a client at the top of each cli invocation, the sdk client hits an api which
4664
// adds (a tiny biy of) overead. swap this with a handle that'll lazily initialize a client and ping for health.
4765
// ditto for fetching registry credentials.
@@ -610,3 +628,25 @@ func shouldAttachStdin(stdin io.Reader) (attach bool, tty bool) {
610628
// the container to attach stdin and keep open
611629
return true, true
612630
}
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+
}
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
package command
2+
3+
type Endpoint struct {
4+
Host string `json:"Host"`
5+
SkipTLSVerify bool `json:"SkipTLSVerify"`
6+
}
7+
8+
type ContextInspect struct {
9+
Endpoints map[string]Endpoint `json:"Endpoints"`
10+
}

0 commit comments

Comments
 (0)