diff --git a/api/v1alpha1/nats_status.go b/api/v1alpha1/nats_status.go index 6e624396..c28a4d65 100644 --- a/api/v1alpha1/nats_status.go +++ b/api/v1alpha1/nats_status.go @@ -101,3 +101,13 @@ func (ns *NATSStatus) Initialize() { ns.UpdateConditionStatefulSet(metav1.ConditionFalse, ConditionReasonProcessing, "") ns.UpdateConditionAvailable(metav1.ConditionFalse, ConditionReasonProcessing, "") } + +// ClearURL clears the url. +func (ns *NATSStatus) ClearURL() { + ns.URL = "" +} + +// SetURL sets the url. +func (ns *NATSStatus) SetURL(url string) { + ns.URL = url +} diff --git a/api/v1alpha1/nats_status_test.go b/api/v1alpha1/nats_status_test.go index 80c30954..9d28d4a6 100644 --- a/api/v1alpha1/nats_status_test.go +++ b/api/v1alpha1/nats_status_test.go @@ -373,3 +373,42 @@ func Test_Initialize(t *testing.T) { require.Equal(t, expectedAvailableCondition, availableCondition) }) } + +func Test_ClearURL(t *testing.T) { + t.Parallel() + t.Run("should clear the url", func(t *testing.T) { + t.Parallel() + + // given + const givenURL = "some.url" + natsStatus := &NATSStatus{URL: givenURL} + + // when + natsStatus.ClearURL() + + // then + const wantURL = "" + + require.NotEqual(t, wantURL, givenURL) + require.Equal(t, wantURL, natsStatus.URL) + }) +} + +func Test_SetURL(t *testing.T) { + t.Parallel() + t.Run("should set the url", func(t *testing.T) { + t.Parallel() + + // given + const givenURL = "" + natsStatus := &NATSStatus{URL: givenURL} + + // when + const wantURL = "some.url" + natsStatus.SetURL(wantURL) + + // then + require.NotEqual(t, wantURL, givenURL) + require.Equal(t, wantURL, natsStatus.URL) + }) +} diff --git a/api/v1alpha1/nats_types.go b/api/v1alpha1/nats_types.go index 0933e9b4..3d51249c 100644 --- a/api/v1alpha1/nats_types.go +++ b/api/v1alpha1/nats_types.go @@ -90,6 +90,7 @@ type NATS struct { // NATSStatus defines the observed state of NATS. type NATSStatus struct { State string `json:"state"` + URL string `json:"url,omitempty"` Conditions []metav1.Condition `json:"conditions,omitempty"` } diff --git a/config/crd/bases/operator.kyma-project.io_nats.yaml b/config/crd/bases/operator.kyma-project.io_nats.yaml index 4cc06168..c07989d3 100644 --- a/config/crd/bases/operator.kyma-project.io_nats.yaml +++ b/config/crd/bases/operator.kyma-project.io_nats.yaml @@ -305,6 +305,8 @@ spec: type: array state: type: string + url: + type: string required: - state type: object diff --git a/docs/user/02-configuration.md b/docs/user/02-configuration.md index 32de57c1..21b57698 100644 --- a/docs/user/02-configuration.md +++ b/docs/user/02-configuration.md @@ -36,43 +36,40 @@ Use the following sample CRs as guidance. Each can be applied immediately when y **Spec:** -| Parameter | Type | Description | -| ---- | ----------- | ---- | -| **annotations** | map\[string\]string | Annotations allows to add annotations to NATS. | -| **cluster** | object | Cluster defines configurations that are specific to NATS clusters. | -| **cluster.​size** | integer | Size of a NATS cluster, i.e. number of NATS nodes. | -| **jetStream** | object | JetStream defines configurations that are specific to NATS JetStream. | -| **jetStream.​fileStorage** | object | FileStorage defines configurations to file storage in NATS JetStream. | -| **jetStream.​fileStorage.​size** | \{integer or string\} | Size defines the file storage size. | -| **jetStream.​fileStorage.​storageClassName** | string | StorageClassName defines the file storage class name. | -| **jetStream.​memStorage** | object | MemStorage defines configurations to memory storage in NATS JetStream. | -| **jetStream.​memStorage.​enabled** | boolean | Enabled allows the enablement of memory storage. | -| **jetStream.​memStorage.​size** | \{integer or string\} | Size defines the mem. | -| **labels** | map\[string\]string | Labels allows to add Labels to NATS. | -| **logging** | object | JetStream defines configurations that are specific to NATS logging in NATS. | -| **logging.​debug** | boolean | Debug allows debug logging. | -| **logging.​trace** | boolean | Trace allows trace logging. | -| **resources** | object | Resources defines resources for NATS. | -| **resources.​claims** | \[\]object | Claims lists the names of resources, defined in spec.resourceClaims, that are used by this container. - This is an alpha field and requires enabling the DynamicResourceAllocation feature gate. - This field is immutable. It can only be set for containers. | -| **resources.​claims.​name** (required) | string | Name must match the name of one entry in pod.spec.resourceClaims of the Pod where this field is used. It makes that resource available inside a container. | -| **resources.​limits** | map\[string\]\{integer or string\} | Limits describes the maximum amount of compute resources allowed. More info: https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/ | -| **resources.​requests** | map\[string\]\{integer or string\} | Requests describes the minimum amount of compute resources required. If Requests is omitted for a container, it defaults to Limits if that is explicitly specified, otherwise to an implementation-defined value. Requests cannot exceed Limits. More info: https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/ | +| Parameter | Type | Description | +|------------------------------------------------------------|------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| **annotations** | map\[string\]string | Annotations allows to add annotations to NATS. | +| **cluster** | object | Cluster defines configurations that are specific to NATS clusters. | +| **cluster.​size** | integer | Size of a NATS cluster, i.e. number of NATS nodes. | +| **jetStream** | object | JetStream defines configurations that are specific to NATS JetStream. | +| **jetStream.​fileStorage** | object | FileStorage defines configurations to file storage in NATS JetStream. | +| **jetStream.​fileStorage.​size** | \{integer or string\} | Size defines the file storage size. | +| **jetStream.​fileStorage.​storageClassName** | string | StorageClassName defines the file storage class name. | +| **jetStream.​memStorage** | object | MemStorage defines configurations to memory storage in NATS JetStream. | +| **jetStream.​memStorage.​enabled** | boolean | Enabled allows the enablement of memory storage. | +| **jetStream.​memStorage.​size** | \{integer or string\} | Size defines the mem. | +| **labels** | map\[string\]string | Labels allows to add Labels to NATS. | +| **logging** | object | JetStream defines configurations that are specific to NATS logging in NATS. | +| **logging.​debug** | boolean | Debug allows debug logging. | +| **logging.​trace** | boolean | Trace allows trace logging. | +| **resources** | object | Resources defines resources for NATS. | +| **resources.​claims** | \[\]object | Claims lists the names of resources, defined in spec.resourceClaims, that are used by this container. This is an alpha field and requires enabling the DynamicResourceAllocation feature gate. This field is immutable. It can only be set for containers. | +| **resources.​claims.​name** (required) | string | Name must match the name of one entry in pod.spec.resourceClaims of the Pod where this field is used. It makes that resource available inside a container. | +| **resources.​limits** | map\[string\]\{integer or string\} | Limits describes the maximum amount of compute resources allowed. More info: https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/ | +| **resources.​requests** | map\[string\]\{integer or string\} | Requests describes the minimum amount of compute resources required. If Requests is omitted for a container, it defaults to Limits if that is explicitly specified, otherwise to an implementation-defined value. Requests cannot exceed Limits. More info: https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/ | **Status:** -| Parameter | Type | Description | -| ---- | ----------- | ---- | -| **conditions** | \[\]object | Condition contains details for one aspect of the current state of this API Resource. --- This struct is intended for direct use as an array at the field path .status.conditions. For example, - type FooStatus struct{ // Represents the observations of a foo's current state. // Known .status.conditions.type are: "Available", "Progressing", and "Degraded" // +patchMergeKey=type // +patchStrategy=merge // +listType=map // +listMapKey=type Conditions []metav1.Condition `json:"conditions,omitempty" patchStrategy:"merge" patchMergeKey:"type" protobuf:"bytes,1,rep,name=conditions"` - // other fields } | -| **conditions.​lastTransitionTime** (required) | string | lastTransitionTime is the last time the condition transitioned from one status to another. This should be when the underlying condition changed. If that is not known, then using the time when the API field changed is acceptable. | -| **conditions.​message** (required) | string | message is a human readable message indicating details about the transition. This may be an empty string. | -| **conditions.​observedGeneration** | integer | observedGeneration represents the .metadata.generation that the condition was set based upon. For instance, if .metadata.generation is currently 12, but the .status.conditions[x].observedGeneration is 9, the condition is out of date with respect to the current state of the instance. | -| **conditions.​reason** (required) | string | reason contains a programmatic identifier indicating the reason for the condition's last transition. Producers of specific condition types may define expected values and meanings for this field, and whether the values are considered a guaranteed API. The value should be a CamelCase string. This field may not be empty. | -| **conditions.​status** (required) | string | status of the condition, one of True, False, Unknown. | -| **conditions.​type** (required) | string | type of condition in CamelCase or in foo.example.com/CamelCase. --- Many .condition.type values are consistent across resources like Available, but because arbitrary conditions can be useful (see .node.status.conditions), the ability to deconflict is important. The regex it matches is (dns1123SubdomainFmt/)?(qualifiedNameFmt) | -| **state** (required) | string | | +| Parameter | Type | Description | +|------------------------------------------------------|------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| **conditions** | \[\]object | Condition contains details for one aspect of the current state of this API Resource. --- This struct is intended for direct use as an array at the field path .status.conditions. For example, type FooStatus struct{ // Represents the observations of a foo's current state. // Known .status.conditions.type are: "Available", "Progressing", and "Degraded" // +patchMergeKey=type // +patchStrategy=merge // +listType=map // +listMapKey=type Conditions []metav1.Condition `json:"conditions,omitempty" patchStrategy:"merge" patchMergeKey:"type" protobuf:"bytes,1,rep,name=conditions"` // other fields } | +| **conditions.​lastTransitionTime** (required) | string | lastTransitionTime is the last time the condition transitioned from one status to another. This should be when the underlying condition changed. If that is not known, then using the time when the API field changed is acceptable. | +| **conditions.​message** (required) | string | message is a human readable message indicating details about the transition. This may be an empty string. | +| **conditions.​observedGeneration** | integer | observedGeneration represents the .metadata.generation that the condition was set based upon. For instance, if .metadata.generation is currently 12, but the .status.conditions[x].observedGeneration is 9, the condition is out of date with respect to the current state of the instance. | +| **conditions.​reason** (required) | string | reason contains a programmatic identifier indicating the reason for the condition's last transition. Producers of specific condition types may define expected values and meanings for this field, and whether the values are considered a guaranteed API. The value should be a CamelCase string. This field may not be empty. | +| **conditions.​status** (required) | string | status of the condition, one of True, False, Unknown. | +| **conditions.​type** (required) | string | type of condition in CamelCase or in foo.example.com/CamelCase. --- Many .condition.type values are consistent across resources like Available, but because arbitrary conditions can be useful (see .node.status.conditions), the ability to deconflict is important. The regex it matches is (dns1123SubdomainFmt/)?(qualifiedNameFmt) | +| **state** (required) | string | | +| **url** | string | | diff --git a/internal/controller/nats/deprovisioner.go b/internal/controller/nats/deprovisioner.go index e96a9ca6..84d25e2d 100644 --- a/internal/controller/nats/deprovisioner.go +++ b/internal/controller/nats/deprovisioner.go @@ -4,20 +4,20 @@ import ( "context" "fmt" - "github.com/kyma-project/nats-manager/pkg/events" - - natsv1alpha1 "github.com/kyma-project/nats-manager/api/v1alpha1" - natspkg "github.com/kyma-project/nats-manager/pkg/nats" "go.uber.org/zap" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" + + natsv1alpha1 "github.com/kyma-project/nats-manager/api/v1alpha1" + natsurl "github.com/kyma-project/nats-manager/internal/controller/nats/url" + "github.com/kyma-project/nats-manager/pkg/events" + natspkg "github.com/kyma-project/nats-manager/pkg/nats" ) const ( StreamExistsErrorMsg = "Cannot delete NATS cluster as customer stream exists" ConsumerExistsErrorMsg = "Cannot delete NATS cluster as stream consumer exists" - natsClientPort = 4222 InstanceLabelKey = "app.kubernetes.io/instance" SapStreamName = "sap" ) @@ -109,7 +109,7 @@ func (r *Reconciler) createAndConnectNatsClient(nats *natsv1alpha1.NATS) error { // create a new instance if it does not exist. if r.getNatsClient(nats) == nil { r.setNatsClient(nats, natspkg.NewNatsClient(&natspkg.Config{ - URL: fmt.Sprintf("nats://%s.%s.svc.cluster.local:%d", nats.Name, nats.Namespace, natsClientPort), + URL: natsurl.Format(nats.Name, nats.Namespace), })) } return r.getNatsClient(nats).Init() diff --git a/internal/controller/nats/integrationtests/controller/integration_test.go b/internal/controller/nats/integrationtests/controller/integration_test.go index d7755efe..68b19841 100644 --- a/internal/controller/nats/integrationtests/controller/integration_test.go +++ b/internal/controller/nats/integrationtests/controller/integration_test.go @@ -182,6 +182,23 @@ func Test_CreateNATSCR(t *testing.T) { testEnvironment.EnsureNATSSpecMemStorageReflected(t, *tc.givenNATS) testEnvironment.EnsureNATSSpecFileStorageReflected(t, *tc.givenNATS) } + + // check url in the NATS CR status + natsCR, err := testEnvironment.GetNATSFromK8s(tc.givenNATS.Name, givenNamespace) + require.NoError(t, err) + require.NotNil(t, natsCR) + switch natsCR.Status.State { + case v1alpha1.StateReady: + { + wantURL := fmt.Sprintf("nats://%s.%s.svc.cluster.local:4222", natsCR.Name, natsCR.Namespace) + require.Equal(t, wantURL, natsCR.Status.URL) + } + default: + { + const wantURL = "" + require.Equal(t, wantURL, natsCR.Status.URL) + } + } }) } } @@ -264,6 +281,23 @@ func Test_UpdateNATSCR(t *testing.T) { testEnvironment.EnsureK8sStatefulSetHasAnnotations(t, testutils.GetStatefulSetName(*tc.givenNATS), givenNamespace, tc.givenUpdateNATS.Spec.Annotations) testEnvironment.EnsureNATSSpecMemStorageReflected(t, *tc.givenUpdateNATS) + + // check url in the NATS CR status + natsCR, err := testEnvironment.GetNATSFromK8s(tc.givenNATS.Name, givenNamespace) + require.NoError(t, err) + require.NotNil(t, natsCR) + switch natsCR.Status.State { + case v1alpha1.StateReady: + { + wantURL := fmt.Sprintf("nats://%s.%s.svc.cluster.local:4222", natsCR.Name, natsCR.Namespace) + require.Equal(t, wantURL, natsCR.Status.URL) + } + default: + { + const wantURL = "" + require.Equal(t, wantURL, natsCR.Status.URL) + } + } }) } } @@ -590,6 +624,23 @@ func Test_DoubleReconcileNATSCR(t *testing.T) { // check NATS CR status again. testEnvironment.GetNATSAssert(g, tc.givenNATS).Should(tc.wantMatchers) + + // check url in the NATS CR status + natsCR, err := testEnvironment.GetNATSFromK8s(tc.givenNATS.Name, givenNamespace) + require.NoError(t, err) + require.NotNil(t, natsCR) + switch natsCR.Status.State { + case v1alpha1.StateReady: + { + wantURL := fmt.Sprintf("nats://%s.%s.svc.cluster.local:4222", natsCR.Name, natsCR.Namespace) + require.Equal(t, wantURL, natsCR.Status.URL) + } + default: + { + const wantURL = "" + require.Equal(t, wantURL, natsCR.Status.URL) + } + } }) } } diff --git a/internal/controller/nats/provisioner.go b/internal/controller/nats/provisioner.go index ed45c393..d2e20c8f 100644 --- a/internal/controller/nats/provisioner.go +++ b/internal/controller/nats/provisioner.go @@ -4,13 +4,14 @@ import ( "context" "time" - "github.com/kyma-project/nats-manager/pkg/events" - - natsv1alpha1 "github.com/kyma-project/nats-manager/api/v1alpha1" - "github.com/kyma-project/nats-manager/pkg/k8s/chart" "go.uber.org/zap" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ctrl "sigs.k8s.io/controller-runtime" + + natsv1alpha1 "github.com/kyma-project/nats-manager/api/v1alpha1" + natsurl "github.com/kyma-project/nats-manager/internal/controller/nats/url" + "github.com/kyma-project/nats-manager/pkg/events" + "github.com/kyma-project/nats-manager/pkg/k8s/chart" ) const RequeueTimeForStatusCheck = 10 @@ -66,6 +67,9 @@ func (r *Reconciler) handleNATSReconcile(ctx context.Context, // It also syncs the NATS CR status. func (r *Reconciler) handleNATSState(ctx context.Context, nats *natsv1alpha1.NATS, instance *chart.ReleaseInstance, log *zap.SugaredLogger) (ctrl.Result, error) { + // Clear the url until the StatefulSet is ready. + nats.Status.ClearURL() + // checking if statefulSet is ready. isSTSReady, err := r.natsManager.IsNATSStatefulSetReady(ctx, instance) if err != nil { @@ -78,6 +82,7 @@ func (r *Reconciler) handleNATSState(ctx context.Context, nats *natsv1alpha1.NAT if isSTSReady { nats.Status.SetStateReady() + nats.Status.SetURL(natsurl.Format(nats.Name, nats.Namespace)) events.Normal(r.recorder, nats, natsv1alpha1.ConditionReasonDeployed, "StatefulSet is ready and NATS is deployed.") } else { nats.Status.SetWaitingStateForStatefulSet() diff --git a/internal/controller/nats/url/url.go b/internal/controller/nats/url/url.go new file mode 100644 index 00000000..f0592e4e --- /dev/null +++ b/internal/controller/nats/url/url.go @@ -0,0 +1,15 @@ +package url + +import ( + "fmt" +) + +const ( + format = "%s://%s.%s.svc.cluster.local:%d" + protocol = "nats" + port = 4222 +) + +func Format(name, namespace string) string { + return fmt.Sprintf(format, protocol, name, namespace, port) +} diff --git a/internal/controller/nats/url/url_test.go b/internal/controller/nats/url/url_test.go new file mode 100644 index 00000000..2bfaec36 --- /dev/null +++ b/internal/controller/nats/url/url_test.go @@ -0,0 +1,38 @@ +package url + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +func TestFormat(t *testing.T) { + // given + type args struct { + name string + namespace string + } + tests := []struct { + name string + args args + want string + }{ + { + name: "should return the correct nats url", + args: args{ + name: "test-name", + namespace: "test-namespace", + }, + want: "nats://test-name.test-namespace.svc.cluster.local:4222", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + // when + got := Format(tt.args.name, tt.args.namespace) + + // then + require.Equal(t, tt.want, got) + }) + } +}