-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathresolvconf.go
72 lines (62 loc) · 1.61 KB
/
resolvconf.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package utils
import (
"bufio"
"bytes"
"os"
"regexp"
"sort"
"strings"
)
const (
// DefaultKubeClusterDomain is the default value of KubeClusterDomain.
DefaultKubeClusterDomain = "cluster.local"
defaultResolvPath = "/etc/resolv.conf"
commentMarker = "#"
)
var searchRegexp = regexp.MustCompile(`^\s*search\s*(([^\s]+\s*)*)$`)
// GetKubeClusterDomain search KubeClusterDomain value from /etc/resolv.conf file.
func GetKubeClusterDomain() (string, error) {
resolvContent, err := getResolvContent(defaultResolvPath)
if err != nil {
return "", err
}
return getClusterDomain(resolvContent)
}
func getClusterDomain(resolvConf []byte) (string, error) {
var kubeClusterDomain string
searchDomains := getResolvSearchDomains(resolvConf)
sort.Strings(searchDomains)
if len(searchDomains) == 0 || searchDomains[0] == "" {
kubeClusterDomain = DefaultKubeClusterDomain
} else {
kubeClusterDomain = searchDomains[0]
}
return kubeClusterDomain, nil
}
func getResolvContent(resolvPath string) ([]byte, error) {
return os.ReadFile(resolvPath)
}
func getResolvSearchDomains(resolvConf []byte) []string {
var (
domains []string
lines [][]byte
)
scanner := bufio.NewScanner(bytes.NewReader(resolvConf))
for scanner.Scan() {
line := scanner.Bytes()
commentIndex := bytes.Index(line, []byte(commentMarker))
if commentIndex == -1 {
lines = append(lines, line)
} else {
lines = append(lines, line[:commentIndex])
}
}
for _, line := range lines {
match := searchRegexp.FindSubmatch(line)
if match == nil {
continue
}
domains = strings.Fields(string(match[1]))
}
return domains
}