Skip to content
Open
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
13 changes: 8 additions & 5 deletions .github/workflows/api-compat.yml
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,14 @@ on:
paths:
- 'cmd/thv-operator/api/**'
# files/crds is the source of truth — controller-gen emits here, and
# helm-crd-wrapper copies from here into templates/. Any drift in
# templates/ is caught by operator-ci.yml's generate-crds job, so
# watching templates/ would be redundant. values.yaml and the
# helm-crd-wrapper only affect Helm conditionals and annotations the
# checker ignores, so they can't change what we compare.
# templates/ is generated from it (crd-strip-descriptions removes
# descriptions from deprecated versions other than the preferred version,
# then helm-crd-wrapper wraps the result). Any drift in templates/ is
# caught by operator-ci.yml's generate-crds job, so watching templates/
# would be redundant.
# values.yaml, the description stripping and helm-crd-wrapper only
# affect descriptions, Helm conditionals and annotations, none of
# which change the API surface we compare.
- 'deploy/charts/operator-crds/files/crds/**'
# Self-exercise when either workflow file (real or no-op companion)
# changes. The companion file reports the same required check on
Expand Down
4 changes: 4 additions & 0 deletions .github/workflows/helm-charts-test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,10 @@ jobs:
exit 1
fi

- name: Check operator-crds release size
# Helm stores a release in a Secret limited to 1 MiB; fails above 90%.
run: deploy/charts/operator-crds/hack/check-release-size.sh

- name: Run chart-testing (lint)
run: ct lint --config ct.yaml

Expand Down
14 changes: 12 additions & 2 deletions cmd/thv-operator/Taskfile.yml
Original file line number Diff line number Diff line change
Expand Up @@ -198,9 +198,19 @@ tasks:
- go install sigs.k8s.io/controller-tools/cmd/controller-gen@v0.17.3
- $(go env GOPATH)/bin/controller-gen rbac:roleName=toolhive-operator-manager-role paths="{{.CONTROLLER_GEN_PATHS}}" output:rbac:artifacts:config={{.PROJECT_ROOT}}/deploy/charts/operator/templates/clusterrole
- $(go env GOPATH)/bin/controller-gen crd webhook paths="{{.CONTROLLER_GEN_PATHS}}" output:crd:artifacts:config={{.PROJECT_ROOT}}/deploy/charts/operator-crds/files/crds
# Wrap CRDs with Helm templates for conditional installation.
# Wrap CRDs with Helm templates for conditional installation. files/crds
# keeps the full descriptions (release tarball, api-compat). The chart
# templates are built from a copy with descriptions removed from the
# deprecated versions other than the preferred version, to keep the Helm
# release under the 1 MiB Secret limit (see
# cmd/thv-operator/crd-strip-descriptions).
- go install github.com/stacklok/helm-crd-wrapper@v0.0.1
- $(go env GOPATH)/bin/helm-crd-wrapper -source {{.PROJECT_ROOT}}/deploy/charts/operator-crds/files/crds -target {{.PROJECT_ROOT}}/deploy/charts/operator-crds/templates
- |
set -e
tmp="$(mktemp -d)"
trap 'rm -rf "$tmp"' EXIT
go run {{.PROJECT_ROOT}}/cmd/thv-operator/crd-strip-descriptions -source {{.PROJECT_ROOT}}/deploy/charts/operator-crds/files/crds -target "$tmp"
$(go env GOPATH)/bin/helm-crd-wrapper -source "$tmp" -target {{.PROJECT_ROOT}}/deploy/charts/operator-crds/templates

operator-test:
desc: Run tests for the operator
Expand Down
196 changes: 196 additions & 0 deletions cmd/thv-operator/crd-strip-descriptions/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,196 @@
// SPDX-FileCopyrightText: Copyright 2025 Stacklok, Inc.
// SPDX-License-Identifier: Apache-2.0

// Command crd-strip-descriptions copies CRD manifests from a source directory
// to a target directory and removes all schema descriptions from deprecated
// versions other than the preferred version.
//
// Why: Helm stores each release in a Secret limited to 1 MiB, and most CRDs
// serve a deprecated version with a full copy of the preferred version's
// schema. Descriptions are prose that compresses badly, so dropping them from
// the deprecated copies keeps the operator-crds release well below the limit.
//
// The preferred version is the served version with the highest Kubernetes
// version priority (v1 > v1beta1 > v1alpha1). It is the version API discovery
// advertises first and `kubectl explain` shows by default, so it always keeps
// its descriptions, even when the whole kind is deprecated. Storage does not
// matter: during a migration the storage version can be an older, deprecated
// one that users no longer read.
//
// The output is written the way controller-gen v0.17.3 writes CRDs (a "---"
// header, sorted keys, no status, no creationTimestamp), so everything that is
// not a removed description comes out byte-identical to the source file.
//
// The source directory (deploy/charts/operator-crds/files/crds) stays the
// complete source of truth: the release tarball and the API compatibility
// check read it.
package main

import (
"encoding/json"
"flag"
"fmt"
"os"
"path/filepath"

apiextv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
"k8s.io/apimachinery/pkg/version"
sigsyaml "sigs.k8s.io/yaml"
)

func main() {
source := flag.String("source", "", "directory with the full CRD manifests")
target := flag.String("target", "", "directory to write the processed manifests to")
strip := flag.Bool("strip", true, "strip descriptions from deprecated non-preferred versions; false only re-serializes")
flag.Parse()

if *source == "" || *target == "" {
fmt.Fprintln(os.Stderr, "usage: crd-strip-descriptions -source DIR -target DIR [-strip=false]")
os.Exit(2)
}
if err := run(*source, *target, *strip); err != nil {
fmt.Fprintln(os.Stderr, "error:", err)
os.Exit(1)
}
}

func run(source, target string, strip bool) error {
files, err := filepath.Glob(filepath.Join(source, "*.yaml"))
if err != nil {
return err
}
if len(files) == 0 {
return fmt.Errorf("no *.yaml files in %s", source)
}
if err := os.MkdirAll(target, 0o750); err != nil {
return err
}
for _, file := range files {
in, err := os.ReadFile(filepath.Clean(file))
if err != nil {
return err
}
out, err := process(in, strip)
if err != nil {
return fmt.Errorf("%s: %w", file, err)
}
if err := os.WriteFile(filepath.Join(target, filepath.Base(file)), out, 0o600); err != nil {
return err
}
}
return nil
}

// process parses one CRD manifest, optionally strips descriptions from the
// schema of its deprecated versions (other than the preferred version), and
// serializes it like controller-gen.
func process(in []byte, strip bool) ([]byte, error) {
var crd apiextv1.CustomResourceDefinition
if err := sigsyaml.UnmarshalStrict(in, &crd); err != nil {
return nil, fmt.Errorf("parsing CRD: %w", err)
}
if strip {
stripDeprecated(&crd)
}
return marshalLikeControllerGen(&crd)
}

// stripDeprecated clears the descriptions in the schema of every deprecated
// version except the preferred one. When a whole kind is deprecated (for
// example MCPRegistry), the preferred version is still the one users read, so
// it keeps its docs. Working on the typed schema means a property named
// "description" is a map key and is never confused with a description string.
func stripDeprecated(crd *apiextv1.CustomResourceDefinition) {
preferred := preferredVersion(crd)
for i := range crd.Spec.Versions {
v := &crd.Spec.Versions[i]
if !v.Deprecated || v.Name == preferred || v.Schema == nil {
continue
}
stripSchema(v.Schema.OpenAPIV3Schema)
}
}

// preferredVersion returns the served version with the highest Kubernetes
// version priority, which is what API discovery and `kubectl explain` use by
// default. It returns "" when no version is served.
func preferredVersion(crd *apiextv1.CustomResourceDefinition) string {
preferred := ""
for _, v := range crd.Spec.Versions {
if !v.Served {
continue
}
if preferred == "" || version.CompareKubeAwareVersionStrings(v.Name, preferred) > 0 {
preferred = v.Name
}
}
return preferred
}

func stripSchema(s *apiextv1.JSONSchemaProps) {
if s == nil {
return
}
s.Description = ""
for k, p := range s.Properties {
stripSchema(&p)
s.Properties[k] = p
}
for k, p := range s.PatternProperties {
stripSchema(&p)
s.PatternProperties[k] = p
}
for k, p := range s.Definitions {
stripSchema(&p)
s.Definitions[k] = p
}
for k, d := range s.Dependencies {
stripSchema(d.Schema)
s.Dependencies[k] = d
}
if s.Items != nil {
stripSchema(s.Items.Schema)
stripList(s.Items.JSONSchemas)
}
if s.AdditionalProperties != nil {
stripSchema(s.AdditionalProperties.Schema)
}
if s.AdditionalItems != nil {
stripSchema(s.AdditionalItems.Schema)
}
stripList(s.AllOf)
stripList(s.AnyOf)
stripList(s.OneOf)
stripSchema(s.Not)
}

func stripList(list []apiextv1.JSONSchemaProps) {
for i := range list {
stripSchema(&list[i])
}
}

// marshalLikeControllerGen mirrors controller-gen v0.17.3: JSON-marshal the
// object, load it into a generic map, drop status and
// metadata.creationTimestamp, and marshal to YAML after a "---" line.
// sigs.k8s.io/yaml uses the same yaml v2 encoder as controller-gen, so the
// layout (sorted keys, unindented sequences) is identical.
func marshalLikeControllerGen(crd *apiextv1.CustomResourceDefinition) ([]byte, error) {
j, err := json.Marshal(crd)
if err != nil {
return nil, err
}
var obj map[string]interface{}
if err := sigsyaml.Unmarshal(j, &obj); err != nil {
return nil, err
}
delete(obj, "status")
if md, ok := obj["metadata"].(map[string]interface{}); ok {
delete(md, "creationTimestamp")
}
body, err := sigsyaml.Marshal(obj)
if err != nil {
return nil, err
}
return append([]byte("---\n"), body...), nil
}
Loading
Loading