Add ready conditon and cleanup finalizer and status patching (#186)

This change adds a ready condition. It also sets a standard for status
fields and documentation. It makes use of helper functions from FluxCD
to better manage patching of finalizers and status.

Signed-off-by: Philip Laine <philip.laine@gmail.com>
This commit is contained in:
Philip Laine
2026-04-21 15:42:11 +02:00
committed by GitHub
parent 1bcd58a7cd
commit af11e31b28
19 changed files with 250 additions and 181 deletions
+9
View File
@@ -0,0 +1,9 @@
package v1alpha1
const NetbirdFinalizer = "finalizers.netbird.io"
const ReadyCondition = "Ready"
const (
ReconciledReason = "Reconciled"
)
+27 -15
View File
@@ -4,49 +4,61 @@ import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
) )
// GroupSpec defines the desired state of Group // GroupSpec defines the desired state of Group.
type GroupSpec struct { type GroupSpec struct {
// name of the group. // Name of the group.
// +kubebuilder:validation:MinLength=1 // +kubebuilder:validation:MinLength=1
Name string `json:"name"` Name string `json:"name"`
} }
// GroupStatus defines the observed state of Group. // GroupStatus defines the observed state of Group.
type GroupStatus struct { type GroupStatus struct {
// ObservedGeneration is the last reconciled generation.
// +optional // +optional
GroupID *string `json:"groupID,omitempty"` ObservedGeneration int64 `json:"observedGeneration,omitempty"`
// The status of each condition is one of True, False, or Unknown. // Conditions holds the conditions for the Group.
// +listType=map // +listType=map
// +listMapKey=type // +listMapKey=type
// +optional // +optional
Conditions []metav1.Condition `json:"conditions,omitempty"` Conditions []metav1.Condition `json:"conditions,omitempty"`
// GroupID is the id of the created group.
// +optional
GroupID string `json:"groupID,omitempty"`
} }
// +kubebuilder:object:root=true // +kubebuilder:object:root=true
// +kubebuilder:subresource:status // +kubebuilder:subresource:status
// +kubebuilder:resource // +kubebuilder:resource
// +kubebuilder:printcolumn:name="Ready",type="string",JSONPath=".status.conditions[?(@.type==\"Ready\")].status",description=""
// +kubebuilder:printcolumn:name="Age",type="date",JSONPath=".metadata.creationTimestamp",description=""
// Group is the Schema for the groups API // Group is the Schema for the groups API.
type Group struct { type Group struct {
metav1.TypeMeta `json:",inline"` metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata,omitempty"`
// metadata is a standard object metadata
// +optional
metav1.ObjectMeta `json:"metadata,omitzero"`
// spec defines the desired state of Group
// +required // +required
Spec GroupSpec `json:"spec"` Spec GroupSpec `json:"spec"`
// status defines the observed state of Group // +kubebuilder:default={"observedGeneration":-1}
// +optional Status GroupStatus `json:"status,omitempty"`
Status GroupStatus `json:"status,omitzero"` }
// GetConditions returns the status conditions of the object.
func (g *Group) GetConditions() []metav1.Condition {
return g.Status.Conditions
}
// SetConditions sets the status conditions on the object.
func (g *Group) SetConditions(conditions []metav1.Condition) {
g.Status.Conditions = conditions
} }
// +kubebuilder:object:root=true // +kubebuilder:object:root=true
// GroupList contains a list of Group // GroupList contains a list of Group.
type GroupList struct { type GroupList struct {
metav1.TypeMeta `json:",inline"` metav1.TypeMeta `json:",inline"`
metav1.ListMeta `json:"metadata,omitzero"` metav1.ListMeta `json:"metadata,omitzero"`
+27 -16
View File
@@ -4,7 +4,7 @@ import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
) )
// SetupKeySpec defines the desired state of SetupKey // SetupKeySpec defines the desired state of SetupKey.
type SetupKeySpec struct { type SetupKeySpec struct {
// Ephemeral decides if peers added with the key are ephemeral or not. // Ephemeral decides if peers added with the key are ephemeral or not.
// +kubebuilder:validation:XValidation:rule="self == oldSelf",message="ephemeral is immutable" // +kubebuilder:validation:XValidation:rule="self == oldSelf",message="ephemeral is immutable"
@@ -15,42 +15,53 @@ type SetupKeySpec struct {
// +optional // +optional
Duration *metav1.Duration `json:"duration,omitempty"` Duration *metav1.Duration `json:"duration,omitempty"`
// Groups that will be automatically assigned to resources using setup key. // AutoGroups are groups that will be automatically assigned to peers using setup key.
// +optional // +optional
AutoGroups []ResourceReference `json:"autoGroups,omitempty"` AutoGroups []ResourceReference `json:"autoGroups,omitempty"`
} }
// SetupKeyStatus defines the observed state of SetupKey. // SetupKeyStatus defines the observed state of SetupKey.
type SetupKeyStatus struct { type SetupKeyStatus struct {
// SetupKeyID of the setup key. // ObservedGeneration is the last reconciled generation.
SetupKeyID *string `json:"setupKeyID,omitempty"` // +optional
ObservedGeneration int64 `json:"observedGeneration,omitempty"`
// The status of each condition is one of True, False, or Unknown. // Conditions holds the conditions for the SetupKey.
// +listType=map // +listType=map
// +listMapKey=type // +listMapKey=type
// +optional // +optional
Conditions []metav1.Condition `json:"conditions,omitempty"` Conditions []metav1.Condition `json:"conditions,omitempty"`
// SetupKeyID is the id of the created setup key.
SetupKeyID string `json:"setupKeyID,omitempty"`
} }
// +kubebuilder:object:root=true // +kubebuilder:object:root=true
// +kubebuilder:subresource:status // +kubebuilder:subresource:status
// +kubebuilder:resource // +kubebuilder:resource
// +kubebuilder:printcolumn:name="Ready",type="string",JSONPath=".status.conditions[?(@.type==\"Ready\")].status",description=""
// +kubebuilder:printcolumn:name="Age",type="date",JSONPath=".metadata.creationTimestamp",description=""
// SetupKey is the Schema for the setupkeys API // SetupKey is the Schema for the setupkeys API.
type SetupKey struct { type SetupKey struct {
metav1.TypeMeta `json:",inline"` metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata,omitempty"`
// metadata is a standard object metadata
// +optional
metav1.ObjectMeta `json:"metadata,omitzero"`
// spec defines the desired state of SetupKey
// +required // +required
Spec SetupKeySpec `json:"spec"` Spec SetupKeySpec `json:"spec"`
// status defines the observed state of SetupKey // +kubebuilder:default={"observedGeneration":-1}
// +optional Status SetupKeyStatus `json:"status,omitempty"`
Status SetupKeyStatus `json:"status,omitzero"` }
// GetConditions returns the status conditions of the object.
func (sk *SetupKey) GetConditions() []metav1.Condition {
return sk.Status.Conditions
}
// SetConditions sets the status conditions on the object.
func (sk *SetupKey) SetConditions(conditions []metav1.Condition) {
sk.Status.Conditions = conditions
} }
func (sk SetupKey) SecretName() string { func (sk SetupKey) SecretName() string {
@@ -59,7 +70,7 @@ func (sk SetupKey) SecretName() string {
// +kubebuilder:object:root=true // +kubebuilder:object:root=true
// SetupKeyList contains a list of SetupKey // SetupKeyList contains a list of SetupKey.
type SetupKeyList struct { type SetupKeyList struct {
metav1.TypeMeta `json:",inline"` metav1.TypeMeta `json:",inline"`
metav1.ListMeta `json:"metadata,omitzero"` metav1.ListMeta `json:"metadata,omitzero"`
-10
View File
@@ -87,11 +87,6 @@ func (in *GroupSpec) DeepCopy() *GroupSpec {
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *GroupStatus) DeepCopyInto(out *GroupStatus) { func (in *GroupStatus) DeepCopyInto(out *GroupStatus) {
*out = *in *out = *in
if in.GroupID != nil {
in, out := &in.GroupID, &out.GroupID
*out = new(string)
**out = **in
}
if in.Conditions != nil { if in.Conditions != nil {
in, out := &in.Conditions, &out.Conditions in, out := &in.Conditions, &out.Conditions
*out = make([]v1.Condition, len(*in)) *out = make([]v1.Condition, len(*in))
@@ -225,11 +220,6 @@ func (in *SetupKeySpec) DeepCopy() *SetupKeySpec {
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *SetupKeyStatus) DeepCopyInto(out *SetupKeyStatus) { func (in *SetupKeyStatus) DeepCopyInto(out *SetupKeyStatus) {
*out = *in *out = *in
if in.SetupKeyID != nil {
in, out := &in.SetupKeyID, &out.SetupKeyID
*out = new(string)
**out = **in
}
if in.Conditions != nil { if in.Conditions != nil {
in, out := &in.Conditions, &out.Conditions in, out := &in.Conditions, &out.Conditions
*out = make([]v1.Condition, len(*in)) *out = make([]v1.Condition, len(*in))
+1 -1
View File
@@ -4,4 +4,4 @@ metadata:
name: test name: test
namespace: default namespace: default
spec: spec:
expiration: 0 ephemeral: true
+8 -5
View File
@@ -5,6 +5,7 @@ go 1.25.0
toolchain go1.26.1 toolchain go1.26.1
require ( require (
github.com/fluxcd/pkg/runtime v0.103.0
github.com/go-logr/logr v1.4.3 github.com/go-logr/logr v1.4.3
github.com/google/uuid v1.6.0 github.com/google/uuid v1.6.0
github.com/netbirdio/netbird v0.66.4 github.com/netbirdio/netbird v0.66.4
@@ -30,6 +31,7 @@ require (
github.com/emicklei/go-restful/v3 v3.13.0 // indirect github.com/emicklei/go-restful/v3 v3.13.0 // indirect
github.com/evanphx/json-patch/v5 v5.9.11 // indirect github.com/evanphx/json-patch/v5 v5.9.11 // indirect
github.com/fatih/color v1.18.0 // indirect github.com/fatih/color v1.18.0 // indirect
github.com/fluxcd/pkg/apis/meta v1.26.0 // indirect
github.com/fsnotify/fsnotify v1.9.0 // indirect github.com/fsnotify/fsnotify v1.9.0 // indirect
github.com/fxamacker/cbor/v2 v2.9.0 // indirect github.com/fxamacker/cbor/v2 v2.9.0 // indirect
github.com/go-logr/zapr v1.3.0 // indirect github.com/go-logr/zapr v1.3.0 // indirect
@@ -52,18 +54,19 @@ require (
github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
github.com/oapi-codegen/runtime v1.1.2 // indirect github.com/oapi-codegen/runtime v1.1.2 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
github.com/pquerna/cachecontrol v0.2.0 // indirect github.com/pquerna/cachecontrol v0.2.0 // indirect
github.com/prometheus/client_golang v1.23.2 // indirect github.com/prometheus/client_golang v1.23.2 // indirect
github.com/prometheus/client_model v0.6.2 // indirect github.com/prometheus/client_model v0.6.2 // indirect
github.com/prometheus/common v0.66.1 // indirect github.com/prometheus/common v0.66.1 // indirect
github.com/prometheus/procfs v0.16.1 // indirect github.com/prometheus/procfs v0.17.0 // indirect
github.com/sirupsen/logrus v1.9.3 // indirect github.com/sirupsen/logrus v1.9.3 // indirect
github.com/spf13/cobra v1.10.2 // indirect github.com/spf13/cobra v1.10.2 // indirect
github.com/spf13/pflag v1.0.10 // indirect github.com/spf13/pflag v1.0.10 // indirect
github.com/x448/float16 v0.8.4 // indirect github.com/x448/float16 v0.8.4 // indirect
go.uber.org/multierr v1.11.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.3 // indirect go.yaml.in/yaml/v2 v2.4.3 // indirect
go.yaml.in/yaml/v3 v3.0.4 // indirect go.yaml.in/yaml/v3 v3.0.4 // indirect
golang.org/x/mod v0.32.0 // indirect golang.org/x/mod v0.32.0 // indirect
@@ -75,7 +78,7 @@ require (
golang.org/x/text v0.33.0 // indirect golang.org/x/text v0.33.0 // indirect
golang.org/x/time v0.14.0 // indirect golang.org/x/time v0.14.0 // indirect
golang.org/x/tools v0.41.0 // indirect golang.org/x/tools v0.41.0 // indirect
gomodules.xyz/jsonpatch/v2 v2.4.0 // indirect gomodules.xyz/jsonpatch/v2 v2.5.0 // indirect
google.golang.org/protobuf v1.36.11 // indirect google.golang.org/protobuf v1.36.11 // indirect
gopkg.in/asn1-ber.v1 v1.0.0-20181015200546-f715ec2f112d // indirect gopkg.in/asn1-ber.v1 v1.0.0-20181015200546-f715ec2f112d // indirect
gopkg.in/evanphx/json-patch.v4 v4.13.0 // indirect gopkg.in/evanphx/json-patch.v4 v4.13.0 // indirect
@@ -84,8 +87,8 @@ require (
gopkg.in/ldap.v2 v2.5.1 // indirect gopkg.in/ldap.v2 v2.5.1 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect
k8s.io/apiextensions-apiserver v0.35.0 // indirect k8s.io/apiextensions-apiserver v0.35.2 // indirect
k8s.io/code-generator v0.35.0 // indirect k8s.io/code-generator v0.35.2 // indirect
k8s.io/gengo/v2 v2.0.0-20250922181213-ec3ebc5fd46b // indirect k8s.io/gengo/v2 v2.0.0-20250922181213-ec3ebc5fd46b // indirect
k8s.io/klog/v2 v2.130.1 // indirect k8s.io/klog/v2 v2.130.1 // indirect
k8s.io/kube-openapi v0.0.0-20250910181357-589584f1c912 // indirect k8s.io/kube-openapi v0.0.0-20250910181357-589584f1c912 // indirect
+22 -16
View File
@@ -10,6 +10,8 @@ dario.cat/mergo v1.0.1 h1:Ra4+bf83h2ztPIQYNP99R6m+Y7KfnARDfID+a+vLl4s=
dario.cat/mergo v1.0.1/go.mod h1:uNxQE+84aUszobStD9th8a29P2fMDhsBdgRYvZOxGmk= dario.cat/mergo v1.0.1/go.mod h1:uNxQE+84aUszobStD9th8a29P2fMDhsBdgRYvZOxGmk=
filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA= filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA=
filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4= filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4=
github.com/AdaLogics/go-fuzz-headers v0.0.0-20240806141605-e8a1dd7889d6 h1:He8afgbRMd7mFxO99hRNu+6tazq8nFF9lIwo9JFroBk=
github.com/AdaLogics/go-fuzz-headers v0.0.0-20240806141605-e8a1dd7889d6/go.mod h1:8o94RPi1/7XTJvwPpRSzSUedZrtlirdB3r9Z20bi2f8=
github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161 h1:L/gRVlceqvL25UVaW/CKtUDjefjrs0SPonmDGUVOYP0= github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161 h1:L/gRVlceqvL25UVaW/CKtUDjefjrs0SPonmDGUVOYP0=
github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E= github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E=
github.com/BurntSushi/toml v1.5.0 h1:W5quZX/G/csjUnuI8SUYlsHs9M38FC7znL0lIO+DvMg= github.com/BurntSushi/toml v1.5.0 h1:W5quZX/G/csjUnuI8SUYlsHs9M38FC7znL0lIO+DvMg=
@@ -119,6 +121,10 @@ github.com/fatih/color v1.18.0 h1:S8gINlzdQ840/4pfAwic/ZE0djQEH3wM94VfqLTZcOM=
github.com/fatih/color v1.18.0/go.mod h1:4FelSpRwEGDpQ12mAdzqdOukCy4u8WUtOY6lkT/6HfU= github.com/fatih/color v1.18.0/go.mod h1:4FelSpRwEGDpQ12mAdzqdOukCy4u8WUtOY6lkT/6HfU=
github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg= github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg=
github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U=
github.com/fluxcd/pkg/apis/meta v1.26.0 h1:dxP1FfBpTCYso6odzRcltVnnRuBb2VyhhgV0VX9YbUE=
github.com/fluxcd/pkg/apis/meta v1.26.0/go.mod h1:c7o6mJGLCMvNrfdinGZehkrdZuFT9vZdZNrn66DtVD0=
github.com/fluxcd/pkg/runtime v0.103.0 h1:J5y5GPhWdkyqIUBlaI1FP2N02TtZmsjbWhhZubuTSFk=
github.com/fluxcd/pkg/runtime v0.103.0/go.mod h1:mbo2f3azo3yVQgm7XZGxQB6/2zvzQ5Wgtd8TjRRwwAw=
github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k= github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k=
github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0= github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=
github.com/fxamacker/cbor/v2 v2.9.0 h1:NpKPmjDBgUfBms6tr6JZkTHtfFGcMKsw3eGcmD/sapM= github.com/fxamacker/cbor/v2 v2.9.0 h1:NpKPmjDBgUfBms6tr6JZkTHtfFGcMKsw3eGcmD/sapM=
@@ -163,8 +169,8 @@ github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
github.com/google/btree v1.1.3 h1:CVpQJjYgC4VbzxeGVHfvZrv1ctoYCAI8vbl07Fcxlyg= github.com/google/btree v1.1.3 h1:CVpQJjYgC4VbzxeGVHfvZrv1ctoYCAI8vbl07Fcxlyg=
github.com/google/btree v1.1.3/go.mod h1:qOPhT0dTNdNzV6Z/lhRX0YXUafgPLFUh+gZMl761Gm4= github.com/google/btree v1.1.3/go.mod h1:qOPhT0dTNdNzV6Z/lhRX0YXUafgPLFUh+gZMl761Gm4=
github.com/google/cel-go v0.26.0 h1:DPGjXackMpJWH680oGY4lZhYjIameYmR+/6RBdDGmaI= github.com/google/cel-go v0.26.1 h1:iPbVVEdkhTX++hpe3lzSk7D3G3QSYqLGoHOcEio+UXQ=
github.com/google/cel-go v0.26.0/go.mod h1:A9O8OU9rdvrK5MQyrqfIxo1a0u4g3sF8KB6PUIaryMM= github.com/google/cel-go v0.26.1/go.mod h1:A9O8OU9rdvrK5MQyrqfIxo1a0u4g3sF8KB6PUIaryMM=
github.com/google/gnostic-models v0.7.0 h1:qwTtogB15McXDaNqTZdzPJRHvaVJlAl+HVQnLmJEJxo= github.com/google/gnostic-models v0.7.0 h1:qwTtogB15McXDaNqTZdzPJRHvaVJlAl+HVQnLmJEJxo=
github.com/google/gnostic-models v0.7.0/go.mod h1:whL5G0m6dmc5cPxKc5bdKdEN3UjI7OUGxBlw57miDrQ= github.com/google/gnostic-models v0.7.0/go.mod h1:whL5G0m6dmc5cPxKc5bdKdEN3UjI7OUGxBlw57miDrQ=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
@@ -329,8 +335,8 @@ github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNw
github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE= github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE=
github.com/prometheus/common v0.66.1 h1:h5E0h5/Y8niHc5DlaLlWLArTQI7tMrsfQjHV+d9ZoGs= github.com/prometheus/common v0.66.1 h1:h5E0h5/Y8niHc5DlaLlWLArTQI7tMrsfQjHV+d9ZoGs=
github.com/prometheus/common v0.66.1/go.mod h1:gcaUsgf3KfRSwHY4dIMXLPV0K/Wg1oZ8+SbZk/HH/dA= github.com/prometheus/common v0.66.1/go.mod h1:gcaUsgf3KfRSwHY4dIMXLPV0K/Wg1oZ8+SbZk/HH/dA=
github.com/prometheus/procfs v0.16.1 h1:hZ15bTNuirocR6u0JZ6BAHHmwS1p8B4P6MRqxtzMyRg= github.com/prometheus/procfs v0.17.0 h1:FuLQ+05u4ZI+SS/w9+BWEM2TXiHKsUQ9TADiRH7DuK0=
github.com/prometheus/procfs v0.16.1/go.mod h1:teAbpZRB1iIAJYREa1LsoWUXykVXA1KlTmWl8x/U+Is= github.com/prometheus/procfs v0.17.0/go.mod h1:oPQLaDAMRbA+u8H5Pbfq+dl3VDAvHxMUOVhe0wYB2zw=
github.com/redis/go-redis/v9 v9.7.3 h1:YpPyAayJV+XErNsatSElgRZZVCwXX9QzkKYNvO7x0wM= github.com/redis/go-redis/v9 v9.7.3 h1:YpPyAayJV+XErNsatSElgRZZVCwXX9QzkKYNvO7x0wM=
github.com/redis/go-redis/v9 v9.7.3/go.mod h1:bGUrSggJ9X9GUmZpZNEOQKaANxSGgOEBRltRTZHSvrA= github.com/redis/go-redis/v9 v9.7.3/go.mod h1:bGUrSggJ9X9GUmZpZNEOQKaANxSGgOEBRltRTZHSvrA=
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
@@ -427,8 +433,8 @@ go.uber.org/mock v0.5.2 h1:LbtPTcP8A5k9WPXj54PPPbjcI4Y6lhyOZXn+VS7wNko=
go.uber.org/mock v0.5.2/go.mod h1:wLlUxC2vVTPTaE3UD51E0BGOAElKrILxhVSDYQLld5o= go.uber.org/mock v0.5.2/go.mod h1:wLlUxC2vVTPTaE3UD51E0BGOAElKrILxhVSDYQLld5o=
go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= 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/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.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=
go.uber.org/zap v1.27.0/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E= go.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=
go.yaml.in/yaml/v2 v2.4.3 h1:6gvOSjQoTB3vt1l+CU+tSyi/HOjfOjRLJ4YwYZGwRO0= go.yaml.in/yaml/v2 v2.4.3 h1:6gvOSjQoTB3vt1l+CU+tSyi/HOjfOjRLJ4YwYZGwRO0=
go.yaml.in/yaml/v2 v2.4.3/go.mod h1:zSxWcmIDjOzPXpjlTTbAsKokqkDNAVtZO0WOMiT90s8= go.yaml.in/yaml/v2 v2.4.3/go.mod h1:zSxWcmIDjOzPXpjlTTbAsKokqkDNAVtZO0WOMiT90s8=
go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc= go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
@@ -469,8 +475,8 @@ golang.zx2c4.com/wireguard/wgctrl v0.0.0-20230429144221-925a1e7659e6 h1:CawjfCvY
golang.zx2c4.com/wireguard/wgctrl v0.0.0-20230429144221-925a1e7659e6/go.mod h1:3rxYc4HtVcSG9gVaTs2GEBdehh+sYPOwKtyUWEOTb80= golang.zx2c4.com/wireguard/wgctrl v0.0.0-20230429144221-925a1e7659e6/go.mod h1:3rxYc4HtVcSG9gVaTs2GEBdehh+sYPOwKtyUWEOTb80=
golang.zx2c4.com/wireguard/windows v0.5.3 h1:On6j2Rpn3OEMXqBq00QEDC7bWSZrPIHKIus8eIuExIE= golang.zx2c4.com/wireguard/windows v0.5.3 h1:On6j2Rpn3OEMXqBq00QEDC7bWSZrPIHKIus8eIuExIE=
golang.zx2c4.com/wireguard/windows v0.5.3/go.mod h1:9TEe8TJmtwyQebdFwAkEWOPr3prrtqm+REGFifP60hI= golang.zx2c4.com/wireguard/windows v0.5.3/go.mod h1:9TEe8TJmtwyQebdFwAkEWOPr3prrtqm+REGFifP60hI=
gomodules.xyz/jsonpatch/v2 v2.4.0 h1:Ci3iUJyx9UeRx7CeFN8ARgGbkESwJK+KB9lLcWxY/Zw= gomodules.xyz/jsonpatch/v2 v2.5.0 h1:JELs8RLM12qJGXU4u/TO3V25KW8GreMKl9pdkk14RM0=
gomodules.xyz/jsonpatch/v2 v2.4.0/go.mod h1:AH3dM2RI6uoBZxn3LVrfvJ3E0/9dG4cSrbuBJT4moAY= gomodules.xyz/jsonpatch/v2 v2.5.0/go.mod h1:AH3dM2RI6uoBZxn3LVrfvJ3E0/9dG4cSrbuBJT4moAY=
google.golang.org/api v0.257.0 h1:8Y0lzvHlZps53PEaw+G29SsQIkuKrumGWs9puiexNAA= google.golang.org/api v0.257.0 h1:8Y0lzvHlZps53PEaw+G29SsQIkuKrumGWs9puiexNAA=
google.golang.org/api v0.257.0/go.mod h1:4eJrr+vbVaZSqs7vovFd1Jb/A6ml6iw2e6FBYf3GAO4= google.golang.org/api v0.257.0/go.mod h1:4eJrr+vbVaZSqs7vovFd1Jb/A6ml6iw2e6FBYf3GAO4=
google.golang.org/genproto/googleapis/api v0.0.0-20250303144028-a0af3efb3deb h1:p31xT4yrYrSM/G4Sn2+TNUkVhFCbG9y8itM2S6Th950= google.golang.org/genproto/googleapis/api v0.0.0-20250303144028-a0af3efb3deb h1:p31xT4yrYrSM/G4Sn2+TNUkVhFCbG9y8itM2S6Th950=
@@ -515,18 +521,18 @@ gorm.io/gorm v1.25.12 h1:I0u8i2hWQItBq1WfE0o2+WuL9+8L21K9e2HHSTE/0f8=
gorm.io/gorm v1.25.12/go.mod h1:xh7N7RHfYlNc5EmcI/El95gXusucDrQnHXe0+CgWcLQ= gorm.io/gorm v1.25.12/go.mod h1:xh7N7RHfYlNc5EmcI/El95gXusucDrQnHXe0+CgWcLQ=
k8s.io/api v0.35.2 h1:tW7mWc2RpxW7HS4CoRXhtYHSzme1PN1UjGHJ1bdrtdw= k8s.io/api v0.35.2 h1:tW7mWc2RpxW7HS4CoRXhtYHSzme1PN1UjGHJ1bdrtdw=
k8s.io/api v0.35.2/go.mod h1:7AJfqGoAZcwSFhOjcGM7WV05QxMMgUaChNfLTXDRE60= k8s.io/api v0.35.2/go.mod h1:7AJfqGoAZcwSFhOjcGM7WV05QxMMgUaChNfLTXDRE60=
k8s.io/apiextensions-apiserver v0.35.0 h1:3xHk2rTOdWXXJM+RDQZJvdx0yEOgC0FgQ1PlJatA5T4= k8s.io/apiextensions-apiserver v0.35.2 h1:iyStXHoJZsUXPh/nFAsjC29rjJWdSgUmG1XpApE29c0=
k8s.io/apiextensions-apiserver v0.35.0/go.mod h1:E1Ahk9SADaLQ4qtzYFkwUqusXTcaV2uw3l14aqpL2LU= k8s.io/apiextensions-apiserver v0.35.2/go.mod h1:OdyGvcO1FtMDWQ+rRh/Ei3b6X3g2+ZDHd0MSRGeS8rU=
k8s.io/apimachinery v0.35.2 h1:NqsM/mmZA7sHW02JZ9RTtk3wInRgbVxL8MPfzSANAK8= k8s.io/apimachinery v0.35.2 h1:NqsM/mmZA7sHW02JZ9RTtk3wInRgbVxL8MPfzSANAK8=
k8s.io/apimachinery v0.35.2/go.mod h1:jQCgFZFR1F4Ik7hvr2g84RTJSZegBc8yHgFWKn//hns= k8s.io/apimachinery v0.35.2/go.mod h1:jQCgFZFR1F4Ik7hvr2g84RTJSZegBc8yHgFWKn//hns=
k8s.io/apiserver v0.35.0 h1:CUGo5o+7hW9GcAEF3x3usT3fX4f9r8xmgQeCBDaOgX4= k8s.io/apiserver v0.35.2 h1:rb52v0CZGEL0FkhjS+I6jHflAp7fZ4MIaKcEHX7wmDk=
k8s.io/apiserver v0.35.0/go.mod h1:QUy1U4+PrzbJaM3XGu2tQ7U9A4udRRo5cyxkFX0GEds= k8s.io/apiserver v0.35.2/go.mod h1:CROJUAu0tfjZLyYgSeBsBan2T7LUJGh0ucWwTCSSk7g=
k8s.io/client-go v0.35.2 h1:YUfPefdGJA4aljDdayAXkc98DnPkIetMl4PrKX97W9o= k8s.io/client-go v0.35.2 h1:YUfPefdGJA4aljDdayAXkc98DnPkIetMl4PrKX97W9o=
k8s.io/client-go v0.35.2/go.mod h1:4QqEwh4oQpeK8AaefZ0jwTFJw/9kIjdQi0jpKeYvz7g= k8s.io/client-go v0.35.2/go.mod h1:4QqEwh4oQpeK8AaefZ0jwTFJw/9kIjdQi0jpKeYvz7g=
k8s.io/code-generator v0.35.0 h1:TvrtfKYZTm9oDF2z+veFKSCcgZE3Igv0svY+ehCmjHQ= k8s.io/code-generator v0.35.2 h1:3874swbO2c26VWTf6lKD4NWGyHIfyBeTCk7caCG3TuU=
k8s.io/code-generator v0.35.0/go.mod h1:iS1gvVf3c/T71N5DOGYO+Gt3PdJ6B9LYSvIyQ4FHzgc= k8s.io/code-generator v0.35.2/go.mod h1:id4XLCm0yAQq5nlvyfAKibMOKnMjzlesAwGw6kM3Adc=
k8s.io/component-base v0.35.0 h1:+yBrOhzri2S1BVqyVSvcM3PtPyx5GUxCK2tinZz1G94= k8s.io/component-base v0.35.2 h1:btgR+qNrpWuRSuvWSnQYsZy88yf5gVwemvz0yw79pGc=
k8s.io/component-base v0.35.0/go.mod h1:85SCX4UCa6SCFt6p3IKAPej7jSnF3L8EbfSyMZayJR0= k8s.io/component-base v0.35.2/go.mod h1:B1iBJjooe6xIJYUucAxb26RwhAjzx0gHnqO9htWIX+0=
k8s.io/gengo/v2 v2.0.0-20250922181213-ec3ebc5fd46b h1:gMplByicHV/TJBizHd9aVEsTYoJBnnUAT5MHlTkbjhQ= k8s.io/gengo/v2 v2.0.0-20250922181213-ec3ebc5fd46b h1:gMplByicHV/TJBizHd9aVEsTYoJBnnUAT5MHlTkbjhQ=
k8s.io/gengo/v2 v2.0.0-20250922181213-ec3ebc5fd46b/go.mod h1:CgujABENc3KuTrcsdpGmrrASjtQsWCT7R99mEV4U/fM= k8s.io/gengo/v2 v2.0.0-20250922181213-ec3ebc5fd46b/go.mod h1:CgujABENc3KuTrcsdpGmrrASjtQsWCT7R99mEV4U/fM=
k8s.io/klog/v2 v2.130.1 h1:n9Xl7H1Xvksem4KFG4PYbdQCQxqc/tTUyrgXaOhHSzk= k8s.io/klog/v2 v2.130.1 h1:n9Xl7H1Xvksem4KFG4PYbdQCQxqc/tTUyrgXaOhHSzk=
@@ -14,10 +14,17 @@ spec:
singular: group singular: group
scope: Namespaced scope: Namespaced
versions: versions:
- name: v1alpha1 - additionalPrinterColumns:
- jsonPath: .status.conditions[?(@.type=="Ready")].status
name: Ready
type: string
- jsonPath: .metadata.creationTimestamp
name: Age
type: date
name: v1alpha1
schema: schema:
openAPIV3Schema: openAPIV3Schema:
description: Group is the Schema for the groups API description: Group is the Schema for the groups API.
properties: properties:
apiVersion: apiVersion:
description: |- description: |-
@@ -37,21 +44,22 @@ spec:
metadata: metadata:
type: object type: object
spec: spec:
description: spec defines the desired state of Group description: GroupSpec defines the desired state of Group.
properties: properties:
name: name:
description: name of the group. description: Name of the group.
minLength: 1 minLength: 1
type: string type: string
required: required:
- name - name
type: object type: object
status: status:
description: status defines the observed state of Group default:
observedGeneration: -1
description: GroupStatus defines the observed state of Group.
properties: properties:
conditions: conditions:
description: The status of each condition is one of True, False, or description: Conditions holds the conditions for the Group.
Unknown.
items: items:
description: Condition contains details for one aspect of the current description: Condition contains details for one aspect of the current
state of this API Resource. state of this API Resource.
@@ -111,7 +119,12 @@ spec:
- type - type
x-kubernetes-list-type: map x-kubernetes-list-type: map
groupID: groupID:
description: GroupID is the id of the created group.
type: string type: string
observedGeneration:
description: ObservedGeneration is the last reconciled generation.
format: int64
type: integer
type: object type: object
required: required:
- spec - spec
@@ -14,10 +14,17 @@ spec:
singular: setupkey singular: setupkey
scope: Namespaced scope: Namespaced
versions: versions:
- name: v1alpha1 - additionalPrinterColumns:
- jsonPath: .status.conditions[?(@.type=="Ready")].status
name: Ready
type: string
- jsonPath: .metadata.creationTimestamp
name: Age
type: date
name: v1alpha1
schema: schema:
openAPIV3Schema: openAPIV3Schema:
description: SetupKey is the Schema for the setupkeys API description: SetupKey is the Schema for the setupkeys API.
properties: properties:
apiVersion: apiVersion:
description: |- description: |-
@@ -37,11 +44,11 @@ spec:
metadata: metadata:
type: object type: object
spec: spec:
description: spec defines the desired state of SetupKey description: SetupKeySpec defines the desired state of SetupKey.
properties: properties:
autoGroups: autoGroups:
description: Groups that will be automatically assigned to resources description: AutoGroups are groups that will be automatically assigned
using setup key. to peers using setup key.
items: items:
properties: properties:
id: id:
@@ -84,11 +91,12 @@ spec:
- ephemeral - ephemeral
type: object type: object
status: status:
description: status defines the observed state of SetupKey default:
observedGeneration: -1
description: SetupKeyStatus defines the observed state of SetupKey.
properties: properties:
conditions: conditions:
description: The status of each condition is one of True, False, or description: Conditions holds the conditions for the SetupKey.
Unknown.
items: items:
description: Condition contains details for one aspect of the current description: Condition contains details for one aspect of the current
state of this API Resource. state of this API Resource.
@@ -147,8 +155,12 @@ spec:
x-kubernetes-list-map-keys: x-kubernetes-list-map-keys:
- type - type
x-kubernetes-list-type: map x-kubernetes-list-type: map
observedGeneration:
description: ObservedGeneration is the last reconciled generation.
format: int64
type: integer
setupKeyID: setupKeyID:
description: SetupKeyID of the setup key. description: SetupKeyID is the id of the created setup key.
type: string type: string
type: object type: object
required: required:
+22 -28
View File
@@ -3,20 +3,17 @@ package controller
import ( import (
"context" "context"
"github.com/fluxcd/pkg/runtime/conditions"
"github.com/fluxcd/pkg/runtime/patch"
netbird "github.com/netbirdio/netbird/shared/management/client/rest" netbird "github.com/netbirdio/netbird/shared/management/client/rest"
"github.com/netbirdio/netbird/shared/management/http/api" "github.com/netbirdio/netbird/shared/management/http/api"
ctrl "sigs.k8s.io/controller-runtime" ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
nbv1alpha1 "github.com/netbirdio/kubernetes-operator/api/v1alpha1" nbv1alpha1 "github.com/netbirdio/kubernetes-operator/api/v1alpha1"
nbv1alpha1ac "github.com/netbirdio/kubernetes-operator/pkg/applyconfigurations/api/v1alpha1"
) )
const (
GroupFinalizer = "netbird.io/group"
)
// GroupReconciler reconciles a Group object
type GroupReconciler struct { type GroupReconciler struct {
client.Client client.Client
@@ -27,28 +24,29 @@ type GroupReconciler struct {
// +kubebuilder:rbac:groups=netbird.io,resources=groups/status,verbs=get;update;patch // +kubebuilder:rbac:groups=netbird.io,resources=groups/status,verbs=get;update;patch
// +kubebuilder:rbac:groups=netbird.io,resources=groups/finalizers,verbs=update // +kubebuilder:rbac:groups=netbird.io,resources=groups/finalizers,verbs=update
func (r *GroupReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { func (r *GroupReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
group := nbv1alpha1.Group{} group := &nbv1alpha1.Group{}
err := r.Get(ctx, req.NamespacedName, &group) err := r.Get(ctx, req.NamespacedName, group)
if err != nil { if err != nil {
return ctrl.Result{}, client.IgnoreNotFound(err) return ctrl.Result{}, client.IgnoreNotFound(err)
} }
sp := patch.NewSerialPatcher(group, r.Client)
if !group.DeletionTimestamp.IsZero() { if !group.DeletionTimestamp.IsZero() {
return r.reconcileDelete(ctx, group) return r.reconcileDelete(ctx, sp, group)
} }
groupAC := nbv1alpha1ac.Group(req.Name, req.Namespace).WithFinalizers(SetupKeyFinalizer) controllerutil.AddFinalizer(group, nbv1alpha1.NetbirdFinalizer)
err = r.Client.Apply(ctx, groupAC) err = sp.Patch(ctx, group)
if err != nil { if err != nil {
return ctrl.Result{}, err return ctrl.Result{}, err
} }
groupID, err := func() (string, error) { groupID, err := func() (string, error) {
if group.Status.GroupID != nil { groupReq := api.GroupRequest{
groupReq := api.GroupRequest{ Name: group.Spec.Name,
Name: group.Spec.Name, }
} if group.Status.GroupID != "" {
resp, err := r.Netbird.Groups.Update(ctx, *group.Status.GroupID, groupReq) resp, err := r.Netbird.Groups.Update(ctx, group.Status.GroupID, groupReq)
if err != nil && !netbird.IsNotFound(err) { if err != nil && !netbird.IsNotFound(err) {
return "", err return "", err
} }
@@ -56,10 +54,6 @@ func (r *GroupReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl
return resp.Id, nil return resp.Id, nil
} }
} }
groupReq := api.GroupRequest{
Name: group.Spec.Name,
}
resp, err := r.Netbird.Groups.Create(ctx, groupReq) resp, err := r.Netbird.Groups.Create(ctx, groupReq)
if err != nil { if err != nil {
return "", err return "", err
@@ -69,26 +63,26 @@ func (r *GroupReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl
if err != nil { if err != nil {
return ctrl.Result{}, err return ctrl.Result{}, err
} }
group.Status.GroupID = groupID
groupAC = nbv1alpha1ac.Group(req.Name, req.Namespace).WithStatus(nbv1alpha1ac.GroupStatus().WithGroupID(groupID)) conditions.MarkTrue(group, nbv1alpha1.ReadyCondition, nbv1alpha1.ReconciledReason, "")
err = r.Client.Status().Apply(ctx, groupAC) err = sp.Patch(ctx, group, patch.WithStatusObservedGeneration{})
if err != nil { if err != nil {
return ctrl.Result{}, err return ctrl.Result{}, err
} }
return ctrl.Result{}, nil return ctrl.Result{}, nil
} }
func (r *GroupReconciler) reconcileDelete(ctx context.Context, group nbv1alpha1.Group) (ctrl.Result, error) { func (r *GroupReconciler) reconcileDelete(ctx context.Context, sp *patch.SerialPatcher, group *nbv1alpha1.Group) (ctrl.Result, error) {
if group.Status.GroupID != nil { if group.Status.GroupID != "" {
err := r.Netbird.Groups.Delete(ctx, *group.Status.GroupID) err := r.Netbird.Groups.Delete(ctx, group.Status.GroupID)
if err != nil && !netbird.IsNotFound(err) { if err != nil && !netbird.IsNotFound(err) {
return ctrl.Result{}, err return ctrl.Result{}, err
} }
} }
groupAC := nbv1alpha1ac.Group(group.Name, group.Namespace).WithFinalizers() controllerutil.RemoveFinalizer(group, nbv1alpha1.NetbirdFinalizer)
err := r.Client.Apply(ctx, groupAC) err := sp.Patch(ctx, group)
if err != nil { if err != nil {
return ctrl.Result{}, err return ctrl.Result{}, err
} }
+4 -4
View File
@@ -60,18 +60,18 @@ var _ = Describe("Group Controller", func() {
Expect(err).NotTo(HaveOccurred()) Expect(err).NotTo(HaveOccurred())
err = k8sClient.Get(ctx, nn, group) err = k8sClient.Get(ctx, nn, group)
Expect(err).NotTo(HaveOccurred()) Expect(err).NotTo(HaveOccurred())
Expect(*group.Status.GroupID).NotTo(BeEmpty()) Expect(group.Status.ObservedGeneration).To(Equal(group.Generation))
Expect(group.Status.GroupID).NotTo(BeEmpty())
By("crerating a new group when deleted from API") By("crerating a new group when deleted from API")
err = controllerReconciler.Netbird.Groups.Delete(ctx, *group.Status.GroupID) err = controllerReconciler.Netbird.Groups.Delete(ctx, group.Status.GroupID)
Expect(err).NotTo(HaveOccurred()) Expect(err).NotTo(HaveOccurred())
_, err = controllerReconciler.Reconcile(ctx, reconcile.Request{NamespacedName: nn}) _, err = controllerReconciler.Reconcile(ctx, reconcile.Request{NamespacedName: nn})
Expect(err).NotTo(HaveOccurred()) Expect(err).NotTo(HaveOccurred())
newGroup := &nbv1alpha1.Group{} newGroup := &nbv1alpha1.Group{}
err = k8sClient.Get(ctx, nn, newGroup) err = k8sClient.Get(ctx, nn, newGroup)
Expect(err).NotTo(HaveOccurred()) Expect(err).NotTo(HaveOccurred())
Expect(*newGroup.Status.GroupID).NotTo(BeEmpty()) Expect(newGroup.Status.GroupID).NotTo(Equal(group.Status.GroupID))
Expect(*newGroup.Status.GroupID).NotTo(Equal(*group.Status.GroupID))
}) })
}) })
}) })
+39 -36
View File
@@ -6,6 +6,8 @@ import (
"fmt" "fmt"
"time" "time"
"github.com/fluxcd/pkg/runtime/conditions"
"github.com/fluxcd/pkg/runtime/patch"
netbird "github.com/netbirdio/netbird/shared/management/client/rest" netbird "github.com/netbirdio/netbird/shared/management/client/rest"
"github.com/netbirdio/netbird/shared/management/http/api" "github.com/netbirdio/netbird/shared/management/http/api"
corev1 "k8s.io/api/core/v1" corev1 "k8s.io/api/core/v1"
@@ -15,14 +17,13 @@ import (
"k8s.io/utils/ptr" "k8s.io/utils/ptr"
ctrl "sigs.k8s.io/controller-runtime" ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
nbv1alpha1 "github.com/netbirdio/kubernetes-operator/api/v1alpha1" nbv1alpha1 "github.com/netbirdio/kubernetes-operator/api/v1alpha1"
"github.com/netbirdio/kubernetes-operator/internal/ssautil" "github.com/netbirdio/kubernetes-operator/internal/ssautil"
nbv1alpha1ac "github.com/netbirdio/kubernetes-operator/pkg/applyconfigurations/api/v1alpha1"
) )
const ( const (
SetupKeyFinalizer = "netbird.io/setupkey"
SetupKeySecretKey = "setup-key" SetupKeySecretKey = "setup-key"
) )
@@ -36,14 +37,19 @@ type SetupKeyReconciler struct {
// +kubebuilder:rbac:groups=netbird.io,resources=setupkeys/status,verbs=get;update;patch // +kubebuilder:rbac:groups=netbird.io,resources=setupkeys/status,verbs=get;update;patch
// +kubebuilder:rbac:groups=netbird.io,resources=setupkeys/finalizers,verbs=update // +kubebuilder:rbac:groups=netbird.io,resources=setupkeys/finalizers,verbs=update
func (r *SetupKeyReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { func (r *SetupKeyReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
setupKey := nbv1alpha1.SetupKey{} setupKey := &nbv1alpha1.SetupKey{}
err := r.Get(ctx, req.NamespacedName, &setupKey) err := r.Get(ctx, req.NamespacedName, setupKey)
if err != nil { if err != nil {
return ctrl.Result{}, client.IgnoreNotFound(err) return ctrl.Result{}, client.IgnoreNotFound(err)
} }
owner, err := ssautil.OwnerReference(setupKey, r.Client.Scheme())
if err != nil {
return ctrl.Result{}, err
}
sp := patch.NewSerialPatcher(setupKey, r.Client)
if !setupKey.DeletionTimestamp.IsZero() { if !setupKey.DeletionTimestamp.IsZero() {
return r.reconcileDelete(ctx, setupKey) return r.reconcileDelete(ctx, sp, setupKey)
} }
// Get ids for auto groups. // Get ids for auto groups.
@@ -67,28 +73,27 @@ func (r *SetupKeyReconciler) Reconcile(ctx context.Context, req ctrl.Request) (c
if err != nil { if err != nil {
return ctrl.Result{}, err return ctrl.Result{}, err
} }
if group.Status.GroupID == nil { if group.Status.GroupID == "" {
return ctrl.Result{}, fmt.Errorf("group %s in auto groups list is not ready", group.Name) return ctrl.Result{}, fmt.Errorf("group %s in auto groups list is not ready", group.Name)
} }
autoGroupIDs = append(autoGroupIDs, *group.Status.GroupID) autoGroupIDs = append(autoGroupIDs, group.Status.GroupID)
} }
} }
// Set finalizer on the setup key. controllerutil.AddFinalizer(setupKey, nbv1alpha1.NetbirdFinalizer)
setupKeyAC := nbv1alpha1ac.SetupKey(req.Name, req.Namespace).WithFinalizers(SetupKeyFinalizer) err = sp.Patch(ctx, setupKey)
err = r.Client.Apply(ctx, setupKeyAC)
if err != nil { if err != nil {
return ctrl.Result{}, err return ctrl.Result{}, err
} }
// Check if setup key is up to date. // Check if setup key is up to date.
ok, err := func() (bool, error) { ok, err := func() (bool, error) {
if setupKey.Status.SetupKeyID == nil { if setupKey.Status.SetupKeyID == "" {
return false, nil return false, nil
} }
// Check setup key in Netbird. // Check setup key in Netbird.
resp, err := r.Netbird.SetupKeys.Get(ctx, *setupKey.Status.SetupKeyID) resp, err := r.Netbird.SetupKeys.Get(ctx, setupKey.Status.SetupKeyID)
if netbird.IsNotFound(err) { if netbird.IsNotFound(err) {
return false, nil return false, nil
} }
@@ -121,7 +126,7 @@ func (r *SetupKeyReconciler) Reconcile(ctx context.Context, req ctrl.Request) (c
setupKeyReq := api.PutApiSetupKeysKeyIdJSONRequestBody{ setupKeyReq := api.PutApiSetupKeysKeyIdJSONRequestBody{
AutoGroups: autoGroupIDs, AutoGroups: autoGroupIDs,
} }
_, err = r.Netbird.SetupKeys.Update(ctx, *setupKey.Status.SetupKeyID, setupKeyReq) _, err = r.Netbird.SetupKeys.Update(ctx, setupKey.Status.SetupKeyID, setupKeyReq)
if err != nil { if err != nil {
return false, err return false, err
} }
@@ -154,19 +159,13 @@ func (r *SetupKeyReconciler) Reconcile(ctx context.Context, req ctrl.Request) (c
if err != nil { if err != nil {
return ctrl.Result{}, err return ctrl.Result{}, err
} }
setupKey.Status.SetupKeyID = resp.Id
// Update the status with the id. err = sp.Patch(ctx, setupKey)
setupKeyAC = nbv1alpha1ac.SetupKey(req.Name, req.Namespace).WithStatus(nbv1alpha1ac.SetupKeyStatus().WithSetupKeyID(resp.Id))
err = r.Client.Status().Apply(ctx, setupKeyAC)
if err != nil { if err != nil {
return ctrl.Result{}, err return ctrl.Result{}, err
} }
// Create the secret containing the key. // Create the secret containing the key.
owner, err := ssautil.OwnerReference(&setupKey, r.Scheme())
if err != nil {
return ctrl.Result{}, err
}
data := map[string]string{ data := map[string]string{
SetupKeySecretKey: resp.Key, SetupKeySecretKey: resp.Key,
} }
@@ -179,30 +178,34 @@ func (r *SetupKeyReconciler) Reconcile(ctx context.Context, req ctrl.Request) (c
} }
// Delete the old status key if we are recreating. // Delete the old status key if we are recreating.
if oldSetupKeyID != nil { if oldSetupKeyID != "" {
err = r.Netbird.SetupKeys.Delete(ctx, *oldSetupKeyID) err = r.Netbird.SetupKeys.Delete(ctx, oldSetupKeyID)
if err != nil && !netbird.IsNotFound(err) { if err != nil && !netbird.IsNotFound(err) {
return ctrl.Result{}, err return ctrl.Result{}, err
} }
} }
return ctrl.Result{RequeueAfter: 15 * time.Minute}, nil conditions.MarkTrue(setupKey, nbv1alpha1.ReadyCondition, nbv1alpha1.ReconciledReason, "")
} err = sp.Patch(ctx, setupKey, patch.WithStatusObservedGeneration{})
func (r *SetupKeyReconciler) reconcileDelete(ctx context.Context, setupKey nbv1alpha1.SetupKey) (ctrl.Result, error) {
if setupKey.Status.SetupKeyID != nil {
err := r.Netbird.SetupKeys.Delete(ctx, *setupKey.Status.SetupKeyID)
if err != nil && !netbird.IsNotFound(err) {
return ctrl.Result{}, err
}
}
setupKeyAC := nbv1alpha1ac.SetupKey(setupKey.Name, setupKey.Namespace).WithFinalizers()
err := r.Client.Apply(ctx, setupKeyAC)
if err != nil { if err != nil {
return ctrl.Result{}, err return ctrl.Result{}, err
} }
return ctrl.Result{RequeueAfter: 15 * time.Minute}, nil
}
func (r *SetupKeyReconciler) reconcileDelete(ctx context.Context, sp *patch.SerialPatcher, setupKey *nbv1alpha1.SetupKey) (ctrl.Result, error) {
if setupKey.Status.SetupKeyID != "" {
err := r.Netbird.SetupKeys.Delete(ctx, setupKey.Status.SetupKeyID)
if err != nil && !netbird.IsNotFound(err) {
return ctrl.Result{}, err
}
}
controllerutil.RemoveFinalizer(setupKey, nbv1alpha1.NetbirdFinalizer)
err := sp.Patch(ctx, setupKey)
if err != nil {
return ctrl.Result{}, err
}
return ctrl.Result{}, nil return ctrl.Result{}, nil
} }
@@ -57,7 +57,8 @@ var _ = Describe("SetupKey Controller", func() {
err = k8sClient.Get(ctx, nn, setupKey) err = k8sClient.Get(ctx, nn, setupKey)
Expect(err).NotTo(HaveOccurred()) Expect(err).NotTo(HaveOccurred())
Expect(*setupKey.Status.SetupKeyID).NotTo(BeEmpty()) Expect(setupKey.Status.ObservedGeneration).To(Equal(setupKey.Generation))
Expect(setupKey.Status.SetupKeyID).NotTo(BeEmpty())
secret := &corev1.Secret{ secret := &corev1.Secret{
ObjectMeta: metav1.ObjectMeta{ ObjectMeta: metav1.ObjectMeta{
@@ -68,7 +69,7 @@ var _ = Describe("SetupKey Controller", func() {
err = k8sClient.Get(ctx, client.ObjectKeyFromObject(secret), secret) err = k8sClient.Get(ctx, client.ObjectKeyFromObject(secret), secret)
Expect(err).NotTo(HaveOccurred()) Expect(err).NotTo(HaveOccurred())
resp, err := controllerReconciler.Netbird.SetupKeys.Get(ctx, *setupKey.Status.SetupKeyID) resp, err := controllerReconciler.Netbird.SetupKeys.Get(ctx, setupKey.Status.SetupKeyID)
Expect(err).NotTo(HaveOccurred()) Expect(err).NotTo(HaveOccurred())
Expect(string(secret.Data[SetupKeySecretKey])).To(Equal(resp.Key)) Expect(string(secret.Data[SetupKeySecretKey])).To(Equal(resp.Key))
}) })
@@ -114,7 +115,7 @@ var _ = Describe("SetupKey Controller", func() {
Expect(err).NotTo(HaveOccurred()) Expect(err).NotTo(HaveOccurred())
Expect(k8sClient.Delete(ctx, &secondSecret)).To(Succeed()) Expect(k8sClient.Delete(ctx, &secondSecret)).To(Succeed())
Expect(*firstSetupKey.Status.SetupKeyID).ToNot(Equal(*secondSetupKey.Status.SetupKeyID)) Expect(firstSetupKey.Status.SetupKeyID).ToNot(Equal(secondSetupKey.Status.SetupKeyID))
Expect(firstSecret.Data[SetupKeySecretKey]).ToNot(BeEquivalentTo(secondSecret.Data[SetupKeySecretKey])) Expect(firstSecret.Data[SetupKeySecretKey]).ToNot(BeEquivalentTo(secondSecret.Data[SetupKeySecretKey]))
}) })
}) })
@@ -11,15 +11,12 @@ import (
// GroupApplyConfiguration represents a declarative configuration of the Group type for use // GroupApplyConfiguration represents a declarative configuration of the Group type for use
// with apply. // with apply.
// //
// Group is the Schema for the groups API // Group is the Schema for the groups API.
type GroupApplyConfiguration struct { type GroupApplyConfiguration struct {
v1.TypeMetaApplyConfiguration `json:",inline"` v1.TypeMetaApplyConfiguration `json:",inline"`
// metadata is a standard object metadata
*v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"`
// spec defines the desired state of Group Spec *GroupSpecApplyConfiguration `json:"spec,omitempty"`
Spec *GroupSpecApplyConfiguration `json:"spec,omitempty"` Status *GroupStatusApplyConfiguration `json:"status,omitempty"`
// status defines the observed state of Group
Status *GroupStatusApplyConfiguration `json:"status,omitempty"`
} }
// Group constructs a declarative configuration of the Group type for use with // Group constructs a declarative configuration of the Group type for use with
@@ -5,9 +5,9 @@ package v1alpha1
// GroupSpecApplyConfiguration represents a declarative configuration of the GroupSpec type for use // GroupSpecApplyConfiguration represents a declarative configuration of the GroupSpec type for use
// with apply. // with apply.
// //
// GroupSpec defines the desired state of Group // GroupSpec defines the desired state of Group.
type GroupSpecApplyConfiguration struct { type GroupSpecApplyConfiguration struct {
// name of the group. // Name of the group.
Name *string `json:"name,omitempty"` Name *string `json:"name,omitempty"`
} }
@@ -11,9 +11,12 @@ import (
// //
// GroupStatus defines the observed state of Group. // GroupStatus defines the observed state of Group.
type GroupStatusApplyConfiguration struct { type GroupStatusApplyConfiguration struct {
GroupID *string `json:"groupID,omitempty"` // ObservedGeneration is the last reconciled generation.
// The status of each condition is one of True, False, or Unknown. ObservedGeneration *int64 `json:"observedGeneration,omitempty"`
// Conditions holds the conditions for the Group.
Conditions []v1.ConditionApplyConfiguration `json:"conditions,omitempty"` Conditions []v1.ConditionApplyConfiguration `json:"conditions,omitempty"`
// GroupID is the id of the created group.
GroupID *string `json:"groupID,omitempty"`
} }
// GroupStatusApplyConfiguration constructs a declarative configuration of the GroupStatus type for use with // GroupStatusApplyConfiguration constructs a declarative configuration of the GroupStatus type for use with
@@ -22,11 +25,11 @@ func GroupStatus() *GroupStatusApplyConfiguration {
return &GroupStatusApplyConfiguration{} return &GroupStatusApplyConfiguration{}
} }
// WithGroupID sets the GroupID field in the declarative configuration to the given value // WithObservedGeneration sets the ObservedGeneration field in the declarative configuration to the given value
// and returns the receiver, so that objects can be built by chaining "With" function invocations. // and returns the receiver, so that objects can be built by chaining "With" function invocations.
// If called multiple times, the GroupID field is set to the value of the last call. // If called multiple times, the ObservedGeneration field is set to the value of the last call.
func (b *GroupStatusApplyConfiguration) WithGroupID(value string) *GroupStatusApplyConfiguration { func (b *GroupStatusApplyConfiguration) WithObservedGeneration(value int64) *GroupStatusApplyConfiguration {
b.GroupID = &value b.ObservedGeneration = &value
return b return b
} }
@@ -42,3 +45,11 @@ func (b *GroupStatusApplyConfiguration) WithConditions(values ...*v1.ConditionAp
} }
return b return b
} }
// WithGroupID sets the GroupID field in the declarative configuration to the given value
// and returns the receiver, so that objects can be built by chaining "With" function invocations.
// If called multiple times, the GroupID field is set to the value of the last call.
func (b *GroupStatusApplyConfiguration) WithGroupID(value string) *GroupStatusApplyConfiguration {
b.GroupID = &value
return b
}
@@ -11,15 +11,12 @@ import (
// SetupKeyApplyConfiguration represents a declarative configuration of the SetupKey type for use // SetupKeyApplyConfiguration represents a declarative configuration of the SetupKey type for use
// with apply. // with apply.
// //
// SetupKey is the Schema for the setupkeys API // SetupKey is the Schema for the setupkeys API.
type SetupKeyApplyConfiguration struct { type SetupKeyApplyConfiguration struct {
v1.TypeMetaApplyConfiguration `json:",inline"` v1.TypeMetaApplyConfiguration `json:",inline"`
// metadata is a standard object metadata
*v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"`
// spec defines the desired state of SetupKey Spec *SetupKeySpecApplyConfiguration `json:"spec,omitempty"`
Spec *SetupKeySpecApplyConfiguration `json:"spec,omitempty"` Status *SetupKeyStatusApplyConfiguration `json:"status,omitempty"`
// status defines the observed state of SetupKey
Status *SetupKeyStatusApplyConfiguration `json:"status,omitempty"`
} }
// SetupKey constructs a declarative configuration of the SetupKey type for use with // SetupKey constructs a declarative configuration of the SetupKey type for use with
@@ -9,13 +9,13 @@ import (
// SetupKeySpecApplyConfiguration represents a declarative configuration of the SetupKeySpec type for use // SetupKeySpecApplyConfiguration represents a declarative configuration of the SetupKeySpec type for use
// with apply. // with apply.
// //
// SetupKeySpec defines the desired state of SetupKey // SetupKeySpec defines the desired state of SetupKey.
type SetupKeySpecApplyConfiguration struct { type SetupKeySpecApplyConfiguration struct {
// Ephemeral decides if peers added with the key are ephemeral or not. // Ephemeral decides if peers added with the key are ephemeral or not.
Ephemeral *bool `json:"ephemeral,omitempty"` Ephemeral *bool `json:"ephemeral,omitempty"`
// Duration sets how long the setup key is valid for. // Duration sets how long the setup key is valid for.
Duration *v1.Duration `json:"duration,omitempty"` Duration *v1.Duration `json:"duration,omitempty"`
// Groups that will be automatically assigned to resources using setup key. // AutoGroups are groups that will be automatically assigned to peers using setup key.
AutoGroups []ResourceReferenceApplyConfiguration `json:"autoGroups,omitempty"` AutoGroups []ResourceReferenceApplyConfiguration `json:"autoGroups,omitempty"`
} }
@@ -11,10 +11,12 @@ import (
// //
// SetupKeyStatus defines the observed state of SetupKey. // SetupKeyStatus defines the observed state of SetupKey.
type SetupKeyStatusApplyConfiguration struct { type SetupKeyStatusApplyConfiguration struct {
// SetupKeyID of the setup key. // ObservedGeneration is the last reconciled generation.
SetupKeyID *string `json:"setupKeyID,omitempty"` ObservedGeneration *int64 `json:"observedGeneration,omitempty"`
// The status of each condition is one of True, False, or Unknown. // Conditions holds the conditions for the SetupKey.
Conditions []v1.ConditionApplyConfiguration `json:"conditions,omitempty"` Conditions []v1.ConditionApplyConfiguration `json:"conditions,omitempty"`
// SetupKeyID is the id of the created setup key.
SetupKeyID *string `json:"setupKeyID,omitempty"`
} }
// SetupKeyStatusApplyConfiguration constructs a declarative configuration of the SetupKeyStatus type for use with // SetupKeyStatusApplyConfiguration constructs a declarative configuration of the SetupKeyStatus type for use with
@@ -23,11 +25,11 @@ func SetupKeyStatus() *SetupKeyStatusApplyConfiguration {
return &SetupKeyStatusApplyConfiguration{} return &SetupKeyStatusApplyConfiguration{}
} }
// WithSetupKeyID sets the SetupKeyID field in the declarative configuration to the given value // WithObservedGeneration sets the ObservedGeneration field in the declarative configuration to the given value
// and returns the receiver, so that objects can be built by chaining "With" function invocations. // and returns the receiver, so that objects can be built by chaining "With" function invocations.
// If called multiple times, the SetupKeyID field is set to the value of the last call. // If called multiple times, the ObservedGeneration field is set to the value of the last call.
func (b *SetupKeyStatusApplyConfiguration) WithSetupKeyID(value string) *SetupKeyStatusApplyConfiguration { func (b *SetupKeyStatusApplyConfiguration) WithObservedGeneration(value int64) *SetupKeyStatusApplyConfiguration {
b.SetupKeyID = &value b.ObservedGeneration = &value
return b return b
} }
@@ -43,3 +45,11 @@ func (b *SetupKeyStatusApplyConfiguration) WithConditions(values ...*v1.Conditio
} }
return b return b
} }
// WithSetupKeyID sets the SetupKeyID field in the declarative configuration to the given value
// and returns the receiver, so that objects can be built by chaining "With" function invocations.
// If called multiple times, the SetupKeyID field is set to the value of the last call.
func (b *SetupKeyStatusApplyConfiguration) WithSetupKeyID(value string) *SetupKeyStatusApplyConfiguration {
b.SetupKeyID = &value
return b
}