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

fix(cli): add flags to admin import for retrying updates on conflicts and skipping resources with specific labels. #21694

Merged
merged 23 commits into from
Feb 4, 2025
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
57 changes: 51 additions & 6 deletions cmd/argocd/commands/admin/backup.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import (
"fmt"
"io"
"os"
"strings"
"time"

"github.com/argoproj/gitops-engine/pkg/utils/kube"
log "github.com/sirupsen/logrus"
Expand All @@ -14,6 +16,8 @@ import (
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/client-go/dynamic"
"k8s.io/client-go/tools/clientcmd"

"k8s.io/client-go/util/retry"
"sigs.k8s.io/yaml"

"github.com/argoproj/argo-cd/v3/cmd/argocd/commands/utils"
Expand Down Expand Up @@ -43,7 +47,6 @@ func NewExportCommand() *cobra.Command {
errors.CheckError(err)
namespace, _, err := clientConfig.Namespace()
errors.CheckError(err)

var writer io.Writer
if out == "-" {
writer = os.Stdout
Expand Down Expand Up @@ -139,7 +142,9 @@ func NewImportCommand() *cobra.Command {
verbose bool
stopOperation bool
ignoreTracking bool
overrideOnConflict bool
promptsEnabled bool
skipResourcesWithLabel string
applicationNamespaces []string
applicationsetNamespaces []string
)
Expand All @@ -162,7 +167,8 @@ func NewImportCommand() *cobra.Command {
acdClients := newArgoCDClientsets(config, namespace)
client, err := dynamic.NewForConfig(config)
errors.CheckError(err)

fmt.Printf("import process started %s\n", namespace)
tt := time.Now()
var input []byte
if in := args[0]; in == "-" {
input, err = io.ReadAll(os.Stdin)
Expand All @@ -176,19 +182,20 @@ func NewImportCommand() *cobra.Command {
}

additionalNamespaces := getAdditionalNamespaces(ctx, acdClients)

if len(applicationNamespaces) == 0 {
applicationNamespaces = additionalNamespaces.applicationNamespaces
}
if len(applicationsetNamespaces) == 0 {
applicationsetNamespaces = additionalNamespaces.applicationsetNamespaces
}

// pruneObjects tracks live objects and it's current resource version. any remaining
// pruneObjects tracks live objects, and it's current resource version. any remaining
// items in this map indicates the resource should be pruned since it no longer appears
// in the backup

pruneObjects := make(map[kube.ResourceKey]unstructured.Unstructured)
configMaps, err := acdClients.configMaps.List(ctx, metav1.ListOptions{})

errors.CheckError(err)
// referencedSecrets holds any secrets referenced in the argocd-cm configmap. These
// secrets need to be imported too
Expand Down Expand Up @@ -234,11 +241,15 @@ func NewImportCommand() *cobra.Command {
}
}
}

// Create or replace existing object
backupObjects, err := kube.SplitYAML(input)

errors.CheckError(err)
for _, bakObj := range backupObjects {
if isSkipLabelMatches(bakObj, skipResourcesWithLabel) {
fmt.Printf("Skipping %s/%s %s in namespace %s\n", bakObj.GroupVersionKind().Group, bakObj.GroupVersionKind().Kind, bakObj.GetName(), bakObj.GetNamespace())
continue
}
gvk := bakObj.GroupVersionKind()
// For objects without namespace, assume they belong in ArgoCD namespace
if bakObj.GetNamespace() == "" {
Expand Down Expand Up @@ -299,6 +310,21 @@ func NewImportCommand() *cobra.Command {
if !dryRun {
newLive := updateLive(bakObj, &liveObj, stopOperation)
_, err = dynClient.Update(ctx, newLive, metav1.UpdateOptions{})
if apierrors.IsConflict(err) {
fmt.Printf("Failed to update %s/%s %s in namespace %s: %v\n", gvk.Group, gvk.Kind, bakObj.GetName(), bakObj.GetNamespace(), err)
if overrideOnConflict {
err = retry.RetryOnConflict(retry.DefaultRetry, func() error {
fmt.Printf("Resource conflict: retrying update for Group: %s, Kind: %s, Name: %s, Namespace: %s\n", gvk.Group, gvk.Kind, bakObj.GetName(), bakObj.GetNamespace())
liveObj, getErr := dynClient.Get(ctx, newLive.GetName(), metav1.GetOptions{})
if getErr != nil {
errors.CheckError(getErr)
}
newLive.SetResourceVersion(liveObj.GetResourceVersion())
_, err = dynClient.Update(ctx, newLive, metav1.UpdateOptions{})
return err
})
}
}
if apierrors.IsForbidden(err) || apierrors.IsNotFound(err) {
isForbidden = true
log.Warnf("%s/%s %s: %v", gvk.Group, gvk.Kind, bakObj.GetName(), err)
Expand Down Expand Up @@ -363,19 +389,22 @@ func NewImportCommand() *cobra.Command {
fmt.Printf("%s/%s %s needs pruning\n", key.Group, key.Kind, key.Name)
}
}
duration := time.Since(tt)
fmt.Printf("Import process completed successfully in namespace %s at %s, duration: %s\n", namespace, time.Now().Format(time.RFC3339), duration)
},
}

clientConfig = cli.AddKubectlFlagsToCmd(&command)
command.Flags().BoolVar(&dryRun, "dry-run", false, "Print what will be performed")
command.Flags().BoolVar(&prune, "prune", false, "Prune secrets, applications and projects which do not appear in the backup")
command.Flags().BoolVar(&ignoreTracking, "ignore-tracking", false, "Do not update the tracking annotation if the resource is already tracked")
command.Flags().BoolVar(&overrideOnConflict, "override-on-conflict", false, "Override the resource on conflict when updating resources")
command.Flags().BoolVar(&verbose, "verbose", false, "Verbose output (versus only changed output)")
command.Flags().BoolVar(&stopOperation, "stop-operation", false, "Stop any existing operations")
command.Flags().StringVarP(&skipResourcesWithLabel, "skip-resources-with-label", "", "", "Skip importing resources based on the label e.g. '--skip-resources-with-label my-label/example.io=true'")
command.Flags().StringSliceVarP(&applicationNamespaces, "application-namespaces", "", []string{}, fmt.Sprintf("Comma separated list of namespace globs to which import of applications is allowed. If not provided value from '%s' in %s will be used,if it's not defined only applications without an explicit namespace will be imported to the Argo CD namespace", applicationNamespacesCmdParamsKey, common.ArgoCDCmdParamsConfigMapName))
command.Flags().StringSliceVarP(&applicationsetNamespaces, "applicationset-namespaces", "", []string{}, fmt.Sprintf("Comma separated list of namespace globs which import of applicationsets is allowed. If not provided value from '%s' in %s will be used,if it's not defined only applicationsets without an explicit namespace will be imported to the Argo CD namespace", applicationsetNamespacesCmdParamsKey, common.ArgoCDCmdParamsConfigMapName))
command.PersistentFlags().BoolVar(&promptsEnabled, "prompts-enabled", localconfig.GetPromptsEnabled(true), "Force optional interactive prompts to be enabled or disabled, overriding local configuration. If not specified, the local configuration value will be used, which is false by default.")

return &command
}

Expand Down Expand Up @@ -472,3 +501,19 @@ func updateTracking(bak, live *unstructured.Unstructured) {
}
}
}

// isSkipLabelMatches return if the resource should be skipped based on the labels
func isSkipLabelMatches(bak *unstructured.Unstructured, skipResourcesWithLabel string) bool {
if skipResourcesWithLabel == "" {
return false
}
parts := strings.SplitN(skipResourcesWithLabel, "=", 2)
if len(parts) != 2 || parts[0] == "" || parts[1] == "" {
return false
}
key, value := parts[0], parts[1]
if val, ok := bak.GetLabels()[key]; ok && val == value {
return true
}
return false
}
73 changes: 73 additions & 0 deletions cmd/argocd/commands/admin/backup_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,3 +85,76 @@ func Test_updateTracking(t *testing.T) {
})
}
}

func TestIsSkipLabelMatches(t *testing.T) {
tests := []struct {
name string
obj *unstructured.Unstructured
skipLabels string
expected bool
}{
{
name: "Label matches",
obj: &unstructured.Unstructured{
Object: map[string]any{
"metadata": map[string]any{
"labels": map[string]any{
"test-label": "value",
},
},
},
},
skipLabels: "test-label=value",
expected: true,
},
{
name: "Label does not match",
obj: &unstructured.Unstructured{
Object: map[string]any{
"metadata": map[string]any{
"labels": map[string]any{
"different-label": "value",
},
},
},
},
skipLabels: "test-label=value",
expected: false,
},
{
name: "Empty skip labels",
obj: &unstructured.Unstructured{
Object: map[string]any{
"metadata": map[string]any{
"labels": map[string]any{
"test-label": "value",
},
},
},
},
skipLabels: "",
expected: false,
},
{
name: "No labels value",
obj: &unstructured.Unstructured{
Object: map[string]any{
"metadata": map[string]any{
"labels": map[string]any{
"test-label": "value",
"another-label": "value2",
},
},
},
},
skipLabels: "test-label",
expected: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := isSkipLabelMatches(tt.obj, tt.skipLabels)
assert.Equal(t, tt.expected, result)
})
}
}
2 changes: 2 additions & 0 deletions docs/user-guide/commands/argocd_admin_import.md

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading