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

458 lines
15 KiB
Go

package diff
import (
"context"
"errors"
"fmt"
"github.com/go-logr/logr"
log "github.com/sirupsen/logrus"
k8smanagedfields "k8s.io/apimachinery/pkg/util/managedfields"
"github.com/hanzoai/deploy/pkg/apis/application/v1alpha1"
"github.com/hanzoai/deploy/util/argo"
"github.com/hanzoai/deploy/util/argo/managedfields"
"github.com/hanzoai/deploy/util/argo/normalizers"
appstatecache "github.com/hanzoai/deploy/util/cache/appstate"
"github.com/hanzoai/deploy/gitops-engine/pkg/diff"
"github.com/hanzoai/deploy/gitops-engine/pkg/utils/kube"
"github.com/hanzoai/deploy/gitops-engine/pkg/utils/kube/scheme"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
)
// DiffConfigBuilder is used as a safe way to create valid DiffConfigs.
type DiffConfigBuilder struct {
diffConfig *diffConfig
}
// NewDiffConfigBuilder create a new DiffConfigBuilder instance.
func NewDiffConfigBuilder() *DiffConfigBuilder {
return &DiffConfigBuilder{
diffConfig: &diffConfig{
ignoreMutationWebhook: true,
},
}
}
// WithDiffSettings will set the diff settings in the builder.
func (b *DiffConfigBuilder) WithDiffSettings(id []v1alpha1.ResourceIgnoreDifferences, o map[string]v1alpha1.ResourceOverride, ignoreAggregatedRoles bool, ignoreNormalizerOpts normalizers.IgnoreNormalizerOpts) *DiffConfigBuilder {
ignores := id
if ignores == nil {
ignores = []v1alpha1.ResourceIgnoreDifferences{}
}
b.diffConfig.ignores = ignores
overrides := o
if overrides == nil {
overrides = make(map[string]v1alpha1.ResourceOverride)
}
b.diffConfig.overrides = overrides
b.diffConfig.ignoreAggregatedRoles = ignoreAggregatedRoles
b.diffConfig.ignoreNormalizerOpts = ignoreNormalizerOpts
return b
}
// WithTrackingMethod sets the tracking in the diff config.
func (b *DiffConfigBuilder) WithTracking(appLabelKey, trackingMethod string) *DiffConfigBuilder {
b.diffConfig.appLabelKey = appLabelKey
b.diffConfig.trackingMethod = trackingMethod
return b
}
// WithNoCache sets the nocache in the diff config.
func (b *DiffConfigBuilder) WithNoCache() *DiffConfigBuilder {
b.diffConfig.noCache = true
return b
}
// WithCache sets the appstatecache.Cache and the appName in the diff config. Those the
// are two objects necessary to retrieve a cached diff.
func (b *DiffConfigBuilder) WithCache(s *appstatecache.Cache, appName string) *DiffConfigBuilder {
b.diffConfig.stateCache = s
b.diffConfig.appName = appName
return b
}
// WithLogger sets the logger in the diff config.
func (b *DiffConfigBuilder) WithLogger(l logr.Logger) *DiffConfigBuilder {
b.diffConfig.logger = &l
return b
}
// WithGVKParser sets the gvkParser in the diff config.
func (b *DiffConfigBuilder) WithGVKParser(parser *k8smanagedfields.GvkParser) *DiffConfigBuilder {
b.diffConfig.gvkParser = parser
return b
}
// WithStructuredMergeDiff defines if the diff should be calculated using structured
// merge.
func (b *DiffConfigBuilder) WithStructuredMergeDiff(smd bool) *DiffConfigBuilder {
b.diffConfig.structuredMergeDiff = smd
return b
}
// WithManager defines the manager that should be using during structured
// merge diffs.
func (b *DiffConfigBuilder) WithManager(manager string) *DiffConfigBuilder {
b.diffConfig.manager = manager
return b
}
func (b *DiffConfigBuilder) WithServerSideDryRunner(ssdr diff.ServerSideDryRunner) *DiffConfigBuilder {
b.diffConfig.serverSideDryRunner = ssdr
return b
}
func (b *DiffConfigBuilder) WithServerSideDiff(ssd bool) *DiffConfigBuilder {
b.diffConfig.serverSideDiff = ssd
return b
}
func (b *DiffConfigBuilder) WithIgnoreMutationWebhook(m bool) *DiffConfigBuilder {
b.diffConfig.ignoreMutationWebhook = m
return b
}
// Build will first validate the current state of the diff config and return the
// DiffConfig implementation if no errors are found. Will return nil and the error
// details otherwise.
func (b *DiffConfigBuilder) Build() (DiffConfig, error) {
err := b.diffConfig.Validate()
if err != nil {
return nil, err
}
return b.diffConfig, nil
}
// DiffConfig defines methods to retrieve the configurations used while applying diffs
// and normalizing resources.
type DiffConfig interface {
// Validate will check if the current configurations are set properly.
Validate() error
// DiffFromCache will verify if it should retrieve the cached ResourceDiff based on this
// DiffConfig.
DiffFromCache(appName string) (bool, []*v1alpha1.ResourceDiff)
// Ignores Application level ignore difference configurations.
Ignores() []v1alpha1.ResourceIgnoreDifferences
// Overrides is map of system configurations to override the Application ones.
// The key should follow the "group/kind" format.
Overrides() map[string]v1alpha1.ResourceOverride
AppLabelKey() string
TrackingMethod() string
// AppName the Application name. Used to retrieve the cached diff.
AppName() string
// NoCache defines if should retrieve the diff from cache.
NoCache() bool
// StateCache is used when retrieving the diff from the cache.
StateCache() *appstatecache.Cache
IgnoreAggregatedRoles() bool
// Logger used during the diff.
Logger() *logr.Logger
// GVKParser returns a parser able to build a TypedValue used in
// structured merge diffs.
GVKParser() *k8smanagedfields.GvkParser
// StructuredMergeDiff defines if the diff should be calculated using
// structured merge diffs. Will use standard 3-way merge diffs if
// returns false.
StructuredMergeDiff() bool
// Manager returns the manager that should be used by the diff while
// calculating the structured merge diff.
Manager() string
ServerSideDiff() bool
ServerSideDryRunner() diff.ServerSideDryRunner
IgnoreMutationWebhook() bool
IgnoreNormalizerOpts() normalizers.IgnoreNormalizerOpts
}
// diffConfig defines the configurations used while applying diffs.
type diffConfig struct {
ignores []v1alpha1.ResourceIgnoreDifferences
overrides map[string]v1alpha1.ResourceOverride
appLabelKey string
trackingMethod string
appName string
noCache bool
stateCache *appstatecache.Cache
ignoreAggregatedRoles bool
logger *logr.Logger
gvkParser *k8smanagedfields.GvkParser
structuredMergeDiff bool
manager string
serverSideDiff bool
serverSideDryRunner diff.ServerSideDryRunner
ignoreMutationWebhook bool
ignoreNormalizerOpts normalizers.IgnoreNormalizerOpts
}
func (c *diffConfig) Ignores() []v1alpha1.ResourceIgnoreDifferences {
return c.ignores
}
func (c *diffConfig) Overrides() map[string]v1alpha1.ResourceOverride {
return c.overrides
}
func (c *diffConfig) AppLabelKey() string {
return c.appLabelKey
}
func (c *diffConfig) TrackingMethod() string {
return c.trackingMethod
}
func (c *diffConfig) AppName() string {
return c.appName
}
func (c *diffConfig) NoCache() bool {
return c.noCache
}
func (c *diffConfig) StateCache() *appstatecache.Cache {
return c.stateCache
}
func (c *diffConfig) IgnoreAggregatedRoles() bool {
return c.ignoreAggregatedRoles
}
func (c *diffConfig) Logger() *logr.Logger {
return c.logger
}
func (c *diffConfig) GVKParser() *k8smanagedfields.GvkParser {
return c.gvkParser
}
func (c *diffConfig) StructuredMergeDiff() bool {
return c.structuredMergeDiff
}
func (c *diffConfig) Manager() string {
return c.manager
}
func (c *diffConfig) ServerSideDryRunner() diff.ServerSideDryRunner {
return c.serverSideDryRunner
}
func (c *diffConfig) ServerSideDiff() bool {
return c.serverSideDiff
}
func (c *diffConfig) IgnoreMutationWebhook() bool {
return c.ignoreMutationWebhook
}
func (c *diffConfig) IgnoreNormalizerOpts() normalizers.IgnoreNormalizerOpts {
return c.ignoreNormalizerOpts
}
// Validate will check the current state of this diffConfig and return
// error if it finds any required configuration missing.
func (c *diffConfig) Validate() error {
msg := "diffConfig validation error"
if c.ignores == nil {
return fmt.Errorf("%s: ResourceIgnoreDifferences can not be nil", msg)
}
if c.overrides == nil {
return fmt.Errorf("%s: ResourceOverride can not be nil", msg)
}
if !c.noCache {
if c.appName == "" {
return fmt.Errorf("%s: AppName must be set when retrieving from cache", msg)
}
if c.stateCache == nil {
return fmt.Errorf("%s: StateCache must be set when retrieving from cache", msg)
}
}
if c.serverSideDiff && c.serverSideDryRunner == nil {
return fmt.Errorf("%s: serverSideDryRunner must be set when using server side diff", msg)
}
return nil
}
// NormalizationResult holds the normalized lives and target resources.
type NormalizationResult struct {
Lives []*unstructured.Unstructured
Targets []*unstructured.Unstructured
}
// StateDiff will apply all required normalizations and calculate the diffs between
// the live and the config/desired states.
func StateDiff(ctx context.Context, live, config *unstructured.Unstructured, diffConfig DiffConfig) (diff.DiffResult, error) {
results, err := StateDiffs(ctx, []*unstructured.Unstructured{live}, []*unstructured.Unstructured{config}, diffConfig)
if err != nil {
return diff.DiffResult{}, err
}
if len(results.Diffs) != 1 {
return diff.DiffResult{}, fmt.Errorf("StateDiff error: unexpected diff results: expected 1 got %d", len(results.Diffs))
}
return results.Diffs[0], nil
}
// StateDiffs will apply all required normalizations and calculate the diffs between
// the live and the config/desired states.
func StateDiffs(ctx context.Context, lives, configs []*unstructured.Unstructured, diffConfig DiffConfig) (*diff.DiffResultList, error) {
normResults, err := preDiffNormalize(lives, configs, diffConfig)
if err != nil {
return nil, fmt.Errorf("failed to perform pre-diff normalization: %w", err)
}
diffNormalizer, err := newDiffNormalizer(diffConfig.Ignores(), diffConfig.Overrides(), diffConfig.IgnoreNormalizerOpts())
if err != nil {
return nil, fmt.Errorf("failed to create diff normalizer: %w", err)
}
diffOpts := []diff.Option{
diff.WithNormalizer(diffNormalizer),
diff.IgnoreAggregatedRoles(diffConfig.IgnoreAggregatedRoles()),
diff.WithStructuredMergeDiff(diffConfig.StructuredMergeDiff()),
diff.WithGVKParser(diffConfig.GVKParser()),
diff.WithManager(diffConfig.Manager()),
diff.WithServerSideDiff(diffConfig.ServerSideDiff()),
diff.WithServerSideDryRunner(diffConfig.ServerSideDryRunner()),
diff.WithIgnoreMutationWebhook(diffConfig.IgnoreMutationWebhook()),
}
if diffConfig.Logger() != nil {
diffOpts = append(diffOpts, diff.WithLogr(*diffConfig.Logger()))
}
useCache, cachedDiff := diffConfig.DiffFromCache(diffConfig.AppName())
if useCache && cachedDiff != nil {
cached, err := diffArrayCached(ctx, normResults.Targets, normResults.Lives, cachedDiff, diffOpts...)
if err != nil {
return nil, fmt.Errorf("failed to calculate diff from cache: %w", err)
}
return cached, nil
}
array, err := diff.DiffArray(ctx, normResults.Targets, normResults.Lives, diffOpts...)
if err != nil {
return nil, fmt.Errorf("failed to calculate diff: %w", err)
}
return array, nil
}
func diffArrayCached(ctx context.Context, configArray []*unstructured.Unstructured, liveArray []*unstructured.Unstructured, cachedDiff []*v1alpha1.ResourceDiff, opts ...diff.Option) (*diff.DiffResultList, error) {
numItems := len(configArray)
if len(liveArray) != numItems {
return nil, errors.New("left and right arrays have mismatched lengths")
}
diffByKey := map[kube.ResourceKey]*v1alpha1.ResourceDiff{}
for _, res := range cachedDiff {
diffByKey[kube.NewResourceKey(res.Group, res.Kind, res.Namespace, res.Name)] = res
}
diffResultList := diff.DiffResultList{
Diffs: make([]diff.DiffResult, numItems),
}
for i := range numItems {
config := configArray[i]
live := liveArray[i]
resourceVersion := ""
var key kube.ResourceKey
if live != nil {
key = kube.GetResourceKey(live)
resourceVersion = live.GetResourceVersion()
} else {
key = kube.GetResourceKey(config)
}
var dr *diff.DiffResult
if cachedDiff, ok := diffByKey[key]; ok && cachedDiff.ResourceVersion == resourceVersion {
dr = &diff.DiffResult{
NormalizedLive: []byte(cachedDiff.NormalizedLiveState),
PredictedLive: []byte(cachedDiff.PredictedLiveState),
Modified: cachedDiff.Modified,
}
} else {
res, err := diff.Diff(ctx, configArray[i], liveArray[i], opts...)
if err != nil {
return nil, err
}
dr = res
}
if dr != nil {
diffResultList.Diffs[i] = *dr
if dr.Modified {
diffResultList.Modified = true
}
}
}
return &diffResultList, nil
}
// DiffFromCache will verify if it should retrieve the cached ResourceDiff based on this
// DiffConfig. Returns true and the cached ResourceDiff if configured to use the cache.
// Returns false and nil otherwise.
func (c *diffConfig) DiffFromCache(appName string) (bool, []*v1alpha1.ResourceDiff) {
if c.noCache || c.stateCache == nil || appName == "" {
return false, nil
}
cachedDiff := make([]*v1alpha1.ResourceDiff, 0)
err := c.stateCache.GetAppManagedResources(appName, &cachedDiff)
if err != nil {
if errors.Is(err, appstatecache.ErrCacheMiss) {
log.Warnf("DiffFromCache: cannot get managed resources for app %s: %s", appName, err)
} else {
log.Errorf("DiffFromCache: cannot get managed resources for app %s: %s", appName, err)
}
return false, nil
}
return true, cachedDiff
}
// preDiffNormalize applies the normalization of live and target resources before invoking
// the diff. None of the attributes in the lives and targets params will be modified.
func preDiffNormalize(lives, targets []*unstructured.Unstructured, diffConfig DiffConfig) (*NormalizationResult, error) {
if diffConfig == nil {
return nil, errors.New("preDiffNormalize error: diffConfig can not be nil")
}
err := diffConfig.Validate()
if err != nil {
return nil, fmt.Errorf("preDiffNormalize error: %w", err)
}
results := &NormalizationResult{}
for i := range targets {
target := safeDeepCopy(targets[i])
live := safeDeepCopy(lives[i])
resourceTracking := argo.NewResourceTracking()
_ = resourceTracking.Normalize(target, live, diffConfig.AppLabelKey(), diffConfig.TrackingMethod())
// just normalize on managed fields if live and target aren't nil as we just care
// about conflicting fields
if live != nil && target != nil {
gvk := target.GetObjectKind().GroupVersionKind()
idc := NewIgnoreDiffConfig(diffConfig.Ignores(), diffConfig.Overrides())
ok, ignoreDiff := idc.HasIgnoreDifference(gvk.Group, gvk.Kind, target.GetName(), target.GetNamespace())
if ok && len(ignoreDiff.ManagedFieldsManagers) > 0 {
pt := scheme.ResolveParseableType(gvk, diffConfig.GVKParser())
var err error
live, target, err = managedfields.Normalize(live, target, ignoreDiff.ManagedFieldsManagers, pt)
if err != nil {
return nil, err
}
}
}
results.Lives = append(results.Lives, live)
results.Targets = append(results.Targets, target)
}
return results, nil
}
// safeDeepCopy will return nil if given obj is nil.
func safeDeepCopy(obj *unstructured.Unstructured) *unstructured.Unstructured {
if obj == nil {
return nil
}
return obj.DeepCopy()
}