diff --git a/Dockerfile b/Dockerfile index 53b53371d..74ecdc021 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,4 +1,4 @@ -ARG GO_VERSION=1.25.7 +ARG GO_VERSION=1.25.9 FROM registry.access.redhat.com/ubi9/go-toolset:${GO_VERSION} AS builder ARG GOARCH=amd64 diff --git a/go.mod b/go.mod index ad69c7a62..8bd7859b5 100644 --- a/go.mod +++ b/go.mod @@ -1,11 +1,11 @@ module github.com/hybrid-cloud-patterns/patterns-operator -go 1.25.5 +go 1.25.9 require ( code.gitea.io/sdk/gitea v0.23.2 github.com/Masterminds/semver/v3 v3.5.0 - github.com/argoproj-labs/argocd-operator v0.17.0 + github.com/argoproj-labs/argocd-operator v0.18.0 github.com/bradleyfalzon/ghinstallation/v2 v2.18.0 github.com/go-errors/errors v1.5.1 github.com/go-git/go-git/v5 v5.19.1 @@ -25,13 +25,14 @@ require ( k8s.io/api v0.35.1 k8s.io/apimachinery v0.36.0-alpha.1 k8s.io/client-go v12.0.0+incompatible - sigs.k8s.io/controller-runtime v0.21.0 + sigs.k8s.io/controller-runtime v0.22.3 ) require ( github.com/argoproj/argo-cd/v3 v3.3.10 sigs.k8s.io/controller-runtime/tools/setup-envtest v0.0.0-20250308055145-5fe7bb3edc86 sigs.k8s.io/controller-tools v0.16.4 + sigs.k8s.io/yaml v1.6.0 ) require ( @@ -50,12 +51,12 @@ require ( github.com/Masterminds/sprig/v3 v3.3.0 // indirect github.com/Microsoft/go-winio v0.6.2 // indirect github.com/ProtonMail/go-crypto v1.1.6 // indirect - github.com/argoproj/gitops-engine v0.7.1-0.20250908182407-97ad5b59a627 // indirect + github.com/argoproj/gitops-engine v0.7.1-0.20251217140045-5baed5604d2d // indirect github.com/argoproj/pkg v0.13.7-0.20250305113207-cbc37dc61de5 // indirect github.com/argoproj/pkg/v2 v2.0.1 // indirect github.com/beorn7/perks v1.0.1 // indirect github.com/blang/semver/v4 v4.0.0 // indirect - github.com/bmatcuk/doublestar/v4 v4.9.1 // indirect + github.com/bmatcuk/doublestar/v4 v4.10.0 // indirect github.com/bmizerany/assert v0.0.0-20160611221934-b7ed37b82869 // indirect github.com/bombsimon/logrusr/v4 v4.1.0 // indirect github.com/casbin/casbin/v2 v2.135.0 // indirect @@ -155,7 +156,7 @@ require ( github.com/russross/blackfriday/v2 v2.1.0 // indirect github.com/santhosh-tekuri/jsonschema/v6 v6.0.2 // indirect github.com/segmentio/backo-go v1.0.0 // indirect - github.com/sergi/go-diff v1.3.2-0.20230802210424-5b0b94c5c0d3 // indirect + github.com/sergi/go-diff v1.4.0 // indirect github.com/shopspring/decimal v1.4.0 // indirect github.com/sirupsen/logrus v1.9.4 // indirect github.com/skeema/knownhosts v1.3.2 // indirect @@ -172,7 +173,7 @@ require ( go.opentelemetry.io/otel v1.43.0 // indirect go.opentelemetry.io/otel/trace v1.43.0 // indirect go.uber.org/multierr v1.11.0 // indirect - go.uber.org/zap v1.27.0 // indirect + go.uber.org/zap v1.27.1 // indirect go.yaml.in/yaml/v2 v2.4.4 // indirect go.yaml.in/yaml/v3 v3.0.4 // indirect golang.org/x/mod v0.35.0 // indirect @@ -206,11 +207,10 @@ require ( k8s.io/utils v0.0.0-20251002143259-bc988d571ff4 // indirect oras.land/oras-go/v2 v2.6.0 // indirect sigs.k8s.io/json v0.0.0-20250730193827-2d320260d730 // indirect - sigs.k8s.io/kustomize/api v0.20.1 // indirect - sigs.k8s.io/kustomize/kyaml v0.20.1 // indirect + sigs.k8s.io/kustomize/api v0.21.0 // indirect + sigs.k8s.io/kustomize/kyaml v0.21.0 // indirect sigs.k8s.io/randfill v1.0.0 // indirect sigs.k8s.io/structured-merge-diff/v6 v6.3.1-0.20251003215857-446d8398e19c // indirect - sigs.k8s.io/yaml v1.6.0 // indirect ) replace ( diff --git a/go.sum b/go.sum index baf24bfae..167c5065f 100644 --- a/go.sum +++ b/go.sum @@ -43,12 +43,12 @@ github.com/alicebob/miniredis/v2 v2.35.0 h1:QwLphYqCEAo1eu1TqPRN2jgVMPBweeQcR21j github.com/alicebob/miniredis/v2 v2.35.0/go.mod h1:TcL7YfarKPGDAthEtl5NBeHZfeUQj6OXMm/+iu5cLMM= github.com/anmitsu/go-shlex v0.0.0-20200514113438-38f4b401e2be h1:9AeTilPcZAjCFIImctFaOjnTIavg87rW78vTPkQqLI8= github.com/anmitsu/go-shlex v0.0.0-20200514113438-38f4b401e2be/go.mod h1:ySMOLuWl6zY27l47sB3qLNK6tF2fkHG55UZxx8oIVo4= -github.com/argoproj-labs/argocd-operator v0.17.0 h1:hsCjIT8F6bZhrzq3hHNjQxv7fesTh5TAWMgBsPjHFYQ= -github.com/argoproj-labs/argocd-operator v0.17.0/go.mod h1:NQ382HBjCxWnDAvg/4nn2SXZ+RHPFhH96rglup3Wi6Y= +github.com/argoproj-labs/argocd-operator v0.18.0 h1:ukU1K4DnyAyPbD9UHCZQRziTy/ZjazAJ5pzfcQrA4/o= +github.com/argoproj-labs/argocd-operator v0.18.0/go.mod h1:AlQPFgHsfi3ibtAuRvV2Gxn8rkFe9eunqzBb8AMS2nk= github.com/argoproj/argo-cd/v3 v3.3.10 h1:3QE36lhN/0ntjwl2TH13xL23w2J2AaXgC0Dxn0469h4= github.com/argoproj/argo-cd/v3 v3.3.10/go.mod h1:LdPjAnIFbx0khaB6vLsOKrGoSWeJ8kzOt//jF1ltCPg= -github.com/argoproj/gitops-engine v0.7.1-0.20250908182407-97ad5b59a627 h1:yntvA+uaFz62HRfWGGwlvs4ErdxoLQjCpDXufdEt2FI= -github.com/argoproj/gitops-engine v0.7.1-0.20250908182407-97ad5b59a627/go.mod h1:yJ3t/GRn9Gx2LEyMrh9X0roL7zzVlk3nvuJt6G1o6jI= +github.com/argoproj/gitops-engine v0.7.1-0.20251217140045-5baed5604d2d h1:iUJYrbSvpV9n8vyl1sBt1GceM60HhHfnHxuzcm5apDg= +github.com/argoproj/gitops-engine v0.7.1-0.20251217140045-5baed5604d2d/go.mod h1:PauXVUVcfiTgC+34lDdWzPS101g4NpsUtDAjFBnWf94= github.com/argoproj/pkg v0.13.7-0.20250305113207-cbc37dc61de5 h1:YBoLSjpoaJXaXAldVvBRKJuOPvIXz9UOv6S96gMJM/Q= github.com/argoproj/pkg v0.13.7-0.20250305113207-cbc37dc61de5/go.mod h1:ebVOzFJphdN1p6EG2mIMECv/3Rk/almSaxIYuFAmsSw= github.com/argoproj/pkg/v2 v2.0.1 h1:O/gCETzB/3+/hyFL/7d/VM/6pSOIRWIiBOTb2xqAHvc= @@ -60,8 +60,8 @@ github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6r github.com/blang/semver/v4 v4.0.0 h1:1PFHFE6yCCTv8C1TeyNNarDzntLi7wMI5i/pzqYIsAM= github.com/blang/semver/v4 v4.0.0/go.mod h1:IbckMUScFkM3pff0VJDNKRiT6TG/YpiHIM2yvyW5YoQ= github.com/bmatcuk/doublestar/v4 v4.6.1/go.mod h1:xBQ8jztBU6kakFMg+8WGxn0c6z1fTSPVIjEY1Wr7jzc= -github.com/bmatcuk/doublestar/v4 v4.9.1 h1:X8jg9rRZmJd4yRy7ZeNDRnM+T3ZfHv15JiBJ/avrEXE= -github.com/bmatcuk/doublestar/v4 v4.9.1/go.mod h1:xBQ8jztBU6kakFMg+8WGxn0c6z1fTSPVIjEY1Wr7jzc= +github.com/bmatcuk/doublestar/v4 v4.10.0 h1:zU9WiOla1YA122oLM6i4EXvGW62DvKZVxIe6TYWexEs= +github.com/bmatcuk/doublestar/v4 v4.10.0/go.mod h1:xBQ8jztBU6kakFMg+8WGxn0c6z1fTSPVIjEY1Wr7jzc= github.com/bmizerany/assert v0.0.0-20160611221934-b7ed37b82869 h1:DDGfHa7BWjL4YnC6+E63dPcxHo2sUxDIu8g3QgEJdRY= github.com/bmizerany/assert v0.0.0-20160611221934-b7ed37b82869/go.mod h1:Ekp36dRnpXw/yCqJaO+ZrUyxD+3VXMFFr56k5XYrpB4= github.com/bombsimon/logrusr/v4 v4.1.0 h1:uZNPbwusB0eUXlO8hIUwStE6Lr5bLN6IgYgG+75kuh4= @@ -426,8 +426,8 @@ github.com/segmentio/analytics-go/v3 v3.3.0 h1:8VOMaVGBW03pdBrj1CMFfY9o/rnjJC+1w github.com/segmentio/analytics-go/v3 v3.3.0/go.mod h1:p8owAF8X+5o27jmvUognuXxdtqvSGtD0ZrfY2kcS9bE= github.com/segmentio/backo-go v1.0.0 h1:kbOAtGJY2DqOR0jfRkYEorx/b18RgtepGtY3+Cpe6qA= github.com/segmentio/backo-go v1.0.0/go.mod h1:kJ9mm9YmoWSkk+oQ+5Cj8DEoRCX2JT6As4kEtIIOp1M= -github.com/sergi/go-diff v1.3.2-0.20230802210424-5b0b94c5c0d3 h1:n661drycOFuPLCN3Uc8sB6B/s6Z4t2xvBgU1htSHuq8= -github.com/sergi/go-diff v1.3.2-0.20230802210424-5b0b94c5c0d3/go.mod h1:A0bzQcvG0E7Rwjx0REVgAGH58e96+X0MeOfepqsbeW4= +github.com/sergi/go-diff v1.4.0 h1:n/SP9D5ad1fORl+llWyN+D6qoUETXNZARKjyY2/KVCw= +github.com/sergi/go-diff v1.4.0/go.mod h1:A0bzQcvG0E7Rwjx0REVgAGH58e96+X0MeOfepqsbeW4= github.com/shopspring/decimal v1.4.0 h1:bxl37RwXBklmTi0C79JfXCEBD1cqqHt0bbgBAGFp81k= github.com/shopspring/decimal v1.4.0/go.mod h1:gawqmDU56v4yIKSwfBSFip1HdCCXN8/+DMd9qYNcwME= github.com/sirupsen/logrus v1.7.0/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0= @@ -503,8 +503,8 @@ go.uber.org/mock v0.6.0 h1:hyF9dfmbgIX5EfOdasqLsWD6xqpNZlXblLB/Dbnwv3Y= go.uber.org/mock v0.6.0/go.mod h1:KiVJ4BqZJaMj4svdfmHM0AUx4NJYO8ZNpPnZn1Z+BBU= go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= -go.uber.org/zap v1.27.0 h1:aJMhYGrd5QSmlpLMr2MftRKl7t8J8PTZPA732ud/XR8= -go.uber.org/zap v1.27.0/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E= +go.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc= +go.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E= go.yaml.in/yaml/v2 v2.4.4 h1:tuyd0P+2Ont/d6e2rl3be67goVK4R6deVxCUX5vyPaQ= go.yaml.in/yaml/v2 v2.4.4/go.mod h1:gMZqIpDtDqOfM0uNfy0SkpRhvUryYH0Z6wdMYcacYXQ= go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc= @@ -704,18 +704,18 @@ k8s.io/utils v0.0.0-20251002143259-bc988d571ff4 h1:SjGebBtkBqHFOli+05xYbK8YF1Dzk k8s.io/utils v0.0.0-20251002143259-bc988d571ff4/go.mod h1:OLgZIPagt7ERELqWJFomSt595RzquPNLL48iOWgYOg0= oras.land/oras-go/v2 v2.6.0 h1:X4ELRsiGkrbeox69+9tzTu492FMUu7zJQW6eJU+I2oc= oras.land/oras-go/v2 v2.6.0/go.mod h1:magiQDfG6H1O9APp+rOsvCPcW1GD2MM7vgnKY0Y+u1o= -sigs.k8s.io/controller-runtime v0.21.0 h1:CYfjpEuicjUecRk+KAeyYh+ouUBn4llGyDYytIGcJS8= -sigs.k8s.io/controller-runtime v0.21.0/go.mod h1:OSg14+F65eWqIu4DceX7k/+QRAbTTvxeQSNSOQpukWM= +sigs.k8s.io/controller-runtime v0.22.3 h1:I7mfqz/a/WdmDCEnXmSPm8/b/yRTy6JsKKENTijTq8Y= +sigs.k8s.io/controller-runtime v0.22.3/go.mod h1:+QX1XUpTXN4mLoblf4tqr5CQcyHPAki2HLXqQMY6vh8= sigs.k8s.io/controller-runtime/tools/setup-envtest v0.0.0-20250308055145-5fe7bb3edc86 h1:96TA+X7D58V3065duUfj+p+Pp17q8U02+cSCmE3IsaU= sigs.k8s.io/controller-runtime/tools/setup-envtest v0.0.0-20250308055145-5fe7bb3edc86/go.mod h1:IaDsO8xSPRxRG1/rm9CP7+jPmj0nMNAuNi/yiHnLX8k= sigs.k8s.io/controller-tools v0.16.4 h1:VXmar78eDXbx1by/H09ikEq1hiq3bqInxuV3lMr3GmQ= sigs.k8s.io/controller-tools v0.16.4/go.mod h1:kcsZyYMXiOFuBhofSPtkB90zTSxVRxVVyvtKQcx3q1A= sigs.k8s.io/json v0.0.0-20250730193827-2d320260d730 h1:IpInykpT6ceI+QxKBbEflcR5EXP7sU1kvOlxwZh5txg= sigs.k8s.io/json v0.0.0-20250730193827-2d320260d730/go.mod h1:mdzfpAEoE6DHQEN0uh9ZbOCuHbLK5wOm7dK4ctXE9Tg= -sigs.k8s.io/kustomize/api v0.20.1 h1:iWP1Ydh3/lmldBnH/S5RXgT98vWYMaTUL1ADcr+Sv7I= -sigs.k8s.io/kustomize/api v0.20.1/go.mod h1:t6hUFxO+Ph0VxIk1sKp1WS0dOjbPCtLJ4p8aADLwqjM= -sigs.k8s.io/kustomize/kyaml v0.20.1 h1:PCMnA2mrVbRP3NIB6v9kYCAc38uvFLVs8j/CD567A78= -sigs.k8s.io/kustomize/kyaml v0.20.1/go.mod h1:0EmkQHRUsJxY8Ug9Niig1pUMSCGHxQ5RklbpV/Ri6po= +sigs.k8s.io/kustomize/api v0.21.0 h1:I7nry5p8iDJbuRdYS7ez8MUvw7XVNPcIP5GkzzuXIIQ= +sigs.k8s.io/kustomize/api v0.21.0/go.mod h1:XGVQuR5n2pXKWbzXHweZU683pALGw/AMVO4zU4iS8SE= +sigs.k8s.io/kustomize/kyaml v0.21.0 h1:7mQAf3dUwf0wBerWJd8rXhVcnkk5Tvn/q91cGkaP6HQ= +sigs.k8s.io/kustomize/kyaml v0.21.0/go.mod h1:hmxADesM3yUN2vbA5z1/YTBnzLJ1dajdqpQonwBL1FQ= sigs.k8s.io/randfill v1.0.0 h1:JfjMILfT8A6RbawdsK2JXGBR5AQVfd+9TbzrlneTyrU= sigs.k8s.io/randfill v1.0.0/go.mod h1:XeLlZ/jmk4i1HRopwe7/aU3H5n1zNUcX6TM94b3QxOY= sigs.k8s.io/structured-merge-diff/v6 v6.3.1-0.20251003215857-446d8398e19c h1:RCkxmWwPjOw2O1RiDgBgI6tfISvB07jAh+GEztp7TWk= diff --git a/vendor/github.com/argoproj-labs/argocd-operator/api/v1beta1/argocd_types.go b/vendor/github.com/argoproj-labs/argocd-operator/api/v1beta1/argocd_types.go index 81e10c2b9..f7592bf2f 100644 --- a/vendor/github.com/argoproj-labs/argocd-operator/api/v1beta1/argocd_types.go +++ b/vendor/github.com/argoproj-labs/argocd-operator/api/v1beta1/argocd_types.go @@ -69,11 +69,11 @@ type ArgoCD struct { // ArgoCDApplicationControllerProcessorsSpec defines the options for the ArgoCD Application Controller processors. type ArgoCDApplicationControllerProcessorsSpec struct { // Operation is the number of application operation processors. - //+operator-sdk:csv:customresourcedefinitions:type=spec,displayName="Operation Processor Count'",xDescriptors={"urn:alm:descriptor:com.tectonic.ui:fieldGroup:Controller","urn:alm:descriptor:com.tectonic.ui:number"} + //+operator-sdk:csv:customresourcedefinitions:type=spec,displayName="Operation Processor Count",xDescriptors={"urn:alm:descriptor:com.tectonic.ui:fieldGroup:Controller","urn:alm:descriptor:com.tectonic.ui:number"} Operation int32 `json:"operation,omitempty"` // Status is the number of application status processors. - //+operator-sdk:csv:customresourcedefinitions:type=spec,displayName="Status Processor Count'",xDescriptors={"urn:alm:descriptor:com.tectonic.ui:fieldGroup:Controller","urn:alm:descriptor:com.tectonic.ui:number"} + //+operator-sdk:csv:customresourcedefinitions:type=spec,displayName="Status Processor Count",xDescriptors={"urn:alm:descriptor:com.tectonic.ui:fieldGroup:Controller","urn:alm:descriptor:com.tectonic.ui:number"} Status int32 `json:"status,omitempty"` } @@ -93,7 +93,7 @@ type ArgoCDApplicationControllerSpec struct { LogFormat string `json:"logFormat,omitempty"` // Resources defines the Compute Resources required by the container for the Application Controller. - //+operator-sdk:csv:customresourcedefinitions:type=spec,displayName="Resource Requirements'",xDescriptors={"urn:alm:descriptor:com.tectonic.ui:fieldGroup:Controller","urn:alm:descriptor:com.tectonic.ui:resourceRequirements"} + //+operator-sdk:csv:customresourcedefinitions:type=spec,displayName="Resource Requirements",xDescriptors={"urn:alm:descriptor:com.tectonic.ui:fieldGroup:Controller","urn:alm:descriptor:com.tectonic.ui:resourceRequirements"} Resources *corev1.ResourceRequirements `json:"resources,omitempty"` // ParallelismLimit defines the limit for parallel kubectl operations @@ -255,11 +255,11 @@ type ArgoCDDexSpec struct { Image string `json:"image,omitempty"` // OpenShiftOAuth enables OpenShift OAuth authentication for the Dex server. - //+operator-sdk:csv:customresourcedefinitions:type=spec,displayName="OpenShift OAuth Enabled'",xDescriptors={"urn:alm:descriptor:com.tectonic.ui:fieldGroup:Dex","urn:alm:descriptor:com.tectonic.ui:booleanSwitch"} + //+operator-sdk:csv:customresourcedefinitions:type=spec,displayName="OpenShift OAuth Enabled",xDescriptors={"urn:alm:descriptor:com.tectonic.ui:fieldGroup:Dex","urn:alm:descriptor:com.tectonic.ui:booleanSwitch"} OpenShiftOAuth bool `json:"openShiftOAuth,omitempty"` // Resources defines the Compute Resources required by the container for Dex. - //+operator-sdk:csv:customresourcedefinitions:type=spec,displayName="Resource Requirements'",xDescriptors={"urn:alm:descriptor:com.tectonic.ui:fieldGroup:Dex","urn:alm:descriptor:com.tectonic.ui:resourceRequirements"} + //+operator-sdk:csv:customresourcedefinitions:type=spec,displayName="Resource Requirements",xDescriptors={"urn:alm:descriptor:com.tectonic.ui:fieldGroup:Dex","urn:alm:descriptor:com.tectonic.ui:resourceRequirements"} Resources *corev1.ResourceRequirements `json:"resources,omitempty"` // Version is the Dex container image tag. @@ -294,7 +294,7 @@ type ArgoCDGrafanaSpec struct { Ingress ArgoCDIngressSpec `json:"ingress,omitempty"` // Resources defines the Compute Resources required by the container for Grafana. - //+operator-sdk:csv:customresourcedefinitions:type=spec,displayName="Resource Requirements'",xDescriptors={"urn:alm:descriptor:com.tectonic.ui:fieldGroup:Grafana","urn:alm:descriptor:com.tectonic.ui:resourceRequirements"} + //+operator-sdk:csv:customresourcedefinitions:type=spec,displayName="Resource Requirements",xDescriptors={"urn:alm:descriptor:com.tectonic.ui:fieldGroup:Grafana","urn:alm:descriptor:com.tectonic.ui:resourceRequirements"} Resources *corev1.ResourceRequirements `json:"resources,omitempty"` // Route defines the desired state for an OpenShift Route for the Grafana component. @@ -354,7 +354,7 @@ type ArgoCDIngressSpec struct { Annotations map[string]string `json:"annotations,omitempty"` // Enabled will toggle the creation of the Ingress. - //+operator-sdk:csv:customresourcedefinitions:type=spec,displayName="Ingress Enabled'",xDescriptors={"urn:alm:descriptor:com.tectonic.ui:fieldGroup:Grafana","urn:alm:descriptor:com.tectonic.ui:fieldGroup:Prometheus","urn:alm:descriptor:com.tectonic.ui:fieldGroup:Server","urn:alm:descriptor:com.tectonic.ui:booleanSwitch"} + //+operator-sdk:csv:customresourcedefinitions:type=spec,displayName="Ingress Enabled",xDescriptors={"urn:alm:descriptor:com.tectonic.ui:fieldGroup:Grafana","urn:alm:descriptor:com.tectonic.ui:fieldGroup:Prometheus","urn:alm:descriptor:com.tectonic.ui:fieldGroup:Server","urn:alm:descriptor:com.tectonic.ui:booleanSwitch"} Enabled bool `json:"enabled"` // IngressClassName for the Ingress resource. @@ -437,20 +437,26 @@ type ArgoCDNotifications struct { // ArgoCDPrometheusSpec defines the desired state for the Prometheus component. type ArgoCDPrometheusSpec struct { // Enabled will toggle Prometheus support globally for ArgoCD. + // When set to true, ServiceMonitors and PrometheusRules will be created for Argo CD metrics. + // The Prometheus CR, Route, and Ingress are deprecated and will no longer be created. //+operator-sdk:csv:customresourcedefinitions:type=spec,displayName="Enabled",xDescriptors={"urn:alm:descriptor:com.tectonic.ui:fieldGroup:Prometheus","urn:alm:descriptor:com.tectonic.ui:booleanSwitch"} Enabled bool `json:"enabled"` // Host is the hostname to use for Ingress/Route resources. + // Deprecated: This field is no longer used and will be ignored. //+operator-sdk:csv:customresourcedefinitions:type=spec,displayName="Host",xDescriptors={"urn:alm:descriptor:com.tectonic.ui:fieldGroup:Prometheus","urn:alm:descriptor:com.tectonic.ui:text"} Host string `json:"host,omitempty"` // Ingress defines the desired state for an Ingress for the Prometheus component. + // Deprecated: This field is no longer used and will be ignored. Ingress ArgoCDIngressSpec `json:"ingress,omitempty"` // Route defines the desired state for an OpenShift Route for the Prometheus component. + // Deprecated: This field is no longer used and will be ignored. Route ArgoCDRouteSpec `json:"route,omitempty"` // Size is the replica count for the Prometheus StatefulSet. + // Deprecated: This field is no longer used and will be ignored. //+operator-sdk:csv:customresourcedefinitions:type=spec,displayName="Size",xDescriptors={"urn:alm:descriptor:com.tectonic.ui:fieldGroup:Prometheus","urn:alm:descriptor:com.tectonic.ui:podCount"} Size *int32 `json:"size,omitempty"` } @@ -460,7 +466,7 @@ type ArgoCDRBACSpec struct { // DefaultPolicy is the name of the default role which Argo CD will falls back to, when // authorizing API requests (optional). If omitted or empty, users may be still be able to login, // but will see no apps, projects, etc... - //+operator-sdk:csv:customresourcedefinitions:type=spec,displayName="Default Policy'",xDescriptors={"urn:alm:descriptor:com.tectonic.ui:fieldGroup:RBAC","urn:alm:descriptor:com.tectonic.ui:text"} + //+operator-sdk:csv:customresourcedefinitions:type=spec,displayName="Default Policy",xDescriptors={"urn:alm:descriptor:com.tectonic.ui:fieldGroup:RBAC","urn:alm:descriptor:com.tectonic.ui:text"} DefaultPolicy *string `json:"defaultPolicy,omitempty"` // Policy is CSV containing user-defined RBAC policies and role definitions. @@ -489,7 +495,7 @@ type ArgoCDRedisSpec struct { Image string `json:"image,omitempty"` // Resources defines the Compute Resources required by the container for Redis. - //+operator-sdk:csv:customresourcedefinitions:type=spec,displayName="Resource Requirements'",xDescriptors={"urn:alm:descriptor:com.tectonic.ui:fieldGroup:Redis","urn:alm:descriptor:com.tectonic.ui:resourceRequirements"} + //+operator-sdk:csv:customresourcedefinitions:type=spec,displayName="Resource Requirements",xDescriptors={"urn:alm:descriptor:com.tectonic.ui:fieldGroup:Redis","urn:alm:descriptor:com.tectonic.ui:resourceRequirements"} Resources *corev1.ResourceRequirements `json:"resources,omitempty"` // Version is the Redis container image tag. @@ -540,7 +546,7 @@ type ArgoCDRepoSpec struct { Replicas *int32 `json:"replicas,omitempty"` // Resources defines the Compute Resources required by the container for Redis. - //+operator-sdk:csv:customresourcedefinitions:type=spec,displayName="Resource Requirements'",xDescriptors={"urn:alm:descriptor:com.tectonic.ui:fieldGroup:Repo","urn:alm:descriptor:com.tectonic.ui:resourceRequirements"} + //+operator-sdk:csv:customresourcedefinitions:type=spec,displayName="Resource Requirements",xDescriptors={"urn:alm:descriptor:com.tectonic.ui:fieldGroup:Repo","urn:alm:descriptor:com.tectonic.ui:resourceRequirements"} Resources *corev1.ResourceRequirements `json:"resources,omitempty"` // ServiceAccount defines the ServiceAccount user that you would like the Repo server to use @@ -591,6 +597,9 @@ type ArgoCDRepoSpec struct { // Custom labels to pods deployed by the operator Labels map[string]string `json:"labels,omitempty"` + + // Custom certificates to inject into the repo server container and its plugins to trust source hosting sites + SystemCATrust *ArgoCDSystemCATrustSpec `json:"systemCATrust,omitempty"` } func (a *ArgoCDRepoSpec) IsEnabled() bool { @@ -601,6 +610,18 @@ func (a *ArgoCDRepoSpec) IsRemote() bool { return a.Remote != nil && *a.Remote != "" } +// ArgoCDSystemCATrustSpec defines custom certificates to inject into the repo server container and its plugins to trust source hosting sites +type ArgoCDSystemCATrustSpec struct { + // DropImageCertificates will remove all certs that are present in the image, leaving only those explicitly configured here. + DropImageCertificates bool `json:"dropImageCertificates,omitempty"` + // ClusterTrustBundles is a list of projected ClusterTrustBundle volume definitions from where to take the trust certs. + ClusterTrustBundles []corev1.ClusterTrustBundleProjection `json:"clusterTrustBundles,omitempty"` + // Secrets is a list of projected Secret volume definitions from where to take the trust certs. + Secrets []corev1.SecretProjection `json:"secrets,omitempty"` + // ConfigMaps is a list of projected ConfigMap volume definitions from where to take the trust certs. + ConfigMaps []corev1.ConfigMapProjection `json:"configMaps,omitempty"` +} + // ArgoCDRouteSpec defines the desired state for an OpenShift Route. type ArgoCDRouteSpec struct { // Annotations is the map of annotations to use for the Route resource. @@ -610,7 +631,7 @@ type ArgoCDRouteSpec struct { Labels map[string]string `json:"labels,omitempty"` // Enabled will toggle the creation of the OpenShift Route. - //+operator-sdk:csv:customresourcedefinitions:type=spec,displayName="Route Enabled'",xDescriptors={"urn:alm:descriptor:com.tectonic.ui:fieldGroup:Grafana","urn:alm:descriptor:com.tectonic.ui:fieldGroup:Prometheus","urn:alm:descriptor:com.tectonic.ui:fieldGroup:Server","urn:alm:descriptor:com.tectonic.ui:booleanSwitch"} + //+operator-sdk:csv:customresourcedefinitions:type=spec,displayName="Route Enabled",xDescriptors={"urn:alm:descriptor:com.tectonic.ui:fieldGroup:Grafana","urn:alm:descriptor:com.tectonic.ui:fieldGroup:Prometheus","urn:alm:descriptor:com.tectonic.ui:fieldGroup:Server","urn:alm:descriptor:com.tectonic.ui:booleanSwitch"} Enabled bool `json:"enabled"` // Path the router watches for, to route traffic for to the service. @@ -626,7 +647,7 @@ type ArgoCDRouteSpec struct { // ArgoCDServerAutoscaleSpec defines the desired state for autoscaling the Argo CD Server component. type ArgoCDServerAutoscaleSpec struct { // Enabled will toggle autoscaling support for the Argo CD Server component. - //+operator-sdk:csv:customresourcedefinitions:type=spec,displayName="Autoscale Enabled'",xDescriptors={"urn:alm:descriptor:com.tectonic.ui:fieldGroup:Server","urn:alm:descriptor:com.tectonic.ui:booleanSwitch"} + //+operator-sdk:csv:customresourcedefinitions:type=spec,displayName="Autoscale Enabled",xDescriptors={"urn:alm:descriptor:com.tectonic.ui:fieldGroup:Server","urn:alm:descriptor:com.tectonic.ui:booleanSwitch"} Enabled bool `json:"enabled"` // HPA defines the HorizontalPodAutoscaler options for the Argo CD Server component. @@ -640,7 +661,7 @@ type ArgoCDServerGRPCSpec struct { Host string `json:"host,omitempty"` // Ingress defines the desired state for the Argo CD Server GRPC Ingress. - //+operator-sdk:csv:customresourcedefinitions:type=spec,displayName="GRPC Ingress Enabled'",xDescriptors={"urn:alm:descriptor:com.tectonic.ui:fieldGroup:Server","urn:alm:descriptor:com.tectonic.ui:booleanSwitch"} + //+operator-sdk:csv:customresourcedefinitions:type=spec,displayName="GRPC Ingress Enabled",xDescriptors={"urn:alm:descriptor:com.tectonic.ui:fieldGroup:Server","urn:alm:descriptor:com.tectonic.ui:booleanSwitch"} Ingress ArgoCDIngressSpec `json:"ingress,omitempty"` } @@ -679,7 +700,7 @@ type ArgoCDServerSpec struct { Replicas *int32 `json:"replicas,omitempty"` // Resources defines the Compute Resources required by the container for the Argo CD server component. - //+operator-sdk:csv:customresourcedefinitions:type=spec,displayName="Resource Requirements'",xDescriptors={"urn:alm:descriptor:com.tectonic.ui:fieldGroup:Server","urn:alm:descriptor:com.tectonic.ui:resourceRequirements"} + //+operator-sdk:csv:customresourcedefinitions:type=spec,displayName="Resource Requirements",xDescriptors={"urn:alm:descriptor:com.tectonic.ui:fieldGroup:Server","urn:alm:descriptor:com.tectonic.ui:resourceRequirements"} Resources *corev1.ResourceRequirements `json:"resources,omitempty"` // Route defines the desired state for an OpenShift Route for the Argo CD Server component. @@ -722,7 +743,7 @@ func (a *ArgoCDServerSpec) IsEnabled() bool { // ArgoCDServerServiceSpec defines the Service options for Argo CD Server component. type ArgoCDServerServiceSpec struct { // Type is the ServiceType to use for the Service resource. - //+operator-sdk:csv:customresourcedefinitions:type=spec,displayName="Service Type'",xDescriptors={"urn:alm:descriptor:com.tectonic.ui:fieldGroup:Server","urn:alm:descriptor:com.tectonic.ui:text"} + //+operator-sdk:csv:customresourcedefinitions:type=spec,displayName="Service Type",xDescriptors={"urn:alm:descriptor:com.tectonic.ui:fieldGroup:Server","urn:alm:descriptor:com.tectonic.ui:text"} Type corev1.ServiceType `json:"type"` } @@ -841,15 +862,28 @@ type ArgoCDNodePlacementSpec struct { Tolerations []corev1.Toleration `json:"tolerations,omitempty"` } +// ArgoCDNetworkPolicySpec defines whether the operator should create NetworkPolicies for an Argo CD instance. +type ArgoCDNetworkPolicySpec struct { + // Enabled defines whether NetworkPolicy resources are created for this Argo CD instance. + // When enabled, the operator will reconcile NetworkPolicies for Argo CD components. + // When disabled, the operator will remove any previously-created NetworkPolicies. + Enabled *bool `json:"enabled,omitempty"` +} + +func (a *ArgoCDNetworkPolicySpec) IsEnabled() bool { + return a == nil || a.Enabled == nil || *a.Enabled +} + // ArgoCDSpec defines the desired state of ArgoCD // +k8s:openapi-gen=true +// +kubebuilder:validation:XValidation:rule="!(has(self.sso) && has(self.oidcConfig))",message="spec.sso and spec.oidcConfig cannot both be set" type ArgoCDSpec struct { // ArgoCDApplicationSet defines whether the Argo CD ApplicationSet controller should be installed. ApplicationSet *ArgoCDApplicationSet `json:"applicationSet,omitempty"` // ApplicationInstanceLabelKey is the key name where Argo CD injects the app name as a tracking label. - //+operator-sdk:csv:customresourcedefinitions:type=spec,displayName="Application Instance Label Key'",xDescriptors={"urn:alm:descriptor:com.tectonic.ui:text","urn:alm:descriptor:com.tectonic.ui:advanced"} + //+operator-sdk:csv:customresourcedefinitions:type=spec,displayName="Application Instance Label Key",xDescriptors={"urn:alm:descriptor:com.tectonic.ui:text","urn:alm:descriptor:com.tectonic.ui:advanced"} ApplicationInstanceLabelKey string `json:"applicationInstanceLabelKey,omitempty"` // InstallationID uniquely identifies an Argo CD instance in multi-instance clusters. @@ -857,7 +891,7 @@ type ArgoCDSpec struct { InstallationID string `json:"installationID,omitempty"` // Deprecated: ConfigManagementPlugins field is no longer supported. Argo CD now requires plugins to be defined as sidecar containers of repo server component. See '.spec.repo.sidecarContainers'. ConfigManagementPlugins was previously used to specify additional config management plugins. - //+operator-sdk:csv:customresourcedefinitions:type=spec,displayName="Config Management Plugins'",xDescriptors={"urn:alm:descriptor:com.tectonic.ui:text","urn:alm:descriptor:com.tectonic.ui:advanced"} + //+operator-sdk:csv:customresourcedefinitions:type=spec,displayName="Config Management Plugins",xDescriptors={"urn:alm:descriptor:com.tectonic.ui:text","urn:alm:descriptor:com.tectonic.ui:advanced"} ConfigManagementPlugins string `json:"configManagementPlugins,omitempty"` // Controller defines the Application Controller options for ArgoCD. @@ -875,11 +909,11 @@ type ArgoCDSpec struct { ExtraConfig map[string]string `json:"extraConfig,omitempty"` // GATrackingID is the google analytics tracking ID to use. - //+operator-sdk:csv:customresourcedefinitions:type=spec,displayName="Google Analytics Tracking ID'",xDescriptors={"urn:alm:descriptor:com.tectonic.ui:text","urn:alm:descriptor:com.tectonic.ui:advanced"} + //+operator-sdk:csv:customresourcedefinitions:type=spec,displayName="Google Analytics Tracking ID",xDescriptors={"urn:alm:descriptor:com.tectonic.ui:text","urn:alm:descriptor:com.tectonic.ui:advanced"} GATrackingID string `json:"gaTrackingID,omitempty"` // GAAnonymizeUsers toggles user IDs being hashed before sending to google analytics. - //+operator-sdk:csv:customresourcedefinitions:type=spec,displayName="Google Analytics Anonymize Users'",xDescriptors={"urn:alm:descriptor:com.tectonic.ui:booleanSwitch","urn:alm:descriptor:com.tectonic.ui:advanced"} + //+operator-sdk:csv:customresourcedefinitions:type=spec,displayName="Google Analytics Anonymize Users",xDescriptors={"urn:alm:descriptor:com.tectonic.ui:booleanSwitch","urn:alm:descriptor:com.tectonic.ui:advanced"} GAAnonymizeUsers bool `json:"gaAnonymizeUsers,omitempty"` // Deprecated: Grafana defines the Grafana server options for ArgoCD. @@ -889,11 +923,11 @@ type ArgoCDSpec struct { HA ArgoCDHASpec `json:"ha,omitempty"` // HelpChatURL is the URL for getting chat help, this will typically be your Slack channel for support. - //+operator-sdk:csv:customresourcedefinitions:type=spec,displayName="Help Chat URL'",xDescriptors={"urn:alm:descriptor:com.tectonic.ui:text","urn:alm:descriptor:com.tectonic.ui:advanced"} + //+operator-sdk:csv:customresourcedefinitions:type=spec,displayName="Help Chat URL",xDescriptors={"urn:alm:descriptor:com.tectonic.ui:text","urn:alm:descriptor:com.tectonic.ui:advanced"} HelpChatURL string `json:"helpChatURL,omitempty"` // HelpChatText is the text for getting chat help, defaults to "Chat now!" - //+operator-sdk:csv:customresourcedefinitions:type=spec,displayName="Help Chat Text'",xDescriptors={"urn:alm:descriptor:com.tectonic.ui:text","urn:alm:descriptor:com.tectonic.ui:advanced"} + //+operator-sdk:csv:customresourcedefinitions:type=spec,displayName="Help Chat Text",xDescriptors={"urn:alm:descriptor:com.tectonic.ui:text","urn:alm:descriptor:com.tectonic.ui:advanced"} HelpChatText string `json:"helpChatText,omitempty"` // Image is the ArgoCD container image for all ArgoCD components. @@ -913,7 +947,7 @@ type ArgoCDSpec struct { Import *ArgoCDImportSpec `json:"import,omitempty"` // Deprecated: InitialRepositories to configure Argo CD with upon creation of the cluster. - //+operator-sdk:csv:customresourcedefinitions:type=spec,displayName="Initial Repositories'",xDescriptors={"urn:alm:descriptor:com.tectonic.ui:text","urn:alm:descriptor:com.tectonic.ui:advanced"} + //+operator-sdk:csv:customresourcedefinitions:type=spec,displayName="Initial Repositories",xDescriptors={"urn:alm:descriptor:com.tectonic.ui:text","urn:alm:descriptor:com.tectonic.ui:advanced"} InitialRepositories string `json:"initialRepositories,omitempty"` // InitialSSHKnownHosts defines the SSH known hosts data upon creation of the cluster for connecting Git repositories via SSH. @@ -923,19 +957,22 @@ type ArgoCDSpec struct { KustomizeBuildOptions string `json:"kustomizeBuildOptions,omitempty"` // KustomizeVersions is a listing of configured versions of Kustomize to be made available within ArgoCD. - //+operator-sdk:csv:customresourcedefinitions:type=spec,displayName="Kustomize Build Options'",xDescriptors={"urn:alm:descriptor:com.tectonic.ui:text","urn:alm:descriptor:com.tectonic.ui:advanced"} + //+operator-sdk:csv:customresourcedefinitions:type=spec,displayName="Kustomize Build Options",xDescriptors={"urn:alm:descriptor:com.tectonic.ui:text","urn:alm:descriptor:com.tectonic.ui:advanced"} KustomizeVersions []KustomizeVersionSpec `json:"kustomizeVersions,omitempty"` // LocalUsers is a listing of local users to be created by the operator for the purpose of issuing ArgoCD API keys. LocalUsers []LocalUserSpec `json:"localUsers,omitempty"` // OIDCConfig is the OIDC configuration as an alternative to dex. - //+operator-sdk:csv:customresourcedefinitions:type=spec,displayName="OIDC Config'",xDescriptors={"urn:alm:descriptor:com.tectonic.ui:text","urn:alm:descriptor:com.tectonic.ui:advanced"} + //+operator-sdk:csv:customresourcedefinitions:type=spec,displayName="OIDC Config",xDescriptors={"urn:alm:descriptor:com.tectonic.ui:text","urn:alm:descriptor:com.tectonic.ui:advanced"} OIDCConfig string `json:"oidcConfig,omitempty"` // Monitoring defines whether workload status monitoring configuration for this instance. Monitoring ArgoCDMonitoringSpec `json:"monitoring,omitempty"` + // NetworkPolicy controls whether the operator should create NetworkPolicy resources for this Argo CD instance. + NetworkPolicy ArgoCDNetworkPolicySpec `json:"networkPolicy,omitempty"` + // NodePlacement defines NodeSelectors and Taints for Argo CD workloads NodePlacement *ArgoCDNodePlacementSpec `json:"nodePlacement,omitempty"` @@ -958,19 +995,19 @@ type ArgoCDSpec struct { RepositoryCredentials string `json:"repositoryCredentials,omitempty"` // ResourceHealthChecks customizes resource health check behavior. - //+operator-sdk:csv:customresourcedefinitions:type=spec,displayName="Resource Health Check Customizations'",xDescriptors={"urn:alm:descriptor:com.tectonic.ui:text","urn:alm:descriptor:com.tectonic.ui:advanced"} + //+operator-sdk:csv:customresourcedefinitions:type=spec,displayName="Resource Health Check Customizations",xDescriptors={"urn:alm:descriptor:com.tectonic.ui:text","urn:alm:descriptor:com.tectonic.ui:advanced"} ResourceHealthChecks []ResourceHealthCheck `json:"resourceHealthChecks,omitempty"` // ResourceIgnoreDifferences customizes resource ignore difference behavior. - //+operator-sdk:csv:customresourcedefinitions:type=spec,displayName="Resource Ignore Difference Customizations'",xDescriptors={"urn:alm:descriptor:com.tectonic.ui:text","urn:alm:descriptor:com.tectonic.ui:advanced"} + //+operator-sdk:csv:customresourcedefinitions:type=spec,displayName="Resource Ignore Difference Customizations",xDescriptors={"urn:alm:descriptor:com.tectonic.ui:text","urn:alm:descriptor:com.tectonic.ui:advanced"} ResourceIgnoreDifferences *ResourceIgnoreDifference `json:"resourceIgnoreDifferences,omitempty"` // ResourceActions customizes resource action behavior. - //+operator-sdk:csv:customresourcedefinitions:type=spec,displayName="Resource Action Customizations'",xDescriptors={"urn:alm:descriptor:com.tectonic.ui:text","urn:alm:descriptor:com.tectonic.ui:advanced"} + //+operator-sdk:csv:customresourcedefinitions:type=spec,displayName="Resource Action Customizations",xDescriptors={"urn:alm:descriptor:com.tectonic.ui:text","urn:alm:descriptor:com.tectonic.ui:advanced"} ResourceActions []ResourceAction `json:"resourceActions,omitempty"` // ResourceExclusions is used to completely ignore entire classes of resource group/kinds. - //+operator-sdk:csv:customresourcedefinitions:type=spec,displayName="Resource Exclusions'",xDescriptors={"urn:alm:descriptor:com.tectonic.ui:text","urn:alm:descriptor:com.tectonic.ui:advanced"} + //+operator-sdk:csv:customresourcedefinitions:type=spec,displayName="Resource Exclusions",xDescriptors={"urn:alm:descriptor:com.tectonic.ui:text","urn:alm:descriptor:com.tectonic.ui:advanced"} ResourceExclusions string `json:"resourceExclusions,omitempty"` // ResourceInclusions is used to only include specific group/kinds in the @@ -978,7 +1015,7 @@ type ArgoCDSpec struct { ResourceInclusions string `json:"resourceInclusions,omitempty"` // ResourceTrackingMethod defines how Argo CD should track resources that it manages - //+operator-sdk:csv:customresourcedefinitions:type=spec,displayName="Resource Tracking Method'",xDescriptors={"urn:alm:descriptor:com.tectonic.ui:text","urn:alm:descriptor:com.tectonic.ui:advanced"} + //+operator-sdk:csv:customresourcedefinitions:type=spec,displayName="Resource Tracking Method",xDescriptors={"urn:alm:descriptor:com.tectonic.ui:text","urn:alm:descriptor:com.tectonic.ui:advanced"} ResourceTrackingMethod string `json:"resourceTrackingMethod,omitempty"` // Server defines the options for the ArgoCD Server component. @@ -991,7 +1028,7 @@ type ArgoCDSpec struct { SSO *ArgoCDSSOSpec `json:"sso,omitempty"` // StatusBadgeEnabled toggles application status badge feature. - //+operator-sdk:csv:customresourcedefinitions:type=spec,displayName="Status Badge Enabled'",xDescriptors={"urn:alm:descriptor:com.tectonic.ui:booleanSwitch","urn:alm:descriptor:com.tectonic.ui:advanced"} + //+operator-sdk:csv:customresourcedefinitions:type=spec,displayName="Status Badge Enabled",xDescriptors={"urn:alm:descriptor:com.tectonic.ui:booleanSwitch","urn:alm:descriptor:com.tectonic.ui:advanced"} StatusBadgeEnabled bool `json:"statusBadgeEnabled,omitempty"` // TLS defines the TLS options for ArgoCD. @@ -999,7 +1036,7 @@ type ArgoCDSpec struct { // UsersAnonymousEnabled toggles anonymous user access. // The anonymous users get default role permissions specified argocd-rbac-cm. - //+operator-sdk:csv:customresourcedefinitions:type=spec,displayName="Anonymous Users Enabled'",xDescriptors={"urn:alm:descriptor:com.tectonic.ui:booleanSwitch","urn:alm:descriptor:com.tectonic.ui:advanced"} + //+operator-sdk:csv:customresourcedefinitions:type=spec,displayName="Anonymous Users Enabled",xDescriptors={"urn:alm:descriptor:com.tectonic.ui:booleanSwitch","urn:alm:descriptor:com.tectonic.ui:advanced"} UsersAnonymousEnabled bool `json:"usersAnonymousEnabled,omitempty"` // Version is the tag to use with the ArgoCD container image for all ArgoCD components. @@ -1034,12 +1071,15 @@ type ManagedNamespaces struct { AllowManagedBy bool `json:"allowManagedBy"` } +const OpenShiftOAuthErrorMessage = "OpenShiftOAuth is not supported when external authentication is enabled on cluster, please provide OIDC config" const ( - ArgoCDConditionType = "Reconciled" + ArgoCDConditionType = "Reconciled" + ArgoCDConditionConfigurationError = "UnsupportedConfiguration" ) const ( ArgoCDConditionReasonSuccess = "Success" + ArgoCDConditionReasonSSOError = "UnsupportedSSOConfiguration" ArgoCDConditionReasonErrorOccurred = "ErrorOccurred" ) @@ -1177,6 +1217,28 @@ type WebhookServerSpec struct { Route ArgoCDRouteSpec `json:"route,omitempty"` } +// AgentMode is a type which represents possible agent modes +type AgentMode string + +// Possible agent modes +const ( + // AgentModeManaged indicates that the agent is in managed mode + AgentModeManaged AgentMode = "managed" + // AgentModeAutonomous indicates that the agent is in autonomous mode + AgentModeAutonomous AgentMode = "autonomous" +) + +// AgentComponentType is a type which represents possible agent component types +type AgentComponentType string + +// Possible agent component types +const ( + // AgentComponentTypePrincipal indicates the component type is principal + AgentComponentTypePrincipal AgentComponentType = "principal" + // AgentComponentTypeAgent indicates the component type is agent + AgentComponentTypeAgent AgentComponentType = "agent" +) + type ArgoCDAgentSpec struct { // Principal defines configurations for the Principal component of Argo CD Agent. @@ -1223,6 +1285,9 @@ type PrincipalSpec struct { // JWT defines the JWT options for the Principal component. JWT *PrincipalJWTSpec `json:"jwt,omitempty"` + + // DestinationBasedMapping is the flag to enable destination based mapping for the Principal component. + DestinationBasedMapping *bool `json:"destinationBasedMapping,omitempty"` } type PrincipalServerSpec struct { @@ -1318,6 +1383,10 @@ type AgentSpec struct { // Enabled is the flag to enable the Agent component during Argo CD installation. (optional, default `false`) Enabled *bool `json:"enabled,omitempty"` + // AllowedNamespaces is a list of additional namespaces the agent is allowed to + // manage applications in. Supports glob patterns. + AllowedNamespaces []string `json:"allowedNamespaces,omitempty"` + // Creds is the credential identifier for the agent authentication Creds string `json:"creds,omitempty"` @@ -1341,6 +1410,32 @@ type AgentSpec struct { // TLS defines the TLS options for the Agent component. TLS *AgentTLSSpec `json:"tls,omitempty"` + + // DestinationBasedMapping defines the options for destination based mapping for the Agent component. + DestinationBasedMapping *DestinationBasedMappingSpec `json:"destinationBasedMapping,omitempty"` +} + +type DestinationBasedMappingSpec struct { + // Enabled is the flag to enable destination based mapping for the Agent component. + Enabled *bool `json:"enabled,omitempty"` + + // CreateNamespace enables automatic creation of target namespaces on the managed cluster + // when destination-based mapping is enabled. + CreateNamespace *bool `json:"createNamespace,omitempty"` +} + +func (d *DestinationBasedMappingSpec) IsEnabled() bool { + if d == nil { + return false + } + return d.Enabled != nil && *d.Enabled +} + +func (d *DestinationBasedMappingSpec) IsCreateNamespaceEnabled() bool { + if d == nil || !d.IsEnabled() || d.CreateNamespace == nil { + return false + } + return *d.CreateNamespace } type AgentClientSpec struct { diff --git a/vendor/github.com/argoproj-labs/argocd-operator/api/v1beta1/zz_generated.deepcopy.go b/vendor/github.com/argoproj-labs/argocd-operator/api/v1beta1/zz_generated.deepcopy.go index 80ba2aa20..b50eaf4a3 100644 --- a/vendor/github.com/argoproj-labs/argocd-operator/api/v1beta1/zz_generated.deepcopy.go +++ b/vendor/github.com/argoproj-labs/argocd-operator/api/v1beta1/zz_generated.deepcopy.go @@ -77,6 +77,11 @@ func (in *AgentSpec) DeepCopyInto(out *AgentSpec) { *out = new(bool) **out = **in } + if in.AllowedNamespaces != nil { + in, out := &in.AllowedNamespaces, &out.AllowedNamespaces + *out = make([]string, len(*in)) + copy(*out, *in) + } if in.Env != nil { in, out := &in.Env, &out.Env *out = make([]v1.EnvVar, len(*in)) @@ -99,6 +104,11 @@ func (in *AgentSpec) DeepCopyInto(out *AgentSpec) { *out = new(AgentTLSSpec) (*in).DeepCopyInto(*out) } + if in.DestinationBasedMapping != nil { + in, out := &in.DestinationBasedMapping, &out.DestinationBasedMapping + *out = new(DestinationBasedMappingSpec) + (*in).DeepCopyInto(*out) + } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AgentSpec. @@ -696,6 +706,26 @@ func (in *ArgoCDMonitoringSpec) DeepCopy() *ArgoCDMonitoringSpec { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ArgoCDNetworkPolicySpec) DeepCopyInto(out *ArgoCDNetworkPolicySpec) { + *out = *in + if in.Enabled != nil { + in, out := &in.Enabled, &out.Enabled + *out = new(bool) + **out = **in + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ArgoCDNetworkPolicySpec. +func (in *ArgoCDNetworkPolicySpec) DeepCopy() *ArgoCDNetworkPolicySpec { + if in == nil { + return nil + } + out := new(ArgoCDNetworkPolicySpec) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ArgoCDNodePlacementSpec) DeepCopyInto(out *ArgoCDNodePlacementSpec) { *out = *in @@ -931,6 +961,11 @@ func (in *ArgoCDRepoSpec) DeepCopyInto(out *ArgoCDRepoSpec) { (*out)[key] = val } } + if in.SystemCATrust != nil { + in, out := &in.SystemCATrust, &out.SystemCATrust + *out = new(ArgoCDSystemCATrustSpec) + (*in).DeepCopyInto(*out) + } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ArgoCDRepoSpec. @@ -1185,6 +1220,7 @@ func (in *ArgoCDSpec) DeepCopyInto(out *ArgoCDSpec) { } } in.Monitoring.DeepCopyInto(&out.Monitoring) + in.NetworkPolicy.DeepCopyInto(&out.NetworkPolicy) if in.NodePlacement != nil { in, out := &in.NodePlacement, &out.NodePlacement *out = new(ArgoCDNodePlacementSpec) @@ -1278,6 +1314,42 @@ func (in *ArgoCDStatus) DeepCopy() *ArgoCDStatus { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ArgoCDSystemCATrustSpec) DeepCopyInto(out *ArgoCDSystemCATrustSpec) { + *out = *in + if in.ClusterTrustBundles != nil { + in, out := &in.ClusterTrustBundles, &out.ClusterTrustBundles + *out = make([]v1.ClusterTrustBundleProjection, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + if in.Secrets != nil { + in, out := &in.Secrets, &out.Secrets + *out = make([]v1.SecretProjection, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + if in.ConfigMaps != nil { + in, out := &in.ConfigMaps, &out.ConfigMaps + *out = make([]v1.ConfigMapProjection, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ArgoCDSystemCATrustSpec. +func (in *ArgoCDSystemCATrustSpec) DeepCopy() *ArgoCDSystemCATrustSpec { + if in == nil { + return nil + } + out := new(ArgoCDSystemCATrustSpec) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ArgoCDTLSSpec) DeepCopyInto(out *ArgoCDTLSSpec) { *out = *in @@ -1316,6 +1388,31 @@ func (in *Banner) DeepCopy() *Banner { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *DestinationBasedMappingSpec) DeepCopyInto(out *DestinationBasedMappingSpec) { + *out = *in + if in.Enabled != nil { + in, out := &in.Enabled, &out.Enabled + *out = new(bool) + **out = **in + } + if in.CreateNamespace != nil { + in, out := &in.CreateNamespace, &out.CreateNamespace + *out = new(bool) + **out = **in + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DestinationBasedMappingSpec. +func (in *DestinationBasedMappingSpec) DeepCopy() *DestinationBasedMappingSpec { + if in == nil { + return nil + } + out := new(DestinationBasedMappingSpec) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *IgnoreDifferenceCustomization) DeepCopyInto(out *IgnoreDifferenceCustomization) { *out = *in @@ -1649,6 +1746,11 @@ func (in *PrincipalSpec) DeepCopyInto(out *PrincipalSpec) { *out = new(PrincipalJWTSpec) (*in).DeepCopyInto(*out) } + if in.DestinationBasedMapping != nil { + in, out := &in.DestinationBasedMapping, &out.DestinationBasedMapping + *out = new(bool) + **out = **in + } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PrincipalSpec. diff --git a/vendor/github.com/argoproj-labs/argocd-operator/common/annotations.go b/vendor/github.com/argoproj-labs/argocd-operator/common/annotations.go index 831983e20..9a7ff3377 100644 --- a/vendor/github.com/argoproj-labs/argocd-operator/common/annotations.go +++ b/vendor/github.com/argoproj-labs/argocd-operator/common/annotations.go @@ -12,4 +12,8 @@ const ( // AnnotationOpenShiftServiceCA is the annotation on services used to // request a TLS certificate from OpenShift's Service CA for AutoTLS AnnotationOpenShiftServiceCA = "service.beta.openshift.io/serving-cert-secret-name" + + // AnnotationOpenShiftOriginatingServiceName is the annotation on secrets used to + // identify the service that created the secret. + AnnotationOpenShiftOriginatingServiceName = "service.beta.openshift.io/originating-service-name" ) diff --git a/vendor/github.com/argoproj-labs/argocd-operator/common/defaults.go b/vendor/github.com/argoproj-labs/argocd-operator/common/defaults.go index 3542f677c..455f09d5d 100644 --- a/vendor/github.com/argoproj-labs/argocd-operator/common/defaults.go +++ b/vendor/github.com/argoproj-labs/argocd-operator/common/defaults.go @@ -70,7 +70,7 @@ const ( ArgoCDDefaultArgoImage = "quay.io/argoproj/argocd" // ArgoCDDefaultArgoVersion is the Argo CD container image digest to use when version not specified. - ArgoCDDefaultArgoVersion = "sha256:db23e2148b3d8ebc7683707da6d0b0c376d194890691222cba5d164776ea8980" // v3.1.11 + ArgoCDDefaultArgoVersion = "sha256:05d68bf224df7cd39713012c19226a33c374f2f3bd65df7b9088349e4ac3e6a2" // v3.3.10 // ArgoCDDefaultBackupKeyLength is the length of the generated default backup key. ArgoCDDefaultBackupKeyLength = 32 @@ -125,7 +125,7 @@ const ( ArgoCDDefaultExportJobImage = "quay.io/argoprojlabs/argocd-operator-util" // ArgoCDDefaultExportJobVersion is the export job container image tag to use when not specified. - ArgoCDDefaultExportJobVersion = "sha256:392ea9e4961c21d496efede212f208b3aacef3e0a55631312d60f93b04600e9b" // 0.17.0 + ArgoCDDefaultExportJobVersion = "sha256:6a10d9d6d770d0d92c67c3794becdcebbf481f55e1a74bf21b595a01fb5223e8" // 0.18.0 // ArgoCDDefaultExportLocalCapicity is the default capacity to use for local export. ArgoCDDefaultExportLocalCapicity = "2Gi" @@ -191,10 +191,10 @@ const ( ArgoCDDefaultRedisSuffix = "redis" // ArgoCDDefaultRedisVersion is the Redis container image tag to use when not specified. - ArgoCDDefaultRedisVersion = "sha256:1a34bdba051ecd8a58ec8a3cc460acef697a1605e918149cc53d920673c1a0a7" // 7.2.11-alpine + ArgoCDDefaultRedisVersion = "sha256:08ad0b1d280850169a790dba1393ff7a90aef951fc19632cf4d3ce4f78e679ba" // 8.2.3-alpine // ArgoCDDefaultRedisVersionHA is the Redis container image tag to use when not specified in HA mode. - ArgoCDDefaultRedisVersionHA = "sha256:1a34bdba051ecd8a58ec8a3cc460acef697a1605e918149cc53d920673c1a0a7" // 7.2.11-alpine + ArgoCDDefaultRedisVersionHA = "sha256:08ad0b1d280850169a790dba1393ff7a90aef951fc19632cf4d3ce4f78e679ba" // 8.2.3-alpine // ArgoCDDefaultRepoMetricsPort is the default listen port for the Argo CD repo server metrics. ArgoCDDefaultRepoMetricsPort = 8084 @@ -288,10 +288,10 @@ vs-ssh.visualstudio.com ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC7Hr1oTWqNqOlzGJOf ArgoCDCmdParamsConfigMapName = "argocd-cmd-params-cm" // ArgoCDAgentPrincipalDefaultImageName is the default image name for the ArgoCD agent's principal component. - ArgoCDAgentPrincipalDefaultImageName = "quay.io/argoprojlabs/argocd-agent:v0.3.2" + ArgoCDAgentPrincipalDefaultImageName = "quay.io/argoprojlabs/argocd-agent:v0.7.0" // ArgoCDAgentAgentDefaultImageName is the default image name for the ArgoCD agent's agent component. - ArgoCDAgentAgentDefaultImageName = "quay.io/argoprojlabs/argocd-agent:v0.3.2" + ArgoCDAgentAgentDefaultImageName = "quay.io/argoprojlabs/argocd-agent:v0.7.0" // ArgoCDImageUpdaterControllerComponent is the name of the Image Updater controller control plane component ArgoCDImageUpdaterControllerComponent = "argocd-image-updater-controller" diff --git a/vendor/github.com/argoproj-labs/argocd-operator/common/keys.go b/vendor/github.com/argoproj-labs/argocd-operator/common/keys.go index c24463908..e14a73eec 100644 --- a/vendor/github.com/argoproj-labs/argocd-operator/common/keys.go +++ b/vendor/github.com/argoproj-labs/argocd-operator/common/keys.go @@ -223,6 +223,9 @@ const ( // ArgoCDNotificationsManagedByClusterArgoCDLabel is needed to identify namespace mentioned as notifications sourceNamespaces on ArgoCD ArgoCDNotificationsManagedByClusterArgoCDLabel = "argocd.argoproj.io/notifications-managed-by-cluster-argocd" + // ArgoCDCATrustChecksum is applied to repo-server Deployment to trigger reconciliation when some of the SystemCATrust sources changes + ArgoCDCATrustChecksum = "argocd.argoproj.io/ca-trust-checksum" + // ArgoCDControllerClusterRoleEnvName is an environment variable to specify a custom cluster role for Argo CD application controller ArgoCDControllerClusterRoleEnvName = "CONTROLLER_CLUSTER_ROLE" diff --git a/vendor/github.com/argoproj/gitops-engine/pkg/diff/diff.go b/vendor/github.com/argoproj/gitops-engine/pkg/diff/diff.go index 166ec2fd6..8513eb03d 100644 --- a/vendor/github.com/argoproj/gitops-engine/pkg/diff/diff.go +++ b/vendor/github.com/argoproj/gitops-engine/pkg/diff/diff.go @@ -183,6 +183,9 @@ func serverSideDiff(config, live *unstructured.Unstructured, opts ...Option) (*D } } + // Remarshal predictedLive to ensure it receives the same normalization as live. + predictedLive = remarshal(predictedLive, o) + Normalize(predictedLive, opts...) unstructured.RemoveNestedField(predictedLive.Object, "metadata", "managedFields") @@ -267,7 +270,7 @@ func removeWebhookMutation(predictedLive, live *unstructured.Unstructured, gvkPa } // In case any of the removed fields cause schema violations, we will keep those fields - nonArgoFieldsSet = safelyRemoveFieldsSet(typedPredictedLive, nonArgoFieldsSet) + nonArgoFieldsSet = filterOutCompositeKeyFields(typedPredictedLive, nonArgoFieldsSet) typedPredictedLive = typedPredictedLive.RemoveItems(nonArgoFieldsSet) // Apply the predicted live state to the live state to get a diff without mutation webhook fields @@ -289,29 +292,58 @@ func removeWebhookMutation(predictedLive, live *unstructured.Unstructured, gvkPa return &unstructured.Unstructured{Object: pl}, nil } -// safelyRemoveFieldSet will validate if removing the fieldsToRemove set from predictedLive maintains -// a valid schema. If removing a field in fieldsToRemove is invalid and breaks the schema, it is not safe -// to remove and will be skipped from removal from predictedLive. -func safelyRemoveFieldsSet(predictedLive *typed.TypedValue, fieldsToRemove *fieldpath.Set) *fieldpath.Set { - // In some cases, we cannot remove fields due to violation of the predicted live schema. In such cases we validate the removal - // of each field and only include it if the removal is valid. - testPredictedLive := predictedLive.RemoveItems(fieldsToRemove) - err := testPredictedLive.Validate() - if err != nil { - adjustedFieldsToRemove := fieldpath.NewSet() - fieldsToRemove.Iterate(func(p fieldpath.Path) { - singleFieldSet := fieldpath.NewSet(p) - testSingleRemoval := predictedLive.RemoveItems(singleFieldSet) - // Check if removing this single field maintains a valid schema - if testSingleRemoval.Validate() == nil { - // If valid, add this field to the adjusted set to remove - adjustedFieldsToRemove.Insert(p) +// filterOutCompositeKeyFields filters out fields that are part of composite keys in associative lists. +// These fields must be preserved to maintain list element identity during merge operations. +func filterOutCompositeKeyFields(_ *typed.TypedValue, fieldsToRemove *fieldpath.Set) *fieldpath.Set { + filteredFields := fieldpath.NewSet() + + fieldsToRemove.Iterate(func(fieldPath fieldpath.Path) { + isCompositeKey := isCompositeKeyField(fieldPath) + if !isCompositeKey { + // Only keep fields that are NOT composite keys - these are safe to remove + filteredFields.Insert(fieldPath) + } + }) + + return filteredFields +} + +// isCompositeKeyField checks if a field path represents a field that is part of a composite key +// in an associative list by examining the PathElement structure. +// Example: .spec.containers[name="nginx"].ports[containerPort=80,protocol="TCP"].protocol +// The path elements include: +// - PathElement{Key: {name: "nginx"}} - single key (not composite) +// - PathElement{Key: {containerPort: 80, protocol: "TCP"}} - composite key with 2 fields +func isCompositeKeyField(fieldPath fieldpath.Path) bool { + if len(fieldPath) == 0 { + return false + } + + // Get the last path element + lastElement := fieldPath[len(fieldPath)-1] + if lastElement.FieldName == nil { + return false + } + finalFieldName := *lastElement.FieldName + + // Look backwards through the path to find the most recent associative list key + for i := len(fieldPath) - 2; i >= 0; i-- { + pe := fieldPath[i] + if pe.Key == nil { + continue + } + if len(*pe.Key) <= 1 { + continue + } + // This is a composite key + for _, keyField := range *pe.Key { + if keyField.Name == finalFieldName { + return true } - }) - return adjustedFieldsToRemove + } } - // If no violations, return the original set to remove - return fieldsToRemove + + return false } func jsonStrToUnstructured(jsonString string) (*unstructured.Unstructured, error) { diff --git a/vendor/github.com/bmatcuk/doublestar/v4/.gitignore b/vendor/github.com/bmatcuk/doublestar/v4/.gitignore index af212ecc2..f2d8e6b8b 100644 --- a/vendor/github.com/bmatcuk/doublestar/v4/.gitignore +++ b/vendor/github.com/bmatcuk/doublestar/v4/.gitignore @@ -29,4 +29,4 @@ _testmain.go *.prof # test directory -test/ +testdata/ diff --git a/vendor/github.com/bmatcuk/doublestar/v4/README.md b/vendor/github.com/bmatcuk/doublestar/v4/README.md index e4d1941e3..57d18b0e5 100644 --- a/vendor/github.com/bmatcuk/doublestar/v4/README.md +++ b/vendor/github.com/bmatcuk/doublestar/v4/README.md @@ -193,6 +193,27 @@ symlink to a directory. However, from this same example, a pattern such as Note: if combined with the WithFilesOnly option, symlinks to directories _will_ be included in the result since no attempt is made to follow the symlink. +```go +WithNoHidden() +``` + +If passed, doublestar will not match hidden files and directories (those +starting with a dot) when using wildcards. This follows traditional shell glob +behavior where `*` or a `?` at the start will not match dotfiles by default. + +Hidden files can still be matched by explicitly including them in the pattern. +For example, `.*` will match hidden files, and `.config/**` will match files +inside the .config directory. + +The rule is: + - For `**`: do not descend into hidden directories + - For `*` or a pattern starting with `?`: do not match dotfiles or + directories + +On Windows, doublestar will check the file attributes and avoid hidden files +and directories this way, instead of matching the filename. Therefore, any +pattern with a `*` or `?` could potentially match a hidden file/directory. + ### Glob ```go @@ -391,6 +412,38 @@ Class | Meaning `[^class]` | matches any single character which does *not* match the class `[!class]` | same as `^`: negates the class +#### Globs Are Not Regular Expressions + +Occasionally I get bug reports that some regular-expression-style syntax +doesn't work, or feature requests to add some regular-expression-inspired +syntax. Globs are not regular expressions. However, if globs are not +sufficiently expressive for your filtering needs, I recommend a two stage +approach using `GlobWalk`. Something like the following will get you started: + +```go +var matches []string +err := doublestar.GlobWalk(fsys, pattern, func(p string, d fs.DirEntry) error { + if (customFilter(p, d)) { + matches = append(matches, p) + } else if (d.isDir()) { + return doublestar.SkipDir + } + return nil +}) +return matches, err +``` + +In this example, `pattern` should be a glob that does a first pass at fetching +the files you might be interested in; `customFilter` is a function that does a +second pass. This second pass could be anything, including regular expressions. +Try to fashion a `pattern` that reduces the number of files you need to +consider in your second pass `customFilter`. + +One final note: empty alternatives can be used to build some more complicated +globs. For example, `some{thing,}` will match both "something" and "some". +Alternatives can also be nested, like `some{thing{new,},}`, which would match +"somethingnew", "something", and "some". + ## Performance ``` diff --git a/vendor/github.com/bmatcuk/doublestar/v4/glob.go b/vendor/github.com/bmatcuk/doublestar/v4/glob.go index 3471bea78..f3ef03920 100644 --- a/vendor/github.com/bmatcuk/doublestar/v4/glob.go +++ b/vendor/github.com/bmatcuk/doublestar/v4/glob.go @@ -158,7 +158,7 @@ func (g *glob) globAlts(fsys fs.FS, pattern string, openingIdx, closingIdx int, nextIdx += patIdx } - alt := buildAlt(d, pattern, startIdx, openingIdx, patIdx, nextIdx, afterIdx) + alt := buildAlt(escapeMeta(d), pattern, startIdx, openingIdx, patIdx, nextIdx, afterIdx) matches, err = g.doGlob(fsys, alt, matches, firstSegment, beforeMeta) if err != nil { return @@ -223,8 +223,21 @@ func (g *glob) globDir(fsys fs.FS, dir, pattern string, matches []string, canMat } var matched bool + checkForHidden := g.noHidden && couldUnintentionallyMatchHidden(pattern) for _, info := range dirs { name := info.Name() + + // Skip hidden files when noHidden is set + if checkForHidden { + isHidden, err := isHiddenPath(name, info) + if e = g.forwardErrIfFailOnIOErrors(err); e != nil { + return + } + if isHidden { + continue + } + } + matched, e = matchWithSeparator(pattern, name, '/', false, g.caseInsensitive) if e != nil { return @@ -268,6 +281,18 @@ func (g *glob) globDoubleStar(fsys fs.FS, dir string, matches []string, canMatch for _, info := range dirs { name := info.Name() + + // Skip hidden files/directories when noHidden is set + if g.noHidden { + isHidden, err := isHiddenPath(name, info) + if err = g.forwardErrIfFailOnIOErrors(err); err != nil { + return nil, err + } + if isHidden { + continue + } + } + isDir, err := g.isDir(fsys, dir, name, info) if err != nil { return nil, err diff --git a/vendor/github.com/bmatcuk/doublestar/v4/globoptions.go b/vendor/github.com/bmatcuk/doublestar/v4/globoptions.go index 629835602..07c2bb816 100644 --- a/vendor/github.com/bmatcuk/doublestar/v4/globoptions.go +++ b/vendor/github.com/bmatcuk/doublestar/v4/globoptions.go @@ -4,11 +4,12 @@ import "strings" // glob is an internal type to store options during globbing. type glob struct { - caseInsensitive bool + caseInsensitive bool failOnIOErrors bool failOnPatternNotExist bool filesOnly bool noFollow bool + noHidden bool } // GlobOption represents a setting that can be passed to Glob, GlobWalk, and @@ -90,6 +91,30 @@ func WithNoFollow() GlobOption { } } +// WithNoHidden is an option that can be passed to Glob, GlobWalk, or +// FilepathGlob. If passed, doublestar will not match hidden files and +// directories (those starting with a dot) when using wildcards. This follows +// traditional shell glob behavior where `*` or a `?` at the start will not +// match dotfiles by default. +// +// Hidden files can still be matched by explicitly including them in the +// pattern. For example, `.*` will match hidden files, and `.config/**` will +// match files inside the .config directory. +// +// The rule is: +// - For `**`: do not descend into hidden directories +// - For `*` or a pattern starting with `?`: do not match dotfiles or +// directories +// +// On Windows, doublestar will check the file attributes and avoid hidden files +// and directories this way, instead of matching the filename. Therefore, any +// pattern with a `*` or `?` could potentially match a hidden file/directory. +func WithNoHidden() GlobOption { + return func(g *glob) { + g.noHidden = true + } +} + // forwardErrIfFailOnIOErrors is used to wrap the return values of I/O // functions. When failOnIOErrors is enabled, it will return err; otherwise, it // always returns nil. @@ -148,6 +173,13 @@ func (g *glob) GoString() string { b.WriteString("WithNoFollow") hasOpts = true } + if g.noHidden { + if hasOpts { + b.WriteString(", ") + } + b.WriteString("WithNoHidden") + hasOpts = true + } if !hasOpts { b.WriteString("nil") diff --git a/vendor/github.com/bmatcuk/doublestar/v4/globwalk.go b/vendor/github.com/bmatcuk/doublestar/v4/globwalk.go index 16601b76a..9516cefdd 100644 --- a/vendor/github.com/bmatcuk/doublestar/v4/globwalk.go +++ b/vendor/github.com/bmatcuk/doublestar/v4/globwalk.go @@ -205,7 +205,7 @@ func (g *glob) doGlobAltsWalk(fsys fs.FS, d, pattern string, startIdx, openingId nextIdx += patIdx } - alt := buildAlt(d, pattern, startIdx, openingIdx, patIdx, nextIdx, afterIdx) + alt := buildAlt(escapeMeta(d), pattern, startIdx, openingIdx, patIdx, nextIdx, afterIdx) err = g.doGlobWalk(fsys, alt, firstSegment, beforeMeta, func(p string, d fs.DirEntry) error { // insertion sort, ignoring dups insertIdx := matchesLen @@ -287,8 +287,21 @@ func (g *glob) globDirWalk(fsys fs.FS, dir, pattern string, canMatchFiles, befor } var matched bool + checkForHidden := g.noHidden && couldUnintentionallyMatchHidden(pattern) for _, info := range dirs { name := info.Name() + + // Skip hidden files when noHidden is set + if checkForHidden { + isHidden, err := isHiddenPath(name, info) + if e = g.forwardErrIfFailOnIOErrors(err); e != nil { + return + } + if isHidden { + continue + } + } + matched, e = matchWithSeparator(pattern, name, '/', false, g.caseInsensitive) if e != nil { return @@ -335,6 +348,18 @@ func (g *glob) globDoubleStarWalk(fsys fs.FS, dir string, canMatchFiles bool, fn for _, info := range dirs { name := info.Name() + + // Skip hidden files/directories when noHidden is set + if g.noHidden { + isHidden, err := isHiddenPath(name, info) + if e = g.forwardErrIfFailOnIOErrors(err); e != nil { + return + } + if isHidden { + continue + } + } + isDir, err := g.isDir(fsys, dir, name, info) if err != nil { return err diff --git a/vendor/github.com/bmatcuk/doublestar/v4/utils.go b/vendor/github.com/bmatcuk/doublestar/v4/utils.go index 7831e5c3d..498c0441d 100644 --- a/vendor/github.com/bmatcuk/doublestar/v4/utils.go +++ b/vendor/github.com/bmatcuk/doublestar/v4/utils.go @@ -14,16 +14,16 @@ import ( // The second string is everything after that slash. For example, given the // pattern: // -// ../../path/to/meta*/** -// ^----------- split here +// ../../path/to/meta*/** +// ^----------- split here // // SplitPattern returns "../../path/to" and "meta*/**". This is useful for // initializing os.DirFS() to call Glob() because Glob() will silently fail if // your pattern includes `/./` or `/../`. For example: // -// base, pattern := SplitPattern("../../path/to/meta*/**") -// fsys := os.DirFS(base) -// matches, err := Glob(fsys, pattern) +// base, pattern := SplitPattern("../../path/to/meta*/**") +// fsys := os.DirFS(base) +// matches, err := Glob(fsys, pattern) // // If SplitPattern cannot find somewhere to split the pattern (for example, // `meta*/**`), it will return "." and the unaltered pattern (`meta*/**` in @@ -35,7 +35,6 @@ import ( // Of course, it is your responsibility to decide if the returned base path is // "safe" in the context of your application. Perhaps you could use Match() to // validate against a list of approved base directories? -// func SplitPattern(p string) (base, pattern string) { base = "." pattern = p @@ -85,7 +84,6 @@ func SplitPattern(p string) (base, pattern string) { // // Note: the returned error doublestar.ErrBadPattern is not equal to // filepath.ErrBadPattern. -// func FilepathGlob(pattern string, opts ...GlobOption) (matches []string, err error) { if pattern == "" { // special case to match filepath.Glob behavior @@ -152,9 +150,16 @@ func indexNextAlt(s string, allowEscaping bool) int { return -1 } -var metaReplacer = strings.NewReplacer("\\*", "*", "\\?", "?", "\\[", "[", "\\]", "]", "\\{", "{", "\\}", "}") +var escapeMetaReplacer = strings.NewReplacer("*", "\\*", "?", "\\?", "[", "\\[", "]", "\\]", "{", "\\{", "}", "\\}") + +// Escapes meta characters (*?[]{}) +func escapeMeta(path string) string { + return escapeMetaReplacer.Replace(path) +} + +var unescapeMetaReplacer = strings.NewReplacer("\\*", "*", "\\?", "?", "\\[", "[", "\\]", "]", "\\{", "{", "\\}", "}") // Unescapes meta characters (*?[]{}) func unescapeMeta(pattern string) string { - return metaReplacer.Replace(pattern) + return unescapeMetaReplacer.Replace(pattern) } diff --git a/vendor/github.com/bmatcuk/doublestar/v4/utils_unix.go b/vendor/github.com/bmatcuk/doublestar/v4/utils_unix.go new file mode 100644 index 000000000..343e55f83 --- /dev/null +++ b/vendor/github.com/bmatcuk/doublestar/v4/utils_unix.go @@ -0,0 +1,19 @@ +//go:build !windows + +package doublestar + +import ( + "io/fs" +) + +// Returns true if the pattern could "unintentionally" match hidden files/dirs. +// An unintentional pattern would use a meta character that could match +// anything. +func couldUnintentionallyMatchHidden(pattern string) bool { + return len(pattern) > 0 && (pattern[0] == '*' || pattern[0] == '?') +} + +// Returns true if the file is "hidden" +func isHiddenPath(filename string, _info fs.DirEntry) (bool, error) { + return filename[0] == '.', nil +} diff --git a/vendor/github.com/bmatcuk/doublestar/v4/utils_windows.go b/vendor/github.com/bmatcuk/doublestar/v4/utils_windows.go new file mode 100644 index 000000000..5c6a67caf --- /dev/null +++ b/vendor/github.com/bmatcuk/doublestar/v4/utils_windows.go @@ -0,0 +1,43 @@ +package doublestar + +import ( + "io/fs" + "syscall" +) + +// Returns true if the pattern could "unintentionally" match hidden files/dirs. +// An unintentional pattern would use a meta character that could match +// anything. +func couldUnintentionallyMatchHidden(pattern string) bool { + var c byte + inClass := false + l := len(pattern) + for i := 0; i < l; i++ { + c = pattern[i] + if !inClass && (c == '*' || c == '?') { + return true + } else if c == '[' { + inClass = true + } else if c == '\\' { + // skip next byte + i++ + } else if inClass && c == ']' { + inClass = false + } + } + return false +} + +// Returns true if the file is "hidden" +func isHiddenPath(_filename string, info fs.DirEntry) (bool, error) { + fileinfo, err := info.Info() + if err != nil { + return false, err + } + + if stat, ok := fileinfo.Sys().(*syscall.Win32FileAttributeData); ok { + return stat.FileAttributes&syscall.FILE_ATTRIBUTE_HIDDEN != 0, nil + } + + return false, nil +} diff --git a/vendor/github.com/bmatcuk/doublestar/v4/validate.go b/vendor/github.com/bmatcuk/doublestar/v4/validate.go index c689b9eba..312129e72 100644 --- a/vendor/github.com/bmatcuk/doublestar/v4/validate.go +++ b/vendor/github.com/bmatcuk/doublestar/v4/validate.go @@ -9,7 +9,6 @@ import "path/filepath" // you might want to validate it. // // ValidatePattern assumes your pattern uses '/' as the path separator. -// func ValidatePattern(s string) bool { return doValidatePattern(s, '/') } @@ -18,7 +17,6 @@ func ValidatePattern(s string) bool { // ValidatePattern if you would normally use Match() or Glob(). Use // ValidatePathPattern if you would normally use PathMatch(). Keep in mind, // Glob() requires '/' separators, even if your OS uses something else. -// func ValidatePathPattern(s string) bool { return doValidatePattern(s, filepath.Separator) } diff --git a/vendor/github.com/sergi/go-diff/diffmatchpatch/diff.go b/vendor/github.com/sergi/go-diff/diffmatchpatch/diff.go index 915d5090d..08c36e74f 100644 --- a/vendor/github.com/sergi/go-diff/diffmatchpatch/diff.go +++ b/vendor/github.com/sergi/go-diff/diffmatchpatch/diff.go @@ -1146,13 +1146,28 @@ func (dmp *DiffMatchPatch) DiffPrettyText(diffs []Diff) string { switch diff.Type { case DiffInsert: - _, _ = buff.WriteString("\x1b[32m") - _, _ = buff.WriteString(text) - _, _ = buff.WriteString("\x1b[0m") + lines := strings.Split(text, "\n") + for i, line := range lines { + _, _ = buff.WriteString("\x1b[32m") + _, _ = buff.WriteString(line) + if i < len(lines)-1 { + _, _ = buff.WriteString("\x1b[0m\n") + } else { + _, _ = buff.WriteString("\x1b[0m") + } + } + case DiffDelete: - _, _ = buff.WriteString("\x1b[31m") - _, _ = buff.WriteString(text) - _, _ = buff.WriteString("\x1b[0m") + lines := strings.Split(text, "\n") + for i, line := range lines { + _, _ = buff.WriteString("\x1b[31m") + _, _ = buff.WriteString(line) + if i < len(lines)-1 { + _, _ = buff.WriteString("\x1b[0m\n") + } else { + _, _ = buff.WriteString("\x1b[0m") + } + } case DiffEqual: _, _ = buff.WriteString(text) } @@ -1305,7 +1320,6 @@ func (dmp *DiffMatchPatch) DiffFromDelta(text1 string, delta string) (diffs []Di // diffLinesToStrings splits two texts into a list of strings. Each string represents one line. func (dmp *DiffMatchPatch) diffLinesToStrings(text1, text2 string) (string, string, []string) { - // '\x00' is a valid character, but various debuggers don't like it. So we'll insert a junk entry to avoid generating a null character. lineArray := []string{""} // e.g. lineArray[4] == 'Hello\n' lineHash := make(map[string]int) @@ -1316,12 +1330,11 @@ func (dmp *DiffMatchPatch) diffLinesToStrings(text1, text2 string) (string, stri return intArrayToString(strIndexArray1), intArrayToString(strIndexArray2), lineArray } -// diffLinesToStringsMunge splits a text into an array of strings, and reduces the texts to a []string. -func (dmp *DiffMatchPatch) diffLinesToStringsMunge(text string, lineArray *[]string, lineHash map[string]int) []uint32 { - // Walk the text, pulling out a substring for each line. text.split('\n') would would temporarily double our memory footprint. Modifying text would create many large strings to garbage collect. +// diffLinesToStringsMunge splits a text into an array of strings, and reduces the texts to a []index. +func (dmp *DiffMatchPatch) diffLinesToStringsMunge(text string, lineArray *[]string, lineHash map[string]int) []index { lineStart := 0 lineEnd := -1 - strs := []uint32{} + strs := []index{} for lineEnd < len(text)-1 { lineEnd = indexOf(text, "\n", lineStart) @@ -1335,11 +1348,11 @@ func (dmp *DiffMatchPatch) diffLinesToStringsMunge(text string, lineArray *[]str lineValue, ok := lineHash[line] if ok { - strs = append(strs, uint32(lineValue)) + strs = append(strs, index(lineValue)) } else { *lineArray = append(*lineArray, line) lineHash[line] = len(*lineArray) - 1 - strs = append(strs, uint32(len(*lineArray)-1)) + strs = append(strs, index(len(*lineArray)-1)) } } diff --git a/vendor/github.com/sergi/go-diff/diffmatchpatch/index.go b/vendor/github.com/sergi/go-diff/diffmatchpatch/index.go new file mode 100644 index 000000000..965a1c64b --- /dev/null +++ b/vendor/github.com/sergi/go-diff/diffmatchpatch/index.go @@ -0,0 +1,32 @@ +package diffmatchpatch + +type index uint32 + +const runeSkipStart = 0xd800 +const runeSkipEnd = 0xdfff + 1 +const runeMax = 0x110000 // next invalid code point + +func stringToIndex(text string) []index { + runes := []rune(text) + indexes := make([]index, len(runes)) + for i, r := range runes { + if r < runeSkipEnd { + indexes[i] = index(r) + } else { + indexes[i] = index(r) - (runeSkipEnd - runeSkipStart) + } + } + return indexes +} + +func indexesToString(indexes []index) string { + runes := make([]rune, len(indexes)) + for i, index := range indexes { + if index < runeSkipStart { + runes[i] = rune(index) + } else { + runes[i] = rune(index + (runeSkipEnd - runeSkipStart)) + } + } + return string(runes) +} diff --git a/vendor/github.com/sergi/go-diff/diffmatchpatch/stringutil.go b/vendor/github.com/sergi/go-diff/diffmatchpatch/stringutil.go index eb727bb59..573b6bf75 100644 --- a/vendor/github.com/sergi/go-diff/diffmatchpatch/stringutil.go +++ b/vendor/github.com/sergi/go-diff/diffmatchpatch/stringutil.go @@ -93,14 +93,14 @@ func runesIndex(r1, r2 []rune) int { return -1 } -func intArrayToString(ns []uint32) string { +func intArrayToString(ns []index) string { if len(ns) == 0 { return "" } b := []rune{} for _, n := range ns { - b = append(b, intToRune(n)) + b = append(b, intToRune(uint32(n))) } return string(b) } diff --git a/vendor/go.uber.org/zap/.golangci.yml b/vendor/go.uber.org/zap/.golangci.yml index 2346df135..74faaa71d 100644 --- a/vendor/go.uber.org/zap/.golangci.yml +++ b/vendor/go.uber.org/zap/.golangci.yml @@ -25,7 +25,7 @@ linters-settings: govet: # These govet checks are disabled by default, but they're useful. enable: - - niliness + - nilness - reflectvaluecompare - sortslice - unusedwrite diff --git a/vendor/go.uber.org/zap/CHANGELOG.md b/vendor/go.uber.org/zap/CHANGELOG.md index 6d6cd5f4d..86e7e6f98 100644 --- a/vendor/go.uber.org/zap/CHANGELOG.md +++ b/vendor/go.uber.org/zap/CHANGELOG.md @@ -3,6 +3,16 @@ All notable changes to this project will be documented in this file. This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## 1.27.1 (19 Nov 2025) +Enhancements: +* [#1501][]: prevent `Object` from panicking on nils +* [#1511][]: Fix a race condition in `WithLazy`. + +Thanks to @rabbbit, @alshopov, @jquirke, @arukiidou for their contributions to this release. + +[#1501]: https://github.com/uber-go/zap/pull/1501 +[#1511]: https://github.com/uber-go/zap/pull/1511 + ## 1.27.0 (20 Feb 2024) Enhancements: * [#1378][]: Add `WithLazy` method for `SugaredLogger`. diff --git a/vendor/go.uber.org/zap/CODE_OF_CONDUCT.md b/vendor/go.uber.org/zap/CODE_OF_CONDUCT.md index e327d9aa5..bc988b72e 100644 --- a/vendor/go.uber.org/zap/CODE_OF_CONDUCT.md +++ b/vendor/go.uber.org/zap/CODE_OF_CONDUCT.md @@ -71,5 +71,5 @@ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version]. -[homepage]: http://contributor-covenant.org -[version]: http://contributor-covenant.org/version/1/4/ +[homepage]: https://contributor-covenant.org +[version]: https://contributor-covenant.org/version/1/4/ diff --git a/vendor/go.uber.org/zap/LICENSE b/vendor/go.uber.org/zap/LICENSE index 6652bed45..3883b9a7e 100644 --- a/vendor/go.uber.org/zap/LICENSE +++ b/vendor/go.uber.org/zap/LICENSE @@ -1,4 +1,4 @@ -Copyright (c) 2016-2017 Uber Technologies, Inc. +Copyright (c) 2016-2024 Uber Technologies, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/vendor/go.uber.org/zap/Makefile b/vendor/go.uber.org/zap/Makefile index eb1cee53b..f9db385b3 100644 --- a/vendor/go.uber.org/zap/Makefile +++ b/vendor/go.uber.org/zap/Makefile @@ -24,7 +24,7 @@ golangci-lint: @$(foreach mod,$(MODULE_DIRS), \ (cd $(mod) && \ echo "[lint] golangci-lint: $(mod)" && \ - golangci-lint run --path-prefix $(mod)) &&) true + golangci-lint run --path-prefix $(mod) ./...) &&) true .PHONY: tidy tidy: diff --git a/vendor/go.uber.org/zap/field.go b/vendor/go.uber.org/zap/field.go index 6743930b8..1884afabc 100644 --- a/vendor/go.uber.org/zap/field.go +++ b/vendor/go.uber.org/zap/field.go @@ -398,6 +398,9 @@ func Durationp(key string, val *time.Duration) Field { // struct-like user-defined types to the logging context. The struct's // MarshalLogObject method is called lazily. func Object(key string, val zapcore.ObjectMarshaler) Field { + if val == nil { + return nilField(key) + } return Field{Key: key, Type: zapcore.ObjectMarshalerType, Interface: val} } @@ -431,6 +434,13 @@ func (d dictObject) MarshalLogObject(enc zapcore.ObjectEncoder) error { return nil } +// DictObject constructs a [zapcore.ObjectMarshaler] with the given list of fields. +// The resulting object marshaler can be used as input to [Object], [Objects], or +// any other functions that expect an object marshaler. +func DictObject(val ...Field) zapcore.ObjectMarshaler { + return dictObject(val) +} + // We discovered an issue where zap.Any can cause a performance degradation // when used in new goroutines. // diff --git a/vendor/go.uber.org/zap/http_handler.go b/vendor/go.uber.org/zap/http_handler.go index 2be8f6515..1cae2c164 100644 --- a/vendor/go.uber.org/zap/http_handler.go +++ b/vendor/go.uber.org/zap/http_handler.go @@ -71,7 +71,7 @@ import ( func (lvl AtomicLevel) ServeHTTP(w http.ResponseWriter, r *http.Request) { if err := lvl.serveHTTP(w, r); err != nil { w.WriteHeader(http.StatusInternalServerError) - fmt.Fprintf(w, "internal error: %v", err) + _, _ = fmt.Fprintf(w, "internal error: %v", err) } } diff --git a/vendor/go.uber.org/zap/logger.go b/vendor/go.uber.org/zap/logger.go index c4d300323..2d0ef141b 100644 --- a/vendor/go.uber.org/zap/logger.go +++ b/vendor/go.uber.org/zap/logger.go @@ -381,7 +381,11 @@ func (log *Logger) check(lvl zapcore.Level, msg string) *zapcore.CheckedEntry { if stack.Count() == 0 { if log.addCaller { - fmt.Fprintf(log.errorOutput, "%v Logger.check error: failed to get caller\n", ent.Time.UTC()) + _, _ = fmt.Fprintf( + log.errorOutput, + "%v Logger.check error: failed to get caller\n", + ent.Time.UTC(), + ) _ = log.errorOutput.Sync() } return ce diff --git a/vendor/go.uber.org/zap/options.go b/vendor/go.uber.org/zap/options.go index 43d357ac9..04a3c1e63 100644 --- a/vendor/go.uber.org/zap/options.go +++ b/vendor/go.uber.org/zap/options.go @@ -125,7 +125,11 @@ func IncreaseLevel(lvl zapcore.LevelEnabler) Option { return optionFunc(func(log *Logger) { core, err := zapcore.NewIncreaseLevelCore(log.core, lvl) if err != nil { - fmt.Fprintf(log.errorOutput, "failed to IncreaseLevel: %v\n", err) + _, _ = fmt.Fprintf( + log.errorOutput, + "failed to IncreaseLevel: %v\n", + err, + ) } else { log.core = core } diff --git a/vendor/go.uber.org/zap/sink.go b/vendor/go.uber.org/zap/sink.go index 499772a00..92202280f 100644 --- a/vendor/go.uber.org/zap/sink.go +++ b/vendor/go.uber.org/zap/sink.go @@ -71,7 +71,7 @@ func newSinkRegistry() *sinkRegistry { return sr } -// RegisterScheme registers the given factory for the specific scheme. +// RegisterSink registers the given factory for the specific scheme. func (sr *sinkRegistry) RegisterSink(scheme string, factory func(*url.URL) (Sink, error)) error { sr.mu.Lock() defer sr.mu.Unlock() diff --git a/vendor/go.uber.org/zap/zapcore/buffered_write_syncer.go b/vendor/go.uber.org/zap/zapcore/buffered_write_syncer.go index a40e93b3e..4b426a564 100644 --- a/vendor/go.uber.org/zap/zapcore/buffered_write_syncer.go +++ b/vendor/go.uber.org/zap/zapcore/buffered_write_syncer.go @@ -188,32 +188,33 @@ func (s *BufferedWriteSyncer) flushLoop() { // Stop closes the buffer, cleans up background goroutines, and flushes // remaining unwritten data. func (s *BufferedWriteSyncer) Stop() (err error) { - var stopped bool - // Critical section. - func() { + stopped := func() bool { s.mu.Lock() defer s.mu.Unlock() if !s.initialized { - return + return false } - stopped = s.stopped - if stopped { - return + if s.stopped { + return false } s.stopped = true s.ticker.Stop() close(s.stop) // tell flushLoop to stop - <-s.done // and wait until it has + return true }() - // Don't call Sync on consecutive Stops. + // Not initialized, or already stopped, no need for any cleanup. if !stopped { - err = s.Sync() + return } - return err + // Wait for flushLoop to end outside of the lock, as it may need the lock to complete. + // See https://github.com/uber-go/zap/issues/1428 for details. + <-s.done + + return s.Sync() } diff --git a/vendor/go.uber.org/zap/zapcore/console_encoder.go b/vendor/go.uber.org/zap/zapcore/console_encoder.go index cc2b4e07b..98eea5154 100644 --- a/vendor/go.uber.org/zap/zapcore/console_encoder.go +++ b/vendor/go.uber.org/zap/zapcore/console_encoder.go @@ -105,7 +105,7 @@ func (c consoleEncoder) EncodeEntry(ent Entry, fields []Field) (*buffer.Buffer, if i > 0 { line.AppendString(c.ConsoleSeparator) } - fmt.Fprint(line, arr.elems[i]) + _, _ = fmt.Fprint(line, arr.elems[i]) } putSliceEncoder(arr) diff --git a/vendor/go.uber.org/zap/zapcore/entry.go b/vendor/go.uber.org/zap/zapcore/entry.go index 459a5d7ce..841752f2e 100644 --- a/vendor/go.uber.org/zap/zapcore/entry.go +++ b/vendor/go.uber.org/zap/zapcore/entry.go @@ -241,7 +241,12 @@ func (ce *CheckedEntry) Write(fields ...Field) { // If the entry is dirty, log an internal error; because the // CheckedEntry is being used after it was returned to the pool, // the message may be an amalgamation from multiple call sites. - fmt.Fprintf(ce.ErrorOutput, "%v Unsafe CheckedEntry re-use near Entry %+v.\n", ce.Time, ce.Entry) + _, _ = fmt.Fprintf( + ce.ErrorOutput, + "%v Unsafe CheckedEntry re-use near Entry %+v.\n", + ce.Time, + ce.Entry, + ) _ = ce.ErrorOutput.Sync() // ignore error } return @@ -253,7 +258,12 @@ func (ce *CheckedEntry) Write(fields ...Field) { err = multierr.Append(err, ce.cores[i].Write(ce.Entry, fields)) } if err != nil && ce.ErrorOutput != nil { - fmt.Fprintf(ce.ErrorOutput, "%v write error: %v\n", ce.Time, err) + _, _ = fmt.Fprintf( + ce.ErrorOutput, + "%v write error: %v\n", + ce.Time, + err, + ) _ = ce.ErrorOutput.Sync() // ignore error } diff --git a/vendor/go.uber.org/zap/zapcore/lazy_with.go b/vendor/go.uber.org/zap/zapcore/lazy_with.go index 05288d6a8..500809de0 100644 --- a/vendor/go.uber.org/zap/zapcore/lazy_with.go +++ b/vendor/go.uber.org/zap/zapcore/lazy_with.go @@ -23,7 +23,8 @@ package zapcore import "sync" type lazyWithCore struct { - Core + core Core + originalCore Core sync.Once fields []Field } @@ -32,23 +33,45 @@ type lazyWithCore struct { // the logger is written to (or is further chained in a lon-lazy manner). func NewLazyWith(core Core, fields []Field) Core { return &lazyWithCore{ - Core: core, - fields: fields, + core: nil, // core is allocated once `initOnce` is called. + originalCore: core, + fields: fields, } } func (d *lazyWithCore) initOnce() { d.Once.Do(func() { - d.Core = d.Core.With(d.fields) + d.core = d.originalCore.With(d.fields) }) } func (d *lazyWithCore) With(fields []Field) Core { d.initOnce() - return d.Core.With(fields) + return d.core.With(fields) } func (d *lazyWithCore) Check(e Entry, ce *CheckedEntry) *CheckedEntry { + // This is safe because `lazyWithCore` doesn't change the level. + // So we can delagate the level check, any not `initOnce` + // just for the check. + if !d.originalCore.Enabled(e.Level) { + return ce + } + d.initOnce() + return d.core.Check(e, ce) +} + +func (d *lazyWithCore) Enabled(level Level) bool { + // Like above, this is safe because `lazyWithCore` doesn't change the level. + return d.originalCore.Enabled(level) +} + +func (d *lazyWithCore) Write(e Entry, fields []Field) error { + d.initOnce() + return d.core.Write(e, fields) +} + +func (d *lazyWithCore) Sync() error { d.initOnce() - return d.Core.Check(e, ce) + return d.core.Sync() } diff --git a/vendor/go.uber.org/zap/zapcore/level.go b/vendor/go.uber.org/zap/zapcore/level.go index e01a24131..f3e166d67 100644 --- a/vendor/go.uber.org/zap/zapcore/level.go +++ b/vendor/go.uber.org/zap/zapcore/level.go @@ -179,19 +179,19 @@ func (l *Level) UnmarshalText(text []byte) error { func (l *Level) unmarshalText(text []byte) bool { switch string(text) { - case "debug", "DEBUG": + case "debug": *l = DebugLevel - case "info", "INFO", "": // make the zero value useful + case "info", "": // make the zero value useful *l = InfoLevel - case "warn", "WARN": + case "warn", "warning": *l = WarnLevel - case "error", "ERROR": + case "error": *l = ErrorLevel - case "dpanic", "DPANIC": + case "dpanic": *l = DPanicLevel - case "panic", "PANIC": + case "panic": *l = PanicLevel - case "fatal", "FATAL": + case "fatal": *l = FatalLevel default: return false diff --git a/vendor/modules.txt b/vendor/modules.txt index 0c4e7f7e5..267e50839 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -125,8 +125,8 @@ github.com/ProtonMail/go-crypto/openpgp/packet github.com/ProtonMail/go-crypto/openpgp/s2k github.com/ProtonMail/go-crypto/openpgp/x25519 github.com/ProtonMail/go-crypto/openpgp/x448 -# github.com/argoproj-labs/argocd-operator v0.17.0 -## explicit; go 1.24.6 +# github.com/argoproj-labs/argocd-operator v0.18.0 +## explicit; go 1.25.9 github.com/argoproj-labs/argocd-operator/api/v1beta1 github.com/argoproj-labs/argocd-operator/common # github.com/argoproj/argo-cd/v3 v3.3.10 @@ -164,7 +164,7 @@ github.com/argoproj/argo-cd/v3/util/regex github.com/argoproj/argo-cd/v3/util/security github.com/argoproj/argo-cd/v3/util/versions github.com/argoproj/argo-cd/v3/util/workloadidentity -# github.com/argoproj/gitops-engine v0.7.1-0.20250908182407-97ad5b59a627 +# github.com/argoproj/gitops-engine v0.7.1-0.20251217140045-5baed5604d2d ## explicit; go 1.24.0 github.com/argoproj/gitops-engine/internal/kubernetes_vendor/pkg/api/v1/endpoints github.com/argoproj/gitops-engine/internal/kubernetes_vendor/pkg/util/hash @@ -194,7 +194,7 @@ github.com/beorn7/perks/quantile # github.com/blang/semver/v4 v4.0.0 ## explicit; go 1.14 github.com/blang/semver/v4 -# github.com/bmatcuk/doublestar/v4 v4.9.1 +# github.com/bmatcuk/doublestar/v4 v4.10.0 ## explicit; go 1.16 github.com/bmatcuk/doublestar/v4 # github.com/bmizerany/assert v0.0.0-20160611221934-b7ed37b82869 @@ -761,7 +761,7 @@ github.com/segmentio/analytics-go/v3 # github.com/segmentio/backo-go v1.0.0 ## explicit github.com/segmentio/backo-go -# github.com/sergi/go-diff v1.3.2-0.20230802210424-5b0b94c5c0d3 +# github.com/sergi/go-diff v1.4.0 ## explicit; go 1.13 github.com/sergi/go-diff/diffmatchpatch # github.com/shopspring/decimal v1.4.0 @@ -826,7 +826,7 @@ go.uber.org/mock/gomock # go.uber.org/multierr v1.11.0 ## explicit; go 1.19 go.uber.org/multierr -# go.uber.org/zap v1.27.0 +# go.uber.org/zap v1.27.1 ## explicit; go 1.19 go.uber.org/zap go.uber.org/zap/buffer @@ -1797,7 +1797,7 @@ oras.land/oras-go/v2/registry/remote/credentials/trace oras.land/oras-go/v2/registry/remote/errcode oras.land/oras-go/v2/registry/remote/internal/errutil oras.land/oras-go/v2/registry/remote/retry -# sigs.k8s.io/controller-runtime v0.21.0 +# sigs.k8s.io/controller-runtime v0.22.3 ## explicit; go 1.24.0 sigs.k8s.io/controller-runtime sigs.k8s.io/controller-runtime/pkg/builder @@ -1851,6 +1851,7 @@ sigs.k8s.io/controller-runtime/pkg/webhook sigs.k8s.io/controller-runtime/pkg/webhook/admission sigs.k8s.io/controller-runtime/pkg/webhook/admission/metrics sigs.k8s.io/controller-runtime/pkg/webhook/conversion +sigs.k8s.io/controller-runtime/pkg/webhook/conversion/metrics sigs.k8s.io/controller-runtime/pkg/webhook/internal/metrics # sigs.k8s.io/controller-runtime/tools/setup-envtest v0.0.0-20250308055145-5fe7bb3edc86 ## explicit; go 1.22.0 @@ -1880,8 +1881,8 @@ sigs.k8s.io/controller-tools/pkg/webhook ## explicit; go 1.23 sigs.k8s.io/json sigs.k8s.io/json/internal/golang/encoding/json -# sigs.k8s.io/kustomize/api v0.20.1 -## explicit; go 1.22.7 +# sigs.k8s.io/kustomize/api v0.21.0 +## explicit; go 1.24.0 sigs.k8s.io/kustomize/api/filters/annotations sigs.k8s.io/kustomize/api/filters/fieldspec sigs.k8s.io/kustomize/api/filters/filtersutil @@ -1926,8 +1927,8 @@ sigs.k8s.io/kustomize/api/provider sigs.k8s.io/kustomize/api/resmap sigs.k8s.io/kustomize/api/resource sigs.k8s.io/kustomize/api/types -# sigs.k8s.io/kustomize/kyaml v0.20.1 -## explicit; go 1.22.7 +# sigs.k8s.io/kustomize/kyaml v0.21.0 +## explicit; go 1.24.0 sigs.k8s.io/kustomize/kyaml/comments sigs.k8s.io/kustomize/kyaml/errors sigs.k8s.io/kustomize/kyaml/ext diff --git a/vendor/sigs.k8s.io/controller-runtime/.golangci.yml b/vendor/sigs.k8s.io/controller-runtime/.golangci.yml index 7390d2024..1741432a0 100644 --- a/vendor/sigs.k8s.io/controller-runtime/.golangci.yml +++ b/vendor/sigs.k8s.io/controller-runtime/.golangci.yml @@ -17,6 +17,7 @@ linters: - errchkjson - errorlint - exhaustive + - forbidigo - ginkgolinter - goconst - gocritic @@ -39,6 +40,12 @@ linters: - unused - whitespace settings: + forbidigo: + forbid: + - pattern: context.Background + msg: Use ginkgos SpecContext or go testings t.Context instead + - pattern: context.TODO + msg: Use ginkgos SpecContext or go testings t.Context instead govet: disable: - fieldalignment @@ -94,6 +101,9 @@ linters: - zz_generated.*\.go$ - .*conversion.*\.go$ rules: + - linters: + - forbidigo + path-except: _test\.go - linters: - gosec text: 'G108: Profiling endpoint is automatically exposed on /debug/pprof' diff --git a/vendor/sigs.k8s.io/controller-runtime/OWNERS_ALIASES b/vendor/sigs.k8s.io/controller-runtime/OWNERS_ALIASES index 5f5b2b66d..47bf6eedf 100644 --- a/vendor/sigs.k8s.io/controller-runtime/OWNERS_ALIASES +++ b/vendor/sigs.k8s.io/controller-runtime/OWNERS_ALIASES @@ -4,8 +4,10 @@ aliases: # active folks who can be contacted to perform admin-related # tasks on the repo, or otherwise approve any PRS. controller-runtime-admins: - - vincepri + - alvaroaleman - joelanford + - sbueringer + - vincepri # non-admin folks who have write-access and can approve any PRs in the repo controller-runtime-maintainers: diff --git a/vendor/sigs.k8s.io/controller-runtime/README.md b/vendor/sigs.k8s.io/controller-runtime/README.md index 20f7fd817..54bacad42 100644 --- a/vendor/sigs.k8s.io/controller-runtime/README.md +++ b/vendor/sigs.k8s.io/controller-runtime/README.md @@ -25,9 +25,9 @@ The full documentation can be found at [VERSIONING.md](VERSIONING.md), but TL;DR Users: -- We follow [Semantic Versioning (semver)](https://semver.org) -- Use releases with your dependency management to ensure that you get compatible code -- The main branch contains all the latest code, some of which may break compatibility (so "normal" `go get` is not recommended) +- We stick to a zero major version +- We publish a minor version for each Kubernetes minor release and allow breaking changes between minor versions +- We publish patch versions as needed and we don't allow breaking changes in them Contributors: diff --git a/vendor/sigs.k8s.io/controller-runtime/VERSIONING.md b/vendor/sigs.k8s.io/controller-runtime/VERSIONING.md index 2c0f2f9b2..7ad6b142c 100644 --- a/vendor/sigs.k8s.io/controller-runtime/VERSIONING.md +++ b/vendor/sigs.k8s.io/controller-runtime/VERSIONING.md @@ -7,6 +7,16 @@ For the purposes of the aforementioned guidelines, controller-runtime counts as a "library project", but otherwise follows the guidelines exactly. +We stick to a major version of zero and create a minor version for +each Kubernetes minor version and we allow breaking changes in our +minor versions. We create patch releases as needed and don't allow +breaking changes in them. + +Publishing a non-zero major version is pointless for us, as the k8s.io/* +libraries we heavily depend on do breaking changes but use the same +versioning scheme as described above. Consequently, a project can only +ever depend on one controller-runtime version. + [guidelines]: https://sigs.k8s.io/kubebuilder-release-tools/VERSIONING.md ## Compatibility and Release Support diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/builder/webhook.go b/vendor/sigs.k8s.io/controller-runtime/pkg/builder/webhook.go index 8ec6d58fd..6263f030a 100644 --- a/vendor/sigs.k8s.io/controller-runtime/pkg/builder/webhook.go +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/builder/webhook.go @@ -98,6 +98,7 @@ func (blder *WebhookBuilder) RecoverPanic(recoverPanic bool) *WebhookBuilder { } // WithCustomPath overrides the webhook's default path by the customPath +// // Deprecated: WithCustomPath should not be used anymore. // Please use WithValidatorCustomPath or WithDefaulterCustomPath instead. func (blder *WebhookBuilder) WithCustomPath(customPath string) *WebhookBuilder { diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/cache/cache.go b/vendor/sigs.k8s.io/controller-runtime/pkg/cache/cache.go index 648d0d75b..a7e491855 100644 --- a/vendor/sigs.k8s.io/controller-runtime/pkg/cache/cache.go +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/cache/cache.go @@ -172,6 +172,15 @@ type Options struct { // is "done" with an object, and would otherwise not requeue it, i.e., we // recommend the `Reconcile` function return `reconcile.Result{RequeueAfter: t}`, // instead of `reconcile.Result{}`. + // + // SyncPeriod will locally trigger an artificial Update event with the same + // object in both ObjectOld and ObjectNew for everything that is in the + // cache. + // + // Predicates or Handlers that expect ObjectOld and ObjectNew to be different + // (such as GenerationChangedPredicate) will filter out this event, preventing + // it from triggering a reconciliation. + // SyncPeriod does not sync between the local cache and the server. SyncPeriod *time.Duration // ReaderFailOnMissingInformer configures the cache to return a ErrResourceNotCached error when a user diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/cache/internal/cache_reader.go b/vendor/sigs.k8s.io/controller-runtime/pkg/cache/internal/cache_reader.go index 33ce8a830..eb6b54485 100644 --- a/vendor/sigs.k8s.io/controller-runtime/pkg/cache/internal/cache_reader.go +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/cache/internal/cache_reader.go @@ -54,7 +54,10 @@ type CacheReader struct { } // Get checks the indexer for the object and writes a copy of it if found. -func (c *CacheReader) Get(_ context.Context, key client.ObjectKey, out client.Object, _ ...client.GetOption) error { +func (c *CacheReader) Get(_ context.Context, key client.ObjectKey, out client.Object, opts ...client.GetOption) error { + getOpts := client.GetOptions{} + getOpts.ApplyOptions(opts) + if c.scopeName == apimeta.RESTScopeNameRoot { key.Namespace = "" } @@ -81,7 +84,7 @@ func (c *CacheReader) Get(_ context.Context, key client.ObjectKey, out client.Ob return fmt.Errorf("cache contained %T, which is not an Object", obj) } - if c.disableDeepCopy { + if c.disableDeepCopy || (getOpts.UnsafeDisableDeepCopy != nil && *getOpts.UnsafeDisableDeepCopy) { // skip deep copy which might be unsafe // you must DeepCopy any object before mutating it outside } else { @@ -97,7 +100,7 @@ func (c *CacheReader) Get(_ context.Context, key client.ObjectKey, out client.Ob return fmt.Errorf("cache had type %s, but %s was asked for", objVal.Type(), outVal.Type()) } reflect.Indirect(outVal).Set(reflect.Indirect(objVal)) - if !c.disableDeepCopy { + if !c.disableDeepCopy && (getOpts.UnsafeDisableDeepCopy == nil || !*getOpts.UnsafeDisableDeepCopy) { out.GetObjectKind().SetGroupVersionKind(c.groupVersionKind) } diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/cache/internal/informers.go b/vendor/sigs.k8s.io/controller-runtime/pkg/cache/internal/informers.go index 4bf832b2d..f216be0d9 100644 --- a/vendor/sigs.k8s.io/controller-runtime/pkg/cache/internal/informers.go +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/cache/internal/informers.go @@ -518,7 +518,7 @@ func (ip *Informers) makeListWatcher(gvk schema.GroupVersionKind, obj runtime.Ob // Structured. // default: - client, err := apiutil.RESTClientForGVK(gvk, false, ip.config, ip.codecs, ip.httpClient) + client, err := apiutil.RESTClientForGVK(gvk, false, false, ip.config, ip.codecs, ip.httpClient) if err != nil { return nil, err } diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/certwatcher/certwatcher.go b/vendor/sigs.k8s.io/controller-runtime/pkg/certwatcher/certwatcher.go index c32324098..2362d020b 100644 --- a/vendor/sigs.k8s.io/controller-runtime/pkg/certwatcher/certwatcher.go +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/certwatcher/certwatcher.go @@ -26,6 +26,7 @@ import ( "time" "github.com/fsnotify/fsnotify" + "github.com/go-logr/logr" kerrors "k8s.io/apimachinery/pkg/util/errors" "k8s.io/apimachinery/pkg/util/sets" "k8s.io/apimachinery/pkg/util/wait" @@ -47,6 +48,7 @@ type CertWatcher struct { currentCert *tls.Certificate watcher *fsnotify.Watcher interval time.Duration + log logr.Logger certPath string keyPath string @@ -65,6 +67,7 @@ func New(certPath, keyPath string) (*CertWatcher, error) { certPath: certPath, keyPath: keyPath, interval: defaultWatchInterval, + log: log.WithValues("cert", certPath, "key", keyPath), } // Initial read of certificate and key. @@ -130,14 +133,14 @@ func (cw *CertWatcher) Start(ctx context.Context) error { ticker := time.NewTicker(cw.interval) defer ticker.Stop() - log.Info("Starting certificate poll+watcher", "interval", cw.interval) + cw.log.Info("Starting certificate poll+watcher", "interval", cw.interval) for { select { case <-ctx.Done(): return cw.watcher.Close() case <-ticker.C: if err := cw.ReadCertificate(); err != nil { - log.Error(err, "failed read certificate") + cw.log.Error(err, "failed read certificate") } } } @@ -160,7 +163,7 @@ func (cw *CertWatcher) Watch() { return } - log.Error(err, "certificate watch error") + cw.log.Error(err, "certificate watch error") } } } @@ -174,7 +177,7 @@ func (cw *CertWatcher) updateCachedCertificate(cert *tls.Certificate, keyPEMBloc if cw.currentCert != nil && bytes.Equal(cw.currentCert.Certificate[0], cert.Certificate[0]) && bytes.Equal(cw.cachedKeyPEMBlock, keyPEMBlock) { - log.V(7).Info("certificate already cached") + cw.log.V(7).Info("certificate already cached") return false } cw.currentCert = cert @@ -208,7 +211,7 @@ func (cw *CertWatcher) ReadCertificate() error { return nil } - log.Info("Updated current TLS certificate") + cw.log.Info("Updated current TLS certificate") // If a callback is registered, invoke it with the new certificate. cw.RLock() @@ -229,14 +232,20 @@ func (cw *CertWatcher) handleEvent(event fsnotify.Event) { case event.Op.Has(fsnotify.Chmod), event.Op.Has(fsnotify.Remove): // If the file was removed or renamed, re-add the watch to the previous name if err := cw.watcher.Add(event.Name); err != nil { - log.Error(err, "error re-watching file") + cw.log.Error(err, "error re-watching file") } default: return } - log.V(1).Info("certificate event", "event", event) + cw.log.V(1).Info("certificate event", "event", event) if err := cw.ReadCertificate(); err != nil { - log.Error(err, "error re-reading certificate") + cw.log.Error(err, "error re-reading certificate") } } + +// NeedLeaderElection indicates that the cert-manager +// does not need leader election. +func (cw *CertWatcher) NeedLeaderElection() bool { + return false +} diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/client/apiutil/apimachinery.go b/vendor/sigs.k8s.io/controller-runtime/pkg/client/apiutil/apimachinery.go index 1d4ce264c..b132cb2d4 100644 --- a/vendor/sigs.k8s.io/controller-runtime/pkg/client/apiutil/apimachinery.go +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/client/apiutil/apimachinery.go @@ -161,15 +161,27 @@ func GVKForObject(obj runtime.Object, scheme *runtime.Scheme) (schema.GroupVersi // RESTClientForGVK constructs a new rest.Interface capable of accessing the resource associated // with the given GroupVersionKind. The REST client will be configured to use the negotiated serializer from // baseConfig, if set, otherwise a default serializer will be set. -func RESTClientForGVK(gvk schema.GroupVersionKind, isUnstructured bool, baseConfig *rest.Config, codecs serializer.CodecFactory, httpClient *http.Client) (rest.Interface, error) { +func RESTClientForGVK( + gvk schema.GroupVersionKind, + forceDisableProtoBuf bool, + isUnstructured bool, + baseConfig *rest.Config, + codecs serializer.CodecFactory, + httpClient *http.Client, +) (rest.Interface, error) { if httpClient == nil { return nil, fmt.Errorf("httpClient must not be nil, consider using rest.HTTPClientFor(c) to create a client") } - return rest.RESTClientForConfigAndClient(createRestConfig(gvk, isUnstructured, baseConfig, codecs), httpClient) + return rest.RESTClientForConfigAndClient(createRestConfig(gvk, forceDisableProtoBuf, isUnstructured, baseConfig, codecs), httpClient) } // createRestConfig copies the base config and updates needed fields for a new rest config. -func createRestConfig(gvk schema.GroupVersionKind, isUnstructured bool, baseConfig *rest.Config, codecs serializer.CodecFactory) *rest.Config { +func createRestConfig(gvk schema.GroupVersionKind, + forceDisableProtoBuf bool, + isUnstructured bool, + baseConfig *rest.Config, + codecs serializer.CodecFactory, +) *rest.Config { gv := gvk.GroupVersion() cfg := rest.CopyConfig(baseConfig) @@ -183,7 +195,7 @@ func createRestConfig(gvk schema.GroupVersionKind, isUnstructured bool, baseConf cfg.UserAgent = rest.DefaultKubernetesUserAgent() } // TODO(FillZpp): In the long run, we want to check discovery or something to make sure that this is actually true. - if cfg.ContentType == "" && !isUnstructured { + if cfg.ContentType == "" && !forceDisableProtoBuf { protobufSchemeLock.RLock() if protobufScheme.Recognizes(gvk) { cfg.ContentType = runtime.ContentTypeProtobuf diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/client/applyconfigurations.go b/vendor/sigs.k8s.io/controller-runtime/pkg/client/applyconfigurations.go new file mode 100644 index 000000000..97192050f --- /dev/null +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/client/applyconfigurations.go @@ -0,0 +1,75 @@ +/* +Copyright 2025 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package client + +import ( + "fmt" + + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/utils/ptr" +) + +type unstructuredApplyConfiguration struct { + *unstructured.Unstructured +} + +func (u *unstructuredApplyConfiguration) IsApplyConfiguration() {} + +// ApplyConfigurationFromUnstructured creates a runtime.ApplyConfiguration from an *unstructured.Unstructured object. +// +// Do not use Unstructured objects here that were generated from API objects, as its impossible to tell +// if a zero value was explicitly set. +func ApplyConfigurationFromUnstructured(u *unstructured.Unstructured) runtime.ApplyConfiguration { + return &unstructuredApplyConfiguration{Unstructured: u} +} + +type applyconfigurationRuntimeObject struct { + runtime.ApplyConfiguration +} + +func (a *applyconfigurationRuntimeObject) GetObjectKind() schema.ObjectKind { + return a +} + +func (a *applyconfigurationRuntimeObject) GroupVersionKind() schema.GroupVersionKind { + return schema.GroupVersionKind{} +} + +func (a *applyconfigurationRuntimeObject) SetGroupVersionKind(gvk schema.GroupVersionKind) {} + +func (a *applyconfigurationRuntimeObject) DeepCopyObject() runtime.Object { + panic("applyconfigurationRuntimeObject does not support DeepCopyObject") +} + +func runtimeObjectFromApplyConfiguration(ac runtime.ApplyConfiguration) runtime.Object { + return &applyconfigurationRuntimeObject{ApplyConfiguration: ac} +} + +func gvkFromApplyConfiguration(ac applyConfiguration) (schema.GroupVersionKind, error) { + var gvk schema.GroupVersionKind + gv, err := schema.ParseGroupVersion(ptr.Deref(ac.GetAPIVersion(), "")) + if err != nil { + return gvk, fmt.Errorf("failed to parse %q as GroupVersion: %w", ptr.Deref(ac.GetAPIVersion(), ""), err) + } + gvk.Group = gv.Group + gvk.Version = gv.Version + gvk.Kind = ptr.Deref(ac.GetKind(), "") + + return gvk, nil +} diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/client/client.go b/vendor/sigs.k8s.io/controller-runtime/pkg/client/client.go index 50b0ebf33..e9f731453 100644 --- a/vendor/sigs.k8s.io/controller-runtime/pkg/client/client.go +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/client/client.go @@ -151,8 +151,7 @@ func newClient(config *rest.Config, options Options) (*client, error) { mapper: options.Mapper, codecs: serializer.NewCodecFactory(options.Scheme), - structuredResourceByType: make(map[schema.GroupVersionKind]*resourceMeta), - unstructuredResourceByType: make(map[schema.GroupVersionKind]*resourceMeta), + resourceByType: make(map[cacheKey]*resourceMeta), } rawMetaClient, err := metadata.NewForConfigAndClient(metadata.ConfigFor(config), options.HTTPClient) @@ -329,6 +328,16 @@ func (c *client) Patch(ctx context.Context, obj Object, patch Patch, opts ...Pat } } +func (c *client) Apply(ctx context.Context, obj runtime.ApplyConfiguration, opts ...ApplyOption) error { + switch obj := obj.(type) { + case *unstructuredApplyConfiguration: + defer c.resetGroupVersionKind(obj, obj.GetObjectKind().GroupVersionKind()) + return c.unstructuredClient.Apply(ctx, obj, opts...) + default: + return c.typedClient.Apply(ctx, obj, opts...) + } +} + // Get implements client.Client. func (c *client) Get(ctx context.Context, key ObjectKey, obj Object, opts ...GetOption) error { if isUncached, err := c.shouldBypassCache(obj); err != nil { diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/client/client_rest_resources.go b/vendor/sigs.k8s.io/controller-runtime/pkg/client/client_rest_resources.go index 2d0787952..d75d685cb 100644 --- a/vendor/sigs.k8s.io/controller-runtime/pkg/client/client_rest_resources.go +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/client/client_rest_resources.go @@ -17,16 +17,17 @@ limitations under the License. package client import ( + "fmt" "net/http" "strings" "sync" "k8s.io/apimachinery/pkg/api/meta" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/runtime/serializer" "k8s.io/client-go/rest" + "k8s.io/utils/ptr" "sigs.k8s.io/controller-runtime/pkg/client/apiutil" ) @@ -47,22 +48,30 @@ type clientRestResources struct { // codecs are used to create a REST client for a gvk codecs serializer.CodecFactory - // structuredResourceByType stores structured type metadata - structuredResourceByType map[schema.GroupVersionKind]*resourceMeta - // unstructuredResourceByType stores unstructured type metadata - unstructuredResourceByType map[schema.GroupVersionKind]*resourceMeta - mu sync.RWMutex + // resourceByType stores type metadata + resourceByType map[cacheKey]*resourceMeta + + mu sync.RWMutex +} + +type cacheKey struct { + gvk schema.GroupVersionKind + forceDisableProtoBuf bool } // newResource maps obj to a Kubernetes Resource and constructs a client for that Resource. // If the object is a list, the resource represents the item's type instead. -func (c *clientRestResources) newResource(gvk schema.GroupVersionKind, isList, isUnstructured bool) (*resourceMeta, error) { +func (c *clientRestResources) newResource(gvk schema.GroupVersionKind, + isList bool, + forceDisableProtoBuf bool, + isUnstructured bool, +) (*resourceMeta, error) { if strings.HasSuffix(gvk.Kind, "List") && isList { // if this was a list, treat it as a request for the item's resource gvk.Kind = gvk.Kind[:len(gvk.Kind)-4] } - client, err := apiutil.RESTClientForGVK(gvk, isUnstructured, c.config, c.codecs, c.httpClient) + client, err := apiutil.RESTClientForGVK(gvk, forceDisableProtoBuf, isUnstructured, c.config, c.codecs, c.httpClient) if err != nil { return nil, err } @@ -73,52 +82,96 @@ func (c *clientRestResources) newResource(gvk schema.GroupVersionKind, isList, i return &resourceMeta{Interface: client, mapping: mapping, gvk: gvk}, nil } +type applyConfiguration interface { + GetName() *string + GetNamespace() *string + GetKind() *string + GetAPIVersion() *string +} + // getResource returns the resource meta information for the given type of object. // If the object is a list, the resource represents the item's type instead. -func (c *clientRestResources) getResource(obj runtime.Object) (*resourceMeta, error) { - gvk, err := apiutil.GVKForObject(obj, c.scheme) - if err != nil { - return nil, err +func (c *clientRestResources) getResource(obj any) (*resourceMeta, error) { + var gvk schema.GroupVersionKind + var err error + var isApplyConfiguration bool + switch o := obj.(type) { + case runtime.Object: + gvk, err = apiutil.GVKForObject(o, c.scheme) + if err != nil { + return nil, err + } + case runtime.ApplyConfiguration: + ac, ok := o.(applyConfiguration) + if !ok { + return nil, fmt.Errorf("%T is a runtime.ApplyConfiguration but not an applyConfiguration", o) + } + gvk, err = gvkFromApplyConfiguration(ac) + if err != nil { + return nil, err + } + isApplyConfiguration = true + default: + return nil, fmt.Errorf("bug: %T is neither a runtime.Object nor a runtime.ApplyConfiguration", o) } _, isUnstructured := obj.(runtime.Unstructured) + forceDisableProtoBuf := isUnstructured || isApplyConfiguration // It's better to do creation work twice than to not let multiple // people make requests at once c.mu.RLock() - resourceByType := c.structuredResourceByType - if isUnstructured { - resourceByType = c.unstructuredResourceByType - } - r, known := resourceByType[gvk] + + cacheKey := cacheKey{gvk: gvk, forceDisableProtoBuf: forceDisableProtoBuf} + + r, known := c.resourceByType[cacheKey] + c.mu.RUnlock() if known { return r, nil } + var isList bool + if runtimeObject, ok := obj.(runtime.Object); ok && meta.IsListType(runtimeObject) { + isList = true + } + // Initialize a new Client c.mu.Lock() defer c.mu.Unlock() - r, err = c.newResource(gvk, meta.IsListType(obj), isUnstructured) + r, err = c.newResource(gvk, isList, forceDisableProtoBuf, isUnstructured) if err != nil { return nil, err } - resourceByType[gvk] = r + c.resourceByType[cacheKey] = r return r, err } // getObjMeta returns objMeta containing both type and object metadata and state. -func (c *clientRestResources) getObjMeta(obj runtime.Object) (*objMeta, error) { +func (c *clientRestResources) getObjMeta(obj any) (*objMeta, error) { r, err := c.getResource(obj) if err != nil { return nil, err } - m, err := meta.Accessor(obj) - if err != nil { - return nil, err + objMeta := &objMeta{resourceMeta: r} + + switch o := obj.(type) { + case runtime.Object: + m, err := meta.Accessor(obj) + if err != nil { + return nil, err + } + objMeta.namespace = m.GetNamespace() + objMeta.name = m.GetName() + case applyConfiguration: + objMeta.namespace = ptr.Deref(o.GetNamespace(), "") + objMeta.name = ptr.Deref(o.GetName(), "") + default: + return nil, fmt.Errorf("object %T is neither a runtime.Object nor a runtime.ApplyConfiguration", obj) } - return &objMeta{resourceMeta: r, Object: m}, err + + return objMeta, nil } // resourceMeta stores state for a Kubernetes type. @@ -146,6 +199,6 @@ type objMeta struct { // resourceMeta contains type information for the object *resourceMeta - // Object contains meta data for the object instance - metav1.Object + namespace string + name string } diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/client/dryrun.go b/vendor/sigs.k8s.io/controller-runtime/pkg/client/dryrun.go index bbcdd3832..a185860d3 100644 --- a/vendor/sigs.k8s.io/controller-runtime/pkg/client/dryrun.go +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/client/dryrun.go @@ -82,6 +82,10 @@ func (c *dryRunClient) Patch(ctx context.Context, obj Object, patch Patch, opts return c.client.Patch(ctx, obj, patch, append(opts, DryRunAll)...) } +func (c *dryRunClient) Apply(ctx context.Context, obj runtime.ApplyConfiguration, opts ...ApplyOption) error { + return c.client.Apply(ctx, obj, append(opts, DryRunAll)...) +} + // Get implements client.Client. func (c *dryRunClient) Get(ctx context.Context, key ObjectKey, obj Object, opts ...GetOption) error { return c.client.Get(ctx, key, obj, opts...) diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/client/fake/client.go b/vendor/sigs.k8s.io/controller-runtime/pkg/client/fake/client.go index 16e2cba51..f88a44edd 100644 --- a/vendor/sigs.k8s.io/controller-runtime/pkg/client/fake/client.go +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/client/fake/client.go @@ -41,6 +41,7 @@ import ( https://github.com/kubernetes/kubernetes/pull/120326 (v5.6.0+incompatible missing a critical fix) */ + jsonpatch "gopkg.in/evanphx/json-patch.v4" appsv1 "k8s.io/api/apps/v1" authenticationv1 "k8s.io/api/authentication/v1" @@ -52,17 +53,21 @@ import ( "k8s.io/apimachinery/pkg/api/meta" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/apis/meta/v1/validation" "k8s.io/apimachinery/pkg/fields" "k8s.io/apimachinery/pkg/labels" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/apimachinery/pkg/runtime/serializer" "k8s.io/apimachinery/pkg/types" "k8s.io/apimachinery/pkg/util/json" + "k8s.io/apimachinery/pkg/util/managedfields" utilrand "k8s.io/apimachinery/pkg/util/rand" "k8s.io/apimachinery/pkg/util/sets" "k8s.io/apimachinery/pkg/util/strategicpatch" "k8s.io/apimachinery/pkg/util/validation/field" "k8s.io/apimachinery/pkg/watch" + clientgoapplyconfigurations "k8s.io/client-go/applyconfigurations" "k8s.io/client-go/kubernetes/scheme" "k8s.io/client-go/testing" "k8s.io/utils/ptr" @@ -76,8 +81,9 @@ import ( type versionedTracker struct { testing.ObjectTracker - scheme *runtime.Scheme - withStatusSubresource sets.Set[schema.GroupVersionKind] + scheme *runtime.Scheme + withStatusSubresource sets.Set[schema.GroupVersionKind] + usesFieldManagedObjectTracker bool } type fakeClient struct { @@ -98,6 +104,8 @@ type fakeClient struct { indexes map[schema.GroupVersionKind]map[string]client.IndexerFunc // indexesLock must be held when accessing indexes. indexesLock sync.RWMutex + + returnManagedFields bool } var _ client.WithWatch = &fakeClient{} @@ -131,6 +139,9 @@ type ClientBuilder struct { withStatusSubresource []client.Object objectTracker testing.ObjectTracker interceptorFuncs *interceptor.Funcs + typeConverters []managedfields.TypeConverter + returnManagedFields bool + isBuilt bool // indexes maps each GroupVersionKind (GVK) to the indexes registered for that GVK. // The inner map maps from index name to IndexerFunc. @@ -172,6 +183,8 @@ func (f *ClientBuilder) WithRuntimeObjects(initRuntimeObjs ...runtime.Object) *C } // WithObjectTracker can be optionally used to initialize this fake client with testing.ObjectTracker. +// Setting this is incompatible with setting WithTypeConverters, as they are a setting on the +// tracker. func (f *ClientBuilder) WithObjectTracker(ot testing.ObjectTracker) *ClientBuilder { f.objectTracker = ot return f @@ -228,8 +241,36 @@ func (f *ClientBuilder) WithInterceptorFuncs(interceptorFuncs interceptor.Funcs) return f } +// WithTypeConverters sets the type converters for the fake client. The list is ordered and the first +// non-erroring converter is used. A type converter must be provided for all types the client is used +// for, otherwise it will error. +// +// This setting is incompatible with WithObjectTracker, as the type converters are a setting on the tracker. +// +// If unset, this defaults to: +// * clientgoapplyconfigurations.NewTypeConverter(scheme.Scheme), +// * managedfields.NewDeducedTypeConverter(), +// +// Be aware that the behavior of the `NewDeducedTypeConverter` might not match the behavior of the +// Kubernetes APIServer, it is recommended to provide a type converter for your types. TypeConverters +// are generated along with ApplyConfigurations. +func (f *ClientBuilder) WithTypeConverters(typeConverters ...managedfields.TypeConverter) *ClientBuilder { + f.typeConverters = append(f.typeConverters, typeConverters...) + return f +} + +// WithReturnManagedFields configures the fake client to return managedFields +// on objects. +func (f *ClientBuilder) WithReturnManagedFields() *ClientBuilder { + f.returnManagedFields = true + return f +} + // Build builds and returns a new fake client. func (f *ClientBuilder) Build() client.WithWatch { + if f.isBuilt { + panic("Build() must not be called multiple times when creating a ClientBuilder") + } if f.scheme == nil { f.scheme = scheme.Scheme } @@ -237,8 +278,6 @@ func (f *ClientBuilder) Build() client.WithWatch { f.restMapper = meta.NewDefaultRESTMapper([]schema.GroupVersion{}) } - var tracker versionedTracker - withStatusSubResource := sets.New(inTreeResourcesWithStatus()...) for _, o := range f.withStatusSubresource { gvk, err := apiutil.GVKForObject(o, f.scheme) @@ -248,10 +287,36 @@ func (f *ClientBuilder) Build() client.WithWatch { withStatusSubResource.Insert(gvk) } + if f.objectTracker != nil && len(f.typeConverters) > 0 { + panic(errors.New("WithObjectTracker and WithTypeConverters are incompatible")) + } + + var usesFieldManagedObjectTracker bool if f.objectTracker == nil { - tracker = versionedTracker{ObjectTracker: testing.NewObjectTracker(f.scheme, scheme.Codecs.UniversalDecoder()), scheme: f.scheme, withStatusSubresource: withStatusSubResource} - } else { - tracker = versionedTracker{ObjectTracker: f.objectTracker, scheme: f.scheme, withStatusSubresource: withStatusSubResource} + if len(f.typeConverters) == 0 { + // Use corresponding scheme to ensure the converter error + // for types it can't handle. + clientGoScheme := runtime.NewScheme() + if err := scheme.AddToScheme(clientGoScheme); err != nil { + panic(fmt.Sprintf("failed to construct client-go scheme: %v", err)) + } + f.typeConverters = []managedfields.TypeConverter{ + clientgoapplyconfigurations.NewTypeConverter(clientGoScheme), + managedfields.NewDeducedTypeConverter(), + } + } + f.objectTracker = testing.NewFieldManagedObjectTracker( + f.scheme, + serializer.NewCodecFactory(f.scheme).UniversalDecoder(), + multiTypeConverter{upstream: f.typeConverters}, + ) + usesFieldManagedObjectTracker = true + } + tracker := versionedTracker{ + ObjectTracker: f.objectTracker, + scheme: f.scheme, + withStatusSubresource: withStatusSubResource, + usesFieldManagedObjectTracker: usesFieldManagedObjectTracker, } for _, obj := range f.initObject { @@ -276,12 +341,14 @@ func (f *ClientBuilder) Build() client.WithWatch { restMapper: f.restMapper, indexes: f.indexes, withStatusSubresource: withStatusSubResource, + returnManagedFields: f.returnManagedFields, } if f.interceptorFuncs != nil { result = interceptor.NewClient(result, *f.interceptorFuncs) } + f.isBuilt = true return result } @@ -318,6 +385,16 @@ func (t versionedTracker) Add(obj runtime.Object) error { if err != nil { return err } + + // If the fieldManager can not decode fields, it will just silently clear them. This is pretty + // much guaranteed not to be what someone that initializes a fake client with objects that + // have them set wants, so validate them here. + // Ref https://github.com/kubernetes/kubernetes/blob/a956ef4862993b825bcd524a19260192ff1da72d/staging/src/k8s.io/apimachinery/pkg/util/managedfields/internal/fieldmanager.go#L105 + if t.usesFieldManagedObjectTracker { + if err := managedfields.ValidateManagedFields(accessor.GetManagedFields()); err != nil { + return fmt.Errorf("invalid managedFields on %T: %w", obj, err) + } + } if err := t.ObjectTracker.Add(obj); err != nil { return err } @@ -332,8 +409,9 @@ func (t versionedTracker) Create(gvr schema.GroupVersionResource, obj runtime.Ob return fmt.Errorf("failed to get accessor for object: %w", err) } if accessor.GetName() == "" { + gvk, _ := apiutil.GVKForObject(obj, t.scheme) return apierrors.NewInvalid( - obj.GetObjectKind().GroupVersionKind().GroupKind(), + gvk.GroupKind(), accessor.GetName(), field.ErrorList{field.Required(field.NewPath("metadata.name"), "name is required")}) } @@ -372,6 +450,9 @@ func convertFromUnstructuredIfNecessary(s *runtime.Scheme, o runtime.Object) (ru if err != nil { return nil, fmt.Errorf("scheme recognizes %s but failed to produce an object for it: %w", gvk, err) } + if _, isTypedUnstructured := typed.(runtime.Unstructured); isTypedUnstructured { + return o, nil + } unstructuredSerialized, err := json.Marshal(u) if err != nil { @@ -394,7 +475,11 @@ func (t versionedTracker) Update(gvr schema.GroupVersionResource, obj runtime.Ob } func (t versionedTracker) update(gvr schema.GroupVersionResource, obj runtime.Object, ns string, isStatus, deleting bool, opts metav1.UpdateOptions) error { - obj, err := t.updateObject(gvr, obj, ns, isStatus, deleting, opts.DryRun) + gvk, err := apiutil.GVKForObject(obj, t.scheme) + if err != nil { + return err + } + obj, err = t.updateObject(gvr, obj, ns, isStatus, deleting, opts.DryRun) if err != nil { return err } @@ -402,6 +487,10 @@ func (t versionedTracker) update(gvr schema.GroupVersionResource, obj runtime.Ob return nil } + if u, unstructured := obj.(*unstructured.Unstructured); unstructured { + u.SetGroupVersionKind(gvk) + } + return t.ObjectTracker.Update(gvr, obj, ns, opts) } @@ -433,8 +522,9 @@ func (t versionedTracker) updateObject(gvr schema.GroupVersionResource, obj runt } if accessor.GetName() == "" { + gvk, _ := apiutil.GVKForObject(obj, t.scheme) return nil, apierrors.NewInvalid( - obj.GetObjectKind().GroupVersionKind().GroupKind(), + gvk.GroupKind(), accessor.GetName(), field.ErrorList{field.Required(field.NewPath("metadata.name"), "name is required")}) } @@ -521,42 +611,60 @@ func (t versionedTracker) updateObject(gvr schema.GroupVersionResource, obj runt } func (c *fakeClient) Get(ctx context.Context, key client.ObjectKey, obj client.Object, opts ...client.GetOption) error { + if err := c.addToSchemeIfUnknownAndUnstructuredOrPartial(obj); err != nil { + return err + } + c.schemeLock.RLock() defer c.schemeLock.RUnlock() gvr, err := getGVRFromObject(obj, c.scheme) if err != nil { return err } + gvk, err := apiutil.GVKForObject(obj, c.scheme) + if err != nil { + return err + } o, err := c.tracker.Get(gvr, key.Namespace, key.Name) if err != nil { return err } - _, isUnstructured := obj.(runtime.Unstructured) - _, isPartialObject := obj.(*metav1.PartialObjectMetadata) - - if isUnstructured || isPartialObject { - gvk, err := apiutil.GVKForObject(obj, c.scheme) - if err != nil { - return err - } - ta, err := meta.TypeAccessor(o) - if err != nil { - return err - } - ta.SetKind(gvk.Kind) - ta.SetAPIVersion(gvk.GroupVersion().String()) + ta, err := meta.TypeAccessor(o) + if err != nil { + return err } + // If the final object is unstructuctured, the json + // representation must contain GVK or the apimachinery + // json serializer will error out. + ta.SetAPIVersion(gvk.GroupVersion().String()) + ta.SetKind(gvk.Kind) + j, err := json.Marshal(o) if err != nil { return err } zero(obj) - return json.Unmarshal(j, obj) + if err := json.Unmarshal(j, obj); err != nil { + return err + } + + if !c.returnManagedFields { + obj.SetManagedFields(nil) + } + + return ensureTypeMeta(obj, gvk) } func (c *fakeClient) Watch(ctx context.Context, list client.ObjectList, opts ...client.ListOption) (watch.Interface, error) { + if err := c.addToSchemeIfUnknownAndUnstructuredOrPartial(list); err != nil { + return nil, err + } + + c.schemeLock.RLock() + defer c.schemeLock.RUnlock() + gvk, err := apiutil.GVKForObject(list, c.scheme) if err != nil { return nil, err @@ -572,6 +680,10 @@ func (c *fakeClient) Watch(ctx context.Context, list client.ObjectList, opts ... } func (c *fakeClient) List(ctx context.Context, obj client.ObjectList, opts ...client.ListOption) error { + if err := c.addToSchemeIfUnknownAndUnstructuredOrPartial(obj); err != nil { + return err + } + c.schemeLock.RLock() defer c.schemeLock.RUnlock() gvk, err := apiutil.GVKForObject(obj, c.scheme) @@ -579,11 +691,12 @@ func (c *fakeClient) List(ctx context.Context, obj client.ObjectList, opts ...cl return err } - originalKind := gvk.Kind - + originalGVK := gvk gvk.Kind = strings.TrimSuffix(gvk.Kind, "List") + listGVK := gvk + listGVK.Kind += "List" - if _, isUnstructuredList := obj.(runtime.Unstructured); isUnstructuredList && !c.scheme.Recognizes(gvk) { + if _, isUnstructuredList := obj.(runtime.Unstructured); isUnstructuredList && !c.scheme.Recognizes(listGVK) { // We need to register the ListKind with UnstructuredList: // https://github.com/kubernetes/kubernetes/blob/7b2776b89fb1be28d4e9203bdeec079be903c103/staging/src/k8s.io/client-go/dynamic/fake/simple.go#L44-L51 c.schemeLock.RUnlock() @@ -602,39 +715,34 @@ func (c *fakeClient) List(ctx context.Context, obj client.ObjectList, opts ...cl return err } - if _, isUnstructured := obj.(runtime.Unstructured); isUnstructured { - ta, err := meta.TypeAccessor(o) - if err != nil { - return err - } - ta.SetKind(originalKind) - ta.SetAPIVersion(gvk.GroupVersion().String()) - } - j, err := json.Marshal(o) if err != nil { return err } zero(obj) + if err := ensureTypeMeta(obj, originalGVK); err != nil { + return err + } objCopy := obj.DeepCopyObject().(client.ObjectList) if err := json.Unmarshal(j, objCopy); err != nil { return err } - if _, isUnstructured := obj.(runtime.Unstructured); isUnstructured { - ta, err := meta.TypeAccessor(obj) - if err != nil { - return err - } - ta.SetKind(originalKind) - ta.SetAPIVersion(gvk.GroupVersion().String()) - } - objs, err := meta.ExtractList(objCopy) if err != nil { return err } + for _, o := range objs { + if err := ensureTypeMeta(o, gvk); err != nil { + return err + } + + if !c.returnManagedFields { + o.(metav1.Object).SetManagedFields(nil) + } + } + if listOpts.LabelSelector == nil && listOpts.FieldSelector == nil { return meta.SetList(obj, objs) } @@ -741,8 +849,13 @@ func (c *fakeClient) IsObjectNamespaced(obj runtime.Object) (bool, error) { } func (c *fakeClient) Create(ctx context.Context, obj client.Object, opts ...client.CreateOption) error { + if err := c.addToSchemeIfUnknownAndUnstructuredOrPartial(obj); err != nil { + return err + } + c.schemeLock.RLock() defer c.schemeLock.RUnlock() + createOptions := &client.CreateOptions{} createOptions.ApplyOptions(opts) @@ -773,14 +886,35 @@ func (c *fakeClient) Create(ctx context.Context, obj client.Object, opts ...clie accessor.SetDeletionTimestamp(nil) } + gvk, err := apiutil.GVKForObject(obj, c.scheme) + if err != nil { + return err + } + c.trackerWriteLock.Lock() defer c.trackerWriteLock.Unlock() - return c.tracker.Create(gvr, obj, accessor.GetNamespace()) + + if err := c.tracker.Create(gvr, obj, accessor.GetNamespace(), *createOptions.AsCreateOptions()); err != nil { + // The managed fields tracker sets gvk even on errors + _ = ensureTypeMeta(obj, gvk) + return err + } + + if !c.returnManagedFields { + obj.SetManagedFields(nil) + } + + return ensureTypeMeta(obj, gvk) } func (c *fakeClient) Delete(ctx context.Context, obj client.Object, opts ...client.DeleteOption) error { + if err := c.addToSchemeIfUnknownAndUnstructuredOrPartial(obj); err != nil { + return err + } + c.schemeLock.RLock() defer c.schemeLock.RUnlock() + gvr, err := getGVRFromObject(obj, c.scheme) if err != nil { return err @@ -826,8 +960,13 @@ func (c *fakeClient) Delete(ctx context.Context, obj client.Object, opts ...clie } func (c *fakeClient) DeleteAllOf(ctx context.Context, obj client.Object, opts ...client.DeleteAllOfOption) error { + if err := c.addToSchemeIfUnknownAndUnstructuredOrPartial(obj); err != nil { + return err + } + c.schemeLock.RLock() defer c.schemeLock.RUnlock() + gvk, err := apiutil.GVKForObject(obj, c.scheme) if err != nil { return err @@ -877,8 +1016,13 @@ func (c *fakeClient) Update(ctx context.Context, obj client.Object, opts ...clie } func (c *fakeClient) update(obj client.Object, isStatus bool, opts ...client.UpdateOption) error { + if err := c.addToSchemeIfUnknownAndUnstructuredOrPartial(obj); err != nil { + return err + } + c.schemeLock.RLock() defer c.schemeLock.RUnlock() + updateOptions := &client.UpdateOptions{} updateOptions.ApplyOptions(opts) @@ -892,6 +1036,10 @@ func (c *fakeClient) update(obj client.Object, isStatus bool, opts ...client.Upd if err != nil { return err } + gvk, err := apiutil.GVKForObject(obj, c.scheme) + if err != nil { + return err + } accessor, err := meta.Accessor(obj) if err != nil { return err @@ -899,19 +1047,100 @@ func (c *fakeClient) update(obj client.Object, isStatus bool, opts ...client.Upd c.trackerWriteLock.Lock() defer c.trackerWriteLock.Unlock() - return c.tracker.update(gvr, obj, accessor.GetNamespace(), isStatus, false, *updateOptions.AsUpdateOptions()) + + // Retain managed fields + // We can ignore all errors here since update will fail if we encounter an error. + obj.SetManagedFields(nil) + current, _ := c.tracker.Get(gvr, accessor.GetNamespace(), accessor.GetName()) + if currentMetaObj, ok := current.(metav1.Object); ok { + obj.SetManagedFields(currentMetaObj.GetManagedFields()) + } + + if err := c.tracker.update(gvr, obj, accessor.GetNamespace(), isStatus, false, *updateOptions.AsUpdateOptions()); err != nil { + return err + } + + if !c.returnManagedFields { + obj.SetManagedFields(nil) + } + + return ensureTypeMeta(obj, gvk) } func (c *fakeClient) Patch(ctx context.Context, obj client.Object, patch client.Patch, opts ...client.PatchOption) error { return c.patch(obj, patch, opts...) } +func (c *fakeClient) Apply(ctx context.Context, obj runtime.ApplyConfiguration, opts ...client.ApplyOption) error { + applyOpts := &client.ApplyOptions{} + applyOpts.ApplyOptions(opts) + + data, err := json.Marshal(obj) + if err != nil { + return fmt.Errorf("failed to marshal apply configuration: %w", err) + } + + u := &unstructured.Unstructured{} + if err := json.Unmarshal(data, u); err != nil { + return fmt.Errorf("failed to unmarshal apply configuration: %w", err) + } + + applyPatch := &fakeApplyPatch{} + + patchOpts := &client.PatchOptions{} + patchOpts.Raw = applyOpts.AsPatchOptions() + + if err := c.patch(u, applyPatch, patchOpts); err != nil { + return err + } + + acJSON, err := json.Marshal(u) + if err != nil { + return fmt.Errorf("failed to marshal patched object: %w", err) + } + + // We have to zero the object in case it contained a status and there is a + // status subresource. If its the private `unstructuredApplyConfiguration` + // we can not zero all of it, as that will cause the embedded Unstructured + // to be nil which then causes a NPD in the json.Unmarshal below. + switch reflect.TypeOf(obj).String() { + case "*client.unstructuredApplyConfiguration": + zero(reflect.ValueOf(obj).Elem().FieldByName("Unstructured").Interface()) + default: + zero(obj) + } + if err := json.Unmarshal(acJSON, obj); err != nil { + return fmt.Errorf("failed to unmarshal patched object: %w", err) + } + + return nil +} + +type fakeApplyPatch struct{} + +func (p *fakeApplyPatch) Type() types.PatchType { + return types.ApplyPatchType +} + +func (p *fakeApplyPatch) Data(obj client.Object) ([]byte, error) { + return json.Marshal(obj) +} + func (c *fakeClient) patch(obj client.Object, patch client.Patch, opts ...client.PatchOption) error { - c.schemeLock.RLock() - defer c.schemeLock.RUnlock() + if err := c.addToSchemeIfUnknownAndUnstructuredOrPartial(obj); err != nil { + return err + } + patchOptions := &client.PatchOptions{} patchOptions.ApplyOptions(opts) + if errs := validation.ValidatePatchOptions(patchOptions.AsPatchOptions(), patch.Type()); len(errs) > 0 { + return apierrors.NewInvalid(schema.GroupKind{Group: "meta.k8s.io", Kind: "PatchOptions"}, "", errs) + } + + c.schemeLock.RLock() + defer c.schemeLock.RUnlock() + for _, dryRunOpt := range patchOptions.DryRun { if dryRunOpt == metav1.DryRunAll { return nil @@ -922,51 +1151,77 @@ func (c *fakeClient) patch(obj client.Object, patch client.Patch, opts ...client if err != nil { return err } - accessor, err := meta.Accessor(obj) - if err != nil { - return err - } - data, err := patch.Data(obj) + gvk, err := apiutil.GVKForObject(obj, c.scheme) if err != nil { return err } - - gvk, err := apiutil.GVKForObject(obj, c.scheme) + accessor, err := meta.Accessor(obj) if err != nil { return err } + var isApplyCreate bool c.trackerWriteLock.Lock() defer c.trackerWriteLock.Unlock() oldObj, err := c.tracker.Get(gvr, accessor.GetNamespace(), accessor.GetName()) if err != nil { - return err + if !apierrors.IsNotFound(err) || patch.Type() != types.ApplyPatchType { + return err + } + oldObj = &unstructured.Unstructured{} + isApplyCreate = true } oldAccessor, err := meta.Accessor(oldObj) if err != nil { return err } - // Apply patch without updating object. - // To remain in accordance with the behavior of k8s api behavior, - // a patch must not allow for changes to the deletionTimestamp of an object. - // The reaction() function applies the patch to the object and calls Update(), - // whereas dryPatch() replicates this behavior but skips the call to Update(). - // This ensures that the patch may be rejected if a deletionTimestamp is modified, prior - // to updating the object. - action := testing.NewPatchAction(gvr, accessor.GetNamespace(), accessor.GetName(), patch.Type(), data) - o, err := dryPatch(action, c.tracker) - if err != nil { - return err + // SSA deletionTimestamp updates are silently ignored + if patch.Type() == types.ApplyPatchType && !isApplyCreate { + obj.SetDeletionTimestamp(oldAccessor.GetDeletionTimestamp()) } - newObj, err := meta.Accessor(o) + + data, err := patch.Data(obj) if err != nil { return err } - // Validate that deletionTimestamp has not been changed - if !deletionTimestampEqual(newObj, oldAccessor) { - return fmt.Errorf("rejected patch, metadata.deletionTimestamp immutable") + action := testing.NewPatchActionWithOptions( + gvr, + accessor.GetNamespace(), + accessor.GetName(), + patch.Type(), + data, + *patchOptions.AsPatchOptions(), + ) + + // Apply is implemented in the tracker and calling it has side-effects + // such as bumping RV and updating managedFields timestamps, hence we + // can not dry-run it. Luckily, the only validation we use it for + // doesn't apply to SSA - Creating objects with non-nil deletionTimestamp + // through SSA is possible and updating the deletionTimestamp is valid, + // but has no effect. + if patch.Type() != types.ApplyPatchType { + // Apply patch without updating object. + // To remain in accordance with the behavior of k8s api behavior, + // a patch must not allow for changes to the deletionTimestamp of an object. + // The reaction() function applies the patch to the object and calls Update(), + // whereas dryPatch() replicates this behavior but skips the call to Update(). + // This ensures that the patch may be rejected if a deletionTimestamp is modified, prior + // to updating the object. + o, err := dryPatch(action, c.tracker) + if err != nil { + return err + } + newObj, err := meta.Accessor(o) + if err != nil { + return err + } + + // Validate that deletionTimestamp has not been changed + if !deletionTimestampEqual(newObj, oldAccessor) { + return fmt.Errorf("rejected patch, metadata.deletionTimestamp immutable") + } } reaction := testing.ObjectReaction(c.tracker) @@ -978,21 +1233,28 @@ func (c *fakeClient) patch(obj client.Object, patch client.Patch, opts ...client panic("tracker could not handle patch method") } - if _, isUnstructured := obj.(runtime.Unstructured); isUnstructured { - ta, err := meta.TypeAccessor(o) - if err != nil { - return err - } - ta.SetKind(gvk.Kind) - ta.SetAPIVersion(gvk.GroupVersion().String()) + ta, err := meta.TypeAccessor(o) + if err != nil { + return err } + ta.SetAPIVersion(gvk.GroupVersion().String()) + ta.SetKind(gvk.Kind) + j, err := json.Marshal(o) if err != nil { return err } zero(obj) - return json.Unmarshal(j, obj) + if err := json.Unmarshal(j, obj); err != nil { + return err + } + + if !c.returnManagedFields { + obj.SetManagedFields(nil) + } + + return ensureTypeMeta(obj, gvk) } // Applying a patch results in a deletionTimestamp that is truncated to the nearest second. @@ -1020,6 +1282,9 @@ func dryPatch(action testing.PatchActionImpl, tracker testing.ObjectTracker) (ru obj, err := tracker.Get(gvr, ns, action.GetName()) if err != nil { + if apierrors.IsNotFound(err) && action.GetPatchType() == types.ApplyPatchType { + return &unstructured.Unstructured{}, nil + } return nil, err } @@ -1064,10 +1329,10 @@ func dryPatch(action testing.PatchActionImpl, tracker testing.ObjectTracker) (ru if err = json.Unmarshal(mergedByte, obj); err != nil { return nil, err } - case types.ApplyPatchType: - return nil, errors.New("apply patches are not supported in the fake client. Follow https://github.com/kubernetes/kubernetes/issues/115598 for the current status") case types.ApplyCBORPatchType: return nil, errors.New("apply CBOR patches are not supported in the fake client") + case types.ApplyPatchType: + return nil, errors.New("bug in controller-runtime: should not end up in dryPatch for SSA") default: return nil, fmt.Errorf("%s PatchType is not supported", action.GetPatchType()) } @@ -1600,3 +1865,47 @@ func AddIndex(c client.Client, obj runtime.Object, field string, extractValue cl return nil } + +func (c *fakeClient) addToSchemeIfUnknownAndUnstructuredOrPartial(obj runtime.Object) error { + c.schemeLock.Lock() + defer c.schemeLock.Unlock() + + _, isUnstructured := obj.(*unstructured.Unstructured) + _, isUnstructuredList := obj.(*unstructured.UnstructuredList) + _, isPartial := obj.(*metav1.PartialObjectMetadata) + _, isPartialList := obj.(*metav1.PartialObjectMetadataList) + if !isUnstructured && !isUnstructuredList && !isPartial && !isPartialList { + return nil + } + + gvk, err := apiutil.GVKForObject(obj, c.scheme) + if err != nil { + return err + } + + if !c.scheme.Recognizes(gvk) { + c.scheme.AddKnownTypeWithName(gvk, obj) + } + + return nil +} + +func ensureTypeMeta(obj runtime.Object, gvk schema.GroupVersionKind) error { + ta, err := meta.TypeAccessor(obj) + if err != nil { + return err + } + _, isUnstructured := obj.(runtime.Unstructured) + _, isPartialObject := obj.(*metav1.PartialObjectMetadata) + _, isPartialObjectList := obj.(*metav1.PartialObjectMetadataList) + if !isUnstructured && !isPartialObject && !isPartialObjectList { + ta.SetKind("") + ta.SetAPIVersion("") + return nil + } + + ta.SetKind(gvk.Kind) + ta.SetAPIVersion(gvk.GroupVersion().String()) + + return nil +} diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/client/fake/typeconverter.go b/vendor/sigs.k8s.io/controller-runtime/pkg/client/fake/typeconverter.go new file mode 100644 index 000000000..3cb3a0dc7 --- /dev/null +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/client/fake/typeconverter.go @@ -0,0 +1,60 @@ +/* +Copyright 2025 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package fake + +import ( + "fmt" + + "k8s.io/apimachinery/pkg/runtime" + kerrors "k8s.io/apimachinery/pkg/util/errors" + "k8s.io/apimachinery/pkg/util/managedfields" + "sigs.k8s.io/structured-merge-diff/v6/typed" +) + +type multiTypeConverter struct { + upstream []managedfields.TypeConverter +} + +func (m multiTypeConverter) ObjectToTyped(r runtime.Object, o ...typed.ValidationOptions) (*typed.TypedValue, error) { + var errs []error + for _, u := range m.upstream { + res, err := u.ObjectToTyped(r, o...) + if err != nil { + errs = append(errs, err) + continue + } + + return res, nil + } + + return nil, fmt.Errorf("failed to convert Object to TypedValue: %w", kerrors.NewAggregate(errs)) +} + +func (m multiTypeConverter) TypedToObject(v *typed.TypedValue) (runtime.Object, error) { + var errs []error + for _, u := range m.upstream { + res, err := u.TypedToObject(v) + if err != nil { + errs = append(errs, err) + continue + } + + return res, nil + } + + return nil, fmt.Errorf("failed to convert TypedValue to Object: %w", kerrors.NewAggregate(errs)) +} diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/client/fieldowner.go b/vendor/sigs.k8s.io/controller-runtime/pkg/client/fieldowner.go index 07183cd19..93274f950 100644 --- a/vendor/sigs.k8s.io/controller-runtime/pkg/client/fieldowner.go +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/client/fieldowner.go @@ -54,6 +54,10 @@ func (f *clientWithFieldManager) Patch(ctx context.Context, obj Object, patch Pa return f.c.Patch(ctx, obj, patch, append([]PatchOption{FieldOwner(f.owner)}, opts...)...) } +func (f *clientWithFieldManager) Apply(ctx context.Context, obj runtime.ApplyConfiguration, opts ...ApplyOption) error { + return f.c.Apply(ctx, obj, append([]ApplyOption{FieldOwner(f.owner)}, opts...)...) +} + func (f *clientWithFieldManager) Delete(ctx context.Context, obj Object, opts ...DeleteOption) error { return f.c.Delete(ctx, obj, opts...) } diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/client/fieldvalidation.go b/vendor/sigs.k8s.io/controller-runtime/pkg/client/fieldvalidation.go index 659b3d44c..ce8d0576c 100644 --- a/vendor/sigs.k8s.io/controller-runtime/pkg/client/fieldvalidation.go +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/client/fieldvalidation.go @@ -53,6 +53,10 @@ func (c *clientWithFieldValidation) Patch(ctx context.Context, obj Object, patch return c.client.Patch(ctx, obj, patch, append([]PatchOption{c.validation}, opts...)...) } +func (c *clientWithFieldValidation) Apply(ctx context.Context, obj runtime.ApplyConfiguration, opts ...ApplyOption) error { + return c.client.Apply(ctx, obj, opts...) +} + func (c *clientWithFieldValidation) Delete(ctx context.Context, obj Object, opts ...DeleteOption) error { return c.client.Delete(ctx, obj, opts...) } diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/client/interceptor/intercept.go b/vendor/sigs.k8s.io/controller-runtime/pkg/client/interceptor/intercept.go index 3d3f3cb01..7ff73bd8d 100644 --- a/vendor/sigs.k8s.io/controller-runtime/pkg/client/interceptor/intercept.go +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/client/interceptor/intercept.go @@ -19,6 +19,7 @@ type Funcs struct { DeleteAllOf func(ctx context.Context, client client.WithWatch, obj client.Object, opts ...client.DeleteAllOfOption) error Update func(ctx context.Context, client client.WithWatch, obj client.Object, opts ...client.UpdateOption) error Patch func(ctx context.Context, client client.WithWatch, obj client.Object, patch client.Patch, opts ...client.PatchOption) error + Apply func(ctx context.Context, client client.WithWatch, obj runtime.ApplyConfiguration, opts ...client.ApplyOption) error Watch func(ctx context.Context, client client.WithWatch, obj client.ObjectList, opts ...client.ListOption) (watch.Interface, error) SubResource func(client client.WithWatch, subResource string) client.SubResourceClient SubResourceGet func(ctx context.Context, client client.Client, subResourceName string, obj client.Object, subResource client.Object, opts ...client.SubResourceGetOption) error @@ -92,6 +93,14 @@ func (c interceptor) Patch(ctx context.Context, obj client.Object, patch client. return c.client.Patch(ctx, obj, patch, opts...) } +func (c interceptor) Apply(ctx context.Context, obj runtime.ApplyConfiguration, opts ...client.ApplyOption) error { + if c.funcs.Apply != nil { + return c.funcs.Apply(ctx, c.client, obj, opts...) + } + + return c.client.Apply(ctx, obj, opts...) +} + func (c interceptor) DeleteAllOf(ctx context.Context, obj client.Object, opts ...client.DeleteAllOfOption) error { if c.funcs.DeleteAllOf != nil { return c.funcs.DeleteAllOf(ctx, c.client, obj, opts...) diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/client/interfaces.go b/vendor/sigs.k8s.io/controller-runtime/pkg/client/interfaces.go index 3b282fc2c..61559ecbe 100644 --- a/vendor/sigs.k8s.io/controller-runtime/pkg/client/interfaces.go +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/client/interfaces.go @@ -61,6 +61,9 @@ type Reader interface { // Writer knows how to create, delete, and update Kubernetes objects. type Writer interface { + // Apply applies the given apply configuration to the Kubernetes cluster. + Apply(ctx context.Context, obj runtime.ApplyConfiguration, opts ...ApplyOption) error + // Create saves the object obj in the Kubernetes cluster. obj must be a // struct pointer so that obj can be updated with the content returned by the Server. Create(ctx context.Context, obj Object, opts ...CreateOption) error diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/client/namespaced_client.go b/vendor/sigs.k8s.io/controller-runtime/pkg/client/namespaced_client.go index 222dc7957..cacba4a9c 100644 --- a/vendor/sigs.k8s.io/controller-runtime/pkg/client/namespaced_client.go +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/client/namespaced_client.go @@ -19,10 +19,13 @@ package client import ( "context" "fmt" + "reflect" "k8s.io/apimachinery/pkg/api/meta" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/utils/ptr" + "sigs.k8s.io/controller-runtime/pkg/client/apiutil" ) // NewNamespacedClient wraps an existing client enforcing the namespace value. @@ -147,6 +150,52 @@ func (n *namespacedClient) Patch(ctx context.Context, obj Object, patch Patch, o return n.client.Patch(ctx, obj, patch, opts...) } +func (n *namespacedClient) Apply(ctx context.Context, obj runtime.ApplyConfiguration, opts ...ApplyOption) error { + var gvk schema.GroupVersionKind + switch o := obj.(type) { + case applyConfiguration: + var err error + gvk, err = gvkFromApplyConfiguration(o) + if err != nil { + return err + } + case *unstructuredApplyConfiguration: + gvk = o.GroupVersionKind() + default: + return fmt.Errorf("object %T is not a valid apply configuration", obj) + } + isNamespaceScoped, err := apiutil.IsGVKNamespaced(gvk, n.RESTMapper()) + if err != nil { + return fmt.Errorf("error finding the scope of the object: %w", err) + } + if isNamespaceScoped { + switch o := obj.(type) { + case applyConfiguration: + if o.GetNamespace() != nil && *o.GetNamespace() != "" && *o.GetNamespace() != n.namespace { + return fmt.Errorf("namespace %s provided for the object %s does not match the namespace %s on the client", + *o.GetNamespace(), ptr.Deref(o.GetName(), ""), n.namespace) + } + v := reflect.ValueOf(o) + withNamespace := v.MethodByName("WithNamespace") + if !withNamespace.IsValid() { + return fmt.Errorf("ApplyConfiguration %T does not have a WithNamespace method", o) + } + if tp := withNamespace.Type(); tp.NumIn() != 1 || tp.In(0).Kind() != reflect.String { + return fmt.Errorf("WithNamespace method of ApplyConfiguration %T must take a single string argument", o) + } + withNamespace.Call([]reflect.Value{reflect.ValueOf(n.namespace)}) + case *unstructuredApplyConfiguration: + if o.GetNamespace() != "" && o.GetNamespace() != n.namespace { + return fmt.Errorf("namespace %s provided for the object %s does not match the namespace %s on the client", + o.GetNamespace(), o.GetName(), n.namespace) + } + o.SetNamespace(n.namespace) + } + } + + return n.client.Apply(ctx, obj, opts...) +} + // Get implements client.Client. func (n *namespacedClient) Get(ctx context.Context, key ObjectKey, obj Object, opts ...GetOption) error { isNamespaceScoped, err := n.IsObjectNamespaced(obj) diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/client/options.go b/vendor/sigs.k8s.io/controller-runtime/pkg/client/options.go index db50ed8fe..33c460738 100644 --- a/vendor/sigs.k8s.io/controller-runtime/pkg/client/options.go +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/client/options.go @@ -21,6 +21,7 @@ import ( "k8s.io/apimachinery/pkg/fields" "k8s.io/apimachinery/pkg/labels" "k8s.io/apimachinery/pkg/selection" + "k8s.io/utils/ptr" ) // {{{ "Functional" Option Interfaces @@ -61,6 +62,12 @@ type PatchOption interface { ApplyToPatch(*PatchOptions) } +// ApplyOption is some configuration that modifies options for an apply request. +type ApplyOption interface { + // ApplyToApply applies this configuration to the given apply options. + ApplyToApply(*ApplyOptions) +} + // DeleteAllOfOption is some configuration that modifies options for a delete request. type DeleteAllOfOption interface { // ApplyToDeleteAllOf applies this configuration to the given deletecollection options. @@ -115,7 +122,12 @@ func (dryRunAll) ApplyToPatch(opts *PatchOptions) { opts.DryRun = []string{metav1.DryRunAll} } -// ApplyToPatch applies this configuration to the given delete options. +// ApplyToApply applies this configuration to the given apply options. +func (dryRunAll) ApplyToApply(opts *ApplyOptions) { + opts.DryRun = []string{metav1.DryRunAll} +} + +// ApplyToDelete applies this configuration to the given delete options. func (dryRunAll) ApplyToDelete(opts *DeleteOptions) { opts.DryRun = []string{metav1.DryRunAll} } @@ -154,6 +166,11 @@ func (f FieldOwner) ApplyToUpdate(opts *UpdateOptions) { opts.FieldManager = string(f) } +// ApplyToApply applies this configuration to the given apply options. +func (f FieldOwner) ApplyToApply(opts *ApplyOptions) { + opts.FieldManager = string(f) +} + // ApplyToSubResourcePatch applies this configuration to the given patch options. func (f FieldOwner) ApplyToSubResourcePatch(opts *SubResourcePatchOptions) { opts.FieldManager = string(f) @@ -431,6 +448,12 @@ type GetOptions struct { // Raw represents raw GetOptions, as passed to the API server. Note // that these may not be respected by all implementations of interface. Raw *metav1.GetOptions + + // UnsafeDisableDeepCopy indicates not to deep copy objects during get object. + // Be very careful with this, when enabled you must DeepCopy any object before mutating it, + // otherwise you will mutate the object in the cache. + // +optional + UnsafeDisableDeepCopy *bool } var _ GetOption = &GetOptions{} @@ -440,6 +463,9 @@ func (o *GetOptions) ApplyToGet(lo *GetOptions) { if o.Raw != nil { lo.Raw = o.Raw } + if o.UnsafeDisableDeepCopy != nil { + lo.UnsafeDisableDeepCopy = o.UnsafeDisableDeepCopy + } } // AsGetOptions returns these options as a flattened metav1.GetOptions. @@ -618,6 +644,9 @@ type MatchingLabelsSelector struct { // ApplyToList applies this configuration to the given list options. func (m MatchingLabelsSelector) ApplyToList(opts *ListOptions) { + if m.Selector == nil { + m.Selector = labels.Nothing() + } opts.LabelSelector = m } @@ -651,6 +680,9 @@ type MatchingFieldsSelector struct { // ApplyToList applies this configuration to the given list options. func (m MatchingFieldsSelector) ApplyToList(opts *ListOptions) { + if m.Selector == nil { + m.Selector = fields.Nothing() + } opts.FieldSelector = m } @@ -692,15 +724,14 @@ func (l Limit) ApplyToList(opts *ListOptions) { // otherwise you will mutate the object in the cache. type UnsafeDisableDeepCopyOption bool +// ApplyToGet applies this configuration to the given an Get options. +func (d UnsafeDisableDeepCopyOption) ApplyToGet(opts *GetOptions) { + opts.UnsafeDisableDeepCopy = ptr.To(bool(d)) +} + // ApplyToList applies this configuration to the given an List options. func (d UnsafeDisableDeepCopyOption) ApplyToList(opts *ListOptions) { - definitelyTrue := true - definitelyFalse := false - if d { - opts.UnsafeDisableDeepCopy = &definitelyTrue - } else { - opts.UnsafeDisableDeepCopy = &definitelyFalse - } + opts.UnsafeDisableDeepCopy = ptr.To(bool(d)) } // UnsafeDisableDeepCopy indicates not to deep copy objects during list objects. @@ -863,10 +894,18 @@ func (o *PatchOptions) AsPatchOptions() *metav1.PatchOptions { o.Raw = &metav1.PatchOptions{} } - o.Raw.DryRun = o.DryRun - o.Raw.Force = o.Force - o.Raw.FieldManager = o.FieldManager - o.Raw.FieldValidation = o.FieldValidation + if o.DryRun != nil { + o.Raw.DryRun = o.DryRun + } + if o.Force != nil { + o.Raw.Force = o.Force + } + if o.FieldManager != "" { + o.Raw.FieldManager = o.FieldManager + } + if o.FieldValidation != "" { + o.Raw.FieldValidation = o.FieldValidation + } return o.Raw } @@ -899,13 +938,15 @@ var ForceOwnership = forceOwnership{} type forceOwnership struct{} func (forceOwnership) ApplyToPatch(opts *PatchOptions) { - definitelyTrue := true - opts.Force = &definitelyTrue + opts.Force = ptr.To(true) } func (forceOwnership) ApplyToSubResourcePatch(opts *SubResourcePatchOptions) { - definitelyTrue := true - opts.Force = &definitelyTrue + opts.Force = ptr.To(true) +} + +func (forceOwnership) ApplyToApply(opts *ApplyOptions) { + opts.Force = ptr.To(true) } // }}} @@ -939,3 +980,57 @@ func (o *DeleteAllOfOptions) ApplyToDeleteAllOf(do *DeleteAllOfOptions) { } // }}} + +// ApplyOptions are the options for an apply request. +type ApplyOptions struct { + // When present, indicates that modifications should not be + // persisted. An invalid or unrecognized dryRun directive will + // result in an error response and no further processing of the + // request. Valid values are: + // - All: all dry run stages will be processed + DryRun []string + + // Force is going to "force" Apply requests. It means user will + // re-acquire conflicting fields owned by other people. + Force *bool + + // fieldManager is a name associated with the actor or entity + // that is making these changes. The value must be less than or + // 128 characters long, and only contain printable characters, + // as defined by https://golang.org/pkg/unicode/#IsPrint. This + // field is required. + // + // +required + FieldManager string +} + +// ApplyOptions applies the given opts onto the ApplyOptions +func (o *ApplyOptions) ApplyOptions(opts []ApplyOption) *ApplyOptions { + for _, opt := range opts { + opt.ApplyToApply(o) + } + return o +} + +// ApplyToApply applies the given opts onto the ApplyOptions +func (o *ApplyOptions) ApplyToApply(opts *ApplyOptions) { + if o.DryRun != nil { + opts.DryRun = o.DryRun + } + if o.Force != nil { + opts.Force = o.Force + } + + if o.FieldManager != "" { + opts.FieldManager = o.FieldManager + } +} + +// AsPatchOptions constructs patch options from the given ApplyOptions +func (o *ApplyOptions) AsPatchOptions() *metav1.PatchOptions { + return &metav1.PatchOptions{ + DryRun: o.DryRun, + Force: o.Force, + FieldManager: o.FieldManager, + } +} diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/client/patch.go b/vendor/sigs.k8s.io/controller-runtime/pkg/client/patch.go index 11d608388..b99d7663b 100644 --- a/vendor/sigs.k8s.io/controller-runtime/pkg/client/patch.go +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/client/patch.go @@ -27,6 +27,11 @@ import ( var ( // Apply uses server-side apply to patch the given object. + // + // This should now only be used to patch sub resources, e.g. with client.Client.Status().Patch(). + // Use client.Client.Apply() instead of client.Client.Patch(..., client.Apply, ...) + // This will be deprecated once the Apply method has been added for sub resources. + // See the following issue for more details: https://github.com/kubernetes-sigs/controller-runtime/issues/3183 Apply Patch = applyPatch{} // Merge uses the raw object as a merge patch, without modifications. diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/client/typed_client.go b/vendor/sigs.k8s.io/controller-runtime/pkg/client/typed_client.go index 92afd9a9c..3bd762a63 100644 --- a/vendor/sigs.k8s.io/controller-runtime/pkg/client/typed_client.go +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/client/typed_client.go @@ -18,8 +18,10 @@ package client import ( "context" + "fmt" "k8s.io/apimachinery/pkg/runtime" + "k8s.io/client-go/util/apply" ) var _ Reader = &typedClient{} @@ -41,7 +43,7 @@ func (c *typedClient) Create(ctx context.Context, obj Object, opts ...CreateOpti createOpts.ApplyOptions(opts) return o.Post(). - NamespaceIfScoped(o.GetNamespace(), o.isNamespaced()). + NamespaceIfScoped(o.namespace, o.isNamespaced()). Resource(o.resource()). Body(obj). VersionedParams(createOpts.AsCreateOptions(), c.paramCodec). @@ -60,9 +62,9 @@ func (c *typedClient) Update(ctx context.Context, obj Object, opts ...UpdateOpti updateOpts.ApplyOptions(opts) return o.Put(). - NamespaceIfScoped(o.GetNamespace(), o.isNamespaced()). + NamespaceIfScoped(o.namespace, o.isNamespaced()). Resource(o.resource()). - Name(o.GetName()). + Name(o.name). Body(obj). VersionedParams(updateOpts.AsUpdateOptions(), c.paramCodec). Do(ctx). @@ -80,9 +82,9 @@ func (c *typedClient) Delete(ctx context.Context, obj Object, opts ...DeleteOpti deleteOpts.ApplyOptions(opts) return o.Delete(). - NamespaceIfScoped(o.GetNamespace(), o.isNamespaced()). + NamespaceIfScoped(o.namespace, o.isNamespaced()). Resource(o.resource()). - Name(o.GetName()). + Name(o.name). Body(deleteOpts.AsDeleteOptions()). Do(ctx). Error() @@ -123,15 +125,40 @@ func (c *typedClient) Patch(ctx context.Context, obj Object, patch Patch, opts . patchOpts.ApplyOptions(opts) return o.Patch(patch.Type()). - NamespaceIfScoped(o.GetNamespace(), o.isNamespaced()). + NamespaceIfScoped(o.namespace, o.isNamespaced()). Resource(o.resource()). - Name(o.GetName()). + Name(o.name). VersionedParams(patchOpts.AsPatchOptions(), c.paramCodec). Body(data). Do(ctx). Into(obj) } +func (c *typedClient) Apply(ctx context.Context, obj runtime.ApplyConfiguration, opts ...ApplyOption) error { + o, err := c.resources.getObjMeta(obj) + if err != nil { + return err + } + req, err := apply.NewRequest(o, obj) + if err != nil { + return fmt.Errorf("failed to create apply request: %w", err) + } + applyOpts := &ApplyOptions{} + applyOpts.ApplyOptions(opts) + + return req. + NamespaceIfScoped(o.namespace, o.isNamespaced()). + Resource(o.resource()). + Name(o.name). + VersionedParams(applyOpts.AsPatchOptions(), c.paramCodec). + Do(ctx). + // This is hacky, it is required because `Into` takes a `runtime.Object` and + // that is not implemented by the ApplyConfigurations. The generated clients + // don't have this problem because they deserialize into the api type, not the + // apply configuration: https://github.com/kubernetes/kubernetes/blob/22f5e01a37c0bc6a5f494dec14dd4e3688ee1d55/staging/src/k8s.io/client-go/gentype/type.go#L296-L317 + Into(runtimeObjectFromApplyConfiguration(obj)) +} + // Get implements client.Client. func (c *typedClient) Get(ctx context.Context, key ObjectKey, obj Object, opts ...GetOption) error { r, err := c.resources.getResource(obj) @@ -179,9 +206,9 @@ func (c *typedClient) GetSubResource(ctx context.Context, obj, subResourceObj Ob getOpts.ApplyOptions(opts) return o.Get(). - NamespaceIfScoped(o.GetNamespace(), o.isNamespaced()). + NamespaceIfScoped(o.namespace, o.isNamespaced()). Resource(o.resource()). - Name(o.GetName()). + Name(o.name). SubResource(subResource). VersionedParams(getOpts.AsGetOptions(), c.paramCodec). Do(ctx). @@ -202,9 +229,9 @@ func (c *typedClient) CreateSubResource(ctx context.Context, obj Object, subReso createOpts.ApplyOptions(opts) return o.Post(). - NamespaceIfScoped(o.GetNamespace(), o.isNamespaced()). + NamespaceIfScoped(o.namespace, o.isNamespaced()). Resource(o.resource()). - Name(o.GetName()). + Name(o.name). SubResource(subResource). Body(subResourceObj). VersionedParams(createOpts.AsCreateOptions(), c.paramCodec). @@ -237,9 +264,9 @@ func (c *typedClient) UpdateSubResource(ctx context.Context, obj Object, subReso } return o.Put(). - NamespaceIfScoped(o.GetNamespace(), o.isNamespaced()). + NamespaceIfScoped(o.namespace, o.isNamespaced()). Resource(o.resource()). - Name(o.GetName()). + Name(o.name). SubResource(subResource). Body(body). VersionedParams(updateOpts.AsUpdateOptions(), c.paramCodec). @@ -268,9 +295,9 @@ func (c *typedClient) PatchSubResource(ctx context.Context, obj Object, subResou } return o.Patch(patch.Type()). - NamespaceIfScoped(o.GetNamespace(), o.isNamespaced()). + NamespaceIfScoped(o.namespace, o.isNamespaced()). Resource(o.resource()). - Name(o.GetName()). + Name(o.name). SubResource(subResource). Body(data). VersionedParams(patchOpts.AsPatchOptions(), c.paramCodec). diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/client/unstructured_client.go b/vendor/sigs.k8s.io/controller-runtime/pkg/client/unstructured_client.go index 0d9695178..e636c3bee 100644 --- a/vendor/sigs.k8s.io/controller-runtime/pkg/client/unstructured_client.go +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/client/unstructured_client.go @@ -22,6 +22,7 @@ import ( "strings" "k8s.io/apimachinery/pkg/runtime" + "k8s.io/client-go/util/apply" ) var _ Reader = &unstructuredClient{} @@ -50,7 +51,7 @@ func (uc *unstructuredClient) Create(ctx context.Context, obj Object, opts ...Cr createOpts.ApplyOptions(opts) result := o.Post(). - NamespaceIfScoped(o.GetNamespace(), o.isNamespaced()). + NamespaceIfScoped(o.namespace, o.isNamespaced()). Resource(o.resource()). Body(obj). VersionedParams(createOpts.AsCreateOptions(), uc.paramCodec). @@ -79,9 +80,9 @@ func (uc *unstructuredClient) Update(ctx context.Context, obj Object, opts ...Up updateOpts.ApplyOptions(opts) result := o.Put(). - NamespaceIfScoped(o.GetNamespace(), o.isNamespaced()). + NamespaceIfScoped(o.namespace, o.isNamespaced()). Resource(o.resource()). - Name(o.GetName()). + Name(o.name). Body(obj). VersionedParams(updateOpts.AsUpdateOptions(), uc.paramCodec). Do(ctx). @@ -106,9 +107,9 @@ func (uc *unstructuredClient) Delete(ctx context.Context, obj Object, opts ...De deleteOpts.ApplyOptions(opts) return o.Delete(). - NamespaceIfScoped(o.GetNamespace(), o.isNamespaced()). + NamespaceIfScoped(o.namespace, o.isNamespaced()). Resource(o.resource()). - Name(o.GetName()). + Name(o.name). Body(deleteOpts.AsDeleteOptions()). Do(ctx). Error() @@ -157,15 +158,41 @@ func (uc *unstructuredClient) Patch(ctx context.Context, obj Object, patch Patch patchOpts.ApplyOptions(opts) return o.Patch(patch.Type()). - NamespaceIfScoped(o.GetNamespace(), o.isNamespaced()). + NamespaceIfScoped(o.namespace, o.isNamespaced()). Resource(o.resource()). - Name(o.GetName()). + Name(o.name). VersionedParams(patchOpts.AsPatchOptions(), uc.paramCodec). Body(data). Do(ctx). Into(obj) } +func (uc *unstructuredClient) Apply(ctx context.Context, obj runtime.ApplyConfiguration, opts ...ApplyOption) error { + unstructuredApplyConfig, ok := obj.(*unstructuredApplyConfiguration) + if !ok { + return fmt.Errorf("bug: unstructured client got an applyconfiguration that was not %T but %T", &unstructuredApplyConfiguration{}, obj) + } + o, err := uc.resources.getObjMeta(unstructuredApplyConfig.Unstructured) + if err != nil { + return err + } + + req, err := apply.NewRequest(o, obj) + if err != nil { + return fmt.Errorf("failed to create apply request: %w", err) + } + applyOpts := &ApplyOptions{} + applyOpts.ApplyOptions(opts) + + return req. + NamespaceIfScoped(o.namespace, o.isNamespaced()). + Resource(o.resource()). + Name(o.name). + VersionedParams(applyOpts.AsPatchOptions(), uc.paramCodec). + Do(ctx). + Into(unstructuredApplyConfig.Unstructured) +} + // Get implements client.Client. func (uc *unstructuredClient) Get(ctx context.Context, key ObjectKey, obj Object, opts ...GetOption) error { u, ok := obj.(runtime.Unstructured) @@ -244,9 +271,9 @@ func (uc *unstructuredClient) GetSubResource(ctx context.Context, obj, subResour getOpts.ApplyOptions(opts) return o.Get(). - NamespaceIfScoped(o.GetNamespace(), o.isNamespaced()). + NamespaceIfScoped(o.namespace, o.isNamespaced()). Resource(o.resource()). - Name(o.GetName()). + Name(o.name). SubResource(subResource). VersionedParams(getOpts.AsGetOptions(), uc.paramCodec). Do(ctx). @@ -275,9 +302,9 @@ func (uc *unstructuredClient) CreateSubResource(ctx context.Context, obj, subRes createOpts.ApplyOptions(opts) return o.Post(). - NamespaceIfScoped(o.GetNamespace(), o.isNamespaced()). + NamespaceIfScoped(o.namespace, o.isNamespaced()). Resource(o.resource()). - Name(o.GetName()). + Name(o.name). SubResource(subResource). Body(subResourceObj). VersionedParams(createOpts.AsCreateOptions(), uc.paramCodec). @@ -310,9 +337,9 @@ func (uc *unstructuredClient) UpdateSubResource(ctx context.Context, obj Object, } return o.Put(). - NamespaceIfScoped(o.GetNamespace(), o.isNamespaced()). + NamespaceIfScoped(o.namespace, o.isNamespaced()). Resource(o.resource()). - Name(o.GetName()). + Name(o.name). SubResource(subResource). Body(body). VersionedParams(updateOpts.AsUpdateOptions(), uc.paramCodec). @@ -347,9 +374,9 @@ func (uc *unstructuredClient) PatchSubResource(ctx context.Context, obj Object, } result := o.Patch(patch.Type()). - NamespaceIfScoped(o.GetNamespace(), o.isNamespaced()). + NamespaceIfScoped(o.namespace, o.isNamespaced()). Resource(o.resource()). - Name(o.GetName()). + Name(o.name). SubResource(subResource). Body(data). VersionedParams(patchOpts.AsPatchOptions(), uc.paramCodec). diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/config/controller.go b/vendor/sigs.k8s.io/controller-runtime/pkg/config/controller.go index a5655593e..3dafaef93 100644 --- a/vendor/sigs.k8s.io/controller-runtime/pkg/config/controller.go +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/config/controller.go @@ -60,12 +60,33 @@ type Controller struct { // Defaults to true, which means the controller will use leader election. NeedLeaderElection *bool + // EnableWarmup specifies whether the controller should start its sources when the manager is not + // the leader. This is useful for cases where sources take a long time to start, as it allows + // for the controller to warm up its caches even before it is elected as the leader. This + // improves leadership failover time, as the caches will be prepopulated before the controller + // transitions to be leader. + // + // Setting EnableWarmup to true and NeedLeaderElection to true means the controller will start its + // sources without waiting to become leader. + // Setting EnableWarmup to true and NeedLeaderElection to false is a no-op as controllers without + // leader election do not wait on leader election to start their sources. + // Defaults to false. + // + // Note: This feature is currently in beta and subject to change. + // For more details, see: https://github.com/kubernetes-sigs/controller-runtime/issues/3220. + EnableWarmup *bool + // UsePriorityQueue configures the controllers queue to use the controller-runtime provided // priority queue. // - // Note: This flag is disabled by default until a future version. It's currently in beta. + // Note: This flag is disabled by default until a future version. This feature is currently in beta. + // For more details, see: https://github.com/kubernetes-sigs/controller-runtime/issues/2374. UsePriorityQueue *bool // Logger is the logger controllers should use. Logger logr.Logger + + // ReconciliationTimeout is used as the timeout passed to the context of each Reconcile call. + // By default, there is no timeout. + ReconciliationTimeout time.Duration } diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/controller/controller.go b/vendor/sigs.k8s.io/controller-runtime/pkg/controller/controller.go index 9de959b48..afa15aebe 100644 --- a/vendor/sigs.k8s.io/controller-runtime/pkg/controller/controller.go +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/controller/controller.go @@ -91,8 +91,29 @@ type TypedOptions[request comparable] struct { // UsePriorityQueue configures the controllers queue to use the controller-runtime provided // priority queue. // - // Note: This flag is disabled by default until a future version. It's currently in beta. + // Note: This flag is disabled by default until a future version. This feature is currently in beta. + // For more details, see: https://github.com/kubernetes-sigs/controller-runtime/issues/2374. UsePriorityQueue *bool + + // EnableWarmup specifies whether the controller should start its sources when the manager is not + // the leader. This is useful for cases where sources take a long time to start, as it allows + // for the controller to warm up its caches even before it is elected as the leader. This + // improves leadership failover time, as the caches will be prepopulated before the controller + // transitions to be leader. + // + // Setting EnableWarmup to true and NeedLeaderElection to true means the controller will start its + // sources without waiting to become leader. + // Setting EnableWarmup to true and NeedLeaderElection to false is a no-op as controllers without + // leader election do not wait on leader election to start their sources. + // Defaults to false. + // + // Note: This feature is currently in beta and subject to change. + // For more details, see: https://github.com/kubernetes-sigs/controller-runtime/issues/3220. + EnableWarmup *bool + + // ReconciliationTimeout is used as the timeout passed to the context of each Reconcile call. + // By default, there is no timeout. + ReconciliationTimeout time.Duration } // DefaultFromConfig defaults the config from a config.Controller @@ -124,6 +145,14 @@ func (options *TypedOptions[request]) DefaultFromConfig(config config.Controller if options.NeedLeaderElection == nil { options.NeedLeaderElection = config.NeedLeaderElection } + + if options.EnableWarmup == nil { + options.EnableWarmup = config.EnableWarmup + } + + if options.ReconciliationTimeout == 0 { + options.ReconciliationTimeout = config.ReconciliationTimeout + } } // Controller implements an API. A Controller manages a work queue fed reconcile.Requests @@ -243,7 +272,7 @@ func NewTypedUnmanaged[request comparable](name string, options TypedOptions[req } // Create controller with dependencies set - return &controller.Controller[request]{ + return controller.New[request](controller.Options[request]{ Do: options.Reconciler, RateLimiter: options.RateLimiter, NewQueue: options.NewQueue, @@ -253,7 +282,9 @@ func NewTypedUnmanaged[request comparable](name string, options TypedOptions[req LogConstructor: options.LogConstructor, RecoverPanic: options.RecoverPanic, LeaderElected: options.NeedLeaderElection, - }, nil + EnableWarmup: options.EnableWarmup, + ReconciliationTimeout: options.ReconciliationTimeout, + }), nil } // ReconcileIDFromContext gets the reconcileID from the current context. diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/controller/priorityqueue/priorityqueue.go b/vendor/sigs.k8s.io/controller-runtime/pkg/controller/priorityqueue/priorityqueue.go index c3f77a6f3..98df84c56 100644 --- a/vendor/sigs.k8s.io/controller-runtime/pkg/controller/priorityqueue/priorityqueue.go +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/controller/priorityqueue/priorityqueue.go @@ -1,6 +1,7 @@ package priorityqueue import ( + "math" "sync" "sync/atomic" "time" @@ -19,7 +20,10 @@ import ( type AddOpts struct { After time.Duration RateLimited bool - Priority int + // Priority is the priority of the item. Higher values + // indicate higher priority. + // Defaults to zero if unset. + Priority *int } // PriorityQueue is a priority queue for a controller. It @@ -129,6 +133,10 @@ type priorityqueue[T comparable] struct { } func (w *priorityqueue[T]) AddWithOpts(o AddOpts, items ...T) { + if w.shutdown.Load() { + return + } + w.lock.Lock() defer w.lock.Unlock() @@ -150,7 +158,7 @@ func (w *priorityqueue[T]) AddWithOpts(o AddOpts, items ...T) { item := &item[T]{ Key: key, AddedCounter: w.addedCounter, - Priority: o.Priority, + Priority: ptr.Deref(o.Priority, 0), ReadyAt: readyAt, } w.items[key] = item @@ -165,12 +173,12 @@ func (w *priorityqueue[T]) AddWithOpts(o AddOpts, items ...T) { // The b-tree de-duplicates based on ordering and any change here // will affect the order - Just delete and re-add. item, _ := w.queue.Delete(w.items[key]) - if o.Priority > item.Priority { + if newPriority := ptr.Deref(o.Priority, 0); newPriority > item.Priority { // Update depth metric only if the item in the queue was already added to the depth metric. if item.ReadyAt == nil || w.becameReady.Has(key) { - w.metrics.updateDepthWithPriorityMetric(item.Priority, o.Priority) + w.metrics.updateDepthWithPriorityMetric(item.Priority, newPriority) } - item.Priority = o.Priority + item.Priority = newPriority } if item.ReadyAt != nil && (readyAt == nil || readyAt.Before(*item.ReadyAt)) { @@ -199,6 +207,7 @@ func (w *priorityqueue[T]) spin() { blockForever := make(chan time.Time) var nextReady <-chan time.Time nextReady = blockForever + var nextItemReadyAt time.Time for { select { @@ -206,10 +215,10 @@ func (w *priorityqueue[T]) spin() { return case <-w.itemOrWaiterAdded: case <-nextReady: + nextReady = blockForever + nextItemReadyAt = time.Time{} } - nextReady = blockForever - func() { w.lock.Lock() defer w.lock.Unlock() @@ -220,39 +229,67 @@ func (w *priorityqueue[T]) spin() { // manipulating the tree from within Ascend might lead to panics, so // track what we want to delete and do it after we are done ascending. var toDelete []*item[T] - w.queue.Ascend(func(item *item[T]) bool { - if item.ReadyAt != nil { - if readyAt := item.ReadyAt.Sub(w.now()); readyAt > 0 { - nextReady = w.tick(readyAt) - return false + + var key T + + // Items in the queue tree are sorted first by priority and second by readiness, so + // items with a lower priority might be ready further down in the queue. + // We iterate through the priorities high to low until we find a ready item + pivot := item[T]{ + Key: key, + AddedCounter: 0, + Priority: math.MaxInt, + ReadyAt: nil, + } + + for { + pivotChange := false + + w.queue.AscendGreaterOrEqual(&pivot, func(item *item[T]) bool { + // Item is locked, we can not hand it out + if w.locked.Has(item.Key) { + return true } - if !w.becameReady.Has(item.Key) { - w.metrics.add(item.Key, item.Priority) - w.becameReady.Insert(item.Key) + + if item.ReadyAt != nil { + if readyAt := item.ReadyAt.Sub(w.now()); readyAt > 0 { + if nextItemReadyAt.After(*item.ReadyAt) || nextItemReadyAt.IsZero() { + nextReady = w.tick(readyAt) + nextItemReadyAt = *item.ReadyAt + } + + // Adjusting the pivot item moves the ascend to the next lower priority + pivot.Priority = item.Priority - 1 + pivotChange = true + return false + } + if !w.becameReady.Has(item.Key) { + w.metrics.add(item.Key, item.Priority) + w.becameReady.Insert(item.Key) + } } - } - if w.waiters.Load() == 0 { - // Have to keep iterating here to ensure we update metrics - // for further items that became ready and set nextReady. - return true - } + if w.waiters.Load() == 0 { + // Have to keep iterating here to ensure we update metrics + // for further items that became ready and set nextReady. + return true + } - // Item is locked, we can not hand it out - if w.locked.Has(item.Key) { - return true - } + w.metrics.get(item.Key, item.Priority) + w.locked.Insert(item.Key) + w.waiters.Add(-1) + delete(w.items, item.Key) + toDelete = append(toDelete, item) + w.becameReady.Delete(item.Key) + w.get <- *item - w.metrics.get(item.Key, item.Priority) - w.locked.Insert(item.Key) - w.waiters.Add(-1) - delete(w.items, item.Key) - toDelete = append(toDelete, item) - w.becameReady.Delete(item.Key) - w.get <- *item + return true + }) - return true - }) + if !pivotChange { + break + } + } for _, item := range toDelete { w.queue.Delete(item) @@ -274,12 +311,27 @@ func (w *priorityqueue[T]) AddRateLimited(item T) { } func (w *priorityqueue[T]) GetWithPriority() (_ T, priority int, shutdown bool) { + if w.shutdown.Load() { + var zero T + return zero, 0, true + } + w.waiters.Add(1) w.notifyItemOrWaiterAdded() - item := <-w.get - return item.Key, item.Priority, w.shutdown.Load() + select { + case <-w.done: + // Return if the queue was shutdown while we were already waiting for an item here. + // For example controller workers are continuously calling GetWithPriority and + // GetWithPriority is blocking the workers if there are no items in the queue. + // If the controller and accordingly the queue is then shut down, without this code + // branch the controller workers remain blocked here and are unable to shut down. + var zero T + return zero, 0, true + case item := <-w.get: + return item.Key, item.Priority, w.shutdown.Load() + } } func (w *priorityqueue[T]) Get() (item T, shutdown bool) { @@ -365,6 +417,9 @@ func (w *priorityqueue[T]) logState() { } func less[T comparable](a, b *item[T]) bool { + if a.Priority != b.Priority { + return a.Priority > b.Priority + } if a.ReadyAt == nil && b.ReadyAt != nil { return true } @@ -374,9 +429,6 @@ func less[T comparable](a, b *item[T]) bool { if a.ReadyAt != nil && b.ReadyAt != nil && !a.ReadyAt.Equal(*b.ReadyAt) { return a.ReadyAt.Before(*b.ReadyAt) } - if a.Priority != b.Priority { - return a.Priority > b.Priority - } return a.AddedCounter < b.AddedCounter } @@ -404,4 +456,5 @@ type bTree[T any] interface { ReplaceOrInsert(item T) (_ T, _ bool) Delete(item T) (T, bool) Ascend(iterator btree.ItemIteratorG[T]) + AscendGreaterOrEqual(pivot T, iterator btree.ItemIteratorG[T]) } diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/envtest/binaries.go b/vendor/sigs.k8s.io/controller-runtime/pkg/envtest/binaries.go index 4c9b1dae3..5110d3265 100644 --- a/vendor/sigs.k8s.io/controller-runtime/pkg/envtest/binaries.go +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/envtest/binaries.go @@ -32,10 +32,9 @@ import ( "path" "path/filepath" "runtime" - "sort" "strings" - "github.com/blang/semver/v4" + "k8s.io/apimachinery/pkg/util/version" "sigs.k8s.io/yaml" ) @@ -111,6 +110,25 @@ type archive struct { SelfLink string `json:"selfLink"` } +// parseKubernetesVersion returns: +// 1. the SemVer form of s when it refers to a specific Kubernetes release, or +// 2. the major and minor portions of s when it refers to a release series, or +// 3. an error +func parseKubernetesVersion(s string) (exact string, major, minor uint, err error) { + if v, err := version.ParseSemantic(s); err == nil { + return v.String(), 0, 0, nil + } + + // See two parseable components and nothing else. + if v, err := version.ParseGeneric(s); err == nil && len(v.Components()) == 2 { + if v.String() == strings.TrimPrefix(s, "v") { + return "", v.Major(), v.Minor(), nil + } + } + + return "", 0, 0, fmt.Errorf("could not parse %q as version", s) +} + func downloadBinaryAssets(ctx context.Context, binaryAssetsDirectory, binaryAssetsVersion, binaryAssetsIndexURL string) (string, string, string, error) { if binaryAssetsIndexURL == "" { binaryAssetsIndexURL = DefaultBinaryAssetsIndexURL @@ -125,14 +143,23 @@ func downloadBinaryAssets(ctx context.Context, binaryAssetsDirectory, binaryAsse } var binaryAssetsIndex *index - if binaryAssetsVersion == "" { - var err error + switch exact, major, minor, err := parseKubernetesVersion(binaryAssetsVersion); { + case binaryAssetsVersion != "" && err != nil: + return "", "", "", err + + case binaryAssetsVersion != "" && exact != "": + // Look for these specific binaries locally before downloading them from the release index. + // Use the canonical form of the version from here on. + binaryAssetsVersion = "v" + exact + + case binaryAssetsVersion == "" || major != 0 || minor != 0: + // Select a stable version from the release index before continuing. binaryAssetsIndex, err = getIndex(ctx, binaryAssetsIndexURL) if err != nil { return "", "", "", err } - binaryAssetsVersion, err = latestStableVersionFromIndex(binaryAssetsIndex) + binaryAssetsVersion, err = latestStableVersionFromIndex(binaryAssetsIndex, major, minor) if err != nil { return "", "", "", err } @@ -252,34 +279,50 @@ func downloadBinaryAssetsArchive(ctx context.Context, index *index, version stri return readBody(resp, out, archiveName, archive.Hash) } -func latestStableVersionFromIndex(index *index) (string, error) { +// latestStableVersionFromIndex returns the version with highest [precedence] in index that is not a prerelease. +// When either major or minor are not zero, the returned version will have those major and minor versions. +// Note that the version cannot be limited to 0.0.x this way. +// +// It is an error when there is no appropriate version in index. +// +// [precedence]: https://semver.org/spec/v2.0.0.html#spec-item-11 +func latestStableVersionFromIndex(index *index, major, minor uint) (string, error) { if len(index.Releases) == 0 { return "", fmt.Errorf("failed to find latest stable version from index: index is empty") } - parsedVersions := []semver.Version{} + var found *version.Version for releaseVersion := range index.Releases { - v, err := semver.ParseTolerant(releaseVersion) + v, err := version.ParseSemantic(releaseVersion) if err != nil { return "", fmt.Errorf("failed to parse version %q: %w", releaseVersion, err) } // Filter out pre-releases. - if len(v.Pre) > 0 { + if len(v.PreRelease()) > 0 { continue } - parsedVersions = append(parsedVersions, v) + // Filter on release series, if any. + if (major != 0 || minor != 0) && (v.Major() != major || v.Minor() != minor) { + continue + } + + if found == nil || v.GreaterThan(found) { + found = v + } } - if len(parsedVersions) == 0 { - return "", fmt.Errorf("failed to find latest stable version from index: index does not have stable versions") + if found == nil { + search := "any" + if major != 0 || minor != 0 { + search = fmt.Sprint(major, ".", minor) + } + + return "", fmt.Errorf("failed to find latest stable version from index: index does not have %s stable versions", search) } - sort.Slice(parsedVersions, func(i, j int) bool { - return parsedVersions[i].GT(parsedVersions[j]) - }) - return "v" + parsedVersions[0].String(), nil + return "v" + found.String(), nil } func getIndex(ctx context.Context, indexURL string) (*index, error) { diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/handler/enqueue_mapped.go b/vendor/sigs.k8s.io/controller-runtime/pkg/handler/enqueue_mapped.go index fe78f21a2..62d672815 100644 --- a/vendor/sigs.k8s.io/controller-runtime/pkg/handler/enqueue_mapped.go +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/handler/enqueue_mapped.go @@ -20,6 +20,7 @@ import ( "context" "k8s.io/client-go/util/workqueue" + "k8s.io/utils/ptr" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/controller/priorityqueue" "sigs.k8s.io/controller-runtime/pkg/event" @@ -141,7 +142,7 @@ func (e *enqueueRequestsFromMapFunc[object, request]) mapAndEnqueue( if !ok { if lowPriority { q.(priorityqueue.PriorityQueue[request]).AddWithOpts(priorityqueue.AddOpts{ - Priority: LowPriority, + Priority: ptr.To(LowPriority), }, req) } else { q.Add(req) diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/handler/eventhandler.go b/vendor/sigs.k8s.io/controller-runtime/pkg/handler/eventhandler.go index 29e755cbf..88510d29e 100644 --- a/vendor/sigs.k8s.io/controller-runtime/pkg/handler/eventhandler.go +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/handler/eventhandler.go @@ -19,8 +19,10 @@ package handler import ( "context" "reflect" + "time" "k8s.io/client-go/util/workqueue" + "k8s.io/utils/ptr" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/controller/priorityqueue" "sigs.k8s.io/controller-runtime/pkg/event" @@ -126,20 +128,14 @@ func (h TypedFuncs[object, request]) Create(ctx context.Context, e event.TypedCr h.CreateFunc(ctx, e, q) return } - wq := workqueueWithCustomAddFunc[request]{ - TypedRateLimitingInterface: q, + + wq := workqueueWithDefaultPriority[request]{ // We already know that we have a priority queue, that event.Object implements // client.Object and that its not nil - addFunc: func(item request, q workqueue.TypedRateLimitingInterface[request]) { - var priority int - if e.IsInInitialList { - priority = LowPriority - } - q.(priorityqueue.PriorityQueue[request]).AddWithOpts( - priorityqueue.AddOpts{Priority: priority}, - item, - ) - }, + PriorityQueue: q.(priorityqueue.PriorityQueue[request]), + } + if e.IsInInitialList { + wq.priority = ptr.To(LowPriority) } h.CreateFunc(ctx, e, wq) } @@ -160,20 +156,13 @@ func (h TypedFuncs[object, request]) Update(ctx context.Context, e event.TypedUp return } - wq := workqueueWithCustomAddFunc[request]{ - TypedRateLimitingInterface: q, + wq := workqueueWithDefaultPriority[request]{ // We already know that we have a priority queue, that event.ObjectOld and ObjectNew implement // client.Object and that they are not nil - addFunc: func(item request, q workqueue.TypedRateLimitingInterface[request]) { - var priority int - if any(e.ObjectOld).(client.Object).GetResourceVersion() == any(e.ObjectNew).(client.Object).GetResourceVersion() { - priority = LowPriority - } - q.(priorityqueue.PriorityQueue[request]).AddWithOpts( - priorityqueue.AddOpts{Priority: priority}, - item, - ) - }, + PriorityQueue: q.(priorityqueue.PriorityQueue[request]), + } + if any(e.ObjectOld).(client.Object).GetResourceVersion() == any(e.ObjectNew).(client.Object).GetResourceVersion() { + wq.priority = ptr.To(LowPriority) } h.UpdateFunc(ctx, e, wq) } @@ -201,13 +190,28 @@ func WithLowPriorityWhenUnchanged[object client.Object, request comparable](u Ty } } -type workqueueWithCustomAddFunc[request comparable] struct { - workqueue.TypedRateLimitingInterface[request] - addFunc func(item request, q workqueue.TypedRateLimitingInterface[request]) +type workqueueWithDefaultPriority[request comparable] struct { + priorityqueue.PriorityQueue[request] + priority *int +} + +func (w workqueueWithDefaultPriority[request]) Add(item request) { + w.PriorityQueue.AddWithOpts(priorityqueue.AddOpts{Priority: w.priority}, item) } -func (w workqueueWithCustomAddFunc[request]) Add(item request) { - w.addFunc(item, w.TypedRateLimitingInterface) +func (w workqueueWithDefaultPriority[request]) AddAfter(item request, after time.Duration) { + w.PriorityQueue.AddWithOpts(priorityqueue.AddOpts{Priority: w.priority, After: after}, item) +} + +func (w workqueueWithDefaultPriority[request]) AddRateLimited(item request) { + w.PriorityQueue.AddWithOpts(priorityqueue.AddOpts{Priority: w.priority, RateLimited: true}, item) +} + +func (w workqueueWithDefaultPriority[request]) AddWithOpts(o priorityqueue.AddOpts, items ...request) { + if o.Priority == nil { + o.Priority = w.priority + } + w.PriorityQueue.AddWithOpts(o, items...) } // addToQueueCreate adds the reconcile.Request to the priorityqueue in the handler @@ -219,9 +223,9 @@ func addToQueueCreate[T client.Object, request comparable](q workqueue.TypedRate return } - var priority int + var priority *int if evt.IsInInitialList { - priority = LowPriority + priority = ptr.To(LowPriority) } priorityQueue.AddWithOpts(priorityqueue.AddOpts{Priority: priority}, item) } @@ -235,9 +239,9 @@ func addToQueueUpdate[T client.Object, request comparable](q workqueue.TypedRate return } - var priority int + var priority *int if evt.ObjectOld.GetResourceVersion() == evt.ObjectNew.GetResourceVersion() { - priority = LowPriority + priority = ptr.To(LowPriority) } priorityQueue.AddWithOpts(priorityqueue.AddOpts{Priority: priority}, item) } diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/internal/controller/controller.go b/vendor/sigs.k8s.io/controller-runtime/pkg/internal/controller/controller.go index 9fa7ec71e..ea7968186 100644 --- a/vendor/sigs.k8s.io/controller-runtime/pkg/internal/controller/controller.go +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/internal/controller/controller.go @@ -30,6 +30,7 @@ import ( utilruntime "k8s.io/apimachinery/pkg/util/runtime" "k8s.io/apimachinery/pkg/util/uuid" "k8s.io/client-go/util/workqueue" + "k8s.io/utils/ptr" "sigs.k8s.io/controller-runtime/pkg/controller/priorityqueue" ctrlmetrics "sigs.k8s.io/controller-runtime/pkg/internal/controller/metrics" @@ -38,6 +39,55 @@ import ( "sigs.k8s.io/controller-runtime/pkg/source" ) +// Options are the arguments for creating a new Controller. +type Options[request comparable] struct { + // Reconciler is a function that can be called at any time with the Name / Namespace of an object and + // ensures that the state of the system matches the state specified in the object. + // Defaults to the DefaultReconcileFunc. + Do reconcile.TypedReconciler[request] + + // RateLimiter is used to limit how frequently requests may be queued into the work queue. + RateLimiter workqueue.TypedRateLimiter[request] + + // NewQueue constructs the queue for this controller once the controller is ready to start. + // This is a func because the standard Kubernetes work queues start themselves immediately, which + // leads to goroutine leaks if something calls controller.New repeatedly. + NewQueue func(controllerName string, rateLimiter workqueue.TypedRateLimiter[request]) workqueue.TypedRateLimitingInterface[request] + + // MaxConcurrentReconciles is the maximum number of concurrent Reconciles which can be run. Defaults to 1. + MaxConcurrentReconciles int + + // CacheSyncTimeout refers to the time limit set on waiting for cache to sync + // Defaults to 2 minutes if not set. + CacheSyncTimeout time.Duration + + // Name is used to uniquely identify a Controller in tracing, logging and monitoring. Name is required. + Name string + + // LogConstructor is used to construct a logger to then log messages to users during reconciliation, + // or for example when a watch is started. + // Note: LogConstructor has to be able to handle nil requests as we are also using it + // outside the context of a reconciliation. + LogConstructor func(request *request) logr.Logger + + // RecoverPanic indicates whether the panic caused by reconcile should be recovered. + // Defaults to true. + RecoverPanic *bool + + // LeaderElected indicates whether the controller is leader elected or always running. + LeaderElected *bool + + // EnableWarmup specifies whether the controller should start its sources + // when the manager is not the leader. + // Defaults to false, which means that the controller will wait for leader election to start + // before starting sources. + EnableWarmup *bool + + // ReconciliationTimeout is used as the timeout passed to the context of each Reconcile call. + // By default, there is no timeout. + ReconciliationTimeout time.Duration +} + // Controller implements controller.Controller. type Controller[request comparable] struct { // Name is used to uniquely identify a Controller in tracing, logging and monitoring. Name is required. @@ -83,6 +133,14 @@ type Controller[request comparable] struct { // startWatches maintains a list of sources, handlers, and predicates to start when the controller is started. startWatches []source.TypedSource[request] + // startedEventSourcesAndQueue is used to track if the event sources have been started. + // It ensures that we append sources to c.startWatches only until we call Start() / Warmup() + // It is true if startEventSourcesAndQueueLocked has been called at least once. + startedEventSourcesAndQueue bool + + // didStartEventSourcesOnce is used to ensure that the event sources are only started once. + didStartEventSourcesOnce sync.Once + // LogConstructor is used to construct a logger to then log messages to users during reconciliation, // or for example when a watch is started. // Note: LogConstructor has to be able to handle nil requests as we are also using it @@ -95,6 +153,38 @@ type Controller[request comparable] struct { // LeaderElected indicates whether the controller is leader elected or always running. LeaderElected *bool + + // EnableWarmup specifies whether the controller should start its sources when the manager is not + // the leader. This is useful for cases where sources take a long time to start, as it allows + // for the controller to warm up its caches even before it is elected as the leader. This + // improves leadership failover time, as the caches will be prepopulated before the controller + // transitions to be leader. + // + // Setting EnableWarmup to true and NeedLeaderElection to true means the controller will start its + // sources without waiting to become leader. + // Setting EnableWarmup to true and NeedLeaderElection to false is a no-op as controllers without + // leader election do not wait on leader election to start their sources. + // Defaults to false. + EnableWarmup *bool + + ReconciliationTimeout time.Duration +} + +// New returns a new Controller configured with the given options. +func New[request comparable](options Options[request]) *Controller[request] { + return &Controller[request]{ + Do: options.Do, + RateLimiter: options.RateLimiter, + NewQueue: options.NewQueue, + MaxConcurrentReconciles: options.MaxConcurrentReconciles, + CacheSyncTimeout: options.CacheSyncTimeout, + Name: options.Name, + LogConstructor: options.LogConstructor, + RecoverPanic: options.RecoverPanic, + LeaderElected: options.LeaderElected, + EnableWarmup: options.EnableWarmup, + ReconciliationTimeout: options.ReconciliationTimeout, + } } // Reconcile implements reconcile.Reconciler. @@ -116,6 +206,13 @@ func (c *Controller[request]) Reconcile(ctx context.Context, req request) (_ rec panic(r) } }() + + if c.ReconciliationTimeout > 0 { + var cancel context.CancelFunc + ctx, cancel = context.WithTimeout(ctx, c.ReconciliationTimeout) + defer cancel() + } + return c.Do.Reconcile(ctx, req) } @@ -124,10 +221,9 @@ func (c *Controller[request]) Watch(src source.TypedSource[request]) error { c.mu.Lock() defer c.mu.Unlock() - // Controller hasn't started yet, store the watches locally and return. - // - // These watches are going to be held on the controller struct until the manager or user calls Start(...). - if !c.Started { + // Sources weren't started yet, store the watches locally and return. + // These sources are going to be held until either Warmup() or Start(...) is called. + if !c.startedEventSourcesAndQueue { c.startWatches = append(c.startWatches, src) return nil } @@ -144,6 +240,21 @@ func (c *Controller[request]) NeedLeaderElection() bool { return *c.LeaderElected } +// Warmup implements the manager.WarmupRunnable interface. +func (c *Controller[request]) Warmup(ctx context.Context) error { + if c.EnableWarmup == nil || !*c.EnableWarmup { + return nil + } + + c.mu.Lock() + defer c.mu.Unlock() + + // Set the ctx so later calls to watch use this internal context + c.ctx = ctx + + return c.startEventSourcesAndQueueLocked(ctx) +} + // Start implements controller.Controller. func (c *Controller[request]) Start(ctx context.Context) error { // use an IIFE to get proper lock handling @@ -158,17 +269,6 @@ func (c *Controller[request]) Start(ctx context.Context) error { // Set the internal context. c.ctx = ctx - queue := c.NewQueue(c.Name, c.RateLimiter) - if priorityQueue, isPriorityQueue := queue.(priorityqueue.PriorityQueue[request]); isPriorityQueue { - c.Queue = priorityQueue - } else { - c.Queue = &priorityQueueWrapper[request]{TypedRateLimitingInterface: queue} - } - go func() { - <-ctx.Done() - c.Queue.ShutDown() - }() - wg := &sync.WaitGroup{} err := func() error { defer c.mu.Unlock() @@ -179,18 +279,12 @@ func (c *Controller[request]) Start(ctx context.Context) error { // NB(directxman12): launch the sources *before* trying to wait for the // caches to sync so that they have a chance to register their intended // caches. - if err := c.startEventSources(ctx); err != nil { + if err := c.startEventSourcesAndQueueLocked(ctx); err != nil { return err } c.LogConstructor(nil).Info("Starting Controller") - // All the watches have been started, we can reset the local slice. - // - // We should never hold watches more than necessary, each watch source can hold a backing cache, - // which won't be garbage collected if we hold a reference to it. - c.startWatches = nil - // Launch workers to process resources c.LogConstructor(nil).Info("Starting workers", "worker count", c.MaxConcurrentReconciles) wg.Add(c.MaxConcurrentReconciles) @@ -218,63 +312,90 @@ func (c *Controller[request]) Start(ctx context.Context) error { return nil } -// startEventSources launches all the sources registered with this controller and waits +// startEventSourcesAndQueueLocked launches all the sources registered with this controller and waits // for them to sync. It returns an error if any of the sources fail to start or sync. -func (c *Controller[request]) startEventSources(ctx context.Context) error { - errGroup := &errgroup.Group{} - for _, watch := range c.startWatches { - log := c.LogConstructor(nil) - _, ok := watch.(interface { - String() string - }) - - if !ok { - log = log.WithValues("source", fmt.Sprintf("%T", watch)) +func (c *Controller[request]) startEventSourcesAndQueueLocked(ctx context.Context) error { + var retErr error + + c.didStartEventSourcesOnce.Do(func() { + queue := c.NewQueue(c.Name, c.RateLimiter) + if priorityQueue, isPriorityQueue := queue.(priorityqueue.PriorityQueue[request]); isPriorityQueue { + c.Queue = priorityQueue } else { - log = log.WithValues("source", fmt.Sprintf("%s", watch)) + c.Queue = &priorityQueueWrapper[request]{TypedRateLimitingInterface: queue} } - didStartSyncingSource := &atomic.Bool{} - errGroup.Go(func() error { - // Use a timeout for starting and syncing the source to avoid silently - // blocking startup indefinitely if it doesn't come up. - sourceStartCtx, cancel := context.WithTimeout(ctx, c.CacheSyncTimeout) - defer cancel() - - sourceStartErrChan := make(chan error, 1) // Buffer chan to not leak goroutine if we time out - go func() { - defer close(sourceStartErrChan) - log.Info("Starting EventSource") - if err := watch.Start(ctx, c.Queue); err != nil { - sourceStartErrChan <- err - return - } - syncingSource, ok := watch.(source.TypedSyncingSource[request]) - if !ok { - return - } - didStartSyncingSource.Store(true) - if err := syncingSource.WaitForSync(sourceStartCtx); err != nil { - err := fmt.Errorf("failed to wait for %s caches to sync %v: %w", c.Name, syncingSource, err) - log.Error(err, "Could not wait for Cache to sync") - sourceStartErrChan <- err + go func() { + <-ctx.Done() + c.Queue.ShutDown() + }() + + errGroup := &errgroup.Group{} + for _, watch := range c.startWatches { + log := c.LogConstructor(nil) + _, ok := watch.(interface { + String() string + }) + if !ok { + log = log.WithValues("source", fmt.Sprintf("%T", watch)) + } else { + log = log.WithValues("source", fmt.Sprintf("%s", watch)) + } + didStartSyncingSource := &atomic.Bool{} + errGroup.Go(func() error { + // Use a timeout for starting and syncing the source to avoid silently + // blocking startup indefinitely if it doesn't come up. + sourceStartCtx, cancel := context.WithTimeout(ctx, c.CacheSyncTimeout) + defer cancel() + + sourceStartErrChan := make(chan error, 1) // Buffer chan to not leak goroutine if we time out + go func() { + defer close(sourceStartErrChan) + log.Info("Starting EventSource") + + if err := watch.Start(ctx, c.Queue); err != nil { + sourceStartErrChan <- err + return + } + syncingSource, ok := watch.(source.TypedSyncingSource[request]) + if !ok { + return + } + didStartSyncingSource.Store(true) + if err := syncingSource.WaitForSync(sourceStartCtx); err != nil { + err := fmt.Errorf("failed to wait for %s caches to sync %v: %w", c.Name, syncingSource, err) + log.Error(err, "Could not wait for Cache to sync") + sourceStartErrChan <- err + } + }() + + select { + case err := <-sourceStartErrChan: + return err + case <-sourceStartCtx.Done(): + if didStartSyncingSource.Load() { // We are racing with WaitForSync, wait for it to let it tell us what happened + return <-sourceStartErrChan + } + if ctx.Err() != nil { // Don't return an error if the root context got cancelled + return nil + } + return fmt.Errorf("timed out waiting for source %s to Start. Please ensure that its Start() method is non-blocking", watch) } - }() + }) + } + retErr = errGroup.Wait() - select { - case err := <-sourceStartErrChan: - return err - case <-sourceStartCtx.Done(): - if didStartSyncingSource.Load() { // We are racing with WaitForSync, wait for it to let it tell us what happened - return <-sourceStartErrChan - } - if ctx.Err() != nil { // Don't return an error if the root context got cancelled - return nil - } - return fmt.Errorf("timed out waiting for source %s to Start. Please ensure that its Start() method is non-blocking", watch) - } - }) - } - return errGroup.Wait() + // All the watches have been started, we can reset the local slice. + // + // We should never hold watches more than necessary, each watch source can hold a backing cache, + // which won't be garbage collected if we hold a reference to it. + c.startWatches = nil + + // Mark event sources as started after resetting the startWatches slice so that watches from + // a new Watch() call are immediately started. + c.startedEventSourcesAndQueue = true + }) + + return retErr } // processNextWorkItem will read a single work item off the workqueue and @@ -343,7 +464,7 @@ func (c *Controller[request]) reconcileHandler(ctx context.Context, req request, if errors.Is(err, reconcile.TerminalError(nil)) { ctrlmetrics.TerminalReconcileErrors.WithLabelValues(c.Name).Inc() } else { - c.Queue.AddWithOpts(priorityqueue.AddOpts{RateLimited: true, Priority: priority}, req) + c.Queue.AddWithOpts(priorityqueue.AddOpts{RateLimited: true, Priority: ptr.To(priority)}, req) } ctrlmetrics.ReconcileErrors.WithLabelValues(c.Name).Inc() ctrlmetrics.ReconcileTotal.WithLabelValues(c.Name, labelError).Inc() @@ -358,11 +479,11 @@ func (c *Controller[request]) reconcileHandler(ctx context.Context, req request, // We need to drive to stable reconcile loops before queuing due // to result.RequestAfter c.Queue.Forget(req) - c.Queue.AddWithOpts(priorityqueue.AddOpts{After: result.RequeueAfter, Priority: priority}, req) + c.Queue.AddWithOpts(priorityqueue.AddOpts{After: result.RequeueAfter, Priority: ptr.To(priority)}, req) ctrlmetrics.ReconcileTotal.WithLabelValues(c.Name, labelRequeueAfter).Inc() case result.Requeue: //nolint: staticcheck // We have to handle it until it is removed log.V(5).Info("Reconcile done, requeueing") - c.Queue.AddWithOpts(priorityqueue.AddOpts{RateLimited: true, Priority: priority}, req) + c.Queue.AddWithOpts(priorityqueue.AddOpts{RateLimited: true, Priority: ptr.To(priority)}, req) ctrlmetrics.ReconcileTotal.WithLabelValues(c.Name, labelRequeue).Inc() default: log.V(5).Info("Reconcile successful") diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/internal/testing/controlplane/apiserver.go b/vendor/sigs.k8s.io/controller-runtime/pkg/internal/testing/controlplane/apiserver.go index bbd2eff64..aadb69e84 100644 --- a/vendor/sigs.k8s.io/controller-runtime/pkg/internal/testing/controlplane/apiserver.go +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/internal/testing/controlplane/apiserver.go @@ -374,7 +374,12 @@ func (s *APIServer) populateAPIServerCerts() error { return err } - servingCerts, err := ca.NewServingCert() + servingAddresses := []string{"localhost"} + if s.SecureServing.ListenAddr.Address != "" { + servingAddresses = append(servingAddresses, s.SecureServing.ListenAddr.Address) + } + + servingCerts, err := ca.NewServingCert(servingAddresses...) if err != nil { return err } diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/internal/testing/controlplane/etcd.go b/vendor/sigs.k8s.io/controller-runtime/pkg/internal/testing/controlplane/etcd.go index c30d21329..98ffe3ac5 100644 --- a/vendor/sigs.k8s.io/controller-runtime/pkg/internal/testing/controlplane/etcd.go +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/internal/testing/controlplane/etcd.go @@ -159,6 +159,10 @@ func (e *Etcd) setProcessState() error { // Stop stops this process gracefully, waits for its termination, and cleans up // the DataDir if necessary. func (e *Etcd) Stop() error { + if e.processState == nil { + return nil + } + if e.processState.DirNeedsCleaning { e.DataDir = "" // reset the directory if it was randomly allocated, so that we can safely restart } diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/leaderelection/leader_election.go b/vendor/sigs.k8s.io/controller-runtime/pkg/leaderelection/leader_election.go index 5cc253917..6c013e799 100644 --- a/vendor/sigs.k8s.io/controller-runtime/pkg/leaderelection/leader_election.go +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/leaderelection/leader_election.go @@ -56,6 +56,10 @@ type Options struct { // Without that, a single slow response from the API server can result // in losing leadership. RenewDeadline time.Duration + + // LeaderLabels are an optional set of labels that will be set on the lease object + // when this replica becomes leader + LeaderLabels map[string]string } // NewResourceLock creates a new resource lock for use in a leader election loop. @@ -63,7 +67,6 @@ func NewResourceLock(config *rest.Config, recorderProvider recorder.Provider, op if !options.LeaderElection { return nil, nil } - // Default resource lock to "leases". The previous default (from v0.7.0 to v0.11.x) was configmapsleases, which was // used to migrate from configmaps to leases. Since the default was "configmapsleases" for over a year, spanning // five minor releases, any actively maintained operators are very likely to have a released version that uses @@ -93,22 +96,21 @@ func NewResourceLock(config *rest.Config, recorderProvider recorder.Provider, op } id = id + "_" + string(uuid.NewUUID()) - // Construct clients for leader election - rest.AddUserAgent(config, "leader-election") + // Construct config for leader election + config = rest.AddUserAgent(config, "leader-election") + // Timeout set for a client used to contact to Kubernetes should be lower than + // RenewDeadline to keep a single hung request from forcing a leader loss. + // Setting it to max(time.Second, RenewDeadline/2) as a reasonable heuristic. if options.RenewDeadline != 0 { - return resourcelock.NewFromKubeconfig(options.LeaderElectionResourceLock, - options.LeaderElectionNamespace, - options.LeaderElectionID, - resourcelock.ResourceLockConfig{ - Identity: id, - EventRecorder: recorderProvider.GetEventRecorderFor(id), - }, - config, - options.RenewDeadline, - ) + timeout := options.RenewDeadline / 2 + if timeout < time.Second { + timeout = time.Second + } + config.Timeout = timeout } + // Construct clients for leader election corev1Client, err := corev1client.NewForConfig(config) if err != nil { return nil, err @@ -118,7 +120,8 @@ func NewResourceLock(config *rest.Config, recorderProvider recorder.Provider, op if err != nil { return nil, err } - return resourcelock.New(options.LeaderElectionResourceLock, + + return resourcelock.NewWithLabels(options.LeaderElectionResourceLock, options.LeaderElectionNamespace, options.LeaderElectionID, corev1Client, @@ -127,6 +130,7 @@ func NewResourceLock(config *rest.Config, recorderProvider recorder.Provider, op Identity: id, EventRecorder: recorderProvider.GetEventRecorderFor(id), }, + options.LeaderLabels, ) } diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/manager/internal.go b/vendor/sigs.k8s.io/controller-runtime/pkg/manager/internal.go index e5204a750..a9f91cbdd 100644 --- a/vendor/sigs.k8s.io/controller-runtime/pkg/manager/internal.go +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/manager/internal.go @@ -439,6 +439,11 @@ func (cm *controllerManager) Start(ctx context.Context) (err error) { return fmt.Errorf("failed to start other runnables: %w", err) } + // Start WarmupRunnables and wait for warmup to complete. + if err := cm.runnables.Warmup.Start(cm.internalCtx); err != nil { + return fmt.Errorf("failed to start warmup runnables: %w", err) + } + // Start the leader election and all required runnables. { ctx, cancel := context.WithCancel(context.Background()) @@ -534,6 +539,18 @@ func (cm *controllerManager) engageStopProcedure(stopComplete <-chan struct{}) e }() go func() { + go func() { + // Stop the warmup runnables in a separate goroutine to avoid blocking. + // It is important to stop the warmup runnables in parallel with the other runnables + // since we cannot assume ordering of whether or not one of the warmup runnables or one + // of the other runnables is holding a lock. + // Cancelling the wrong runnable (one that is not holding the lock) will cause the + // shutdown sequence to block indefinitely as it will wait for the runnable that is + // holding the lock to finish. + cm.logger.Info("Stopping and waiting for warmup runnables") + cm.runnables.Warmup.StopAndWait(cm.shutdownCtx) + }() + // First stop the non-leader election runnables. cm.logger.Info("Stopping and waiting for non leader election runnables") cm.runnables.Others.StopAndWait(cm.shutdownCtx) diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/manager/manager.go b/vendor/sigs.k8s.io/controller-runtime/pkg/manager/manager.go index c3ae317b0..e0e94245e 100644 --- a/vendor/sigs.k8s.io/controller-runtime/pkg/manager/manager.go +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/manager/manager.go @@ -201,10 +201,15 @@ type Options struct { // LeaseDuration time first. LeaderElectionReleaseOnCancel bool + // LeaderElectionLabels allows a controller to supplement all leader election api calls with a set of custom labels based on + // the replica attempting to acquire leader status. + LeaderElectionLabels map[string]string + // LeaderElectionResourceLockInterface allows to provide a custom resourcelock.Interface that was created outside // of the controller-runtime. If this value is set the options LeaderElectionID, LeaderElectionNamespace, - // LeaderElectionResourceLock, LeaseDuration, RenewDeadline and RetryPeriod will be ignored. This can be useful if you - // want to use a locking mechanism that is currently not supported, like a MultiLock across two Kubernetes clusters. + // LeaderElectionResourceLock, LeaseDuration, RenewDeadline, RetryPeriod and LeaderElectionLeases will be ignored. + // This can be useful if you want to use a locking mechanism that is currently not supported, like a MultiLock across + // two Kubernetes clusters. LeaderElectionResourceLockInterface resourcelock.Interface // LeaseDuration is the duration that non-leader candidates will @@ -314,6 +319,15 @@ type LeaderElectionRunnable interface { NeedLeaderElection() bool } +// warmupRunnable knows if a Runnable requires warmup. A warmup runnable is a runnable +// that should be run when the manager is started but before it becomes leader. +// Note: Implementing this interface is only useful when LeaderElection can be enabled, as the +// behavior when leaderelection is not enabled is to run LeaderElectionRunnables immediately. +type warmupRunnable interface { + // Warmup will be called when the manager is started but before it becomes leader. + Warmup(context.Context) error +} + // New returns a new Manager for creating Controllers. // Note that if ContentType in the given config is not set, "application/vnd.kubernetes.protobuf" // will be used for all built-in resources of Kubernetes, and "application/json" is for other types @@ -390,6 +404,7 @@ func New(config *rest.Config, options Options) (Manager, error) { LeaderElectionID: options.LeaderElectionID, LeaderElectionNamespace: options.LeaderElectionNamespace, RenewDeadline: *options.RenewDeadline, + LeaderLabels: options.LeaderElectionLabels, }) if err != nil { return nil, err @@ -417,7 +432,7 @@ func New(config *rest.Config, options Options) (Manager, error) { } errChan := make(chan error, 1) - runnables := newRunnables(options.BaseContext, errChan) + runnables := newRunnables(options.BaseContext, errChan).withLogger(options.Logger) return &controllerManager{ stopProcedureEngaged: ptr.To(int64(0)), cluster: cluster, diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/manager/runnable_group.go b/vendor/sigs.k8s.io/controller-runtime/pkg/manager/runnable_group.go index db5cda7c8..53e29fc56 100644 --- a/vendor/sigs.k8s.io/controller-runtime/pkg/manager/runnable_group.go +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/manager/runnable_group.go @@ -5,6 +5,7 @@ import ( "errors" "sync" + "github.com/go-logr/logr" "sigs.k8s.io/controller-runtime/pkg/webhook" ) @@ -32,6 +33,7 @@ type runnables struct { Webhooks *runnableGroup Caches *runnableGroup LeaderElection *runnableGroup + Warmup *runnableGroup Others *runnableGroup } @@ -42,10 +44,21 @@ func newRunnables(baseContext BaseContextFunc, errChan chan error) *runnables { Webhooks: newRunnableGroup(baseContext, errChan), Caches: newRunnableGroup(baseContext, errChan), LeaderElection: newRunnableGroup(baseContext, errChan), + Warmup: newRunnableGroup(baseContext, errChan), Others: newRunnableGroup(baseContext, errChan), } } +// withLogger returns the runnables with the logger set for all runnable groups. +func (r *runnables) withLogger(logger logr.Logger) *runnables { + r.HTTPServers.withLogger(logger) + r.Webhooks.withLogger(logger) + r.Caches.withLogger(logger) + r.LeaderElection.withLogger(logger) + r.Others.withLogger(logger) + return r +} + // Add adds a runnable to closest group of runnable that they belong to. // // Add should be able to be called before and after Start, but not after StopAndWait. @@ -65,8 +78,20 @@ func (r *runnables) Add(fn Runnable) error { }) case webhook.Server: return r.Webhooks.Add(fn, nil) - case LeaderElectionRunnable: - if !runnable.NeedLeaderElection() { + case warmupRunnable, LeaderElectionRunnable: + if warmupRunnable, ok := fn.(warmupRunnable); ok { + if err := r.Warmup.Add(RunnableFunc(warmupRunnable.Warmup), nil); err != nil { + return err + } + } + + leaderElectionRunnable, ok := fn.(LeaderElectionRunnable) + if !ok { + // If the runnable is not a LeaderElectionRunnable, add it to the leader election group for backwards compatibility + return r.LeaderElection.Add(fn, nil) + } + + if !leaderElectionRunnable.NeedLeaderElection() { return r.Others.Add(fn, nil) } return r.LeaderElection.Add(fn, nil) @@ -105,6 +130,9 @@ type runnableGroup struct { // wg is an internal sync.WaitGroup that allows us to properly stop // and wait for all the runnables to finish before returning. wg *sync.WaitGroup + + // logger is used for logging when errors are dropped during shutdown + logger logr.Logger } func newRunnableGroup(baseContext BaseContextFunc, errChan chan error) *runnableGroup { @@ -113,12 +141,18 @@ func newRunnableGroup(baseContext BaseContextFunc, errChan chan error) *runnable errChan: errChan, ch: make(chan *readyRunnable), wg: new(sync.WaitGroup), + logger: logr.Discard(), // Default to no-op logger } r.ctx, r.cancel = context.WithCancel(baseContext()) return r } +// withLogger sets the logger for this runnable group. +func (r *runnableGroup) withLogger(logger logr.Logger) { + r.logger = logger +} + // Started returns true if the group has started. func (r *runnableGroup) Started() bool { r.start.Lock() @@ -224,7 +258,27 @@ func (r *runnableGroup) reconcile() { // Start the runnable. if err := rn.Start(r.ctx); err != nil { - r.errChan <- err + // Check if we're during the shutdown process. + r.stop.RLock() + isStopped := r.stopped + r.stop.RUnlock() + + if isStopped { + // During shutdown, try to send error first (error drain goroutine might still be running) + // but drop if it would block to prevent goroutine leaks + select { + case r.errChan <- err: + // Error sent successfully (error drain goroutine is still running) + default: + // Error drain goroutine has exited, drop error to prevent goroutine leak + if !errors.Is(err, context.Canceled) { // don't log context.Canceled errors as they are expected during shutdown + r.logger.Info("error dropped during shutdown to prevent goroutine leak", "error", err) + } + } + } else { + // During normal operation, always try to send errors (may block briefly) + r.errChan <- err + } } }(runnable) } diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/manager/server.go b/vendor/sigs.k8s.io/controller-runtime/pkg/manager/server.go index 76f6165b5..1983165da 100644 --- a/vendor/sigs.k8s.io/controller-runtime/pkg/manager/server.go +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/manager/server.go @@ -70,7 +70,7 @@ func (s *Server) Start(ctx context.Context) error { shutdownCtx := context.Background() if s.ShutdownTimeout != nil { var shutdownCancel context.CancelFunc - shutdownCtx, shutdownCancel = context.WithTimeout(context.Background(), *s.ShutdownTimeout) + shutdownCtx, shutdownCancel = context.WithTimeout(shutdownCtx, *s.ShutdownTimeout) defer shutdownCancel() } diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/predicate/predicate.go b/vendor/sigs.k8s.io/controller-runtime/pkg/predicate/predicate.go index ce33975f3..9f24cb178 100644 --- a/vendor/sigs.k8s.io/controller-runtime/pkg/predicate/predicate.go +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/predicate/predicate.go @@ -47,13 +47,15 @@ type TypedPredicate[object any] interface { Generic(event.TypedGenericEvent[object]) bool } -var _ Predicate = Funcs{} -var _ Predicate = ResourceVersionChangedPredicate{} -var _ Predicate = GenerationChangedPredicate{} -var _ Predicate = AnnotationChangedPredicate{} -var _ Predicate = or[client.Object]{} -var _ Predicate = and[client.Object]{} -var _ Predicate = not[client.Object]{} +var ( + _ Predicate = Funcs{} + _ Predicate = ResourceVersionChangedPredicate{} + _ Predicate = GenerationChangedPredicate{} + _ Predicate = AnnotationChangedPredicate{} + _ Predicate = or[client.Object]{} + _ Predicate = and[client.Object]{} + _ Predicate = not[client.Object]{} +) // Funcs is a function that implements Predicate. type Funcs = TypedFuncs[client.Object] @@ -259,11 +261,10 @@ func (TypedAnnotationChangedPredicate[object]) Update(e event.TypedUpdateEvent[o // This predicate will skip update events that have no change in the object's label. // It is intended to be used in conjunction with the GenerationChangedPredicate, as in the following example: // -// Controller.Watch( -// -// &source.Kind{Type: v1.MyCustomKind}, -// &handler.EnqueueRequestForObject{}, -// predicate.Or(predicate.GenerationChangedPredicate{}, predicate.LabelChangedPredicate{})) +// Controller.Watch( +// &source.Kind{Type: v1.MyCustomKind}, +// &handler.EnqueueRequestForObject{}, +// predicate.Or(predicate.GenerationChangedPredicate{}, predicate.LabelChangedPredicate{})) // // This will be helpful when object's labels is carrying some extra specification information beyond object's spec, // and the controller will be triggered if any valid spec change (not only in spec, but also in labels) happens. diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/webhook/conversion/conversion.go b/vendor/sigs.k8s.io/controller-runtime/pkg/webhook/conversion/conversion.go index 249a364b3..a26fa348b 100644 --- a/vendor/sigs.k8s.io/controller-runtime/pkg/webhook/conversion/conversion.go +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/webhook/conversion/conversion.go @@ -22,7 +22,9 @@ See pkg/conversion for interface definitions required to ensure an API Type is c package conversion import ( + "context" "encoding/json" + "errors" "fmt" "net/http" @@ -31,8 +33,10 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" + utilruntime "k8s.io/apimachinery/pkg/util/runtime" "sigs.k8s.io/controller-runtime/pkg/conversion" logf "sigs.k8s.io/controller-runtime/pkg/log" + conversionmetrics "sigs.k8s.io/controller-runtime/pkg/webhook/conversion/metrics" ) var ( @@ -53,6 +57,8 @@ type webhook struct { var _ http.Handler = &webhook{} func (wh *webhook) ServeHTTP(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + convertReview := &apix.ConversionReview{} err := json.NewDecoder(r.Body).Decode(convertReview) if err != nil { @@ -69,7 +75,7 @@ func (wh *webhook) ServeHTTP(w http.ResponseWriter, r *http.Request) { // TODO(droot): may be move the conversion logic to a separate module to // decouple it from the http layer ? - resp, err := wh.handleConvertRequest(convertReview.Request) + resp, err := wh.handleConvertRequest(ctx, convertReview.Request) if err != nil { log.Error(err, "failed to convert", "request", convertReview.Request.UID) convertReview.Response = errored(err) @@ -87,7 +93,18 @@ func (wh *webhook) ServeHTTP(w http.ResponseWriter, r *http.Request) { } // handles a version conversion request. -func (wh *webhook) handleConvertRequest(req *apix.ConversionRequest) (*apix.ConversionResponse, error) { +func (wh *webhook) handleConvertRequest(ctx context.Context, req *apix.ConversionRequest) (_ *apix.ConversionResponse, retErr error) { + defer func() { + if r := recover(); r != nil { + conversionmetrics.WebhookPanics.WithLabelValues().Inc() + + for _, fn := range utilruntime.PanicHandlers { + fn(ctx, r) + } + retErr = errors.New("internal error occurred during conversion") + return + } + }() if req == nil { return nil, fmt.Errorf("conversion request is nil") } diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/webhook/conversion/metrics/metrics.go b/vendor/sigs.k8s.io/controller-runtime/pkg/webhook/conversion/metrics/metrics.go new file mode 100644 index 000000000..c825f17f0 --- /dev/null +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/webhook/conversion/metrics/metrics.go @@ -0,0 +1,39 @@ +/* +Copyright 2025 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package metrics + +import ( + "github.com/prometheus/client_golang/prometheus" + "sigs.k8s.io/controller-runtime/pkg/metrics" +) + +var ( + // WebhookPanics is a prometheus counter metrics which holds the total + // number of panics from conversion webhooks. + WebhookPanics = prometheus.NewCounterVec(prometheus.CounterOpts{ + Name: "controller_runtime_conversion_webhook_panics_total", + Help: "Total number of conversion webhook panics", + }, []string{}) +) + +func init() { + metrics.Registry.MustRegister( + WebhookPanics, + ) + // Init metric. + WebhookPanics.WithLabelValues().Add(0) +} diff --git a/vendor/sigs.k8s.io/kustomize/api/filters/nameref/nameref.go b/vendor/sigs.k8s.io/kustomize/api/filters/nameref/nameref.go index ff83420cb..c25cf8282 100644 --- a/vendor/sigs.k8s.io/kustomize/api/filters/nameref/nameref.go +++ b/vendor/sigs.k8s.io/kustomize/api/filters/nameref/nameref.go @@ -205,16 +205,14 @@ func getRoleRefGvk(n *resource.Resource) (*resid.Gvk, error) { return nil, err } if apiGroup.IsNil() { - return nil, fmt.Errorf( - "apiGroup cannot be found in roleRef %s", roleRef.MustString()) + return nil, fmt.Errorf("apiGroup cannot be found in roleRef %s", roleRef.MustString()) } kind, err := roleRef.Pipe(yaml.Lookup("kind")) if err != nil { return nil, err } if kind.IsNil() { - return nil, fmt.Errorf( - "kind cannot be found in roleRef %s", roleRef.MustString()) + return nil, fmt.Errorf("kind cannot be found in roleRef %s", roleRef.MustString()) } return &resid.Gvk{ Group: apiGroup.YNode().Value, diff --git a/vendor/sigs.k8s.io/kustomize/api/filters/replacement/replacement.go b/vendor/sigs.k8s.io/kustomize/api/filters/replacement/replacement.go index 56e70d875..8afc646d2 100644 --- a/vendor/sigs.k8s.io/kustomize/api/filters/replacement/replacement.go +++ b/vendor/sigs.k8s.io/kustomize/api/filters/replacement/replacement.go @@ -4,6 +4,7 @@ package replacement import ( + "encoding/json" "fmt" "strings" @@ -11,7 +12,6 @@ import ( "sigs.k8s.io/kustomize/api/resource" "sigs.k8s.io/kustomize/api/types" "sigs.k8s.io/kustomize/kyaml/errors" - "sigs.k8s.io/kustomize/kyaml/resid" kyaml_utils "sigs.k8s.io/kustomize/kyaml/utils" "sigs.k8s.io/kustomize/kyaml/yaml" ) @@ -117,6 +117,10 @@ func applyReplacement(nodes []*yaml.RNode, value *yaml.RNode, targetSelectors [] if len(selector.FieldPaths) == 0 { selector.FieldPaths = []string{types.DefaultReplacementFieldPath} } + tsr, err := types.NewTargetSelectorRegex(selector) + if err != nil { + return nil, fmt.Errorf("error creating target selector: %w", err) + } for _, possibleTarget := range nodes { ids, err := utils.MakeResIds(possibleTarget) if err != nil { @@ -132,9 +136,13 @@ func applyReplacement(nodes []*yaml.RNode, value *yaml.RNode, targetSelectors [] continue } + if tsr.RejectsAny(ids) { + continue + } + // filter targets by matching resource IDs for _, id := range ids { - if id.IsSelectedBy(selector.Select.ResId) && !containsRejectId(selector.Reject, ids) { + if tsr.Selects(id) { err := copyValueToTarget(possibleTarget, value, selector) if err != nil { return nil, err @@ -175,43 +183,37 @@ func matchesAnnoAndLabelSelector(n *yaml.RNode, selector *types.Selector) (bool, return annoMatch && labelMatch, nil } -func containsRejectId(rejects []*types.Selector, ids []resid.ResId) bool { - for _, r := range rejects { - if r.ResId.IsEmpty() { - continue - } - for _, id := range ids { - if id.IsSelectedBy(r.ResId) { - return true - } - } - } - return false -} - func copyValueToTarget(target *yaml.RNode, value *yaml.RNode, selector *types.TargetSelector) error { for _, fp := range selector.FieldPaths { createKind := yaml.Kind(0) // do not create if selector.Options != nil && selector.Options.Create { createKind = value.YNode().Kind } + + // Check if this fieldPath contains structured data access + if err := setValueInStructuredData(target, value, fp, createKind); err == nil { + // Successfully handled as structured data + continue + } + + // Fall back to normal path handling targetFieldList, err := target.Pipe(&yaml.PathMatcher{ Path: kyaml_utils.SmarterPathSplitter(fp, "."), Create: createKind}) if err != nil { - return errors.WrapPrefixf(err, fieldRetrievalError(fp, createKind != 0)) //nolint:govet + return errors.WrapPrefixf(err, "%s", fieldRetrievalError(fp, createKind != 0)) } targetFields, err := targetFieldList.Elements() if err != nil { - return errors.WrapPrefixf(err, fieldRetrievalError(fp, createKind != 0)) //nolint:govet + return errors.WrapPrefixf(err, "%s", fieldRetrievalError(fp, createKind != 0)) } if len(targetFields) == 0 { - return errors.Errorf(fieldRetrievalError(fp, createKind != 0)) //nolint:govet + return errors.Errorf("%s", fieldRetrievalError(fp, createKind != 0)) } for _, t := range targetFields { if err := setFieldValue(selector.Options, t, value); err != nil { - return err + return fmt.Errorf("%w", err) } } } @@ -254,3 +256,146 @@ func setFieldValue(options *types.FieldOptions, targetField *yaml.RNode, value * return nil } + +// setValueInStructuredData handles setting values within structured data (JSON/YAML) in scalar fields +func setValueInStructuredData(target *yaml.RNode, value *yaml.RNode, fieldPath string, createKind yaml.Kind) error { + pathParts := kyaml_utils.SmarterPathSplitter(fieldPath, ".") + if len(pathParts) < 2 { + return fmt.Errorf("not a structured data path") + } + + // Find the potential scalar field that might contain structured data + var scalarFieldPath []string + var structuredDataPath []string + var foundScalar = false + + // Try to find where the scalar field ends and structured data begins + for i := 1; i <= len(pathParts); i++ { + potentialScalarPath := pathParts[:i] + scalarField, err := target.Pipe(yaml.Lookup(potentialScalarPath...)) + if err != nil { + continue + } + if scalarField != nil && scalarField.YNode().Kind == yaml.ScalarNode && i < len(pathParts) { + // Try to parse the scalar value as structured data + scalarValue := scalarField.YNode().Value + var parsedNode yaml.Node + if err := yaml.Unmarshal([]byte(scalarValue), &parsedNode); err == nil { + // Successfully parsed - this is structured data + scalarFieldPath = potentialScalarPath + structuredDataPath = pathParts[i:] + foundScalar = true + break + } + } + } + + if !foundScalar { + return fmt.Errorf("no structured data found in path") + } + + // Get the scalar field containing structured data + scalarField, err := target.Pipe(yaml.Lookup(scalarFieldPath...)) + if err != nil { + return fmt.Errorf("%w", err) + } + + // Parse the structured data + scalarValue := scalarField.YNode().Value + var parsedNode yaml.Node + if err := yaml.Unmarshal([]byte(scalarValue), &parsedNode); err != nil { + return fmt.Errorf("%w", err) + } + + structuredData := yaml.NewRNode(&parsedNode) + + // Navigate to the target location within the structured data + targetInStructured, err := structuredData.Pipe(&yaml.PathMatcher{ + Path: structuredDataPath, + Create: createKind, + }) + if err != nil { + return fmt.Errorf("%w", err) + } + + targetFields, err := targetInStructured.Elements() + if err != nil { + return fmt.Errorf("%w", err) + } + + if len(targetFields) == 0 { + return fmt.Errorf("unable to find field in structured data") + } + + // Set the value in the structured data + for _, t := range targetFields { + if t.YNode().Kind == yaml.ScalarNode { + t.YNode().Value = value.YNode().Value + } else { + t.SetYNode(value.YNode()) + } + } + + // Serialize the modified structured data back to the scalar field + // Try to detect if original was JSON or YAML and preserve formatting + serializedData, err := serializeStructuredData(structuredData, scalarValue) + if err != nil { + return fmt.Errorf("%w", err) + } + + // Update the original scalar field + scalarField.YNode().Value = serializedData + + return nil +} + +// serializeStructuredData handles the serialization of structured data back to string format +// preserving the original format (JSON vs YAML) and style (pretty vs compact) +func serializeStructuredData(structuredData *yaml.RNode, originalValue string) (string, error) { + firstChar := rune(strings.TrimSpace(originalValue)[0]) + if firstChar == '{' || firstChar == '[' { + return serializeAsJSON(structuredData, originalValue) + } + + // Fallback to YAML format + return serializeAsYAML(structuredData) +} + +// serializeAsJSON converts structured data back to JSON format +func serializeAsJSON(structuredData *yaml.RNode, originalValue string) (string, error) { + modifiedData, err := structuredData.String() + if err != nil { + return "", fmt.Errorf("failed to serialize structured data: %w", err) + } + + // Parse the YAML output as JSON + var jsonData interface{} + if err := yaml.Unmarshal([]byte(modifiedData), &jsonData); err != nil { + return "", fmt.Errorf("failed to unmarshal YAML data: %w", err) + } + + // Check if original was pretty-printed by looking for newlines and indentation + if strings.Contains(originalValue, "\n") && strings.Contains(originalValue, " ") { + // Pretty-print the JSON to match original formatting + if prettyJSON, err := json.MarshalIndent(jsonData, "", " "); err == nil { + return string(prettyJSON), nil + } + } + + // Compact JSON + if compactJSON, err := json.Marshal(jsonData); err == nil { + return string(compactJSON), nil + } + + return "", fmt.Errorf("failed to marshal JSON data") +} + +// serializeAsYAML converts structured data back to YAML format +func serializeAsYAML(structuredData *yaml.RNode) (string, error) { + modifiedData, err := structuredData.String() + if err != nil { + return "", fmt.Errorf("failed to serialize YAML data: %w", err) + } + + return strings.TrimSpace(modifiedData), nil +} diff --git a/vendor/sigs.k8s.io/kustomize/api/internal/builtins/AnnotationsTransformer.go b/vendor/sigs.k8s.io/kustomize/api/internal/builtins/AnnotationsTransformer.go index 0910c472b..d3b3fc8c2 100644 --- a/vendor/sigs.k8s.io/kustomize/api/internal/builtins/AnnotationsTransformer.go +++ b/vendor/sigs.k8s.io/kustomize/api/internal/builtins/AnnotationsTransformer.go @@ -1,6 +1,4 @@ // Code generated by pluginator on AnnotationsTransformer; DO NOT EDIT. -// pluginator {(devel) unknown } - package builtins import ( diff --git a/vendor/sigs.k8s.io/kustomize/api/internal/builtins/ConfigMapGenerator.go b/vendor/sigs.k8s.io/kustomize/api/internal/builtins/ConfigMapGenerator.go index dc18bce85..180a6c2c1 100644 --- a/vendor/sigs.k8s.io/kustomize/api/internal/builtins/ConfigMapGenerator.go +++ b/vendor/sigs.k8s.io/kustomize/api/internal/builtins/ConfigMapGenerator.go @@ -1,6 +1,4 @@ // Code generated by pluginator on ConfigMapGenerator; DO NOT EDIT. -// pluginator {(devel) unknown } - package builtins import ( diff --git a/vendor/sigs.k8s.io/kustomize/api/internal/builtins/HashTransformer.go b/vendor/sigs.k8s.io/kustomize/api/internal/builtins/HashTransformer.go index ec2331265..08dd37d06 100644 --- a/vendor/sigs.k8s.io/kustomize/api/internal/builtins/HashTransformer.go +++ b/vendor/sigs.k8s.io/kustomize/api/internal/builtins/HashTransformer.go @@ -1,6 +1,4 @@ // Code generated by pluginator on HashTransformer; DO NOT EDIT. -// pluginator {(devel) unknown } - package builtins import ( diff --git a/vendor/sigs.k8s.io/kustomize/api/internal/builtins/HelmChartInflationGenerator.go b/vendor/sigs.k8s.io/kustomize/api/internal/builtins/HelmChartInflationGenerator.go index 5811e73ec..7a148f81e 100644 --- a/vendor/sigs.k8s.io/kustomize/api/internal/builtins/HelmChartInflationGenerator.go +++ b/vendor/sigs.k8s.io/kustomize/api/internal/builtins/HelmChartInflationGenerator.go @@ -1,6 +1,4 @@ // Code generated by pluginator on HelmChartInflationGenerator; DO NOT EDIT. -// pluginator {(devel) unknown } - package builtins import ( @@ -13,6 +11,7 @@ import ( "slices" "strings" + "sigs.k8s.io/kustomize/api/konfig" "sigs.k8s.io/kustomize/api/resmap" "sigs.k8s.io/kustomize/api/types" "sigs.k8s.io/kustomize/kyaml/errors" @@ -178,12 +177,11 @@ func (p *HelmChartInflationGeneratorPlugin) runHelmCommand( } if err != nil { helm := p.h.GeneralConfig().HelmConfig.Command - //nolint:govet err = errors.WrapPrefixf( fmt.Errorf( "unable to run: '%s %s' with env=%s (is '%s' installed?): %w", helm, strings.Join(args, " "), env, helm, err), - errorOutput, + "%s", errorOutput, ) } return stdout.Bytes(), err @@ -297,6 +295,9 @@ func (p *HelmChartInflationGeneratorPlugin) Generate() (rm resmap.ResMap, err er rm, resMapErr := p.h.ResmapFactory().NewResMapFromBytes(stdout) if resMapErr == nil { + if err := p.markHelmGeneratedResources(rm); err != nil { + return nil, err + } return rm, nil } // try to remove the contents before first "---" because @@ -312,6 +313,9 @@ func (p *HelmChartInflationGeneratorPlugin) Generate() (rm resmap.ResMap, err er if err != nil { return nil, fmt.Errorf("could not parse rnode slice into resource map: %w", err) } + if err := p.markHelmGeneratedResources(rm); err != nil { + return nil, err + } return rm, nil } return nil, fmt.Errorf("could not parse bytes into resource map: %w", resMapErr) @@ -354,6 +358,15 @@ func (p *HelmChartInflationGeneratorPlugin) chartExistsLocally() (string, bool) return path, s.IsDir() } +func (p *HelmChartInflationGeneratorPlugin) markHelmGeneratedResources(rm resmap.ResMap) error { + for _, r := range rm.Resources() { + if err := r.RNode.PipeE(kyaml.SetAnnotation(konfig.HelmGeneratedAnnotation, "true")); err != nil { + return fmt.Errorf("failed to set helm annotation: %w", err) + } + } + return nil +} + // checkHelmVersion will return an error if the helm version is not V3 func (p *HelmChartInflationGeneratorPlugin) checkHelmVersion() error { stdout, err := p.runHelmCommand([]string{"version", "-c", "--short"}) diff --git a/vendor/sigs.k8s.io/kustomize/api/internal/builtins/IAMPolicyGenerator.go b/vendor/sigs.k8s.io/kustomize/api/internal/builtins/IAMPolicyGenerator.go index cfb1fa81b..314e60c7c 100644 --- a/vendor/sigs.k8s.io/kustomize/api/internal/builtins/IAMPolicyGenerator.go +++ b/vendor/sigs.k8s.io/kustomize/api/internal/builtins/IAMPolicyGenerator.go @@ -1,6 +1,4 @@ // Code generated by pluginator on IAMPolicyGenerator; DO NOT EDIT. -// pluginator {(devel) unknown } - package builtins import ( diff --git a/vendor/sigs.k8s.io/kustomize/api/internal/builtins/ImageTagTransformer.go b/vendor/sigs.k8s.io/kustomize/api/internal/builtins/ImageTagTransformer.go index ffde73a7a..c5284cb70 100644 --- a/vendor/sigs.k8s.io/kustomize/api/internal/builtins/ImageTagTransformer.go +++ b/vendor/sigs.k8s.io/kustomize/api/internal/builtins/ImageTagTransformer.go @@ -1,6 +1,4 @@ // Code generated by pluginator on ImageTagTransformer; DO NOT EDIT. -// pluginator {(devel) unknown } - package builtins import ( diff --git a/vendor/sigs.k8s.io/kustomize/api/internal/builtins/LabelTransformer.go b/vendor/sigs.k8s.io/kustomize/api/internal/builtins/LabelTransformer.go index c45731b54..8ebbd19f7 100644 --- a/vendor/sigs.k8s.io/kustomize/api/internal/builtins/LabelTransformer.go +++ b/vendor/sigs.k8s.io/kustomize/api/internal/builtins/LabelTransformer.go @@ -1,6 +1,4 @@ // Code generated by pluginator on LabelTransformer; DO NOT EDIT. -// pluginator {(devel) unknown } - package builtins import ( diff --git a/vendor/sigs.k8s.io/kustomize/api/internal/builtins/NamespaceTransformer.go b/vendor/sigs.k8s.io/kustomize/api/internal/builtins/NamespaceTransformer.go index d839fb975..3b98195b3 100644 --- a/vendor/sigs.k8s.io/kustomize/api/internal/builtins/NamespaceTransformer.go +++ b/vendor/sigs.k8s.io/kustomize/api/internal/builtins/NamespaceTransformer.go @@ -1,12 +1,11 @@ // Code generated by pluginator on NamespaceTransformer; DO NOT EDIT. -// pluginator {(devel) unknown } - package builtins import ( "fmt" "sigs.k8s.io/kustomize/api/filters/namespace" + "sigs.k8s.io/kustomize/api/konfig" "sigs.k8s.io/kustomize/api/resmap" "sigs.k8s.io/kustomize/api/types" "sigs.k8s.io/kustomize/kyaml/errors" @@ -53,6 +52,10 @@ func (p *NamespaceTransformerPlugin) Transform(m resmap.ResMap) error { // Don't mutate empty objects? continue } + if annotations := r.GetAnnotations(konfig.HelmGeneratedAnnotation); annotations[konfig.HelmGeneratedAnnotation] == "true" { + // Don't apply namespace on Helm generated manifest. Helm should take care of it. + continue + } r.StorePreviousId() if err := r.ApplyFilter(namespace.Filter{ Namespace: p.Namespace, diff --git a/vendor/sigs.k8s.io/kustomize/api/internal/builtins/PatchJson6902Transformer.go b/vendor/sigs.k8s.io/kustomize/api/internal/builtins/PatchJson6902Transformer.go index 04625e510..348863263 100644 --- a/vendor/sigs.k8s.io/kustomize/api/internal/builtins/PatchJson6902Transformer.go +++ b/vendor/sigs.k8s.io/kustomize/api/internal/builtins/PatchJson6902Transformer.go @@ -1,6 +1,4 @@ // Code generated by pluginator on PatchJson6902Transformer; DO NOT EDIT. -// pluginator {(devel) unknown } - package builtins import ( diff --git a/vendor/sigs.k8s.io/kustomize/api/internal/builtins/PatchStrategicMergeTransformer.go b/vendor/sigs.k8s.io/kustomize/api/internal/builtins/PatchStrategicMergeTransformer.go index d68f2425e..29f8f2b9d 100644 --- a/vendor/sigs.k8s.io/kustomize/api/internal/builtins/PatchStrategicMergeTransformer.go +++ b/vendor/sigs.k8s.io/kustomize/api/internal/builtins/PatchStrategicMergeTransformer.go @@ -1,6 +1,4 @@ // Code generated by pluginator on PatchStrategicMergeTransformer; DO NOT EDIT. -// pluginator {(devel) unknown } - package builtins import ( diff --git a/vendor/sigs.k8s.io/kustomize/api/internal/builtins/PatchTransformer.go b/vendor/sigs.k8s.io/kustomize/api/internal/builtins/PatchTransformer.go index 05d96f23c..278d10093 100644 --- a/vendor/sigs.k8s.io/kustomize/api/internal/builtins/PatchTransformer.go +++ b/vendor/sigs.k8s.io/kustomize/api/internal/builtins/PatchTransformer.go @@ -1,6 +1,4 @@ // Code generated by pluginator on PatchTransformer; DO NOT EDIT. -// pluginator {(devel) unknown } - package builtins import ( @@ -24,10 +22,10 @@ type PatchTransformerPlugin struct { patchText string // patchSource is patch source message patchSource string - Path string `json:"path,omitempty" yaml:"path,omitempty"` - Patch string `json:"patch,omitempty" yaml:"patch,omitempty"` - Target *types.Selector `json:"target,omitempty" yaml:"target,omitempty"` - Options map[string]bool `json:"options,omitempty" yaml:"options,omitempty"` + Path string `json:"path,omitempty" yaml:"path,omitempty"` + Patch string `json:"patch,omitempty" yaml:"patch,omitempty"` + Target *types.Selector `json:"target,omitempty" yaml:"target,omitempty"` + Options *types.PatchArgs `json:"options,omitempty" yaml:"options,omitempty"` } func (p *PatchTransformerPlugin) Config(h *resmap.PluginHelpers, c []byte) error { @@ -70,10 +68,14 @@ func (p *PatchTransformerPlugin) Config(h *resmap.PluginHelpers, c []byte) error if errSM == nil { p.smPatches = patchesSM for _, loadedPatch := range p.smPatches { - if p.Options["allowNameChange"] { + if p.Options == nil { + continue + } + + if p.Options.AllowNameChange { loadedPatch.AllowNameChange() } - if p.Options["allowKindChange"] { + if p.Options.AllowKindChange { loadedPatch.AllowKindChange() } } diff --git a/vendor/sigs.k8s.io/kustomize/api/internal/builtins/PrefixTransformer.go b/vendor/sigs.k8s.io/kustomize/api/internal/builtins/PrefixTransformer.go index 33700bb4b..fc26de228 100644 --- a/vendor/sigs.k8s.io/kustomize/api/internal/builtins/PrefixTransformer.go +++ b/vendor/sigs.k8s.io/kustomize/api/internal/builtins/PrefixTransformer.go @@ -1,6 +1,4 @@ // Code generated by pluginator on PrefixTransformer; DO NOT EDIT. -// pluginator {(devel) unknown } - package builtins import ( diff --git a/vendor/sigs.k8s.io/kustomize/api/internal/builtins/ReplacementTransformer.go b/vendor/sigs.k8s.io/kustomize/api/internal/builtins/ReplacementTransformer.go index ef0c93212..795af7b87 100644 --- a/vendor/sigs.k8s.io/kustomize/api/internal/builtins/ReplacementTransformer.go +++ b/vendor/sigs.k8s.io/kustomize/api/internal/builtins/ReplacementTransformer.go @@ -1,6 +1,4 @@ // Code generated by pluginator on ReplacementTransformer; DO NOT EDIT. -// pluginator {(devel) unknown } - package builtins import ( diff --git a/vendor/sigs.k8s.io/kustomize/api/internal/builtins/ReplicaCountTransformer.go b/vendor/sigs.k8s.io/kustomize/api/internal/builtins/ReplicaCountTransformer.go index c87d64251..afbd4b105 100644 --- a/vendor/sigs.k8s.io/kustomize/api/internal/builtins/ReplicaCountTransformer.go +++ b/vendor/sigs.k8s.io/kustomize/api/internal/builtins/ReplicaCountTransformer.go @@ -1,6 +1,4 @@ // Code generated by pluginator on ReplicaCountTransformer; DO NOT EDIT. -// pluginator {(devel) unknown } - package builtins import ( diff --git a/vendor/sigs.k8s.io/kustomize/api/internal/builtins/SecretGenerator.go b/vendor/sigs.k8s.io/kustomize/api/internal/builtins/SecretGenerator.go index 2a4ef1c90..fbb4efa40 100644 --- a/vendor/sigs.k8s.io/kustomize/api/internal/builtins/SecretGenerator.go +++ b/vendor/sigs.k8s.io/kustomize/api/internal/builtins/SecretGenerator.go @@ -1,6 +1,4 @@ // Code generated by pluginator on SecretGenerator; DO NOT EDIT. -// pluginator {(devel) unknown } - package builtins import ( diff --git a/vendor/sigs.k8s.io/kustomize/api/internal/builtins/SortOrderTransformer.go b/vendor/sigs.k8s.io/kustomize/api/internal/builtins/SortOrderTransformer.go index 90e290719..8b88b129f 100644 --- a/vendor/sigs.k8s.io/kustomize/api/internal/builtins/SortOrderTransformer.go +++ b/vendor/sigs.k8s.io/kustomize/api/internal/builtins/SortOrderTransformer.go @@ -1,6 +1,4 @@ // Code generated by pluginator on SortOrderTransformer; DO NOT EDIT. -// pluginator {(devel) unknown } - package builtins import ( diff --git a/vendor/sigs.k8s.io/kustomize/api/internal/builtins/SuffixTransformer.go b/vendor/sigs.k8s.io/kustomize/api/internal/builtins/SuffixTransformer.go index 31b5b8fea..2999711ab 100644 --- a/vendor/sigs.k8s.io/kustomize/api/internal/builtins/SuffixTransformer.go +++ b/vendor/sigs.k8s.io/kustomize/api/internal/builtins/SuffixTransformer.go @@ -1,6 +1,4 @@ // Code generated by pluginator on SuffixTransformer; DO NOT EDIT. -// pluginator {(devel) unknown } - package builtins import ( diff --git a/vendor/sigs.k8s.io/kustomize/api/internal/builtins/ValueAddTransformer.go b/vendor/sigs.k8s.io/kustomize/api/internal/builtins/ValueAddTransformer.go index 1d70c98c2..2bab5b6b6 100644 --- a/vendor/sigs.k8s.io/kustomize/api/internal/builtins/ValueAddTransformer.go +++ b/vendor/sigs.k8s.io/kustomize/api/internal/builtins/ValueAddTransformer.go @@ -1,6 +1,4 @@ // Code generated by pluginator on ValueAddTransformer; DO NOT EDIT. -// pluginator {(devel) unknown } - package builtins import ( diff --git a/vendor/sigs.k8s.io/kustomize/api/internal/loader/fileloader.go b/vendor/sigs.k8s.io/kustomize/api/internal/loader/fileloader.go index 69b8295eb..e4202815c 100644 --- a/vendor/sigs.k8s.io/kustomize/api/internal/loader/fileloader.go +++ b/vendor/sigs.k8s.io/kustomize/api/internal/loader/fileloader.go @@ -169,7 +169,7 @@ func (fl *FileLoader) New(path string) (ifc.Loader, error) { } root, err := filesys.ConfirmDir(fl.fSys, fl.root.Join(path)) if err != nil { - return nil, errors.WrapPrefixf(err, ErrRtNotDir.Error()) //nolint:govet + return nil, errors.WrapPrefixf(err, "%s", ErrRtNotDir.Error()) } if err = fl.errIfGitContainmentViolation(root); err != nil { return nil, err @@ -311,7 +311,11 @@ func (fl *FileLoader) httpClientGetContent(path string) ([]byte, error) { } else { hc = &http.Client{} } - resp, err := hc.Get(path) + parsedURL, err := url.ParseRequestURI(path) + if err != nil { + return nil, errors.Wrap(err) + } + resp, err := hc.Get(parsedURL.String()) if err != nil { return nil, errors.Wrap(err) } diff --git a/vendor/sigs.k8s.io/kustomize/api/internal/loader/loader.go b/vendor/sigs.k8s.io/kustomize/api/internal/loader/loader.go index 60b254fa7..36b246fb4 100644 --- a/vendor/sigs.k8s.io/kustomize/api/internal/loader/loader.go +++ b/vendor/sigs.k8s.io/kustomize/api/internal/loader/loader.go @@ -28,7 +28,7 @@ func NewLoader( } root, err := filesys.ConfirmDir(fSys, target) if err != nil { - return nil, errors.WrapPrefixf(err, ErrRtNotDir.Error()) //nolint:govet + return nil, errors.WrapPrefixf(err, "%s", ErrRtNotDir.Error()) } return newLoaderAtConfirmedDir( lr, root, fSys, nil, git.ClonerUsingGitExec), nil diff --git a/vendor/sigs.k8s.io/kustomize/api/internal/plugins/execplugin/execplugin.go b/vendor/sigs.k8s.io/kustomize/api/internal/plugins/execplugin/execplugin.go index f6c1dba3c..f6cc0b53f 100644 --- a/vendor/sigs.k8s.io/kustomize/api/internal/plugins/execplugin/execplugin.go +++ b/vendor/sigs.k8s.io/kustomize/api/internal/plugins/execplugin/execplugin.go @@ -161,14 +161,13 @@ func (p *ExecPlugin) invokePlugin(input []byte) ([]byte, error) { _, err = f.Write(p.cfg) if err != nil { return nil, errors.WrapPrefixf( - err, "writing plugin config to "+f.Name()) + err, "writing plugin config to %s", f.Name()) } err = f.Close() if err != nil { return nil, errors.WrapPrefixf( - err, "closing plugin config file "+f.Name()) + err, "closing plugin config file %s", f.Name()) } - //nolint:gosec cmd := exec.Command( p.path, append([]string{f.Name()}, p.args...)...) cmd.Env = p.getEnv() @@ -180,10 +179,9 @@ func (p *ExecPlugin) invokePlugin(input []byte) ([]byte, error) { } result, err := cmd.Output() if err != nil { - //nolint:govet return nil, errors.WrapPrefixf( - fmt.Errorf("failure in plugin configured via %s; %w", - f.Name(), err), stdErr.String()) + fmt.Errorf("failure in plugin configured via %s; %w", f.Name(), err), + "%s", stdErr.String()) } return result, os.Remove(f.Name()) } diff --git a/vendor/sigs.k8s.io/kustomize/api/internal/plugins/loader/loader.go b/vendor/sigs.k8s.io/kustomize/api/internal/plugins/loader/loader.go index 2edf8791f..afae8940d 100644 --- a/vendor/sigs.k8s.io/kustomize/api/internal/plugins/loader/loader.go +++ b/vendor/sigs.k8s.io/kustomize/api/internal/plugins/loader/loader.go @@ -251,7 +251,7 @@ func (l *Loader) loadPlugin(res *resource.Resource) (resmap.Configurable, error) return nil, errors.Errorf("plugin %s with mount path '%s' is not permitted; "+ "mount paths must be relative to the current kustomization directory", res.OrgId(), mount.Src) } - if strings.HasPrefix(filepath.Clean(mount.Src), "../") { + if strings.HasPrefix(filepath.Clean(mount.Src), "..") { return nil, errors.Errorf("plugin %s with mount path '%s' is not permitted; "+ "mount paths must be under the current kustomization directory", res.OrgId(), mount.Src) } diff --git a/vendor/sigs.k8s.io/kustomize/api/internal/target/kusttarget.go b/vendor/sigs.k8s.io/kustomize/api/internal/target/kusttarget.go index 5f1d1095a..3eb4c00c0 100644 --- a/vendor/sigs.k8s.io/kustomize/api/internal/target/kusttarget.go +++ b/vendor/sigs.k8s.io/kustomize/api/internal/target/kusttarget.go @@ -496,6 +496,11 @@ func (kt *KustTarget) accumulateDirectory( } subKt.kustomization.BuildMetadata = kt.kustomization.BuildMetadata subKt.origin = kt.origin + // Propagate namespace to child kustomization if child doesn't have one + // This ensures Helm charts in base kustomizations inherit namespace from overlays + if subKt.kustomization.Namespace == "" && kt.kustomization.Namespace != "" { + subKt.kustomization.Namespace = kt.kustomization.Namespace + } var bytes []byte if openApiPath, exists := subKt.Kustomization().OpenAPI["path"]; exists { bytes, err = ldr.Load(openApiPath) diff --git a/vendor/sigs.k8s.io/kustomize/api/internal/target/kusttarget_configplugin.go b/vendor/sigs.k8s.io/kustomize/api/internal/target/kusttarget_configplugin.go index 1ba028a36..c41d6c84f 100644 --- a/vendor/sigs.k8s.io/kustomize/api/internal/target/kusttarget_configplugin.go +++ b/vendor/sigs.k8s.io/kustomize/api/internal/target/kusttarget_configplugin.go @@ -166,6 +166,11 @@ var generatorConfigurators = map[builtinhelpers.BuiltinPluginType]func( for _, chart := range kt.kustomization.HelmCharts { c.HelmGlobals = globals c.HelmChart = chart + // Pass kustomize namespace to helm + // Fixes https://github.com/kubernetes-sigs/kustomize/issues/5566 + if c.HelmChart.Namespace == "" && kt.kustomization.Namespace != "" { + c.HelmChart.Namespace = kt.kustomization.Namespace + } p := f() if err = kt.configureBuiltinPlugin(p, c, bpt); err != nil { return nil, err @@ -250,10 +255,10 @@ var transformerConfigurators = map[builtinhelpers.BuiltinPluginType]func( return } var c struct { - Path string `json:"path,omitempty" yaml:"path,omitempty"` - Patch string `json:"patch,omitempty" yaml:"patch,omitempty"` - Target *types.Selector `json:"target,omitempty" yaml:"target,omitempty"` - Options map[string]bool `json:"options,omitempty" yaml:"options,omitempty"` + Path string `json:"path,omitempty" yaml:"path,omitempty"` + Patch string `json:"patch,omitempty" yaml:"patch,omitempty"` + Target *types.Selector `json:"target,omitempty" yaml:"target,omitempty"` + Options *types.PatchArgs `json:"options,omitempty" yaml:"options,omitempty"` } for _, pc := range kt.kustomization.Patches { c.Target = pc.Target diff --git a/vendor/sigs.k8s.io/kustomize/api/konfig/general.go b/vendor/sigs.k8s.io/kustomize/api/konfig/general.go index 712bfe789..c66188388 100644 --- a/vendor/sigs.k8s.io/kustomize/api/konfig/general.go +++ b/vendor/sigs.k8s.io/kustomize/api/konfig/general.go @@ -46,4 +46,7 @@ const ( // Label key that indicates the resources are validated by a validator ValidatedByLabelKey = "validated-by" + + // Annotation key for marking helm-generated resources to skip namespace transformation + HelmGeneratedAnnotation = ConfigAnnoDomain + "/helm-generated" ) diff --git a/vendor/sigs.k8s.io/kustomize/api/resmap/reswrangler.go b/vendor/sigs.k8s.io/kustomize/api/resmap/reswrangler.go index f6443539f..33578a0bb 100644 --- a/vendor/sigs.k8s.io/kustomize/api/resmap/reswrangler.go +++ b/vendor/sigs.k8s.io/kustomize/api/resmap/reswrangler.go @@ -597,7 +597,7 @@ func (m *resWrangler) appendReplaceOrMerge(res *resource.Resource) error { default: return fmt.Errorf( - "id %#v exists; behavior must be merge or replace", id) + "id %#v exists; can not use behavior: '%s', behavior must be merge or replace", id, res.Behavior()) } i, err := m.Replace(res) if err != nil { diff --git a/vendor/sigs.k8s.io/kustomize/api/resource/resource.go b/vendor/sigs.k8s.io/kustomize/api/resource/resource.go index 9884a672c..dc6995799 100644 --- a/vendor/sigs.k8s.io/kustomize/api/resource/resource.go +++ b/vendor/sigs.k8s.io/kustomize/api/resource/resource.go @@ -11,6 +11,7 @@ import ( "sigs.k8s.io/kustomize/api/filters/patchstrategicmerge" "sigs.k8s.io/kustomize/api/ifc" "sigs.k8s.io/kustomize/api/internal/utils" + "sigs.k8s.io/kustomize/api/konfig" "sigs.k8s.io/kustomize/api/types" "sigs.k8s.io/kustomize/kyaml/kio" "sigs.k8s.io/kustomize/kyaml/kio/kioutil" @@ -47,6 +48,8 @@ var BuildAnnotations = []string{ kioutil.LegacyPathAnnotation, kioutil.LegacyIndexAnnotation, kioutil.LegacyIdAnnotation, + + konfig.HelmGeneratedAnnotation, } func (r *Resource) ResetRNode(incoming *Resource) { diff --git a/vendor/sigs.k8s.io/kustomize/api/types/patch.go b/vendor/sigs.k8s.io/kustomize/api/types/patch.go index 5310a6e66..7ad141975 100644 --- a/vendor/sigs.k8s.io/kustomize/api/types/patch.go +++ b/vendor/sigs.k8s.io/kustomize/api/types/patch.go @@ -3,8 +3,6 @@ package types -import "reflect" - // Patch represent either a Strategic Merge Patch or a JSON patch // and its targets. // The content of the patch can either be from a file @@ -20,15 +18,17 @@ type Patch struct { Target *Selector `json:"target,omitempty" yaml:"target,omitempty"` // Options is a list of options for the patch - Options map[string]bool `json:"options,omitempty" yaml:"options,omitempty"` + Options *PatchArgs `json:"options,omitempty" yaml:"options,omitempty"` } // Equals return true if p equals o. func (p *Patch) Equals(o Patch) bool { targetEqual := (p.Target == o.Target) || (p.Target != nil && o.Target != nil && *p.Target == *o.Target) + optionsEqual := (p.Options == o.Options) || + (p.Options != nil && o.Options != nil && *p.Options == *o.Options) return p.Path == o.Path && p.Patch == o.Patch && targetEqual && - reflect.DeepEqual(p.Options, o.Options) + optionsEqual } diff --git a/vendor/sigs.k8s.io/kustomize/api/types/patchargs.go b/vendor/sigs.k8s.io/kustomize/api/types/patchargs.go new file mode 100644 index 000000000..453849fa6 --- /dev/null +++ b/vendor/sigs.k8s.io/kustomize/api/types/patchargs.go @@ -0,0 +1,13 @@ +// Copyright 2019 The Kubernetes Authors. +// SPDX-License-Identifier: Apache-2.0 + +package types + +// PatchArgs represent set of options on resources of a patch. +type PatchArgs struct { + // AllowNameChange allows name changes to the resource. + AllowNameChange bool `json:"allowNameChange,omitempty" yaml:"allowNameChange,omitempty"` + + // AllowKindChange allows kind changes to the resource. + AllowKindChange bool `json:"allowKindChange,omitempty" yaml:"allowKindChange,omitempty"` +} diff --git a/vendor/sigs.k8s.io/kustomize/api/types/replacement.go b/vendor/sigs.k8s.io/kustomize/api/types/replacement.go index b110322e7..dd8ed5dc4 100644 --- a/vendor/sigs.k8s.io/kustomize/api/types/replacement.go +++ b/vendor/sigs.k8s.io/kustomize/api/types/replacement.go @@ -66,6 +66,53 @@ type TargetSelector struct { Options *FieldOptions `json:"options,omitempty" yaml:"options,omitempty"` } +type TargetSelectorRegex struct { + targetSelector *TargetSelector + selectRegex *SelectorRegex + rejectRegex []*SelectorRegex +} + +func NewTargetSelectorRegex(ts *TargetSelector) (*TargetSelectorRegex, error) { + tsr := new(TargetSelectorRegex) + tsr.targetSelector = ts + var err error + + tsr.selectRegex, err = NewSelectorRegex(ts.Select) + if err != nil { + return nil, err + } + + rej := []*SelectorRegex{} + for _, r := range ts.Reject { + rr, err := NewSelectorRegex(r) + if err != nil { + return nil, err + } + rej = append(rej, rr) + } + tsr.rejectRegex = rej + + return tsr, nil +} + +func (tsr *TargetSelectorRegex) Selects(id resid.ResId) bool { + return tsr.selectRegex.MatchGvk(id.Gvk) && tsr.selectRegex.MatchName(id.Name) && tsr.selectRegex.MatchNamespace(id.Namespace) +} + +func (tsr *TargetSelectorRegex) RejectsAny(ids []resid.ResId) bool { + for _, r := range tsr.rejectRegex { + if r.selector.ResId.IsEmpty() { + continue + } + for _, id := range ids { + if r.MatchGvk(id.Gvk) && r.MatchName(id.Name) && r.MatchNamespace(id.Namespace) { + return true + } + } + } + return false +} + // FieldOptions refine the interpretation of FieldPaths. type FieldOptions struct { // Used to split/join the field. diff --git a/vendor/sigs.k8s.io/kustomize/kyaml/filesys/filesystem.go b/vendor/sigs.k8s.io/kustomize/kyaml/filesys/filesystem.go index c29d5ad8a..4e1c3d896 100644 --- a/vendor/sigs.k8s.io/kustomize/kyaml/filesys/filesystem.go +++ b/vendor/sigs.k8s.io/kustomize/kyaml/filesys/filesystem.go @@ -4,7 +4,6 @@ package filesys import ( - "fmt" "path/filepath" "sigs.k8s.io/kustomize/kyaml/errors" @@ -78,8 +77,7 @@ func ConfirmDir(fSys FileSystem, path string) (ConfirmedDir, error) { return "", errors.WrapPrefixf(err, "not a valid directory") } if f != "" { - //nolint:govet - return "", errors.WrapPrefixf(errors.Errorf("file is not directory"), fmt.Sprintf("'%s'", path)) + return "", errors.WrapPrefixf(errors.Errorf("file is not directory"), "'%s'", path) } return d, nil } diff --git a/vendor/sigs.k8s.io/kustomize/kyaml/fn/runtime/exec/exec.go b/vendor/sigs.k8s.io/kustomize/kyaml/fn/runtime/exec/exec.go index 562dab30f..7425d183e 100644 --- a/vendor/sigs.k8s.io/kustomize/kyaml/fn/runtime/exec/exec.go +++ b/vendor/sigs.k8s.io/kustomize/kyaml/fn/runtime/exec/exec.go @@ -37,7 +37,7 @@ func (c *Filter) Filter(nodes []*yaml.RNode) ([]*yaml.RNode, error) { } func (c *Filter) Run(reader io.Reader, writer io.Writer) error { - cmd := exec.Command(c.Path, c.Args...) //nolint:gosec + cmd := exec.Command(c.Path, c.Args...) cmd.Env = append(os.Environ(), c.Env...) cmd.Stdin = reader cmd.Stdout = writer diff --git a/vendor/sigs.k8s.io/kustomize/kyaml/kio/kioutil/kioutil.go b/vendor/sigs.k8s.io/kustomize/kyaml/kio/kioutil/kioutil.go index 510ecae18..818d6ca00 100644 --- a/vendor/sigs.k8s.io/kustomize/kyaml/kio/kioutil/kioutil.go +++ b/vendor/sigs.k8s.io/kustomize/kyaml/kio/kioutil/kioutil.go @@ -387,7 +387,7 @@ func ConfirmInternalAnnotationUnchanged(r1 *yaml.RNode, r2 *yaml.RNode, exclusio for _, key := range keys { errorString = errorString + key + ", " } - return errors.Errorf(errorString[0 : len(errorString)-2]) + return errors.Errorf("%s", errorString[0:len(errorString)-2]) } return nil diff --git a/vendor/sigs.k8s.io/kustomize/kyaml/kio/pkgio_reader.go b/vendor/sigs.k8s.io/kustomize/kyaml/kio/pkgio_reader.go index 609a791f3..d7eeda793 100644 --- a/vendor/sigs.k8s.io/kustomize/kyaml/kio/pkgio_reader.go +++ b/vendor/sigs.k8s.io/kustomize/kyaml/kio/pkgio_reader.go @@ -268,7 +268,7 @@ func (r LocalPackageReader) Read() ([]*yaml.RNode, error) { // to another location. relPath, err := filepath.Rel(pathRelativeTo, path) if err != nil { - return errors.WrapPrefixf(err, pathRelativeTo) + return errors.WrapPrefixf(err, "%s", pathRelativeTo) } if match, err := r.shouldSkipFile(path, relPath, ignoreFilesMatcher); err != nil { return err @@ -280,7 +280,7 @@ func (r LocalPackageReader) Read() ([]*yaml.RNode, error) { r.initReaderAnnotations(relPath, info) nodes, err := r.readFile(path, info) if err != nil { - return errors.WrapPrefixf(err, path) + return errors.WrapPrefixf(err, "%s", path) } operand = append(operand, nodes...) return nil diff --git a/vendor/sigs.k8s.io/kustomize/kyaml/runfn/runfn.go b/vendor/sigs.k8s.io/kustomize/kyaml/runfn/runfn.go index bf8863c57..4fd175cd8 100644 --- a/vendor/sigs.k8s.io/kustomize/kyaml/runfn/runfn.go +++ b/vendor/sigs.k8s.io/kustomize/kyaml/runfn/runfn.go @@ -230,7 +230,7 @@ func (r RunFns) runFunctions( } } if len(errs) > 0 { - return fmt.Errorf(strings.Join(errs, "\n---\n")) + return fmt.Errorf("%s", strings.Join(errs, "\n---\n")) } return nil } diff --git a/vendor/sigs.k8s.io/kustomize/kyaml/yaml/fns.go b/vendor/sigs.k8s.io/kustomize/kyaml/yaml/fns.go index 740a28ed0..9c26055ed 100644 --- a/vendor/sigs.k8s.io/kustomize/kyaml/yaml/fns.go +++ b/vendor/sigs.k8s.io/kustomize/kyaml/yaml/fns.go @@ -830,6 +830,10 @@ func (e *InvalidNodeKindError) Error() string { return msg } +func (e *InvalidNodeKindError) Unwrap() error { + return errors.Errorf("InvalidNodeKindError") +} + func (e *InvalidNodeKindError) ActualNodeKind() Kind { return e.node.YNode().Kind } diff --git a/vendor/sigs.k8s.io/kustomize/kyaml/yaml/match.go b/vendor/sigs.k8s.io/kustomize/kyaml/yaml/match.go index 28ea03ca6..1e70de3c9 100644 --- a/vendor/sigs.k8s.io/kustomize/kyaml/yaml/match.go +++ b/vendor/sigs.k8s.io/kustomize/kyaml/yaml/match.go @@ -14,7 +14,7 @@ import ( ) // PathMatcher returns all RNodes matching the path wrapped in a SequenceNode. -// Lists may have multiple elements matching the path, and each matching element +// Lists may have multiple elements matching the pafunc cleanPath(path []string) []string {g element // is added to the return result. // If Path points to a SequenceNode, the SequenceNode is wrapped in another SequenceNode // If Path does not contain any lists, the result is still wrapped in a SequenceNode of len == 1 @@ -137,10 +137,14 @@ func (p *PathMatcher) visitEveryElem(elem *RNode) error { func (p *PathMatcher) doField(rn *RNode) (*RNode, error) { // lookup the field field, err := rn.Pipe(Get(p.Path[0])) - if err != nil || (!IsCreate(p.Create) && field == nil) { + if err != nil { return nil, err } + if !IsCreate(p.Create) && field == nil { + return nil, nil + } + if IsCreate(p.Create) && field == nil { var nextPart string if len(p.Path) > 1 { @@ -154,6 +158,11 @@ func (p *PathMatcher) doField(rn *RNode) (*RNode, error) { } } + // Check if the field is a scalar and there are remaining path segments + if field != nil && field.YNode().Kind == yaml.ScalarNode && len(p.Path) > 1 { + return p.handleStructuredDataInScalar(field) + } + // recurse on the field, removing the first element of the path pm := &PathMatcher{Path: p.Path[1:], Create: p.Create} p.val, err = pm.filter(field) @@ -253,12 +262,12 @@ func (p *PathMatcher) doSeq(rn *RNode) (*RNode, error) { func (p *PathMatcher) visitPrimitiveElem(elem *RNode) error { r, err := regexp.Compile(p.matchRegex) if err != nil { - return err + return fmt.Errorf("%w", err) } str, err := elem.String() if err != nil { - return err + return fmt.Errorf("%w", err) } str = strings.TrimSpace(str) if !r.MatchString(str) { @@ -272,7 +281,7 @@ func (p *PathMatcher) visitPrimitiveElem(elem *RNode) error { func (p *PathMatcher) visitElem(elem *RNode) error { r, err := regexp.Compile(p.matchRegex) if err != nil { - return err + return fmt.Errorf("%w", err) } // check if this elements field matches the regex @@ -282,7 +291,7 @@ func (p *PathMatcher) visitElem(elem *RNode) error { } str, err := val.Value.String() if err != nil { - return err + return fmt.Errorf("%w", err) } str = strings.TrimSpace(str) if !r.MatchString(str) { @@ -331,3 +340,26 @@ func cleanPath(path []string) []string { } return p } + +// handleStructuredDataInScalar processes a scalar field that contains structured data (JSON/YAML) +// and allows path navigation within that structured data +func (p *PathMatcher) handleStructuredDataInScalar(scalarField *RNode) (*RNode, error) { + scalarValue := scalarField.YNode().Value + var parsedNode yaml.Node + if err := yaml.Unmarshal([]byte(scalarValue), &parsedNode); err != nil { + return nil, fmt.Errorf("%w", err) + } + + // Create a structured field from the parsed data + structuredField := NewRNode(&parsedNode) + + // Process the remaining path on the structured data + pm := &PathMatcher{Path: p.Path[1:], Create: p.Create} + result, err := pm.filter(structuredField) + if err != nil { + return nil, err + } + p.Matches = pm.Matches + + return result, nil +} diff --git a/vendor/sigs.k8s.io/kustomize/kyaml/yaml/rnode.go b/vendor/sigs.k8s.io/kustomize/kyaml/yaml/rnode.go index 0059ec2eb..43cad97e5 100644 --- a/vendor/sigs.k8s.io/kustomize/kyaml/yaml/rnode.go +++ b/vendor/sigs.k8s.io/kustomize/kyaml/yaml/rnode.go @@ -718,10 +718,11 @@ func (rn *RNode) MustString() string { // Content returns Node Content field. func (rn *RNode) Content() []*yaml.Node { - if rn == nil { + yNode := rn.YNode() + if yNode == nil { return nil } - return rn.YNode().Content + return yNode.Content } // Fields returns the list of field names for a MappingNode. @@ -756,7 +757,11 @@ func (rn *RNode) FieldRNodes() ([]*RNode, error) { // Field returns a fieldName, fieldValue pair for MappingNodes. // Returns nil for non-MappingNodes. func (rn *RNode) Field(field string) *MapNode { - if rn.YNode().Kind != yaml.MappingNode { + yNode := rn.YNode() + if yNode == nil { + return nil + } + if yNode.Kind != yaml.MappingNode { return nil } var result *MapNode @@ -892,7 +897,11 @@ func (rn *RNode) ElementValuesList(keys []string) ([][]string, error) { // Element returns the element in the list which contains the field matching the value. // Returns nil for non-SequenceNodes or if no Element matches. func (rn *RNode) Element(key, value string) *RNode { - if rn.YNode().Kind != yaml.SequenceNode { + yNode := rn.YNode() + if yNode == nil { + return nil + } + if yNode.Kind != yaml.SequenceNode { return nil } elem, err := rn.Pipe(MatchElement(key, value)) @@ -906,7 +915,11 @@ func (rn *RNode) Element(key, value string) *RNode { // corresponding values[i]. // Returns nil for non-SequenceNodes or if no Element matches. func (rn *RNode) ElementList(keys []string, values []string) *RNode { - if rn.YNode().Kind != yaml.SequenceNode { + yNode := rn.YNode() + if yNode == nil { + return nil + } + if yNode.Kind != yaml.SequenceNode { return nil } elem, err := rn.Pipe(MatchElementList(keys, values)) @@ -960,12 +973,17 @@ func (rn *RNode) GetAssociativeKey() string { // MarshalJSON creates a byte slice from the RNode. func (rn *RNode) MarshalJSON() ([]byte, error) { + yNode := rn.YNode() + if yNode == nil { + return []byte("null"), nil + } + s, err := rn.String() if err != nil { return nil, err } - if rn.YNode().Kind == SequenceNode { + if yNode.Kind == SequenceNode { var a []interface{} if err := Unmarshal([]byte(s), &a); err != nil { return nil, err @@ -977,6 +995,7 @@ func (rn *RNode) MarshalJSON() ([]byte, error) { if err := Unmarshal([]byte(s), &m); err != nil { return nil, err } + return json.Marshal(m) }