mirror of
https://github.com/hanzoai/deploy.git
synced 2026-10-07 08:44:50 +00:00
* 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]>
365 lines
14 KiB
Go
365 lines
14 KiB
Go
package lua
|
|
|
|
import (
|
|
"bytes"
|
|
"fmt"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"testing"
|
|
|
|
"github.com/stretchr/testify/assert"
|
|
"github.com/stretchr/testify/require"
|
|
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
|
|
"k8s.io/apimachinery/pkg/runtime/schema"
|
|
"sigs.k8s.io/yaml"
|
|
|
|
"github.com/hanzoai/deploy/gitops-engine/pkg/diff"
|
|
|
|
applicationpkg "github.com/hanzoai/deploy/pkg/apiclient/application"
|
|
appsv1 "github.com/hanzoai/deploy/pkg/apis/application/v1alpha1"
|
|
"github.com/hanzoai/deploy/util/cli"
|
|
)
|
|
|
|
type testNormalizer struct{}
|
|
|
|
func (t testNormalizer) Normalize(un *unstructured.Unstructured) error {
|
|
if un == nil {
|
|
return nil
|
|
}
|
|
// Disambiguate resources by apiVersion group to avoid collisions on Kind names
|
|
gv, err := schema.ParseGroupVersion(un.GetAPIVersion())
|
|
if err != nil {
|
|
return fmt.Errorf("failed to parse apiVersion for %s: %w", un.GetKind(), err)
|
|
}
|
|
group := gv.Group
|
|
// First, group-specific, then kind-specific normalization
|
|
switch group {
|
|
case "batch":
|
|
if un.GetKind() == "Job" {
|
|
return t.normalizeJob(un)
|
|
}
|
|
case "apps":
|
|
switch un.GetKind() {
|
|
case "DaemonSet", "Deployment", "StatefulSet":
|
|
if err := setRestartedAtAnnotationOnPodTemplate(un); err != nil {
|
|
return fmt.Errorf("failed to normalize %s: %w", un.GetKind(), err)
|
|
}
|
|
}
|
|
if un.GetKind() == "Deployment" {
|
|
if err := unstructured.SetNestedField(un.Object, nil, "status"); err != nil {
|
|
return fmt.Errorf("failed to normalize %s: %w", un.GetKind(), err)
|
|
}
|
|
if err := unstructured.SetNestedField(un.Object, nil, "metadata", "creationTimestamp"); err != nil {
|
|
return fmt.Errorf("failed to normalize %s: %w", un.GetKind(), err)
|
|
}
|
|
if err := unstructured.SetNestedField(un.Object, nil, "metadata", "generation"); err != nil {
|
|
return fmt.Errorf("failed to normalize %s: %w", un.GetKind(), err)
|
|
}
|
|
}
|
|
case "argoproj.io":
|
|
switch un.GetKind() {
|
|
case "Rollout":
|
|
if err := unstructured.SetNestedField(un.Object, nil, "spec", "restartAt"); err != nil {
|
|
return fmt.Errorf("failed to normalize %s: %w", un.GetKind(), err)
|
|
}
|
|
case "Workflow":
|
|
if err := unstructured.SetNestedField(un.Object, nil, "metadata", "resourceVersion"); err != nil {
|
|
return fmt.Errorf("failed to normalize %s: %w", un.GetKind(), err)
|
|
}
|
|
if err := unstructured.SetNestedField(un.Object, nil, "metadata", "uid"); err != nil {
|
|
return fmt.Errorf("failed to normalize %s: %w", un.GetKind(), err)
|
|
}
|
|
if err := unstructured.SetNestedField(un.Object, nil, "metadata", "annotations", "workflows.argoproj.io/scheduled-time"); err != nil {
|
|
return fmt.Errorf("failed to normalize %s: %w", un.GetKind(), err)
|
|
}
|
|
}
|
|
case "external-secrets.io":
|
|
switch un.GetKind() {
|
|
case "ExternalSecret", "PushSecret":
|
|
if err := unstructured.SetNestedStringMap(un.Object, map[string]string{"force-sync": "0001-01-01T00:00:00Z"}, "metadata", "annotations"); err != nil {
|
|
return fmt.Errorf("failed to normalize %s: %w", un.GetKind(), err)
|
|
}
|
|
}
|
|
case "postgresql.cnpg.io":
|
|
if un.GetKind() == "Cluster" {
|
|
if err := setPgClusterAnnotations(un); err != nil {
|
|
return fmt.Errorf("failed to normalize %s: %w", un.GetKind(), err)
|
|
}
|
|
if err := unstructured.SetNestedField(un.Object, nil, "status", "targetPrimaryTimestamp"); err != nil {
|
|
return fmt.Errorf("failed to normalize %s: %w", un.GetKind(), err)
|
|
}
|
|
}
|
|
case "helm.toolkit.fluxcd.io":
|
|
if un.GetKind() == "HelmRelease" {
|
|
if err := setFluxRequestedAtAnnotation(un); err != nil {
|
|
return fmt.Errorf("failed to normalize %s: %w", un.GetKind(), err)
|
|
}
|
|
}
|
|
case "source.toolkit.fluxcd.io":
|
|
switch un.GetKind() {
|
|
case "Bucket", "GitRepository", "HelmChart", "HelmRepository", "OCIRepository":
|
|
if err := setFluxRequestedAtAnnotation(un); err != nil {
|
|
return fmt.Errorf("failed to normalize %s: %w", un.GetKind(), err)
|
|
}
|
|
}
|
|
case "image.toolkit.fluxcd.io":
|
|
switch un.GetKind() {
|
|
case "ImageRepository", "ImageUpdateAutomation":
|
|
if err := setFluxRequestedAtAnnotation(un); err != nil {
|
|
return fmt.Errorf("failed to normalize %s: %w", un.GetKind(), err)
|
|
}
|
|
}
|
|
case "kustomize.toolkit.fluxcd.io":
|
|
if un.GetKind() == "Kustomization" {
|
|
if err := setFluxRequestedAtAnnotation(un); err != nil {
|
|
return fmt.Errorf("failed to normalize %s: %w", un.GetKind(), err)
|
|
}
|
|
}
|
|
case "notification.toolkit.fluxcd.io":
|
|
if un.GetKind() == "Receiver" {
|
|
if err := setFluxRequestedAtAnnotation(un); err != nil {
|
|
return fmt.Errorf("failed to normalize %s: %w", un.GetKind(), err)
|
|
}
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// Helper: normalize restart annotation on pod template used by apps workloads
|
|
func setRestartedAtAnnotationOnPodTemplate(un *unstructured.Unstructured) error {
|
|
return unstructured.SetNestedStringMap(un.Object, map[string]string{"kubectl.kubernetes.io/restartedAt": "0001-01-01T00:00:00Z"}, "spec", "template", "metadata", "annotations")
|
|
}
|
|
|
|
// Helper: normalize Flux requestedAt annotation across FluxCD kinds
|
|
func setFluxRequestedAtAnnotation(un *unstructured.Unstructured) error {
|
|
return unstructured.SetNestedStringMap(un.Object, map[string]string{"reconcile.fluxcd.io/requestedAt": "By Argo CD at: 0001-01-01T00:00:00"}, "metadata", "annotations")
|
|
}
|
|
|
|
// Helper: normalize PostgreSQL CNPG Cluster annotations while preserving existing ones
|
|
func setPgClusterAnnotations(un *unstructured.Unstructured) error {
|
|
// Get existing annotations or create an empty map
|
|
existingAnnotations, _, _ := unstructured.NestedStringMap(un.Object, "metadata", "annotations")
|
|
if existingAnnotations == nil {
|
|
existingAnnotations = make(map[string]string)
|
|
}
|
|
|
|
// Update only the specific keys
|
|
existingAnnotations["cnpg.io/reloadedAt"] = "0001-01-01T00:00:00Z"
|
|
existingAnnotations["kubectl.kubernetes.io/restartedAt"] = "0001-01-01T00:00:00Z"
|
|
|
|
// Set the updated annotations back
|
|
return unstructured.SetNestedStringMap(un.Object, existingAnnotations, "metadata", "annotations")
|
|
}
|
|
|
|
func (t testNormalizer) normalizeJob(un *unstructured.Unstructured) error {
|
|
if conditions, exist, err := unstructured.NestedSlice(un.Object, "status", "conditions"); err != nil {
|
|
return fmt.Errorf("failed to normalize %s: %w", un.GetKind(), err)
|
|
} else if exist {
|
|
changed := false
|
|
for i := range conditions {
|
|
condition := conditions[i].(map[string]any)
|
|
cType := condition["type"].(string)
|
|
if cType == "FailureTarget" {
|
|
condition["lastTransitionTime"] = "0001-01-01T00:00:00Z"
|
|
changed = true
|
|
}
|
|
}
|
|
if changed {
|
|
if err := unstructured.SetNestedSlice(un.Object, conditions, "status", "conditions"); err != nil {
|
|
return fmt.Errorf("failed to normalize %s: %w", un.GetKind(), err)
|
|
}
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
type ActionTestStructure struct {
|
|
DiscoveryTests []IndividualDiscoveryTest `yaml:"discoveryTests"`
|
|
ActionTests []IndividualActionTest `yaml:"actionTests"`
|
|
}
|
|
|
|
type IndividualDiscoveryTest struct {
|
|
InputPath string `yaml:"inputPath"`
|
|
Result []appsv1.ResourceAction `yaml:"result"`
|
|
}
|
|
|
|
type IndividualActionTest struct {
|
|
Action string `yaml:"action"`
|
|
InputPath string `yaml:"inputPath"`
|
|
ExpectedOutputPath string `yaml:"expectedOutputPath"`
|
|
ExpectedErrorMessage string `yaml:"expectedErrorMessage"`
|
|
InputStr string `yaml:"input"`
|
|
Parameters map[string]string `yaml:"parameters"`
|
|
}
|
|
|
|
func TestLuaResourceActionsScript(t *testing.T) {
|
|
err := filepath.Walk("../../resource_customizations", func(path string, _ os.FileInfo, err error) error {
|
|
if !strings.Contains(path, "action_test.yaml") {
|
|
return nil
|
|
}
|
|
require.NoError(t, err)
|
|
dir := filepath.Dir(path)
|
|
yamlBytes, err := os.ReadFile(filepath.Join(dir, "action_test.yaml"))
|
|
require.NoError(t, err)
|
|
var resourceTest ActionTestStructure
|
|
err = yaml.Unmarshal(yamlBytes, &resourceTest)
|
|
require.NoError(t, err)
|
|
for i := range resourceTest.DiscoveryTests {
|
|
test := resourceTest.DiscoveryTests[i]
|
|
testName := "discovery/" + test.InputPath
|
|
t.Run(testName, func(t *testing.T) {
|
|
vm := VM{
|
|
UseOpenLibs: true,
|
|
}
|
|
obj := getObj(t, filepath.Join(dir, test.InputPath))
|
|
discoveryLua, err := vm.GetResourceActionDiscovery(obj)
|
|
require.NoError(t, err)
|
|
result, err := vm.ExecuteResourceActionDiscovery(obj, discoveryLua)
|
|
require.NoError(t, err)
|
|
for i := range result {
|
|
assert.Contains(t, test.Result, result[i])
|
|
}
|
|
})
|
|
}
|
|
for i := range resourceTest.ActionTests {
|
|
test := resourceTest.ActionTests[i]
|
|
testName := fmt.Sprintf("actions/%s/%s", test.Action, test.InputPath)
|
|
|
|
t.Run(testName, func(t *testing.T) {
|
|
vm := VM{
|
|
// Uncomment the following line if you need to use lua libraries debugging
|
|
// purposes. Otherwise, leave this false to ensure tests reflect the same
|
|
// privileges that API server has.
|
|
// UseOpenLibs: true,
|
|
}
|
|
sourceObj := getObj(t, filepath.Join(dir, test.InputPath))
|
|
action, err := vm.GetResourceAction(sourceObj, test.Action)
|
|
|
|
require.NoError(t, err)
|
|
|
|
// Log the action Lua script
|
|
t.Logf("Action Lua script: %s", action.ActionLua)
|
|
|
|
// Parse action parameters
|
|
var params []*applicationpkg.ResourceActionParameters
|
|
if test.Parameters != nil {
|
|
for k, v := range test.Parameters {
|
|
params = append(params, &applicationpkg.ResourceActionParameters{
|
|
Name: &k,
|
|
Value: &v,
|
|
})
|
|
}
|
|
}
|
|
|
|
if len(params) > 0 {
|
|
// Log the parameters
|
|
t.Logf("Parameters: %+v", params)
|
|
}
|
|
|
|
require.NoError(t, err)
|
|
impactedResources, err := vm.ExecuteResourceAction(sourceObj, action.ActionLua, params)
|
|
|
|
// Handle expected errors
|
|
if test.ExpectedErrorMessage != "" {
|
|
assert.EqualError(t, err, test.ExpectedErrorMessage)
|
|
return
|
|
}
|
|
|
|
require.NoError(t, err)
|
|
|
|
// Treat the Lua expected output as a list
|
|
expectedObjects := getExpectedObjectList(t, filepath.Join(dir, test.ExpectedOutputPath))
|
|
|
|
for _, impactedResource := range impactedResources {
|
|
result := impactedResource.UnstructuredObj
|
|
|
|
// The expected output is a list of objects
|
|
// Find the actual impacted resource in the expected output
|
|
expectedObj := findFirstMatchingItem(expectedObjects.Items, func(u unstructured.Unstructured) bool {
|
|
// Some resources' name is derived from the source object name, so the returned name is not actually equal to the testdata output name
|
|
// Considering the resource found in the testdata output if its name starts with source object name
|
|
// TODO: maybe this should use a normalizer function instead of hard-coding the resource specifics here
|
|
if (result.GetKind() == "Job" && sourceObj.GetKind() == "CronJob") || (result.GetKind() == "Workflow" && (sourceObj.GetKind() == "CronWorkflow" || sourceObj.GetKind() == "WorkflowTemplate")) {
|
|
return u.GroupVersionKind() == result.GroupVersionKind() && strings.HasPrefix(u.GetName(), sourceObj.GetName()) && u.GetNamespace() == result.GetNamespace()
|
|
}
|
|
return u.GroupVersionKind() == result.GroupVersionKind() && u.GetName() == result.GetName() && u.GetNamespace() == result.GetNamespace()
|
|
})
|
|
|
|
assert.NotNil(t, expectedObj)
|
|
|
|
switch impactedResource.K8SOperation {
|
|
// No default case since a not supported operation would have failed upon unmarshaling earlier
|
|
case PatchOperation:
|
|
// Patching is only allowed for the source resource, so the GVK + name + ns must be the same as the impacted resource
|
|
assert.Equal(t, sourceObj.GroupVersionKind(), result.GroupVersionKind())
|
|
assert.Equal(t, sourceObj.GetName(), result.GetName())
|
|
assert.Equal(t, sourceObj.GetNamespace(), result.GetNamespace())
|
|
case CreateOperation:
|
|
switch result.GetKind() {
|
|
case "Job", "Workflow":
|
|
// The name of the created resource is derived from the source object name, so the returned name is not actually equal to the testdata output name
|
|
result.SetName(expectedObj.GetName())
|
|
}
|
|
}
|
|
|
|
// Ideally, we would use assert.Equal to detect the difference, but the Lua VM returns an object with float64 instead of the original int32.
|
|
// As a result, assert.Equal is never true despite that the change has been applied.
|
|
diffResult, err := diff.Diff(t.Context(), expectedObj, result, diff.WithNormalizer(testNormalizer{}))
|
|
require.NoError(t, err)
|
|
if diffResult.Modified {
|
|
t.Error("Output does not match input:")
|
|
err = cli.PrintDiff(test.Action, expectedObj, result)
|
|
require.NoError(t, err)
|
|
}
|
|
}
|
|
})
|
|
}
|
|
|
|
return nil
|
|
})
|
|
require.NoError(t, err)
|
|
}
|
|
|
|
// Handling backward compatibility.
|
|
// The old-style actions return a single object in the expected output from testdata, so will wrap them in a list
|
|
func getExpectedObjectList(t *testing.T, path string) *unstructured.UnstructuredList {
|
|
t.Helper()
|
|
yamlBytes, err := os.ReadFile(path)
|
|
require.NoError(t, err)
|
|
unstructuredList := &unstructured.UnstructuredList{}
|
|
yamlString := bytes.NewBuffer(yamlBytes).String()
|
|
if yamlString[0] == '-' {
|
|
// The string represents a new-style action array output, where each member is a wrapper around a k8s unstructured resource
|
|
objList := make([]map[string]any, 5)
|
|
err = yaml.Unmarshal(yamlBytes, &objList)
|
|
require.NoError(t, err)
|
|
unstructuredList.Items = make([]unstructured.Unstructured, len(objList))
|
|
// Append each map in objList to the Items field of the new object
|
|
for i, obj := range objList {
|
|
unstructuredObj, ok := obj["unstructuredObj"].(map[string]any)
|
|
assert.True(t, ok, "Wrong type of unstructuredObj")
|
|
unstructuredList.Items[i] = unstructured.Unstructured{Object: unstructuredObj}
|
|
}
|
|
} else {
|
|
// The string represents an old-style action object output, which is a k8s unstructured resource
|
|
obj := make(map[string]any)
|
|
err = yaml.Unmarshal(yamlBytes, &obj)
|
|
require.NoError(t, err)
|
|
unstructuredList.Items = make([]unstructured.Unstructured, 1)
|
|
unstructuredList.Items[0] = unstructured.Unstructured{Object: obj}
|
|
}
|
|
return unstructuredList
|
|
}
|
|
|
|
func findFirstMatchingItem(items []unstructured.Unstructured, f func(unstructured.Unstructured) bool) *unstructured.Unstructured {
|
|
var matching *unstructured.Unstructured
|
|
for _, item := range items {
|
|
if f(item) {
|
|
matching = &item
|
|
break
|
|
}
|
|
}
|
|
return matching
|
|
}
|