blob: 85ac63f50aedc398d51d86a50c02085268bdb8fc [file] [log] [blame]
Serge Bazanski93d593b2023-03-28 16:43:47 +02001// Package clusternet implements a Cluster Networking mesh service running on all
2// Metropolis nodes.
3//
4// The mesh is based on wireguard and a centralized configuration store in the
5// cluster Curator (in etcd).
6//
7// While the implementation is nearly generic, it currently makes an assumption
8// that it is used only for Kubernetes pod networking. That has a few
9// implications:
10//
11// First, we only have a single real route on the host into the wireguard
12// networking mesh / interface, and that is configured ahead of time in the
13// Service as ClusterNet. All destination addresses that should be carried by the
14// mesh must thus be part of this single route. Otherwise, traffic will be able
15// to flow into the node from other nodes, but will exit through another
16// interface. This is used in practice to allow other host nodes (whose external
17// addresses are outside the cluster network) to access the cluster network.
18//
Serge Bazanskib565cc62023-03-30 18:43:51 +020019// Second, we have two hardcoded/purpose-specific sources of prefixes:
20// 1. Pod networking node prefixes from the kubelet
21// 2. The host's external IP address (as a /32) from the network service.
Serge Bazanski93d593b2023-03-28 16:43:47 +020022package clusternet
23
24import (
25 "context"
26 "fmt"
27 "net"
Serge Bazanskib565cc62023-03-30 18:43:51 +020028 "net/netip"
Serge Bazanski60461b22023-10-26 19:16:59 +020029 "slices"
Serge Bazanski93d593b2023-03-28 16:43:47 +020030
31 "github.com/cenkalti/backoff/v4"
32
Serge Bazanski60461b22023-10-26 19:16:59 +020033 "source.monogon.dev/metropolis/node/core/curator/watcher"
Serge Bazanski93d593b2023-03-28 16:43:47 +020034 "source.monogon.dev/metropolis/node/core/localstorage"
Serge Bazanskib565cc62023-03-30 18:43:51 +020035 "source.monogon.dev/metropolis/node/core/network"
Serge Bazanski93d593b2023-03-28 16:43:47 +020036 "source.monogon.dev/metropolis/pkg/event"
37 "source.monogon.dev/metropolis/pkg/supervisor"
Serge Bazanskib565cc62023-03-30 18:43:51 +020038
39 apb "source.monogon.dev/metropolis/node/core/curator/proto/api"
Serge Bazanski93d593b2023-03-28 16:43:47 +020040 cpb "source.monogon.dev/metropolis/proto/common"
41)
42
43// Service implements the Cluster Networking Mesh. See package-level docs for
44// more details.
45type Service struct {
46 // Curator is the gRPC client that the service will use to reach the cluster's
47 // Curator, for pushing locally announced prefixes and pulling information about
48 // other nodes.
49 Curator apb.CuratorClient
50 // ClusterNet is the prefix that will be programmed to exit through the wireguard
51 // mesh.
52 ClusterNet net.IPNet
53 // DataDirectory is where the WireGuard key of this node will be stored.
54 DataDirectory *localstorage.DataKubernetesClusterNetworkingDirectory
55 // LocalKubernetesPodNetwork is an event.Value watched for prefixes that should
56 // be announced into the mesh. This is to be Set by the Kubernetes service once
57 // it knows about the local node's IPAM address assignment.
58 LocalKubernetesPodNetwork event.Value[*Prefixes]
Serge Bazanskib565cc62023-03-30 18:43:51 +020059 // Network service used to get the local node's IP address to submit it as a /32.
60 Network event.Value[*network.Status]
Serge Bazanski93d593b2023-03-28 16:43:47 +020061
62 // wg is the interface to all the low-level interactions with WireGuard (and
63 // kernel routing). If not set, this defaults to a production implementation.
64 // This can be overridden by test to a test implementation instead.
65 wg wireguard
66}
67
68// Run the Service. This must be used in a supervisor Runnable.
69func (s *Service) Run(ctx context.Context) error {
70 if s.wg == nil {
71 s.wg = &localWireguard{}
72 }
73 if err := s.wg.ensureOnDiskKey(s.DataDirectory); err != nil {
74 return fmt.Errorf("could not ensure wireguard key: %w", err)
75 }
76 if err := s.wg.setup(&s.ClusterNet); err != nil {
77 return fmt.Errorf("could not setup wireguard: %w", err)
78 }
79
80 supervisor.Logger(ctx).Infof("Wireguard setup complete, starting updaters...")
81
Serge Bazanskib565cc62023-03-30 18:43:51 +020082 kubeC := make(chan *Prefixes)
83 netC := make(chan *network.Status)
84 if err := supervisor.RunGroup(ctx, map[string]supervisor.Runnable{
85 "source-kubernetes": event.Pipe(s.LocalKubernetesPodNetwork, kubeC),
86 "source-network": event.Pipe(s.Network, netC),
87 "push": func(ctx context.Context) error {
88 return s.push(ctx, kubeC, netC)
89 },
90 }); err != nil {
Serge Bazanski93d593b2023-03-28 16:43:47 +020091 return err
92 }
Serge Bazanskib565cc62023-03-30 18:43:51 +020093
94 if err := supervisor.Run(ctx, "pull", s.pull); err != nil {
Serge Bazanski93d593b2023-03-28 16:43:47 +020095 return err
96 }
97 supervisor.Signal(ctx, supervisor.SignalHealthy)
98 <-ctx.Done()
99 return ctx.Err()
100}
101
102// push is the sub-runnable responsible for letting the Curator know about what
103// prefixes that are originated by this node.
Serge Bazanskib565cc62023-03-30 18:43:51 +0200104func (s *Service) push(ctx context.Context, kubeC chan *Prefixes, netC chan *network.Status) error {
Serge Bazanski93d593b2023-03-28 16:43:47 +0200105 supervisor.Signal(ctx, supervisor.SignalHealthy)
106
Serge Bazanskib565cc62023-03-30 18:43:51 +0200107 var kubePrefixes *Prefixes
Serge Bazanski521a8352023-06-29 12:38:17 +0200108 var prevKubePrefixes *Prefixes
109
Serge Bazanskib565cc62023-03-30 18:43:51 +0200110 var localAddr net.IP
Serge Bazanski521a8352023-06-29 12:38:17 +0200111 var prevLocalAddr net.IP
112
Serge Bazanski93d593b2023-03-28 16:43:47 +0200113 for {
Serge Bazanski521a8352023-06-29 12:38:17 +0200114 kubeChanged := false
115 localChanged := false
116
Serge Bazanskib565cc62023-03-30 18:43:51 +0200117 select {
118 case <-ctx.Done():
119 return ctx.Err()
120 case kubePrefixes = <-kubeC:
Serge Bazanski521a8352023-06-29 12:38:17 +0200121 if !kubePrefixes.Equal(prevKubePrefixes) {
122 kubeChanged = true
123 }
Serge Bazanskib565cc62023-03-30 18:43:51 +0200124 case n := <-netC:
125 localAddr = n.ExternalAddress
Serge Bazanski521a8352023-06-29 12:38:17 +0200126 if !localAddr.Equal(prevLocalAddr) {
127 localChanged = true
128 }
129 }
130
131 // Ignore spurious updates.
132 if !localChanged && !kubeChanged {
133 continue
Serge Bazanski93d593b2023-03-28 16:43:47 +0200134 }
135
Serge Bazanskib565cc62023-03-30 18:43:51 +0200136 // Prepare prefixes to submit to cluster.
137 var prefixes Prefixes
138
139 // Do we have a local node address? Add it to the prefixes.
140 if len(localAddr) > 0 {
141 addr, ok := netip.AddrFromSlice(localAddr)
142 if ok {
143 prefixes = append(prefixes, netip.PrefixFrom(addr, 32))
144 }
145 }
146 // Do we have any kubelet prefixes? Add them, too.
147 if kubePrefixes != nil {
148 prefixes.Update(kubePrefixes)
149 }
150
Serge Bazanski521a8352023-06-29 12:38:17 +0200151 supervisor.Logger(ctx).Infof("Submitting prefixes: %s (kube update: %v, local update: %v)", prefixes, kubeChanged, localChanged)
Serge Bazanskib565cc62023-03-30 18:43:51 +0200152
153 err := backoff.Retry(func() error {
Serge Bazanski93d593b2023-03-28 16:43:47 +0200154 _, err := s.Curator.UpdateNodeClusterNetworking(ctx, &apb.UpdateNodeClusterNetworkingRequest{
155 Clusternet: &cpb.NodeClusterNetworking{
156 WireguardPubkey: s.wg.key().PublicKey().String(),
Serge Bazanskib565cc62023-03-30 18:43:51 +0200157 Prefixes: prefixes.proto(),
Serge Bazanski93d593b2023-03-28 16:43:47 +0200158 },
159 })
160 if err != nil {
161 supervisor.Logger(ctx).Warningf("Could not submit cluster networking update: %v", err)
162 }
163 return err
164 }, backoff.WithContext(backoff.NewExponentialBackOff(), ctx))
165 if err != nil {
166 return fmt.Errorf("couldn't update curator: %w", err)
167 }
Serge Bazanski521a8352023-06-29 12:38:17 +0200168
169 prevKubePrefixes = kubePrefixes
170 prevLocalAddr = localAddr
171
Serge Bazanski93d593b2023-03-28 16:43:47 +0200172 }
173}
174
175// pull is the sub-runnable responsible for fetching information about the
176// cluster networking setup/status of other nodes, and programming it as
177// WireGuard peers.
178func (s *Service) pull(ctx context.Context) error {
179 supervisor.Signal(ctx, supervisor.SignalHealthy)
180
Serge Bazanski60461b22023-10-26 19:16:59 +0200181 var batch []*apb.Node
182 return watcher.WatchNodes(ctx, s.Curator, watcher.SimpleFollower{
183 FilterFn: func(a *apb.Node) bool {
184 if a.Clusternet == nil {
185 return false
186 }
187 if a.Clusternet.WireguardPubkey == "" {
188 return false
189 }
190 return true
191 },
192 EqualsFn: func(a *apb.Node, b *apb.Node) bool {
193 if a.Status.ExternalAddress != b.Status.ExternalAddress {
194 return false
195 }
196 if a.Clusternet.WireguardPubkey != b.Clusternet.WireguardPubkey {
197 return false
198 }
199 if !slices.Equal(a.Clusternet.Prefixes, b.Clusternet.Prefixes) {
200 return false
201 }
202 return true
203 },
204 OnNewUpdated: func(new *apb.Node) error {
205 batch = append(batch, new)
206 return nil
207 },
208 OnBatchDone: func() error {
209 if err := s.wg.configurePeers(batch); err != nil {
210 supervisor.Logger(ctx).Errorf("nodes couldn't be configured: %v", err)
211 }
212 batch = nil
213 return nil
214 },
215 OnDeleted: func(prev *apb.Node) error {
216 if err := s.wg.unconfigurePeer(prev); err != nil {
217 supervisor.Logger(ctx).Errorf("Node %s couldn't be unconfigured: %v", prev.Id, err)
218 }
219 return nil
Serge Bazanski93d593b2023-03-28 16:43:47 +0200220 },
221 })
Serge Bazanski93d593b2023-03-28 16:43:47 +0200222}