From 3ae47f7d2b9328ff47dc5702d834ae9ee296a27b Mon Sep 17 00:00:00 2001 From: Daniel J Walsh Date: Tue, 6 Oct 2020 07:04:18 -0400 Subject: Populate /etc/hosts file when run in a user namespace We do not populate the hostname field with the IP Address when running within a user namespace. Fixes https://github.com/containers/podman/issues/7490 Signed-off-by: Daniel J Walsh --- libpod/container_internal.go | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) (limited to 'libpod/container_internal.go') diff --git a/libpod/container_internal.go b/libpod/container_internal.go index d64d3ab87..4ae571de6 100644 --- a/libpod/container_internal.go +++ b/libpod/container_internal.go @@ -976,6 +976,21 @@ func (c *Container) completeNetworkSetup() error { } } } + // check if we have a bindmount for /etc/hosts + if hostsBindMount, ok := state.BindMounts["/etc/hosts"]; ok && len(c.cniHosts()) > 0 { + ctrHostPath := filepath.Join(c.state.RunDir, "hosts") + if hostsBindMount == ctrHostPath { + // read the existing hosts + b, err := ioutil.ReadFile(hostsBindMount) + if err != nil { + return err + } + if err := ioutil.WriteFile(hostsBindMount, append(b, []byte(c.cniHosts())...), 0644); err != nil { + return err + } + } + } + // check if we have a bindmount for resolv.conf resolvBindMount := state.BindMounts["/etc/resolv.conf"] if len(outResolvConf) < 1 || resolvBindMount == "" || len(c.config.NetNsCtr) > 0 { @@ -997,6 +1012,15 @@ func (c *Container) completeNetworkSetup() error { return ioutil.WriteFile(resolvBindMount, []byte(strings.Join(outResolvConf, "\n")), 0644) } +func (c *Container) cniHosts() string { + var hosts string + if len(c.state.NetworkStatus) > 0 && len(c.state.NetworkStatus[0].IPs) > 0 { + ipAddress := strings.Split(c.state.NetworkStatus[0].IPs[0].Address.String(), "/")[0] + hosts += fmt.Sprintf("%s\t%s %s\n", ipAddress, c.Hostname(), c.Config().Name) + } + return hosts +} + // Initialize a container, creating it in the runtime func (c *Container) init(ctx context.Context, retainRetries bool) error { span, _ := opentracing.StartSpanFromContext(ctx, "init") -- cgit v1.2.3-54-g00ecf