diff --git a/cni/pkg/xdsclient/client.go b/cni/pkg/xdsclient/client.go new file mode 100644 index 000000000..5b034ff82 --- /dev/null +++ b/cni/pkg/xdsclient/client.go @@ -0,0 +1,415 @@ +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to You 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. + +package xdsclient + +import ( + "context" + "fmt" + "reflect" + "sync" + "sync/atomic" + "time" + + pkgmodel "github.com/apache/dubbo-kubernetes/pkg/model" + clusterv1 "github.com/dubml/xds-api/cluster/v1" + core "github.com/dubml/xds-api/core/v1" + endpointv1 "github.com/dubml/xds-api/endpoint/v1" + listenerv1 "github.com/dubml/xds-api/listener/v1" + routev1 "github.com/dubml/xds-api/route/v1" + discoveryv1 "github.com/dubml/xds-api/service/discovery/v1" + rpcstatus "google.golang.org/genproto/googleapis/rpc/status" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/credentials" + "google.golang.org/grpc/credentials/insecure" + "google.golang.org/grpc/keepalive" +) + +const ( + initialBackoff = 50 * time.Millisecond + maxBackoff = 5 * time.Second +) + +// Status describes the live ADS synchronization state of a managed workload client. +type Status struct { + NodeID string `json:"node_id"` + Connected bool `json:"connected"` + Ready bool `json:"ready"` + Attempts uint64 `json:"attempts"` + Generation uint64 `json:"generation"` + AcceptedVersions map[string]string `json:"accepted_versions,omitempty"` + LastError string `json:"last_error,omitempty"` +} + +type typeState struct { + names []string + version string + nonce string +} + +// Client manages a persistent authenticated ADS stream to dubbod on behalf of a workload +// and publishes atomic routing Snapshots for the node-level Triple tunnel proxy. +type Client struct { + mu sync.RWMutex + cfg Config + cache *resourceCache + states map[string]*typeState + status Status + snapshot atomic.Pointer[Snapshot] + + reconnectCh chan struct{} +} + +// New creates a new xDS ADS Client with the validated Config. +func New(cfg Config) (*Client, error) { + node, err := cfg.EffectiveNode() + if err != nil { + return nil, err + } + cfg.Node = node + + c := &Client{ + cfg: cfg, + cache: newResourceCache(), + states: map[string]*typeState{ + pkgmodel.ListenerType: {names: append([]string(nil), cfg.Listeners...)}, + pkgmodel.RouteType: {}, + pkgmodel.ClusterType: {}, + pkgmodel.EndpointType: {}, + }, + status: Status{ + NodeID: node.GetId(), + AcceptedVersions: map[string]string{}, + }, + reconnectCh: make(chan struct{}, 1), + } + c.snapshot.Store(&Snapshot{ + Listeners: map[string]*routev1.RouteConfiguration{}, + Clusters: map[string]*TargetCluster{}, + }) + return c, nil +} + +// Snapshot returns the latest atomically published routing snapshot. +func (c *Client) Snapshot() *Snapshot { + return c.snapshot.Load() +} + +// Status returns a copy of the current connection and sync status. +func (c *Client) Status() Status { + c.mu.RLock() + defer c.mu.RUnlock() + out := c.status + out.AcceptedVersions = make(map[string]string, len(c.status.AcceptedVersions)) + for k, v := range c.status.AcceptedVersions { + out.AcceptedVersions[k] = v + } + return out +} + +// UpdateConfig updates credentials or bootstrap config (e.g. on Secret rotation) +// and triggers an immediate reconnect so dubbod sees the renewed mTLS certificate. +func (c *Client) UpdateConfig(cfg Config) error { + node, err := cfg.EffectiveNode() + if err != nil { + return err + } + cfg.Node = node + c.mu.Lock() + c.cfg = cfg + c.status.NodeID = node.GetId() + c.mu.Unlock() + select { + case c.reconnectCh <- struct{}{}: + default: + } + return nil +} + +// Run maintains the ADS stream until ctx is cancelled, reconnecting with bounded backoff. +func (c *Client) Run(ctx context.Context) error { + backoff := initialBackoff + for { + if ctx.Err() != nil { + c.setDisconnected("") + return ctx.Err() + } + + c.mu.Lock() + c.status.Attempts++ + c.mu.Unlock() + + err := c.runSession(ctx) + if ctx.Err() != nil { + c.setDisconnected("") + return ctx.Err() + } + + errMsg := "" + if err != nil { + errMsg = err.Error() + } + c.setDisconnected(errMsg) + + select { + case <-ctx.Done(): + return ctx.Err() + case <-c.reconnectCh: + backoff = initialBackoff + case <-time.After(backoff): + backoff *= 2 + if backoff > maxBackoff { + backoff = maxBackoff + } + } + } +} + +func (c *Client) setDisconnected(errMsg string) { + c.mu.Lock() + defer c.mu.Unlock() + c.status.Connected = false + if errMsg != "" { + c.status.LastError = errMsg + } +} + +func (c *Client) runSession(parentCtx context.Context) error { + sessionCtx, cancel := context.WithCancel(parentCtx) + defer cancel() + + // Cancel active stream immediately when UpdateConfig signals credential rotation. + go func() { + select { + case <-sessionCtx.Done(): + case <-c.reconnectCh: + cancel() + } + }() + + c.mu.RLock() + cfg := c.cfg + c.mu.RUnlock() + + dialOpts, err := buildDialOptions(cfg) + if err != nil { + return fmt.Errorf("build xDS dial options: %w", err) + } + conn, err := grpc.NewClient(cfg.ServerURI, dialOpts...) + if err != nil { + return fmt.Errorf("dial xDS server %s: %w", cfg.ServerURI, err) + } + defer conn.Close() + + adsClient := discoveryv1.NewAggregatedDiscoveryServiceClient(conn) + stream, err := adsClient.StreamAggregatedResources(sessionCtx) + if err != nil { + return fmt.Errorf("open ADS stream: %w", err) + } + + // Clear old stream nonces and replay initial LDS + any active subscriptions. + c.mu.Lock() + for _, st := range c.states { + st.nonce = "" + } + node := cfg.Node + initialReqs := []*discoveryv1.DiscoveryRequest{ + { + Node: node, + TypeUrl: pkgmodel.ListenerType, + VersionInfo: c.states[pkgmodel.ListenerType].version, + ResourceNames: append([]string(nil), c.states[pkgmodel.ListenerType].names...), + }, + } + for _, typeURL := range []string{pkgmodel.RouteType, pkgmodel.ClusterType, pkgmodel.EndpointType} { + st := c.states[typeURL] + if len(st.names) > 0 { + initialReqs = append(initialReqs, &discoveryv1.DiscoveryRequest{ + Node: node, + TypeUrl: typeURL, + VersionInfo: st.version, + ResourceNames: append([]string(nil), st.names...), + }) + } + } + c.mu.Unlock() + + for _, req := range initialReqs { + if err := stream.Send(req); err != nil { + return fmt.Errorf("send initial xDS request (%s): %w", req.TypeUrl, err) + } + } + + for { + resp, err := stream.Recv() + if err != nil { + return err + } + followups, ackErr := c.handleResponse(node, resp) + if ackErr != nil { + // NACK with last accepted version and error detail; keep prior snapshot intact. + c.mu.RLock() + lastVer := "" + var names []string + if st, ok := c.states[resp.GetTypeUrl()]; ok { + lastVer = st.version + names = append([]string(nil), st.names...) + } + c.mu.RUnlock() + nack := &discoveryv1.DiscoveryRequest{ + Node: node, + TypeUrl: resp.GetTypeUrl(), + VersionInfo: lastVer, + ResponseNonce: resp.GetNonce(), + ResourceNames: names, + ErrorDetail: &rpcstatus.Status{ + Code: int32(codes.InvalidArgument), + Message: ackErr.Error(), + }, + } + if sendErr := stream.Send(nack); sendErr != nil { + return sendErr + } + continue + } + for _, req := range followups { + if sendErr := stream.Send(req); sendErr != nil { + return sendErr + } + } + } +} + +func (c *Client) handleResponse(node *core.Node, resp *discoveryv1.DiscoveryResponse) ([]*discoveryv1.DiscoveryRequest, error) { + c.mu.Lock() + defer c.mu.Unlock() + + typeURL := resp.GetTypeUrl() + switch typeURL { + case pkgmodel.ListenerType: + next := make(map[string]*listenerv1.Listener, len(resp.GetResources())) + for _, anyRes := range resp.GetResources() { + l := &listenerv1.Listener{} + if err := anyRes.UnmarshalTo(l); err != nil { + return nil, fmt.Errorf("decode LDS resource: %w", err) + } + next[l.GetName()] = l + } + c.cache.listeners = next + case pkgmodel.RouteType: + next := make(map[string]*routev1.RouteConfiguration, len(resp.GetResources())) + for _, anyRes := range resp.GetResources() { + rc := &routev1.RouteConfiguration{} + if err := anyRes.UnmarshalTo(rc); err != nil { + return nil, fmt.Errorf("decode RDS resource: %w", err) + } + next[rc.GetName()] = rc + } + c.cache.routes = next + case pkgmodel.ClusterType: + next := make(map[string]*clusterv1.Cluster, len(resp.GetResources())) + for _, anyRes := range resp.GetResources() { + cl := &clusterv1.Cluster{} + if err := anyRes.UnmarshalTo(cl); err != nil { + return nil, fmt.Errorf("decode CDS resource: %w", err) + } + next[cl.GetName()] = cl + } + c.cache.clusters = next + case pkgmodel.EndpointType: + for _, anyRes := range resp.GetResources() { + cla := &endpointv1.ClusterLoadAssignment{} + if err := anyRes.UnmarshalTo(cla); err != nil { + return nil, fmt.Errorf("decode EDS resource: %w", err) + } + c.cache.endpoints[cla.GetClusterName()] = cla + } + default: + return nil, fmt.Errorf("unsupported xDS type URL %q", typeURL) + } + + st, ok := c.states[typeURL] + if !ok { + st = &typeState{} + c.states[typeURL] = st + } + st.version = resp.GetVersionInfo() + st.nonce = resp.GetNonce() + + nextGen := c.status.Generation + 1 + snap, deps := c.cache.compile(nextGen) + c.snapshot.Store(snap) + + c.status.Connected = true + c.status.Ready = snap.Ready + c.status.Generation = nextGen + c.status.AcceptedVersions[typeURL] = resp.GetVersionInfo() + c.status.LastError = "" + + // 1) Always ACK the received response so dubbod marks this type SYNCED. + reqs := []*discoveryv1.DiscoveryRequest{ + { + Node: node, + TypeUrl: typeURL, + VersionInfo: st.version, + ResponseNonce: st.nonce, + ResourceNames: append([]string(nil), st.names...), + }, + } + + // 2) Trigger downstream RDS / CDS / EDS subscriptions when dependencies change. + depMap := map[string][]string{ + pkgmodel.RouteType: deps.routes, + pkgmodel.ClusterType: deps.clusters, + pkgmodel.EndpointType: deps.endpoints, + } + for _, depType := range []string{pkgmodel.RouteType, pkgmodel.ClusterType, pkgmodel.EndpointType} { + desired := depMap[depType] + depState := c.states[depType] + if len(desired) == 0 || reflect.DeepEqual(depState.names, desired) { + continue + } + depState.names = desired + reqs = append(reqs, &discoveryv1.DiscoveryRequest{ + Node: node, + TypeUrl: depType, + VersionInfo: depState.version, + ResponseNonce: depState.nonce, + ResourceNames: append([]string(nil), desired...), + }) + } + return reqs, nil +} + +func buildDialOptions(cfg Config) ([]grpc.DialOption, error) { + opts := []grpc.DialOption{ + grpc.WithKeepaliveParams(keepalive.ClientParameters{ + Time: 30 * time.Second, + Timeout: 10 * time.Second, + PermitWithoutStream: true, + }), + } + if cfg.Insecure { + opts = append(opts, grpc.WithTransportCredentials(insecure.NewCredentials())) + return opts, nil + } + tlsCfg, err := cfg.Certs.BuildClientTLSConfig(cfg.ServerURI, cfg.ServerName) + if err != nil { + return nil, err + } + opts = append(opts, grpc.WithTransportCredentials(credentials.NewTLS(tlsCfg))) + return opts, nil +} diff --git a/cni/pkg/xdsclient/client_test.go b/cni/pkg/xdsclient/client_test.go new file mode 100644 index 000000000..7f9f836ec --- /dev/null +++ b/cni/pkg/xdsclient/client_test.go @@ -0,0 +1,378 @@ +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to You 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. + +package xdsclient + +import ( + "context" + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/tls" + "crypto/x509" + "crypto/x509/pkix" + "encoding/pem" + "math/big" + "net" + "net/url" + "os" + "path/filepath" + "testing" + "time" + + "github.com/apache/dubbo-kubernetes/dubbod/discovery/pkg/config/memory" + "github.com/apache/dubbo-kubernetes/dubbod/discovery/pkg/model" + "github.com/apache/dubbo-kubernetes/dubbod/discovery/pkg/serviceregistry/aggregate" + "github.com/apache/dubbo-kubernetes/dubbod/discovery/pkg/util/protoconv" + discoveryxds "github.com/apache/dubbo-kubernetes/dubbod/discovery/pkg/xds" + "github.com/apache/dubbo-kubernetes/dubbod/security/pkg/server/ca/authenticate" + meshconfig "github.com/apache/dubbo-kubernetes/pkg/config/mesh" + "github.com/apache/dubbo-kubernetes/pkg/config/mesh/meshwatcher" + "github.com/apache/dubbo-kubernetes/pkg/config/schema/collection" + "github.com/apache/dubbo-kubernetes/pkg/kube/krt" + pkgmodel "github.com/apache/dubbo-kubernetes/pkg/model" + "github.com/apache/dubbo-kubernetes/pkg/security" + clusterv1 "github.com/dubml/xds-api/cluster/v1" + corev1 "github.com/dubml/xds-api/core/v1" + endpointv1 "github.com/dubml/xds-api/endpoint/v1" + hcmv1 "github.com/dubml/xds-api/extensions/filters/v1/network/http_connection_manager" + tlsv1 "github.com/dubml/xds-api/extensions/transport_sockets/tls/v1" + listenerv1 "github.com/dubml/xds-api/listener/v1" + routev1 "github.com/dubml/xds-api/route/v1" + "google.golang.org/grpc" + "google.golang.org/grpc/credentials" +) + +func TestResolveConfigPrecedenceArgsOverEnvOverManual(t *testing.T) { + t.Setenv("XDS_ADDRESS", "env.dubbod.svc:26012") + t.Setenv("POD_NAMESPACE", "env-ns") + t.Setenv("DUBBO_META_GENERATOR", "triple") + + cfg, err := ResolveConfig(Config{ + ServerURI: "manual.dubbod.svc:26012", + Namespace: "manual-ns", + Insecure: true, + }, []string{"--xds-address=arg.dubbod.svc:26012", "--xds-namespace=arg-ns"}) + if err != nil { + t.Fatalf("ResolveConfig() error = %v", err) + } + if cfg.ServerURI != "arg.dubbod.svc:26012" { + t.Fatalf("ServerURI = %q, want args override", cfg.ServerURI) + } + if cfg.Namespace != "arg-ns" { + t.Fatalf("Namespace = %q, want arg-ns", cfg.Namespace) + } + + // Env fallback when manual is empty and no args are supplied. + cfgEnv, err := ResolveConfig(Config{Insecure: true}, nil) + if err != nil { + t.Fatalf("ResolveConfig(env) error = %v", err) + } + if cfgEnv.ServerURI != "env.dubbod.svc:26012" || cfgEnv.Namespace != "env-ns" { + t.Fatalf("unexpected env config: %+v", cfgEnv) + } + + // Bootstrap file parsing via TRIPLE_XDS_BOOTSTRAP. + tmp := t.TempDir() + bootstrapPath := filepath.Join(tmp, "triple-bootstrap.json") + bootstrapJSON := `{ + "xds_servers": [{ + "server_uri": "dubbod.dubbo-system.svc:26012", + "channel_creds": [{"type": "tls", "config": { + "certificate_file": "/etc/dubbo/proxy/cert-chain.pem", + "private_key_file": "/etc/dubbo/proxy/key.pem", + "ca_certificate_file": "/etc/dubbo/proxy/root-cert.pem" + }}] + }], + "node": { + "id": "inherent~10.244.0.9~test-app.test-inject~test-inject.svc.cluster.local", + "metadata": {"GENERATOR": "triple", "NAMESPACE": "test-inject", "CLUSTER_ID": "Kubernetes"} + } +}` + if err := os.WriteFile(bootstrapPath, []byte(bootstrapJSON), 0o600); err != nil { + t.Fatal(err) + } + t.Setenv("XDS_ADDRESS", "") + t.Setenv("TRIPLE_XDS_BOOTSTRAP", bootstrapPath) + cfgBoot, err := ResolveConfig(Config{}, nil) + if err != nil { + t.Fatalf("ResolveConfig(bootstrap) error = %v", err) + } + if cfgBoot.ServerURI != "dubbod.dubbo-system.svc:26012" || cfgBoot.Node.GetId() != "inherent~10.244.0.9~test-app.test-inject~test-inject.svc.cluster.local" { + t.Fatalf("unexpected bootstrap config: %+v", cfgBoot) + } +} + +type staticGenerator struct { + resources map[string]model.Resources +} + +func (g staticGenerator) Generate(_ *model.Proxy, w *model.WatchedResource, _ *model.PushRequest) (model.Resources, model.XdsLogDetails, error) { + return g.resources[w.TypeUrl], model.DefaultXdsLogDetails, nil +} + +func TestClientSyncsWithDubbodMTLSAndAppearsInSyncz(t *testing.T) { + caCert, caKey, rootPEM := generateTestCA(t) + serverCert := generateTestCert(t, caCert, caKey, []string{"dubbod.dubbo-system.svc", "localhost"}, []net.IP{net.ParseIP("127.0.0.1")}, "") + clientCertPEM, clientKeyPEM := generateTestCertPEM(t, caCert, caKey, nil, nil, "spiffe://cluster.local/ns/test-inject/sa/default") + + rootPool := x509.NewCertPool() + rootPool.AppendCertsFromPEM(rootPEM) + + env := model.NewEnvironment() + env.ServiceDiscovery = aggregate.NewController(aggregate.Options{}) + env.ConfigStore = memory.Make(collection.Schemas{}) + env.Watcher = meshwatcher.ConfigAdapter(krt.NewStatic(&meshwatcher.MeshConfigResource{ + MeshConfig: meshconfig.DefaultMeshConfig(), + }, true)) + env.Init() + push := model.NewPushContext() + push.PushVersion = "test-v1" + push.InitContext(env, nil, nil) + env.SetPushContext(push) + ds := discoveryxds.NewDiscoveryServer(env, nil) + ds.Authenticators = []security.Authenticator{&authenticate.ClientCertAuthenticator{}} + ds.Authorize = func(_ *model.Proxy, ids []string) error { + if len(ids) == 0 { + return context.DeadlineExceeded + } + return nil + } + + listenerName := "echo.test-inject.svc.cluster.local:8080" + clusterName := "outbound|8080||echo.test-inject.svc.cluster.local" + hcm := &hcmv1.HttpConnectionManager{ + RouteSpecifier: &hcmv1.HttpConnectionManager_Rds{ + Rds: &hcmv1.Rds{RouteConfigName: clusterName}, + }, + } + gen := staticGenerator{ + resources: map[string]model.Resources{ + pkgmodel.ListenerType: {{ + Name: listenerName, + Resource: protoconv.MessageToAny(&listenerv1.Listener{ + Name: listenerName, + ApiListener: &listenerv1.ApiListener{ApiListener: protoconv.MessageToAny(hcm)}, + }), + }}, + pkgmodel.RouteType: {{ + Name: clusterName, + Resource: protoconv.MessageToAny(&routev1.RouteConfiguration{ + Name: clusterName, + VirtualHosts: []*routev1.VirtualHost{{ + Name: "vh", + Domains: []string{"*"}, + Routes: []*routev1.Route{{ + Match: &routev1.RouteMatch{PathSpecifier: &routev1.RouteMatch_Prefix{Prefix: "/"}}, + Action: &routev1.Route_Route{ + Route: &routev1.RouteAction{ + ClusterSpecifier: &routev1.RouteAction_Cluster{Cluster: clusterName}, + }, + }, + }}, + }}, + }), + }}, + pkgmodel.ClusterType: {{ + Name: clusterName, + Resource: protoconv.MessageToAny(&clusterv1.Cluster{ + Name: clusterName, + ClusterDiscoveryType: &clusterv1.Cluster_Type{Type: clusterv1.Cluster_EDS}, + EdsClusterConfig: &clusterv1.Cluster_EdsClusterConfig{ServiceName: clusterName}, + TransportSocket: &corev1.TransportSocket{ + Name: "tls", + ConfigType: &corev1.TransportSocket_TypedConfig{ + TypedConfig: protoconv.MessageToAny(&tlsv1.UpstreamTlsContext{Sni: "echo.test-inject.svc.cluster.local"}), + }, + }, + }), + }}, + pkgmodel.EndpointType: {{ + Name: clusterName, + Resource: protoconv.MessageToAny(&endpointv1.ClusterLoadAssignment{ + ClusterName: clusterName, + Endpoints: []*endpointv1.LocalityLbEndpoints{{ + LbEndpoints: []*endpointv1.LbEndpoint{{ + HealthStatus: corev1.HealthStatus_HEALTHY, + HostIdentifier: &endpointv1.LbEndpoint_Endpoint{ + Endpoint: &endpointv1.Endpoint{ + Address: &corev1.Address{ + Address: &corev1.Address_SocketAddress{ + SocketAddress: &corev1.SocketAddress{ + Address: "10.244.0.12", + PortSpecifier: &corev1.SocketAddress_PortValue{PortValue: 8080}, + }, + }, + }, + }, + }, + }}, + }}, + }), + }}, + }, + } + ds.Generators = map[string]model.XdsResourceGenerator{ + "triple/" + pkgmodel.ListenerType: gen, + "triple/" + pkgmodel.RouteType: gen, + "triple/" + pkgmodel.ClusterType: gen, + "triple/" + pkgmodel.EndpointType: gen, + } + ds.CachesSynced() + + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + defer ln.Close() + + grpcSrv := grpc.NewServer(grpc.Creds(credentials.NewTLS(&tls.Config{ + Certificates: []tls.Certificate{serverCert}, + ClientCAs: rootPool, + ClientAuth: tls.RequireAndVerifyClientCert, + MinVersion: tls.VersionTLS12, + }))) + ds.Register(grpcSrv) + go func() { _ = grpcSrv.Serve(ln) }() + defer grpcSrv.Stop() + + client, err := New(Config{ + ServerURI: ln.Addr().String(), + ServerName: "dubbod.dubbo-system.svc", + NodeID: "inherent~10.244.0.9~test-app.test-inject~test-inject.svc.cluster.local", + Namespace: "test-inject", + ClusterID: "Kubernetes", + Generator: "triple", + Certs: CertMaterial{ + CertChainPEM: clientCertPEM, + KeyPEM: clientKeyPEM, + RootCertPEM: rootPEM, + }, + }) + if err != nil { + t.Fatal(err) + } + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + go func() { _ = client.Run(ctx) }() + + deadline := time.Now().Add(5 * time.Second) + for time.Now().Before(deadline) { + snap := client.Snapshot() + if snap.Ready { + sel, err := snap.Select(listenerName, listenerName, "/hello", 1) + if err == nil && sel.Endpoint.HostPort() == "10.244.0.12:8080" && sel.UseMTLS { + break + } + } + time.Sleep(25 * time.Millisecond) + } + if !client.Snapshot().Ready { + t.Fatalf("client snapshot never became ready; status=%+v", client.Status()) + } + + // Verify dubbod /debug/syncz reports test-app as connected and SYNCED. + var synced bool + for time.Now().Before(deadline) { + syncz := ds.Syncz() + if len(syncz) == 1 && syncz[0].ProxyID == "test-app.test-inject" { + allSynced := len(syncz[0].WatchedTypes) >= 4 + for _, wt := range syncz[0].WatchedTypes { + if !wt.Synced { + allSynced = false + } + } + if allSynced { + synced = true + break + } + } + time.Sleep(25 * time.Millisecond) + } + if !synced { + t.Fatalf("dubbod Syncz did not report test-app.test-inject SYNCED: %+v", ds.Syncz()) + } +} + +func generateTestCA(t *testing.T) (*x509.Certificate, *ecdsa.PrivateKey, []byte) { + t.Helper() + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + t.Fatal(err) + } + tmpl := &x509.Certificate{ + SerialNumber: big.NewInt(1), + Subject: pkix.Name{CommonName: "dubbo-test-ca"}, + NotBefore: time.Now().Add(-time.Hour), + NotAfter: time.Now().Add(time.Hour), + IsCA: true, + BasicConstraintsValid: true, + KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign, + } + der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key) + if err != nil { + t.Fatal(err) + } + cert, err := x509.ParseCertificate(der) + if err != nil { + t.Fatal(err) + } + return cert, key, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}) +} + +func generateTestCert(t *testing.T, caCert *x509.Certificate, caKey *ecdsa.PrivateKey, dns []string, ips []net.IP, spiffeURI string) tls.Certificate { + t.Helper() + certPEM, keyPEM := generateTestCertPEM(t, caCert, caKey, dns, ips, spiffeURI) + cert, err := tls.X509KeyPair(certPEM, keyPEM) + if err != nil { + t.Fatal(err) + } + return cert +} + +func generateTestCertPEM(t *testing.T, caCert *x509.Certificate, caKey *ecdsa.PrivateKey, dns []string, ips []net.IP, spiffeURI string) ([]byte, []byte) { + t.Helper() + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + t.Fatal(err) + } + tmpl := &x509.Certificate{ + SerialNumber: big.NewInt(time.Now().UnixNano()), + NotBefore: time.Now().Add(-time.Hour), + NotAfter: time.Now().Add(time.Hour), + DNSNames: dns, + IPAddresses: ips, + KeyUsage: x509.KeyUsageDigitalSignature, + ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth}, + } + if spiffeURI != "" { + u, err := url.Parse(spiffeURI) + if err != nil { + t.Fatal(err) + } + tmpl.URIs = []*url.URL{u} + } + der, err := x509.CreateCertificate(rand.Reader, tmpl, caCert, &key.PublicKey, caKey) + if err != nil { + t.Fatal(err) + } + keyDER, err := x509.MarshalPKCS8PrivateKey(key) + if err != nil { + t.Fatal(err) + } + return pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}), + pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: keyDER}) +} diff --git a/cni/pkg/xdsclient/config.go b/cni/pkg/xdsclient/config.go new file mode 100644 index 000000000..55a97977e --- /dev/null +++ b/cni/pkg/xdsclient/config.go @@ -0,0 +1,396 @@ +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to You 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. + +package xdsclient + +import ( + "crypto/tls" + "crypto/x509" + "encoding/json" + "flag" + "fmt" + "net" + "os" + "path/filepath" + "strings" + + "github.com/apache/dubbo-kubernetes/pkg/config/constants" + "github.com/apache/dubbo-kubernetes/pkg/kube/inject" + core "github.com/dubml/xds-api/core/v1" + "google.golang.org/protobuf/encoding/protojson" + "google.golang.org/protobuf/types/known/structpb" +) + +// CertMaterial holds either in-memory PEM bytes (from a Kubernetes dubbo-xds-* Secret) +// or file paths (from /etc/dubbo/proxy mounted by triple-engine). +type CertMaterial struct { + CertChainPEM []byte + KeyPEM []byte + RootCertPEM []byte + + CertChainFile string + KeyFile string + RootCertFile string +} + +// Config configures a Triple xDS ADS client connection to dubbod. +// It can be populated manually in code, automatically via env/args, or directly +// from a Pod's dubbo-xds-* Secret managed by dubbod. +type Config struct { + BootstrapFile string + ServerURI string + ServerName string + Node *core.Node + NodeID string + Namespace string + ClusterID string + Generator string + Certs CertMaterial + Insecure bool + Listeners []string +} + +type rawBootstrap struct { + XDSServers []struct { + ServerURI string `json:"server_uri"` + ChannelCreds []struct { + Type string `json:"type"` + Config struct { + CertificateFile string `json:"certificate_file"` + PrivateKeyFile string `json:"private_key_file"` + CACertificateFile string `json:"ca_certificate_file"` + } `json:"config"` + } `json:"channel_creds"` + } `json:"xds_servers"` + Node json.RawMessage `json:"node"` + CertProviders map[string]struct { + PluginName string `json:"plugin_name"` + Config struct { + CertificateFile string `json:"certificate_file"` + PrivateKeyFile string `json:"private_key_file"` + CACertificateFile string `json:"ca_certificate_file"` + } `json:"config"` + } `json:"certificate_providers"` +} + +// ParseBootstrapBytes parses a dubbod triple-bootstrap.json payload into Config. +func ParseBootstrapBytes(data []byte) (Config, error) { + var raw rawBootstrap + if err := json.Unmarshal(data, &raw); err != nil { + return Config{}, fmt.Errorf("parse triple bootstrap json: %w", err) + } + if len(raw.XDSServers) == 0 || strings.TrimSpace(raw.XDSServers[0].ServerURI) == "" { + return Config{}, fmt.Errorf("triple bootstrap missing xds_servers[0].server_uri") + } + + cfg := Config{ + ServerURI: raw.XDSServers[0].ServerURI, + } + + if len(raw.Node) > 0 && string(raw.Node) != "null" { + node := &core.Node{} + if err := (protojson.UnmarshalOptions{DiscardUnknown: true}).Unmarshal(raw.Node, node); err != nil { + return Config{}, fmt.Errorf("parse bootstrap node: %w", err) + } + cfg.Node = node + cfg.NodeID = node.GetId() + if fields := node.GetMetadata().GetFields(); fields != nil { + if v, ok := fields["GENERATOR"]; ok { + cfg.Generator = v.GetStringValue() + } + if v, ok := fields["NAMESPACE"]; ok { + cfg.Namespace = v.GetStringValue() + } + if v, ok := fields["CLUSTER_ID"]; ok { + cfg.ClusterID = v.GetStringValue() + } + } + } + + // Extract TLS file paths from channel_creds or certificate_providers["default"]. + for _, cred := range raw.XDSServers[0].ChannelCreds { + switch cred.Type { + case "insecure": + cfg.Insecure = true + case "tls": + cfg.Certs.CertChainFile = cred.Config.CertificateFile + cfg.Certs.KeyFile = cred.Config.PrivateKeyFile + cfg.Certs.RootCertFile = cred.Config.CACertificateFile + } + } + if cfg.Certs.CertChainFile == "" { + if def, ok := raw.CertProviders["default"]; ok { + cfg.Certs.CertChainFile = def.Config.CertificateFile + cfg.Certs.KeyFile = def.Config.PrivateKeyFile + cfg.Certs.RootCertFile = def.Config.CACertificateFile + } + } + if cfg.Generator == "" { + cfg.Generator = "triple" + } + return cfg, nil +} + +// ConfigFromSecretData builds an authenticated Config from a Pod's dubbo-xds-* Secret data. +func ConfigFromSecretData(data map[string][]byte) (Config, error) { + bootstrapBytes := data[inject.InherentTripleBootstrapFileName] + if len(bootstrapBytes) == 0 { + return Config{}, fmt.Errorf("secret missing %s", inject.InherentTripleBootstrapFileName) + } + cfg, err := ParseBootstrapBytes(bootstrapBytes) + if err != nil { + return Config{}, err + } + cfg.Certs.CertChainPEM = append([]byte(nil), data[constants.CertChainFilename]...) + cfg.Certs.KeyPEM = append([]byte(nil), data[constants.KeyFilename]...) + cfg.Certs.RootCertPEM = append([]byte(nil), data[constants.CACertNamespaceConfigMapDataName]...) + if !cfg.Insecure && (len(cfg.Certs.CertChainPEM) == 0 || len(cfg.Certs.KeyPEM) == 0 || len(cfg.Certs.RootCertPEM) == 0) { + return Config{}, fmt.Errorf("secret missing workload TLS credentials (%s/%s/%s)", + constants.CertChainFilename, constants.KeyFilename, constants.CACertNamespaceConfigMapDataName) + } + return cfg, nil +} + +// ResolveConfig merges configuration with precedence: args > env > manual. +func ResolveConfig(manual Config, args []string) (Config, error) { + cfg := manual + + // Env fallback aligned with webhook injection. + if cfg.BootstrapFile == "" { + cfg.BootstrapFile = os.Getenv(inject.InherentTripleBootstrapEnvName) + } + if cfg.ServerURI == "" { + if addr := os.Getenv("XDS_ADDRESS"); addr != "" { + cfg.ServerURI = addr + } else if reg := os.Getenv("DUBBO_REGISTRY_ADDRESS"); reg != "" { + cfg.ServerURI = strings.TrimPrefix(reg, "xds://") + } + } + if cfg.Namespace == "" { + cfg.Namespace = os.Getenv("POD_NAMESPACE") + } + if cfg.ClusterID == "" { + cfg.ClusterID = os.Getenv("DUBBO_META_CLUSTER_ID") + } + if cfg.Generator == "" { + cfg.Generator = os.Getenv("DUBBO_META_GENERATOR") + } + + // CLI args override both manual and env. + if len(args) > 0 { + fs := flag.NewFlagSet("xdsclient", flag.ContinueOnError) + var fBootstrap, fAddr, fCertDir, fNodeID, fNS, fGen string + fs.StringVar(&fBootstrap, "xds-bootstrap", "", "path to triple-bootstrap.json") + fs.StringVar(&fAddr, "xds-address", "", "dubbod xDS server address") + fs.StringVar(&fCertDir, "xds-cert-dir", "", "directory containing workload certs") + fs.StringVar(&fNodeID, "xds-node-id", "", "xDS node identifier") + fs.StringVar(&fNS, "xds-namespace", "", "workload namespace") + fs.StringVar(&fGen, "xds-generator", "", "xDS generator name") + if err := fs.Parse(args); err != nil { + return Config{}, err + } + if fBootstrap != "" { + cfg.BootstrapFile = fBootstrap + } + if fAddr != "" { + cfg.ServerURI = fAddr + } + if fCertDir != "" { + cfg.Certs.CertChainFile = filepath.Join(fCertDir, constants.CertChainFilename) + cfg.Certs.KeyFile = filepath.Join(fCertDir, constants.KeyFilename) + cfg.Certs.RootCertFile = filepath.Join(fCertDir, constants.CACertNamespaceConfigMapDataName) + } + if fNodeID != "" { + cfg.NodeID = fNodeID + } + if fNS != "" { + cfg.Namespace = fNS + } + if fGen != "" { + cfg.Generator = fGen + } + } + + if cfg.BootstrapFile != "" { + raw, err := os.ReadFile(cfg.BootstrapFile) + if err != nil { + return Config{}, fmt.Errorf("read bootstrap file %s: %w", cfg.BootstrapFile, err) + } + parsed, err := ParseBootstrapBytes(raw) + if err != nil { + return Config{}, err + } + if cfg.ServerURI == "" { + cfg.ServerURI = parsed.ServerURI + } + if cfg.Node == nil { + cfg.Node = parsed.Node + } + if cfg.NodeID == "" { + cfg.NodeID = parsed.NodeID + } + if cfg.Namespace == "" { + cfg.Namespace = parsed.Namespace + } + if cfg.ClusterID == "" { + cfg.ClusterID = parsed.ClusterID + } + if cfg.Generator == "" { + cfg.Generator = parsed.Generator + } + if cfg.Certs.CertChainFile == "" && len(cfg.Certs.CertChainPEM) == 0 { + cfg.Certs = parsed.Certs + } + if !cfg.Insecure { + cfg.Insecure = parsed.Insecure + } + } + + if cfg.Generator == "" { + cfg.Generator = "triple" + } + if cfg.ClusterID == "" { + cfg.ClusterID = constants.DefaultClusterName + } + if cfg.ServerURI == "" { + return Config{}, fmt.Errorf("missing xDS server URI") + } + node, err := cfg.EffectiveNode() + if err != nil { + return Config{}, err + } + cfg.Node = node + return cfg, nil +} + +// EffectiveNode builds or normalizes the core.Node sent on ADS streams. +func (c *Config) EffectiveNode() (*core.Node, error) { + if c.Node != nil && c.Node.GetId() != "" { + return c.Node, nil + } + nodeID := c.NodeID + if nodeID == "" { + ns := c.Namespace + if ns == "" { + ns = "default" + } + host, _ := os.Hostname() + if host == "" { + host = "workload" + } + ip := os.Getenv("INSTANCE_IP") + if ip == "" { + ip = "0.0.0.0" + } + nodeID = fmt.Sprintf("inherent~%s~%s.%s~%s.svc.%s", ip, host, ns, ns, constants.DefaultClusterLocalDomain) + } + gen := c.Generator + if gen == "" { + gen = "triple" + } + clusterID := c.ClusterID + if clusterID == "" { + clusterID = constants.DefaultClusterName + } + metaMap := map[string]any{ + "GENERATOR": gen, + "CLUSTER_ID": clusterID, + } + if c.Namespace != "" { + metaMap["NAMESPACE"] = c.Namespace + } + meta, err := structpb.NewStruct(metaMap) + if err != nil { + return nil, err + } + return &core.Node{ + Id: nodeID, + Metadata: meta, + }, nil +} + +// BuildClientTLSConfig builds a TLS config from CertMaterial (in-memory PEM or files). +func (m CertMaterial) BuildClientTLSConfig(serverURI, overrideServerName string) (*tls.Config, error) { + rootPEM := m.RootCertPEM + if len(rootPEM) == 0 && m.RootCertFile != "" { + var err error + rootPEM, err = os.ReadFile(m.RootCertFile) + if err != nil { + return nil, fmt.Errorf("read root CA %s: %w", m.RootCertFile, err) + } + } + if len(rootPEM) == 0 { + return nil, fmt.Errorf("missing root CA certificate") + } + pool := x509.NewCertPool() + if !pool.AppendCertsFromPEM(rootPEM) { + return nil, fmt.Errorf("failed to parse root CA PEM") + } + + serverName := overrideServerName + if serverName == "" { + target := strings.TrimPrefix(strings.TrimPrefix(serverURI, "https://"), "http://") + if host, _, err := net.SplitHostPort(target); err == nil { + serverName = host + } else { + serverName = target + } + if serverName == "127.0.0.1" || serverName == "localhost" || serverName == "::1" { + serverName = "dubbod.dubbo-system.svc" + } + } + + certCopy := m + return &tls.Config{ + RootCAs: pool, + ServerName: serverName, + MinVersion: tls.VersionTLS12, + GetClientCertificate: func(*tls.CertificateRequestInfo) (*tls.Certificate, error) { + cert, err := certCopy.LoadKeyPair() + if err != nil { + return nil, err + } + return &cert, nil + }, + }, nil +} + +// LoadKeyPair loads the workload certificate and private key from memory or disk. +func (m CertMaterial) LoadKeyPair() (tls.Certificate, error) { + if len(m.CertChainPEM) > 0 && len(m.KeyPEM) > 0 { + return tls.X509KeyPair(m.CertChainPEM, m.KeyPEM) + } + if m.CertChainFile != "" && m.KeyFile != "" { + return tls.LoadX509KeyPair(m.CertChainFile, m.KeyFile) + } + return tls.Certificate{}, fmt.Errorf("missing workload certificate and key") +} + +// RootCertPool parses the mesh root CA into an x509.CertPool. +func (m CertMaterial) RootCertPool() (*x509.CertPool, error) { + rootPEM := m.RootCertPEM + if len(rootPEM) == 0 && m.RootCertFile != "" { + var err error + rootPEM, err = os.ReadFile(m.RootCertFile) + if err != nil { + return nil, err + } + } + pool := x509.NewCertPool() + if len(rootPEM) == 0 || !pool.AppendCertsFromPEM(rootPEM) { + return nil, fmt.Errorf("invalid root certificate PEM") + } + return pool, nil +} diff --git a/cni/pkg/xdsclient/snapshot.go b/cni/pkg/xdsclient/snapshot.go new file mode 100644 index 000000000..2c7e4aa89 --- /dev/null +++ b/cni/pkg/xdsclient/snapshot.go @@ -0,0 +1,497 @@ +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to You 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. + +package xdsclient + +import ( + "fmt" + "net" + "sort" + "strconv" + "strings" + "time" + + clusterv1 "github.com/dubml/xds-api/cluster/v1" + corev1 "github.com/dubml/xds-api/core/v1" + endpointv1 "github.com/dubml/xds-api/endpoint/v1" + hcmv1 "github.com/dubml/xds-api/extensions/filters/v1/network/http_connection_manager" + tlsv1 "github.com/dubml/xds-api/extensions/transport_sockets/tls/v1" + listenerv1 "github.com/dubml/xds-api/listener/v1" + routev1 "github.com/dubml/xds-api/route/v1" +) + +// TargetEndpoint represents a healthy selectable backend endpoint. +type TargetEndpoint struct { + Address string + Port uint32 + Weight uint32 +} + +// HostPort returns net.JoinHostPort for this endpoint. +func (e TargetEndpoint) HostPort() string { + return net.JoinHostPort(e.Address, strconv.Itoa(int(e.Port))) +} + +// TargetCluster holds the compiled cluster routing and TLS parameters. +type TargetCluster struct { + Name string + ServiceName string + Endpoints []TargetEndpoint + UseMTLS bool + SNI string + ConnectTimeout time.Duration +} + +// Snapshot is an immutable, atomically published routing table compiled from LDS/RDS/CDS/EDS. +type Snapshot struct { + Generation uint64 + Ready bool + Listeners map[string]*routev1.RouteConfiguration + Clusters map[string]*TargetCluster +} + +// Selection is the resolved routing decision for a single connection or request. +type Selection struct { + ClusterName string + Endpoint TargetEndpoint + UseMTLS bool + SNI string + ConnectTimeout time.Duration +} + +// resourceCache maintains the latest validated xDS resources per type. +type resourceCache struct { + listeners map[string]*listenerv1.Listener + routes map[string]*routev1.RouteConfiguration + clusters map[string]*clusterv1.Cluster + endpoints map[string]*endpointv1.ClusterLoadAssignment +} + +func newResourceCache() *resourceCache { + return &resourceCache{ + listeners: map[string]*listenerv1.Listener{}, + routes: map[string]*routev1.RouteConfiguration{}, + clusters: map[string]*clusterv1.Cluster{}, + endpoints: map[string]*endpointv1.ClusterLoadAssignment{}, + } +} + +type dependencies struct { + routes []string + clusters []string + endpoints []string +} + +func (c *resourceCache) compile(generation uint64) (*Snapshot, dependencies) { + snap := &Snapshot{ + Generation: generation, + Listeners: make(map[string]*routev1.RouteConfiguration, len(c.listeners)), + Clusters: make(map[string]*TargetCluster, len(c.clusters)), + } + + routeSet := map[string]struct{}{} + clusterSet := map[string]struct{}{} + endpointSet := map[string]struct{}{} + missing := false + + for name, l := range c.listeners { + if l == nil { + continue + } + hcm := extractHCM(l) + if hcm == nil { + continue + } + switch rs := hcm.GetRouteSpecifier().(type) { + case *hcmv1.HttpConnectionManager_RouteConfig: + if rs.RouteConfig != nil { + snap.Listeners[name] = rs.RouteConfig + collectRouteClusters(rs.RouteConfig, clusterSet) + } + case *hcmv1.HttpConnectionManager_Rds: + if rs.Rds != nil && rs.Rds.RouteConfigName != "" { + routeName := rs.Rds.RouteConfigName + routeSet[routeName] = struct{}{} + if rc, ok := c.routes[routeName]; ok && rc != nil { + snap.Listeners[name] = rc + collectRouteClusters(rc, clusterSet) + } else { + missing = true + } + } + } + } + + for name, cl := range c.clusters { + if cl == nil { + continue + } + tc := compileCluster(cl, c.endpoints) + snap.Clusters[name] = tc + if cl.GetType() == clusterv1.Cluster_EDS { + svcName := cl.GetEdsClusterConfig().GetServiceName() + if svcName == "" { + svcName = name + } + endpointSet[svcName] = struct{}{} + } + } + + for clName := range clusterSet { + if _, ok := c.clusters[clName]; !ok { + missing = true + } + } + for epName := range endpointSet { + if _, ok := c.endpoints[epName]; !ok { + missing = true + } + } + + snap.Ready = len(c.listeners) > 0 && !missing + return snap, dependencies{ + routes: sortedKeys(routeSet), + clusters: sortedKeys(clusterSet), + endpoints: sortedKeys(endpointSet), + } +} + +// Select resolves an endpoint by listener name (or host:port fallback), authority, path, and deterministic ticket. +func (s *Snapshot) Select(listenerName, authority, path string, ticket uint64) (Selection, error) { + if s == nil { + return Selection{}, fmt.Errorf("xDS snapshot unavailable") + } + + rc := s.Listeners[listenerName] + if rc == nil && authority != "" { + rc = s.Listeners[authority] + } + if rc == nil { + // Fallback: direct cluster lookup if listenerName matches a known cluster/service. + if tc, ok := s.Clusters[listenerName]; ok { + return selectFromCluster(tc, ticket) + } + return Selection{}, fmt.Errorf("no xDS listener for %q", listenerName) + } + + clusterName := matchRouteCluster(rc, authority, path, ticket) + if clusterName == "" { + return Selection{}, fmt.Errorf("no matching xDS route for listener %q authority %q path %q", listenerName, authority, path) + } + tc, ok := s.Clusters[clusterName] + if !ok { + return Selection{}, fmt.Errorf("xDS cluster %q not found", clusterName) + } + return selectFromCluster(tc, ticket) +} + +// SelectByDestinationIPPort matches a Cluster or Listener using a destination ClusterIP:port or host:port. +func (s *Snapshot) SelectByDestinationIPPort(destAddr string, ticket uint64) (Selection, error) { + if s == nil { + return Selection{}, fmt.Errorf("xDS snapshot unavailable") + } + if sel, err := s.Select(destAddr, destAddr, "/", ticket); err == nil { + return sel, nil + } + host, portStr, err := net.SplitHostPort(destAddr) + if err != nil { + return Selection{}, fmt.Errorf("invalid destination %q: %w", destAddr, err) + } + // Check if destAddr is already a known healthy endpoint in any cluster (direct pod IP). + for _, tc := range s.Clusters { + for _, ep := range tc.Endpoints { + if ep.Address == host && strconv.Itoa(int(ep.Port)) == portStr { + return Selection{ + ClusterName: tc.Name, + Endpoint: ep, + UseMTLS: tc.UseMTLS, + SNI: tc.SNI, + ConnectTimeout: tc.ConnectTimeout, + }, nil + } + } + } + return Selection{}, fmt.Errorf("no xDS route or endpoint matches destination %q", destAddr) +} + +func selectFromCluster(tc *TargetCluster, ticket uint64) (Selection, error) { + if tc == nil || len(tc.Endpoints) == 0 { + name := "" + if tc != nil { + name = tc.Name + } + return Selection{}, fmt.Errorf("no healthy endpoints for cluster %q", name) + } + var totalWeight uint64 + for _, ep := range tc.Endpoints { + w := uint64(ep.Weight) + if w == 0 { + w = 1 + } + totalWeight += w + } + slot := ticket % totalWeight + var acc uint64 + chosen := tc.Endpoints[0] + for _, ep := range tc.Endpoints { + w := uint64(ep.Weight) + if w == 0 { + w = 1 + } + acc += w + if slot < acc { + chosen = ep + break + } + } + return Selection{ + ClusterName: tc.Name, + Endpoint: chosen, + UseMTLS: tc.UseMTLS, + SNI: tc.SNI, + ConnectTimeout: tc.ConnectTimeout, + }, nil +} + +func extractHCM(l *listenerv1.Listener) *hcmv1.HttpConnectionManager { + if api := l.GetApiListener().GetApiListener(); api != nil { + hcm := &hcmv1.HttpConnectionManager{} + if err := api.UnmarshalTo(hcm); err == nil { + return hcm + } + } + for _, fc := range l.GetFilterChains() { + for _, f := range fc.GetFilters() { + if typed := f.GetTypedConfig(); typed != nil { + hcm := &hcmv1.HttpConnectionManager{} + if err := typed.UnmarshalTo(hcm); err == nil { + return hcm + } + } + } + } + return nil +} + +func collectRouteClusters(rc *routev1.RouteConfiguration, out map[string]struct{}) { + for _, vh := range rc.GetVirtualHosts() { + for _, r := range vh.GetRoutes() { + ra := r.GetRoute() + if ra == nil { + continue + } + switch cs := ra.GetClusterSpecifier().(type) { + case *routev1.RouteAction_Cluster: + if cs.Cluster != "" { + out[cs.Cluster] = struct{}{} + } + case *routev1.RouteAction_WeightedClusters: + for _, wc := range cs.WeightedClusters.GetClusters() { + if wc.GetName() != "" { + out[wc.GetName()] = struct{}{} + } + } + } + } + } +} + +func compileCluster(cl *clusterv1.Cluster, eds map[string]*endpointv1.ClusterLoadAssignment) *TargetCluster { + tc := &TargetCluster{ + Name: cl.GetName(), + ConnectTimeout: 5 * time.Second, + } + if d := cl.GetConnectTimeout(); d != nil && d.AsDuration() > 0 { + tc.ConnectTimeout = d.AsDuration() + } + if ts := cl.GetTransportSocket().GetTypedConfig(); ts != nil { + tlsCtx := &tlsv1.UpstreamTlsContext{} + if err := ts.UnmarshalTo(tlsCtx); err == nil { + tc.UseMTLS = true + tc.SNI = tlsCtx.GetSni() + } + } + + var cla *endpointv1.ClusterLoadAssignment + if cl.GetType() == clusterv1.Cluster_EDS { + svcName := cl.GetEdsClusterConfig().GetServiceName() + if svcName == "" { + svcName = cl.GetName() + } + tc.ServiceName = svcName + cla = eds[svcName] + } else { + cla = cl.GetLoadAssignment() + } + + if cla != nil { + tc.Endpoints = extractHealthyEndpoints(cla) + } + return tc +} + +func extractHealthyEndpoints(cla *endpointv1.ClusterLoadAssignment) []TargetEndpoint { + var minPriority uint32 = ^uint32(0) + var byPriority []struct { + priority uint32 + ep TargetEndpoint + } + for _, loc := range cla.GetEndpoints() { + locWeight := uint32(1) + if loc.GetLoadBalancingWeight() != nil && loc.GetLoadBalancingWeight().GetValue() > 0 { + locWeight = loc.GetLoadBalancingWeight().GetValue() + } + for _, lb := range loc.GetLbEndpoints() { + if lb.GetHealthStatus() != corev1.HealthStatus_UNKNOWN && lb.GetHealthStatus() != corev1.HealthStatus_HEALTHY { + continue + } + sa := lb.GetEndpoint().GetAddress().GetSocketAddress() + if sa == nil || sa.GetAddress() == "" || sa.GetPortValue() == 0 { + continue + } + epWeight := uint32(1) + if lb.GetLoadBalancingWeight() != nil && lb.GetLoadBalancingWeight().GetValue() > 0 { + epWeight = lb.GetLoadBalancingWeight().GetValue() + } + p := loc.GetPriority() + if p < minPriority { + minPriority = p + } + byPriority = append(byPriority, struct { + priority uint32 + ep TargetEndpoint + }{ + priority: p, + ep: TargetEndpoint{ + Address: sa.GetAddress(), + Port: sa.GetPortValue(), + Weight: locWeight * epWeight, + }, + }) + } + } + out := make([]TargetEndpoint, 0, len(byPriority)) + for _, item := range byPriority { + if item.priority == minPriority { + out = append(out, item.ep) + } + } + return out +} + +func matchRouteCluster(rc *routev1.RouteConfiguration, authority, path string, ticket uint64) string { + vh := matchVirtualHost(rc.GetVirtualHosts(), authority) + if vh == nil { + return "" + } + if path == "" { + path = "/" + } + for _, r := range vh.GetRoutes() { + if !routeMatchesPath(r.GetMatch(), path) { + continue + } + ra := r.GetRoute() + if ra == nil { + continue + } + switch cs := ra.GetClusterSpecifier().(type) { + case *routev1.RouteAction_Cluster: + return cs.Cluster + case *routev1.RouteAction_WeightedClusters: + return selectWeightedCluster(cs.WeightedClusters, ticket) + } + } + return "" +} + +func matchVirtualHost(vhs []*routev1.VirtualHost, authority string) *routev1.VirtualHost { + hostOnly := authority + if h, _, err := net.SplitHostPort(authority); err == nil { + hostOnly = h + } + var wildcard *routev1.VirtualHost + for _, vh := range vhs { + for _, d := range vh.GetDomains() { + if d == "*" { + if wildcard == nil { + wildcard = vh + } + continue + } + if strings.EqualFold(d, authority) || strings.EqualFold(d, hostOnly) { + return vh + } + if strings.HasPrefix(d, "*.") && strings.HasSuffix(strings.ToLower(hostOnly), strings.ToLower(d[1:])) { + return vh + } + } + } + return wildcard +} + +func routeMatchesPath(m *routev1.RouteMatch, path string) bool { + if m == nil { + return true + } + switch ps := m.GetPathSpecifier().(type) { + case *routev1.RouteMatch_Prefix: + return strings.HasPrefix(path, ps.Prefix) + case *routev1.RouteMatch_Path: + return path == ps.Path + default: + return true + } +} + +func selectWeightedCluster(wc *routev1.WeightedCluster, ticket uint64) string { + clusters := wc.GetClusters() + if len(clusters) == 0 { + return "" + } + var total uint64 + for _, c := range clusters { + w := uint64(c.GetWeight().GetValue()) + if w == 0 { + w = 1 + } + total += w + } + slot := ticket % total + var acc uint64 + for _, c := range clusters { + w := uint64(c.GetWeight().GetValue()) + if w == 0 { + w = 1 + } + acc += w + if slot < acc { + return c.GetName() + } + } + return clusters[0].GetName() +} + +func sortedKeys(m map[string]struct{}) []string { + if len(m) == 0 { + return nil + } + out := make([]string, 0, len(m)) + for k := range m { + out = append(out, k) + } + sort.Strings(out) + return out +}