blob: 89c5c10e5f1f7c4ec2a141f800bf8864999a6f2e [file] [log] [blame]
Tim Windelschmidt6d33a432025-02-04 14:34:25 +01001// Copyright The Monogon Project Authors.
2// SPDX-License-Identifier: Apache-2.0
3
Serge Bazanski93d593b2023-03-28 16:43:47 +02004// Package clusternet implements a Cluster Networking mesh service running on all
5// Metropolis nodes.
6//
7// The mesh is based on wireguard and a centralized configuration store in the
8// cluster Curator (in etcd).
9//
10// While the implementation is nearly generic, it currently makes an assumption
11// that it is used only for Kubernetes pod networking. That has a few
12// implications:
13//
14// First, we only have a single real route on the host into the wireguard
15// networking mesh / interface, and that is configured ahead of time in the
16// Service as ClusterNet. All destination addresses that should be carried by the
17// mesh must thus be part of this single route. Otherwise, traffic will be able
18// to flow into the node from other nodes, but will exit through another
19// interface. This is used in practice to allow other host nodes (whose external
20// addresses are outside the cluster network) to access the cluster network.
21//
Serge Bazanskib565cc62023-03-30 18:43:51 +020022// Second, we have two hardcoded/purpose-specific sources of prefixes:
23// 1. Pod networking node prefixes from the kubelet
24// 2. The host's external IP address (as a /32) from the network service.
Serge Bazanski93d593b2023-03-28 16:43:47 +020025package clusternet
26
27import (
28 "context"
29 "fmt"
30 "net"
Serge Bazanskib565cc62023-03-30 18:43:51 +020031 "net/netip"
Serge Bazanski60461b22023-10-26 19:16:59 +020032 "slices"
Serge Bazanski93d593b2023-03-28 16:43:47 +020033
34 "github.com/cenkalti/backoff/v4"
Tim Windelschmidt011dce62024-03-03 16:00:52 +010035 "github.com/vishvananda/netlink"
Serge Bazanski93d593b2023-03-28 16:43:47 +020036
Serge Bazanski60461b22023-10-26 19:16:59 +020037 "source.monogon.dev/metropolis/node/core/curator/watcher"
Serge Bazanski93d593b2023-03-28 16:43:47 +020038 "source.monogon.dev/metropolis/node/core/localstorage"
Serge Bazanskib565cc62023-03-30 18:43:51 +020039 "source.monogon.dev/metropolis/node/core/network"
Tim Windelschmidt9f21f532024-05-07 15:14:20 +020040 "source.monogon.dev/osbase/event"
41 "source.monogon.dev/osbase/supervisor"
Serge Bazanskib565cc62023-03-30 18:43:51 +020042
43 apb "source.monogon.dev/metropolis/node/core/curator/proto/api"
Serge Bazanski93d593b2023-03-28 16:43:47 +020044 cpb "source.monogon.dev/metropolis/proto/common"
45)
46
47// Service implements the Cluster Networking Mesh. See package-level docs for
48// more details.
49type Service struct {
50 // Curator is the gRPC client that the service will use to reach the cluster's
51 // Curator, for pushing locally announced prefixes and pulling information about
52 // other nodes.
53 Curator apb.CuratorClient
54 // ClusterNet is the prefix that will be programmed to exit through the wireguard
55 // mesh.
56 ClusterNet net.IPNet
57 // DataDirectory is where the WireGuard key of this node will be stored.
58 DataDirectory *localstorage.DataKubernetesClusterNetworkingDirectory
59 // LocalKubernetesPodNetwork is an event.Value watched for prefixes that should
60 // be announced into the mesh. This is to be Set by the Kubernetes service once
61 // it knows about the local node's IPAM address assignment.
62 LocalKubernetesPodNetwork event.Value[*Prefixes]
Serge Bazanskib565cc62023-03-30 18:43:51 +020063 // Network service used to get the local node's IP address to submit it as a /32.
64 Network event.Value[*network.Status]
Serge Bazanski93d593b2023-03-28 16:43:47 +020065
66 // wg is the interface to all the low-level interactions with WireGuard (and
67 // kernel routing). If not set, this defaults to a production implementation.
68 // This can be overridden by test to a test implementation instead.
69 wg wireguard
70}
71
72// Run the Service. This must be used in a supervisor Runnable.
73func (s *Service) Run(ctx context.Context) error {
74 if s.wg == nil {
75 s.wg = &localWireguard{}
76 }
77 if err := s.wg.ensureOnDiskKey(s.DataDirectory); err != nil {
78 return fmt.Errorf("could not ensure wireguard key: %w", err)
79 }
80 if err := s.wg.setup(&s.ClusterNet); err != nil {
81 return fmt.Errorf("could not setup wireguard: %w", err)
82 }
83
84 supervisor.Logger(ctx).Infof("Wireguard setup complete, starting updaters...")
85
Serge Bazanskib565cc62023-03-30 18:43:51 +020086 kubeC := make(chan *Prefixes)
87 netC := make(chan *network.Status)
88 if err := supervisor.RunGroup(ctx, map[string]supervisor.Runnable{
89 "source-kubernetes": event.Pipe(s.LocalKubernetesPodNetwork, kubeC),
90 "source-network": event.Pipe(s.Network, netC),
91 "push": func(ctx context.Context) error {
92 return s.push(ctx, kubeC, netC)
93 },
94 }); err != nil {
Serge Bazanski93d593b2023-03-28 16:43:47 +020095 return err
96 }
Serge Bazanskib565cc62023-03-30 18:43:51 +020097
98 if err := supervisor.Run(ctx, "pull", s.pull); err != nil {
Serge Bazanski93d593b2023-03-28 16:43:47 +020099 return err
100 }
101 supervisor.Signal(ctx, supervisor.SignalHealthy)
102 <-ctx.Done()
103 return ctx.Err()
104}
105
106// push is the sub-runnable responsible for letting the Curator know about what
107// prefixes that are originated by this node.
Serge Bazanskib565cc62023-03-30 18:43:51 +0200108func (s *Service) push(ctx context.Context, kubeC chan *Prefixes, netC chan *network.Status) error {
Serge Bazanski93d593b2023-03-28 16:43:47 +0200109 supervisor.Signal(ctx, supervisor.SignalHealthy)
110
Serge Bazanskib565cc62023-03-30 18:43:51 +0200111 var kubePrefixes *Prefixes
Serge Bazanski521a8352023-06-29 12:38:17 +0200112 var prevKubePrefixes *Prefixes
113
Serge Bazanskib565cc62023-03-30 18:43:51 +0200114 var localAddr net.IP
Serge Bazanski521a8352023-06-29 12:38:17 +0200115 var prevLocalAddr net.IP
116
Serge Bazanski93d593b2023-03-28 16:43:47 +0200117 for {
Serge Bazanski521a8352023-06-29 12:38:17 +0200118 kubeChanged := false
119 localChanged := false
120
Serge Bazanskib565cc62023-03-30 18:43:51 +0200121 select {
122 case <-ctx.Done():
123 return ctx.Err()
124 case kubePrefixes = <-kubeC:
Serge Bazanski521a8352023-06-29 12:38:17 +0200125 if !kubePrefixes.Equal(prevKubePrefixes) {
126 kubeChanged = true
127 }
Serge Bazanskib565cc62023-03-30 18:43:51 +0200128 case n := <-netC:
129 localAddr = n.ExternalAddress
Serge Bazanski521a8352023-06-29 12:38:17 +0200130 if !localAddr.Equal(prevLocalAddr) {
131 localChanged = true
132 }
133 }
134
Tim Windelschmidt011dce62024-03-03 16:00:52 +0100135 if kubeChanged {
136 if err := configureKubeNetwork(prevKubePrefixes, kubePrefixes); err != nil {
137 supervisor.Logger(ctx).Warningf("Could not configure cluster networking update: %v", err)
138 }
139 }
140
Serge Bazanski521a8352023-06-29 12:38:17 +0200141 // Ignore spurious updates.
142 if !localChanged && !kubeChanged {
143 continue
Serge Bazanski93d593b2023-03-28 16:43:47 +0200144 }
145
Serge Bazanskib565cc62023-03-30 18:43:51 +0200146 // Prepare prefixes to submit to cluster.
147 var prefixes Prefixes
148
149 // Do we have a local node address? Add it to the prefixes.
150 if len(localAddr) > 0 {
151 addr, ok := netip.AddrFromSlice(localAddr)
152 if ok {
153 prefixes = append(prefixes, netip.PrefixFrom(addr, 32))
154 }
155 }
156 // Do we have any kubelet prefixes? Add them, too.
157 if kubePrefixes != nil {
158 prefixes.Update(kubePrefixes)
159 }
160
Serge Bazanski521a8352023-06-29 12:38:17 +0200161 supervisor.Logger(ctx).Infof("Submitting prefixes: %s (kube update: %v, local update: %v)", prefixes, kubeChanged, localChanged)
Serge Bazanskib565cc62023-03-30 18:43:51 +0200162
163 err := backoff.Retry(func() error {
Serge Bazanski93d593b2023-03-28 16:43:47 +0200164 _, err := s.Curator.UpdateNodeClusterNetworking(ctx, &apb.UpdateNodeClusterNetworkingRequest{
165 Clusternet: &cpb.NodeClusterNetworking{
166 WireguardPubkey: s.wg.key().PublicKey().String(),
Serge Bazanskib565cc62023-03-30 18:43:51 +0200167 Prefixes: prefixes.proto(),
Serge Bazanski93d593b2023-03-28 16:43:47 +0200168 },
169 })
170 if err != nil {
171 supervisor.Logger(ctx).Warningf("Could not submit cluster networking update: %v", err)
172 }
173 return err
174 }, backoff.WithContext(backoff.NewExponentialBackOff(), ctx))
175 if err != nil {
176 return fmt.Errorf("couldn't update curator: %w", err)
177 }
Serge Bazanski521a8352023-06-29 12:38:17 +0200178
179 prevKubePrefixes = kubePrefixes
180 prevLocalAddr = localAddr
181
Serge Bazanski93d593b2023-03-28 16:43:47 +0200182 }
183}
184
Tim Windelschmidt011dce62024-03-03 16:00:52 +0100185// configureKubeNetwork configures the point-to-point peer IP address of the
186// node host network namespace (i.e. the one container P2P interfaces point to)
187// on its loopback interface to make it eligible to be used as a source IP
188// address for communication into the clusternet overlay.
189func configureKubeNetwork(oldPrefixes *Prefixes, newPrefixes *Prefixes) error {
190 // diff maps prefixes to be removed to false
191 // and prefixes to be added to true.
192 diff := make(map[netip.Prefix]bool)
193
194 if newPrefixes != nil {
195 for _, newAddr := range *newPrefixes {
196 diff[newAddr] = true
197 }
198 }
199
200 if oldPrefixes != nil {
201 for _, oldAddr := range *oldPrefixes {
202 // Remove all prefixes in both the old
203 // and new prefix sets from `diff`.
204 if diff[oldAddr] {
205 delete(diff, oldAddr)
206 continue
207 }
208
209 // Mark all remaining (i.e. ones not in the new prefix set)
210 // prefixes for removal.
211 diff[oldAddr] = false
212 }
213 }
214
215 loInterface, err := netlink.LinkByName("lo")
216 if err != nil {
217 return fmt.Errorf("while getting lo interface: %w", err)
218 }
219
220 for prefix, shouldAdd := range diff {
221 // By CNI convention the first IP after the subnet base address is the
222 // point-to-point partner for all pod veths. To make this IP eligible
223 // to be used as a general host network namespace source IP we also add
224 // it to the loopback interface. This ensures that the kernel picks it
225 // as the source IP for traffic flowing into clusternet
226 // (due to its preference for source IPs in the same subnet).
227 addr := &netlink.Addr{
228 IPNet: &net.IPNet{
229 IP: prefix.Addr().Next().AsSlice(),
230 Mask: net.CIDRMask(prefix.Addr().BitLen(), prefix.Addr().BitLen()),
231 },
232 }
233
234 if shouldAdd {
235 if err := netlink.AddrAdd(loInterface, addr); err != nil {
Tim Windelschmidt5f1a7de2024-09-19 02:00:14 +0200236 return fmt.Errorf("assigning extra loopback IP: %w", err)
Tim Windelschmidt011dce62024-03-03 16:00:52 +0100237 }
238 } else {
239 if err := netlink.AddrDel(loInterface, addr); err != nil {
Tim Windelschmidt5f1a7de2024-09-19 02:00:14 +0200240 return fmt.Errorf("removing extra loopback IP: %w", err)
Tim Windelschmidt011dce62024-03-03 16:00:52 +0100241 }
242 }
243 }
244
245 return nil
246}
247
Serge Bazanski93d593b2023-03-28 16:43:47 +0200248// pull is the sub-runnable responsible for fetching information about the
249// cluster networking setup/status of other nodes, and programming it as
250// WireGuard peers.
251func (s *Service) pull(ctx context.Context) error {
252 supervisor.Signal(ctx, supervisor.SignalHealthy)
253
Serge Bazanski60461b22023-10-26 19:16:59 +0200254 var batch []*apb.Node
255 return watcher.WatchNodes(ctx, s.Curator, watcher.SimpleFollower{
256 FilterFn: func(a *apb.Node) bool {
257 if a.Clusternet == nil {
258 return false
259 }
260 if a.Clusternet.WireguardPubkey == "" {
261 return false
262 }
263 return true
264 },
265 EqualsFn: func(a *apb.Node, b *apb.Node) bool {
266 if a.Status.ExternalAddress != b.Status.ExternalAddress {
267 return false
268 }
269 if a.Clusternet.WireguardPubkey != b.Clusternet.WireguardPubkey {
270 return false
271 }
272 if !slices.Equal(a.Clusternet.Prefixes, b.Clusternet.Prefixes) {
273 return false
274 }
275 return true
276 },
277 OnNewUpdated: func(new *apb.Node) error {
278 batch = append(batch, new)
279 return nil
280 },
281 OnBatchDone: func() error {
282 if err := s.wg.configurePeers(batch); err != nil {
283 supervisor.Logger(ctx).Errorf("nodes couldn't be configured: %v", err)
284 }
285 batch = nil
286 return nil
287 },
288 OnDeleted: func(prev *apb.Node) error {
289 if err := s.wg.unconfigurePeer(prev); err != nil {
290 supervisor.Logger(ctx).Errorf("Node %s couldn't be unconfigured: %v", prev.Id, err)
291 }
292 return nil
Serge Bazanski93d593b2023-03-28 16:43:47 +0200293 },
294 })
Serge Bazanski93d593b2023-03-28 16:43:47 +0200295}