-
-
Notifications
You must be signed in to change notification settings - Fork 455
/
host.go
155 lines (123 loc) · 5.29 KB
/
host.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
/*
Copyright © 2020-2022 The k3d Author(s)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package client
import (
"bufio"
"context"
"fmt"
"net"
"regexp"
goruntime "runtime"
l "github.com/rancher/k3d/v5/pkg/logger"
"github.com/rancher/k3d/v5/pkg/runtimes"
"github.com/rancher/k3d/v5/pkg/runtimes/docker"
k3d "github.com/rancher/k3d/v5/pkg/types"
"github.com/rancher/k3d/v5/pkg/util"
)
type ResolveHostCmd struct {
Cmd string
LogMatcher *regexp.Regexp
}
var (
ResolveHostCmdNSLookup = ResolveHostCmd{
Cmd: "nslookup %s",
LogMatcher: regexp.MustCompile(`^Address:\s+(?P<ip>\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$`),
}
ResolveHostCmdGetEnt = ResolveHostCmd{
Cmd: "getent ahostsv4 '%s'",
LogMatcher: regexp.MustCompile(`(?P<ip>\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s+STREAM.+`), // e.g. `192.168.47.4 STREAM host.docker.internal`,
}
)
// GetHostIP returns the routable IP address to be able to access services running on the host system from inside the cluster.
// This depends on the Operating System and the chosen Runtime.
func GetHostIP(ctx context.Context, runtime runtimes.Runtime, cluster *k3d.Cluster) (net.IP, error) {
rtimeInfo, err := runtime.Info()
if err != nil {
return nil, err
}
l.Log().Tracef("GOOS: %s / Runtime OS: %s (%s)", goruntime.GOOS, rtimeInfo.OSType, rtimeInfo.OS)
// Docker Runtime
if runtime == runtimes.Docker {
// Docker (for Desktop) on MacOS or Windows
if docker.IsDockerDesktop(rtimeInfo.OS) {
toolsNode, err := EnsureToolsNode(ctx, runtime, cluster)
if err != nil {
return nil, fmt.Errorf("failed to ensure that k3d-tools node is running to get host IP :%w", err)
}
k3dInternalIP, err := resolveHostnameFromInside(ctx, runtime, toolsNode, k3d.DefaultK3dInternalHostRecord, ResolveHostCmdGetEnt)
if err == nil {
return k3dInternalIP, nil
}
l.Log().Debugf("[GetHostIP on Docker Desktop] failed to resolve '%s' from inside the k3d-tools node: %v", k3d.DefaultK3dInternalHostRecord, err)
dockerInternalIP, err := resolveHostnameFromInside(ctx, runtime, toolsNode, "host.docker.internal", ResolveHostCmdGetEnt)
if err == nil {
return dockerInternalIP, nil
}
l.Log().Debugf("[GetHostIP on Docker Desktop] failed to resolve 'host.docker.internal' from inside the k3d-tools node: %v", err)
}
ip, err := runtime.GetHostIP(ctx, cluster.Network.Name)
if err != nil {
return nil, fmt.Errorf("runtime failed to get host IP: %w", err)
}
l.Log().Infof("HostIP: using network gateway %s address", ip)
return ip, nil
}
// Catch all other runtime selections
return nil, fmt.Errorf("GetHostIP only implemented for the docker runtime")
}
func resolveHostnameFromInside(ctx context.Context, rtime runtimes.Runtime, node *k3d.Node, hostname string, cmd ResolveHostCmd) (net.IP, error) {
errPrefix := fmt.Errorf("error resolving hostname %s from inside node %s", hostname, node.Name)
logreader, execErr := rtime.ExecInNodeGetLogs(ctx, node, []string{"sh", "-c", fmt.Sprintf(cmd.Cmd, hostname)})
if logreader == nil {
if execErr != nil {
return nil, fmt.Errorf("%v: %w", errPrefix, execErr)
}
return nil, fmt.Errorf("%w: failed to get logs from exec process", errPrefix)
}
submatches := map[string]string{}
scanner := bufio.NewScanner(logreader)
if scanner == nil {
if execErr != nil {
return nil, fmt.Errorf("%v: %w", errPrefix, execErr)
}
return nil, fmt.Errorf("Failed to scan logs for host IP: Could not create scanner from logreader")
}
if scanner != nil && execErr != nil {
l.Log().Debugln("Exec Process Failed, but we still got logs, so we're at least trying to get the IP from there...")
l.Log().Tracef("-> Exec Process Error was: %+v", execErr)
}
for scanner.Scan() {
l.Log().Tracef("Scanning Log Line '%s'", scanner.Text())
match := cmd.LogMatcher.FindStringSubmatch(scanner.Text())
if len(match) == 0 {
continue
}
submatches = util.MapSubexpNames(cmd.LogMatcher.SubexpNames(), match)
l.Log().Tracef("-> Match(es): '%+v' -> Submatch(es): %+v", match, submatches)
break
}
if _, ok := submatches["ip"]; !ok {
if execErr != nil {
l.Log().Errorln(execErr)
}
return nil, fmt.Errorf("%w: failed to read address for '%s' from command output", errPrefix, hostname)
}
l.Log().Debugf("Hostname '%s' resolved to address '%s' inside node %s", hostname, submatches["ip"], node.Name)
return net.ParseIP(submatches["ip"]), nil
}