|
| 1 | +/* |
| 2 | +Copyright 2026 Cozystack contributors. |
| 3 | +
|
| 4 | +Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +you may not use this file except in compliance with the License. |
| 6 | +You may obtain a copy of the License at |
| 7 | +
|
| 8 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +
|
| 10 | +Unless required by applicable law or agreed to in writing, software |
| 11 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +See the License for the specific language governing permissions and |
| 14 | +limitations under the License. |
| 15 | +*/ |
| 16 | + |
| 17 | +// Package dispatcher is the controller-side glue that turns Resource |
| 18 | +// CRDs into satellite-side ApplyResources calls. The kubebuilder |
| 19 | +// reconciler delegates here so the wire format and the gRPC dial / |
| 20 | +// retry logic live in one testable place. |
| 21 | +package dispatcher |
| 22 | + |
| 23 | +import ( |
| 24 | + "context" |
| 25 | + "crypto/sha256" |
| 26 | + "encoding/binary" |
| 27 | + "sort" |
| 28 | + "strconv" |
| 29 | + |
| 30 | + "github.com/cockroachdb/errors" |
| 31 | + "google.golang.org/grpc" |
| 32 | + "google.golang.org/grpc/credentials/insecure" |
| 33 | + |
| 34 | + blockstoriov1alpha1 "github.com/cozystack/blockstor/api/v1alpha1" |
| 35 | + satellitepb "github.com/cozystack/blockstor/pkg/satellite/proto" |
| 36 | +) |
| 37 | + |
| 38 | +// drbdAddrAny is the placeholder address we put into the .res file at |
| 39 | +// dispatch time. The satellite rewrites it to its actual pod IP when |
| 40 | +// it renders the file (drbd doesn't accept literal 0.0.0.0). |
| 41 | +const drbdAddrAny = "0.0.0.0" |
| 42 | + |
| 43 | +// Dialer abstracts how we open a gRPC connection. Production wires |
| 44 | +// the actual `grpc.NewClient`; tests inject a stub that returns a |
| 45 | +// canned client. |
| 46 | +type Dialer interface { |
| 47 | + Dial(ctx context.Context, endpoint string) (satellitepb.SatelliteClient, func() error, error) |
| 48 | +} |
| 49 | + |
| 50 | +// realDialer wraps grpc.NewClient with our standard insecure (cluster- |
| 51 | +// internal) transport. |
| 52 | +type realDialer struct{} |
| 53 | + |
| 54 | +// NewDialer returns a production Dialer. We export it so the |
| 55 | +// reconciler in main.go can wire it without leaking grpc imports |
| 56 | +// across packages. |
| 57 | +func NewDialer() Dialer { |
| 58 | + return realDialer{} |
| 59 | +} |
| 60 | + |
| 61 | +// Dial opens a connection to endpoint and returns the satellite |
| 62 | +// client, a close func, or an error. |
| 63 | +func (realDialer) Dial(_ context.Context, endpoint string) (satellitepb.SatelliteClient, func() error, error) { |
| 64 | + conn, err := grpc.NewClient(endpoint, grpc.WithTransportCredentials(insecure.NewCredentials())) |
| 65 | + if err != nil { |
| 66 | + return nil, nil, errors.Wrapf(err, "dial %s", endpoint) |
| 67 | + } |
| 68 | + |
| 69 | + return satellitepb.NewSatelliteClient(conn), conn.Close, nil |
| 70 | +} |
| 71 | + |
| 72 | +// Dispatcher pushes a Resource's desired state to the satellite that |
| 73 | +// hosts it. |
| 74 | +type Dispatcher struct { |
| 75 | + dialer Dialer |
| 76 | +} |
| 77 | + |
| 78 | +// New constructs a Dispatcher with the given Dialer. |
| 79 | +func New(dialer Dialer) *Dispatcher { |
| 80 | + return &Dispatcher{dialer: dialer} |
| 81 | +} |
| 82 | + |
| 83 | +// Apply builds the DesiredResource for this Resource (looking up its |
| 84 | +// peers from the full RD-wide list) and sends it to the target |
| 85 | +// satellite. Returns the per-resource result the satellite reported. |
| 86 | +// |
| 87 | +// nodes is the full Node CRD list — Apply uses it to resolve each |
| 88 | +// peer's SatelliteEndpoint property. |
| 89 | +func (d *Dispatcher) Apply(ctx context.Context, target *blockstoriov1alpha1.Resource, peers []blockstoriov1alpha1.Resource, nodes []blockstoriov1alpha1.Node) (*satellitepb.ResourceApplyResult, error) { |
| 90 | + endpoint := lookupEndpoint(target.Spec.NodeName, nodes) |
| 91 | + if endpoint == "" { |
| 92 | + return nil, errors.Errorf("no SatelliteEndpoint for node %q", target.Spec.NodeName) |
| 93 | + } |
| 94 | + |
| 95 | + desired := buildDesired(target, peers) |
| 96 | + |
| 97 | + client, closer, err := d.dialer.Dial(ctx, endpoint) |
| 98 | + if err != nil { |
| 99 | + return nil, errors.Wrapf(err, "dial %s", endpoint) |
| 100 | + } |
| 101 | + defer func() { _ = closer() }() |
| 102 | + |
| 103 | + resp, err := client.ApplyResources(ctx, &satellitepb.ApplyResourcesRequest{ |
| 104 | + Resources: []*satellitepb.DesiredResource{desired}, |
| 105 | + }) |
| 106 | + if err != nil { |
| 107 | + return nil, errors.Wrap(err, "ApplyResources RPC") |
| 108 | + } |
| 109 | + |
| 110 | + if len(resp.GetResults()) == 0 { |
| 111 | + return nil, errors.New("empty ApplyResources response") |
| 112 | + } |
| 113 | + |
| 114 | + return resp.GetResults()[0], nil |
| 115 | +} |
| 116 | + |
| 117 | +// lookupEndpoint reads SatelliteEndpoint from the Node prop bag. |
| 118 | +func lookupEndpoint(nodeName string, nodes []blockstoriov1alpha1.Node) string { |
| 119 | + for i := range nodes { |
| 120 | + if nodes[i].Name == nodeName { |
| 121 | + return nodes[i].Spec.Props["SatelliteEndpoint"] |
| 122 | + } |
| 123 | + } |
| 124 | + |
| 125 | + return "" |
| 126 | +} |
| 127 | + |
| 128 | +// buildDesired translates a Resource + its same-RD peers into the |
| 129 | +// satellite-facing DesiredResource. Port/minor/node-id assignment is |
| 130 | +// deterministic from the RD name + sorted peer list — good enough for |
| 131 | +// the first stand smoke; the autoplacer will replace it with a real |
| 132 | +// allocator once we wire the IPAM hookup. |
| 133 | +func buildDesired(target *blockstoriov1alpha1.Resource, peers []blockstoriov1alpha1.Resource) *satellitepb.DesiredResource { |
| 134 | + rdName := target.Spec.ResourceDefinitionName |
| 135 | + port := derivePort(rdName) |
| 136 | + minor := deriveMinor(rdName) |
| 137 | + |
| 138 | + // Collect every node hosting this RD, sorted, with self at front. |
| 139 | + nodeNames := append([]string{}, target.Spec.NodeName) |
| 140 | + seen := map[string]bool{target.Spec.NodeName: true} |
| 141 | + |
| 142 | + for i := range peers { |
| 143 | + name := peers[i].Spec.NodeName |
| 144 | + if seen[name] { |
| 145 | + continue |
| 146 | + } |
| 147 | + |
| 148 | + seen[name] = true |
| 149 | + nodeNames = append(nodeNames, name) |
| 150 | + } |
| 151 | + |
| 152 | + // Sort all (incl. self) so node-id assignment is stable across |
| 153 | + // reconciles. |
| 154 | + sortedAll := append([]string{}, nodeNames...) |
| 155 | + sort.Strings(sortedAll) |
| 156 | + |
| 157 | + idOf := map[string]int{} |
| 158 | + for i, name := range sortedAll { |
| 159 | + idOf[name] = i |
| 160 | + } |
| 161 | + |
| 162 | + dropped := nodeNames[1:] |
| 163 | + |
| 164 | + drbdOpts := map[string]string{ |
| 165 | + "port": strconv.Itoa(port), |
| 166 | + "node-id": strconv.Itoa(idOf[target.Spec.NodeName]), |
| 167 | + "address": drbdAddrAny, // satellite picks pod IP at .res render time |
| 168 | + "minor": strconv.Itoa(minor), |
| 169 | + } |
| 170 | + |
| 171 | + // Per-peer entries — used by ConfFileBuilder on the satellite to |
| 172 | + // compose the connection mesh. |
| 173 | + for _, peer := range dropped { |
| 174 | + drbdOpts["peer."+peer+".port"] = strconv.Itoa(port) |
| 175 | + drbdOpts["peer."+peer+".node-id"] = strconv.Itoa(idOf[peer]) |
| 176 | + drbdOpts["peer."+peer+".address"] = drbdAddrAny |
| 177 | + } |
| 178 | + |
| 179 | + return &satellitepb.DesiredResource{ |
| 180 | + Name: rdName, |
| 181 | + NodeName: target.Spec.NodeName, |
| 182 | + Flags: target.Spec.Flags, |
| 183 | + Props: target.Spec.Props, |
| 184 | + Peers: dropped, |
| 185 | + DrbdOptions: drbdOpts, |
| 186 | + } |
| 187 | +} |
| 188 | + |
| 189 | +// derivePort hashes the RD name into the drbd-9 reserved range |
| 190 | +// 7000–7999. Matches what upstream LINSTOR's TcpPortPool does for |
| 191 | +// fresh deployments — collisions on a real cluster are handled by |
| 192 | +// the autoplacer, but for the smoke we live with the hash. |
| 193 | +func derivePort(rd string) int { |
| 194 | + const ( |
| 195 | + portBase = 7000 |
| 196 | + portRange = 1000 |
| 197 | + ) |
| 198 | + |
| 199 | + digest := sha256.Sum256([]byte(rd)) |
| 200 | + |
| 201 | + return portBase + int(binary.BigEndian.Uint16(digest[:2])%portRange) |
| 202 | +} |
| 203 | + |
| 204 | +// deriveMinor likewise hashes into 1000–9999. |
| 205 | +func deriveMinor(rd string) int { |
| 206 | + const ( |
| 207 | + minorBase = 1000 |
| 208 | + minorRange = 9000 |
| 209 | + ) |
| 210 | + |
| 211 | + digest := sha256.Sum256([]byte(rd)) |
| 212 | + |
| 213 | + return minorBase + int(binary.BigEndian.Uint16(digest[2:4])%minorRange) |
| 214 | +} |
0 commit comments