|
| 1 | +/* |
| 2 | +Copyright 2025. |
| 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 csrapproval |
| 18 | + |
| 19 | +import ( |
| 20 | + "context" |
| 21 | + "fmt" |
| 22 | + |
| 23 | + corev1 "k8s.io/api/core/v1" |
| 24 | + "k8s.io/apimachinery/pkg/types" |
| 25 | + "k8s.io/client-go/kubernetes" |
| 26 | + "k8s.io/client-go/tools/clientcmd" |
| 27 | + clientcmdapi "k8s.io/client-go/tools/clientcmd/api" |
| 28 | + "sigs.k8s.io/controller-runtime/pkg/client" |
| 29 | +) |
| 30 | + |
| 31 | +// ClientManager manages hosted cluster client lifecycle |
| 32 | +type ClientManager struct { |
| 33 | + mgmtClient client.Client |
| 34 | + // hcClients caches Kubernetes clientsets for hosted clusters to avoid recreating them on every reconciliation. |
| 35 | + // Each DPFHCPProvisioner creates a hosted cluster with its own API server. This map stores one clientset |
| 36 | + // per hosted cluster (keyed by "namespace/name") to reuse connections and avoid expensive client creation |
| 37 | + // (parsing kubeconfig, establishing TCP connections) every 30 seconds during CSR polling. |
| 38 | + // Without this cache, we would create 120+ clients per hour per hosted cluster. |
| 39 | + hcClients map[string]*kubernetes.Clientset |
| 40 | +} |
| 41 | + |
| 42 | +// NewClientManager creates a new client manager |
| 43 | +func NewClientManager(mgmtClient client.Client) *ClientManager { |
| 44 | + return &ClientManager{ |
| 45 | + mgmtClient: mgmtClient, |
| 46 | + hcClients: make(map[string]*kubernetes.Clientset), |
| 47 | + } |
| 48 | +} |
| 49 | + |
| 50 | +// GetHostedClusterClient retrieves or creates a client for the hosted cluster |
| 51 | +func (cm *ClientManager) GetHostedClusterClient(ctx context.Context, namespace, name string) (*kubernetes.Clientset, error) { |
| 52 | + key := namespace + "/" + name |
| 53 | + |
| 54 | + // Return cached client if it exists |
| 55 | + if clientset, ok := cm.hcClients[key]; ok { |
| 56 | + return clientset, nil |
| 57 | + } |
| 58 | + |
| 59 | + // Create new client |
| 60 | + clientset, err := cm.createHostedClusterClient(ctx, namespace, name) |
| 61 | + if err != nil { |
| 62 | + return nil, err |
| 63 | + } |
| 64 | + |
| 65 | + // Cache the client |
| 66 | + cm.hcClients[key] = clientset |
| 67 | + |
| 68 | + return clientset, nil |
| 69 | +} |
| 70 | + |
| 71 | +// InvalidateClient removes a cached client (useful when kubeconfig rotates) |
| 72 | +func (cm *ClientManager) InvalidateClient(namespace, name string) { |
| 73 | + key := namespace + "/" + name |
| 74 | + delete(cm.hcClients, key) |
| 75 | +} |
| 76 | + |
| 77 | +// createHostedClusterClient creates a Kubernetes client for the hosted cluster |
| 78 | +func (cm *ClientManager) createHostedClusterClient(ctx context.Context, namespace, name string) (*kubernetes.Clientset, error) { |
| 79 | + // Fetch kubeconfig secret |
| 80 | + kubeconfigData, err := cm.getKubeconfigData(ctx, namespace, name) |
| 81 | + if err != nil { |
| 82 | + return nil, fmt.Errorf("failed to get kubeconfig: %w", err) |
| 83 | + } |
| 84 | + |
| 85 | + // Parse kubeconfig |
| 86 | + kubeconfig, err := clientcmd.Load(kubeconfigData) |
| 87 | + if err != nil { |
| 88 | + return nil, fmt.Errorf("failed to parse kubeconfig: %w", err) |
| 89 | + } |
| 90 | + |
| 91 | + // Replace external endpoint with internal service DNS name |
| 92 | + // The HyperShift admin-kubeconfig uses external endpoints (LoadBalancer IP or NodePort) |
| 93 | + // which are not accessible from inside the operator pod's network. |
| 94 | + // We need to use the internal service endpoint for in-cluster access. |
| 95 | + if err := replaceServerWithInternalEndpoint(ctx, cm.mgmtClient, kubeconfig, namespace, name); err != nil { |
| 96 | + return nil, fmt.Errorf("failed to replace server endpoint: %w", err) |
| 97 | + } |
| 98 | + |
| 99 | + // Create REST config from modified kubeconfig |
| 100 | + config, err := clientcmd.NewDefaultClientConfig(*kubeconfig, &clientcmd.ConfigOverrides{}).ClientConfig() |
| 101 | + if err != nil { |
| 102 | + return nil, fmt.Errorf("failed to create rest config from kubeconfig: %w", err) |
| 103 | + } |
| 104 | + |
| 105 | + // Set reasonable timeouts |
| 106 | + config.Timeout = 0 // No timeout for long-lived connections (watches) |
| 107 | + config.QPS = 5 |
| 108 | + config.Burst = 10 |
| 109 | + |
| 110 | + // Create clientset |
| 111 | + clientset, err := kubernetes.NewForConfig(config) |
| 112 | + if err != nil { |
| 113 | + return nil, fmt.Errorf("failed to create clientset: %w", err) |
| 114 | + } |
| 115 | + |
| 116 | + return clientset, nil |
| 117 | +} |
| 118 | + |
| 119 | +// getKubeconfigData retrieves the kubeconfig data from the admin secret |
| 120 | +func (cm *ClientManager) getKubeconfigData(ctx context.Context, namespace, name string) ([]byte, error) { |
| 121 | + // The kubeconfig secret name follows HyperShift convention: <hostedcluster-name>-admin-kubeconfig |
| 122 | + secretName := name + "-admin-kubeconfig" |
| 123 | + |
| 124 | + secret := &corev1.Secret{} |
| 125 | + secretKey := types.NamespacedName{ |
| 126 | + Namespace: namespace, |
| 127 | + Name: secretName, |
| 128 | + } |
| 129 | + |
| 130 | + if err := cm.mgmtClient.Get(ctx, secretKey, secret); err != nil { |
| 131 | + return nil, fmt.Errorf("failed to get kubeconfig secret %s: %w", secretKey, err) |
| 132 | + } |
| 133 | + |
| 134 | + kubeconfigData, ok := secret.Data["kubeconfig"] |
| 135 | + if !ok { |
| 136 | + return nil, fmt.Errorf("kubeconfig key not found in secret %s", secretKey) |
| 137 | + } |
| 138 | + |
| 139 | + if len(kubeconfigData) == 0 { |
| 140 | + return nil, fmt.Errorf("kubeconfig data is empty in secret %s", secretKey) |
| 141 | + } |
| 142 | + |
| 143 | + return kubeconfigData, nil |
| 144 | +} |
| 145 | + |
| 146 | +// replaceServerWithInternalEndpoint modifies the kubeconfig to use internal service DNS name |
| 147 | +// instead of the external LoadBalancer IP or NodePort. This allows the operator pod (running inside the cluster) |
| 148 | +// to reach the hosted cluster API server via the internal Kubernetes service. |
| 149 | +// |
| 150 | +// HyperShift creates admin-kubeconfig with external endpoints: |
| 151 | +// - LoadBalancer: https://10.6.135.42:6443 (example external IP, not accessible from operator pod) |
| 152 | +// - NodePort: https://<node-ip>:31039 (example NodePort, dynamically allocated per cluster) |
| 153 | +// |
| 154 | +// This function replaces it with the internal service DNS name: |
| 155 | +// https://kube-apiserver.<namespace>-<name>.svc.cluster.local:6443 |
| 156 | +// |
| 157 | +// Port 6443 is hardcoded to match HyperShift's implementation. HyperShift itself hardcodes |
| 158 | +// the kube-apiserver port as a constant (KASSVCPort = 6443) in their codebase. |
| 159 | +func replaceServerWithInternalEndpoint(ctx context.Context, mgmtClient client.Client, kubeconfig *clientcmdapi.Config, hostedClusterNamespace, hostedClusterName string) error { |
| 160 | + if kubeconfig == nil { |
| 161 | + return fmt.Errorf("kubeconfig is nil") |
| 162 | + } |
| 163 | + |
| 164 | + // Find the current context |
| 165 | + currentContext := kubeconfig.CurrentContext |
| 166 | + if currentContext == "" { |
| 167 | + return fmt.Errorf("kubeconfig has no current context") |
| 168 | + } |
| 169 | + |
| 170 | + context, ok := kubeconfig.Contexts[currentContext] |
| 171 | + if !ok { |
| 172 | + return fmt.Errorf("context %s not found in kubeconfig", currentContext) |
| 173 | + } |
| 174 | + |
| 175 | + // Find the cluster referenced by the context |
| 176 | + clusterName := context.Cluster |
| 177 | + cluster, ok := kubeconfig.Clusters[clusterName] |
| 178 | + if !ok { |
| 179 | + return fmt.Errorf("cluster %s not found in kubeconfig", clusterName) |
| 180 | + } |
| 181 | + |
| 182 | + // Construct the service namespace following HyperShift convention |
| 183 | + serviceNamespace := fmt.Sprintf("%s-%s", hostedClusterNamespace, hostedClusterName) |
| 184 | + |
| 185 | + // Construct internal service DNS name with hardcoded port 6443 (matching HyperShift's approach) |
| 186 | + internalServer := fmt.Sprintf("https://kube-apiserver.%s.svc.cluster.local:6443", serviceNamespace) |
| 187 | + |
| 188 | + // Replace the server URL |
| 189 | + cluster.Server = internalServer |
| 190 | + |
| 191 | + return nil |
| 192 | +} |
| 193 | + |
| 194 | +// TestConnection verifies the hosted cluster client can connect to the API server |
| 195 | +func TestConnection(ctx context.Context, clientset *kubernetes.Clientset) error { |
| 196 | + _, err := clientset.Discovery().ServerVersion() |
| 197 | + if err != nil { |
| 198 | + return fmt.Errorf("failed to connect to hosted cluster API server: %w", err) |
| 199 | + } |
| 200 | + return nil |
| 201 | +} |
0 commit comments