diff --git a/Makefile b/Makefile index fdcc2b2..98c42e7 100644 --- a/Makefile +++ b/Makefile @@ -308,9 +308,10 @@ delete-targetsources-dev-lab: ## Delete the target sources for the development l ##@ Testing Lab .PHONY: run-integration-tests -run-integration-tests: docker-build undeploy-test-cluster deploy-test-cluster install-test-cluster-dependencies load-test-image deploy install-kubectl install-gnmic install-containerlab deploy-test-topology apply-test-resources +run-integration-tests: docker-build undeploy-test-cluster deploy-test-cluster install-test-cluster-dependencies load-test-image deploy deploy-test-http-server install-kubectl install-gnmic install-containerlab deploy-test-topology apply-test-resources kubectl wait --for=condition=Ready cluster --all --timeout=180s kubectl wait --for=condition=Ready pipeline --all --timeout=180s + kubectl wait --for=jsonpath='{.status.targetsCount}'=3 targetsource --all --timeout=180s kubectl wait --for=jsonpath='{.status.connectionState}'=READY target --all --timeout=180s kubectl get subscriptions -o yaml kubectl get outputs -o yaml diff --git a/api/v1alpha1/targetsource_types.go b/api/v1alpha1/targetsource_types.go index 3d69743..89f48c1 100644 --- a/api/v1alpha1/targetsource_types.go +++ b/api/v1alpha1/targetsource_types.go @@ -17,44 +17,209 @@ limitations under the License. package v1alpha1 import ( + corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) // TargetSourceSpec defines the desired state of TargetSource // +kubebuilder:validation:Required type TargetSourceSpec struct { + // Provider defines the source of targets for this TargetSource + // Only one provider can be specified per TargetSource + // +kubebuilder:validation:Required Provider *ProviderSpec `json:"provider"` + // TODO: implement in message processor + // Optional port to use for discovered targets if not specified by the provider + // +kubebuilder:validation:Optional + TargetPort int32 `json:"targetPort,omitempty"` + + // Optional labels to apply to all targets discovered by this TargetSource // +kubebuilder:validation:Optional TargetLabels map[string]string `json:"targetLabels,omitempty"` + // The TargetProfile to use for targets discovered by this TargetSource + // +kubebuilder:validation:Required // +kubebuilder:validation:MinLength=1 TargetProfile string `json:"targetProfile"` } -// +kubebuilder:validation:ExactlyOneOf=http;consul +// ProviderSpec defines the source of targets for a TargetSource +// Only one provider can be specified per TargetSource +// +kubebuilder:validation:ExactlyOneOf=http type ProviderSpec struct { - HTTP *HTTPConfig `json:"http,omitempty"` - Consul *ConsulConfig `json:"consul,omitempty"` + // HTTP defines the configuration for a HTTP provider + HTTP *HTTPConfig `json:"http,omitempty"` } +// HTTPConfig defines the configuration for the HTTP provider +// +kubebuilder:validation:AtLeastOneOf=url;acceptPush type HTTPConfig struct { - // +kubebuilder:validation:MinLength=1 - URL string `json:"url"` + // URL of the HTTP endpoint to pull targets from + // If defined, the loader will periodically poll this endpoint for targets + // +kubebuilder:validation:Optional + URL string `json:"url,omitempty"` + + // If true, the loader will accept pushed target updates to the controller endpoint + // The endpoint will be /{namespace}/{targetsource}/ + // +kubebuilder:default=false // +kubebuilder:validation:Optional AcceptPush bool `json:"acceptPush,omitempty"` + + // Optional authorization configuration for accessing the HTTP endpoint + // +kubebuilder:validation:Optional + Authorization *AuthorizationSpec `json:"authorization,omitempty"` + + // Optional interval for polling the HTTP endpoint for targets + // TODO: increase default value + // +kubebuilder:default="30s" + // +kubebuilder:validation:Optional + PollInterval *metav1.Duration `json:"interval,omitempty"` + + // Optional timeout for HTTP requests to the endpoint + // +kubebuilder:default="10s" + // +kubebuilder:validation:Optional + Timeout *metav1.Duration `json:"timeout,omitempty"` + + // Optional TLS configuration for connecting to the HTTP endpoint + // +kubebuilder:validation:Optional + TLS *ClientTLSConfig `json:"tls,omitempty"` + + // Optional pagination configuration for parsing responses from the HTTP endpoint + // +kubebuilder:validation:Optional + Pagination *PaginationSpec `json:"pagination,omitempty"` + + // Optional mapping configuration for parsing responses from the HTTP endpoint + // +kubebuilder:validation:Optional + ResponseMapping *ResponseMappingSpec `json:"mapping,omitempty"` } -type ConsulConfig struct { +// +kubebuilder:validation:XValidation:rule="!(has(self.caBundle) && has(self.caBundleSecretRef))",message="caBundle and caBundleSecretRef are mutually exclusive" +type ClientTLSConfig struct { + // Skip TLS verification of the Provider's certificate. + // +kubebuilder:default:=false + InsecureSkipVerify bool `json:"insecureSkipVerify,omitempty"` + + // Base64-encoded bundle of PEM CAs which will be used to validate the certificate + // chain presented by the Provider. Only used if using HTTPS to connect to Provider and + // ignored for HTTP connections. + // Mutually exclusive with CABundleSecretRef. + // +optional + CABundle []byte `json:"caBundle,omitempty"` + + // Reference to a Secret containing a bundle of PEM-encoded CAs to use when + // verifying the certificate chain presented by the Provider when using HTTPS. + // Mutually exclusive with CABundle. + CABundleSecretRef *corev1.SecretKeySelector `json:"caBundleSecretRef,omitempty"` +} + +// AuthorizationSpec defines the configuration for authentication +// +kubebuilder:validation:ExactlyOneOf=basic;token +type AuthorizationSpec struct { + // Basic authentication configuration + Basic *BasicAuthSpec `json:"basic,omitempty"` + // Token-based authentication configuration + Token *TokenAuthSpec `json:"token,omitempty"` + // JWT *JWTAuthSpec `json:"jwt,omitempty"` + // MTLS +} + +// BasicAuthSpec defines the configuration for basic authentication +// Enforce EITHER inline creds OR secret ref +// +kubebuilder:validation:XValidation:rule="(has(self.credentialsSecretRef) && !has(self.username) && !has(self.password)) || (!has(self.credentialsSecretRef) && has(self.username) && has(self.password))",message="either credentialsSecretRef OR both username and password must be set, but not a mix" +type BasicAuthSpec struct { + // Username for basic auth + // Mutually exclusive with CredentialsSecretRef. + Username string `json:"username,omitempty"` + // Password for basic auth + // Mutually exclusive with CredentialsSecretRef. + Password string `json:"password,omitempty"` + + // Reference to a Secret containing "username" and "password" keys to use for + // basic authentication when connecting to the Provider. + // Mutually exclusive with Username and Password. + CredentialsSecretRef *corev1.SecretKeySelector `json:"credentialsSecretRef,omitempty"` +} + +// TokenAuthSpec defines the configuration for token-based authentication +// +kubebuilder:validation:XValidation:rule="has(self.token) != has(self.tokenSecretRef)",message="either token or tokenSecretRef must be set, but not both" +type TokenAuthSpec struct { + // Scheme for the token, e.g. "Bearer" // +kubebuilder:validation:MinLength=1 - URL string `json:"url,omitempty"` + Scheme string `json:"scheme"` + // Token value for authentication + // Mutually exclusive with TokenSecretRef. + Token string `json:"token,omitempty"` + // Reference to a Secret containing a key with the token value to use for + // authentication when connecting to the Provider. + // Mutually exclusive with Token. + TokenSecretRef *corev1.SecretKeySelector `json:"tokenSecretRef,omitempty"` +} + +// +kubebuilder(disabled):validation:XValidation:rule="!((has(self.token) || has(self.tokenSecretRef)) && (has(self.key) || has(self.signingKeySecretRef) || has(self.claims)))",message="static JWT token and generated JWT configuration cannot be combined" +// +kubebuilder(disabled):validation:XValidation:rule="!has(self.signingKeySecretRef) || self.algorithm != \"\"",message="algorithm must be specified when generating a JWT" +// type JWTAuthSpec struct { +// // Static pre-generated JWT +// Token string `json:"token,omitempty"` +// TokenSecretRef *corev1.SecretKeySelector `json:"tokenSecretRef,omitempty"` +// // Optional: generate JWT dynamically +// Claims map[string]string `json:"claims,omitempty"` +// Key string `json:"key,omitempty"` +// SigningKeySecretRef *corev1.SecretKeySelector `json:"signingKeySecretRef,omitempty"` +// // HS256, RS256, ES256, etc. +// Algorithm string `json:"algorithm,omitempty"` +// TTL *metav1.Duration `json:"ttl,omitempty"` +// } + +// PaginationSpec defines the configuration for paginating through responses from providers +type PaginationSpec struct { + // Field name in the JSON response that contains the list of items (targets). + // Must refer to a top-level key in the response object. + // Example: "results" + ItemsField string `json:"itemsField,omitempty"` + + // Field name in the JSON response that contains the next page reference. + // The value can be either: + // - a full URL (used directly for the next request), or + // - a pagination token (appended as a query parameter using this field name as the key). + // + // Must refer to a top-level key in the response object. + // Example: "next" or "nextToken" + NextField string `json:"nextField,omitempty"` +} + +// JSONPath-style expressions to extract target fields from the response +// and map them to the corresponding Target fields. +type ResponseMappingSpec struct { + // JSONPath expression to extract the target name from the response + // +kubebuilder:validation:Required + Name string `json:"name"` + + // JSONPath expression to extract the target IP from the response + // +kubebuilder:validation:Required + IP string `json:"ip"` + + // JSONPath expression to extract the target port from the response + // +kubebuilder:validation:Optional + Port string `json:"port,omitempty"` + + // JSONPath expression to extract the target labels from the response + // The extracted labels will be merged with the static TargetLabels defined in the TargetSourceSpec, + // with values from the response taking precedence in case of conflicts. + // +kubebuilder:validation:Optional + Labels map[string]string `json:"labels,omitempty"` + + // JSONPath expression to extract the target profile from the response + // +kubebuilder:validation:Optional + TargetProfile string `json:"targetProfile,omitempty"` } // TargetSourceStatus defines the observed state of TargetSource type TargetSourceStatus struct { - Status string `json:"status"` - TargetsCount int32 `json:"targetsCount"` - LastSync metav1.Time `json:"lastSync"` + Status string `json:"status,omitempty"` + ObservedGeneration int64 `json:"observedGeneration"` + TargetsCount int32 `json:"targetsCount,omitempty"` + LastSync metav1.Time `json:"lastSync,omitempty"` } //+kubebuilder:object:root=true diff --git a/api/v1alpha1/zz_generated.deepcopy.go b/api/v1alpha1/zz_generated.deepcopy.go index 61e81fd..dc4b784 100644 --- a/api/v1alpha1/zz_generated.deepcopy.go +++ b/api/v1alpha1/zz_generated.deepcopy.go @@ -46,6 +46,76 @@ func (in *APIConfig) DeepCopy() *APIConfig { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *AuthorizationSpec) DeepCopyInto(out *AuthorizationSpec) { + *out = *in + if in.Basic != nil { + in, out := &in.Basic, &out.Basic + *out = new(BasicAuthSpec) + (*in).DeepCopyInto(*out) + } + if in.Token != nil { + in, out := &in.Token, &out.Token + *out = new(TokenAuthSpec) + (*in).DeepCopyInto(*out) + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AuthorizationSpec. +func (in *AuthorizationSpec) DeepCopy() *AuthorizationSpec { + if in == nil { + return nil + } + out := new(AuthorizationSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *BasicAuthSpec) DeepCopyInto(out *BasicAuthSpec) { + *out = *in + if in.CredentialsSecretRef != nil { + in, out := &in.CredentialsSecretRef, &out.CredentialsSecretRef + *out = new(v1.SecretKeySelector) + (*in).DeepCopyInto(*out) + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new BasicAuthSpec. +func (in *BasicAuthSpec) DeepCopy() *BasicAuthSpec { + if in == nil { + return nil + } + out := new(BasicAuthSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ClientTLSConfig) DeepCopyInto(out *ClientTLSConfig) { + *out = *in + if in.CABundle != nil { + in, out := &in.CABundle, &out.CABundle + *out = make([]byte, len(*in)) + copy(*out, *in) + } + if in.CABundleSecretRef != nil { + in, out := &in.CABundleSecretRef, &out.CABundleSecretRef + *out = new(v1.SecretKeySelector) + (*in).DeepCopyInto(*out) + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClientTLSConfig. +func (in *ClientTLSConfig) DeepCopy() *ClientTLSConfig { + if in == nil { + return nil + } + out := new(ClientTLSConfig) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Cluster) DeepCopyInto(out *Cluster) { *out = *in @@ -213,21 +283,6 @@ func (in *ClusterTargetState) DeepCopy() *ClusterTargetState { return out } -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ConsulConfig) DeepCopyInto(out *ConsulConfig) { - *out = *in -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ConsulConfig. -func (in *ConsulConfig) DeepCopy() *ConsulConfig { - if in == nil { - return nil - } - out := new(ConsulConfig) - in.DeepCopyInto(out) - return out -} - // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *GRPCKeepAliveConfig) DeepCopyInto(out *GRPCKeepAliveConfig) { *out = *in @@ -273,6 +328,36 @@ func (in *GRPCTunnelConfig) DeepCopy() *GRPCTunnelConfig { // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *HTTPConfig) DeepCopyInto(out *HTTPConfig) { *out = *in + if in.Authorization != nil { + in, out := &in.Authorization, &out.Authorization + *out = new(AuthorizationSpec) + (*in).DeepCopyInto(*out) + } + if in.PollInterval != nil { + in, out := &in.PollInterval, &out.PollInterval + *out = new(metav1.Duration) + **out = **in + } + if in.Timeout != nil { + in, out := &in.Timeout, &out.Timeout + *out = new(metav1.Duration) + **out = **in + } + if in.TLS != nil { + in, out := &in.TLS, &out.TLS + *out = new(ClientTLSConfig) + (*in).DeepCopyInto(*out) + } + if in.Pagination != nil { + in, out := &in.Pagination, &out.Pagination + *out = new(PaginationSpec) + **out = **in + } + if in.ResponseMapping != nil { + in, out := &in.ResponseMapping, &out.ResponseMapping + *out = new(ResponseMappingSpec) + (*in).DeepCopyInto(*out) + } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new HTTPConfig. @@ -587,6 +672,21 @@ func (in *OutputStatus) DeepCopy() *OutputStatus { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *PaginationSpec) DeepCopyInto(out *PaginationSpec) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PaginationSpec. +func (in *PaginationSpec) DeepCopy() *PaginationSpec { + if in == nil { + return nil + } + out := new(PaginationSpec) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Pipeline) DeepCopyInto(out *Pipeline) { *out = *in @@ -824,12 +924,7 @@ func (in *ProviderSpec) DeepCopyInto(out *ProviderSpec) { if in.HTTP != nil { in, out := &in.HTTP, &out.HTTP *out = new(HTTPConfig) - **out = **in - } - if in.Consul != nil { - in, out := &in.Consul, &out.Consul - *out = new(ConsulConfig) - **out = **in + (*in).DeepCopyInto(*out) } } @@ -843,6 +938,28 @@ func (in *ProviderSpec) DeepCopy() *ProviderSpec { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ResponseMappingSpec) DeepCopyInto(out *ResponseMappingSpec) { + *out = *in + if in.Labels != nil { + in, out := &in.Labels, &out.Labels + *out = make(map[string]string, len(*in)) + for key, val := range *in { + (*out)[key] = val + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ResponseMappingSpec. +func (in *ResponseMappingSpec) DeepCopy() *ResponseMappingSpec { + if in == nil { + return nil + } + out := new(ResponseMappingSpec) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ServiceConfig) DeepCopyInto(out *ServiceConfig) { *out = *in @@ -1384,6 +1501,26 @@ func (in *TargetTLSConfig) DeepCopy() *TargetTLSConfig { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *TokenAuthSpec) DeepCopyInto(out *TokenAuthSpec) { + *out = *in + if in.TokenSecretRef != nil { + in, out := &in.TokenSecretRef, &out.TokenSecretRef + *out = new(v1.SecretKeySelector) + (*in).DeepCopyInto(*out) + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new TokenAuthSpec. +func (in *TokenAuthSpec) DeepCopy() *TokenAuthSpec { + if in == nil { + return nil + } + out := new(TokenAuthSpec) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *TunnelTargetPolicy) DeepCopyInto(out *TunnelTargetPolicy) { *out = *in diff --git a/cmd/main.go b/cmd/main.go index aaf398a..3bb04f7 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -41,8 +41,8 @@ import ( operatorv1alpha1 "github.com/gnmic/operator/api/v1alpha1" "github.com/gnmic/operator/internal/apiserver" "github.com/gnmic/operator/internal/controller" - "github.com/gnmic/operator/internal/controller/discovery/core" "github.com/gnmic/operator/internal/controller/discovery" + "github.com/gnmic/operator/internal/controller/discovery/core" webhookv1alpha1 "github.com/gnmic/operator/internal/webhook/v1alpha1" //+kubebuilder:scaffold:imports ) diff --git a/config/crd/bases/operator.gnmic.dev_targetsources.yaml b/config/crd/bases/operator.gnmic.dev_targetsources.yaml index 37d6919..eecee6f 100644 --- a/config/crd/bases/operator.gnmic.dev_targetsources.yaml +++ b/config/crd/bases/operator.gnmic.dev_targetsources.yaml @@ -40,33 +40,260 @@ spec: description: TargetSourceSpec defines the desired state of TargetSource properties: provider: + description: |- + Provider defines the source of targets for this TargetSource + Only one provider can be specified per TargetSource properties: - consul: - properties: - url: - minLength: 1 - type: string - type: object http: + description: HTTP defines the configuration for a HTTP provider properties: acceptPush: + default: false + description: |- + If true, the loader will accept pushed target updates to the controller endpoint + The endpoint will be /{namespace}/{targetsource}/ type: boolean + authorization: + description: Optional authorization configuration for accessing + the HTTP endpoint + properties: + basic: + description: Basic authentication configuration + properties: + credentialsSecretRef: + description: |- + Reference to a Secret containing "username" and "password" keys to use for + basic authentication when connecting to the Provider. + Mutually exclusive with Username and Password. + properties: + key: + description: The key of the secret to select from. Must + be a valid secret key. + type: string + name: + default: "" + description: |- + Name of the referent. + This field is effectively required, but due to backwards compatibility is + allowed to be empty. Instances of this type with an empty value here are + almost certainly wrong. + More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names + type: string + optional: + description: Specify whether the Secret or its + key must be defined + type: boolean + required: + - key + type: object + x-kubernetes-map-type: atomic + password: + description: |- + Password for basic auth + Mutually exclusive with CredentialsSecretRef. + type: string + username: + description: |- + Username for basic auth + Mutually exclusive with CredentialsSecretRef. + type: string + type: object + x-kubernetes-validations: + - message: either credentialsSecretRef OR both username + and password must be set, but not a mix + rule: (has(self.credentialsSecretRef) && !has(self.username) + && !has(self.password)) || (!has(self.credentialsSecretRef) + && has(self.username) && has(self.password)) + token: + description: Token-based authentication configuration + properties: + scheme: + description: Scheme for the token, e.g. "Bearer" + minLength: 1 + type: string + token: + description: |- + Token value for authentication + Mutually exclusive with TokenSecretRef. + type: string + tokenSecretRef: + description: |- + Reference to a Secret containing a key with the token value to use for + authentication when connecting to the Provider. + Mutually exclusive with Token. + properties: + key: + description: The key of the secret to select from. Must + be a valid secret key. + type: string + name: + default: "" + description: |- + Name of the referent. + This field is effectively required, but due to backwards compatibility is + allowed to be empty. Instances of this type with an empty value here are + almost certainly wrong. + More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names + type: string + optional: + description: Specify whether the Secret or its + key must be defined + type: boolean + required: + - key + type: object + x-kubernetes-map-type: atomic + required: + - scheme + type: object + x-kubernetes-validations: + - message: either token or tokenSecretRef must be set, + but not both + rule: has(self.token) != has(self.tokenSecretRef) + type: object + x-kubernetes-validations: + - message: exactly one of the fields in [basic token] must + be set + rule: '[has(self.basic),has(self.token)].filter(x,x==true).size() + == 1' + interval: + default: 30s + description: Optional interval for polling the HTTP endpoint + for targets + type: string + mapping: + description: Optional mapping configuration for parsing responses + from the HTTP endpoint + properties: + ip: + description: JSONPath expression to extract the target + IP from the response + type: string + labels: + additionalProperties: + type: string + description: |- + JSONPath expression to extract the target labels from the response + The extracted labels will be merged with the static TargetLabels defined in the TargetSourceSpec, + with values from the response taking precedence in case of conflicts. + type: object + name: + description: JSONPath expression to extract the target + name from the response + type: string + port: + description: JSONPath expression to extract the target + port from the response + type: string + targetProfile: + description: JSONPath expression to extract the target + profile from the response + type: string + required: + - ip + - name + type: object + pagination: + description: Optional pagination configuration for parsing + responses from the HTTP endpoint + properties: + itemsField: + description: |- + Field name in the JSON response that contains the list of items (targets). + Must refer to a top-level key in the response object. + Example: "results" + type: string + nextField: + description: |- + Field name in the JSON response that contains the next page reference. + The value can be either: + - a full URL (used directly for the next request), or + - a pagination token (appended as a query parameter using this field name as the key). + + Must refer to a top-level key in the response object. + Example: "next" or "nextToken" + type: string + type: object + timeout: + default: 10s + description: Optional timeout for HTTP requests to the endpoint + type: string + tls: + description: Optional TLS configuration for connecting to + the HTTP endpoint + properties: + caBundle: + description: |- + Base64-encoded bundle of PEM CAs which will be used to validate the certificate + chain presented by the Provider. Only used if using HTTPS to connect to Provider and + ignored for HTTP connections. + Mutually exclusive with CABundleSecretRef. + format: byte + type: string + caBundleSecretRef: + description: |- + Reference to a Secret containing a bundle of PEM-encoded CAs to use when + verifying the certificate chain presented by the Provider when using HTTPS. + Mutually exclusive with CABundle. + properties: + key: + description: The key of the secret to select from. Must + be a valid secret key. + type: string + name: + default: "" + description: |- + Name of the referent. + This field is effectively required, but due to backwards compatibility is + allowed to be empty. Instances of this type with an empty value here are + almost certainly wrong. + More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names + type: string + optional: + description: Specify whether the Secret or its key + must be defined + type: boolean + required: + - key + type: object + x-kubernetes-map-type: atomic + insecureSkipVerify: + default: false + description: Skip TLS verification of the Provider's certificate. + type: boolean + type: object + x-kubernetes-validations: + - message: caBundle and caBundleSecretRef are mutually exclusive + rule: '!(has(self.caBundle) && has(self.caBundleSecretRef))' url: - minLength: 1 + description: |- + URL of the HTTP endpoint to pull targets from + If defined, the loader will periodically poll this endpoint for targets type: string - required: - - url type: object + x-kubernetes-validations: + - message: at least one of the fields in [url acceptPush] must + be set + rule: '[has(self.url),has(self.acceptPush)].filter(x,x==true).size() + >= 1' type: object x-kubernetes-validations: - - message: exactly one of the fields in [http consul] must be set - rule: '[has(self.http),has(self.consul)].filter(x,x==true).size() - == 1' + - message: exactly one of the fields in [http] must be set + rule: '[has(self.http)].filter(x,x==true).size() == 1' targetLabels: additionalProperties: type: string + description: Optional labels to apply to all targets discovered by + this TargetSource type: object + targetPort: + description: Optional port to use for discovered targets if not specified + by the provider + format: int32 + type: integer targetProfile: + description: The TargetProfile to use for targets discovered by this + TargetSource minLength: 1 type: string required: @@ -79,15 +306,16 @@ spec: lastSync: format: date-time type: string + observedGeneration: + format: int64 + type: integer status: type: string targetsCount: format: int32 type: integer required: - - lastSync - - status - - targetsCount + - observedGeneration type: object type: object served: true diff --git a/go.mod b/go.mod index 9dc2b78..c877a7b 100644 --- a/go.mod +++ b/go.mod @@ -21,6 +21,8 @@ require ( require ( cloud.google.com/go/compute/metadata v0.9.0 // indirect github.com/Masterminds/semver/v3 v3.4.0 // indirect + github.com/PaesslerAG/gval v1.0.0 // indirect + github.com/PaesslerAG/jsonpath v0.1.1 // indirect github.com/beorn7/perks v1.0.1 // indirect github.com/cespare/xxhash/v2 v2.3.0 // indirect github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect diff --git a/go.sum b/go.sum index 45485f1..d900003 100644 --- a/go.sum +++ b/go.sum @@ -2,6 +2,11 @@ cloud.google.com/go/compute/metadata v0.9.0 h1:pDUj4QMoPejqq20dK0Pg2N4yG9zIkYGdB cloud.google.com/go/compute/metadata v0.9.0/go.mod h1:E0bWwX5wTnLPedCKqk3pJmVgCBSM6qQI1yTBdEb3C10= github.com/Masterminds/semver/v3 v3.4.0 h1:Zog+i5UMtVoCU8oKka5P7i9q9HgrJeGzI9SA1Xbatp0= github.com/Masterminds/semver/v3 v3.4.0/go.mod h1:4V+yj/TJE1HU9XfppCwVMZq3I84lprf4nC11bSS5beM= +github.com/PaesslerAG/gval v1.0.0 h1:GEKnRwkWDdf9dOmKcNrar9EA1bz1z9DqPIO1+iLzhd8= +github.com/PaesslerAG/gval v1.0.0/go.mod h1:y/nm5yEyTeX6av0OfKJNp9rBNj2XrGhAf5+v24IBN1I= +github.com/PaesslerAG/jsonpath v0.1.0/go.mod h1:4BzmtoM/PI8fPO4aQGIusjGxGir2BzcV0grWtFzq1Y8= +github.com/PaesslerAG/jsonpath v0.1.1 h1:c1/AToHQMVsduPAa4Vh6xp2U0evy4t8SWp8imEsylIk= +github.com/PaesslerAG/jsonpath v0.1.1/go.mod h1:lVboNxFGal/VwW6d9JzIy56bUsYAP6tH/x80vjnCseY= github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= github.com/cert-manager/cert-manager v1.19.3 h1:3d0Nk/HO3BOmAdBJNaBh+6YgaO3Ciey3xCpOjiX5Obs= diff --git a/internal/controller/discovery/client.go b/internal/controller/discovery/client.go index cb02161..45798ed 100644 --- a/internal/controller/discovery/client.go +++ b/internal/controller/discovery/client.go @@ -2,18 +2,21 @@ package discovery import ( "context" + "fmt" + corev1 "k8s.io/api/core/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/types" + "k8s.io/client-go/util/retry" "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" gnmicv1alpha1 "github.com/gnmic/operator/api/v1alpha1" ) -func fetchExistingTargets( - ctx context.Context, - c client.Client, - ts *gnmicv1alpha1.TargetSource, -) ([]gnmicv1alpha1.Target, error) { - +func fetchExistingTargets(ctx context.Context, c client.Client, ts *gnmicv1alpha1.TargetSource) ([]gnmicv1alpha1.Target, error) { var targetList gnmicv1alpha1.TargetList err := c.List( @@ -30,3 +33,100 @@ func fetchExistingTargets( return targetList.Items, nil } + +func applyTarget(ctx context.Context, c client.Client, s *runtime.Scheme, desired *gnmicv1alpha1.Target, ts *gnmicv1alpha1.TargetSource) error { + existing := &gnmicv1alpha1.Target{ + ObjectMeta: metav1.ObjectMeta{ + Name: desired.Name, + Namespace: desired.Namespace, + }, + } + + _, err := controllerutil.CreateOrUpdate(ctx, c, existing, func() error { + existing.Spec = desired.Spec + existing.Labels = desired.Labels + + return controllerutil.SetControllerReference(ts, existing, s) + }) + + return err +} + +func deleteTarget(ctx context.Context, c client.Client, name string, namespace string) error { + existing := &gnmicv1alpha1.Target{} + + err := c.Get(ctx, types.NamespacedName{ + Name: name, + Namespace: namespace, + }, existing) + if apierrors.IsNotFound(err) { + return nil + } else if err != nil { + return err + } + + err = c.Delete(ctx, existing) + if apierrors.IsNotFound(err) { + return nil + } + + return err +} + +// updateTargetSourceStatus updates the status of the TargetSource Object ts. The only fields updated are targetCount and LastSync, which takes the current timestamp. +func updateTargetSourceStatus(ctx context.Context, c client.Client, ts *gnmicv1alpha1.TargetSource, targetCount int32) error { + err := retry.RetryOnConflict(retry.DefaultRetry, func() error { + latest := &gnmicv1alpha1.TargetSource{} + if err := c.Get(ctx, client.ObjectKeyFromObject(ts), latest); err != nil { + return err + } + + latest.Status.TargetsCount = targetCount + latest.Status.LastSync = metav1.Now() + + return c.Status().Update(ctx, latest) + }) + + return err +} + +// Helper: GetSecretValues returns values from a secret +// If keys are provided -> returns only those keys +// If keys is empty -> returns entire secret data +func GetSecretValues( + ctx context.Context, + c client.Client, + namespace string, + secretRef string, + keys ...string, +) (map[string]string, error) { + var secret corev1.Secret + if err := c.Get(ctx, + client.ObjectKey{ + Name: secretRef, + Namespace: namespace, + }, &secret); err != nil { + return nil, fmt.Errorf("failed to get secret %s/%s: %w", namespace, secretRef, err) + } + + result := make(map[string]string) + + // Return full secret + if len(keys) == 0 { + for k, v := range secret.Data { + result[k] = string(v) + } + return result, nil + } + + // Return specific keys + for _, key := range keys { + val, ok := secret.Data[key] + if !ok { + return nil, fmt.Errorf("key %s missing in secret %s/%s", key, namespace, secretRef) + } + result[key] = string(val) + } + + return result, nil +} diff --git a/internal/controller/discovery/const.go b/internal/controller/discovery/const.go index ac7a57f..8d37785 100644 --- a/internal/controller/discovery/const.go +++ b/internal/controller/discovery/const.go @@ -1,6 +1,13 @@ package discovery const ( - // Labels + // Kubernetes Side Labels LabelTargetSourceName = "operator.gnmic.dev/targetsource" ) + +const ( + // Prefix and Labels for external systems + ExternalLabelPrefix = "gnmic_operator_" + + ExternalLabelTargetProfile = ExternalLabelPrefix + "target_profile" +) diff --git a/internal/controller/discovery/core/loader_interface.go b/internal/controller/discovery/core/loader_interface.go index 895258a..97810cb 100644 --- a/internal/controller/discovery/core/loader_interface.go +++ b/internal/controller/discovery/core/loader_interface.go @@ -2,6 +2,8 @@ package core import ( "context" + + gnmicv1alpha1 "github.com/gnmic/operator/api/v1alpha1" ) // Loader defines a pluggable TargetSource loader interface @@ -12,5 +14,5 @@ type Loader interface { // Run begins discovery and pushes target snapshots or events into the out channel // The loader must stop cleanly when ctx is canceled - Run(ctx context.Context, out chan<- []DiscoveryMessage) error + Run(ctx context.Context, out chan<- []DiscoveryMessage, spec gnmicv1alpha1.TargetSourceSpec) error } diff --git a/internal/controller/discovery/core/types.go b/internal/controller/discovery/core/types.go index 99605b9..7c6d39c 100644 --- a/internal/controller/discovery/core/types.go +++ b/internal/controller/discovery/core/types.go @@ -37,9 +37,11 @@ const ( // DiscoveredTarget represents a target discovered from an external source // before it is materialized as a Kubernetes Target CR type DiscoveredTarget struct { - Name string - Address string - Labels map[string]string + Name string + IP string + Port int32 + Labels map[string]string + TargetProfile string } type DiscoveryEvent struct { @@ -47,6 +49,17 @@ type DiscoveryEvent struct { Event EventAction } +func (e EventAction) String() string { + switch e { + case EventDelete: + return "DELETE" + case EventApply: + return "APPLY" + default: + return "UNKNOWN" + } +} + type DiscoverySnapshot struct { SnapshotID string ChunkIndex int diff --git a/internal/controller/discovery/loaders.go b/internal/controller/discovery/loaders.go index c888c27..42ab588 100644 --- a/internal/controller/discovery/loaders.go +++ b/internal/controller/discovery/loaders.go @@ -1,24 +1,170 @@ package discovery import ( + "context" "fmt" + "sigs.k8s.io/controller-runtime/pkg/client" + gnmicv1alpha1 "github.com/gnmic/operator/api/v1alpha1" "github.com/gnmic/operator/internal/controller/discovery/core" http "github.com/gnmic/operator/internal/controller/discovery/loaders/http" ) // NewLoader creates a loader by name -func NewLoader(cfg *core.CommonLoaderConfig, spec gnmicv1alpha1.TargetSourceSpec) (core.Loader, error) { +func NewLoader(ctx context.Context, c client.Client, cfg *core.CommonLoaderConfig, spec gnmicv1alpha1.TargetSourceSpec) (core.Loader, error) { switch { case spec.Provider.HTTP != nil: - cfg.AcceptPush = spec.Provider.HTTP.AcceptPush - return http.New(*cfg), nil - case spec.Provider.Consul != nil: - return nil, fmt.Errorf("Unimplemented targetsource provider, check TargetSource CRD for %s", cfg.TargetsourceNN) + httpSpec := *spec.Provider.HTTP + cfg.AcceptPush = httpSpec.AcceptPush + + // TODO: watch secrets -> if secret changes reconcile has to be executed + if httpSpec.Authorization != nil { + if err := resolveAuthorizationIntoSpec( + ctx, + c, + cfg.TargetsourceNN.Namespace, + httpSpec.Authorization, + ); err != nil { + return nil, err + } + } + if httpSpec.TLS != nil { + if err := resolveTLSIntoSpec( + ctx, + c, + cfg.TargetsourceNN.Namespace, + httpSpec.TLS, + ); err != nil { + return nil, err + } + } + + return http.New(*cfg, httpSpec), nil default: return nil, fmt.Errorf("unknown targetsource provider, check TargetSource CRD for %s", cfg.TargetsourceNN) } +} + +// resolveAuthorizationIntoSpec fetches credentials from Kubernetes Secrets +// and populates the AuthorizationSpec accordingly +func resolveAuthorizationIntoSpec( + ctx context.Context, + c client.Client, + namespace string, + authSpec *gnmicv1alpha1.AuthorizationSpec, +) error { + if authSpec == nil { + return nil + } + auth := authSpec + + switch { + case auth.Basic != nil: + b := auth.Basic + + if b.CredentialsSecretRef != nil { + values, err := GetSecretValues( + ctx, + c, + namespace, + b.CredentialsSecretRef.Name, + "username", + "password", + ) + if err != nil { + return err + } + b.Username = values["username"] + b.Password = values["password"] + } + + case auth.Token != nil: + t := auth.Token + if t.TokenSecretRef != nil { + key := "token" + if t.TokenSecretRef.Key != "" { + key = t.TokenSecretRef.Key + } + values, err := GetSecretValues( + ctx, + c, + namespace, + t.TokenSecretRef.Name, + key, + ) + if err != nil { + return err + } + t.Token = values[key] + } + + // case auth.JWT != nil: + // jwt := auth.JWT + // if jwt.TokenSecretRef != nil { + // values, err := GetSecretValues( + // ctx, + // c, + // namespaceName, + // jwt.TokenSecretRef.Name, + // "token", + // ) + // if err != nil { + // return err + // } + // jwt.Token = values[jwt.TokenSecretRef.Key] + // } + // if jwt.SigningKeySecretRef != nil { + // values, err := GetSecretValues( + // ctx, + // c, + // namespaceName, + // jwt.SigningKeySecretRef.Name, + // "key", + // ) + // if err != nil { + // return err + // } + // jwt.Key = values[jwt.SigningKeySecretRef.Key] + + // } + } + + return nil +} + +// resolveTLSIntoSpec fetches TLS credentials from Kubernetes Secrets +// and populates the ClientTLSConfig accordingly +func resolveTLSIntoSpec( + ctx context.Context, + c client.Client, + namespace string, + tlsSpec *gnmicv1alpha1.ClientTLSConfig, +) error { + if tlsSpec == nil { + return nil + } + tls := tlsSpec + + if tls.CABundleSecretRef != nil { + key := "ca.crt" + if tls.CABundleSecretRef.Key != "" { + key = tls.CABundleSecretRef.Key + } + values, err := GetSecretValues( + ctx, + c, + namespace, + tls.CABundleSecretRef.Name, + key, + ) + if err != nil { + return err + } + // convert string to []byte + tls.CABundle = []byte(values[key]) + } + return nil } diff --git a/internal/controller/discovery/loaders/http/auth.go b/internal/controller/discovery/loaders/http/auth.go new file mode 100644 index 0000000..0af0556 --- /dev/null +++ b/internal/controller/discovery/loaders/http/auth.go @@ -0,0 +1,38 @@ +package http + +import ( + "fmt" + "net/http" +) + +func (l *Loader) applyAuthorization(req *http.Request) { + auth := l.spec.Authorization + if auth == nil { + return + } + + switch { + case auth.Basic != nil: + req.SetBasicAuth( + auth.Basic.Username, + auth.Basic.Password, + ) + + case auth.Token != nil: + req.Header.Set( + "Authorization", + fmt.Sprintf("%s %s", + auth.Token.Scheme, + auth.Token.Token, + ), + ) + + // case auth.JWT != nil: + // if auth.JWT.Token != "" { + // req.Header.Set( + // "Authorization", + // fmt.Sprintf("Bearer %s", auth.JWT.Token), + // ) + // } + } +} diff --git a/internal/controller/discovery/loaders/http/loader.go b/internal/controller/discovery/loaders/http/loader.go index 3325adb..5f837dc 100644 --- a/internal/controller/discovery/loaders/http/loader.go +++ b/internal/controller/discovery/loaders/http/loader.go @@ -2,46 +2,112 @@ package http import ( "context" + "crypto/tls" + "crypto/x509" + "encoding/json" "fmt" + "net/http" "time" + "github.com/google/uuid" + "sigs.k8s.io/controller-runtime/pkg/log" + gnmicv1alpha1 "github.com/gnmic/operator/api/v1alpha1" "github.com/gnmic/operator/internal/controller/discovery/core" loaderUtils "github.com/gnmic/operator/internal/controller/discovery/loaders/utils" - "github.com/google/uuid" ) +// Loader implements the HTTP pull discovery mechanism +// It periodically polls an HTTP endpoint, extracts targets from the response, +// and emits discovery snapshots downstream type Loader struct { - commonCfg core.CommonLoaderConfig + loaderCfg core.CommonLoaderConfig + spec gnmicv1alpha1.HTTPConfig } -// New instantiates the http loader with the provided config -func New(cfg core.CommonLoaderConfig) core.Loader { - return &Loader{commonCfg: cfg} +// New creates a new HTTP loader instance with the provided configuration. +// The loader is stateless apart from its config and spec +func New(cfg core.CommonLoaderConfig, httpConfig gnmicv1alpha1.HTTPConfig) core.Loader { + return &Loader{loaderCfg: cfg, spec: httpConfig} } +// Name returns the loader's name, used for logging and metrics func (l *Loader) Name() string { return "http" } -func (l *Loader) Run(ctx context.Context, out chan<- []core.DiscoveryMessage) error { +// Run starts the HTTP discovery loop +// It performs an immediate fetch and then continues polling at a fixed interval +func (l *Loader) Run(ctx context.Context, out chan<- []core.DiscoveryMessage, spec gnmicv1alpha1.TargetSourceSpec) error { + if l.spec.URL == "" { + return nil + } + logger := log.FromContext(ctx).WithValues( "component", "loader", "name", l.Name(), - "targetsource", l.commonCfg.TargetsourceNN, + "targetsource", l.loaderCfg.TargetsourceNN, ) logger.Info( "HTTP loader started", - "targetsource", l.commonCfg.TargetsourceNN.Name, - "namespace", l.commonCfg.TargetsourceNN.Namespace, + "targetsource", l.loaderCfg.TargetsourceNN.Name, + "namespace", l.loaderCfg.TargetsourceNN.Namespace, ) - // Only for debugging: emit a static snapshot every 30 seconds - ticker := time.NewTicker(30 * time.Second) + logger.Info("HTTP loader started") + + client, err := l.buildHTTPClient() + if err != nil { + return fmt.Errorf("failed to build HTTP client: %w", err) + } + interval := l.spec.PollInterval.Duration + ticker := time.NewTicker(interval) defer ticker.Stop() + logger.Info( + "HTTP polling discovery started", + "interval", interval.String(), + "url", l.spec.URL, + ) + + // helper function to fetch targets and emit discovery messages + fetchAndEmit := func() { + // Fetch targets from HTTP endpoint + targets, err := l.fetchTargetsFromHTTPEndpoint(ctx, client) + if err != nil { + logger.Error( + err, + "Failed to fetch targets from HTTP endpoint", + "url", l.spec.URL, + ) + return + } + + // Emit discovery snapshot downstream + snapshotID := fmt.Sprintf("%s-%s-%s", l.loaderCfg.TargetsourceNN.Namespace, l.loaderCfg.TargetsourceNN.Name, uuid.NewString()) + if err := loaderUtils.SendSnapshot(ctx, out, targets, snapshotID, l.loaderCfg.ChunkSize); err != nil { + logger.Error( + err, + "Failed to send discovery snapshot", + "snapshotID", snapshotID, + "targets", len(targets), + ) + return + } + + logger.Info( + "Discovery snapshot sent", + "snapshotID", snapshotID, + "targets", len(targets), + ) + } + + // Immediate fetch on startup + fetchAndEmit() + + // Periodic fetch for { select { case <-ctx.Done(): @@ -49,24 +115,139 @@ func (l *Loader) Run(ctx context.Context, out chan<- []core.DiscoveryMessage) er return nil case <-ticker.C: - // Example snapshot (placeholder) - snapshotID := fmt.Sprintf("%s-%s-%s", l.commonCfg.TargetsourceNN.Namespace, l.commonCfg.TargetsourceNN.Name, uuid.NewString()) - targets := []core.DiscoveredTarget{ - { - Name: "ceos1", - Address: "clab-3-nodes-ceos1:6030", - Labels: map[string]string{"TargetSource": l.commonCfg.TargetsourceNN.String()}, - }, - { - Name: "leaf1", - Address: "clab-3-nodes-leaf1:57400", - Labels: map[string]string{"TargetSource": l.commonCfg.TargetsourceNN.String()}, - }, + fetchAndEmit() + } + } +} + +// buildHTTPClient constructs an HTTP client with optional configuration +func (l *Loader) buildHTTPClient() (*http.Client, error) { + tlsConfig := &tls.Config{ + InsecureSkipVerify: l.spec.TLS != nil && l.spec.TLS.InsecureSkipVerify, + } + + // If a CA bundle is provided, add it to the TLS config + if l.spec.TLS != nil && len(l.spec.TLS.CABundle) > 0 { + certPool := x509.NewCertPool() + if ok := certPool.AppendCertsFromPEM(l.spec.TLS.CABundle); !ok { + return nil, fmt.Errorf("Failed to parse CA bundle for TargetSource %s/%s\n", l.loaderCfg.TargetsourceNN.Namespace, l.loaderCfg.TargetsourceNN.Name) + } + tlsConfig.RootCAs = certPool + } + + // Build the HTTP client with the specified timeout and TLS config + return &http.Client{ + Timeout: l.spec.Timeout.Duration, + Transport: &http.Transport{ + TLSClientConfig: tlsConfig, + }, + }, nil +} + +// fetchTargetsFromHTTPEndpoint retrieves targets from the configured HTTP endpoint +func (l *Loader) fetchTargetsFromHTTPEndpoint( + ctx context.Context, + client *http.Client, +) ([]core.DiscoveredTarget, error) { + var allTargets []core.DiscoveredTarget + currentUrl := l.spec.URL + + for { + // Create HTTP request with context + req, err := http.NewRequestWithContext(ctx, http.MethodGet, currentUrl, nil) + if err != nil { + return nil, fmt.Errorf("creating HTTP request failed: %w", err) + } + req.Header.Set("Accept", "application/json") + l.applyAuthorization(req) + + // Execute HTTP request + resp, err := client.Do(req) + if err != nil { + return nil, fmt.Errorf("HTTP request failed: %w", err) + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + return nil, fmt.Errorf("unexpected HTTP status code: %d", resp.StatusCode) + } + + // Decode response into raw map for pagination support + var raw interface{} + if err := json.NewDecoder(resp.Body).Decode(&raw); err != nil { + return nil, fmt.Errorf("failed to decode HTTP response: %w", err) + } + + // Extract targets from response + targets, err := l.extractTargetsFromResponse(raw) + if err != nil { + return nil, err + } + allTargets = append(allTargets, targets...) + + // Check for pagination + nextPageInfo, err := l.extractNextPageInfo(raw) + if err != nil { + return nil, err + } + if nextPageInfo == "" { + break + } + nextURL, err := l.buildNextURL(currentUrl, nextPageInfo) + if err != nil { + return nil, err + } + currentUrl = nextURL + } + + return allTargets, nil +} + +// extractTargetsFromResponse extracts items from the response +// and maps each item into a DiscoveredTarget +func (l *Loader) extractTargetsFromResponse(raw interface{}) ([]core.DiscoveredTarget, error) { + var items []interface{} + + switch v := raw.(type) { + // Top-level array response + case []interface{}: + items = v + // Object with itemsField containing the array + case map[string]interface{}: + if l.spec.Pagination != nil && l.spec.Pagination.ItemsField != "" { + // Extract items array from response using itemsField + val, ok := v[l.spec.Pagination.ItemsField] + if !ok { + return nil, fmt.Errorf("itemsField '%s' not found", l.spec.Pagination.ItemsField) } - if err := loaderUtils.SendSnapshot(ctx, out, targets, snapshotID, l.commonCfg.ChunkSize); err != nil { - return err + arr, ok := val.([]interface{}) + if !ok { + return nil, fmt.Errorf("itemsField '%s' is not an array", l.spec.Pagination.ItemsField) } + + items = arr + } else { + return nil, fmt.Errorf("response is an object but no itemsField specified for TargetSource %s/%s", l.loaderCfg.TargetsourceNN.Namespace, l.loaderCfg.TargetsourceNN.Name) } + default: + return nil, fmt.Errorf("unexpected response format") } + + // Map items to targets + var targets []core.DiscoveredTarget + for _, item := range items { + obj, ok := item.(map[string]interface{}) + if !ok { + continue + } + + target, err := l.mapItem(obj) + if err != nil { + return nil, err + } + + targets = append(targets, target) + } + + return targets, nil } diff --git a/internal/controller/discovery/loaders/http/mapper.go b/internal/controller/discovery/loaders/http/mapper.go new file mode 100644 index 0000000..de618fa --- /dev/null +++ b/internal/controller/discovery/loaders/http/mapper.go @@ -0,0 +1,85 @@ +package http + +import ( + "math" + "strconv" + + "github.com/gnmic/operator/internal/controller/discovery/core" +) + +// valueGetter defines the contract for extracting values from a response item +type valueGetter interface { + GetName() (string, error) + GetIP() (string, error) + GetPort() int32 + GetLabels() map[string]string + GetTargetProfile() string +} + +// getGetter selects the extraction strategy based on the spec +// If no ResponseMapping is defined -> use direct mapping +func (l *Loader) getGetter(item map[string]interface{}) valueGetter { + if l.spec.ResponseMapping == nil { + return &directGetter{ + item: item, + } + } + + return &jsonPathGetter{ + item: item, + spec: l.spec.ResponseMapping, + } +} + +// mapItem is the mapping entrypoint used by the loader +// It uses the selected valueGetter and produces a DiscoveredTarget +func (l *Loader) mapItem(item map[string]interface{}) (core.DiscoveredTarget, error) { + getter := l.getGetter(item) + + name, err := getter.GetName() + if err != nil { + return core.DiscoveredTarget{}, err + } + + ip, err := getter.GetIP() + if err != nil { + return core.DiscoveredTarget{}, err + } + + port := getter.GetPort() + labels := getter.GetLabels() + targetProfile := getter.GetTargetProfile() + + return core.DiscoveredTarget{ + Name: name, + IP: ip, + Port: port, + Labels: labels, + TargetProfile: targetProfile, + }, nil +} + +// extractPort attempts to normalize different JSON types into int32 +// +// Supports: +// - float64 (default JSON number type) +// - string ("1234") +// +// Returns 0 if conversion fails (treated as "no port specified"). +func extractPort(val interface{}) int32 { + switch v := val.(type) { + case float64: + if v < 0 || v > math.MaxInt32 { + return 0 + } + return int32(v) + case string: + p, err := strconv.ParseInt(v, 10, 32) + if err != nil { + return 0 + } + return int32(p) + default: + return 0 + } +} diff --git a/internal/controller/discovery/loaders/http/mapper_direct.go b/internal/controller/discovery/loaders/http/mapper_direct.go new file mode 100644 index 0000000..185e1cb --- /dev/null +++ b/internal/controller/discovery/loaders/http/mapper_direct.go @@ -0,0 +1,82 @@ +package http + +import ( + "fmt" +) + +// directGetter extracts values via direct map access +// Example input: +// +// { +// "name": "router1", +// "ip": "10.0.0.1", +// "port": 57400, +// "labels": { ... }, +// "targetProfile": "profile1" +// } +type directGetter struct { + item map[string]interface{} +} + +// GetName extracts the "name" field directly +func (g *directGetter) GetName() (string, error) { + val, ok := g.item["name"].(string) + if !ok || val == "" { + return "", fmt.Errorf("name must be a non-empty string") + } + return val, nil +} + +// GetIP extracts the "ip" field directly. +func (g *directGetter) GetIP() (string, error) { + val, ok := g.item["ip"].(string) + if !ok || val == "" { + return "", fmt.Errorf("ip must be a non-empty string") + } + return val, nil +} + +// GetPort extracts and normalizes the "port" field +// +// Behavior: +// - supports int, float64, string +// - returns 0 if value is missing or invalid +func (g *directGetter) GetPort() int32 { + if val, ok := g.item["port"]; ok { + return extractPort(val) + } + return 0 +} + +// GetLabels extracts labels from the "labels" field +// Expected format: +// +// "labels": { +// "key": "value" +// } +// +// Non-string values are converted to string +func (g *directGetter) GetLabels() map[string]string { + labels := make(map[string]string) + + if val, ok := g.item["labels"]; ok { + if m, ok := val.(map[string]interface{}); ok { + for k, v := range m { + labels[k] = fmt.Sprintf("%v", v) + } + } + } + + return labels +} + +// GetTargetProfile extracts the "targetProfile" field directly +// +// Behavior: +// - returns "" if value is missing or invalid +func (g *directGetter) GetTargetProfile() string { + if val, ok := g.item["targetProfile"].(string); ok { + return val + } + return "" +} diff --git a/internal/controller/discovery/loaders/http/mapper_jsonpath.go b/internal/controller/discovery/loaders/http/mapper_jsonpath.go new file mode 100644 index 0000000..85bf00a --- /dev/null +++ b/internal/controller/discovery/loaders/http/mapper_jsonpath.go @@ -0,0 +1,106 @@ +package http + +import ( + "fmt" + + "github.com/PaesslerAG/jsonpath" + gnmicv1alpha1 "github.com/gnmic/operator/api/v1alpha1" +) + +// jsonPathGetter extracts values using JSONPath expressions defined in the CR +// Example mapping: +// +// name: "$.hostname" +// ip: "$.ip" +// port: "$.port" +// labels: +// rack: "$.meta.rack" +type jsonPathGetter struct { + item map[string]interface{} + spec *gnmicv1alpha1.ResponseMappingSpec +} + +// helper function to execute JSONPath queries +func (g *jsonPathGetter) get(expr string) (interface{}, error) { + return jsonpath.Get(expr, g.item) +} + +// GetName extracts the target name using JSONPath +func (g *jsonPathGetter) GetName() (string, error) { + val, err := g.get(g.spec.Name) + if err != nil { + return "", fmt.Errorf("name mapping failed: %w", err) + } + + str, ok := val.(string) + if !ok || str == "" { + return "", fmt.Errorf("name must be a non-empty string") + } + + return str, nil +} + +// GetIP extracts the IP using JSONPath +func (g *jsonPathGetter) GetIP() (string, error) { + val, err := g.get(g.spec.IP) + if err != nil { + return "", fmt.Errorf("IP mapping failed: %w", err) + } + + str, ok := val.(string) + if !ok || str == "" { + return "", fmt.Errorf("IP must be a non-empty string") + } + + return str, nil +} + +// GetPort extracts the port using JSONPath +// +// Behavior: +// - returns 0 if no port mapping defined +// - returns 0 if extraction fails or value invalid +func (g *jsonPathGetter) GetPort() int32 { + if g.spec.Port == "" { + return 0 + } + + val, err := g.get(g.spec.Port) + if err != nil { + return 0 + } + + return extractPort(val) +} + +// GetLabels extracts labels using JSONPath expressions defined per label key +func (g *jsonPathGetter) GetLabels() map[string]string { + labels := make(map[string]string) + + for key, expr := range g.spec.Labels { + if val, err := g.get(expr); err == nil { + labels[key] = fmt.Sprintf("%v", val) + } + } + + return labels +} + +// GetTargetProfile extracts the target profile using JSONPath +// +// Behavior: +// - returns "" if no target profile mapping defined +// - returns "" if extraction fails or value invalid +func (g *jsonPathGetter) GetTargetProfile() string { + val, err := g.get(g.spec.TargetProfile) + if err != nil { + return "" + } + + str, ok := val.(string) + if !ok { + return "" + } + + return str +} diff --git a/internal/controller/discovery/loaders/http/pagination.go b/internal/controller/discovery/loaders/http/pagination.go new file mode 100644 index 0000000..9fef778 --- /dev/null +++ b/internal/controller/discovery/loaders/http/pagination.go @@ -0,0 +1,51 @@ +package http + +import ( + "fmt" + "net/url" +) + +// extractNextPageInfo extracts pagination information from a response +func (l *Loader) extractNextPageInfo(raw interface{}) (string, error) { + if l.spec.Pagination == nil || l.spec.Pagination.NextField == "" { + return "", nil + } + + // Only objects can have "next" fields + obj, ok := raw.(map[string]interface{}) + if !ok { + // array case -> no pagination + return "", nil + } + + val, ok := obj[l.spec.Pagination.NextField] + if !ok { + return "", fmt.Errorf("nextField '%s' not found in response", l.spec.Pagination.NextField) + } + + next, ok := val.(string) + if !ok { + return "", fmt.Errorf("nextField '%s' is not a string in response", l.spec.Pagination.NextField) + } + + return next, nil +} + +// buildNextURL constructs the URL for the next page based on the current URL and pagination info +func (l *Loader) buildNextURL(currentURL, nextVal string) (string, error) { + // nextVal is a full URL -> return as is + if parsed, err := url.Parse(nextVal); err == nil && parsed.Scheme != "" { + return nextVal, nil + } + + // nextVal is a token -> append as query parameter + parsedURL, err := url.Parse(currentURL) + if err != nil { + return "", fmt.Errorf("failed to parse current URL in order to build next URL: %w", err) + } + q := parsedURL.Query() + q.Set(l.spec.Pagination.NextField, nextVal) + parsedURL.RawQuery = q.Encode() + + return parsedURL.String(), nil +} diff --git a/internal/controller/discovery/mapper.go b/internal/controller/discovery/mapper.go new file mode 100644 index 0000000..f3521cb --- /dev/null +++ b/internal/controller/discovery/mapper.go @@ -0,0 +1,91 @@ +package discovery + +import ( + "fmt" + "maps" + "strings" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + + gnmicv1alpha1 "github.com/gnmic/operator/api/v1alpha1" + "github.com/gnmic/operator/internal/controller/discovery/core" +) + +// generateTargetResource converts a DiscoveredTarget into a Kubernetes Target Object based on the TargetSource Spec. +// Returns the Target Resource and a map of unknown operator labels. +func generateTargetResource(d core.DiscoveredTarget, ts *gnmicv1alpha1.TargetSource) (*gnmicv1alpha1.Target, map[string]string) { + // Create object instance + t := &gnmicv1alpha1.Target{ + ObjectMeta: metav1.ObjectMeta{ + Name: d.Name, + Namespace: ts.Namespace, + Labels: make(map[string]string), + }, + } + unknownLabels := make(map[string]string) + + // Add Address from DiscoveredTarget + t.Spec.Address = fmt.Sprintf("%s:%d", d.IP, d.Port) + // Add default Target Profile from the TargetSource Spec TargetProfile + t.Spec.Profile = ts.Spec.TargetProfile + + // Handle labels from Source of Truth + for k, v := range d.Labels { + if strings.HasPrefix(k, ExternalLabelPrefix) { + switch k { + case ExternalLabelTargetProfile: // Overwrite TargetProfile if specified by SoT + t.Spec.Profile = v + default: + unknownLabels[k] = v + } + } else { // Copy all other labels into the Target + t.Labels[k] = v + } + } + + // Copy TargetLabels from TargetSource Spec + maps.Copy(t.Labels, ts.Spec.TargetLabels) + + // Add TargetSource Label to the Target (precedence over all labels) + t.Labels[LabelTargetSourceName] = ts.Name + + return t, unknownLabels +} + +// generateEvents returns a list of DiscoveryEvents. Needed for snapshot handling to determine which devices get deleted and which applied. +func generateEvents(existing []gnmicv1alpha1.Target, discovered []core.DiscoveredTarget) []core.DiscoveryEvent { + var events []core.DiscoveryEvent + + discoveredMap := make(map[string]core.DiscoveredTarget) + for _, d := range discovered { + discoveredMap[d.Name] = d + } + + // Create delete events for targets which are present in existing but not in discovered + for _, e := range existing { + if _, found := discoveredMap[e.Name]; !found { + events = append(events, core.DiscoveryEvent{ + Target: core.DiscoveredTarget{ + Name: e.Name, + }, + Event: core.EventDelete, + }) + } + } + + // Create apply events for all targets in discovered + for _, d := range discovered { + events = append(events, core.DiscoveryEvent{ + Target: d, + Event: core.EventApply, + }) + } + + return events +} + +// normalizeTarget adds the prefix to the target name for identification in Kubernetes +func normalizeTarget(t core.DiscoveredTarget, tsName string) core.DiscoveredTarget { + t.Name = tsName + "-" + t.Name + return t +} diff --git a/internal/controller/discovery/mapper_test.go b/internal/controller/discovery/mapper_test.go new file mode 100644 index 0000000..295478e --- /dev/null +++ b/internal/controller/discovery/mapper_test.go @@ -0,0 +1,454 @@ +package discovery + +import ( + "fmt" + "testing" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + + gnmicv1alpha1 "github.com/gnmic/operator/api/v1alpha1" + "github.com/gnmic/operator/internal/controller/discovery/core" +) + +func mockDiscoveredTargetList(len int) []core.DiscoveredTarget { + targets := make([]core.DiscoveredTarget, len) + + if len > 100 { + len = 100 + } + + for i := range len { + targets[i] = core.DiscoveredTarget{ + IP: fmt.Sprintf("192.168.1.%d", i+1), + Port: 57400, + Name: fmt.Sprintf("router%d", i+1), + } + } + + return targets +} + +func mockDiscoveryTarget(opts ...func(*core.DiscoveredTarget)) core.DiscoveredTarget { + t := core.DiscoveredTarget{ + Name: "target1", + IP: "10.0.0.1", + Port: 57400, + Labels: map[string]string{}, + } + + for _, opt := range opts { + opt(&t) + } + + return t +} + +func withDiscoveredTargetName(name string) func(*core.DiscoveredTarget) { + return func(t *core.DiscoveredTarget) { + t.Name = name + } +} + +func withDiscoveredTargetIP(ip string) func(*core.DiscoveredTarget) { + return func(t *core.DiscoveredTarget) { + t.IP = ip + } +} + +func withDiscoveredTargetLabels(labels map[string]string) func(*core.DiscoveredTarget) { + return func(t *core.DiscoveredTarget) { + t.Labels = labels + } +} + +func mockTargetSource(opts ...func(*gnmicv1alpha1.TargetSource)) gnmicv1alpha1.TargetSource { + ts := gnmicv1alpha1.TargetSource{ + ObjectMeta: metav1.ObjectMeta{ + Name: "ts1", + Namespace: "default", + }, + Spec: gnmicv1alpha1.TargetSourceSpec{ + TargetProfile: "default", + TargetLabels: map[string]string{}, + }, + } + + for _, opt := range opts { + opt(&ts) + } + + return ts +} + +func withTargetSourceName(name string) func(*gnmicv1alpha1.TargetSource) { + return func(ts *gnmicv1alpha1.TargetSource) { + ts.ObjectMeta.Name = name + } +} + +func withTargetSourceNamespace(namespace string) func(*gnmicv1alpha1.TargetSource) { + return func(ts *gnmicv1alpha1.TargetSource) { + ts.ObjectMeta.Namespace = namespace + } +} + +func withTargetSourceTargetProfile(profile string) func(*gnmicv1alpha1.TargetSource) { + return func(ts *gnmicv1alpha1.TargetSource) { + ts.Spec.TargetProfile = profile + } +} + +func withTargetSourceTargetLabels(labels map[string]string) func(*gnmicv1alpha1.TargetSource) { + return func(ts *gnmicv1alpha1.TargetSource) { + ts.Spec.TargetLabels = labels + } +} + +func mockGnmicTargetList(len int) []gnmicv1alpha1.Target { + targets := make([]gnmicv1alpha1.Target, len) + + if len > 100 { + len = 100 + } + + for i := range len { + targets[i] = gnmicv1alpha1.Target{ + ObjectMeta: metav1.ObjectMeta{ + Name: fmt.Sprintf("router%d", i+1), + Namespace: "default", + }, + Spec: gnmicv1alpha1.TargetSpec{ + Address: fmt.Sprintf("192.168.1.%d", i+1), + Profile: "default", + }, + } + } + + return targets +} + +func TestGenerateEvents_EmptyLists(t *testing.T) { + events := generateEvents( + mockGnmicTargetList(0), + mockDiscoveredTargetList(0), + ) + + if len(events) != 0 { + t.Fatalf("expected 0 events, got %d", len(events)) + } +} + +func TestGenerateEvents_AllDiscoveredTargetsBecomeApplyEvents(t *testing.T) { + discovered := mockDiscoveredTargetList(5) + + events := generateEvents( + mockGnmicTargetList(0), + discovered, + ) + + if len(events) != len(discovered) { + t.Fatalf("expected %d events, got %d", len(discovered), len(events)) + } + + for _, event := range events { + if event.Event != core.EventApply { + t.Fatalf( + "expected all events to be %s, got %s", + core.EventApply.String(), + event.Event.String(), + ) + } + } +} + +func TestGenerateEvents_AllExistingTargetsBecomeDeleteEvents(t *testing.T) { + existing := mockGnmicTargetList(5) + + events := generateEvents( + existing, + mockDiscoveredTargetList(0), + ) + + if len(events) != len(existing) { + t.Fatalf("expected %d events, got %d", len(existing), len(events)) + } + + for _, event := range events { + if event.Event != core.EventDelete { + t.Fatalf( + "expected all events to be %s, got %s", + core.EventDelete.String(), + event.Event.String(), + ) + } + } +} + +func TestGenerateEvents_GeneratesDeleteThenApplyEvents(t *testing.T) { + existing := mockGnmicTargetList(5) + discovered := mockDiscoveredTargetList(3) + + events := generateEvents(existing, discovered) + + var ( + numDelete int + numApply int + seenApply bool + ) + + for _, event := range events { + switch event.Event { + case core.EventDelete: + if seenApply { + t.Fatalf("expected delete events before apply events") + } + numDelete++ + + case core.EventApply: + seenApply = true + numApply++ + } + } + + if numDelete != 2 { + t.Fatalf("expected 2 delete events, got %d", numDelete) + } + + if numApply != 3 { + t.Fatalf("expected 3 apply events, got %d", numApply) + } +} + +func TestGenerateEvents_OnlyApplyEventsAreGeneratedForNewTargets(t *testing.T) { + existing := mockGnmicTargetList(3) + discovered := mockDiscoveredTargetList(5) + + events := generateEvents(existing, discovered) + + var ( + numDelete int + numApply int + ) + + for _, event := range events { + switch event.Event { + case core.EventDelete: + numDelete++ + + case core.EventApply: + numApply++ + } + } + + if numDelete != 0 { + t.Fatalf("expected 0 delete events, got %d", numDelete) + } + + if numApply != 5 { + t.Fatalf("expected 5 apply events, got %d", numApply) + } +} + +func TestGenerateEvents_NonOverlappingListsGenerateDeleteAndApplyEvents(t *testing.T) { + existing := mockGnmicTargetList(5) + + discovered := mockDiscoveredTargetList(10)[5:] + + events := generateEvents(existing, discovered) + + var ( + numDelete int + numApply int + seenApply bool + ) + + for _, event := range events { + switch event.Event { + case core.EventDelete: + if seenApply { + t.Fatalf("expected delete events before apply events") + } + numDelete++ + + case core.EventApply: + seenApply = true + numApply++ + } + } + + if numDelete != 5 { + t.Fatalf("expected 5 delete events, got %d", numDelete) + } + + if numApply != 5 { + t.Fatalf("expected 5 apply events, got %d", numApply) + } +} + +func TestGenerateTargetResource_SetsTargetSourceNameLabel(t *testing.T) { + ts := mockTargetSource() + d := mockDiscoveryTarget() + + target, _ := generateTargetResource(d, &ts) + + if got := target.Labels[LabelTargetSourceName]; got != ts.Name { + t.Fatalf( + "expected %s=%q, got %q", + LabelTargetSourceName, + ts.Name, + got, + ) + } +} + +func TestGenerateTargetResource_CopiesDiscoveredLabels(t *testing.T) { + d := mockDiscoveryTarget( + withDiscoveredTargetLabels(map[string]string{ + "discoveredLabel1": "discoveredValue1", + "discoveredLabel2": "discoveredValue2", + }), + ) + + ts := mockTargetSource() + + target, _ := generateTargetResource(d, &ts) + + tests := map[string]string{ + "discoveredLabel1": "discoveredValue1", + "discoveredLabel2": "discoveredValue2", + } + + for k, want := range tests { + if got := target.Labels[k]; got != want { + t.Fatalf("expected label %s=%q, got %q", k, want, got) + } + } +} + +func TestGenerateTargetResource_CopiesTargetSourceLabels(t *testing.T) { + ts := mockTargetSource( + withTargetSourceTargetLabels(map[string]string{ + "targetSourceLabel1": "targetSourceValue1", + "targetSourceLabel2": "targetSourceValue2", + }), + ) + + d := mockDiscoveryTarget() + + target, _ := generateTargetResource(d, &ts) + + tests := map[string]string{ + "targetSourceLabel1": "targetSourceValue1", + "targetSourceLabel2": "targetSourceValue2", + } + + for k, want := range tests { + if got := target.Labels[k]; got != want { + t.Fatalf("expected label %s=%q, got %q", k, want, got) + } + } +} + +func TestGenerateTargetResource_OverridesReservedTargetSourceNameLabel(t *testing.T) { + ts := mockTargetSource( + withTargetSourceTargetLabels(map[string]string{ + LabelTargetSourceName: "wrong-value", + }), + ) + + d := mockDiscoveryTarget( + withDiscoveredTargetLabels(map[string]string{ + LabelTargetSourceName: "another-wrong-value", + }), + ) + + target, _ := generateTargetResource(d, &ts) + + if got := target.Labels[LabelTargetSourceName]; got != ts.Name { + t.Fatalf( + "expected reserved label %s=%q, got %q", + LabelTargetSourceName, + ts.Name, + got, + ) + } +} + +func TestGenerateTargetResource_TargetSourceLabelsOverrideDiscoveredLabels(t *testing.T) { + ts := mockTargetSource( + withTargetSourceTargetLabels(map[string]string{ + "sharedLabel": "targetSourceValue", + }), + ) + + d := mockDiscoveryTarget( + withDiscoveredTargetLabels(map[string]string{ + "sharedLabel": "discoveredValue", + }), + ) + + target, _ := generateTargetResource(d, &ts) + + if got := target.Labels["sharedLabel"]; got != "targetSourceValue" { + t.Fatalf( + "expected target source label to override discovered label, got %q", + got, + ) + } +} + +func TestNormalizeTarget_PrefixesTargetName(t *testing.T) { + target := mockDiscoveryTarget( + withDiscoveredTargetName("router1"), + ) + + normalized := normalizeTarget(target, "ts1") + + if got := normalized.Name; got != "ts1-router1" { + t.Fatalf( + "expected normalized name %q, got %q", + "ts1-router1", + got, + ) + } +} + +func TestNormalizeTarget_PreservesTargetAddress(t *testing.T) { + target := mockDiscoveryTarget( + withDiscoveredTargetIP("192.168.1.10"), + ) + + normalized := normalizeTarget(target, "ts1") + + if got := normalized.IP; got != "192.168.1.10" { + t.Fatalf( + "expected IP %q, got %q", + "192.168.1.10", + got, + ) + } +} + +func TestNormalizeTarget_PreservesTargetLabels(t *testing.T) { + labels := map[string]string{ + "env": "prod", + "role": "leaf", + } + + target := mockDiscoveryTarget( + withDiscoveredTargetLabels(labels), + ) + + normalized := normalizeTarget(target, "ts1") + + for k, want := range labels { + if got := normalized.Labels[k]; got != want { + t.Fatalf( + "expected label %s=%q, got %q", + k, + want, + got, + ) + } + } +} diff --git a/internal/controller/discovery/message_processor.go b/internal/controller/discovery/message_processor.go index f7aafb1..e202347 100644 --- a/internal/controller/discovery/message_processor.go +++ b/internal/controller/discovery/message_processor.go @@ -30,6 +30,7 @@ type MessageProcessor struct { activeSnapshot *snapshotBuffer // Events are deferred while snapshot is in progress deferredEvents []core.DiscoveryEvent + targetCount int32 } // NewMessageProcessor wires a MessageProcessor instance @@ -53,6 +54,13 @@ func (m *MessageProcessor) Run(ctx context.Context) error { logger.Info("Message processor started") + // Update internal counter in case of a process restart + if existing, err := fetchExistingTargets(ctx, m.client, m.targetSource); err != nil { + logger.Error(err, "error fetching existing targets") + } else { + m.targetCount = int32(len(existing)) + } + for { select { case batch, ok := <-m.in: @@ -90,6 +98,7 @@ func (m *MessageProcessor) Run(ctx context.Context) error { } } +// processMessage handles all of the incoming messages from the channel func (m *MessageProcessor) processMessage(ctx context.Context, message core.DiscoveryMessage, logger logr.Logger) error { if err := ctx.Err(); err != nil { return err @@ -105,6 +114,11 @@ func (m *MessageProcessor) processMessage(ctx context.Context, message core.Disc "chunkIndex", msg.ChunkIndex, "targets", len(msg.Targets), ) + + for i := range msg.Targets { + msg.Targets[i] = normalizeTarget(msg.Targets[i], m.targetSource.Name) + } + return m.processSnapshot(ctx, msg, logger) case core.DiscoveryEvent: @@ -114,6 +128,8 @@ func (m *MessageProcessor) processMessage(ctx context.Context, message core.Disc "event", msg.Event, "target", msg.Target.Name, ) + + msg.Target = normalizeTarget(msg.Target, m.targetSource.Name) return m.processEvent(ctx, msg, logger) default: @@ -204,6 +220,31 @@ func (m *MessageProcessor) collectSnapshot(ctx context.Context, chunk core.Disco return nil } +// processEvent handles a single DiscoveryEvent message. If a snapshot is in the queue, the events get deferred and applied after. +func (m *MessageProcessor) processEvent(ctx context.Context, event core.DiscoveryEvent, logger logr.Logger) error { + // If snapshot collecting is active defer events + if m.activeSnapshot != nil { + m.deferredEvents = append(m.deferredEvents, event) + return nil + } + + // Apply events + err := m.applyEvent(ctx, event, logger) + if err == nil { + switch event.Event { + case core.EventApply: + m.targetCount++ + m.updateStatus(ctx, logger) + case core.EventDelete: + m.targetCount-- + m.updateStatus(ctx, logger) + } + } + + return err +} + +// applySnapshot is in charge of getting the Events for the discovered targets and applying them through applyEvent func (m *MessageProcessor) applySnapshot(ctx context.Context, snapshot *snapshotBuffer, logger logr.Logger) error { select { case <-ctx.Done(): @@ -240,8 +281,37 @@ func (m *MessageProcessor) applySnapshot(ctx context.Context, snapshot *snapshot "targets", len(allTargets), ) - // todo: apply all targets - // a.applyTargets + existing, err := fetchExistingTargets(ctx, m.client, m.targetSource) + if err != nil { + logger.Error(err, "error fetching existing targets") + } else { + logger.Info("fetched existing targets", + "numOfTargets", len(existing), + ) + } + + events := generateEvents(existing, allTargets) + + nApply := 0 + nDelete := 0 + + for _, e := range events { + switch e.Event { + case core.EventApply: + nApply++ + case core.EventDelete: + nDelete++ + } + } + + logger.Info("generated events", + "numOfApply", nApply, + "numOfDelete", nDelete, + ) + + for _, e := range events { + m.applyEvent(ctx, e, logger) + } // Replay deferred events for _, event := range m.deferredEvents { @@ -250,47 +320,68 @@ func (m *MessageProcessor) applySnapshot(ctx context.Context, snapshot *snapshot return nil default: } - if err := m.applyEvent(ctx, event, logger); err != nil { + if err := m.processEvent(ctx, event, logger); err != nil { return err } } + // Because of idempotency, allTargets = desired state = targets existing in Kubernetes. Overwrites the counter to "reset" it. + m.targetCount = int32(len(allTargets)) + m.updateStatus(ctx, logger) + m.resetSnapshot() m.deferredEvents = nil return nil } -func (m *MessageProcessor) processEvent(ctx context.Context, event core.DiscoveryEvent, logger logr.Logger) error { - // If snapshot collecting is active defer events - if m.activeSnapshot != nil { - m.deferredEvents = append(m.deferredEvents, event) - return nil - } - - // Apply events - return m.applyEvent(ctx, event, logger) -} - func (m *MessageProcessor) applyEvent(ctx context.Context, event core.DiscoveryEvent, logger logr.Logger) error { switch event.Event { case core.EventDelete: - logger.Info( - "Deleting Target", - "target", event.Target.Name, - "targetsource", m.targetSource.Name, - ) + if err := deleteTarget(ctx, m.client, event.Target.Name, m.targetSource.Namespace); err != nil { + logger.Error(err, "error deleting target", + "targetName", event.Target.Name, + ) + return err + } else { + logger.Info("deleted target object", + "name", event.Target.Name, + ) + } case core.EventApply: - logger.Info( - "Applying Target", - "target", event.Target.Name, - "address", event.Target.Address, - "labels", event.Target.Labels, - "targetsource", m.targetSource.Name, - ) + target, unknownLabels := generateTargetResource(event.Target, m.targetSource) + for k, v := range unknownLabels { + logger.Info("unknown operator label for target", + "target", event.Target.Name, + "label", k, + "value", v, + ) + } + + if err := applyTarget(ctx, m.client, m.scheme, target, m.targetSource); err != nil { + logger.Error(err, "error applying target", + "targetName", event.Target.Name, + ) + return err + } else { + logger.Info("applied target object", + "name", event.Target.Name, + ) + } } + return nil } +func (m *MessageProcessor) updateStatus(ctx context.Context, logger logr.Logger) { + if err := updateTargetSourceStatus(ctx, m.client, m.targetSource, m.targetCount); err != nil { + logger.Error(err, "error updating TargetSource status") + } else { + logger.Info("updated target source status", + "targetCount", m.targetCount, + ) + } +} + func (m *MessageProcessor) resetSnapshot() { m.activeSnapshot = nil } diff --git a/internal/controller/targetsource_controller.go b/internal/controller/targetsource_controller.go index 522aabd..3becdf4 100644 --- a/internal/controller/targetsource_controller.go +++ b/internal/controller/targetsource_controller.go @@ -23,9 +23,11 @@ import ( "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/types" ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/builder" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" "sigs.k8s.io/controller-runtime/pkg/log" + "sigs.k8s.io/controller-runtime/pkg/predicate" gnmicv1alpha1 "github.com/gnmic/operator/api/v1alpha1" "github.com/gnmic/operator/internal/controller/discovery" @@ -90,11 +92,20 @@ func (r *TargetSourceReconciler) Reconcile(ctx context.Context, req ctrl.Request } if r.DiscoveryRegistry.Exists(req.NamespacedName) { - logger.Info("Discovery runtime already running; reconciliation completed") - return ctrl.Result{}, nil + if targetSource.Generation != targetSource.Status.ObservedGeneration { + return r.reconcileDeletion(ctx, req.NamespacedName, targetSource) + } else { + logger.Info("Discovery runtime already running; reconciliation completed") + return ctrl.Result{}, nil + } + } + + if err := r.startDiscovery(ctx, req.NamespacedName, targetSource, logger); err != nil { + return ctrl.Result{}, err } - if err := r.startDiscovery(req.NamespacedName, targetSource, logger); err != nil { + targetSource.Status.ObservedGeneration = targetSource.Generation + if err := r.Status().Update(ctx, targetSource); err != nil { return ctrl.Result{}, err } @@ -162,6 +173,7 @@ func (r *TargetSourceReconciler) ensureFinalizer(ctx context.Context, targetSour // - MessageProcessor and Loader must run for the lifetime of the TargetSource // - Any unexpected exit is treated as a bug and triggers full shutdown func (r *TargetSourceReconciler) startDiscovery( + reconcileCtx context.Context, key types.NamespacedName, targetSource *gnmicv1alpha1.TargetSource, logger logr.Logger, @@ -185,7 +197,7 @@ func (r *TargetSourceReconciler) startDiscovery( targetSource, targetChannel, ) - loader, err := discovery.NewLoader(&loaderConfig, targetSource.Spec) + loader, err := discovery.NewLoader(reconcileCtx, r.Client, &loaderConfig, targetSource.Spec) if err != nil { logger.Error(err, "Target loader could not be created") cleanup() @@ -217,7 +229,7 @@ func (r *TargetSourceReconciler) startDiscovery( // Start target loader go func() { - if err := loader.Run(ctx, targetChannel); err != nil { + if err := loader.Run(ctx, targetChannel, targetSource.Spec); err != nil { logger.Error(err, "Target loader exited unexpectedly") } else { logger.Error(nil, "Target loader exited unexpectedly without error") @@ -230,7 +242,10 @@ func (r *TargetSourceReconciler) startDiscovery( // SetupWithManager sets up the controller with the Manager. func (r *TargetSourceReconciler) SetupWithManager(mgr ctrl.Manager) error { return ctrl.NewControllerManagedBy(mgr). - For(&gnmicv1alpha1.TargetSource{}). + For( + &gnmicv1alpha1.TargetSource{}, + builder.WithPredicates(predicate.GenerationChangedPredicate{}), + ). Named("targetsource"). Complete(r) } diff --git a/test.mk b/test.mk index 23c5983..fb30c30 100644 --- a/test.mk +++ b/test.mk @@ -153,5 +153,5 @@ apply-test-clusters: ## Apply the test clusters for testing kubectl apply -f test/integration/resources/clusters .PHONY: apply-test-resources -apply-test-resources: apply-test-targets apply-test-subscriptions apply-test-outputs apply-test-pipelines apply-test-clusters +apply-test-resources: apply-test-targets apply-test-subscriptions apply-test-outputs apply-test-pipelines apply-test-clusters apply-test-targetsources diff --git a/test/integration/http/resources/configmap.yaml b/test/integration/http/resources/configmap.yaml index f017566..685c670 100644 --- a/test/integration/http/resources/configmap.yaml +++ b/test/integration/http/resources/configmap.yaml @@ -6,7 +6,8 @@ data: targets.json: | [ { - "address": "clab-t1-spine1:57400", + "ip": "clab-t1-spine1", + "port": 57400, "name": "spine1", "labels": { "vendor": "nokia_srlinux", @@ -14,7 +15,8 @@ data: } }, { - "address": "clab-t1-leaf1:57400", + "ip": "clab-t1-leaf1", + "port": 57400, "name": "leaf1", "labels": { "vendor": "nokia_srlinux", @@ -22,11 +24,12 @@ data: } }, { - "address": "clab-t1-leaf2:57400", + "ip": "clab-t1-leaf2", + "port": 57400, "name": "leaf2", "labels": { "vendor": "nokia_srlinux", "role": "leaf" } } - ] \ No newline at end of file + ]