From 92af10a0feef6fa053207030822c6372134f8f94 Mon Sep 17 00:00:00 2001 From: Tim Hockin Date: Sat, 13 Feb 2016 15:37:42 -0800 Subject: [PATCH] Extract hostname from (hostname.domainname) This approach allows the user to provide a FQDN as hostname if that is what they want in their container, or to provide distinct host and domain parts. In both cases we will correctly extract the first token for /etc/hosts. Signed-off-by: Tim Hockin --- libnetwork/etchosts/etchosts.go | 12 ++++++++++-- libnetwork/etchosts/etchosts_test.go | 22 ++++++++++++++++++++++ 2 files changed, 32 insertions(+), 2 deletions(-) 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 {