Files
41536738c8 refactor(cd): hard-fork - rename CRD API group argoproj.io -> deploy.hanzo.ai (#1)
* feat(api): hard-fork CRD API group argoproj.io -> deploy.hanzo.ai

Hanzo CD hard-fork, phase 1.1. Single source of truth is
pkg/apis/application/register.go's Group constant (Application/AppProject/
ApplicationSet all derive their FullName from it); every other Go call-site
that hardcoded the literal group string is updated to match: the 3 generated
informer GVRs, the app-of-apps nested-Application detector in types.go, the
resource-tree Application-kind cache populator, the 3 NotFound error
constructors in server/application, and the applicationset-controller's
leader-election Lease name/ID (kept in lockstep across Go source + RBAC
resourceNames, or leader election would get RBAC-denied on startup).

CRD YAMLs (application/appproject/applicationset) and every RBAC apiGroups
rule that actually governs our 3 CRDs are repointed to deploy.hanzo.ai, across
both manifests/base/* (namespaced Roles) and manifests/cluster-rbac/* (cluster
scope). Two adjacent things that share the "argoproj.io" string but are NOT
ours are deliberately left untouched: gitops-engine's health-check dispatch
for Argo Workflows' `Workflow` kind, and argocd-server-clusterrole's second
apiGroups block granting read on Argo Workflows' `workflows` resource — both
belong to a separate, unrelated Argoproj-family project we are not forking.

Also untouched, per explicit scope: annotation/label keys (argocd.argoproj.io/*)
and finalizers (*.argoproj.io) that track already-applied live resources, and
argocd-cm.yaml's resource.customizations.ignoreResourceUpdates keys (a narrow
app-of-apps diffing nicety, not build- or RBAC-relevant).

CGO_ENABLED=0 go build ./... verified green.

* ci: wire canonical hanzo.yml + cicd.yml (Hanzo CD image build)

Phase 1.3. Follows the same one-way pattern every hanzo/lux/zoo repo uses:
hanzo.yml declares the image (root Dockerfile -> ghcr.io/hanzoai/deploy) and a
fast go-build sanity test (the multi-stage Dockerfile build is the slow, real
gate); cicd.yml is the ~10-line trigger shim importing hanzoai/ci's reusable
build workflow on the arc pool, secrets from KMS only.

No `deploy:` block yet, matching the hanzoai/cms build-only-first-cutover
pattern: this repo's own live hanzo-cd namespace runs the whole Hanzo fleet's
GitOps, so the prod image/CRD swap is a deliberate separate action (see the
[HELD] universe PR), never an automatic rollout on merge. Every PR/push still
builds and pushes an immutable ghcr.io/hanzoai/deploy:sha-<7>-amd64 image.

* feat(ui): rebrand Argo CD -> Hanzo CD (title, favicon, logo, sidebar)

Phase 1.2. User-facing "Argo CD"/"ArgoCD" text replaced with "Hanzo CD"
across the login page, help modal, settings screens, version-info panel,
sync-options warning, fullscreen-logs title, app.tsx page titles, and
index.html's <title>/noscript text (dropped the now-wrong upstream CLI
doc link rather than invent a hanzo.ai URL that doesn't exist).

Logo/favicon assets replaced with the canonical Hanzo mark (never
hand-drawn, copied from ~/work/hanzo/logo/dist): the two real usages of
Argo's logo collapse onto one Hanzo glyph (mono + white variants) at the
same 5 call sites (login icon + footer, login.scss $logoPath/
$logoNegativePath, sidebar text-logo), preserving the existing CSS
invert() filters so both the light login panel and dark sidebar still
render correctly. Old argologo.svg/argo_o.svg/argo.png deleted (no
longer referenced). favicon-{16x16,32x32}.png added at
ui/src/assets/favicon/ (index.html's links to that path were previously
dead - the directory didn't exist in this checkout). package.json name
argo-cd-ui -> hanzo-cd-ui.

Left alone, deliberately: the two Kubernetes resource-kind icon sets
under ui/src/assets/images/resources/ (unrelated to branding), and
upstream doc/project links (argoproj.io, argo-cd.readthedocs.io) since
we have no equivalent hanzo.ai docs to point to yet - except the login
footer logo's outbound link, which now points to hanzo.ai instead of
argoproj.io (a Hanzo-branded mark linking to the upstream project it
was forked from read as an obvious leftover).

* feat(module): rename Go module github.com/argoproj/argo-cd/v3 -> github.com/hanzoai/deploy

Phase 2. No version suffix on the new path (org policy: never publish our
own Go modules above v1.x.x / with a v2+ suffix) — this fork starts a fresh
v0/v1 module identity rather than carrying the v3 the upstream fork point
had reached.

Mechanical, symmetric rewrite: 704 .go files (import statements only; two
disjoint substitutions applied specific-first so the nested gitops-engine
module path never double-matches), plus go.mod (module line, the
gitops-engine require+replace pair, version reset to v0.0.0-... since a
suffix-less path can't carry a v3 semver), gitops-engine/go.mod, Makefile
(ldflags PACKAGE + 2 TEST_MODULE filters), .golangci.yaml, .goreleaser.yaml,
.mockery.yaml (+ gitops-engine's), Procfile, the codegen/proto generation
scripts (hack/generate-proto.sh, update-codegen.sh, update-openapi.sh), and
20 .proto files' go_package options. Also one OpenTelemetry tracer name
string in gitops-engine/pkg/sync/sync_context.go (a cosmestic label, not an
import, but worth keeping consistent).

CGO_ENABLED=0 go build ./... verified green for both the root module and
the nested gitops-engine module; go vet clean on both; go mod tidy run
(network available) to reconcile go.sum, dependency set unchanged.

Left alone, deliberately: doc-only mentions (docs/snyk/*.html scan reports,
gitops-engine/README.md), a comment-only reference in
.github/workflows/release.yaml, and one Renovate bot config line — none are
build- or codegen-load-bearing. Also left alone: comments citing upstream
GitHub issue URLs (github.com/argoproj/argo-cd/issues/NNNNN) and a handful
of test fixtures using "https://github.com/argoproj/argo-cd.git" as a
representative example repo URL — both are accurate historical/test-data
references, not stale self-references.

---------

Co-authored-by: Hanzo Dev <[email protected]>
2026-07-29 18:27:58 -07:00

990 lines
27 KiB
Go

package cache
import (
"context"
"errors"
"net"
"net/url"
"sync"
"testing"
"time"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime/schema"
"github.com/hanzoai/deploy/gitops-engine/pkg/cache"
"github.com/hanzoai/deploy/gitops-engine/pkg/cache/mocks"
"github.com/hanzoai/deploy/gitops-engine/pkg/health"
"github.com/hanzoai/deploy/gitops-engine/pkg/utils/kube"
"github.com/stretchr/testify/mock"
"k8s.io/client-go/kubernetes/fake"
"github.com/hanzoai/deploy/common"
"github.com/hanzoai/deploy/controller/metrics"
"github.com/hanzoai/deploy/controller/sharding"
"github.com/hanzoai/deploy/pkg/apis/application"
appv1 "github.com/hanzoai/deploy/pkg/apis/application/v1alpha1"
dbmocks "github.com/hanzoai/deploy/util/db/mocks"
argosettings "github.com/hanzoai/deploy/util/settings"
)
type netError string
func (n netError) Error() string { return string(n) }
func (n netError) Timeout() bool { return false }
func (n netError) Temporary() bool { return false }
func fixtures(ctx context.Context, data map[string]string, opts ...func(secret *corev1.Secret)) (*fake.Clientset, *argosettings.SettingsManager) {
cm := &corev1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: common.ArgoCDConfigMapName,
Namespace: "default",
Labels: map[string]string{
"app.kubernetes.io/part-of": "argocd",
},
},
Data: data,
}
secret := &corev1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: common.ArgoCDSecretName,
Namespace: "default",
Labels: map[string]string{
"app.kubernetes.io/part-of": "argocd",
},
},
Data: map[string][]byte{},
}
for i := range opts {
opts[i](secret)
}
kubeClient := fake.NewClientset(cm, secret)
settingsManager := argosettings.NewSettingsManager(ctx, kubeClient, "default")
return kubeClient, settingsManager
}
func TestHandleModEvent_HasChanges(_ *testing.T) {
clusterCache := &mocks.ClusterCache{}
clusterCache.EXPECT().Invalidate(mock.Anything, mock.Anything).Return().Once()
clusterCache.EXPECT().EnsureSynced().Return(nil).Once()
db := &dbmocks.ArgoDB{}
db.EXPECT().GetApplicationControllerReplicas().Return(1)
clustersCache := liveStateCache{
clusters: map[string]cache.ClusterCache{
"https://mycluster": clusterCache,
},
clusterSharding: sharding.NewClusterSharding(db, 0, 1, common.DefaultShardingAlgorithm),
}
clustersCache.handleModEvent(&appv1.Cluster{
Server: "https://mycluster",
Config: appv1.ClusterConfig{Username: "foo"},
}, &appv1.Cluster{
Server: "https://mycluster",
Config: appv1.ClusterConfig{Username: "bar"},
Namespaces: []string{"default"},
})
}
func TestHandleModEvent_ClusterExcluded(t *testing.T) {
t.Parallel()
clusterCache := &mocks.ClusterCache{}
clusterCache.EXPECT().Invalidate(mock.Anything, mock.Anything).Return().Once()
clusterCache.EXPECT().EnsureSynced().Return(nil).Once()
db := &dbmocks.ArgoDB{}
db.EXPECT().GetApplicationControllerReplicas().Return(1).Maybe()
clustersCache := liveStateCache{
db: nil,
appInformer: nil,
onObjectUpdated: func(_ map[string]bool, _ corev1.ObjectReference) {
},
settingsMgr: &argosettings.SettingsManager{},
metricsServer: &metrics.MetricsServer{},
// returns a shard that never process any cluster
clusterSharding: sharding.NewClusterSharding(db, 0, 1, common.DefaultShardingAlgorithm),
resourceTracking: nil,
clusters: map[string]cache.ClusterCache{"https://mycluster": clusterCache},
cacheSettings: cacheSettings{},
lock: sync.RWMutex{},
}
clustersCache.handleModEvent(&appv1.Cluster{
Server: "https://mycluster",
Config: appv1.ClusterConfig{Username: "foo"},
}, &appv1.Cluster{
Server: "https://mycluster",
Config: appv1.ClusterConfig{Username: "bar"},
Namespaces: []string{"default"},
})
assert.Len(t, clustersCache.clusters, 1)
}
func TestHandleModEvent_NoChanges(_ *testing.T) {
clusterCache := &mocks.ClusterCache{}
clusterCache.EXPECT().Invalidate(mock.Anything).Panic("should not invalidate").Maybe()
clusterCache.EXPECT().EnsureSynced().Return(nil).Panic("should not re-sync").Maybe()
db := &dbmocks.ArgoDB{}
db.EXPECT().GetApplicationControllerReplicas().Return(1).Maybe()
clustersCache := liveStateCache{
clusters: map[string]cache.ClusterCache{
"https://mycluster": clusterCache,
},
clusterSharding: sharding.NewClusterSharding(db, 0, 1, common.DefaultShardingAlgorithm),
}
clustersCache.handleModEvent(&appv1.Cluster{
Server: "https://mycluster",
Config: appv1.ClusterConfig{Username: "bar"},
}, &appv1.Cluster{
Server: "https://mycluster",
Config: appv1.ClusterConfig{Username: "bar"},
})
}
func TestHandleAddEvent_ClusterExcluded(t *testing.T) {
t.Parallel()
db := &dbmocks.ArgoDB{}
db.EXPECT().GetApplicationControllerReplicas().Return(1).Maybe()
clustersCache := liveStateCache{
clusters: map[string]cache.ClusterCache{},
clusterSharding: sharding.NewClusterSharding(db, 0, 2, common.DefaultShardingAlgorithm),
}
clustersCache.handleAddEvent(&appv1.Cluster{
Server: "https://mycluster",
Config: appv1.ClusterConfig{Username: "bar"},
})
assert.Empty(t, clustersCache.clusters)
}
func TestHandleDeleteEvent_CacheDeadlock(t *testing.T) {
t.Parallel()
testCluster := &appv1.Cluster{
Server: "https://mycluster",
Config: appv1.ClusterConfig{Username: "bar"},
}
db := &dbmocks.ArgoDB{}
db.EXPECT().GetApplicationControllerReplicas().Return(1)
fakeClient := fake.NewClientset()
settingsMgr := argosettings.NewSettingsManager(t.Context(), fakeClient, "argocd")
gitopsEngineClusterCache := &mocks.ClusterCache{}
clustersCache := liveStateCache{
clusters: map[string]cache.ClusterCache{
testCluster.Server: gitopsEngineClusterCache,
},
clusterSharding: sharding.NewClusterSharding(db, 0, 1, common.DefaultShardingAlgorithm),
settingsMgr: settingsMgr,
lock: sync.RWMutex{},
}
channel := make(chan string)
// Mocked lock held by the gitops-engine cluster cache
gitopsEngineClusterCacheLock := sync.Mutex{}
// Ensure completion of both EnsureSynced and Invalidate
ensureSyncedCompleted := sync.Mutex{}
invalidateCompleted := sync.Mutex{}
// Locks to force trigger condition during test
// Condition order:
// EnsuredSynced -> Locks gitops-engine
// handleDeleteEvent -> Locks liveStateCache
// EnsureSynced via sync, newResource, populateResourceInfoHandler -> attempts to Lock liveStateCache
// handleDeleteEvent via cluster.Invalidate -> attempts to Lock gitops-engine
handleDeleteWasCalled := sync.Mutex{}
engineHoldsEngineLock := sync.Mutex{}
ensureSyncedCompleted.Lock()
invalidateCompleted.Lock()
handleDeleteWasCalled.Lock()
engineHoldsEngineLock.Lock()
gitopsEngineClusterCache.EXPECT().EnsureSynced().Run(func() {
gitopsEngineClusterCacheLock.Lock()
t.Log("EnsureSynced: Engine has engine lock")
engineHoldsEngineLock.Unlock()
defer gitopsEngineClusterCacheLock.Unlock()
// Wait until handleDeleteEvent holds the liveStateCache lock
handleDeleteWasCalled.Lock()
// Try and obtain the liveStateCache lock
clustersCache.lock.Lock()
t.Log("EnsureSynced: Engine has LiveStateCache lock")
clustersCache.lock.Unlock()
ensureSyncedCompleted.Unlock()
}).Return(nil).Once()
gitopsEngineClusterCache.EXPECT().Invalidate().Run(func(_ ...cache.UpdateSettingsFunc) {
// Allow EnsureSynced to continue now that we're in the deadlock condition
handleDeleteWasCalled.Unlock()
// Wait until gitops engine holds the gitops lock
// This prevents timing issues if we reach this point before EnsureSynced has obtained the lock
engineHoldsEngineLock.Lock()
t.Log("Invalidate: Engine has engine lock")
engineHoldsEngineLock.Unlock()
// Lock engine lock
gitopsEngineClusterCacheLock.Lock()
t.Log("Invalidate: Invalidate has engine lock")
gitopsEngineClusterCacheLock.Unlock()
invalidateCompleted.Unlock()
}).Return().Maybe()
go func() {
// Start the gitops-engine lock holds
go func() {
err := gitopsEngineClusterCache.EnsureSynced()
if err != nil {
assert.Fail(t, err.Error())
}
}()
// Run in background
go clustersCache.handleDeleteEvent(testCluster.Server)
// Allow execution to continue on clusters cache call to trigger lock
ensureSyncedCompleted.Lock()
invalidateCompleted.Lock()
t.Log("Competing functions were able to obtain locks")
invalidateCompleted.Unlock()
ensureSyncedCompleted.Unlock()
channel <- "PASSED"
}()
select {
case str := <-channel:
assert.Equal(t, "PASSED", str, str)
case <-time.After(5 * time.Second):
assert.Fail(t, "Ended up in deadlock")
}
}
func TestIsRetryableError(t *testing.T) {
t.Parallel()
var (
tlsHandshakeTimeoutErr net.Error = netError("net/http: TLS handshake timeout")
ioTimeoutErr net.Error = netError("i/o timeout")
connectionTimedout net.Error = netError("connection timed out")
connectionReset net.Error = netError("connection reset by peer")
)
t.Run("Nil", func(t *testing.T) {
t.Parallel()
assert.False(t, isRetryableError(nil))
})
t.Run("ResourceQuotaConflictErr", func(t *testing.T) {
t.Parallel()
assert.False(t, isRetryableError(apierrors.NewConflict(schema.GroupResource{}, "", nil)))
assert.True(t, isRetryableError(apierrors.NewConflict(schema.GroupResource{Group: "v1", Resource: "resourcequotas"}, "", nil)))
})
t.Run("ExceededQuotaErr", func(t *testing.T) {
t.Parallel()
assert.False(t, isRetryableError(apierrors.NewForbidden(schema.GroupResource{}, "", nil)))
assert.True(t, isRetryableError(apierrors.NewForbidden(schema.GroupResource{Group: "v1", Resource: "pods"}, "", errors.New("exceeded quota"))))
})
t.Run("TooManyRequestsDNS", func(t *testing.T) {
t.Parallel()
assert.True(t, isRetryableError(apierrors.NewTooManyRequests("", 0)))
})
t.Run("DNSError", func(t *testing.T) {
t.Parallel()
assert.True(t, isRetryableError(&net.DNSError{}))
})
t.Run("OpError", func(t *testing.T) {
t.Parallel()
assert.True(t, isRetryableError(&net.OpError{}))
})
t.Run("UnknownNetworkError", func(t *testing.T) {
t.Parallel()
assert.True(t, isRetryableError(net.UnknownNetworkError("")))
})
t.Run("ConnectionClosedErr", func(t *testing.T) {
t.Parallel()
assert.False(t, isRetryableError(&url.Error{Err: errors.New("")}))
assert.True(t, isRetryableError(&url.Error{Err: errors.New("Connection closed by foreign host")}))
})
t.Run("TLSHandshakeTimeout", func(t *testing.T) {
t.Parallel()
assert.True(t, isRetryableError(tlsHandshakeTimeoutErr))
})
t.Run("IOHandshakeTimeout", func(t *testing.T) {
t.Parallel()
assert.True(t, isRetryableError(ioTimeoutErr))
})
t.Run("ConnectionTimeout", func(t *testing.T) {
t.Parallel()
assert.True(t, isRetryableError(connectionTimedout))
})
t.Run("ConnectionReset", func(t *testing.T) {
t.Parallel()
assert.True(t, isRetryableError(connectionReset))
})
}
func Test_asResourceNode_owner_refs(t *testing.T) {
resNode := asResourceNode(&cache.Resource{
ResourceVersion: "",
Ref: corev1.ObjectReference{
APIVersion: "v1",
},
OwnerRefs: []metav1.OwnerReference{
{
APIVersion: "v1",
Kind: "ConfigMap",
Name: "cm-1",
},
{
APIVersion: "v1",
Kind: "ConfigMap",
Name: "cm-2",
},
},
CreationTimestamp: nil,
Info: nil,
Resource: nil,
}, nil)
expected := appv1.ResourceNode{
ResourceRef: appv1.ResourceRef{
Version: "v1",
},
ParentRefs: []appv1.ResourceRef{
{
Group: "",
Kind: "ConfigMap",
Version: "v1",
Name: "cm-1",
},
{
Group: "",
Kind: "ConfigMap",
Version: "v1",
Name: "cm-2",
},
},
Info: nil,
NetworkingInfo: nil,
ResourceVersion: "",
Images: nil,
Health: nil,
CreatedAt: nil,
}
assert.Equal(t, expected, resNode)
}
func Test_getAppRecursive(t *testing.T) {
for _, tt := range []struct {
name string
r *cache.Resource
ns map[kube.ResourceKey]*cache.Resource
wantName string
wantOK assert.BoolAssertionFunc
}{
{
name: "ok: cm1->app1",
r: &cache.Resource{
Ref: corev1.ObjectReference{
Name: "cm1",
},
OwnerRefs: []metav1.OwnerReference{
{Name: "app1"},
},
},
ns: map[kube.ResourceKey]*cache.Resource{
kube.NewResourceKey("", "", "", "app1"): {
Info: &ResourceInfo{
AppName: "app1",
},
},
},
wantName: "app1",
wantOK: assert.True,
},
{
name: "ok: cm1->cm2->app1",
r: &cache.Resource{
Ref: corev1.ObjectReference{
Name: "cm1",
},
OwnerRefs: []metav1.OwnerReference{
{Name: "cm2"},
},
},
ns: map[kube.ResourceKey]*cache.Resource{
kube.NewResourceKey("", "", "", "cm2"): {
Ref: corev1.ObjectReference{
Name: "cm2",
},
OwnerRefs: []metav1.OwnerReference{
{Name: "app1"},
},
},
kube.NewResourceKey("", "", "", "app1"): {
Info: &ResourceInfo{
AppName: "app1",
},
},
},
wantName: "app1",
wantOK: assert.True,
},
{
name: "cm1->cm2->app1 & cm1->cm3->app1",
r: &cache.Resource{
Ref: corev1.ObjectReference{
Name: "cm1",
},
OwnerRefs: []metav1.OwnerReference{
{Name: "cm2"},
{Name: "cm3"},
},
},
ns: map[kube.ResourceKey]*cache.Resource{
kube.NewResourceKey("", "", "", "cm2"): {
Ref: corev1.ObjectReference{
Name: "cm2",
},
OwnerRefs: []metav1.OwnerReference{
{Name: "app1"},
},
},
kube.NewResourceKey("", "", "", "cm3"): {
Ref: corev1.ObjectReference{
Name: "cm3",
},
OwnerRefs: []metav1.OwnerReference{
{Name: "app1"},
},
},
kube.NewResourceKey("", "", "", "app1"): {
Info: &ResourceInfo{
AppName: "app1",
},
},
},
wantName: "app1",
wantOK: assert.True,
},
{
// Nothing cycle.
// Issue #11699, fixed #12667.
name: "ok: cm1->cm2 & cm1->cm3->cm2 & cm1->cm3->app1",
r: &cache.Resource{
Ref: corev1.ObjectReference{
Name: "cm1",
},
OwnerRefs: []metav1.OwnerReference{
{Name: "cm2"},
{Name: "cm3"},
},
},
ns: map[kube.ResourceKey]*cache.Resource{
kube.NewResourceKey("", "", "", "cm2"): {
Ref: corev1.ObjectReference{
Name: "cm2",
},
},
kube.NewResourceKey("", "", "", "cm3"): {
Ref: corev1.ObjectReference{
Name: "cm3",
},
OwnerRefs: []metav1.OwnerReference{
{Name: "cm2"},
{Name: "app1"},
},
},
kube.NewResourceKey("", "", "", "app1"): {
Info: &ResourceInfo{
AppName: "app1",
},
},
},
wantName: "app1",
wantOK: assert.True,
},
{
name: "cycle: cm1<->cm2",
r: &cache.Resource{
Ref: corev1.ObjectReference{
Name: "cm1",
},
OwnerRefs: []metav1.OwnerReference{
{Name: "cm2"},
},
},
ns: map[kube.ResourceKey]*cache.Resource{
kube.NewResourceKey("", "", "", "cm1"): {
Ref: corev1.ObjectReference{
Name: "cm1",
},
OwnerRefs: []metav1.OwnerReference{
{Name: "cm2"},
},
},
kube.NewResourceKey("", "", "", "cm2"): {
Ref: corev1.ObjectReference{
Name: "cm2",
},
OwnerRefs: []metav1.OwnerReference{
{Name: "cm1"},
},
},
},
wantName: "",
wantOK: assert.False,
},
{
name: "cycle: cm1->cm2->cm3->cm1",
r: &cache.Resource{
Ref: corev1.ObjectReference{
Name: "cm1",
},
OwnerRefs: []metav1.OwnerReference{
{Name: "cm2"},
},
},
ns: map[kube.ResourceKey]*cache.Resource{
kube.NewResourceKey("", "", "", "cm1"): {
Ref: corev1.ObjectReference{
Name: "cm1",
},
OwnerRefs: []metav1.OwnerReference{
{Name: "cm2"},
},
},
kube.NewResourceKey("", "", "", "cm2"): {
Ref: corev1.ObjectReference{
Name: "cm2",
},
OwnerRefs: []metav1.OwnerReference{
{Name: "cm3"},
},
},
kube.NewResourceKey("", "", "", "cm3"): {
Ref: corev1.ObjectReference{
Name: "cm3",
},
OwnerRefs: []metav1.OwnerReference{
{Name: "cm1"},
},
},
},
wantName: "",
wantOK: assert.False,
},
} {
t.Run(tt.name, func(t *testing.T) {
visited := map[kube.ResourceKey]bool{}
got, ok := getAppRecursive(tt.r, tt.ns, visited)
assert.Equal(t, tt.wantName, got)
tt.wantOK(t, ok)
})
}
}
func TestSkipResourceUpdate(t *testing.T) {
t.Parallel()
var (
hash1X = "x"
hash2Y = "y"
hash3X = "x"
)
info := &ResourceInfo{
manifestHash: hash1X,
Health: &health.HealthStatus{
Status: health.HealthStatusHealthy,
Message: "default",
},
}
t.Run("Nil", func(t *testing.T) {
t.Parallel()
assert.False(t, skipResourceUpdate(nil, nil))
})
t.Run("From Nil", func(t *testing.T) {
t.Parallel()
assert.False(t, skipResourceUpdate(nil, info))
})
t.Run("To Nil", func(t *testing.T) {
t.Parallel()
assert.False(t, skipResourceUpdate(info, nil))
})
t.Run("No hash", func(t *testing.T) {
t.Parallel()
assert.False(t, skipResourceUpdate(&ResourceInfo{}, &ResourceInfo{}))
})
t.Run("Same hash", func(t *testing.T) {
t.Parallel()
assert.True(t, skipResourceUpdate(&ResourceInfo{
manifestHash: hash1X,
}, &ResourceInfo{
manifestHash: hash1X,
}))
})
t.Run("Same hash value", func(t *testing.T) {
t.Parallel()
assert.True(t, skipResourceUpdate(&ResourceInfo{
manifestHash: hash1X,
}, &ResourceInfo{
manifestHash: hash3X,
}))
})
t.Run("Different hash value", func(t *testing.T) {
t.Parallel()
assert.False(t, skipResourceUpdate(&ResourceInfo{
manifestHash: hash1X,
}, &ResourceInfo{
manifestHash: hash2Y,
}))
})
t.Run("Same hash, empty health", func(t *testing.T) {
t.Parallel()
assert.True(t, skipResourceUpdate(&ResourceInfo{
manifestHash: hash1X,
Health: &health.HealthStatus{},
}, &ResourceInfo{
manifestHash: hash3X,
Health: &health.HealthStatus{},
}))
})
t.Run("Same hash, old health", func(t *testing.T) {
t.Parallel()
assert.False(t, skipResourceUpdate(&ResourceInfo{
manifestHash: hash1X,
Health: &health.HealthStatus{
Status: health.HealthStatusHealthy,
},
}, &ResourceInfo{
manifestHash: hash3X,
Health: nil,
}))
})
t.Run("Same hash, new health", func(t *testing.T) {
t.Parallel()
assert.False(t, skipResourceUpdate(&ResourceInfo{
manifestHash: hash1X,
Health: &health.HealthStatus{},
}, &ResourceInfo{
manifestHash: hash3X,
Health: &health.HealthStatus{
Status: health.HealthStatusHealthy,
},
}))
})
t.Run("Same hash, same health", func(t *testing.T) {
t.Parallel()
assert.True(t, skipResourceUpdate(&ResourceInfo{
manifestHash: hash1X,
Health: &health.HealthStatus{
Status: health.HealthStatusHealthy,
Message: "same",
},
}, &ResourceInfo{
manifestHash: hash3X,
Health: &health.HealthStatus{
Status: health.HealthStatusHealthy,
Message: "same",
},
}))
})
t.Run("Same hash, different health status", func(t *testing.T) {
t.Parallel()
assert.False(t, skipResourceUpdate(&ResourceInfo{
manifestHash: hash1X,
Health: &health.HealthStatus{
Status: health.HealthStatusHealthy,
Message: "same",
},
}, &ResourceInfo{
manifestHash: hash3X,
Health: &health.HealthStatus{
Status: health.HealthStatusDegraded,
Message: "same",
},
}))
})
t.Run("Same hash, different health message", func(t *testing.T) {
t.Parallel()
assert.True(t, skipResourceUpdate(&ResourceInfo{
manifestHash: hash1X,
Health: &health.HealthStatus{
Status: health.HealthStatusHealthy,
Message: "same",
},
}, &ResourceInfo{
manifestHash: hash3X,
Health: &health.HealthStatus{
Status: health.HealthStatusHealthy,
Message: "different",
},
}))
})
}
func TestShouldHashManifest(t *testing.T) {
t.Parallel()
tests := []struct {
name string
appName string
gvk schema.GroupVersionKind
un *unstructured.Unstructured
annotations map[string]string
want bool
}{
{
name: "appName not empty gvk matches",
appName: "MyApp",
gvk: schema.GroupVersionKind{Group: application.Group, Kind: application.ApplicationKind},
un: &unstructured.Unstructured{},
want: true,
},
{
name: "appName empty",
appName: "",
gvk: schema.GroupVersionKind{Group: application.Group, Kind: application.ApplicationKind},
un: &unstructured.Unstructured{},
want: true,
},
{
name: "appName empty group not match",
appName: "",
gvk: schema.GroupVersionKind{Group: "group1", Kind: application.ApplicationKind},
un: &unstructured.Unstructured{},
want: false,
},
{
name: "appName empty kind not match",
appName: "",
gvk: schema.GroupVersionKind{Group: application.Group, Kind: "kind1"},
un: &unstructured.Unstructured{},
want: false,
},
{
name: "argocd.argoproj.io/ignore-resource-updates=true",
appName: "",
gvk: schema.GroupVersionKind{Group: application.Group, Kind: "kind1"},
un: &unstructured.Unstructured{},
annotations: map[string]string{"argocd.argoproj.io/ignore-resource-updates": "true"},
want: true,
},
{
name: "argocd.argoproj.io/ignore-resource-updates=invalid",
appName: "",
gvk: schema.GroupVersionKind{Group: application.Group, Kind: "kind1"},
un: &unstructured.Unstructured{},
annotations: map[string]string{"argocd.argoproj.io/ignore-resource-updates": "invalid"},
want: false,
},
{
name: "argocd.argoproj.io/ignore-resource-updates=false",
appName: "",
gvk: schema.GroupVersionKind{Group: application.Group, Kind: "kind1"},
un: &unstructured.Unstructured{},
annotations: map[string]string{"argocd.argoproj.io/ignore-resource-updates": "false"},
want: false,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
t.Parallel()
if test.annotations != nil {
test.un.SetAnnotations(test.annotations)
}
got := shouldHashManifest(test.appName, test.gvk, test.un)
require.Equalf(t, test.want, got, "test=%v", test.name)
})
}
}
func Test_GetVersionsInfo_error_redacted(t *testing.T) {
c := liveStateCache{}
cluster := &appv1.Cluster{
Server: "https://localhost:1234",
Config: appv1.ClusterConfig{
Username: "admin",
Password: "password",
},
}
_, _, err := c.GetVersionsInfo(cluster)
require.Error(t, err)
assert.NotContains(t, err.Error(), "password")
}
func TestLoadCacheSettings(t *testing.T) {
t.Parallel()
_, settingsManager := fixtures(t.Context(), map[string]string{
"application.instanceLabelKey": "testLabel",
"application.resourceTrackingMethod": string(appv1.TrackingMethodLabel),
"installationID": "123456789",
})
ch := liveStateCache{
settingsMgr: settingsManager,
}
label, err := settingsManager.GetAppInstanceLabelKey()
require.NoError(t, err)
trackingMethod, err := settingsManager.GetTrackingMethod()
require.NoError(t, err)
res, err := ch.loadCacheSettings()
require.NoError(t, err)
assert.Equal(t, label, res.appInstanceLabelKey)
assert.Equal(t, string(appv1.TrackingMethodLabel), trackingMethod)
assert.Equal(t, "123456789", res.installationID)
// By default the values won't be nil
assert.NotNil(t, res.resourceOverrides)
assert.NotNil(t, res.clusterSettings)
assert.True(t, res.ignoreResourceUpdatesEnabled)
}
func Test_ownerRefGV(t *testing.T) {
t.Parallel()
tests := []struct {
name string
input metav1.OwnerReference
expected schema.GroupVersion
}{
{
name: "valid API Version",
input: metav1.OwnerReference{
APIVersion: "apps/v1",
},
expected: schema.GroupVersion{
Group: "apps",
Version: "v1",
},
},
{
name: "custom defined version",
input: metav1.OwnerReference{
APIVersion: "custom-version",
},
expected: schema.GroupVersion{
Version: "custom-version",
Group: "",
},
},
{
name: "empty APIVersion",
input: metav1.OwnerReference{
APIVersion: "",
},
expected: schema.GroupVersion{},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
res := ownerRefGV(tt.input)
assert.Equal(t, tt.expected, res)
})
}
}
func Test_asResourceNode_cross_namespace_parent(t *testing.T) {
// Test that a namespaced resource with a cluster-scoped parent
// correctly sets the parent namespace to empty string
// Create a Role (namespaced) with an owner reference to a ClusterRole (cluster-scoped)
roleResource := &cache.Resource{
Ref: corev1.ObjectReference{
APIVersion: "rbac.authorization.k8s.io/v1",
Kind: "Role",
Namespace: "my-namespace",
Name: "my-role",
},
OwnerRefs: []metav1.OwnerReference{
{
APIVersion: "rbac.authorization.k8s.io/v1",
Kind: "ClusterRole",
Name: "my-cluster-role",
UID: "cluster-role-uid",
},
},
}
// Create namespace resources map (ClusterRole won't be in here since it's cluster-scoped)
namespaceResources := map[kube.ResourceKey]*cache.Resource{
// Add some other namespace resources but not the ClusterRole
{
Group: "rbac.authorization.k8s.io",
Kind: "Role",
Namespace: "my-namespace",
Name: "other-role",
}: {
Ref: corev1.ObjectReference{
APIVersion: "rbac.authorization.k8s.io/v1",
Kind: "Role",
Namespace: "my-namespace",
Name: "other-role",
},
},
}
resNode := asResourceNode(roleResource, namespaceResources)
// The parent reference should have empty namespace since ClusterRole is cluster-scoped
assert.Len(t, resNode.ParentRefs, 1)
assert.Equal(t, "ClusterRole", resNode.ParentRefs[0].Kind)
assert.Equal(t, "my-cluster-role", resNode.ParentRefs[0].Name)
assert.Empty(t, resNode.ParentRefs[0].Namespace, "ClusterRole parent should have empty namespace")
}
func Test_asResourceNode_same_namespace_parent(t *testing.T) {
// Test that a namespaced resource with a namespaced parent in the same namespace
// correctly sets the parent namespace
// Create a ReplicaSet with an owner reference to a Deployment (both namespaced)
rsResource := &cache.Resource{
Ref: corev1.ObjectReference{
APIVersion: "apps/v1",
Kind: "ReplicaSet",
Namespace: "my-namespace",
Name: "my-rs",
},
OwnerRefs: []metav1.OwnerReference{
{
APIVersion: "apps/v1",
Kind: "Deployment",
Name: "my-deployment",
UID: "deployment-uid",
},
},
}
// Create namespace resources map with the Deployment
deploymentKey := kube.ResourceKey{
Group: "apps",
Kind: "Deployment",
Namespace: "my-namespace",
Name: "my-deployment",
}
namespaceResources := map[kube.ResourceKey]*cache.Resource{
deploymentKey: {
Ref: corev1.ObjectReference{
APIVersion: "apps/v1",
Kind: "Deployment",
Namespace: "my-namespace",
Name: "my-deployment",
UID: "deployment-uid",
},
Resource: &unstructured.Unstructured{
Object: map[string]any{
"apiVersion": "apps/v1",
"kind": "Deployment",
"metadata": map[string]any{
"name": "my-deployment",
"namespace": "my-namespace",
"uid": "deployment-uid",
},
},
},
},
}
resNode := asResourceNode(rsResource, namespaceResources)
// The parent reference should have the same namespace
assert.Len(t, resNode.ParentRefs, 1)
assert.Equal(t, "Deployment", resNode.ParentRefs[0].Kind)
assert.Equal(t, "my-deployment", resNode.ParentRefs[0].Name)
assert.Equal(t, "my-namespace", resNode.ParentRefs[0].Namespace, "Deployment parent should have same namespace")
}