diff --git a/libnetwork/etchosts/etchosts.go b/libnetwork/etchosts/etchosts.go index 5f68372b90..99ea5dec77 100644 --- a/libnetwork/etchosts/etchosts.go +++ b/libnetwork/etchosts/etchosts.go @@ -8,6 +8,7 @@ import ( "io/ioutil" "os" "regexp" + "strings" "sync" ) @@ -78,10 +79,17 @@ func Build(path, IP, hostname, domainname string, extraContent []Record) error { //set main record var mainRec Record mainRec.IP = IP + // User might have provided a FQDN in hostname or split it across hostname + // and domainname. We want the FQDN and the bare hostname. + fqdn := hostname if domainname != "" { - mainRec.Hosts = fmt.Sprintf("%s.%s %s", hostname, domainname, hostname) + fqdn = fmt.Sprintf("%s.%s", fqdn, domainname) + } + parts := strings.SplitN(fqdn, ".", 2) + if len(parts) == 2 { + mainRec.Hosts = fmt.Sprintf("%s %s", fqdn, parts[0]) } else { - mainRec.Hosts = hostname + mainRec.Hosts = fqdn } if _, err := mainRec.WriteTo(content); err != nil { return err diff --git a/libnetwork/etchosts/etchosts_test.go b/libnetwork/etchosts/etchosts_test.go index 2a0a4f6d68..f897096da5 100644 --- a/libnetwork/etchosts/etchosts_test.go +++ b/libnetwork/etchosts/etchosts_test.go @@ -81,6 +81,28 @@ func TestBuildHostname(t *testing.T) { } } +func TestBuildHostnameFQDN(t *testing.T) { + file, err := ioutil.TempFile("", "") + if err != nil { + t.Fatal(err) + } + defer os.Remove(file.Name()) + + err = Build(file.Name(), "10.11.12.13", "testhostname.testdomainname.com", "", nil) + if err != nil { + t.Fatal(err) + } + + content, err := ioutil.ReadFile(file.Name()) + if err != nil { + t.Fatal(err) + } + + if expected := "10.11.12.13\ttesthostname.testdomainname.com testhostname\n"; !bytes.Contains(content, []byte(expected)) { + t.Fatalf("Expected to find '%s' got '%s'", expected, content) + } +} + func TestBuildNoIP(t *testing.T) { file, err := ioutil.TempFile("", "") if err != nil {