|
| 1 | +/* |
| 2 | +Copyright AppsCode Inc. and Contributors |
| 3 | +
|
| 4 | +Licensed under the AppsCode Community License 1.0.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 | + https://github.com/appscode/licenses/raw/1.0.0/AppsCode-Community-1.0.0.md |
| 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 utils |
| 18 | + |
| 19 | +import ( |
| 20 | + "context" |
| 21 | + "fmt" |
| 22 | + "log" |
| 23 | + "net" |
| 24 | + "net/url" |
| 25 | + "strings" |
| 26 | + |
| 27 | + corev1 "k8s.io/api/core/v1" |
| 28 | + "k8s.io/apimachinery/pkg/runtime" |
| 29 | + "k8s.io/client-go/rest" |
| 30 | + "k8s.io/client-go/tools/clientcmd" |
| 31 | + clientcmdapi "k8s.io/client-go/tools/clientcmd/api" |
| 32 | + "k8s.io/klog/v2" |
| 33 | + kmapi "kmodules.xyz/client-go/api/v1" |
| 34 | + "sigs.k8s.io/controller-runtime/pkg/client" |
| 35 | +) |
| 36 | + |
| 37 | +const ( |
| 38 | + firstUser = "ace.user.1" |
| 39 | + firstOrg = "2" |
| 40 | + defaultCluster = "generated-cluster" |
| 41 | + defaultContext = "generated-context" |
| 42 | + defaultUser = "default" |
| 43 | + DefaultPath = "/tmp/kubeconfig" |
| 44 | +) |
| 45 | + |
| 46 | +type KubeConfigGetter struct { |
| 47 | + scm *runtime.Scheme |
| 48 | + config *rest.Config |
| 49 | + kc client.Client |
| 50 | + kubeCfg *clientcmdapi.Config |
| 51 | + secret *corev1.Secret |
| 52 | +} |
| 53 | + |
| 54 | +func NewKubeconfigGetter(scm *runtime.Scheme, config *rest.Config) *KubeConfigGetter { |
| 55 | + kc, err := client.New(config, client.Options{Scheme: scm}) |
| 56 | + if err != nil { |
| 57 | + log.Fatalf("failed to create client: %v", err) |
| 58 | + } |
| 59 | + |
| 60 | + secret, err := getAuthSecret(kc) |
| 61 | + if err != nil { |
| 62 | + klog.Errorf("failed to get auth secret: %v", err) |
| 63 | + return nil |
| 64 | + } |
| 65 | + |
| 66 | + return &KubeConfigGetter{ |
| 67 | + scm: scm, |
| 68 | + config: config, |
| 69 | + kc: kc, |
| 70 | + kubeCfg: RESTConfigToKubeconfig(config), |
| 71 | + secret: &secret, |
| 72 | + } |
| 73 | +} |
| 74 | + |
| 75 | +func RESTConfigToKubeconfig(cfg *rest.Config) *clientcmdapi.Config { |
| 76 | + kubeCfg := clientcmdapi.NewConfig() |
| 77 | + |
| 78 | + kubeCfg.Clusters[defaultCluster] = &clientcmdapi.Cluster{ |
| 79 | + Server: cfg.Host, |
| 80 | + CertificateAuthorityData: cfg.CAData, |
| 81 | + InsecureSkipTLSVerify: cfg.Insecure, |
| 82 | + } |
| 83 | + |
| 84 | + kubeCfg.AuthInfos[defaultUser] = &clientcmdapi.AuthInfo{ |
| 85 | + Token: cfg.BearerToken, |
| 86 | + ClientCertificateData: cfg.CertData, |
| 87 | + ClientKeyData: cfg.KeyData, |
| 88 | + Username: cfg.Username, |
| 89 | + Password: cfg.Password, |
| 90 | + } |
| 91 | + |
| 92 | + kubeCfg.Contexts[defaultContext] = &clientcmdapi.Context{ |
| 93 | + Cluster: defaultCluster, |
| 94 | + AuthInfo: defaultUser, |
| 95 | + } |
| 96 | + |
| 97 | + kubeCfg.CurrentContext = defaultContext |
| 98 | + |
| 99 | + return kubeCfg |
| 100 | +} |
| 101 | + |
| 102 | +func getAuthSecret(kc client.Client) (corev1.Secret, error) { |
| 103 | + var secretList corev1.SecretList |
| 104 | + err := kc.List(context.TODO(), &secretList, &client.ListOptions{Namespace: "open-cluster-management-cluster-auth"}) |
| 105 | + if err != nil { |
| 106 | + return corev1.Secret{}, err |
| 107 | + } |
| 108 | + var secret corev1.Secret |
| 109 | + for _, s := range secretList.Items { |
| 110 | + // kubectl get secrets -n open-cluster-management-cluster-auth ace.user.1-token-j8dhhc |
| 111 | + // annotations: |
| 112 | + // kubernetes.io/service-account.name: ace.user.1 |
| 113 | + if strings.HasPrefix(s.Name, firstUser) { |
| 114 | + val, exists := s.Annotations[corev1.ServiceAccountNameKey] |
| 115 | + if exists && val == firstUser { |
| 116 | + secret = s |
| 117 | + } |
| 118 | + } |
| 119 | + } |
| 120 | + |
| 121 | + if secret.Name == "" { |
| 122 | + return corev1.Secret{}, fmt.Errorf("secret not found") |
| 123 | + } |
| 124 | + return secret, nil |
| 125 | +} |
| 126 | + |
| 127 | +func (g *KubeConfigGetter) GetSpokeClient(spokeName string) (client.Client, error) { |
| 128 | + spokeKubeCfg := g.getSpokeKubeConfig(spokeName) |
| 129 | + return g.convertToClient(spokeKubeCfg) |
| 130 | +} |
| 131 | + |
| 132 | +func (g *KubeConfigGetter) getSpokeKubeConfig(spokeName string) *clientcmdapi.Config { |
| 133 | + kubeCfg := g.kubeCfg.DeepCopy() |
| 134 | + // clusters: |
| 135 | + // - cluster: |
| 136 | + // certificate-authority-data: <ca-from-above-secret> |
| 137 | + // server: https://<hub-ip>:6443/apis/gateway.open-cluster-management.io/v1alpha1/clustergateways/<spoke-name>/proxy |
| 138 | + // users: |
| 139 | + // - name: default |
| 140 | + // user: |
| 141 | + // as: ace.user.1 |
| 142 | + // as-user-extra: |
| 143 | + // ace.appscode.com/org-id: |
| 144 | + // - "2" |
| 145 | + // token: <token-from-above-secret> |
| 146 | + kubeCfg.Clusters[defaultCluster].CertificateAuthorityData = g.secret.Data["ca.crt"] |
| 147 | + kubeCfg.Clusters[defaultCluster].Server = calculateServerURL(kubeCfg.Clusters[defaultCluster].Server, spokeName) |
| 148 | + kubeCfg.AuthInfos[defaultUser] = calculateUser(string(g.secret.Data["token"])) |
| 149 | + return kubeCfg |
| 150 | +} |
| 151 | + |
| 152 | +func calculateServerURL(cur string, spokeName string) string { |
| 153 | + getHost := func(server string) (string, error) { |
| 154 | + u, err := url.Parse(server) |
| 155 | + if err != nil { |
| 156 | + return "", err |
| 157 | + } |
| 158 | + |
| 159 | + host := u.Hostname() |
| 160 | + |
| 161 | + // If it's an IP, return as-is |
| 162 | + if net.ParseIP(host) != nil { |
| 163 | + return host, nil |
| 164 | + } |
| 165 | + |
| 166 | + // Otherwise it's DNS |
| 167 | + return host, nil |
| 168 | + } |
| 169 | + host, err := getHost(cur) |
| 170 | + if err != nil { |
| 171 | + _ = fmt.Errorf("err getting host: %v", err) |
| 172 | + } |
| 173 | + ret := fmt.Sprintf("https://%s:6443/apis/gateway.open-cluster-management.io/v1alpha1/clustergateways/%s/proxy", host, spokeName) |
| 174 | + fmt.Printf("Using host: %s\n", ret) |
| 175 | + return ret |
| 176 | +} |
| 177 | + |
| 178 | +func calculateUser(token string) *clientcmdapi.AuthInfo { |
| 179 | + user := clientcmdapi.NewAuthInfo() |
| 180 | + user.Token = token |
| 181 | + user.Impersonate = firstUser |
| 182 | + user.ImpersonateUserExtra = map[string][]string{ |
| 183 | + kmapi.AceOrgIDKey: {firstOrg}, |
| 184 | + } |
| 185 | + return user |
| 186 | +} |
| 187 | + |
| 188 | +func (g *KubeConfigGetter) convertToClient(kubeCfg *clientcmdapi.Config) (client.Client, error) { |
| 189 | + err := writeKubeconfig(DefaultPath, kubeCfg) |
| 190 | + if err != nil { |
| 191 | + return nil, err |
| 192 | + } |
| 193 | + |
| 194 | + config, err := clientcmd.BuildConfigFromFlags("", DefaultPath) |
| 195 | + if err != nil { |
| 196 | + klog.Errorf("err building config: %v", err) |
| 197 | + } |
| 198 | + |
| 199 | + kc, err := client.New(config, client.Options{Scheme: g.scm}) |
| 200 | + if err != nil { |
| 201 | + klog.Errorf("err creating client: %v", err) |
| 202 | + } |
| 203 | + |
| 204 | + return kc, nil |
| 205 | +} |
| 206 | + |
| 207 | +func writeKubeconfig(path string, cfg *clientcmdapi.Config) error { |
| 208 | + return clientcmd.WriteToFile(*cfg, path) |
| 209 | +} |
0 commit comments