-
Notifications
You must be signed in to change notification settings - Fork 371
Expand file tree
/
Copy pathmain.go
More file actions
283 lines (244 loc) · 8.45 KB
/
Copy pathmain.go
File metadata and controls
283 lines (244 loc) · 8.45 KB
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
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
/*
Copyright © 2025 SUSE LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Rancher-desktop-guestagent runs inside the WSL VM on Windows. It is
// primarily used to monitor and forward Kubernetes Service Ports
// (NodePorts and LoadBalancers) to the host. Also, it can be configured
// to perform port forwarding for the exposed container ports on both
// Moby and Containerd backends.
package main
import (
"context"
"errors"
"flag"
"fmt"
"net"
"os"
"os/signal"
"syscall"
"time"
"github.com/Masterminds/log-go"
"github.com/docker/go-connections/nat"
"golang.org/x/sync/errgroup"
"github.com/rancher-sandbox/rancher-desktop/src/go/guestagent/pkg/containerd"
"github.com/rancher-sandbox/rancher-desktop/src/go/guestagent/pkg/docker"
"github.com/rancher-sandbox/rancher-desktop/src/go/guestagent/pkg/forwarder"
"github.com/rancher-sandbox/rancher-desktop/src/go/guestagent/pkg/iptables"
"github.com/rancher-sandbox/rancher-desktop/src/go/guestagent/pkg/kube"
"github.com/rancher-sandbox/rancher-desktop/src/go/guestagent/pkg/procnet"
"github.com/rancher-sandbox/rancher-desktop/src/go/guestagent/pkg/tracker"
"github.com/rancher-sandbox/rancher-desktop/src/go/guestagent/pkg/types"
)
const (
iptablesUpdateInterval = 3 * time.Second
procNetScanInterval = 3 * time.Second
socketInterval = 5 * time.Second
socketRetryTimeout = 2 * time.Minute
dockerSocketFile = "/var/run/docker.sock"
containerdSocketFile = "/run/k3s/containerd/containerd.sock"
)
func main() {
var (
debug = flag.Bool("debug", false, "display debug output")
configPath = flag.String("kubeconfig", "/etc/rancher/k3s/k3s.yaml", "path to kubeconfig")
enableKubernetes = flag.Bool("kubernetes", false, "enable Kubernetes service forwarding")
enableDocker = flag.Bool("docker", false, "enable Docker event monitoring")
enableContainerd = flag.Bool("containerd", false, "enable Containerd event monitoring")
containerdSock = flag.String("containerdSock",
containerdSocketFile,
"file path for Containerd socket address")
k8sServiceListenerAddr = flag.String("k8sServiceListenerAddr", net.IPv4zero.String(),
"address to bind Kubernetes services to on the host, valid options are 0.0.0.0 or 127.0.0.1")
adminInstall = flag.Bool("adminInstall", false, "indicates if Rancher Desktop is installed as admin or not")
k8sAPIPort = flag.String("k8sAPIPort", "6443",
"K8sAPI port number to forward to rancher-desktop wsl-proxy as a static portMapping event")
tapIfaceIP = flag.String("tap-interface-ip", "192.168.127.2",
"IP address for the tap interface eth0 in network namespace")
)
// Setup logging with debug and trace levels
logger := log.NewStandard()
flag.Parse()
if *debug {
logger.Level = log.DebugLevel
}
log.Current = logger
log.Infof("Starting Rancher Desktop Agent in [AdminInstall=%t] mode", *adminInstall)
if os.Geteuid() != 0 {
log.Fatal("agent must run as root")
}
if !*enableContainerd &&
!*enableDocker {
log.Fatal("requires either -docker or -containerd enabled.")
}
if *enableContainerd &&
*enableDocker {
log.Fatal("requires either -docker or -containerd but not both.")
}
if err := runAgent(
*enableContainerd, *enableDocker, *enableKubernetes,
*containerdSock, *configPath, *k8sServiceListenerAddr,
*adminInstall, *k8sAPIPort, *tapIfaceIP,
); err != nil {
log.Fatal(err)
}
log.Info("Rancher Desktop Agent Shutting Down")
}
func runAgent(
enableContainerd, enableDocker, enableKubernetes bool,
containerdSock, configPath, k8sServiceListenerAddr string,
adminInstall bool,
k8sAPIPort, tapIfaceIP string,
) error {
bindIP := net.ParseIP(tapIfaceIP)
if bindIP == nil {
return fmt.Errorf("invalid tap interface IP %q", tapIfaceIP)
}
groupCtx, cancel := context.WithCancel(context.Background())
defer cancel()
group, ctx := errgroup.WithContext(groupCtx)
sigCh := make(chan os.Signal, 1)
signal.Notify(sigCh, syscall.SIGTERM)
go func() {
s := <-sigCh
log.Debugf("received [%s] signal", s)
cancel()
}()
var portTracker tracker.Tracker
wslProxyForwarder := forwarder.NewWSLProxyForwarder(ctx, "/run/wsl-proxy.sock")
portTracker = tracker.NewAPITracker(ctx, wslProxyForwarder, tracker.GatewayBaseURL, tapIfaceIP, adminInstall)
// Manually register the port for K8s API, we would
// only want to send this manual port mapping if both
// of the following conditions are met:
// 1) if kubernetes is enabled
// 2) when wsl-proxy for wsl-integration is enabled
if enableKubernetes {
port, err := nat.NewPort("tcp", k8sAPIPort)
if err != nil {
return fmt.Errorf("failed to parse port for k8s API: %w", err)
}
k8sAPIPortMapping := types.PortMapping{
Remove: false,
Ports: nat.PortMap{
port: []nat.PortBinding{
{
HostIP: "127.0.0.1",
HostPort: k8sAPIPort,
},
},
},
}
if err := wslProxyForwarder.Send(k8sAPIPortMapping); err != nil {
return fmt.Errorf("failed to send a static portMapping event to wsl-proxy: %w", err)
}
log.Debugf("successfully forwarded k8s API port [%s] to wsl-proxy", k8sAPIPort)
}
if enableContainerd {
group.Go(func() error {
for {
eventMonitor, err := containerd.NewEventMonitor(containerdSock, portTracker)
if err != nil {
return fmt.Errorf("error initializing containerd event monitor: %w", err)
}
if err := tryConnectAPI(ctx, containerdSocketFile, eventMonitor.IsServing); err != nil {
return err
}
eventMonitor.MonitorPorts(ctx)
if err := eventMonitor.Close(); err != nil {
return err
}
select {
case <-ctx.Done():
return nil
default:
}
}
})
}
if enableDocker {
group.Go(func() error {
for {
eventMonitor, err := docker.NewEventMonitor(portTracker)
if err != nil {
return fmt.Errorf("error initializing docker event monitor: %w", err)
}
if err := tryConnectAPI(ctx, dockerSocketFile, eventMonitor.Info); err != nil {
return err
}
eventMonitor.MonitorPorts(ctx)
eventMonitor.Flush()
select {
case <-ctx.Done():
return nil
default:
}
}
})
}
if enableKubernetes {
k8sServiceListenerIP := net.ParseIP(k8sServiceListenerAddr)
if k8sServiceListenerIP == nil || (!k8sServiceListenerIP.Equal(net.IPv4zero) && !k8sServiceListenerIP.Equal(net.IPv4(127, 0, 0, 1))) {
return fmt.Errorf("empty or invalid Kubernetes service listener IP address %s; "+
"valid options are 0.0.0.0 and 127.0.0.1", k8sServiceListenerAddr)
}
group.Go(func() error {
// Watch for kube
err := kube.WatchForServices(ctx,
configPath,
k8sServiceListenerIP,
portTracker)
if err != nil {
return fmt.Errorf("kubernetes service watcher failed: %w", err)
}
return nil
})
group.Go(func() error {
iptablesScanner := iptables.NewIptablesScanner()
iptablesHandler := iptables.New(ctx, portTracker, iptablesScanner, k8sServiceListenerIP, iptablesUpdateInterval)
err := iptablesHandler.ForwardPorts()
if err != nil {
return fmt.Errorf("iptables port forwarding failed: %w", err)
}
return nil
})
}
group.Go(func() error {
procScanner, err := procnet.NewProcNetScanner(ctx, portTracker, bindIP, procNetScanInterval)
if err != nil {
return fmt.Errorf("scanning /proc/net/{tcp, udp} failed: %w", err)
}
return procScanner.ForwardPorts()
})
return group.Wait()
}
func tryConnectAPI(ctx context.Context, socketFile string, verify func(context.Context) error) error {
socketRetry := time.NewTicker(socketInterval)
defer socketRetry.Stop()
// it can potentially take a few minutes to start RD
ctxTimeout, cancel := context.WithTimeout(ctx, socketRetryTimeout)
defer cancel()
for {
select {
case <-ctxTimeout.Done():
return fmt.Errorf("tryConnectAPI failed: %w", ctxTimeout.Err())
case <-socketRetry.C:
log.Debugf("checking if container engine API is running at %s", socketFile)
if _, err := os.Stat(socketFile); errors.Is(err, os.ErrNotExist) {
continue
}
if err := verify(ctx); err != nil {
log.Errorf("container engine is not ready yet: %v", err)
continue
}
return nil
}
}
}