mirror of
https://github.com/k3s-io/kubernetes.git
synced 2025-09-21 01:50:55 +00:00
nodes: improve handling of erroneous host names
This commit is contained in:
@@ -19,7 +19,6 @@ go_library(
|
||||
"//staging/src/k8s.io/apimachinery/pkg/util/strategicpatch:go_default_library",
|
||||
"//staging/src/k8s.io/client-go/kubernetes:go_default_library",
|
||||
"//staging/src/k8s.io/client-go/kubernetes/typed/core/v1:go_default_library",
|
||||
"//vendor/github.com/golang/glog:go_default_library",
|
||||
],
|
||||
)
|
||||
|
||||
|
@@ -24,7 +24,6 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/golang/glog"
|
||||
"k8s.io/api/core/v1"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"k8s.io/apimachinery/pkg/types"
|
||||
@@ -43,16 +42,23 @@ const (
|
||||
)
|
||||
|
||||
// GetHostname returns OS's hostname if 'hostnameOverride' is empty; otherwise, return 'hostnameOverride'.
|
||||
func GetHostname(hostnameOverride string) string {
|
||||
hostname := hostnameOverride
|
||||
if hostname == "" {
|
||||
nodename, err := os.Hostname()
|
||||
func GetHostname(hostnameOverride string) (string, error) {
|
||||
hostName := hostnameOverride
|
||||
if len(hostName) == 0 {
|
||||
nodeName, err := os.Hostname()
|
||||
if err != nil {
|
||||
glog.Fatalf("Couldn't determine hostname: %v", err)
|
||||
return "", fmt.Errorf("couldn't determine hostname: %v", err)
|
||||
}
|
||||
hostname = nodename
|
||||
hostName = nodeName
|
||||
}
|
||||
return strings.ToLower(strings.TrimSpace(hostname))
|
||||
|
||||
// Trim whitespaces first to avoid getting an empty hostname
|
||||
// For linux, the hostname is read from file /proc/sys/kernel/hostname directly
|
||||
hostName = strings.TrimSpace(hostName)
|
||||
if len(hostName) == 0 {
|
||||
return "", fmt.Errorf("empty hostname is invalid")
|
||||
}
|
||||
return strings.ToLower(hostName), nil
|
||||
}
|
||||
|
||||
// GetPreferredNodeAddress returns the address of the provided node, using the provided preference order.
|
||||
|
@@ -89,3 +89,35 @@ func TestGetPreferredAddress(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetHostname(t *testing.T) {
|
||||
testCases := []struct {
|
||||
hostName string
|
||||
expectedHostName string
|
||||
expectError bool
|
||||
}{
|
||||
{
|
||||
hostName: " ",
|
||||
expectError: true,
|
||||
},
|
||||
{
|
||||
hostName: " abc ",
|
||||
expectedHostName: "abc",
|
||||
expectError: false,
|
||||
},
|
||||
}
|
||||
|
||||
for idx, test := range testCases {
|
||||
hostName, err := GetHostname(test.hostName)
|
||||
if err != nil && !test.expectError {
|
||||
t.Errorf("[%d]: unexpected error: %s", idx, err)
|
||||
}
|
||||
if err == nil && test.expectError {
|
||||
t.Errorf("[%d]: expected error, got none", idx)
|
||||
}
|
||||
if test.expectedHostName != hostName {
|
||||
t.Errorf("[%d]: expected output %q, got %q", idx, test.expectedHostName, hostName)
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user