-
Notifications
You must be signed in to change notification settings - Fork 13
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
add support for adopting external cluster #306
base: main
Are you sure you want to change the base?
Changes from 4 commits
43ae169
3c7e658
8eabbb7
756f7b7
28260e7
ecbb432
d80da22
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -54,11 +54,42 @@ spec: | |
spec: | ||
description: ControlPlaneSpec defines the desired state of ControlPlane | ||
properties: | ||
adoptedTokenExpirationSeconds: | ||
description: expiration time for token of adopted cluster | ||
format: int64 | ||
type: integer | ||
backend: | ||
enum: | ||
- shared | ||
- dedicated | ||
type: string | ||
bootstrapSecretRef: | ||
description: |- | ||
BootstrapSecretRef contains a reference to the kubeconfig used to bootstrap adoption of | ||
an external cluster | ||
properties: | ||
inClusterKey: | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Can you please clarify what is Perhaps I missed, but I did not see a documentation of what the bootstrap secret should look like. This is useful if somebody wants/needs to create it without using kflex. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. You may see the defaults being used for the bootstrap secret in func GenerateBoostrapSecretName(cpName string) string {
return fmt.Sprintf("%s-bootstrap", cpName)
} namespace is There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. To further clarify, Since you have a default, can you make it not required? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
No, There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. (A) Since the golang source re-uses the existing type (B) @pdettori, what do you mean by "You do not have to provide these values in the ControlPlane CR, they are optional"? Which values are optional? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. @MikeSpreitzer - re. (B) - what I stated previously was not correct. The bootstrap secret must be provided in the secret reference. Please check "Creating a control plane of type |
||
description: Required | ||
type: string | ||
key: | ||
description: Required | ||
type: string | ||
name: | ||
description: |- | ||
`name` is the name of the secret. | ||
Required | ||
type: string | ||
namespace: | ||
description: |- | ||
`namespace` is the namespace of the secret. | ||
Required | ||
type: string | ||
required: | ||
- inClusterKey | ||
- key | ||
- name | ||
- namespace | ||
type: object | ||
postCreateHook: | ||
type: string | ||
postCreateHookVars: | ||
|
@@ -71,6 +102,7 @@ spec: | |
- ocm | ||
- vcluster | ||
- host | ||
- external | ||
type: string | ||
type: object | ||
status: | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,224 @@ | ||
/* | ||
Copyright 2024 The KubeStellar Authors. | ||
|
||
Licensed 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 adopt | ||
|
||
import ( | ||
"context" | ||
"fmt" | ||
"os" | ||
"strings" | ||
"sync" | ||
|
||
"path/filepath" | ||
|
||
homedir "github.com/mitchellh/go-homedir" | ||
corev1 "k8s.io/api/core/v1" | ||
apierrors "k8s.io/apimachinery/pkg/api/errors" | ||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" | ||
"k8s.io/client-go/kubernetes" | ||
"k8s.io/client-go/tools/clientcmd" | ||
"k8s.io/client-go/tools/clientcmd/api" | ||
"sigs.k8s.io/controller-runtime/pkg/client" | ||
|
||
tenancyv1alpha1 "github.com/kubestellar/kubeflex/api/v1alpha1" | ||
"github.com/kubestellar/kubeflex/cmd/kflex/common" | ||
cont "github.com/kubestellar/kubeflex/cmd/kflex/ctx" | ||
kfclient "github.com/kubestellar/kubeflex/pkg/client" | ||
"github.com/kubestellar/kubeflex/pkg/util" | ||
) | ||
|
||
type CPAdopt struct { | ||
common.CP | ||
AdoptedKubeconfig string | ||
AdoptedContext string | ||
AdoptedURLOverride string | ||
AdoptedTokenExpirationSeconds int | ||
SkipURLOverride bool | ||
} | ||
|
||
// Adopt a control plane from another cluster | ||
func (c *CPAdopt) Adopt(hook string, hookVars []string, chattyStatus bool) { | ||
done := make(chan bool) | ||
var wg sync.WaitGroup | ||
cx := cont.CPCtx{} | ||
cx.Context(chattyStatus, false, false, false) | ||
|
||
controlPlaneType := tenancyv1alpha1.ControlPlaneTypeExternal | ||
util.PrintStatus(fmt.Sprintf("Adopting control plane %s of type %s ...", c.Name, controlPlaneType), done, &wg, chattyStatus) | ||
MikeSpreitzer marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
adoptedKubeconfig := getAdoptedKubeconfig(c) | ||
MikeSpreitzer marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
clp, err := kfclient.GetClient(c.Kubeconfig) | ||
if err != nil { | ||
fmt.Fprintf(os.Stderr, "Error getting kubeflex client: %v\n", err) | ||
os.Exit(1) | ||
} | ||
cl := *clp | ||
MikeSpreitzer marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
clientsetp, err := kfclient.GetClientSet(c.Kubeconfig) | ||
if err != nil { | ||
fmt.Fprintf(os.Stderr, "Error getting clientset: %v\n", err) | ||
os.Exit(1) | ||
} | ||
|
||
if err := applyAdoptedBootstrapSecret(clientsetp, c.Name, adoptedKubeconfig, c.AdoptedContext, c.AdoptedURLOverride, c.SkipURLOverride); err != nil { | ||
fmt.Fprintf(os.Stderr, "error creating adopted cluster kubeconfig: %v\n", err) | ||
os.Exit(1) | ||
} | ||
|
||
cp := common.GenerateControlPlane(c.Name, string(controlPlaneType), "", hook, hookVars) | ||
|
||
if err := cl.Create(context.TODO(), cp, &client.CreateOptions{}); err != nil { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. FYI, all writes should supply a FieldManager in the XXXOptions. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I prefer to leave this to a separate campaign/PR as there are many other places where there are writes so should probably be done consistently everywhere. |
||
fmt.Fprintf(os.Stderr, "Error creating ControlPlane object: %v\n", err) | ||
os.Exit(1) | ||
} | ||
|
||
done <- true | ||
wg.Wait() | ||
} | ||
|
||
func applyAdoptedBootstrapSecret(clientset *kubernetes.Clientset, cpName, adoptedKubeconfig, contextName, adoptedURLOverride string, skipURLOverride bool) error { | ||
// Load the kubeconfig from file | ||
config, err := clientcmd.LoadFromFile(adoptedKubeconfig) | ||
if err != nil { | ||
return fmt.Errorf("failed to load kubeconfig file %s: %v", adoptedKubeconfig, err) | ||
} | ||
|
||
// Retrieve the specified context | ||
context, exists := config.Contexts[contextName] | ||
if !exists { | ||
return fmt.Errorf("context %s not found in the kubeconfig", contextName) | ||
} | ||
|
||
// Retrieve the associated cluster | ||
cluster, exists := config.Clusters[context.Cluster] | ||
if !exists { | ||
return fmt.Errorf("cluster %s not found for context %s", context.Cluster, contextName) | ||
} | ||
|
||
// Construct a new kubeConfig object | ||
kubeConfig := api.NewConfig() | ||
|
||
kubeConfig.Clusters[context.Cluster] = cluster | ||
|
||
if !skipURLOverride { | ||
// Determine the server endpoint | ||
endpoint := adoptedURLOverride | ||
if endpoint == "" { | ||
endpoint = cluster.Server | ||
if !isValidServerURL(endpoint) { | ||
MikeSpreitzer marked this conversation as resolved.
Show resolved
Hide resolved
|
||
return fmt.Errorf("invalid server endpoint %s. Please provide a valid value with the `url-override` option", endpoint) | ||
} | ||
} | ||
kubeConfig.Clusters[context.Cluster].Server = endpoint | ||
} | ||
|
||
if authInfo, exists := config.AuthInfos[context.AuthInfo]; exists { | ||
kubeConfig.AuthInfos[contextName] = authInfo | ||
} else { | ||
return fmt.Errorf("authInfo %s not found for context %s", context.AuthInfo, contextName) | ||
} | ||
|
||
kubeConfig.Contexts[contextName] = &api.Context{ | ||
Cluster: context.Cluster, | ||
AuthInfo: contextName, | ||
} | ||
MikeSpreitzer marked this conversation as resolved.
Show resolved
Hide resolved
|
||
kubeConfig.CurrentContext = contextName | ||
|
||
newKubeConfig, err := clientcmd.Write(*kubeConfig) | ||
if err != nil { | ||
return fmt.Errorf("failed to serialize the new kubeconfig: %v", err) | ||
} | ||
|
||
createOrUpdateSecret(clientset, cpName, newKubeConfig) | ||
|
||
return nil | ||
} | ||
|
||
func createOrUpdateSecret(clientset *kubernetes.Clientset, cpName string, kubeconfig []byte) error { | ||
|
||
// Define the kubeconfig secret | ||
kubeConfigSecret := &corev1.Secret{ | ||
ObjectMeta: metav1.ObjectMeta{ | ||
Name: util.GenerateBoostrapSecretName(cpName), | ||
Namespace: util.SystemNamespace, | ||
}, | ||
Type: corev1.SecretTypeOpaque, | ||
Data: map[string][]byte{util.KubeconfigSecretKeyInCluster: kubeconfig}, | ||
MikeSpreitzer marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} | ||
|
||
// Try to create the secret | ||
if _, err := clientset.CoreV1().Secrets(util.SystemNamespace).Create(context.TODO(), kubeConfigSecret, metav1.CreateOptions{}); err != nil { | ||
// Check if the error is because the secret already exists | ||
if apierrors.IsAlreadyExists(err) { | ||
// Retrieve the existing secret | ||
existingSecret, getErr := clientset.CoreV1().Secrets(util.SystemNamespace).Get(context.TODO(), util.AdminConfSecret, metav1.GetOptions{}) | ||
if getErr != nil { | ||
return fmt.Errorf("failed to fetch existing secret %s in namespace %s: %v", util.AdminConfSecret, util.SystemNamespace, getErr) | ||
} | ||
|
||
// Update the data of the existing secret | ||
existingSecret.Data = kubeConfigSecret.Data | ||
|
||
// Update the secret with new data | ||
if _, updateErr := clientset.CoreV1().Secrets(util.SystemNamespace).Update(context.TODO(), existingSecret, metav1.UpdateOptions{}); updateErr != nil { | ||
return fmt.Errorf("failed to update existing secret %s in namespace %s: %v", util.AdminConfSecret, util.SystemNamespace, updateErr) | ||
} | ||
} else { | ||
return fmt.Errorf("failed to create secret %s in namespace %s: %v", util.AdminConfSecret, util.SystemNamespace, err) | ||
} | ||
} | ||
|
||
return nil | ||
} | ||
|
||
// check if the current server URL in the adopted cluster kubeconfig is using | ||
// a local address, which would not work in a container | ||
MikeSpreitzer marked this conversation as resolved.
Show resolved
Hide resolved
|
||
func isValidServerURL(serverURL string) bool { | ||
localAddresses := []string{"127.0.0.1", "localhost", "::1"} | ||
MikeSpreitzer marked this conversation as resolved.
Show resolved
Hide resolved
|
||
for _, addr := range localAddresses { | ||
if strings.Contains(serverURL, addr) { | ||
return false | ||
} | ||
} | ||
return true | ||
} | ||
|
||
func getAdoptedKubeconfig(c *CPAdopt) string { | ||
if c.AdoptedKubeconfig != "" { | ||
return c.AdoptedKubeconfig | ||
} | ||
if c.Kubeconfig != "" { | ||
return c.Kubeconfig | ||
} | ||
return getKubeConfigFromEnv(c.Kubeconfig) | ||
} | ||
|
||
func getKubeConfigFromEnv(kubeconfig string) string { | ||
MikeSpreitzer marked this conversation as resolved.
Show resolved
Hide resolved
|
||
if kubeconfig == "" { | ||
kubeconfig = os.Getenv("KUBECONFIG") | ||
if kubeconfig == "" { | ||
home, err := homedir.Dir() | ||
if err != nil { | ||
fmt.Fprintf(os.Stderr, "Error finding home directory: %v\n", err) | ||
os.Exit(1) | ||
} | ||
kubeconfig = filepath.Join(home, ".kube", "config") | ||
} | ||
} | ||
return kubeconfig | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is an "inline union": some unconditional fields plus a discriminator (
Type
) that determines whether some of the other fields should be present or absent. FYI, these are frowned upon in the Kubernetes API design community. They prefer pure unions: a pure union struct has only a discriminator plus fields whose proper presence is determined by the discriminator.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
You are correct, but I am concerned about introducing a non-backward compatible change if we go with the pure union. Just to be clear, is something like the following what you have in mind for the "pure union"?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
What you showed looks like a pure union.