builder: handle host-gateway with extra hosts

Signed-off-by: CrazyMax <crazy-max@users.noreply.github.com>
(cherry picked from commit 521b8c02cc)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
This commit is contained in:
CrazyMax 2022-11-25 21:22:04 +01:00 committed by Sebastiaan van Stijn
parent 6112b23b36
commit 877a5e6867
No known key found for this signature in database
GPG key ID: 76698F39D527CE8C

View file

@ -17,6 +17,7 @@ import (
"github.com/docker/docker/builder"
"github.com/docker/docker/daemon/config"
"github.com/docker/docker/daemon/images"
"github.com/docker/docker/opts"
"github.com/docker/docker/pkg/idtools"
"github.com/docker/docker/pkg/streamformatter"
"github.com/docker/docker/pkg/system"
@ -81,6 +82,7 @@ type Opt struct {
// Builder can build using BuildKit backend
type Builder struct {
controller *control.Controller
dnsconfig config.DNSConfig
reqBodyHandler *reqBodyHandler
mu sync.Mutex
@ -101,6 +103,7 @@ func New(opt Opt) (*Builder, error) {
}
b := &Builder{
controller: c,
dnsconfig: opt.DNSConfig,
reqBodyHandler: reqHandler,
jobs: map[string]*buildJob{},
}
@ -317,7 +320,7 @@ func (b *Builder) Build(ctx context.Context, opt backend.BuildConfig) (*builder.
return nil, errors.Errorf("network mode %q not supported by buildkit", opt.Options.NetworkMode)
}
extraHosts, err := toBuildkitExtraHosts(opt.Options.ExtraHosts)
extraHosts, err := toBuildkitExtraHosts(opt.Options.ExtraHosts, b.dnsconfig.HostGatewayIP)
if err != nil {
return nil, err
}
@ -546,18 +549,28 @@ func (j *buildJob) SetUpload(ctx context.Context, rc io.ReadCloser) error {
}
// toBuildkitExtraHosts converts hosts from docker key:value format to buildkit's csv format
func toBuildkitExtraHosts(inp []string) (string, error) {
func toBuildkitExtraHosts(inp []string, hostGatewayIP net.IP) (string, error) {
if len(inp) == 0 {
return "", nil
}
hosts := make([]string, 0, len(inp))
for _, h := range inp {
parts := strings.Split(h, ":")
if len(parts) != 2 || parts[0] == "" || net.ParseIP(parts[1]) == nil {
host, ip, ok := strings.Cut(h, ":")
if !ok || host == "" || ip == "" {
return "", errors.Errorf("invalid host %s", h)
}
hosts = append(hosts, parts[0]+"="+parts[1])
// If the IP Address is a "host-gateway", replace this value with the
// IP address stored in the daemon level HostGatewayIP config variable.
if ip == opts.HostGatewayName {
gateway := hostGatewayIP.String()
if gateway == "" {
return "", fmt.Errorf("unable to derive the IP value for host-gateway")
}
ip = gateway
} else if net.ParseIP(ip) == nil {
return "", fmt.Errorf("invalid host %s", h)
}
hosts = append(hosts, host+"="+ip)
}
return strings.Join(hosts, ","), nil
}