Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions controllers/export_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,10 @@ var (
DeployContentOfSecret = deployContentOfSecret
DeployContent = deployContent
GetClusterSummaryAdmin = getClusterSummaryAdmin
NeedsRemoteAccess = needsRemoteAccess
SkipRemoteAccess = skipRemoteAccess
SkipRemoteAccessToUndeployHelm = skipRemoteAccessToUndeployHelm
GetRestConfig = getRestConfig
GetReferenceClient = getReferenceClient
GetReferencedObject = getReferencedObject
GetValuesFrom = getValuesFrom
Expand Down
19 changes: 13 additions & 6 deletions controllers/handlers_helm.go
Original file line number Diff line number Diff line change
Expand Up @@ -379,16 +379,23 @@ func undeployHelmCharts(ctx context.Context, c client.Client,
return undeployHelmChartsInPullMode(ctx, c, clusterSummary, mgmtResources, logger)
}

// Kubeconfig Secret read: must bypass any Secret-cache scoping, so use the
// direct client rather than c.
remoteRestConfig, err := clustercache.GetManager().GetKubernetesRestConfig(ctx, getManagementClusterClient(),
clusterNamespace, clusterName, adminNamespace, adminName, clusterSummary.Spec.ClusterType, logger)
skipRemote, err := skipRemoteAccessToUndeployHelm(ctx, getManagementClusterClient(), clusterSummary)
if err != nil {
return err
}

var kubeconfig string
if remoteRestConfig != nil {
ctx = withRestConfig(ctx, remoteRestConfig)
if !skipRemote {
// Kubeconfig Secret read: must bypass any Secret-cache scoping, so use the
// direct client rather than c.
remoteRestConfig, restErr := clustercache.GetManager().GetKubernetesRestConfig(ctx, getManagementClusterClient(),
clusterNamespace, clusterName, adminNamespace, adminName, clusterSummary.Spec.ClusterType, logger)
if restErr != nil {
return restErr
}
if remoteRestConfig != nil {
ctx = withRestConfig(ctx, remoteRestConfig)
}
}

mgmtResources, err := collectTemplateResourceRefs(ctx, clusterSummary)
Expand Down
10 changes: 7 additions & 3 deletions controllers/handlers_helm_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,6 @@ import (
"github.com/projectsveltos/addon-controller/lib/clusterops"
"github.com/projectsveltos/addon-controller/pkg/scope"
libsveltosv1beta1 "github.com/projectsveltos/libsveltos/api/v1beta1"
"github.com/projectsveltos/libsveltos/lib/clusterproxy"
"github.com/projectsveltos/libsveltos/lib/k8s_utils"
"github.com/projectsveltos/libsveltos/lib/pullmode"
)
Expand Down Expand Up @@ -1927,9 +1926,14 @@ var _ = Describe("HandlersHelm", func() {

Expect(waitForObject(context.TODO(), testEnv.Client, clusterReport)).To(Succeed())

kubeconfig, closer, err := clusterproxy.CreateKubeconfig(textlogger.NewLogger(textlogger.NewConfig()), testEnv.Kubeconfig)
// HandleCharts takes the path of a kubeconfig file
kubeconfigFile, err := os.CreateTemp("", "kubeconfig")
Expect(err).To(BeNil())
defer closer()
kubeconfig := kubeconfigFile.Name()
defer os.Remove(kubeconfig)
_, err = kubeconfigFile.Write(testEnv.Kubeconfig)
Expect(err).To(BeNil())
Expect(kubeconfigFile.Close()).To(Succeed())

// ClusterSummary in DryRun mode. Nothing registered with chartManager with respect to the two referenced
// helm chart. So expect action for Install will be install, and the action for Uninstall will be no action as
Expand Down
25 changes: 21 additions & 4 deletions controllers/handlers_kustomize.go
Original file line number Diff line number Diff line change
Expand Up @@ -96,12 +96,12 @@ func deployKustomizeRefs(ctx context.Context, c client.Client,
o deployer.Options, logger logr.Logger) error {

// Get ClusterSummary that requested this
clusterSummary, _, err := getClusterSummaryAndClusterClient(ctx, clusterNamespace, applicant, c, logger)
clusterSummary, err := getClusterSummaryToDeploy(ctx, clusterNamespace, applicant, c, logger)
if err != nil {
return err
}

remoteRestConfig, logger, err := getRestConfig(ctx, clusterSummary, logger)
remoteRestConfig, logger, err := getRestConfig(ctx, clusterSummary, libsveltosv1beta1.FeatureKustomize, logger)
if err != nil {
return err
}
Expand Down Expand Up @@ -222,7 +222,7 @@ func processKustomizeDeployment(ctx context.Context, remoteRestConfig *rest.Conf
return err
}

err = updateClusterReportWithResourceReports(ctx, c, clusterSummary, remoteRestConfig == nil,
err = updateClusterReportWithResourceReports(ctx, c, clusterSummary, isPullMode,
remoteResourceReports, libsveltosv1beta1.FeatureKustomize)
if err != nil {
return err
Expand Down Expand Up @@ -1156,6 +1156,23 @@ func deployKustomizeResources(ctx context.Context, c client.Client, remoteRestCo
return localReports, nil, err
}

// No restConfig for the managed cluster: either the SveltosCluster is in pull mode or the ClusterSummary
// was created by a tenant and nothing needs to be deployed in the managed cluster (see skipRemoteAccess)
if remoteRestConfig == nil {
isPullMode, pullModeErr := clusterproxy.IsClusterInPullMode(ctx, c, dCtx.clusterSummary.Spec.ClusterNamespace,
dCtx.clusterSummary.Spec.ClusterName, dCtx.clusterSummary.Spec.ClusterType, logger)
if pullModeErr != nil {
return nil, nil, pullModeErr
}
if !isPullMode {
if len(objectsToDeployRemotely) > 0 {
return localReports, nil, fmt.Errorf("no access to the managed cluster, cannot deploy %d resources in it",
len(objectsToDeployRemotely))
}
return localReports, nil, nil
}
}

// Only for SveltosCluster in pull mode and when the content must be deployed in the managed cluster
if remoteRestConfig == nil {
bundleResources := make(map[string][]unstructured.Unstructured)
Expand Down Expand Up @@ -1410,7 +1427,7 @@ func extractTarGz(src, dest string) error {
func instantiateResourceWithSubstituteValues(templateName string, resource []byte,
substituteValues map[string]string, useTxtFuncMap bool, logger logr.Logger) ([]byte, error) {

tmpl, err := template.New(templateName).Option("missingkey=error").Funcs(funcmap.SveltosFuncMap(useTxtFuncMap)).
tmpl, err := template.New(templateName).Option("missingkey=error").Funcs(funcmap.SveltosSandboxedFuncMap(useTxtFuncMap)).
Parse(string(resource))
if err != nil {
return nil, err
Expand Down
13 changes: 11 additions & 2 deletions controllers/handlers_resources.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,17 +52,26 @@ func deployResources(ctx context.Context, c client.Client,
o deployer.Options, logger logr.Logger) error {

// Get ClusterSummary that requested this
clusterSummary, remoteClient, err := getClusterSummaryAndClusterClient(ctx, clusterNamespace, applicant, c, logger)
clusterSummary, err := getClusterSummaryToDeploy(ctx, clusterNamespace, applicant, c, logger)
if err != nil {
return err
}

// remoteClient is nil if nothing needs to be deployed in the managed cluster (see skipRemoteAccess)
var remoteClient client.Client
if !skipRemoteAccess(clusterSummary, libsveltosv1beta1.FeatureResources) {
remoteClient, err = getClusterClient(ctx, clusterSummary, logger)
if err != nil {
return err
}
}

isPullMode, err := clusterproxy.IsClusterInPullMode(ctx, c, clusterNamespace, clusterName, clusterType, logger)
if err != nil {
return err
}

remoteRestConfig, logger, err := getRestConfig(ctx, clusterSummary, logger)
remoteRestConfig, logger, err := getRestConfig(ctx, clusterSummary, libsveltosv1beta1.FeatureResources, logger)
if err != nil {
return err
}
Expand Down
138 changes: 127 additions & 11 deletions controllers/handlers_utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ import (
"sigs.k8s.io/yaml"

configv1beta1 "github.com/projectsveltos/addon-controller/api/v1beta1"
"github.com/projectsveltos/addon-controller/controllers/chartmanager"
"github.com/projectsveltos/addon-controller/lib/clusterops"
libsveltosv1beta1 "github.com/projectsveltos/libsveltos/api/v1beta1"
"github.com/projectsveltos/libsveltos/lib/clustercache"
Expand Down Expand Up @@ -880,42 +881,143 @@ func validateProfileServiceAccountNamespace(clusterSummary *configv1beta1.Cluste
func getClusterSummaryAndClusterClient(ctx context.Context, clusterNamespace, clusterSummaryName string,
c client.Client, logger logr.Logger) (*configv1beta1.ClusterSummary, client.Client, error) {

clusterSummary, err := getClusterSummaryToDeploy(ctx, clusterNamespace, clusterSummaryName, c, logger)
if err != nil {
return nil, nil, err
}

clusterClient, err := getClusterClient(ctx, clusterSummary, logger)
if err != nil {
return nil, nil, err
}

return clusterSummary, clusterClient, nil
}

// getClusterSummaryToDeploy gets ClusterSummary.
// Returns an err if ClusterSummary or associated CAPI Cluster are marked for deletion, or if an
// error occurs while getting resources.
func getClusterSummaryToDeploy(ctx context.Context, clusterNamespace, clusterSummaryName string,
c client.Client, logger logr.Logger) (*configv1beta1.ClusterSummary, error) {

// Get ClusterSummary that requested this
clusterSummary := &configv1beta1.ClusterSummary{}
if err := c.Get(ctx,
types.NamespacedName{Namespace: clusterNamespace, Name: clusterSummaryName}, clusterSummary); err != nil {
return nil, nil, err
return nil, err
}

if !clusterSummary.DeletionTimestamp.IsZero() {
logger.V(logs.LogInfo).Info("ClusterSummary is marked for deletion. Nothing to do.")
// if clusterSummary is marked for deletion, there is nothing to deploy
return nil, nil, fmt.Errorf("clustersummary is marked for deletion")
return nil, fmt.Errorf("clustersummary is marked for deletion")
}

// Get Cluster
cluster, err := clusterproxy.GetCluster(ctx, c, clusterSummary.Spec.ClusterNamespace,
clusterSummary.Spec.ClusterName, clusterSummary.Spec.ClusterType)
if err != nil {
return nil, nil, err
return nil, err
}

if !cluster.GetDeletionTimestamp().IsZero() {
logger.V(logs.LogInfo).Info("cluster is marked for deletion. Nothing to do.")
// if cluster is marked for deletion, there is nothing to deploy
return nil, nil, fmt.Errorf("cluster is marked for deletion")
return nil, fmt.Errorf("cluster is marked for deletion")
}

return clusterSummary, nil
}

// getClusterClient returns the client to access the CAPI/Sveltos Cluster, with the permissions
// of the tenant admin if the ClusterSummary was created by one.
func getClusterClient(ctx context.Context, clusterSummary *configv1beta1.ClusterSummary,
logger logr.Logger) (client.Client, error) {

adminNamespace, adminName := getClusterSummaryAdmin(clusterSummary)
// Kubeconfig Secret read: must bypass any Secret-cache scoping, so use the
// direct client rather than the c passed into this function.
clusterClient, err := clustercache.GetManager().GetKubernetesClient(ctx, getManagementClusterClient(), clusterSummary.Spec.ClusterNamespace,
// direct client rather than the one used to get the ClusterSummary.
return clustercache.GetManager().GetKubernetesClient(ctx, getManagementClusterClient(), clusterSummary.Spec.ClusterNamespace,
clusterSummary.Spec.ClusterName, adminNamespace, adminName, clusterSummary.Spec.ClusterType, logger)
}

// needsRemoteAccess returns true if deploying featureID for clusterSummary requires access to the
// managed cluster: something is deployed there, or checks run against it.
// PolicyRefs and KustomizationRefs can be deployed in the management cluster (DeploymentTypeLocal).
// Helm charts are always deployed in the managed cluster.
func needsRemoteAccess(clusterSummary *configv1beta1.ClusterSummary, featureID libsveltosv1beta1.FeatureID) bool {
spec := &clusterSummary.Spec.ClusterProfileSpec

// Both kind of checks are run against the managed cluster
if len(spec.PreDeployChecks) > 0 || len(spec.ValidateHealths) > 0 {
return true
}

switch featureID {
case libsveltosv1beta1.FeatureResources:
for i := range spec.PolicyRefs {
if spec.PolicyRefs[i].DeploymentType != configv1beta1.DeploymentTypeLocal {
return true
}
}
return false
case libsveltosv1beta1.FeatureKustomize:
for i := range spec.KustomizationRefs {
if spec.KustomizationRefs[i].DeploymentType != configv1beta1.DeploymentTypeLocal {
return true
}
}
return false
case libsveltosv1beta1.FeatureHelm:
return true
default:
return true
}
}

// skipRemoteAccessToUndeployHelm returns true if the ClusterSummary was created by a tenant (ServiceAccount
// labels are set) and there is no helm release to undeploy from the managed cluster. A tenant that never
// deployed a helm chart must not need access to the managed cluster to have its ClusterSummary removed.
// There is something to undeploy if:
// - helm charts are still referenced (they are uninstalled); or
// - the ClusterSummary is the manager of a release registered with the chart manager. This is how
// releases that are not referenced anymore (chart removed from the spec after being deployed) are found
// and uninstalled (see getStaleReleases); or
// - the status still lists helm releases (the chart manager registrations are rebuilt from it on restart).
func skipRemoteAccessToUndeployHelm(ctx context.Context, c client.Client,
clusterSummary *configv1beta1.ClusterSummary) (bool, error) {

_, adminName := getClusterSummaryAdmin(clusterSummary)
if adminName == "" {
return false, nil
}

if len(clusterSummary.Spec.ClusterProfileSpec.HelmCharts) > 0 ||
len(clusterSummary.Status.HelmReleaseSummaries) > 0 {

return false, nil
}

chartManager, err := chartmanager.GetChartManagerInstance(ctx, c)
if err != nil {
return nil, nil, err
return false, err
}

return clusterSummary, clusterClient, nil
return len(chartManager.GetManagedHelmReleases(clusterSummary)) == 0, nil
}

// skipRemoteAccess returns true if the ClusterSummary was created by a tenant (ServiceAccount labels
// are set) and deploying featureID does not require access to the managed cluster.
// A tenant is granted access to a managed cluster only by a RoleRequest: a tenant who deploys only in the
// management cluster must not need it. Anything else (including a ClusterSummary created by a platform
// admin) is unchanged and fails if the managed cluster cannot be accessed.
func skipRemoteAccess(clusterSummary *configv1beta1.ClusterSummary, featureID libsveltosv1beta1.FeatureID) bool {
_, adminName := getClusterSummaryAdmin(clusterSummary)
if adminName == "" {
return false
}

return !needsRemoteAccess(clusterSummary, featureID)
}

func appendPathAnnotations(object client.Object, path string) {
Expand Down Expand Up @@ -1238,7 +1340,8 @@ func setupRemoteConfigAndClient(isMgmtCluster bool, remoteConfig *rest.Config, r
UserName: fmt.Sprintf("system:serviceaccount:%s:%s", adminNamespace, adminName),
}
}
localClient, err := client.New(localConfig, client.Options{Scheme: remoteClient.Scheme()})
// remoteClient is nil when nothing is deployed in the managed cluster (see skipRemoteAccess)
localClient, err := client.New(localConfig, client.Options{Scheme: getManagementClusterClient().Scheme()})
if err != nil {
return nil, nil, err
}
Expand Down Expand Up @@ -1581,9 +1684,12 @@ func tranformGroupVersionKindToString(gvks []schema.GroupVersionKind) []string {
return result
}

// getRestConfig returns restConfig to access remote cluster
// getRestConfig returns restConfig to access remote cluster.
// A nil restConfig is returned for a SveltosCluster in pull mode and when the ClusterSummary was created
// by a tenant and featureID does not need to access the remote cluster (see skipRemoteAccess). In the latter
// case nothing must be deployed in the managed cluster.
func getRestConfig(ctx context.Context, clusterSummary *configv1beta1.ClusterSummary,
logger logr.Logger) (*rest.Config, logr.Logger, error) {
featureID libsveltosv1beta1.FeatureID, logger logr.Logger) (*rest.Config, logr.Logger, error) {

clusterNamespace := clusterSummary.Spec.ClusterNamespace
clusterName := clusterSummary.Spec.ClusterName
Expand All @@ -1592,6 +1698,11 @@ func getRestConfig(ctx context.Context, clusterSummary *configv1beta1.ClusterSum
logger = logger.WithValues("cluster", fmt.Sprintf("%s/%s", clusterNamespace, clusterName)).
WithValues("clusterSummary", clusterSummary.Name).WithValues("admin", fmt.Sprintf("%s/%s", adminNamespace, adminName))

if skipRemoteAccess(clusterSummary, featureID) {
logger.V(logs.LogDebug).Info("nothing to deploy in the remote cluster. Skip remote restConfig")
return nil, logger, nil
}

logger.V(logs.LogDebug).Info("get remote restConfig")
// Kubeconfig Secret read: must bypass any Secret-cache scoping, so use the
// direct client rather than c.
Expand Down Expand Up @@ -2188,6 +2299,11 @@ func getValuesFrom(ctx context.Context, c client.Client, clusterSummary *configv
func validatePreDeployChecks(ctx context.Context, c client.Client, clusterSummary *configv1beta1.ClusterSummary,
featureID libsveltosv1beta1.FeatureID, logger logr.Logger) error {

// No check is run against the managed cluster (PreDeployChecks is empty, see needsRemoteAccess)
if skipRemoteAccess(clusterSummary, featureID) {
return nil
}

adminNamespace, adminName := getClusterSummaryAdmin(clusterSummary)
clusterNamespace := clusterSummary.Spec.ClusterNamespace
clusterName := clusterSummary.Spec.ClusterName
Expand Down
2 changes: 1 addition & 1 deletion controllers/template_instantiation.go
Original file line number Diff line number Diff line change
Expand Up @@ -201,7 +201,7 @@ func instantiateTemplateValues(ctx context.Context, config *rest.Config, c clien
}
}

funcMap := funcmap.SveltosFuncMap(funcmap.HasTextTemplateAnnotation(clusterSummary.Annotations))
funcMap := funcmap.SveltosSandboxedFuncMap(funcmap.HasTextTemplateAnnotation(clusterSummary.Annotations))
funcMap["getResource"] = func(id string) map[string]interface{} {
u, ok := objects.MgmtResources[id]
if !ok {
Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ require (
github.com/onsi/gomega v1.44.0
github.com/opencontainers/image-spec v1.1.1
github.com/pkg/errors v0.9.1
github.com/projectsveltos/libsveltos v1.18.0
github.com/projectsveltos/libsveltos v1.18.1-0.20261202143947-d5020b2bd612
github.com/prometheus/client_golang v1.25.0
github.com/sigstore/cosign/v3 v3.1.6
github.com/sigstore/sigstore v1.11.4
Expand Down
4 changes: 2 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -643,8 +643,8 @@ github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRI
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/poy/onpar v1.1.2 h1:QaNrNiZx0+Nar5dLgTVp5mXkyoVFIbepjyEoGSnhbAY=
github.com/poy/onpar v1.1.2/go.mod h1:6X8FLNoxyr9kkmnlqpK6LSoiOtrO6MICtWwEuWkLjzg=
github.com/projectsveltos/libsveltos v1.18.0 h1:Cq6ON8hIZT/xG/TC2jd0Jn3Hn3RWGSMAyQyjjGe2Sh4=
github.com/projectsveltos/libsveltos v1.18.0/go.mod h1:m4ts0OeHjqhLp/zu/ryZdprj/bPuKqJHqsS32tzEGaI=
github.com/projectsveltos/libsveltos v1.18.1-0.20261202143947-d5020b2bd612 h1:CgY/N51ojIZVjT1B3u6mhJpc6OAY7GRsILlfSlExnGg=
github.com/projectsveltos/libsveltos v1.18.1-0.20261202143947-d5020b2bd612/go.mod h1:m4ts0OeHjqhLp/zu/ryZdprj/bPuKqJHqsS32tzEGaI=
github.com/projectsveltos/lua-utils/glua-json v0.0.0-20251212200258-2b3cdcb7c0f5 h1:khnc+994UszxZYu69J+R5FKiLA/Nk1JQj0EYAkwTWz0=
github.com/projectsveltos/lua-utils/glua-json v0.0.0-20251212200258-2b3cdcb7c0f5/go.mod h1:yVL8KQFa9tmcxgwl9nwIMtKgtmIVC1zaFRSCfOwYvPY=
github.com/projectsveltos/lua-utils/glua-runes v0.0.0-20251212200258-2b3cdcb7c0f5 h1:YbsebwRwTRhV8QacvEAdFqxcxHdeu7JTVtsBovbkgos=
Expand Down