Browse Source

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 <thockin@google.com>
Tim Hockin 9 years ago
parent
commit
92af10a0fe
2 changed files with 32 additions and 2 deletions
  1. 10 2
      libnetwork/etchosts/etchosts.go
  2. 22 0
      libnetwork/etchosts/etchosts_test.go

+ 10 - 2
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

+ 22 - 0
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 {