Skip to content
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 filter for apps for which ownership can be overriden #996

Merged
merged 2 commits into from
Aug 5, 2024
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
12 changes: 12 additions & 0 deletions pkg/kapp/cmd/app/deploy.go
Original file line number Diff line number Diff line change
Expand Up @@ -382,15 +382,27 @@ func (o *DeployOptions) existingResources(newResources []ctlres.Resource,
return ""
}

labelValAppMapResolver := func() map[string]string {
items, _ := apps.List(nil)
appLabelMap := map[string]string{}
for _, item := range items {
meta, _ := item.Meta()
appLabelMap[meta.LabelValue] = item.Name()
}
return appLabelMap
}

matchingOpts := ctlres.AllAndMatchingOpts{
ExistingNonLabeledResourcesCheck: o.DeployFlags.ExistingNonLabeledResourcesCheck,
ExistingNonLabeledResourcesCheckConcurrency: o.DeployFlags.ExistingNonLabeledResourcesCheckConcurrency,
SkipResourceOwnershipCheck: o.DeployFlags.OverrideOwnershipOfExistingResources,
SkipOwnershipCheckAllowedApps: o.DeployFlags.OwnershipOverrideAllowedApps,
IsNewApp: isNewApp,

// Prevent accidently overriding kapp state records
DisallowedResourcesByLabelKeys: []string{ctlapp.KappIsAppLabelKey},
LabelErrorResolutionFunc: labelErrorResolutionFunc,
LabelValAppMapResolverFunc: labelValAppMapResolver,

//Scope resource searching to UsedGKs
IdentifiedResourcesListOpts: ctlres.IdentifiedResourcesListOpts{
Expand Down
1 change: 1 addition & 0 deletions pkg/kapp/cmd/app/deploy_flag_help_sections.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ var (
ExactMatch: []string{
"dangerous-allow-empty-list-of-resources",
"dangerous-override-ownership-of-existing-resources",
"ownership-override-allowed-apps",
},
}
WaitFlagGroup = cobrautil.FlagHelpSection{
Expand Down
3 changes: 3 additions & 0 deletions pkg/kapp/cmd/app/deploy_flags.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ type DeployFlags struct {
ExistingNonLabeledResourcesCheck bool
ExistingNonLabeledResourcesCheckConcurrency int
OverrideOwnershipOfExistingResources bool
OwnershipOverrideAllowedApps []string

AppChangesMaxToKeep int

Expand Down Expand Up @@ -48,6 +49,8 @@ func (s *DeployFlags) Set(cmd *cobra.Command) {
100, "Concurrency to check for existing non-labeled resources")
cmd.Flags().BoolVar(&s.OverrideOwnershipOfExistingResources, "dangerous-override-ownership-of-existing-resources",
false, "Steal existing resources from another app")
cmd.Flags().StringSliceVar(&s.OwnershipOverrideAllowedApps, "ownership-override-allowed-apps", nil,
"Specify existing apps in the same namespace that existing resources can be stolen from if --dangerous-override-ownership-of-existing-resources is set")

cmd.Flags().BoolVar(&s.DefaultLabelScopingRules, "default-label-scoping-rules",
true, "Use default label scoping rules")
Expand Down
30 changes: 28 additions & 2 deletions pkg/kapp/resources/labeled_resources.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ package resources

import (
"fmt"
"slices"
"strings"
"sync"

Expand Down Expand Up @@ -93,10 +94,12 @@ type AllAndMatchingOpts struct {
ExistingNonLabeledResourcesCheck bool
ExistingNonLabeledResourcesCheckConcurrency int
SkipResourceOwnershipCheck bool
SkipOwnershipCheckAllowedApps []string
IsNewApp bool

DisallowedResourcesByLabelKeys []string
LabelErrorResolutionFunc func(string, string) string
LabelValAppMapResolverFunc func() map[string]string

IdentifiedResourcesListOpts IdentifiedResourcesListOpts
}
Expand Down Expand Up @@ -131,7 +134,8 @@ func (a *LabeledResources) AllAndMatching(newResources []Resource, opts AllAndMa
}
}

if !opts.SkipResourceOwnershipCheck && len(nonLabeledResources) > 0 {
if len(nonLabeledResources) > 0 && (!opts.SkipResourceOwnershipCheck ||
(opts.SkipResourceOwnershipCheck && len(opts.SkipOwnershipCheckAllowedApps) > 0)) {
resourcesForCheck := a.resourcesForOwnershipCheck(newResources, nonLabeledResources)
if len(resourcesForCheck) > 0 {
err := a.checkResourceOwnership(resourcesForCheck, opts)
Expand Down Expand Up @@ -180,10 +184,19 @@ func (a *LabeledResources) checkResourceOwnership(resources []Resource, opts All
}

var errs []error
labelValAppMap := map[string]string{}
if len(opts.SkipOwnershipCheckAllowedApps) > 0 && opts.SkipResourceOwnershipCheck {
labelValAppMap = opts.LabelValAppMapResolverFunc()
}

for _, res := range resources {
if val, found := res.Labels()[expectedLabelKey]; found {
if val != expectedLabelVal {
ownershipOverrideAllowed := false
if opts.SkipResourceOwnershipCheck {
ownershipOverrideAllowed = a.ownershipOverrideAllowed(labelValAppMap, res,
expectedLabelKey, opts.SkipOwnershipCheckAllowedApps)
}
if val != expectedLabelVal && !ownershipOverrideAllowed {
ownerMsg := fmt.Sprintf("different label '%s=%s'", expectedLabelKey, val)
if opts.LabelErrorResolutionFunc != nil {
ownerMsgSuggested := opts.LabelErrorResolutionFunc(expectedLabelKey, val)
Expand All @@ -208,6 +221,19 @@ func (a *LabeledResources) checkResourceOwnership(resources []Resource, opts All
return nil
}

func (a *LabeledResources) ownershipOverrideAllowed(labelValAppMap map[string]string, res Resource,
expectedLabelKey string, overrideAllowedApps []string) bool {
labelVal, found := res.Labels()[expectedLabelKey]
if !found {
return true
}
appName, found := labelValAppMap[labelVal]
if !found {
return false
}
return slices.Contains(overrideAllowedApps, appName)
}

func (a *LabeledResources) checkDisallowedLabels(resources []Resource, disallowedLblKeys []string) error {
var errs []error

Expand Down
72 changes: 72 additions & 0 deletions test/e2e/selective_ownership_override_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
// Copyright 2024 The Carvel Authors.
// SPDX-License-Identifier: Apache-2.0

package e2e

import (
"fmt"
"strings"
"testing"

"github.com/stretchr/testify/require"
)

func TestSelectiveOwnershipOverride(t *testing.T) {
env := BuildEnv(t)
logger := Logger{}
kapp := Kapp{t, env.Namespace, env.KappBinaryPath, logger}

const existingAppName1 = "existing-app-1"
const existingAppName2 = "existing-app-2"
const newAppName = "new-app"

resourceYAML := `
---
apiVersion: v1
kind: ConfigMap
metadata:
name: cm-%s
data:
foo: bar
`

cleanUp := func() {
kapp.Run([]string{"delete", "-a", existingAppName1})
kapp.Run([]string{"delete", "-a", existingAppName2})
kapp.Run([]string{"delete", "-a", newAppName})
}
cleanUp()
defer cleanUp()

logger.Section("deploy existing apps", func() {
kapp.RunWithOpts([]string{"deploy", "-a", existingAppName1, "-f", "-"}, RunOpts{StdinReader: strings.NewReader(fmt.Sprintf(resourceYAML, "1"))})
kapp.RunWithOpts([]string{"deploy", "-a", existingAppName2, "-f", "-"}, RunOpts{StdinReader: strings.NewReader(fmt.Sprintf(resourceYAML, "2"))})
})

logger.Section("deploy new app with selective overrides", func() {
resourcesString := fmt.Sprintf("%s%s", fmt.Sprintf(resourceYAML, "1"), fmt.Sprintf(resourceYAML, "2"))
// Overrides disallowed
_, err := kapp.RunWithOpts([]string{"deploy", "-a", newAppName, "-f", "-"}, RunOpts{StdinReader: strings.NewReader(resourcesString), AllowError: true})
require.Error(t, err)
require.Contains(t, err.Error(), existingAppName1)
require.Contains(t, err.Error(), existingAppName2)

// Test with override scoped while override is disallowed
_, err = kapp.RunWithOpts([]string{"deploy", "-a", newAppName, "-f", "-", "--ownership-override-allowed-apps", existingAppName1},
RunOpts{StdinReader: strings.NewReader(resourcesString), AllowError: true})
require.Error(t, err)
require.Contains(t, err.Error(), existingAppName1)
require.Contains(t, err.Error(), existingAppName2)

// Test with override scoped to single existing app
_, err = kapp.RunWithOpts([]string{"deploy", "-a", newAppName, "-f", "-", "--dangerous-override-ownership-of-existing-resources", "--ownership-override-allowed-apps", existingAppName1},
RunOpts{StdinReader: strings.NewReader(resourcesString), AllowError: true})
require.Error(t, err)
require.NotContains(t, err.Error(), existingAppName1)
require.Contains(t, err.Error(), existingAppName2)

// Test with override scoped to both existing app
kapp.RunWithOpts([]string{"deploy", "-a", newAppName, "-f", "-", "--dangerous-override-ownership-of-existing-resources", "--ownership-override-allowed-apps", fmt.Sprintf("%s,%s", existingAppName1, existingAppName2)},
RunOpts{StdinReader: strings.NewReader(resourcesString)})
})
}
Loading