From bb40bb880b2269a96b6c5b04fe831d6b1ecd86df Mon Sep 17 00:00:00 2001 From: Michael Nairn Date: Mon, 23 Oct 2023 09:44:23 +0100 Subject: [PATCH] feat: DNSProvider secret ref in DNSPolicy Removes the requirement for a ManagedZone to be configured for a host in order for the DNSPolicy to create dns records for it. Make DNSRecord.zoneID optional Set specific allowed values for providerRef.Kind Allow a providerRef.Kind of ManagedZone that looks up zones from Managedzones in the current ns (Current behaviour) and loads dns client through the managed zone providerRef. Add logic around zoneAssignment in dnsPolicy, some providerRef.kinds will result in zoneAssignment being false which indicates that a zone is not going to be looked up or assigned to any created DNSRecords. A DNSRecord will be created for all listeners in this case. Created a v1alpha2 API for DNSPolicy, ManagedZone and DNSRecord. v1alpha1 versions are removed and no longer supported. E2E Test Updates * DO NOT MERGE Add 406_dnspolicy_provider_ref branch for testing * Add e2e test for dnspolicy focused on istio gateways and providers * Add suite id and generate a testDomainName to use for all tests in that instance of the suite (Avoids thigns like wildcard hosts being created that coudl affect all instances of a suite running in teh same hosted zone) * Removed all references to managed zones as input to the e2e test suite. Env vars required now are TEST_DNS_ZONE_DOMAIN_NAME, TEST_DNS_ZONE_ID and TEST_DNS_PROVIDER_SECRET_NAME. ManagedZone updates * Make description optional * fix managedZoneListToZoneList - use range index * Make ID and description pointers * Remove hostedzone prefix from AWS hosted zones * Use status id in managedZoneListToZoneList --- .github/workflows/ci-e2e.yaml | 50 +- bundle/manifests/kuadrant.io_dnspolicies.yaml | 17 +- bundle/manifests/kuadrant.io_dnsrecords.yaml | 17 +- .../manifests/kuadrant.io_managedzones.yaml | 26 +- ...eway-controller.clusterserviceversion.yaml | 12 +- cmd/policy_controller/main.go | 2 + .../controller/aws/managed_zone.yaml | 4 +- .../controller/gcp/managed_zone.yaml | 4 +- .../crd/bases/kuadrant.io_dnspolicies.yaml | 17 +- .../crd/bases/kuadrant.io_dnsrecords.yaml | 17 +- .../crd/bases/kuadrant.io_managedzones.yaml | 26 +- config/samples/dnspolicy.yaml | 2 +- .../kuadrant.io_v1alpha1_dnsrecord-ns.yaml | 22 - .../kuadrant.io_v1alpha1_dnsrecord.yaml | 20 - .../kuadrant.io_v1alpha1_managedzone.yaml | 11 +- ...> kuadrant.io_v1alpha2_dnsrecord-geo.yaml} | 13 +- .../kuadrant.io_v1alpha2_dnsrecord-ns.yaml | 17 + .../kuadrant.io_v1alpha2_dnsrecord.yaml | 15 + hack/.deployUtils | 8 +- pkg/_internal/conditions/conditions_test.go | 6 +- pkg/_internal/policy/policy_test.go | 10 +- pkg/apis/v1alpha1/zz_generated.deepcopy.go | 696 ----------------- .../{v1alpha1 => v1alpha2}/dnspolicy_types.go | 29 +- .../{v1alpha1 => v1alpha2}/dnsrecord_types.go | 16 +- pkg/apis/v1alpha2/groupversion_info.go | 36 + .../managedzone_types.go | 26 +- pkg/apis/v1alpha2/shared_types.go | 39 + pkg/apis/v1alpha2/zz_generated.deepcopy.go | 708 ++++++++++++++++++ .../dnshealthcheckprobe_controller.go | 5 +- pkg/controllers/dnspolicy/dns_helper.go | 109 ++- pkg/controllers/dnspolicy/dns_helper_test.go | 331 ++++---- .../dnspolicy/dnspolicy_controller.go | 13 +- .../dnspolicy/dnspolicy_dnsrecords.go | 88 ++- .../dnspolicy/dnspolicy_healthchecks.go | 11 +- .../dnspolicy/dnspolicy_healthchecks_test.go | 47 +- .../dnsrecord/dnsrecord_controller.go | 72 +- .../managedzone/managedzone_controller.go | 46 +- pkg/dns/aws/dns.go | 143 +++- pkg/dns/aws/health.go | 16 +- pkg/dns/aws/health_test.go | 40 +- pkg/dns/dns.go | 62 +- pkg/dns/dnsprovider/dnsProvider.go | 55 +- pkg/dns/filters.go | 71 ++ pkg/dns/google/google.go | 98 ++- pkg/dns/google/google_test.go | 56 +- pkg/dns/health.go | 16 +- pkg/dns/target.go | 13 +- pkg/dns/target_test.go | 51 +- pkg/policysync/policy_test.go | 6 +- .../dnspolicy_providers_istio_gateway_test.go | 394 ++++++++++ test/e2e/gateway_single_spoke_test.go | 16 +- test/e2e/suite_test.go | 8 + test/gateway_integration/suite_test.go | 20 +- ...dnspolicy_controller_health_checks_test.go | 62 +- ...dnspolicy_controller_multi_cluster_test.go | 130 ++-- ...nspolicy_controller_single_cluster_test.go | 66 +- .../dnspolicy_controller_test.go | 35 +- .../managedzone_controller_test.go | 23 +- test/policy_integration/suite_test.go | 6 +- test/util/helper.go | 2 + test/util/suite_config.go | 5 + test/util/test_dnspolicy_types.go | 113 ++- 62 files changed, 2490 insertions(+), 1605 deletions(-) delete mode 100644 config/samples/kuadrant.io_v1alpha1_dnsrecord-ns.yaml delete mode 100644 config/samples/kuadrant.io_v1alpha1_dnsrecord.yaml rename config/samples/{kuadrant.io_v1alpha1_dnsrecord-geo.yaml => kuadrant.io_v1alpha2_dnsrecord-geo.yaml} (77%) create mode 100644 config/samples/kuadrant.io_v1alpha2_dnsrecord-ns.yaml create mode 100644 config/samples/kuadrant.io_v1alpha2_dnsrecord.yaml rename pkg/apis/{v1alpha1 => v1alpha2}/dnspolicy_types.go (87%) rename pkg/apis/{v1alpha1 => v1alpha2}/dnsrecord_types.go (97%) create mode 100644 pkg/apis/v1alpha2/groupversion_info.go rename pkg/apis/{v1alpha1 => v1alpha2}/managedzone_types.go (91%) create mode 100644 pkg/apis/v1alpha2/shared_types.go create mode 100644 pkg/apis/v1alpha2/zz_generated.deepcopy.go create mode 100644 pkg/dns/filters.go create mode 100644 test/e2e/dnspolicy_providers_istio_gateway_test.go diff --git a/.github/workflows/ci-e2e.yaml b/.github/workflows/ci-e2e.yaml index 5656212a7..c1a392e3c 100644 --- a/.github/workflows/ci-e2e.yaml +++ b/.github/workflows/ci-e2e.yaml @@ -5,6 +5,7 @@ on: branches: - main - "release-*" + - 406_dnspolicy_provider_ref tags: - "v[0-9]+.[0-9]+.[0-9]+" paths-ignore: @@ -43,24 +44,6 @@ jobs: - uses: actions/setup-go@v4 with: go-version: "1.21.x" - - name: Create controller-config.env - run: | - echo "AWS_DNS_PUBLIC_ZONE_ID=${{ secrets.E2E_AWS_DNS_PUBLIC_ZONE_ID }}" >> controller-config.env - echo "ZONE_ROOT_DOMAIN=${{ secrets.E2E_AWS_DNS_PUBLIC_ZONE_NAME }}" >> controller-config.env - echo "ZONE_NAME=${{ secrets.E2E_GCP_ZONE_NAME }}" >> controller-config.env - echo "ZONE_DNS_NAME=${{ secrets.E2E_GCP_ZONE_DNS_NAME }}" >> controller-config.env - - - name: Create aws-credentials.env - run: | - echo "AWS_ACCESS_KEY_ID=${{ secrets.E2E_AWS_ACCESS_KEY_ID }}" >> aws-credentials.env - echo "AWS_SECRET_ACCESS_KEY=${{ secrets.E2E_AWS_SECRET_ACCESS_KEY }}" >> aws-credentials.env - echo "AWS_REGION=${{ env.AWS_REGION }}" >> aws-credentials.env - - name: Create gcp-credentials.env - run: | - secret="${{ secrets.E2E_GOOGLE }}" - decoded=$(echo "$secret" | base64 --decode ) - echo "GOOGLE=$decoded" >> gcp-credentials.env - echo "PROJECT_ID=${{ secrets.E2E_PROJECT_ID }}" >> gcp-credentials.env - name: Setup environment run: | export OCM_SINGLE=1 @@ -74,31 +57,42 @@ jobs: kubectl --context kind-mgc-control-plane -n multicluster-gateway-controller-system wait --timeout=300s --for=condition=Available deployment/mgc-policy-controller kubectl --context kind-mgc-control-plane logs --all-containers --ignore-errors deployment/mgc-controller-manager -n multicluster-gateway-controller-system kubectl --context kind-mgc-control-plane logs --all-containers --ignore-errors deployment/mgc-policy-controller -n multicluster-gateway-controller-system - kubectl get managedzones -n multi-cluster-gateways mgc-dev-mz-aws -o yaml - kubectl --context kind-mgc-control-plane -n multi-cluster-gateways wait --timeout=60s --for=condition=Ready managedzone/mgc-dev-mz-aws - kubectl get managedzones -n multi-cluster-gateways mgc-dev-mz-gcp -o yaml - kubectl --context kind-mgc-control-plane -n multi-cluster-gateways wait --timeout=60s --for=condition=Ready managedzone/mgc-dev-mz-gcp + - name: Create AWS provider secret + run: | + echo "{\"zoneIDFilter\": [], \"domainFilter\": [\"e2e.hcpapps.net\"]}" > e2e-test-aws-provider-config.json + kubectl create secret generic e2e-test-aws-credentials -n multi-cluster-gateways \ + --type=kuadrant.io/aws \ + --from-literal=AWS_ACCESS_KEY_ID=${{ secrets.E2E_AWS_ACCESS_KEY_ID }} \ + --from-literal=AWS_SECRET_ACCESS_KEY=${{ secrets.E2E_AWS_SECRET_ACCESS_KEY }} \ + --from-file=CONFIG=e2e-test-aws-provider-config.json + - name: Create GCP provider secret + run: | + secret="${{ secrets.E2E_GOOGLE }}" + decoded=$(echo "$secret" | base64 --decode ) + echo "$decoded" >> gcp_credentials.json + echo "{\"zoneIDFilter\": [], \"domainFilter\": [\"e2e.google.hcpapps.net\"]}" > e2e-test-gcp-provider-config.json + kubectl create secret generic e2e-test-gcp-credentials -n multi-cluster-gateways \ + --type=kuadrant.io/gcp \ + --from-literal=PROJECT_ID=${{ secrets.E2E_PROJECT_ID }} \ + --from-file=GOOGLE=gcp_credentials.json \ + --from-file=CONFIG=e2e-test-gcp-provider-config.json - name: Run suite AWS run: | export OCM_SINGLE=1 export TEST_HUB_NAMESPACE=multi-cluster-gateways export TEST_HUB_KUBE_CONTEXT=kind-mgc-control-plane - export TEST_DNS_PROVIDER_SECRET_NAME=mgc-aws-credentials + export TEST_DNS_PROVIDER_SECRET_NAME=e2e-test-aws-credentials export TEST_DNS_ZONE_DOMAIN_NAME=e2e.hcpapps.net export TEST_DNS_ZONE_ID=Z086929132US3PB46EOLR - export TEST_MANAGED_ZONE=${{ secrets.E2E_AWS_DNS_PUBLIC_ZONE_NAME }} - export TEST_MANAGED_ZONE_NAME=mgc-dev-mz-aws make test-e2e - name: Run suite GCP run: | export OCM_SINGLE=1 export TEST_HUB_NAMESPACE=multi-cluster-gateways export TEST_HUB_KUBE_CONTEXT=kind-mgc-control-plane - export TEST_DNS_PROVIDER_SECRET_NAME=mgc-gcp-credentials + export TEST_DNS_PROVIDER_SECRET_NAME=e2e-test-gcp-credentials export TEST_DNS_ZONE_DOMAIN_NAME=e2e.google.hcpapps.net export TEST_DNS_ZONE_ID=e2e-google-hcpapps-net - export TEST_MANAGED_ZONE=${{ secrets.E2E_GCP_ZONE_DNS_NAME }} - export TEST_MANAGED_ZONE_NAME=mgc-dev-mz-gcp make test-e2e - name: Dump Gateway Controller logs if: ${{ failure() }} diff --git a/bundle/manifests/kuadrant.io_dnspolicies.yaml b/bundle/manifests/kuadrant.io_dnspolicies.yaml index c971d8477..71b80e2f3 100644 --- a/bundle/manifests/kuadrant.io_dnspolicies.yaml +++ b/bundle/manifests/kuadrant.io_dnspolicies.yaml @@ -21,7 +21,7 @@ spec: jsonPath: .status.conditions[?(@.type=="Ready")].status name: Ready type: string - name: v1alpha1 + name: v1alpha2 schema: openAPIV3Schema: description: DNSPolicy is the Schema for the dnspolicies API @@ -156,6 +156,20 @@ spec: type: integer type: object type: object + providerRef: + properties: + kind: + enum: + - None + - Secret + - ManagedZone + type: string + name: + type: string + required: + - kind + - name + type: object routingStrategy: default: loadbalanced enum: @@ -201,6 +215,7 @@ spec: - name type: object required: + - providerRef - routingStrategy - targetRef type: object diff --git a/bundle/manifests/kuadrant.io_dnsrecords.yaml b/bundle/manifests/kuadrant.io_dnsrecords.yaml index 59c146a08..cb036a085 100644 --- a/bundle/manifests/kuadrant.io_dnsrecords.yaml +++ b/bundle/manifests/kuadrant.io_dnsrecords.yaml @@ -19,7 +19,7 @@ spec: jsonPath: .status.conditions[?(@.type=="Ready")].status name: Ready type: string - name: v1alpha1 + name: v1alpha2 schema: openAPIV3Schema: description: DNSRecord is the Schema for the dnsrecords API @@ -85,15 +85,24 @@ spec: type: object minItems: 1 type: array - managedZone: - description: ManagedZoneReference holds a reference to a ManagedZone + providerRef: properties: + kind: + enum: + - None + - Secret + - ManagedZone + type: string name: - description: '`name` is the name of the managed zone. Required' type: string required: + - kind - name type: object + zoneID: + type: string + required: + - providerRef type: object status: description: DNSRecordStatus defines the observed state of DNSRecord diff --git a/bundle/manifests/kuadrant.io_managedzones.yaml b/bundle/manifests/kuadrant.io_managedzones.yaml index b9d9fd74a..74e102b95 100644 --- a/bundle/manifests/kuadrant.io_managedzones.yaml +++ b/bundle/manifests/kuadrant.io_managedzones.yaml @@ -35,7 +35,7 @@ spec: jsonPath: .status.conditions[?(@.type=="Ready")].status name: Ready type: string - name: v1alpha1 + name: v1alpha2 schema: openAPIV3Schema: description: ManagedZone is the Schema for the managedzones API @@ -58,13 +58,6 @@ spec: description: description: Description for this ManagedZone type: string - dnsProviderSecretRef: - properties: - name: - type: string - required: - - name - type: object domainName: description: Domain name of this ManagedZone pattern: ^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$ @@ -82,10 +75,23 @@ spec: required: - name type: object + providerRef: + properties: + kind: + enum: + - None + - Secret + - ManagedZone + type: string + name: + type: string + required: + - kind + - name + type: object required: - - description - - dnsProviderSecretRef - domainName + - providerRef type: object status: description: ManagedZoneStatus defines the observed state of a Zone diff --git a/bundle/manifests/multicluster-gateway-controller.clusterserviceversion.yaml b/bundle/manifests/multicluster-gateway-controller.clusterserviceversion.yaml index 37cb742a8..63efb780b 100644 --- a/bundle/manifests/multicluster-gateway-controller.clusterserviceversion.yaml +++ b/bundle/manifests/multicluster-gateway-controller.clusterserviceversion.yaml @@ -4,7 +4,7 @@ metadata: annotations: alm-examples: '[]' capabilities: Basic Install - createdAt: "2023-12-21T13:08:31Z" + createdAt: "2023-12-04T11:02:57Z" operators.operatorframework.io/builder: operator-sdk-v1.28.0 operators.operatorframework.io/project_layout: go.kubebuilder.io/v3 name: multicluster-gateway-controller.v0.0.0 @@ -18,15 +18,13 @@ spec: version: v1alpha1 - kind: DNSPolicy name: dnspolicies.kuadrant.io - version: v1alpha1 + version: v1alpha2 - kind: DNSRecord name: dnsrecords.kuadrant.io - version: v1alpha1 - - description: ManagedZone is the Schema for the managedzones API - displayName: Managed Zone - kind: ManagedZone + version: v1alpha2 + - kind: ManagedZone name: managedzones.kuadrant.io - version: v1alpha1 + version: v1alpha2 - kind: TLSPolicy name: tlspolicies.kuadrant.io version: v1alpha1 diff --git a/cmd/policy_controller/main.go b/cmd/policy_controller/main.go index 2cc81ce0f..7f99d06ed 100644 --- a/cmd/policy_controller/main.go +++ b/cmd/policy_controller/main.go @@ -38,6 +38,7 @@ import ( "github.com/kuadrant/kuadrant-operator/pkg/reconcilers" "github.com/Kuadrant/multicluster-gateway-controller/pkg/apis/v1alpha1" + "github.com/Kuadrant/multicluster-gateway-controller/pkg/apis/v1alpha2" "github.com/Kuadrant/multicluster-gateway-controller/pkg/controllers/dnshealthcheckprobe" "github.com/Kuadrant/multicluster-gateway-controller/pkg/controllers/dnspolicy" "github.com/Kuadrant/multicluster-gateway-controller/pkg/controllers/dnsrecord" @@ -55,6 +56,7 @@ func init() { utilruntime.Must(clientgoscheme.AddToScheme(scheme.Scheme)) utilruntime.Must(gatewayapiv1.AddToScheme(scheme.Scheme)) utilruntime.Must(v1alpha1.AddToScheme(scheme.Scheme)) + utilruntime.Must(v1alpha2.AddToScheme(scheme.Scheme)) utilruntime.Must(certmanv1.AddToScheme(scheme.Scheme)) //this is need for now but will be removed soon utilruntime.Must(clusterv1.AddToScheme(scheme.Scheme)) diff --git a/config/local-setup/controller/aws/managed_zone.yaml b/config/local-setup/controller/aws/managed_zone.yaml index 6e7e3be28..4e8608ac3 100644 --- a/config/local-setup/controller/aws/managed_zone.yaml +++ b/config/local-setup/controller/aws/managed_zone.yaml @@ -1,4 +1,4 @@ -apiVersion: kuadrant.io/v1alpha1 +apiVersion: kuadrant.io/v1alpha2 kind: ManagedZone metadata: name: dev-mz-aws @@ -6,5 +6,5 @@ spec: id: DUMMY_ID domainName: DUMMY_DOMAIN_NAME description: "Dev Managed Zone" - dnsProviderSecretRef: + providerRef: name: mgc-aws-credentials diff --git a/config/local-setup/controller/gcp/managed_zone.yaml b/config/local-setup/controller/gcp/managed_zone.yaml index d67f57715..6ddee876b 100644 --- a/config/local-setup/controller/gcp/managed_zone.yaml +++ b/config/local-setup/controller/gcp/managed_zone.yaml @@ -1,4 +1,4 @@ -apiVersion: kuadrant.io/v1alpha1 +apiVersion: kuadrant.io/v1alpha2 kind: ManagedZone metadata: name: dev-mz-gcp @@ -6,5 +6,5 @@ spec: id: DUMMY_ID domainName: DUMMY_DOMAIN_NAME description: "Dev Managed Zone" - dnsProviderSecretRef: + providerRef: name: mgc-gcp-credentials diff --git a/config/policy-controller/crd/bases/kuadrant.io_dnspolicies.yaml b/config/policy-controller/crd/bases/kuadrant.io_dnspolicies.yaml index 44486d0f9..b865b4664 100644 --- a/config/policy-controller/crd/bases/kuadrant.io_dnspolicies.yaml +++ b/config/policy-controller/crd/bases/kuadrant.io_dnspolicies.yaml @@ -20,7 +20,7 @@ spec: jsonPath: .status.conditions[?(@.type=="Ready")].status name: Ready type: string - name: v1alpha1 + name: v1alpha2 schema: openAPIV3Schema: description: DNSPolicy is the Schema for the dnspolicies API @@ -155,6 +155,20 @@ spec: type: integer type: object type: object + providerRef: + properties: + kind: + enum: + - None + - Secret + - ManagedZone + type: string + name: + type: string + required: + - kind + - name + type: object routingStrategy: default: loadbalanced enum: @@ -200,6 +214,7 @@ spec: - name type: object required: + - providerRef - routingStrategy - targetRef type: object diff --git a/config/policy-controller/crd/bases/kuadrant.io_dnsrecords.yaml b/config/policy-controller/crd/bases/kuadrant.io_dnsrecords.yaml index b75091f0b..e49cdeaef 100644 --- a/config/policy-controller/crd/bases/kuadrant.io_dnsrecords.yaml +++ b/config/policy-controller/crd/bases/kuadrant.io_dnsrecords.yaml @@ -20,7 +20,7 @@ spec: jsonPath: .status.conditions[?(@.type=="Ready")].status name: Ready type: string - name: v1alpha1 + name: v1alpha2 schema: openAPIV3Schema: description: DNSRecord is the Schema for the dnsrecords API @@ -86,15 +86,24 @@ spec: type: object minItems: 1 type: array - managedZone: - description: ManagedZoneReference holds a reference to a ManagedZone + providerRef: properties: + kind: + enum: + - None + - Secret + - ManagedZone + type: string name: - description: '`name` is the name of the managed zone. Required' type: string required: + - kind - name type: object + zoneID: + type: string + required: + - providerRef type: object status: description: DNSRecordStatus defines the observed state of DNSRecord diff --git a/config/policy-controller/crd/bases/kuadrant.io_managedzones.yaml b/config/policy-controller/crd/bases/kuadrant.io_managedzones.yaml index d96bbb44d..e69a37179 100644 --- a/config/policy-controller/crd/bases/kuadrant.io_managedzones.yaml +++ b/config/policy-controller/crd/bases/kuadrant.io_managedzones.yaml @@ -36,7 +36,7 @@ spec: jsonPath: .status.conditions[?(@.type=="Ready")].status name: Ready type: string - name: v1alpha1 + name: v1alpha2 schema: openAPIV3Schema: description: ManagedZone is the Schema for the managedzones API @@ -59,13 +59,6 @@ spec: description: description: Description for this ManagedZone type: string - dnsProviderSecretRef: - properties: - name: - type: string - required: - - name - type: object domainName: description: Domain name of this ManagedZone pattern: ^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$ @@ -83,10 +76,23 @@ spec: required: - name type: object + providerRef: + properties: + kind: + enum: + - None + - Secret + - ManagedZone + type: string + name: + type: string + required: + - kind + - name + type: object required: - - description - - dnsProviderSecretRef - domainName + - providerRef type: object status: description: ManagedZoneStatus defines the observed state of a Zone diff --git a/config/samples/dnspolicy.yaml b/config/samples/dnspolicy.yaml index dbd506ddc..9919c9da9 100644 --- a/config/samples/dnspolicy.yaml +++ b/config/samples/dnspolicy.yaml @@ -1,4 +1,4 @@ -apiVersion: kuadrant.io/v1alpha1 +apiVersion: kuadrant.io/v1alpha2 kind: DNSPolicy metadata: name: example-dnspolicy diff --git a/config/samples/kuadrant.io_v1alpha1_dnsrecord-ns.yaml b/config/samples/kuadrant.io_v1alpha1_dnsrecord-ns.yaml deleted file mode 100644 index 8ffe83b48..000000000 --- a/config/samples/kuadrant.io_v1alpha1_dnsrecord-ns.yaml +++ /dev/null @@ -1,22 +0,0 @@ -apiVersion: kuadrant.io/v1alpha1 -kind: DNSRecord -metadata: - labels: - app.kubernetes.io/name: dnsrecord-ns - app.kubernetes.io/instance: dnsrecord-sample - app.kubernetes.io/part-of: multicluster-gateway-controller - app.kubernetes.io/managed-by: kustomize - app.kubernetes.io/created-by: multicluster-gateway-controller - name: dnsrecord-ns -spec: - managedZone: - name: mgc-dev-mz - endpoints: - - dnsName: testns.hcpapps.net - recordTTL: 172800 - recordType: NS - targets: - - ns-59.awsdns-07.com - - ns-59.awsdns-07.com - - ns-910.awsdns-49.net - - ns-1440.awsdns-52.org diff --git a/config/samples/kuadrant.io_v1alpha1_dnsrecord.yaml b/config/samples/kuadrant.io_v1alpha1_dnsrecord.yaml deleted file mode 100644 index bdc0fd231..000000000 --- a/config/samples/kuadrant.io_v1alpha1_dnsrecord.yaml +++ /dev/null @@ -1,20 +0,0 @@ -apiVersion: kuadrant.io/v1alpha1 -kind: DNSRecord -metadata: - labels: - app.kubernetes.io/name: dnsrecord - app.kubernetes.io/instance: dnsrecord-sample - app.kubernetes.io/part-of: multicluster-gateway-controller - app.kubernetes.io/managed-by: kustomize - app.kubernetes.io/created-by: multicluster-gateway-controller - name: dnsrecord-sample -spec: - managedZone: - name: mgc-dev-mz - endpoints: - - dnsName: dnsrecord-simple.mn.hcpapps.net - recordTTL: 60 - recordType: A - targets: - - 52.215.108.61 - - 52.30.101.221 diff --git a/config/samples/kuadrant.io_v1alpha1_managedzone.yaml b/config/samples/kuadrant.io_v1alpha1_managedzone.yaml index 549542884..5a41b4f97 100644 --- a/config/samples/kuadrant.io_v1alpha1_managedzone.yaml +++ b/config/samples/kuadrant.io_v1alpha1_managedzone.yaml @@ -1,13 +1,10 @@ -apiVersion: kuadrant.io/v1alpha1 +apiVersion: kuadrant.io/v1alpha2 kind: ManagedZone metadata: - labels: - app.kubernetes.io/name: managedzone - app.kubernetes.io/instance: managedzone-sample - app.kubernetes.io/part-of: multicluster-gateway-controller - app.kubernetes.io/managed-by: kustomize - app.kubernetes.io/created-by: multicluster-gateway-controller name: managedzone-sample spec: domainName: testmz.hcapps.net description: "My managed domain" + providerRef: + name: my-provider-credentials + kind: Secret \ No newline at end of file diff --git a/config/samples/kuadrant.io_v1alpha1_dnsrecord-geo.yaml b/config/samples/kuadrant.io_v1alpha2_dnsrecord-geo.yaml similarity index 77% rename from config/samples/kuadrant.io_v1alpha1_dnsrecord-geo.yaml rename to config/samples/kuadrant.io_v1alpha2_dnsrecord-geo.yaml index e025b123b..f0a60693b 100644 --- a/config/samples/kuadrant.io_v1alpha1_dnsrecord-geo.yaml +++ b/config/samples/kuadrant.io_v1alpha2_dnsrecord-geo.yaml @@ -1,16 +1,11 @@ -apiVersion: kuadrant.io/v1alpha1 +apiVersion: kuadrant.io/v1alpha2 kind: DNSRecord metadata: - labels: - app.kubernetes.io/name: dnsrecord-geo - app.kubernetes.io/instance: dnsrecord-sample - app.kubernetes.io/part-of: multicluster-gateway-controller - app.kubernetes.io/managed-by: kustomize - app.kubernetes.io/created-by: multicluster-gateway-controller name: dnsrecord-geo spec: - managedZone: - name: mgc-dev-mz + providerRef: + name: managedzone-sample + kind: ManagedZone endpoints: - dnsName: dnsrecord-geo.mn.hcpapps.net recordTTL: 60 diff --git a/config/samples/kuadrant.io_v1alpha2_dnsrecord-ns.yaml b/config/samples/kuadrant.io_v1alpha2_dnsrecord-ns.yaml new file mode 100644 index 000000000..bc55e6d12 --- /dev/null +++ b/config/samples/kuadrant.io_v1alpha2_dnsrecord-ns.yaml @@ -0,0 +1,17 @@ +apiVersion: kuadrant.io/v1alpha2 +kind: DNSRecord +metadata: + name: dnsrecord-ns +spec: + providerRef: + name: managedzone-sample + kind: ManagedZone + endpoints: + - dnsName: testns.hcpapps.net + recordTTL: 172800 + recordType: NS + targets: + - ns-59.awsdns-07.com + - ns-59.awsdns-07.com + - ns-910.awsdns-49.net + - ns-1440.awsdns-52.org diff --git a/config/samples/kuadrant.io_v1alpha2_dnsrecord.yaml b/config/samples/kuadrant.io_v1alpha2_dnsrecord.yaml new file mode 100644 index 000000000..d010e4af7 --- /dev/null +++ b/config/samples/kuadrant.io_v1alpha2_dnsrecord.yaml @@ -0,0 +1,15 @@ +apiVersion: kuadrant.io/v1alpha2 +kind: DNSRecord +metadata: + name: dnsrecord-sample +spec: + providerRef: + name: managedzone-sample + kind: ManagedZone + endpoints: + - dnsName: dnsrecord-simple.mn.hcpapps.net + recordTTL: 60 + recordType: A + targets: + - 52.215.108.61 + - 52.30.101.221 diff --git a/hack/.deployUtils b/hack/.deployUtils index ab4eab53b..dcab6a613 100644 --- a/hack/.deployUtils +++ b/hack/.deployUtils @@ -353,7 +353,7 @@ data: ZONE_ROOT_DOMAIN: ${KUADRANT_ZONE_ROOT_DOMAIN} LOG_LEVEL: "${LOG_LEVEL}" --- -apiVersion: kuadrant.io/v1alpha1 +apiVersion: kuadrant.io/v1alpha2 kind: ManagedZone metadata: name: ${KIND_CLUSTER_PREFIX}dev-mz @@ -362,7 +362,7 @@ spec: id: ${KUADRANT_AWS_DNS_PUBLIC_ZONE_ID} domainName: ${KUADRANT_ZONE_ROOT_DOMAIN} description: "Dev Managed Zone" - dnsProviderSecretRef: + providerRef: name: ${KIND_CLUSTER_PREFIX}aws-credentials EOF } @@ -393,7 +393,7 @@ data: ZONE_NAME: ${ZONE_NAME} LOG_LEVEL: "${LOG_LEVEL}" --- -apiVersion: kuadrant.io/v1alpha1 +apiVersion: kuadrant.io/v1alpha2 kind: ManagedZone metadata: name: ${KIND_CLUSTER_PREFIX}dev-mz @@ -402,7 +402,7 @@ spec: id: ${ZONE_NAME} domainName: ${ZONE_DNS_NAME} description: "Dev Managed Zone" - dnsProviderSecretRef: + providerRef: name: ${KIND_CLUSTER_PREFIX}gcp-credentials EOF } diff --git a/pkg/_internal/conditions/conditions_test.go b/pkg/_internal/conditions/conditions_test.go index f0e1c02db..cecff20d1 100644 --- a/pkg/_internal/conditions/conditions_test.go +++ b/pkg/_internal/conditions/conditions_test.go @@ -9,7 +9,7 @@ import ( gatewayapiv1 "sigs.k8s.io/gateway-api/apis/v1" "github.com/Kuadrant/multicluster-gateway-controller/pkg/_internal/conditions" - "github.com/Kuadrant/multicluster-gateway-controller/pkg/apis/v1alpha1" + "github.com/Kuadrant/multicluster-gateway-controller/pkg/apis/v1alpha2" ) const ( @@ -18,10 +18,10 @@ const ( func TestBuildPolicyCondition(t *testing.T) { runtimeObject := func() runtime.Object { - return &v1alpha1.DNSPolicy{ + return &v1alpha2.DNSPolicy{ TypeMeta: metav1.TypeMeta{ Kind: "DNSPolicy", - APIVersion: "kuadrant.io/v1alpha1", + APIVersion: "kuadrant.io/v1alpha2", }, } } diff --git a/pkg/_internal/policy/policy_test.go b/pkg/_internal/policy/policy_test.go index 4bb8dec04..36076fb78 100644 --- a/pkg/_internal/policy/policy_test.go +++ b/pkg/_internal/policy/policy_test.go @@ -11,7 +11,7 @@ import ( "github.com/kuadrant/kuadrant-operator/pkg/common" - "github.com/Kuadrant/multicluster-gateway-controller/pkg/apis/v1alpha1" + "github.com/Kuadrant/multicluster-gateway-controller/pkg/apis/v1alpha2" testutil "github.com/Kuadrant/multicluster-gateway-controller/test/util" ) @@ -27,13 +27,13 @@ func TestGetTargetRefValueFromPolicy(t *testing.T) { { name: "should use target namespace", args: args{ - policy: &v1alpha1.DNSPolicy{ + policy: &v1alpha2.DNSPolicy{ TypeMeta: metav1.TypeMeta{}, ObjectMeta: metav1.ObjectMeta{ Name: "test-policy", Namespace: "test-policy-ns", }, - Spec: v1alpha1.DNSPolicySpec{ + Spec: v1alpha2.DNSPolicySpec{ TargetRef: gatewayapiv1alpha2.PolicyTargetReference{ Group: "gateway.networking.k8s.io", Kind: "Gateway", @@ -47,13 +47,13 @@ func TestGetTargetRefValueFromPolicy(t *testing.T) { { name: "should use policy namespace when no target namespace set", args: args{ - policy: &v1alpha1.DNSPolicy{ + policy: &v1alpha2.DNSPolicy{ TypeMeta: metav1.TypeMeta{}, ObjectMeta: metav1.ObjectMeta{ Name: "test-policy", Namespace: "test-policy-ns", }, - Spec: v1alpha1.DNSPolicySpec{ + Spec: v1alpha2.DNSPolicySpec{ TargetRef: gatewayapiv1alpha2.PolicyTargetReference{ Group: "gateway.networking.k8s.io", Kind: "Gateway", diff --git a/pkg/apis/v1alpha1/zz_generated.deepcopy.go b/pkg/apis/v1alpha1/zz_generated.deepcopy.go index 2aae0a414..ffe3fd1ea 100644 --- a/pkg/apis/v1alpha1/zz_generated.deepcopy.go +++ b/pkg/apis/v1alpha1/zz_generated.deepcopy.go @@ -118,26 +118,6 @@ func (in *CertificateSpec) DeepCopy() *CertificateSpec { return out } -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *CustomWeight) DeepCopyInto(out *CustomWeight) { - *out = *in - if in.Selector != nil { - in, out := &in.Selector, &out.Selector - *out = new(v1.LabelSelector) - (*in).DeepCopyInto(*out) - } -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CustomWeight. -func (in *CustomWeight) DeepCopy() *CustomWeight { - if in == nil { - return nil - } - out := new(CustomWeight) - in.DeepCopyInto(out) - return out -} - // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *DNSHealthCheckProbe) DeepCopyInto(out *DNSHealthCheckProbe) { *out = *in @@ -249,648 +229,6 @@ func (in *DNSHealthCheckProbeStatus) DeepCopy() *DNSHealthCheckProbeStatus { return out } -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *DNSPolicy) DeepCopyInto(out *DNSPolicy) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) - in.Spec.DeepCopyInto(&out.Spec) - in.Status.DeepCopyInto(&out.Status) -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DNSPolicy. -func (in *DNSPolicy) DeepCopy() *DNSPolicy { - if in == nil { - return nil - } - out := new(DNSPolicy) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *DNSPolicy) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *DNSPolicyList) DeepCopyInto(out *DNSPolicyList) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ListMeta.DeepCopyInto(&out.ListMeta) - if in.Items != nil { - in, out := &in.Items, &out.Items - *out = make([]DNSPolicy, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DNSPolicyList. -func (in *DNSPolicyList) DeepCopy() *DNSPolicyList { - if in == nil { - return nil - } - out := new(DNSPolicyList) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *DNSPolicyList) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *DNSPolicySpec) DeepCopyInto(out *DNSPolicySpec) { - *out = *in - in.TargetRef.DeepCopyInto(&out.TargetRef) - if in.HealthCheck != nil { - in, out := &in.HealthCheck, &out.HealthCheck - *out = new(HealthCheckSpec) - (*in).DeepCopyInto(*out) - } - if in.LoadBalancing != nil { - in, out := &in.LoadBalancing, &out.LoadBalancing - *out = new(LoadBalancingSpec) - (*in).DeepCopyInto(*out) - } -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DNSPolicySpec. -func (in *DNSPolicySpec) DeepCopy() *DNSPolicySpec { - if in == nil { - return nil - } - out := new(DNSPolicySpec) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *DNSPolicyStatus) DeepCopyInto(out *DNSPolicyStatus) { - *out = *in - if in.Conditions != nil { - in, out := &in.Conditions, &out.Conditions - *out = make([]v1.Condition, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - if in.HealthCheck != nil { - in, out := &in.HealthCheck, &out.HealthCheck - *out = new(HealthCheckStatus) - (*in).DeepCopyInto(*out) - } -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DNSPolicyStatus. -func (in *DNSPolicyStatus) DeepCopy() *DNSPolicyStatus { - if in == nil { - return nil - } - out := new(DNSPolicyStatus) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *DNSRecord) DeepCopyInto(out *DNSRecord) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) - in.Spec.DeepCopyInto(&out.Spec) - in.Status.DeepCopyInto(&out.Status) -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DNSRecord. -func (in *DNSRecord) DeepCopy() *DNSRecord { - if in == nil { - return nil - } - out := new(DNSRecord) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *DNSRecord) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *DNSRecordList) DeepCopyInto(out *DNSRecordList) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ListMeta.DeepCopyInto(&out.ListMeta) - if in.Items != nil { - in, out := &in.Items, &out.Items - *out = make([]DNSRecord, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DNSRecordList. -func (in *DNSRecordList) DeepCopy() *DNSRecordList { - if in == nil { - return nil - } - out := new(DNSRecordList) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *DNSRecordList) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *DNSRecordRef) DeepCopyInto(out *DNSRecordRef) { - *out = *in -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DNSRecordRef. -func (in *DNSRecordRef) DeepCopy() *DNSRecordRef { - if in == nil { - return nil - } - out := new(DNSRecordRef) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *DNSRecordSpec) DeepCopyInto(out *DNSRecordSpec) { - *out = *in - if in.ManagedZoneRef != nil { - in, out := &in.ManagedZoneRef, &out.ManagedZoneRef - *out = new(ManagedZoneReference) - **out = **in - } - if in.Endpoints != nil { - in, out := &in.Endpoints, &out.Endpoints - *out = make([]*Endpoint, len(*in)) - for i := range *in { - if (*in)[i] != nil { - in, out := &(*in)[i], &(*out)[i] - *out = new(Endpoint) - (*in).DeepCopyInto(*out) - } - } - } -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DNSRecordSpec. -func (in *DNSRecordSpec) DeepCopy() *DNSRecordSpec { - if in == nil { - return nil - } - out := new(DNSRecordSpec) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *DNSRecordStatus) DeepCopyInto(out *DNSRecordStatus) { - *out = *in - if in.Conditions != nil { - in, out := &in.Conditions, &out.Conditions - *out = make([]v1.Condition, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - if in.Endpoints != nil { - in, out := &in.Endpoints, &out.Endpoints - *out = make([]*Endpoint, len(*in)) - for i := range *in { - if (*in)[i] != nil { - in, out := &(*in)[i], &(*out)[i] - *out = new(Endpoint) - (*in).DeepCopyInto(*out) - } - } - } -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DNSRecordStatus. -func (in *DNSRecordStatus) DeepCopy() *DNSRecordStatus { - if in == nil { - return nil - } - out := new(DNSRecordStatus) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *Endpoint) DeepCopyInto(out *Endpoint) { - *out = *in - if in.Targets != nil { - in, out := &in.Targets, &out.Targets - *out = make(Targets, len(*in)) - copy(*out, *in) - } - if in.Labels != nil { - in, out := &in.Labels, &out.Labels - *out = make(Labels, len(*in)) - for key, val := range *in { - (*out)[key] = val - } - } - if in.ProviderSpecific != nil { - in, out := &in.ProviderSpecific, &out.ProviderSpecific - *out = make(ProviderSpecific, len(*in)) - copy(*out, *in) - } -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Endpoint. -func (in *Endpoint) DeepCopy() *Endpoint { - if in == nil { - return nil - } - out := new(Endpoint) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *HealthCheckSpec) DeepCopyInto(out *HealthCheckSpec) { - *out = *in - if in.Port != nil { - in, out := &in.Port, &out.Port - *out = new(int) - **out = **in - } - if in.Protocol != nil { - in, out := &in.Protocol, &out.Protocol - *out = new(HealthProtocol) - **out = **in - } - if in.FailureThreshold != nil { - in, out := &in.FailureThreshold, &out.FailureThreshold - *out = new(int) - **out = **in - } - if in.AdditionalHeadersRef != nil { - in, out := &in.AdditionalHeadersRef, &out.AdditionalHeadersRef - *out = new(AdditionalHeadersRef) - **out = **in - } - if in.ExpectedResponses != nil { - in, out := &in.ExpectedResponses, &out.ExpectedResponses - *out = make([]int, len(*in)) - copy(*out, *in) - } - if in.Interval != nil { - in, out := &in.Interval, &out.Interval - *out = new(v1.Duration) - **out = **in - } -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new HealthCheckSpec. -func (in *HealthCheckSpec) DeepCopy() *HealthCheckSpec { - if in == nil { - return nil - } - out := new(HealthCheckSpec) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *HealthCheckStatus) DeepCopyInto(out *HealthCheckStatus) { - *out = *in - if in.Conditions != nil { - in, out := &in.Conditions, &out.Conditions - *out = make([]v1.Condition, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new HealthCheckStatus. -func (in *HealthCheckStatus) DeepCopy() *HealthCheckStatus { - if in == nil { - return nil - } - out := new(HealthCheckStatus) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in Labels) DeepCopyInto(out *Labels) { - { - in := &in - *out = make(Labels, len(*in)) - for key, val := range *in { - (*out)[key] = val - } - } -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Labels. -func (in Labels) DeepCopy() Labels { - if in == nil { - return nil - } - out := new(Labels) - in.DeepCopyInto(out) - return *out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *LoadBalancingGeo) DeepCopyInto(out *LoadBalancingGeo) { - *out = *in -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new LoadBalancingGeo. -func (in *LoadBalancingGeo) DeepCopy() *LoadBalancingGeo { - if in == nil { - return nil - } - out := new(LoadBalancingGeo) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *LoadBalancingSpec) DeepCopyInto(out *LoadBalancingSpec) { - *out = *in - if in.Weighted != nil { - in, out := &in.Weighted, &out.Weighted - *out = new(LoadBalancingWeighted) - (*in).DeepCopyInto(*out) - } - if in.Geo != nil { - in, out := &in.Geo, &out.Geo - *out = new(LoadBalancingGeo) - **out = **in - } -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new LoadBalancingSpec. -func (in *LoadBalancingSpec) DeepCopy() *LoadBalancingSpec { - if in == nil { - return nil - } - out := new(LoadBalancingSpec) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *LoadBalancingWeighted) DeepCopyInto(out *LoadBalancingWeighted) { - *out = *in - if in.Custom != nil { - in, out := &in.Custom, &out.Custom - *out = make([]*CustomWeight, len(*in)) - for i := range *in { - if (*in)[i] != nil { - in, out := &(*in)[i], &(*out)[i] - *out = new(CustomWeight) - (*in).DeepCopyInto(*out) - } - } - } -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new LoadBalancingWeighted. -func (in *LoadBalancingWeighted) DeepCopy() *LoadBalancingWeighted { - if in == nil { - return nil - } - out := new(LoadBalancingWeighted) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ManagedHost) DeepCopyInto(out *ManagedHost) { - *out = *in - if in.ManagedZone != nil { - in, out := &in.ManagedZone, &out.ManagedZone - *out = new(ManagedZone) - (*in).DeepCopyInto(*out) - } - if in.DnsRecord != nil { - in, out := &in.DnsRecord, &out.DnsRecord - *out = new(DNSRecord) - (*in).DeepCopyInto(*out) - } -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ManagedHost. -func (in *ManagedHost) DeepCopy() *ManagedHost { - if in == nil { - return nil - } - out := new(ManagedHost) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ManagedZone) DeepCopyInto(out *ManagedZone) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) - in.Spec.DeepCopyInto(&out.Spec) - in.Status.DeepCopyInto(&out.Status) -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ManagedZone. -func (in *ManagedZone) DeepCopy() *ManagedZone { - if in == nil { - return nil - } - out := new(ManagedZone) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *ManagedZone) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ManagedZoneList) DeepCopyInto(out *ManagedZoneList) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ListMeta.DeepCopyInto(&out.ListMeta) - if in.Items != nil { - in, out := &in.Items, &out.Items - *out = make([]ManagedZone, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ManagedZoneList. -func (in *ManagedZoneList) DeepCopy() *ManagedZoneList { - if in == nil { - return nil - } - out := new(ManagedZoneList) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *ManagedZoneList) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ManagedZoneReference) DeepCopyInto(out *ManagedZoneReference) { - *out = *in -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ManagedZoneReference. -func (in *ManagedZoneReference) DeepCopy() *ManagedZoneReference { - if in == nil { - return nil - } - out := new(ManagedZoneReference) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ManagedZoneSpec) DeepCopyInto(out *ManagedZoneSpec) { - *out = *in - if in.ParentManagedZone != nil { - in, out := &in.ParentManagedZone, &out.ParentManagedZone - *out = new(ManagedZoneReference) - **out = **in - } - if in.SecretRef != nil { - in, out := &in.SecretRef, &out.SecretRef - *out = new(SecretRef) - **out = **in - } -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ManagedZoneSpec. -func (in *ManagedZoneSpec) DeepCopy() *ManagedZoneSpec { - if in == nil { - return nil - } - out := new(ManagedZoneSpec) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ManagedZoneStatus) DeepCopyInto(out *ManagedZoneStatus) { - *out = *in - if in.Conditions != nil { - in, out := &in.Conditions, &out.Conditions - *out = make([]v1.Condition, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - if in.NameServers != nil { - in, out := &in.NameServers, &out.NameServers - *out = make([]*string, len(*in)) - for i := range *in { - if (*in)[i] != nil { - in, out := &(*in)[i], &(*out)[i] - *out = new(string) - **out = **in - } - } - } -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ManagedZoneStatus. -func (in *ManagedZoneStatus) DeepCopy() *ManagedZoneStatus { - if in == nil { - return nil - } - out := new(ManagedZoneStatus) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in ProviderSpecific) DeepCopyInto(out *ProviderSpecific) { - { - in := &in - *out = make(ProviderSpecific, len(*in)) - copy(*out, *in) - } -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ProviderSpecific. -func (in ProviderSpecific) DeepCopy() ProviderSpecific { - if in == nil { - return nil - } - out := new(ProviderSpecific) - in.DeepCopyInto(out) - return *out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ProviderSpecificProperty) DeepCopyInto(out *ProviderSpecificProperty) { - *out = *in -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ProviderSpecificProperty. -func (in *ProviderSpecificProperty) DeepCopy() *ProviderSpecificProperty { - if in == nil { - return nil - } - out := new(ProviderSpecificProperty) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *SecretRef) DeepCopyInto(out *SecretRef) { - *out = *in -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SecretRef. -func (in *SecretRef) DeepCopy() *SecretRef { - if in == nil { - return nil - } - out := new(SecretRef) - in.DeepCopyInto(out) - return out -} - // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *TLSPolicy) DeepCopyInto(out *TLSPolicy) { *out = *in @@ -988,37 +326,3 @@ func (in *TLSPolicyStatus) DeepCopy() *TLSPolicyStatus { in.DeepCopyInto(out) return out } - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *Target) DeepCopyInto(out *Target) { - *out = *in -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Target. -func (in *Target) DeepCopy() *Target { - if in == nil { - return nil - } - out := new(Target) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in Targets) DeepCopyInto(out *Targets) { - { - in := &in - *out = make(Targets, len(*in)) - copy(*out, *in) - } -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Targets. -func (in Targets) DeepCopy() Targets { - if in == nil { - return nil - } - out := new(Targets) - in.DeepCopyInto(out) - return *out -} diff --git a/pkg/apis/v1alpha1/dnspolicy_types.go b/pkg/apis/v1alpha2/dnspolicy_types.go similarity index 87% rename from pkg/apis/v1alpha1/dnspolicy_types.go rename to pkg/apis/v1alpha2/dnspolicy_types.go index 60ff89103..83769c80b 100644 --- a/pkg/apis/v1alpha1/dnspolicy_types.go +++ b/pkg/apis/v1alpha2/dnspolicy_types.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package v1alpha1 +package v1alpha2 import ( "fmt" @@ -23,6 +23,8 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" gatewayapiv1 "sigs.k8s.io/gateway-api/apis/v1" gatewayapiv1alpha2 "sigs.k8s.io/gateway-api/apis/v1alpha2" + + "github.com/Kuadrant/multicluster-gateway-controller/pkg/apis/v1alpha1" ) type RoutingStrategy string @@ -49,6 +51,9 @@ type DNSPolicySpec struct { // +kubebuilder:validation:Enum=simple;loadbalanced // +kubebuilder:default=loadbalanced RoutingStrategy RoutingStrategy `json:"routingStrategy"` + + // +required + ProviderRef ProviderRef `json:"providerRef"` } type LoadBalancingSpec struct { @@ -136,6 +141,10 @@ func (p *DNSPolicy) GetTargetRef() gatewayapiv1alpha2.PolicyTargetReference { return p.Spec.TargetRef } +func (p *DNSPolicy) GetProviderRef() ProviderRef { + return p.Spec.ProviderRef +} + // Validate ensures the resource is valid. Compatible with the validating interface // used by webhooks func (p *DNSPolicy) Validate() error { @@ -179,14 +188,14 @@ type DNSPolicyList struct { // By default, this health check will be applied to each unique DNS A Record for // the listeners assigned to the target gateway type HealthCheckSpec struct { - Endpoint string `json:"endpoint,omitempty"` - Port *int `json:"port,omitempty"` - Protocol *HealthProtocol `json:"protocol,omitempty"` - FailureThreshold *int `json:"failureThreshold,omitempty"` - AdditionalHeadersRef *AdditionalHeadersRef `json:"additionalHeadersRef,omitempty"` - ExpectedResponses []int `json:"expectedResponses,omitempty"` - AllowInsecureCertificates bool `json:"allowInsecureCertificates,omitempty"` - Interval *metav1.Duration `json:"interval,omitempty"` + Endpoint string `json:"endpoint,omitempty"` + Port *int `json:"port,omitempty"` + Protocol *v1alpha1.HealthProtocol `json:"protocol,omitempty"` + FailureThreshold *int `json:"failureThreshold,omitempty"` + AdditionalHeadersRef *v1alpha1.AdditionalHeadersRef `json:"additionalHeadersRef,omitempty"` + ExpectedResponses []int `json:"expectedResponses,omitempty"` + AllowInsecureCertificates bool `json:"allowInsecureCertificates,omitempty"` + Interval *metav1.Duration `json:"interval,omitempty"` } func (s *HealthCheckSpec) Validate() error { @@ -207,7 +216,7 @@ func (s *HealthCheckSpec) Default() { } if s.Protocol == nil { - protocol := HttpsProtocol + protocol := v1alpha1.HttpsProtocol s.Protocol = &protocol } } diff --git a/pkg/apis/v1alpha1/dnsrecord_types.go b/pkg/apis/v1alpha2/dnsrecord_types.go similarity index 97% rename from pkg/apis/v1alpha1/dnsrecord_types.go rename to pkg/apis/v1alpha2/dnsrecord_types.go index 3b8fe43f2..8f30bfd75 100644 --- a/pkg/apis/v1alpha1/dnsrecord_types.go +++ b/pkg/apis/v1alpha2/dnsrecord_types.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package v1alpha1 +package v1alpha2 import ( "fmt" @@ -102,12 +102,16 @@ func (e *Endpoint) String() string { // DNSRecordSpec defines the desired state of DNSRecord type DNSRecordSpec struct { - // +kubebuilder:validation:Required - // +required - ManagedZoneRef *ManagedZoneReference `json:"managedZone,omitempty"` // +kubebuilder:validation:MinItems=1 // +optional Endpoints []*Endpoint `json:"endpoints,omitempty"` + + // +kubebuilder:validation:Required + // +required + ProviderRef ProviderRef `json:"providerRef"` + + // +optional + ZoneID *string `json:"zoneID,omitempty"` } // DNSRecordStatus defines the observed state of DNSRecord @@ -151,6 +155,10 @@ type DNSRecord struct { Status DNSRecordStatus `json:"status,omitempty"` } +func (p *DNSRecord) GetProviderRef() ProviderRef { + return p.Spec.ProviderRef +} + //+kubebuilder:object:root=true // DNSRecordList contains a list of DNSRecord diff --git a/pkg/apis/v1alpha2/groupversion_info.go b/pkg/apis/v1alpha2/groupversion_info.go new file mode 100644 index 000000000..3f0cb8367 --- /dev/null +++ b/pkg/apis/v1alpha2/groupversion_info.go @@ -0,0 +1,36 @@ +/* +Copyright 2023 The MultiCluster Traffic Controller Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Package v1alpha2 contains API Schema definitions for the kuadrant.io v1alpha2 API group +// +kubebuilder:object:generate=true +// +groupName=kuadrant.io +package v1alpha2 + +import ( + "k8s.io/apimachinery/pkg/runtime/schema" + "sigs.k8s.io/controller-runtime/pkg/scheme" +) + +var ( + // GroupVersion is group version used to register these objects + GroupVersion = schema.GroupVersion{Group: "kuadrant.io", Version: "v1alpha2"} + + // SchemeBuilder is used to add go types to the GroupVersionKind scheme + SchemeBuilder = &scheme.Builder{GroupVersion: GroupVersion} + + // AddToScheme adds the types in this group-version to the given scheme. + AddToScheme = SchemeBuilder.AddToScheme +) diff --git a/pkg/apis/v1alpha1/managedzone_types.go b/pkg/apis/v1alpha2/managedzone_types.go similarity index 91% rename from pkg/apis/v1alpha1/managedzone_types.go rename to pkg/apis/v1alpha2/managedzone_types.go index 8cbbede47..ffcafde84 100644 --- a/pkg/apis/v1alpha1/managedzone_types.go +++ b/pkg/apis/v1alpha2/managedzone_types.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package v1alpha1 +package v1alpha2 import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -31,22 +31,19 @@ type ManagedZoneReference struct { type ManagedZoneSpec struct { // ID is the provider assigned id of this zone (i.e. route53.HostedZone.ID). // +optional - ID string `json:"id,omitempty"` + ID *string `json:"id,omitempty"` //Domain name of this ManagedZone + // +required // +kubebuilder:validation:Pattern=`^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$` DomainName string `json:"domainName"` //Description for this ManagedZone - Description string `json:"description"` + // +optional + Description *string `json:"description"` // Reference to another managed zone that this managed zone belongs to. // +optional ParentManagedZone *ManagedZoneReference `json:"parentManagedZone,omitempty"` // +required - SecretRef *SecretRef `json:"dnsProviderSecretRef"` -} - -type SecretRef struct { - //+required - Name string `json:"name"` + ProviderRef ProviderRef `json:"providerRef"` } // ManagedZoneStatus defines the observed state of a Zone @@ -89,6 +86,10 @@ type ManagedZone struct { Status ManagedZoneStatus `json:"status,omitempty"` } +func (p *ManagedZone) GetProviderRef() ProviderRef { + return p.Spec.ProviderRef +} + //+kubebuilder:object:root=true // ManagedZoneList contains a list of ManagedZone @@ -98,13 +99,6 @@ type ManagedZoneList struct { Items []ManagedZone `json:"items"` } -type ManagedHost struct { - Subdomain string - Host string - ManagedZone *ManagedZone - DnsRecord *DNSRecord -} - func init() { SchemeBuilder.Register(&ManagedZone{}, &ManagedZoneList{}) } diff --git a/pkg/apis/v1alpha2/shared_types.go b/pkg/apis/v1alpha2/shared_types.go new file mode 100644 index 000000000..8dbb03415 --- /dev/null +++ b/pkg/apis/v1alpha2/shared_types.go @@ -0,0 +1,39 @@ +/* +Copyright 2023 The MultiCluster Traffic Controller Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1alpha2 + +// +kubebuilder:validation:Enum=None;Secret;ManagedZone +type ProviderKind string + +type ProviderRef struct { + //+required + Name string `json:"name"` + //+required + Kind ProviderKind `json:"kind"` +} + +const ( + ProviderKindNone = "None" + ProviderKindSecret = "Secret" + ProviderKindManagedZone = "ManagedZone" +) + +// +kubebuilder:object:generate=false +type ProviderAccessor interface { + GetNamespace() string + GetProviderRef() ProviderRef +} diff --git a/pkg/apis/v1alpha2/zz_generated.deepcopy.go b/pkg/apis/v1alpha2/zz_generated.deepcopy.go new file mode 100644 index 000000000..a76f880c6 --- /dev/null +++ b/pkg/apis/v1alpha2/zz_generated.deepcopy.go @@ -0,0 +1,708 @@ +//go:build !ignore_autogenerated +// +build !ignore_autogenerated + +/* +Copyright 2022 The MultiCluster Traffic Controller Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by controller-gen. DO NOT EDIT. + +package v1alpha2 + +import ( + "k8s.io/apimachinery/pkg/apis/meta/v1" + runtime "k8s.io/apimachinery/pkg/runtime" + + "github.com/Kuadrant/multicluster-gateway-controller/pkg/apis/v1alpha1" +) + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *CustomWeight) DeepCopyInto(out *CustomWeight) { + *out = *in + if in.Selector != nil { + in, out := &in.Selector, &out.Selector + *out = new(v1.LabelSelector) + (*in).DeepCopyInto(*out) + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CustomWeight. +func (in *CustomWeight) DeepCopy() *CustomWeight { + if in == nil { + return nil + } + out := new(CustomWeight) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *DNSPolicy) DeepCopyInto(out *DNSPolicy) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + in.Spec.DeepCopyInto(&out.Spec) + in.Status.DeepCopyInto(&out.Status) +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DNSPolicy. +func (in *DNSPolicy) DeepCopy() *DNSPolicy { + if in == nil { + return nil + } + out := new(DNSPolicy) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *DNSPolicy) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *DNSPolicyList) DeepCopyInto(out *DNSPolicyList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]DNSPolicy, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DNSPolicyList. +func (in *DNSPolicyList) DeepCopy() *DNSPolicyList { + if in == nil { + return nil + } + out := new(DNSPolicyList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *DNSPolicyList) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *DNSPolicySpec) DeepCopyInto(out *DNSPolicySpec) { + *out = *in + in.TargetRef.DeepCopyInto(&out.TargetRef) + if in.HealthCheck != nil { + in, out := &in.HealthCheck, &out.HealthCheck + *out = new(HealthCheckSpec) + (*in).DeepCopyInto(*out) + } + if in.LoadBalancing != nil { + in, out := &in.LoadBalancing, &out.LoadBalancing + *out = new(LoadBalancingSpec) + (*in).DeepCopyInto(*out) + } + out.ProviderRef = in.ProviderRef +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DNSPolicySpec. +func (in *DNSPolicySpec) DeepCopy() *DNSPolicySpec { + if in == nil { + return nil + } + out := new(DNSPolicySpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *DNSPolicyStatus) DeepCopyInto(out *DNSPolicyStatus) { + *out = *in + if in.Conditions != nil { + in, out := &in.Conditions, &out.Conditions + *out = make([]v1.Condition, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + if in.HealthCheck != nil { + in, out := &in.HealthCheck, &out.HealthCheck + *out = new(HealthCheckStatus) + (*in).DeepCopyInto(*out) + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DNSPolicyStatus. +func (in *DNSPolicyStatus) DeepCopy() *DNSPolicyStatus { + if in == nil { + return nil + } + out := new(DNSPolicyStatus) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *DNSRecord) DeepCopyInto(out *DNSRecord) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + in.Spec.DeepCopyInto(&out.Spec) + in.Status.DeepCopyInto(&out.Status) +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DNSRecord. +func (in *DNSRecord) DeepCopy() *DNSRecord { + if in == nil { + return nil + } + out := new(DNSRecord) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *DNSRecord) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *DNSRecordList) DeepCopyInto(out *DNSRecordList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]DNSRecord, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DNSRecordList. +func (in *DNSRecordList) DeepCopy() *DNSRecordList { + if in == nil { + return nil + } + out := new(DNSRecordList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *DNSRecordList) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *DNSRecordRef) DeepCopyInto(out *DNSRecordRef) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DNSRecordRef. +func (in *DNSRecordRef) DeepCopy() *DNSRecordRef { + if in == nil { + return nil + } + out := new(DNSRecordRef) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *DNSRecordSpec) DeepCopyInto(out *DNSRecordSpec) { + *out = *in + if in.Endpoints != nil { + in, out := &in.Endpoints, &out.Endpoints + *out = make([]*Endpoint, len(*in)) + for i := range *in { + if (*in)[i] != nil { + in, out := &(*in)[i], &(*out)[i] + *out = new(Endpoint) + (*in).DeepCopyInto(*out) + } + } + } + out.ProviderRef = in.ProviderRef + if in.ZoneID != nil { + in, out := &in.ZoneID, &out.ZoneID + *out = new(string) + **out = **in + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DNSRecordSpec. +func (in *DNSRecordSpec) DeepCopy() *DNSRecordSpec { + if in == nil { + return nil + } + out := new(DNSRecordSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *DNSRecordStatus) DeepCopyInto(out *DNSRecordStatus) { + *out = *in + if in.Conditions != nil { + in, out := &in.Conditions, &out.Conditions + *out = make([]v1.Condition, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + if in.Endpoints != nil { + in, out := &in.Endpoints, &out.Endpoints + *out = make([]*Endpoint, len(*in)) + for i := range *in { + if (*in)[i] != nil { + in, out := &(*in)[i], &(*out)[i] + *out = new(Endpoint) + (*in).DeepCopyInto(*out) + } + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DNSRecordStatus. +func (in *DNSRecordStatus) DeepCopy() *DNSRecordStatus { + if in == nil { + return nil + } + out := new(DNSRecordStatus) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *Endpoint) DeepCopyInto(out *Endpoint) { + *out = *in + if in.Targets != nil { + in, out := &in.Targets, &out.Targets + *out = make(Targets, len(*in)) + copy(*out, *in) + } + if in.Labels != nil { + in, out := &in.Labels, &out.Labels + *out = make(Labels, len(*in)) + for key, val := range *in { + (*out)[key] = val + } + } + if in.ProviderSpecific != nil { + in, out := &in.ProviderSpecific, &out.ProviderSpecific + *out = make(ProviderSpecific, len(*in)) + copy(*out, *in) + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Endpoint. +func (in *Endpoint) DeepCopy() *Endpoint { + if in == nil { + return nil + } + out := new(Endpoint) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *HealthCheckSpec) DeepCopyInto(out *HealthCheckSpec) { + *out = *in + if in.Port != nil { + in, out := &in.Port, &out.Port + *out = new(int) + **out = **in + } + if in.Protocol != nil { + in, out := &in.Protocol, &out.Protocol + *out = new(v1alpha1.HealthProtocol) + **out = **in + } + if in.FailureThreshold != nil { + in, out := &in.FailureThreshold, &out.FailureThreshold + *out = new(int) + **out = **in + } + if in.AdditionalHeadersRef != nil { + in, out := &in.AdditionalHeadersRef, &out.AdditionalHeadersRef + *out = new(v1alpha1.AdditionalHeadersRef) + **out = **in + } + if in.ExpectedResponses != nil { + in, out := &in.ExpectedResponses, &out.ExpectedResponses + *out = make([]int, len(*in)) + copy(*out, *in) + } + if in.Interval != nil { + in, out := &in.Interval, &out.Interval + *out = new(v1.Duration) + **out = **in + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new HealthCheckSpec. +func (in *HealthCheckSpec) DeepCopy() *HealthCheckSpec { + if in == nil { + return nil + } + out := new(HealthCheckSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *HealthCheckStatus) DeepCopyInto(out *HealthCheckStatus) { + *out = *in + if in.Conditions != nil { + in, out := &in.Conditions, &out.Conditions + *out = make([]v1.Condition, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new HealthCheckStatus. +func (in *HealthCheckStatus) DeepCopy() *HealthCheckStatus { + if in == nil { + return nil + } + out := new(HealthCheckStatus) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in Labels) DeepCopyInto(out *Labels) { + { + in := &in + *out = make(Labels, len(*in)) + for key, val := range *in { + (*out)[key] = val + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Labels. +func (in Labels) DeepCopy() Labels { + if in == nil { + return nil + } + out := new(Labels) + in.DeepCopyInto(out) + return *out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *LoadBalancingGeo) DeepCopyInto(out *LoadBalancingGeo) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new LoadBalancingGeo. +func (in *LoadBalancingGeo) DeepCopy() *LoadBalancingGeo { + if in == nil { + return nil + } + out := new(LoadBalancingGeo) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *LoadBalancingSpec) DeepCopyInto(out *LoadBalancingSpec) { + *out = *in + if in.Weighted != nil { + in, out := &in.Weighted, &out.Weighted + *out = new(LoadBalancingWeighted) + (*in).DeepCopyInto(*out) + } + if in.Geo != nil { + in, out := &in.Geo, &out.Geo + *out = new(LoadBalancingGeo) + **out = **in + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new LoadBalancingSpec. +func (in *LoadBalancingSpec) DeepCopy() *LoadBalancingSpec { + if in == nil { + return nil + } + out := new(LoadBalancingSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *LoadBalancingWeighted) DeepCopyInto(out *LoadBalancingWeighted) { + *out = *in + if in.Custom != nil { + in, out := &in.Custom, &out.Custom + *out = make([]*CustomWeight, len(*in)) + for i := range *in { + if (*in)[i] != nil { + in, out := &(*in)[i], &(*out)[i] + *out = new(CustomWeight) + (*in).DeepCopyInto(*out) + } + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new LoadBalancingWeighted. +func (in *LoadBalancingWeighted) DeepCopy() *LoadBalancingWeighted { + if in == nil { + return nil + } + out := new(LoadBalancingWeighted) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ManagedZone) DeepCopyInto(out *ManagedZone) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + in.Spec.DeepCopyInto(&out.Spec) + in.Status.DeepCopyInto(&out.Status) +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ManagedZone. +func (in *ManagedZone) DeepCopy() *ManagedZone { + if in == nil { + return nil + } + out := new(ManagedZone) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *ManagedZone) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ManagedZoneList) DeepCopyInto(out *ManagedZoneList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]ManagedZone, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ManagedZoneList. +func (in *ManagedZoneList) DeepCopy() *ManagedZoneList { + if in == nil { + return nil + } + out := new(ManagedZoneList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *ManagedZoneList) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ManagedZoneReference) DeepCopyInto(out *ManagedZoneReference) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ManagedZoneReference. +func (in *ManagedZoneReference) DeepCopy() *ManagedZoneReference { + if in == nil { + return nil + } + out := new(ManagedZoneReference) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ManagedZoneSpec) DeepCopyInto(out *ManagedZoneSpec) { + *out = *in + if in.ID != nil { + in, out := &in.ID, &out.ID + *out = new(string) + **out = **in + } + if in.Description != nil { + in, out := &in.Description, &out.Description + *out = new(string) + **out = **in + } + if in.ParentManagedZone != nil { + in, out := &in.ParentManagedZone, &out.ParentManagedZone + *out = new(ManagedZoneReference) + **out = **in + } + out.ProviderRef = in.ProviderRef +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ManagedZoneSpec. +func (in *ManagedZoneSpec) DeepCopy() *ManagedZoneSpec { + if in == nil { + return nil + } + out := new(ManagedZoneSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ManagedZoneStatus) DeepCopyInto(out *ManagedZoneStatus) { + *out = *in + if in.Conditions != nil { + in, out := &in.Conditions, &out.Conditions + *out = make([]v1.Condition, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + if in.NameServers != nil { + in, out := &in.NameServers, &out.NameServers + *out = make([]*string, len(*in)) + for i := range *in { + if (*in)[i] != nil { + in, out := &(*in)[i], &(*out)[i] + *out = new(string) + **out = **in + } + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ManagedZoneStatus. +func (in *ManagedZoneStatus) DeepCopy() *ManagedZoneStatus { + if in == nil { + return nil + } + out := new(ManagedZoneStatus) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ProviderRef) DeepCopyInto(out *ProviderRef) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ProviderRef. +func (in *ProviderRef) DeepCopy() *ProviderRef { + if in == nil { + return nil + } + out := new(ProviderRef) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in ProviderSpecific) DeepCopyInto(out *ProviderSpecific) { + { + in := &in + *out = make(ProviderSpecific, len(*in)) + copy(*out, *in) + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ProviderSpecific. +func (in ProviderSpecific) DeepCopy() ProviderSpecific { + if in == nil { + return nil + } + out := new(ProviderSpecific) + in.DeepCopyInto(out) + return *out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ProviderSpecificProperty) DeepCopyInto(out *ProviderSpecificProperty) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ProviderSpecificProperty. +func (in *ProviderSpecificProperty) DeepCopy() *ProviderSpecificProperty { + if in == nil { + return nil + } + out := new(ProviderSpecificProperty) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *Target) DeepCopyInto(out *Target) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Target. +func (in *Target) DeepCopy() *Target { + if in == nil { + return nil + } + out := new(Target) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in Targets) DeepCopyInto(out *Targets) { + { + in := &in + *out = make(Targets, len(*in)) + copy(*out, *in) + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Targets. +func (in Targets) DeepCopy() Targets { + if in == nil { + return nil + } + out := new(Targets) + in.DeepCopyInto(out) + return *out +} diff --git a/pkg/controllers/dnshealthcheckprobe/dnshealthcheckprobe_controller.go b/pkg/controllers/dnshealthcheckprobe/dnshealthcheckprobe_controller.go index 4b08b971d..e535ef676 100644 --- a/pkg/controllers/dnshealthcheckprobe/dnshealthcheckprobe_controller.go +++ b/pkg/controllers/dnshealthcheckprobe/dnshealthcheckprobe_controller.go @@ -18,6 +18,7 @@ import ( "github.com/Kuadrant/multicluster-gateway-controller/pkg/_internal/slice" "github.com/Kuadrant/multicluster-gateway-controller/pkg/apis/v1alpha1" + "github.com/Kuadrant/multicluster-gateway-controller/pkg/apis/v1alpha2" "github.com/Kuadrant/multicluster-gateway-controller/pkg/health" ) @@ -257,7 +258,7 @@ func (r *DNSHealthCheckProbeReconciler) newProbeNotifierFor(ctx context.Context, ), nil } -func getDNSRecord(ctx context.Context, apiClient client.Client, obj metav1.Object) (*v1alpha1.DNSRecord, bool, error) { +func getDNSRecord(ctx context.Context, apiClient client.Client, obj metav1.Object) (*v1alpha2.DNSRecord, bool, error) { if obj.GetAnnotations() == nil { return nil, false, nil } @@ -269,7 +270,7 @@ func getDNSRecord(ctx context.Context, apiClient client.Client, obj metav1.Objec return nil, false, nil } - dnsRecord := &v1alpha1.DNSRecord{} + dnsRecord := &v1alpha2.DNSRecord{} if err := apiClient.Get(ctx, client.ObjectKey{ Name: name, Namespace: ns, diff --git a/pkg/controllers/dnspolicy/dns_helper.go b/pkg/controllers/dnspolicy/dns_helper.go index a38a7e452..d84dd482e 100644 --- a/pkg/controllers/dnspolicy/dns_helper.go +++ b/pkg/controllers/dnspolicy/dns_helper.go @@ -14,7 +14,6 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/labels" "sigs.k8s.io/controller-runtime/pkg/client" - "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" "sigs.k8s.io/controller-runtime/pkg/log" gatewayapiv1 "sigs.k8s.io/gateway-api/apis/v1" @@ -22,6 +21,7 @@ import ( "github.com/Kuadrant/multicluster-gateway-controller/pkg/_internal/slice" "github.com/Kuadrant/multicluster-gateway-controller/pkg/apis/v1alpha1" + "github.com/Kuadrant/multicluster-gateway-controller/pkg/apis/v1alpha2" "github.com/Kuadrant/multicluster-gateway-controller/pkg/dns" ) @@ -33,17 +33,15 @@ const ( var ( ErrUnknownRoutingStrategy = fmt.Errorf("unknown routing strategy") - ErrNoManagedZoneForHost = fmt.Errorf("no managed zone for host") - ErrAlreadyAssigned = fmt.Errorf("managed host already assigned") ) type dnsHelper struct { client.Client } -func findMatchingManagedZone(originalHost, host string, zones []v1alpha1.ManagedZone) (*v1alpha1.ManagedZone, string, error) { - if len(zones) == 0 { - return nil, "", fmt.Errorf("%w : %s", ErrNoManagedZoneForHost, host) +func findMatchingZone(originalHost, host string, zones dns.ZoneList) (*dns.Zone, string, error) { + if len(zones.Items) == 0 { + return nil, "", fmt.Errorf("no zones available") } host = strings.ToLower(host) //get the TLD from this host @@ -64,18 +62,18 @@ func findMatchingManagedZone(originalHost, host string, zones []v1alpha1.Managed // we should never be trying to find a managed zone that matches the `originalHost` exactly. Instead, we just continue // on to the next possible valid host to try i.e. the parent domain. if host == originalHost { - return findMatchingManagedZone(originalHost, parentDomain, zones) + return findMatchingZone(originalHost, parentDomain, zones) } - zone, ok := slice.Find(zones, func(zone v1alpha1.ManagedZone) bool { - return strings.ToLower(zone.Spec.DomainName) == host + zone, ok := slice.Find(zones.Items, func(zone *dns.Zone) bool { + return strings.ToLower(*zone.DNSName) == host }) if ok { - subdomain := strings.Replace(strings.ToLower(originalHost), "."+strings.ToLower(zone.Spec.DomainName), "", 1) - return &zone, subdomain, nil + subdomain := strings.Replace(strings.ToLower(originalHost), "."+strings.ToLower(*zone.DNSName), "", 1) + return zone, subdomain, nil } - return findMatchingManagedZone(originalHost, parentDomain, zones) + return findMatchingZone(originalHost, parentDomain, zones) } @@ -104,28 +102,29 @@ func gatewayDNSRecordLabels(gwKey client.ObjectKey) map[string]string { } } -func (dh *dnsHelper) buildDNSRecordForListener(gateway *gatewayapiv1.Gateway, dnsPolicy *v1alpha1.DNSPolicy, targetListener gatewayapiv1.Listener, managedZone *v1alpha1.ManagedZone) *v1alpha1.DNSRecord { +func (dh *dnsHelper) buildDNSRecordForListener(gateway *gatewayapiv1.Gateway, dnsPolicy *v1alpha2.DNSPolicy, targetListener gatewayapiv1.Listener, zone *dns.Zone) *v1alpha2.DNSRecord { - dnsRecord := &v1alpha1.DNSRecord{ + dnsRecord := &v1alpha2.DNSRecord{ ObjectMeta: metav1.ObjectMeta{ Name: dnsRecordName(gateway.Name, string(targetListener.Name)), - Namespace: managedZone.Namespace, + Namespace: dnsPolicy.Namespace, Labels: commonDNSRecordLabels(client.ObjectKeyFromObject(gateway), client.ObjectKeyFromObject(dnsPolicy)), }, - Spec: v1alpha1.DNSRecordSpec{ - ManagedZoneRef: &v1alpha1.ManagedZoneReference{ - Name: managedZone.Name, - }, + Spec: v1alpha2.DNSRecordSpec{ + ProviderRef: dnsPolicy.Spec.ProviderRef, }, } + if zone != nil { + dnsRecord.Spec.ZoneID = zone.ID + } dnsRecord.Labels[LabelListenerReference] = string(targetListener.Name) return dnsRecord } // getDNSRecordForListener returns a v1alpha1.DNSRecord, if one exists, for the given listener in the given v1alpha1.ManagedZone. -func (dh *dnsHelper) getDNSRecordForListener(ctx context.Context, listener gatewayapiv1.Listener, owner metav1.Object) (*v1alpha1.DNSRecord, error) { +func (dh *dnsHelper) getDNSRecordForListener(ctx context.Context, listener gatewayapiv1.Listener, owner metav1.Object) (*v1alpha2.DNSRecord, error) { recordName := dnsRecordName(owner.GetName(), string(listener.Name)) - dnsRecord := &v1alpha1.DNSRecord{} + dnsRecord := &v1alpha2.DNSRecord{} if err := dh.Get(ctx, client.ObjectKey{Name: recordName, Namespace: owner.GetNamespace()}, dnsRecord); err != nil { if k8serrors.IsNotFound(err) { log.Log.V(1).Info("no dnsrecord found for listener ", "listener", listener) @@ -146,21 +145,21 @@ func withGatewayListener[T metav1.Object](gateway common.GatewayWrapper, listene return obj } -func (dh *dnsHelper) setEndpoints(ctx context.Context, mcgTarget *dns.MultiClusterGatewayTarget, dnsRecord *v1alpha1.DNSRecord, listener gatewayapiv1.Listener, strategy v1alpha1.RoutingStrategy) error { +func (dh *dnsHelper) setEndpoints(ctx context.Context, mcgTarget *dns.MultiClusterGatewayTarget, dnsRecord *v1alpha2.DNSRecord, listener gatewayapiv1.Listener, strategy v1alpha2.RoutingStrategy) error { old := dnsRecord.DeepCopy() gwListenerHost := string(*listener.Hostname) - var endpoints []*v1alpha1.Endpoint + var endpoints []*v1alpha2.Endpoint //Health Checks currently modify endpoints so we have to keep existing ones in order to not lose health check ids - currentEndpoints := make(map[string]*v1alpha1.Endpoint, len(dnsRecord.Spec.Endpoints)) + currentEndpoints := make(map[string]*v1alpha2.Endpoint, len(dnsRecord.Spec.Endpoints)) for _, endpoint := range dnsRecord.Spec.Endpoints { currentEndpoints[endpoint.SetID()] = endpoint } switch strategy { - case v1alpha1.SimpleRoutingStrategy: + case v1alpha2.SimpleRoutingStrategy: endpoints = dh.getSimpleEndpoints(mcgTarget, gwListenerHost, currentEndpoints) - case v1alpha1.LoadBalancedRoutingStrategy: + case v1alpha2.LoadBalancedRoutingStrategy: endpoints = dh.getLoadBalancedEndpoints(mcgTarget, gwListenerHost, currentEndpoints) default: return fmt.Errorf("%w : %s", ErrUnknownRoutingStrategy, strategy) @@ -181,10 +180,10 @@ func (dh *dnsHelper) setEndpoints(ctx context.Context, mcgTarget *dns.MultiClust // getSimpleEndpoints returns the endpoints for the given MultiClusterGatewayTarget using the simple routing strategy -func (dh *dnsHelper) getSimpleEndpoints(mcgTarget *dns.MultiClusterGatewayTarget, hostname string, currentEndpoints map[string]*v1alpha1.Endpoint) []*v1alpha1.Endpoint { +func (dh *dnsHelper) getSimpleEndpoints(mcgTarget *dns.MultiClusterGatewayTarget, hostname string, currentEndpoints map[string]*v1alpha2.Endpoint) []*v1alpha2.Endpoint { var ( - endpoints []*v1alpha1.Endpoint + endpoints []*v1alpha2.Endpoint ipValues []string hostValues []string ) @@ -200,13 +199,13 @@ func (dh *dnsHelper) getSimpleEndpoints(mcgTarget *dns.MultiClusterGatewayTarget } if len(ipValues) > 0 { - endpoint := createOrUpdateEndpoint(hostname, ipValues, v1alpha1.ARecordType, "", dns.DefaultTTL, currentEndpoints) + endpoint := createOrUpdateEndpoint(hostname, ipValues, v1alpha2.ARecordType, "", dns.DefaultTTL, currentEndpoints) endpoints = append(endpoints, endpoint) } //ToDO This could possibly result in an invalid record since you can't have multiple CNAME target values https://github.com/Kuadrant/multicluster-gateway-controller/issues/663 if len(hostValues) > 0 { - endpoint := createOrUpdateEndpoint(hostname, hostValues, v1alpha1.CNAMERecordType, "", dns.DefaultTTL, currentEndpoints) + endpoint := createOrUpdateEndpoint(hostname, hostValues, v1alpha2.CNAMERecordType, "", dns.DefaultTTL, currentEndpoints) endpoints = append(endpoints, endpoint) } @@ -252,7 +251,7 @@ func (dh *dnsHelper) getSimpleEndpoints(mcgTarget *dns.MultiClusterGatewayTarget // ab2.lb-a1b2.shop.example.com A 192.22.2.3 // ab3.lb-a1b2.shop.example.com A 192.22.2.4 -func (dh *dnsHelper) getLoadBalancedEndpoints(mcgTarget *dns.MultiClusterGatewayTarget, hostname string, currentEndpoints map[string]*v1alpha1.Endpoint) []*v1alpha1.Endpoint { +func (dh *dnsHelper) getLoadBalancedEndpoints(mcgTarget *dns.MultiClusterGatewayTarget, hostname string, currentEndpoints map[string]*v1alpha2.Endpoint) []*v1alpha2.Endpoint { cnameHost := hostname if isWildCardHost(hostname) { @@ -260,15 +259,15 @@ func (dh *dnsHelper) getLoadBalancedEndpoints(mcgTarget *dns.MultiClusterGateway } var ( - endpoints []*v1alpha1.Endpoint - endpoint *v1alpha1.Endpoint - defaultEndpoint *v1alpha1.Endpoint + endpoints []*v1alpha2.Endpoint + endpoint *v1alpha2.Endpoint + defaultEndpoint *v1alpha2.Endpoint ) lbName := strings.ToLower(fmt.Sprintf("lb-%s.%s", mcgTarget.GetShortCode(), cnameHost)) for geoCode, cgwTargets := range mcgTarget.GroupTargetsByGeo() { geoLbName := strings.ToLower(fmt.Sprintf("%s.%s", geoCode, lbName)) - var clusterEndpoints []*v1alpha1.Endpoint + var clusterEndpoints []*v1alpha2.Endpoint for _, cgwTarget := range cgwTargets { var ipValues []string @@ -283,13 +282,13 @@ func (dh *dnsHelper) getLoadBalancedEndpoints(mcgTarget *dns.MultiClusterGateway if len(ipValues) > 0 { clusterLbName := strings.ToLower(fmt.Sprintf("%s.%s", cgwTarget.GetShortCode(), lbName)) - endpoint = createOrUpdateEndpoint(clusterLbName, ipValues, v1alpha1.ARecordType, "", dns.DefaultTTL, currentEndpoints) + endpoint = createOrUpdateEndpoint(clusterLbName, ipValues, v1alpha2.ARecordType, "", dns.DefaultTTL, currentEndpoints) clusterEndpoints = append(clusterEndpoints, endpoint) hostValues = append(hostValues, clusterLbName) } for _, hostValue := range hostValues { - endpoint = createOrUpdateEndpoint(geoLbName, []string{hostValue}, v1alpha1.CNAMERecordType, hostValue, dns.DefaultTTL, currentEndpoints) + endpoint = createOrUpdateEndpoint(geoLbName, []string{hostValue}, v1alpha2.CNAMERecordType, hostValue, dns.DefaultTTL, currentEndpoints) endpoint.SetProviderSpecific(dns.ProviderSpecificWeight, strconv.Itoa(cgwTarget.GetWeight())) clusterEndpoints = append(clusterEndpoints, endpoint) } @@ -300,7 +299,7 @@ func (dh *dnsHelper) getLoadBalancedEndpoints(mcgTarget *dns.MultiClusterGateway endpoints = append(endpoints, clusterEndpoints...) //Create lbName CNAME (lb-a1b2.shop.example.com -> default.lb-a1b2.shop.example.com) - endpoint = createOrUpdateEndpoint(lbName, []string{geoLbName}, v1alpha1.CNAMERecordType, string(geoCode), dns.DefaultCnameTTL, currentEndpoints) + endpoint = createOrUpdateEndpoint(lbName, []string{geoLbName}, v1alpha2.CNAMERecordType, string(geoCode), dns.DefaultCnameTTL, currentEndpoints) //Deal with the default geo endpoint first if geoCode.IsDefaultCode() { @@ -309,7 +308,7 @@ func (dh *dnsHelper) getLoadBalancedEndpoints(mcgTarget *dns.MultiClusterGateway continue } else if (geoCode == mcgTarget.GetDefaultGeo()) || defaultEndpoint == nil { // Ensure that a `defaultEndpoint` is always set, but the expected default takes precedence - defaultEndpoint = createOrUpdateEndpoint(lbName, []string{geoLbName}, v1alpha1.CNAMERecordType, "default", dns.DefaultCnameTTL, currentEndpoints) + defaultEndpoint = createOrUpdateEndpoint(lbName, []string{geoLbName}, v1alpha2.CNAMERecordType, "default", dns.DefaultCnameTTL, currentEndpoints) } endpoint.SetProviderSpecific(dns.ProviderSpecificGeoCode, string(geoCode)) @@ -322,19 +321,19 @@ func (dh *dnsHelper) getLoadBalancedEndpoints(mcgTarget *dns.MultiClusterGateway defaultEndpoint.SetProviderSpecific(dns.ProviderSpecificGeoCode, string(dns.WildcardGeo)) endpoints = append(endpoints, defaultEndpoint) //Create gwListenerHost CNAME (shop.example.com -> lb-a1b2.shop.example.com) - endpoint = createOrUpdateEndpoint(hostname, []string{lbName}, v1alpha1.CNAMERecordType, "", dns.DefaultCnameTTL, currentEndpoints) + endpoint = createOrUpdateEndpoint(hostname, []string{lbName}, v1alpha2.CNAMERecordType, "", dns.DefaultCnameTTL, currentEndpoints) endpoints = append(endpoints, endpoint) } return endpoints } -func createOrUpdateEndpoint(dnsName string, targets v1alpha1.Targets, recordType v1alpha1.DNSRecordType, setIdentifier string, - recordTTL v1alpha1.TTL, currentEndpoints map[string]*v1alpha1.Endpoint) (endpoint *v1alpha1.Endpoint) { +func createOrUpdateEndpoint(dnsName string, targets v1alpha2.Targets, recordType v1alpha2.DNSRecordType, setIdentifier string, + recordTTL v1alpha2.TTL, currentEndpoints map[string]*v1alpha2.Endpoint) (endpoint *v1alpha2.Endpoint) { ok := false endpointID := dnsName + setIdentifier if endpoint, ok = currentEndpoints[endpointID]; !ok { - endpoint = &v1alpha1.Endpoint{} + endpoint = &v1alpha2.Endpoint{} if setIdentifier != "" { endpoint.SetIdentifier = setIdentifier } @@ -348,7 +347,7 @@ func createOrUpdateEndpoint(dnsName string, targets v1alpha1.Targets, recordType // removeDNSForDeletedListeners remove any DNSRecords that are associated with listeners that no longer exist in this gateway func (dh *dnsHelper) removeDNSForDeletedListeners(ctx context.Context, upstreamGateway *gatewayapiv1.Gateway) error { - dnsList := &v1alpha1.DNSRecordList{} + dnsList := &v1alpha2.DNSRecordList{} //List all dns records that belong to this gateway labelSelector := &client.MatchingLabels{ LabelGatewayReference: upstreamGateway.Name, @@ -375,28 +374,14 @@ func (dh *dnsHelper) removeDNSForDeletedListeners(ctx context.Context, upstreamG } -func (dh *dnsHelper) getManagedZoneForListener(ctx context.Context, ns string, listener gatewayapiv1.Listener) (*v1alpha1.ManagedZone, error) { - var managedZones v1alpha1.ManagedZoneList - if err := dh.List(ctx, &managedZones, client.InNamespace(ns)); err != nil { - log.FromContext(ctx).Error(err, "unable to list managed zones for gateway ", "in ns", ns) - return nil, err - } - host := string(*listener.Hostname) - mz, _, err := findMatchingManagedZone(host, host, managedZones.Items) - return mz, err -} - func dnsRecordName(gatewayName, listenerName string) string { return fmt.Sprintf("%s-%s", gatewayName, listenerName) } -func (dh *dnsHelper) createDNSRecordForListener(ctx context.Context, gateway *gatewayapiv1.Gateway, dnsPolicy *v1alpha1.DNSPolicy, mz *v1alpha1.ManagedZone, listener gatewayapiv1.Listener) (*v1alpha1.DNSRecord, error) { +func (dh *dnsHelper) createDNSRecordForListener(ctx context.Context, gateway *gatewayapiv1.Gateway, dnsPolicy *v1alpha2.DNSPolicy, listener gatewayapiv1.Listener, zone *dns.Zone) (*v1alpha2.DNSRecord, error) { logger := log.FromContext(ctx) logger.Info("creating dns for gateway listener", "listener", listener.Name) - dnsRecord := dh.buildDNSRecordForListener(gateway, dnsPolicy, listener, mz) - if err := controllerutil.SetControllerReference(mz, dnsRecord, dh.Scheme()); err != nil { - return dnsRecord, err - } + dnsRecord := dh.buildDNSRecordForListener(gateway, dnsPolicy, listener, zone) err := dh.Create(ctx, dnsRecord, &client.CreateOptions{}) if err != nil && !k8serrors.IsAlreadyExists(err) { @@ -413,7 +398,7 @@ func (dh *dnsHelper) createDNSRecordForListener(ctx context.Context, gateway *ga func (dh *dnsHelper) deleteDNSRecordForListener(ctx context.Context, owner metav1.Object, listener gatewayapiv1.Listener) error { recordName := dnsRecordName(owner.GetName(), string(listener.Name)) - dnsRecord := v1alpha1.DNSRecord{ + dnsRecord := v1alpha2.DNSRecord{ ObjectMeta: metav1.ObjectMeta{ Name: recordName, Namespace: owner.GetNamespace(), @@ -426,7 +411,7 @@ func isWildCardHost(host string) bool { return strings.HasPrefix(host, "*") } -func (dh *dnsHelper) getDNSHealthCheckProbes(ctx context.Context, gateway *gatewayapiv1.Gateway, dnsPolicy *v1alpha1.DNSPolicy) ([]*v1alpha1.DNSHealthCheckProbe, error) { +func (dh *dnsHelper) getDNSHealthCheckProbes(ctx context.Context, gateway *gatewayapiv1.Gateway, dnsPolicy *v1alpha2.DNSPolicy) ([]*v1alpha1.DNSHealthCheckProbe, error) { list := &v1alpha1.DNSHealthCheckProbeList{} if err := dh.List(ctx, list, &client.ListOptions{ LabelSelector: labels.SelectorFromSet(commonDNSRecordLabels(client.ObjectKeyFromObject(gateway), client.ObjectKeyFromObject(dnsPolicy))), diff --git a/pkg/controllers/dnspolicy/dns_helper_test.go b/pkg/controllers/dnspolicy/dns_helper_test.go index 198a7dd35..e23a758fc 100644 --- a/pkg/controllers/dnspolicy/dns_helper_test.go +++ b/pkg/controllers/dnspolicy/dns_helper_test.go @@ -17,6 +17,7 @@ import ( gatewayapiv1 "sigs.k8s.io/gateway-api/apis/v1" "github.com/Kuadrant/multicluster-gateway-controller/pkg/apis/v1alpha1" + "github.com/Kuadrant/multicluster-gateway-controller/pkg/apis/v1alpha2" "github.com/Kuadrant/multicluster-gateway-controller/pkg/dns" "github.com/Kuadrant/multicluster-gateway-controller/pkg/utils" testutil "github.com/Kuadrant/multicluster-gateway-controller/test/util" @@ -27,6 +28,9 @@ func testScheme(t *testing.T) *runtime.Scheme { if err := v1alpha1.AddToScheme(scheme); err != nil { t.Fatalf("falied to add work scheme %s ", err) } + if err := v1alpha2.AddToScheme(scheme); err != nil { + t.Fatalf("falied to add work scheme %s ", err) + } if err := gatewayapiv1.AddToScheme(scheme); err != nil { t.Fatalf("falied to add work scheme %s ", err) } @@ -42,8 +46,8 @@ func getTestListener(hostName string) gatewayapiv1.Listener { } func TestSetProviderSpecific(t *testing.T) { - endpoint := &v1alpha1.Endpoint{ - ProviderSpecific: []v1alpha1.ProviderSpecificProperty{ + endpoint := &v1alpha2.Endpoint{ + ProviderSpecific: []v1alpha2.ProviderSpecificProperty{ {Name: "weight", Value: "120"}, }, } @@ -63,16 +67,16 @@ func Test_dnsHelper_createDNSRecordForListener(t *testing.T) { testListenerName = "test" ) type args struct { - gateway *gatewayapiv1.Gateway - dnsPolicy *v1alpha1.DNSPolicy - managedZone *v1alpha1.ManagedZone - listener gatewayapiv1.Listener + gateway *gatewayapiv1.Gateway + dnsPolicy *v1alpha2.DNSPolicy + zone *dns.Zone + listener gatewayapiv1.Listener } testCases := []struct { name string args args - recordList *v1alpha1.DNSRecordList - wantRecord *v1alpha1.DNSRecord + recordList *v1alpha2.DNSRecordList + wantRecord *v1alpha2.DNSRecord wantErr bool }{ { @@ -85,24 +89,19 @@ func Test_dnsHelper_createDNSRecordForListener(t *testing.T) { }, }, listener: getTestListener("test.domain.com"), - dnsPolicy: &v1alpha1.DNSPolicy{ + dnsPolicy: &v1alpha2.DNSPolicy{ ObjectMeta: v1.ObjectMeta{ Name: "tstpolicy", Namespace: "test", }, }, - managedZone: &v1alpha1.ManagedZone{ - ObjectMeta: v1.ObjectMeta{ - Name: "mz", - Namespace: "test", - }, - Spec: v1alpha1.ManagedZoneSpec{ - DomainName: "domain.com", - }, + zone: &dns.Zone{ + ID: testutil.Pointer("mz"), + DNSName: testutil.Pointer("domain.com"), }, }, - recordList: &v1alpha1.DNSRecordList{}, - wantRecord: &v1alpha1.DNSRecord{ + recordList: &v1alpha2.DNSRecordList{}, + wantRecord: &v1alpha2.DNSRecord{ ObjectMeta: v1.ObjectMeta{ Name: dnsRecordName(testGatewayName, testListenerName), Namespace: "test", @@ -113,21 +112,10 @@ func Test_dnsHelper_createDNSRecordForListener(t *testing.T) { LabelGatewayReference: "tstgateway", LabelListenerReference: testListenerName, }, - OwnerReferences: []v1.OwnerReference{ - { - APIVersion: "kuadrant.io/v1alpha1", - Kind: "ManagedZone", - Name: "mz", - Controller: testutil.Pointer(true), - BlockOwnerDeletion: testutil.Pointer(true), - }, - }, ResourceVersion: "1", }, - Spec: v1alpha1.DNSRecordSpec{ - ManagedZoneRef: &v1alpha1.ManagedZoneReference{ - Name: "mz", - }, + Spec: v1alpha2.DNSRecordSpec{ + ZoneID: testutil.Pointer("mz"), }, }, }, @@ -141,24 +129,19 @@ func Test_dnsHelper_createDNSRecordForListener(t *testing.T) { }, }, listener: getTestListener("test.domain.com"), - dnsPolicy: &v1alpha1.DNSPolicy{ + dnsPolicy: &v1alpha2.DNSPolicy{ ObjectMeta: v1.ObjectMeta{ Name: "tstpolicy", Namespace: "test", }, }, - managedZone: &v1alpha1.ManagedZone{ - ObjectMeta: v1.ObjectMeta{ - Name: "mz", - Namespace: "test", - }, - Spec: v1alpha1.ManagedZoneSpec{ - DomainName: "domain.com", - }, + zone: &dns.Zone{ + ID: testutil.Pointer("mz"), + DNSName: testutil.Pointer("domain.com"), }, }, - recordList: &v1alpha1.DNSRecordList{ - Items: []v1alpha1.DNSRecord{ + recordList: &v1alpha2.DNSRecordList{ + Items: []v1alpha2.DNSRecord{ { ObjectMeta: v1.ObjectMeta{ Name: dnsRecordName(testGatewayName, testListenerName), @@ -167,7 +150,7 @@ func Test_dnsHelper_createDNSRecordForListener(t *testing.T) { }, }, }, - wantRecord: &v1alpha1.DNSRecord{ + wantRecord: &v1alpha2.DNSRecord{ ObjectMeta: v1.ObjectMeta{ Name: dnsRecordName(testGatewayName, testListenerName), Namespace: "test", @@ -175,7 +158,7 @@ func Test_dnsHelper_createDNSRecordForListener(t *testing.T) { }, TypeMeta: v1.TypeMeta{ Kind: "DNSRecord", - APIVersion: "kuadrant.io/v1alpha1", + APIVersion: "kuadrant.io/v1alpha2", }, }, }, @@ -189,26 +172,21 @@ func Test_dnsHelper_createDNSRecordForListener(t *testing.T) { }, }, listener: getTestListener("*.domain.com"), - dnsPolicy: &v1alpha1.DNSPolicy{ + dnsPolicy: &v1alpha2.DNSPolicy{ ObjectMeta: v1.ObjectMeta{ Name: "tstpolicy", Namespace: "test", }, }, - managedZone: &v1alpha1.ManagedZone{ - ObjectMeta: v1.ObjectMeta{ - Name: "mz", - Namespace: "test", - }, - Spec: v1alpha1.ManagedZoneSpec{ - DomainName: "domain.com", - }, + zone: &dns.Zone{ + ID: testutil.Pointer("mz"), + DNSName: testutil.Pointer("domain.com"), }, }, - recordList: &v1alpha1.DNSRecordList{ - Items: []v1alpha1.DNSRecord{}, + recordList: &v1alpha2.DNSRecordList{ + Items: []v1alpha2.DNSRecord{}, }, - wantRecord: &v1alpha1.DNSRecord{ + wantRecord: &v1alpha2.DNSRecord{ ObjectMeta: v1.ObjectMeta{ Name: dnsRecordName(testGatewayName, testListenerName), Namespace: "test", @@ -219,21 +197,10 @@ func Test_dnsHelper_createDNSRecordForListener(t *testing.T) { LabelGatewayReference: "tstgateway", LabelListenerReference: testListenerName, }, - OwnerReferences: []v1.OwnerReference{ - { - APIVersion: "kuadrant.io/v1alpha1", - Kind: "ManagedZone", - Name: "mz", - Controller: testutil.Pointer(true), - BlockOwnerDeletion: testutil.Pointer(true), - }, - }, ResourceVersion: "1", }, - Spec: v1alpha1.DNSRecordSpec{ - ManagedZoneRef: &v1alpha1.ManagedZoneReference{ - Name: "mz", - }, + Spec: v1alpha2.DNSRecordSpec{ + ZoneID: testutil.Pointer("mz"), }, }, }, @@ -243,7 +210,7 @@ func Test_dnsHelper_createDNSRecordForListener(t *testing.T) { f := fake.NewClientBuilder().WithScheme(testScheme(t)).WithLists(testCase.recordList).Build() s := dnsHelper{Client: f} - gotRecord, err := s.createDNSRecordForListener(context.TODO(), testCase.args.gateway, testCase.args.dnsPolicy, testCase.args.managedZone, testCase.args.listener) + gotRecord, err := s.createDNSRecordForListener(context.TODO(), testCase.args.gateway, testCase.args.dnsPolicy, testCase.args.listener, testCase.args.zone) if (err != nil) != testCase.wantErr { t.Errorf("CreateDNSRecord() error = %v, wantErr %v", err, testCase.wantErr) return @@ -255,24 +222,21 @@ func Test_dnsHelper_createDNSRecordForListener(t *testing.T) { } } -func Test_dnsHelper_findMatchingManagedZone(t *testing.T) { +func Test_dnsHelper_findMatchingZone(t *testing.T) { testCases := []struct { name string Host string - Zones []v1alpha1.ManagedZone - Assert func(t *testing.T, zone *v1alpha1.ManagedZone, subdomain string, err error) + Zones dns.ZoneList + Assert func(t *testing.T, zone *dns.Zone, subdomain string, err error) }{ { name: "finds the matching managed zone", Host: "sub.domain.test.example.com", - Zones: []v1alpha1.ManagedZone{ - { - ObjectMeta: v1.ObjectMeta{ - Name: "example.com", - Namespace: "test", - }, - Spec: v1alpha1.ManagedZoneSpec{ - DomainName: "example.com", + Zones: dns.ZoneList{ + Items: []*dns.Zone{ + { + ID: testutil.Pointer("example.com"), + DNSName: testutil.Pointer("example.com"), }, }, }, @@ -281,23 +245,15 @@ func Test_dnsHelper_findMatchingManagedZone(t *testing.T) { { name: "finds the most exactly matching managed zone", Host: "sub.domain.test.example.com", - Zones: []v1alpha1.ManagedZone{ - { - ObjectMeta: v1.ObjectMeta{ - Name: "example.com", - Namespace: "test", - }, - Spec: v1alpha1.ManagedZoneSpec{ - DomainName: "example.com", - }, - }, - { - ObjectMeta: v1.ObjectMeta{ - Name: "test.example.com", - Namespace: "test", + Zones: dns.ZoneList{ + Items: []*dns.Zone{ + { + ID: testutil.Pointer("example.com"), + DNSName: testutil.Pointer("example.com"), }, - Spec: v1alpha1.ManagedZoneSpec{ - DomainName: "test.example.com", + { + ID: testutil.Pointer("test.example.com"), + DNSName: testutil.Pointer("test.example.com"), }, }, }, @@ -306,14 +262,11 @@ func Test_dnsHelper_findMatchingManagedZone(t *testing.T) { { name: "returns a single subdomain", Host: "sub.test.example.com", - Zones: []v1alpha1.ManagedZone{ - { - ObjectMeta: v1.ObjectMeta{ - Name: "test.example.com", - Namespace: "test", - }, - Spec: v1alpha1.ManagedZoneSpec{ - DomainName: "test.example.com", + Zones: dns.ZoneList{ + Items: []*dns.Zone{ + { + ID: testutil.Pointer("test.example.com"), + DNSName: testutil.Pointer("test.example.com"), }, }, }, @@ -322,14 +275,11 @@ func Test_dnsHelper_findMatchingManagedZone(t *testing.T) { { name: "returns an error when nothing matches", Host: "sub.test.example.com", - Zones: []v1alpha1.ManagedZone{ - { - ObjectMeta: v1.ObjectMeta{ - Name: "testing.example.com", - Namespace: "test", - }, - Spec: v1alpha1.ManagedZoneSpec{ - DomainName: "testing.example.com", + Zones: dns.ZoneList{ + Items: []*dns.Zone{ + { + ID: testutil.Pointer("testing.example.com"), + DNSName: testutil.Pointer("testing.example.com"), }, }, }, @@ -338,14 +288,11 @@ func Test_dnsHelper_findMatchingManagedZone(t *testing.T) { { name: "handles TLD with a dot", Host: "sub.domain.test.example.co.uk", - Zones: []v1alpha1.ManagedZone{ - { - ObjectMeta: v1.ObjectMeta{ - Name: "example.co.uk", - Namespace: "test", - }, - Spec: v1alpha1.ManagedZoneSpec{ - DomainName: "example.co.uk", + Zones: dns.ZoneList{ + Items: []*dns.Zone{ + { + ID: testutil.Pointer("example.co.uk"), + DNSName: testutil.Pointer("example.co.uk"), }, }, }, @@ -354,24 +301,23 @@ func Test_dnsHelper_findMatchingManagedZone(t *testing.T) { { name: "TLD with a . will not match against a managedzone of the TLD", Host: "sub.domain.test.example.co.uk", - Zones: []v1alpha1.ManagedZone{ - { - ObjectMeta: v1.ObjectMeta{ - Name: "co.uk", - Namespace: "test", - }, - Spec: v1alpha1.ManagedZoneSpec{ - DomainName: "co.uk", + Zones: dns.ZoneList{ + Items: []*dns.Zone{ + { + ID: testutil.Pointer("co.uk"), + DNSName: testutil.Pointer("co.uk"), }, }, }, Assert: assertSub("", "", "no valid zone found"), }, { - name: "no managed zones for host give error", - Host: "sub.domain.test.example.co.uk", - Zones: []v1alpha1.ManagedZone{}, - Assert: func(t *testing.T, zone *v1alpha1.ManagedZone, subdomain string, err error) { + name: "no managed zones for host give error", + Host: "sub.domain.test.example.co.uk", + Zones: dns.ZoneList{ + Items: []*dns.Zone{}, + }, + Assert: func(t *testing.T, zone *dns.Zone, subdomain string, err error) { if err == nil { t.Fatalf("expected error, got %v", err) } @@ -380,14 +326,11 @@ func Test_dnsHelper_findMatchingManagedZone(t *testing.T) { { name: "should not match when host and zone domain name are identical", Host: "test.example.com", - Zones: []v1alpha1.ManagedZone{ - { - ObjectMeta: v1.ObjectMeta{ - Name: "test.example.com", - Namespace: "test", - }, - Spec: v1alpha1.ManagedZoneSpec{ - DomainName: "test.example.com", + Zones: dns.ZoneList{ + Items: []*dns.Zone{ + { + ID: testutil.Pointer("test.example.com"), + DNSName: testutil.Pointer("test.example.com"), }, }, }, @@ -397,7 +340,7 @@ func Test_dnsHelper_findMatchingManagedZone(t *testing.T) { for _, testCase := range testCases { t.Run(testCase.name, func(t *testing.T) { - mx, subDomain, err := findMatchingManagedZone(testCase.Host, testCase.Host, testCase.Zones) + mx, subDomain, err := findMatchingZone(testCase.Host, testCase.Host, testCase.Zones) testCase.Assert(t, mx, subDomain, err) }) } @@ -409,8 +352,8 @@ func Test_dnsHelper_setEndpoints(t *testing.T) { name string mcgTarget *dns.MultiClusterGatewayTarget listener gatewayapiv1.Listener - dnsRecord *v1alpha1.DNSRecord - wantSpec *v1alpha1.DNSRecordSpec + dnsRecord *v1alpha2.DNSRecord + wantSpec *v1alpha2.DNSRecordSpec wantErr bool }{ { @@ -464,13 +407,13 @@ func Test_dnsHelper_setEndpoints(t *testing.T) { }, }, }, - dnsRecord: &v1alpha1.DNSRecord{ + dnsRecord: &v1alpha2.DNSRecord{ ObjectMeta: v1.ObjectMeta{ Name: "test.example.com", }, }, - wantSpec: &v1alpha1.DNSRecordSpec{ - Endpoints: []*v1alpha1.Endpoint{ + wantSpec: &v1alpha2.DNSRecordSpec{ + Endpoints: []*v1alpha2.Endpoint{ { DNSName: "20qri0.lb-ocnswx.example.com", Targets: []string{"1.1.1.1", "2.2.2.2"}, @@ -483,7 +426,7 @@ func Test_dnsHelper_setEndpoints(t *testing.T) { RecordType: "CNAME", SetIdentifier: "20qri0.lb-ocnswx.example.com", RecordTTL: dns.DefaultTTL, - ProviderSpecific: []v1alpha1.ProviderSpecificProperty{ + ProviderSpecific: []v1alpha2.ProviderSpecificProperty{ { Name: "weight", Value: "120", @@ -496,7 +439,7 @@ func Test_dnsHelper_setEndpoints(t *testing.T) { RecordType: "CNAME", SetIdentifier: "mylb.example.com", RecordTTL: dns.DefaultTTL, - ProviderSpecific: []v1alpha1.ProviderSpecificProperty{ + ProviderSpecific: []v1alpha2.ProviderSpecificProperty{ { Name: "weight", Value: "120", @@ -509,7 +452,7 @@ func Test_dnsHelper_setEndpoints(t *testing.T) { RecordType: "CNAME", SetIdentifier: "default", RecordTTL: dns.DefaultCnameTTL, - ProviderSpecific: []v1alpha1.ProviderSpecificProperty{ + ProviderSpecific: []v1alpha2.ProviderSpecificProperty{ { Name: "geo-code", Value: "*", @@ -575,19 +518,19 @@ func Test_dnsHelper_setEndpoints(t *testing.T) { Weight: testutil.Pointer(120), }, }, - LoadBalancing: &v1alpha1.LoadBalancingSpec{ - Geo: &v1alpha1.LoadBalancingGeo{ + LoadBalancing: &v1alpha2.LoadBalancingSpec{ + Geo: &v1alpha2.LoadBalancingGeo{ DefaultGeo: "NA", }, }, }, - dnsRecord: &v1alpha1.DNSRecord{ + dnsRecord: &v1alpha2.DNSRecord{ ObjectMeta: v1.ObjectMeta{ Name: "gw-test", }, }, - wantSpec: &v1alpha1.DNSRecordSpec{ - Endpoints: []*v1alpha1.Endpoint{ + wantSpec: &v1alpha2.DNSRecordSpec{ + Endpoints: []*v1alpha2.Endpoint{ { DNSName: "20qri0.lb-ocnswx.example.com", Targets: []string{"1.1.1.1", "2.2.2.2"}, @@ -600,7 +543,7 @@ func Test_dnsHelper_setEndpoints(t *testing.T) { RecordType: "CNAME", SetIdentifier: "20qri0.lb-ocnswx.example.com", RecordTTL: dns.DefaultTTL, - ProviderSpecific: []v1alpha1.ProviderSpecificProperty{ + ProviderSpecific: []v1alpha2.ProviderSpecificProperty{ { Name: "weight", Value: "120", @@ -613,7 +556,7 @@ func Test_dnsHelper_setEndpoints(t *testing.T) { RecordType: "CNAME", SetIdentifier: "mylb.example.com", RecordTTL: dns.DefaultTTL, - ProviderSpecific: []v1alpha1.ProviderSpecificProperty{ + ProviderSpecific: []v1alpha2.ProviderSpecificProperty{ { Name: "weight", Value: "120", @@ -626,7 +569,7 @@ func Test_dnsHelper_setEndpoints(t *testing.T) { RecordType: "CNAME", SetIdentifier: "default", RecordTTL: dns.DefaultCnameTTL, - ProviderSpecific: []v1alpha1.ProviderSpecificProperty{ + ProviderSpecific: []v1alpha2.ProviderSpecificProperty{ { Name: "geo-code", Value: "*", @@ -639,7 +582,7 @@ func Test_dnsHelper_setEndpoints(t *testing.T) { RecordType: "CNAME", SetIdentifier: "NA", RecordTTL: dns.DefaultCnameTTL, - ProviderSpecific: []v1alpha1.ProviderSpecificProperty{ + ProviderSpecific: []v1alpha2.ProviderSpecificProperty{ { Name: "geo-code", Value: "NA", @@ -652,7 +595,7 @@ func Test_dnsHelper_setEndpoints(t *testing.T) { RecordType: "CNAME", SetIdentifier: "IE", RecordTTL: dns.DefaultCnameTTL, - ProviderSpecific: []v1alpha1.ProviderSpecificProperty{ + ProviderSpecific: []v1alpha2.ProviderSpecificProperty{ { Name: "geo-code", Value: "IE", @@ -723,13 +666,13 @@ func Test_dnsHelper_setEndpoints(t *testing.T) { }, }, }, - dnsRecord: &v1alpha1.DNSRecord{ + dnsRecord: &v1alpha2.DNSRecord{ ObjectMeta: v1.ObjectMeta{ Name: "test.example.com", }, }, - wantSpec: &v1alpha1.DNSRecordSpec{ - Endpoints: []*v1alpha1.Endpoint{ + wantSpec: &v1alpha2.DNSRecordSpec{ + Endpoints: []*v1alpha2.Endpoint{ { DNSName: "20qri0.lb-0ecjaw.test.example.com", Targets: []string{"1.1.1.1", "2.2.2.2"}, @@ -742,7 +685,7 @@ func Test_dnsHelper_setEndpoints(t *testing.T) { RecordType: "CNAME", SetIdentifier: "20qri0.lb-0ecjaw.test.example.com", RecordTTL: dns.DefaultTTL, - ProviderSpecific: []v1alpha1.ProviderSpecificProperty{ + ProviderSpecific: []v1alpha2.ProviderSpecificProperty{ { Name: "weight", Value: "120", @@ -755,7 +698,7 @@ func Test_dnsHelper_setEndpoints(t *testing.T) { RecordType: "CNAME", SetIdentifier: "mylb.example.com", RecordTTL: dns.DefaultTTL, - ProviderSpecific: []v1alpha1.ProviderSpecificProperty{ + ProviderSpecific: []v1alpha2.ProviderSpecificProperty{ { Name: "weight", Value: "120", @@ -768,7 +711,7 @@ func Test_dnsHelper_setEndpoints(t *testing.T) { RecordType: "CNAME", SetIdentifier: "default", RecordTTL: dns.DefaultCnameTTL, - ProviderSpecific: []v1alpha1.ProviderSpecificProperty{ + ProviderSpecific: []v1alpha2.ProviderSpecificProperty{ { Name: "geo-code", Value: "*", @@ -835,19 +778,19 @@ func Test_dnsHelper_setEndpoints(t *testing.T) { Weight: testutil.Pointer(120), }, }, - LoadBalancing: &v1alpha1.LoadBalancingSpec{ - Geo: &v1alpha1.LoadBalancingGeo{ + LoadBalancing: &v1alpha2.LoadBalancingSpec{ + Geo: &v1alpha2.LoadBalancingGeo{ DefaultGeo: "NA", }, }, }, - dnsRecord: &v1alpha1.DNSRecord{ + dnsRecord: &v1alpha2.DNSRecord{ ObjectMeta: v1.ObjectMeta{ Name: "test.example.com", }, }, - wantSpec: &v1alpha1.DNSRecordSpec{ - Endpoints: []*v1alpha1.Endpoint{ + wantSpec: &v1alpha2.DNSRecordSpec{ + Endpoints: []*v1alpha2.Endpoint{ { DNSName: "20qri0.lb-ocnswx.test.example.com", Targets: []string{"1.1.1.1", "2.2.2.2"}, @@ -860,7 +803,7 @@ func Test_dnsHelper_setEndpoints(t *testing.T) { RecordType: "CNAME", SetIdentifier: "20qri0.lb-ocnswx.test.example.com", RecordTTL: dns.DefaultTTL, - ProviderSpecific: []v1alpha1.ProviderSpecificProperty{ + ProviderSpecific: []v1alpha2.ProviderSpecificProperty{ { Name: "weight", Value: "120", @@ -873,7 +816,7 @@ func Test_dnsHelper_setEndpoints(t *testing.T) { RecordType: "CNAME", SetIdentifier: "mylb.example.com", RecordTTL: dns.DefaultTTL, - ProviderSpecific: []v1alpha1.ProviderSpecificProperty{ + ProviderSpecific: []v1alpha2.ProviderSpecificProperty{ { Name: "weight", Value: "120", @@ -886,7 +829,7 @@ func Test_dnsHelper_setEndpoints(t *testing.T) { RecordType: "CNAME", SetIdentifier: "default", RecordTTL: dns.DefaultCnameTTL, - ProviderSpecific: []v1alpha1.ProviderSpecificProperty{ + ProviderSpecific: []v1alpha2.ProviderSpecificProperty{ { Name: "geo-code", Value: "*", @@ -899,7 +842,7 @@ func Test_dnsHelper_setEndpoints(t *testing.T) { RecordType: "CNAME", SetIdentifier: "NA", RecordTTL: dns.DefaultCnameTTL, - ProviderSpecific: []v1alpha1.ProviderSpecificProperty{ + ProviderSpecific: []v1alpha2.ProviderSpecificProperty{ { Name: "geo-code", Value: "NA", @@ -912,7 +855,7 @@ func Test_dnsHelper_setEndpoints(t *testing.T) { RecordType: "CNAME", SetIdentifier: "IE", RecordTTL: dns.DefaultCnameTTL, - ProviderSpecific: []v1alpha1.ProviderSpecificProperty{ + ProviderSpecific: []v1alpha2.ProviderSpecificProperty{ { Name: "geo-code", Value: "IE", @@ -965,19 +908,19 @@ func Test_dnsHelper_setEndpoints(t *testing.T) { Weight: testutil.Pointer(120), }, }, - LoadBalancing: &v1alpha1.LoadBalancingSpec{ - Geo: &v1alpha1.LoadBalancingGeo{ + LoadBalancing: &v1alpha2.LoadBalancingSpec{ + Geo: &v1alpha2.LoadBalancingGeo{ DefaultGeo: "NA", }, }, }, - dnsRecord: &v1alpha1.DNSRecord{ + dnsRecord: &v1alpha2.DNSRecord{ ObjectMeta: v1.ObjectMeta{ Name: "test.example.com", }, }, - wantSpec: &v1alpha1.DNSRecordSpec{ - Endpoints: []*v1alpha1.Endpoint{}, + wantSpec: &v1alpha2.DNSRecordSpec{ + Endpoints: []*v1alpha2.Endpoint{}, }, }, } @@ -985,11 +928,11 @@ func Test_dnsHelper_setEndpoints(t *testing.T) { t.Run(testCase.name, func(t *testing.T) { f := fake.NewClientBuilder().WithScheme(testScheme(t)).WithObjects(testCase.dnsRecord).Build() s := dnsHelper{Client: f} - if err := s.setEndpoints(context.TODO(), testCase.mcgTarget, testCase.dnsRecord, testCase.listener, v1alpha1.LoadBalancedRoutingStrategy); (err != nil) != testCase.wantErr { + if err := s.setEndpoints(context.TODO(), testCase.mcgTarget, testCase.dnsRecord, testCase.listener, v1alpha2.LoadBalancedRoutingStrategy); (err != nil) != testCase.wantErr { t.Errorf("SetEndpoints() error = %v, wantErr %v", err, testCase.wantErr) } - gotRecord := &v1alpha1.DNSRecord{} + gotRecord := &v1alpha2.DNSRecord{} if err := f.Get(context.TODO(), client.ObjectKeyFromObject(testCase.dnsRecord), gotRecord); err != nil { t.Errorf("error gettinging updated DNSrecord") } else { @@ -1020,14 +963,14 @@ func Test_dnsHelper_getDNSRecordForListener(t *testing.T) { name string Listener gatewayapiv1.Listener Assert func(t *testing.T, err error) - DNSRecord *v1alpha1.DNSRecord + DNSRecord *v1alpha2.DNSRecord Gateway *gatewayapiv1.Gateway - DNSPolicy *v1alpha1.DNSPolicy + DNSPolicy *v1alpha2.DNSPolicy }{ { name: "test get dns record returns record", Listener: getTestListener("a.b.c.com"), - DNSRecord: &v1alpha1.DNSRecord{ + DNSRecord: &v1alpha2.DNSRecord{ ObjectMeta: v1.ObjectMeta{ Name: "gw-test", Namespace: "test", @@ -1051,7 +994,7 @@ func Test_dnsHelper_getDNSRecordForListener(t *testing.T) { }, { name: "test get dns error when not found", - DNSRecord: &v1alpha1.DNSRecord{ + DNSRecord: &v1alpha2.DNSRecord{ ObjectMeta: v1.ObjectMeta{ Name: "gw-test", Namespace: "test", @@ -1062,7 +1005,7 @@ func Test_dnsHelper_getDNSRecordForListener(t *testing.T) { }, { name: "test get dns error when referencing different Gateway", - DNSRecord: &v1alpha1.DNSRecord{ + DNSRecord: &v1alpha2.DNSRecord{ ObjectMeta: v1.ObjectMeta{ Name: "gw-test", Namespace: "test", @@ -1086,7 +1029,7 @@ func Test_dnsHelper_getDNSRecordForListener(t *testing.T) { { name: "test get dns error when not owned by Gateway", Listener: getTestListener("other.com"), - DNSRecord: &v1alpha1.DNSRecord{ + DNSRecord: &v1alpha2.DNSRecord{ ObjectMeta: v1.ObjectMeta{ Name: "other.com", Namespace: "test", @@ -1104,7 +1047,7 @@ func Test_dnsHelper_getDNSRecordForListener(t *testing.T) { Namespace: "test", }, }, - DNSPolicy: &v1alpha1.DNSPolicy{ + DNSPolicy: &v1alpha2.DNSPolicy{ ObjectMeta: v1.ObjectMeta{ Name: "tstpolicy", Namespace: "test", @@ -1125,8 +1068,8 @@ func Test_dnsHelper_getDNSRecordForListener(t *testing.T) { } -func assertSub(domain string, subdomain string, err string) func(t *testing.T, expectedzone *v1alpha1.ManagedZone, expectedsubdomain string, expectedErr error) { - return func(t *testing.T, expectedzone *v1alpha1.ManagedZone, expectedsubdomain string, expectedErr error) { +func assertSub(domain string, subdomain string, err string) func(t *testing.T, expectedzone *dns.Zone, expectedsubdomain string, expectedErr error) { + return func(t *testing.T, expectedzone *dns.Zone, expectedsubdomain string, expectedErr error) { if (err == "") != (expectedErr == nil) { t.Errorf("expected error '%s' but got '%s'", err, expectedErr) } @@ -1136,7 +1079,7 @@ func assertSub(domain string, subdomain string, err string) func(t *testing.T, e if subdomain != expectedsubdomain { t.Fatalf("expected subdomain '%v', got '%v'", subdomain, expectedsubdomain) } - if expectedzone != nil && domain != expectedzone.Spec.DomainName { + if expectedzone != nil && domain != *expectedzone.DNSName { t.Fatalf("expected zone with domain name '%v', got '%v'", domain, expectedzone) } if expectedzone == nil && domain != "" { diff --git a/pkg/controllers/dnspolicy/dnspolicy_controller.go b/pkg/controllers/dnspolicy/dnspolicy_controller.go index ebdf574ff..76cdcd3c4 100644 --- a/pkg/controllers/dnspolicy/dnspolicy_controller.go +++ b/pkg/controllers/dnspolicy/dnspolicy_controller.go @@ -37,6 +37,7 @@ import ( "github.com/Kuadrant/multicluster-gateway-controller/pkg/_internal/conditions" "github.com/Kuadrant/multicluster-gateway-controller/pkg/apis/v1alpha1" + "github.com/Kuadrant/multicluster-gateway-controller/pkg/apis/v1alpha2" "github.com/Kuadrant/multicluster-gateway-controller/pkg/controllers/events" "github.com/Kuadrant/multicluster-gateway-controller/pkg/dns" ) @@ -73,7 +74,7 @@ func (r *DNSPolicyReconciler) Reconcile(ctx context.Context, req ctrl.Request) ( log.Info("Reconciling DNSPolicy") ctx = crlog.IntoContext(ctx, log) - previous := &v1alpha1.DNSPolicy{} + previous := &v1alpha2.DNSPolicy{} if err := r.Client().Get(ctx, req.NamespacedName, previous); err != nil { log.Info("error getting dns policy", "error", err) return ctrl.Result{}, client.IgnoreNotFound(err) @@ -134,7 +135,7 @@ func (r *DNSPolicyReconciler) Reconcile(ctx context.Context, req ctrl.Request) ( return statusResult, statusErr } -func (r *DNSPolicyReconciler) reconcileResources(ctx context.Context, dnsPolicy *v1alpha1.DNSPolicy, targetNetworkObject client.Object) error { +func (r *DNSPolicyReconciler) reconcileResources(ctx context.Context, dnsPolicy *v1alpha2.DNSPolicy, targetNetworkObject client.Object) error { gatewayCondition := conditions.BuildPolicyAffectedCondition(DNSPolicyAffected, dnsPolicy, targetNetworkObject, conditions.PolicyReasonAccepted, nil) // validate @@ -186,7 +187,7 @@ func (r *DNSPolicyReconciler) reconcileResources(ctx context.Context, dnsPolicy return nil } -func (r *DNSPolicyReconciler) deleteResources(ctx context.Context, dnsPolicy *v1alpha1.DNSPolicy, targetNetworkObject client.Object) error { +func (r *DNSPolicyReconciler) deleteResources(ctx context.Context, dnsPolicy *v1alpha2.DNSPolicy, targetNetworkObject client.Object) error { // delete based on gateway diffs if err := r.deleteDNSRecords(ctx, dnsPolicy); err != nil { @@ -218,7 +219,7 @@ func (r *DNSPolicyReconciler) deleteResources(ctx context.Context, dnsPolicy *v1 return r.updateGatewayCondition(ctx, metav1.Condition{Type: string(DNSPolicyAffected)}, gatewayDiffObj) } -func (r *DNSPolicyReconciler) reconcileStatus(ctx context.Context, dnsPolicy *v1alpha1.DNSPolicy, specErr error) (ctrl.Result, error) { +func (r *DNSPolicyReconciler) reconcileStatus(ctx context.Context, dnsPolicy *v1alpha2.DNSPolicy, specErr error) (ctrl.Result, error) { newStatus := r.calculateStatus(dnsPolicy, specErr) if !equality.Semantic.DeepEqual(newStatus, dnsPolicy.Status) { @@ -240,7 +241,7 @@ func (r *DNSPolicyReconciler) reconcileStatus(ctx context.Context, dnsPolicy *v1 return ctrl.Result{}, nil } -func (r *DNSPolicyReconciler) calculateStatus(dnsPolicy *v1alpha1.DNSPolicy, specErr error) *v1alpha1.DNSPolicyStatus { +func (r *DNSPolicyReconciler) calculateStatus(dnsPolicy *v1alpha2.DNSPolicy, specErr error) *v1alpha2.DNSPolicyStatus { newStatus := dnsPolicy.Status.DeepCopy() if specErr != nil { newStatus.ObservedGeneration = dnsPolicy.Generation @@ -303,7 +304,7 @@ func (r *DNSPolicyReconciler) SetupWithManager(mgr ctrl.Manager) error { probeEventMapper := events.NewProbeEventMapper(r.Logger(), DNSPolicyBackRefAnnotation, "dnspolicy") r.dnsHelper = dnsHelper{Client: r.Client()} ctrlr := ctrl.NewControllerManagedBy(mgr). - For(&v1alpha1.DNSPolicy{}). + For(&v1alpha2.DNSPolicy{}). Watches( &gatewayapiv1.Gateway{}, handler.EnqueueRequestsFromMapFunc(gatewayEventMapper.MapToPolicy), diff --git a/pkg/controllers/dnspolicy/dnspolicy_dnsrecords.go b/pkg/controllers/dnspolicy/dnspolicy_dnsrecords.go index 1b058a5b2..ac4ffdf12 100644 --- a/pkg/controllers/dnspolicy/dnspolicy_dnsrecords.go +++ b/pkg/controllers/dnspolicy/dnspolicy_dnsrecords.go @@ -13,12 +13,12 @@ import ( "github.com/kuadrant/kuadrant-operator/pkg/reconcilers" "github.com/Kuadrant/multicluster-gateway-controller/pkg/_internal/slice" - "github.com/Kuadrant/multicluster-gateway-controller/pkg/apis/v1alpha1" + "github.com/Kuadrant/multicluster-gateway-controller/pkg/apis/v1alpha2" "github.com/Kuadrant/multicluster-gateway-controller/pkg/dns" "github.com/Kuadrant/multicluster-gateway-controller/pkg/utils" ) -func (r *DNSPolicyReconciler) reconcileDNSRecords(ctx context.Context, dnsPolicy *v1alpha1.DNSPolicy, gwDiffObj *reconcilers.GatewayDiff) error { +func (r *DNSPolicyReconciler) reconcileDNSRecords(ctx context.Context, dnsPolicy *v1alpha2.DNSPolicy, gwDiffObj *reconcilers.GatewayDiff) error { log := crlog.FromContext(ctx) log.V(3).Info("reconciling dns records") @@ -39,34 +39,44 @@ func (r *DNSPolicyReconciler) reconcileDNSRecords(ctx context.Context, dnsPolicy return nil } -func (r *DNSPolicyReconciler) reconcileGatewayDNSRecords(ctx context.Context, gw *gatewayapiv1.Gateway, dnsPolicy *v1alpha1.DNSPolicy) error { +func (r *DNSPolicyReconciler) reconcileGatewayDNSRecords(ctx context.Context, gateway *gatewayapiv1.Gateway, dnsPolicy *v1alpha2.DNSPolicy) error { log := crlog.FromContext(ctx) - gatewayWrapper := utils.NewGatewayWrapper(gw) - if err := gatewayWrapper.Validate(); err != nil { + gw := utils.NewGatewayWrapper(gateway) + if err := gw.Validate(); err != nil { return err } - if err := r.dnsHelper.removeDNSForDeletedListeners(ctx, gatewayWrapper.Gateway); err != nil { + if err := r.dnsHelper.removeDNSForDeletedListeners(ctx, gw.Gateway); err != nil { log.V(3).Info("error removing DNS for deleted listeners") return err } - clusterGateways := gatewayWrapper.GetClusterGateways() + clusterGateways := gw.GetClusterGateways() - log.V(3).Info("checking gateway for attached routes ", "gateway", gatewayWrapper.Name, "clusterGateways", clusterGateways) + zoneList, zoneAssignment, err := r.getProviderDNSZones(ctx, dnsPolicy) + if err != nil { + return err + } + log.V(1).Info("got zones", "zoneList", zoneList, "zoneAssignment", zoneAssignment) - for _, listener := range gatewayWrapper.Spec.Listeners { - var mz, err = r.dnsHelper.getManagedZoneForListener(ctx, gatewayWrapper.Namespace, listener) - if err != nil { - return err - } + for _, listener := range gw.Spec.Listeners { listenerHost := *listener.Hostname if listenerHost == "" { - log.Info("skipping listener no hostname assigned", listener.Name, "in ns ", gatewayWrapper.Namespace) + log.Info("skipping listener no hostname assigned", listener.Name, "in ns ", gw.Namespace) continue } + var zone *dns.Zone + if zoneAssignment { + zone, _, err = findMatchingZone(string(listenerHost), string(listenerHost), zoneList) + if err != nil { + log.V(1).Info("skipping listener no matching zone for host", "listenerHost", listenerHost) + continue + } + log.V(1).Info("found zone for listener host", "zone", zone, "listenerHost", listenerHost) + } + listenerGateways := slice.Filter(clusterGateways, func(cgw utils.ClusterGateway) bool { hasAttachedRoute := false for _, statusListener := range cgw.Status.Listeners { @@ -81,23 +91,23 @@ func (r *DNSPolicyReconciler) reconcileGatewayDNSRecords(ctx context.Context, gw if len(listenerGateways) == 0 { // delete record log.V(1).Info("no cluster gateways, deleting DNS record", " for listener ", listener.Name) - if err := r.dnsHelper.deleteDNSRecordForListener(ctx, gatewayWrapper, listener); client.IgnoreNotFound(err) != nil { + if err := r.dnsHelper.deleteDNSRecordForListener(ctx, gw, listener); client.IgnoreNotFound(err) != nil { return fmt.Errorf("failed to delete dns record for listener %s : %s", listener.Name, err) } return nil } - dnsRecord, err := r.dnsHelper.createDNSRecordForListener(ctx, gatewayWrapper.Gateway, dnsPolicy, mz, listener) + dnsRecord, err := r.dnsHelper.createDNSRecordForListener(ctx, gw.Gateway, dnsPolicy, listener, zone) if err := client.IgnoreAlreadyExists(err); err != nil { return fmt.Errorf("failed to create dns record for listener host %s : %s ", *listener.Hostname, err) } if k8serrors.IsAlreadyExists(err) { - dnsRecord, err = r.dnsHelper.getDNSRecordForListener(ctx, listener, gatewayWrapper) + dnsRecord, err = r.dnsHelper.getDNSRecordForListener(ctx, listener, gw) if err != nil { return fmt.Errorf("failed to get dns record for host %s : %s ", listener.Name, err) } } - mcgTarget, err := dns.NewMultiClusterGatewayTarget(gatewayWrapper.Gateway, listenerGateways, dnsPolicy.Spec.LoadBalancing) + mcgTarget, err := dns.NewMultiClusterGatewayTarget(gw.Gateway, listenerGateways, dnsPolicy.Spec.LoadBalancing) if err != nil { return fmt.Errorf("failed to create multi cluster gateway target for listener %s : %s ", listener.Name, err) } @@ -115,11 +125,11 @@ func (r *DNSPolicyReconciler) reconcileGatewayDNSRecords(ctx context.Context, gw return nil } -func (r *DNSPolicyReconciler) deleteGatewayDNSRecords(ctx context.Context, gateway *gatewayapiv1.Gateway, dnsPolicy *v1alpha1.DNSPolicy) error { +func (r *DNSPolicyReconciler) deleteGatewayDNSRecords(ctx context.Context, gateway *gatewayapiv1.Gateway, dnsPolicy *v1alpha2.DNSPolicy) error { return r.deleteDNSRecordsWithLabels(ctx, commonDNSRecordLabels(client.ObjectKeyFromObject(gateway), client.ObjectKeyFromObject(dnsPolicy)), dnsPolicy.Namespace) } -func (r *DNSPolicyReconciler) deleteDNSRecords(ctx context.Context, dnsPolicy *v1alpha1.DNSPolicy) error { +func (r *DNSPolicyReconciler) deleteDNSRecords(ctx context.Context, dnsPolicy *v1alpha2.DNSPolicy) error { return r.deleteDNSRecordsWithLabels(ctx, policyDNSRecordLabels(client.ObjectKeyFromObject(dnsPolicy)), dnsPolicy.Namespace) } @@ -127,7 +137,7 @@ func (r *DNSPolicyReconciler) deleteDNSRecordsWithLabels(ctx context.Context, lb log := crlog.FromContext(ctx) listOptions := &client.ListOptions{LabelSelector: labels.SelectorFromSet(lbls), Namespace: namespace} - recordsList := &v1alpha1.DNSRecordList{} + recordsList := &v1alpha2.DNSRecordList{} if err := r.Client().List(ctx, recordsList, listOptions); err != nil { return err } @@ -140,3 +150,39 @@ func (r *DNSPolicyReconciler) deleteDNSRecordsWithLabels(ctx context.Context, lb } return nil } + +// getProviderDNSZones returns a list of dns.Zones for the given provider +func (r *DNSPolicyReconciler) getProviderDNSZones(ctx context.Context, pa v1alpha2.ProviderAccessor) (dns.ZoneList, bool, error) { + logger := crlog.FromContext(ctx) + zoneList := dns.ZoneList{} + zoneAssignment := false + + switch pa.GetProviderRef().Kind { + case v1alpha2.ProviderKindSecret: + zoneAssignment = true + dnsProvider, err := r.DNSProvider(ctx, pa) + if err != nil { + return zoneList, zoneAssignment, err + } + zoneList, err = dnsProvider.ListZones() + if err != nil { + return zoneList, zoneAssignment, err + } + case v1alpha2.ProviderKindManagedZone: + zoneAssignment = true + var mz v1alpha2.ManagedZone + if err := r.Client().Get(ctx, client.ObjectKey{Name: pa.GetProviderRef().Name, Namespace: pa.GetNamespace()}, &mz); err != nil { + logger.Error(err, "unable to get managed zone for provider", "ProviderRef", pa.GetProviderRef()) + return zoneList, zoneAssignment, err + } + zoneList.Items = append(zoneList.Items, &dns.Zone{ + ID: &mz.Status.ID, + DNSName: &mz.Spec.DomainName, + }) + case v1alpha2.ProviderKindNone: + fallthrough + default: + zoneAssignment = false + } + return zoneList, zoneAssignment, nil +} diff --git a/pkg/controllers/dnspolicy/dnspolicy_healthchecks.go b/pkg/controllers/dnspolicy/dnspolicy_healthchecks.go index cec93ab47..13871128f 100644 --- a/pkg/controllers/dnspolicy/dnspolicy_healthchecks.go +++ b/pkg/controllers/dnspolicy/dnspolicy_healthchecks.go @@ -18,10 +18,11 @@ import ( "github.com/Kuadrant/multicluster-gateway-controller/pkg/_internal/slice" "github.com/Kuadrant/multicluster-gateway-controller/pkg/apis/v1alpha1" + "github.com/Kuadrant/multicluster-gateway-controller/pkg/apis/v1alpha2" "github.com/Kuadrant/multicluster-gateway-controller/pkg/utils" ) -func (r *DNSPolicyReconciler) reconcileHealthCheckProbes(ctx context.Context, dnsPolicy *v1alpha1.DNSPolicy, gwDiffObj *reconcilers.GatewayDiff) error { +func (r *DNSPolicyReconciler) reconcileHealthCheckProbes(ctx context.Context, dnsPolicy *v1alpha2.DNSPolicy, gwDiffObj *reconcilers.GatewayDiff) error { log := crlog.FromContext(ctx) log.V(3).Info("reconciling health checks") @@ -68,11 +69,11 @@ func (r *DNSPolicyReconciler) createOrUpdateHealthCheckProbes(ctx context.Contex return nil } -func (r *DNSPolicyReconciler) deleteGatewayHealthCheckProbes(ctx context.Context, gateway *gatewayapiv1.Gateway, dnsPolicy *v1alpha1.DNSPolicy) error { +func (r *DNSPolicyReconciler) deleteGatewayHealthCheckProbes(ctx context.Context, gateway *gatewayapiv1.Gateway, dnsPolicy *v1alpha2.DNSPolicy) error { return r.deleteHealthCheckProbesWithLabels(ctx, commonDNSRecordLabels(client.ObjectKeyFromObject(gateway), client.ObjectKeyFromObject(dnsPolicy)), dnsPolicy.Namespace) } -func (r *DNSPolicyReconciler) deleteHealthCheckProbes(ctx context.Context, dnsPolicy *v1alpha1.DNSPolicy) error { +func (r *DNSPolicyReconciler) deleteHealthCheckProbes(ctx context.Context, dnsPolicy *v1alpha2.DNSPolicy) error { return r.deleteHealthCheckProbesWithLabels(ctx, policyDNSRecordLabels(client.ObjectKeyFromObject(dnsPolicy)), dnsPolicy.Namespace) } @@ -90,7 +91,7 @@ func (r *DNSPolicyReconciler) deleteHealthCheckProbesWithLabels(ctx context.Cont return nil } -func (r *DNSPolicyReconciler) deleteUnexpectedGatewayHealthCheckProbes(ctx context.Context, expectedProbes []*v1alpha1.DNSHealthCheckProbe, gateway *gatewayapiv1.Gateway, dnsPolicy *v1alpha1.DNSPolicy) error { +func (r *DNSPolicyReconciler) deleteUnexpectedGatewayHealthCheckProbes(ctx context.Context, expectedProbes []*v1alpha1.DNSHealthCheckProbe, gateway *gatewayapiv1.Gateway, dnsPolicy *v1alpha2.DNSPolicy) error { // remove any probes for this gateway and DNS Policy that are no longer expected existingProbes := &v1alpha1.DNSHealthCheckProbeList{} dnsLabels := commonDNSRecordLabels(client.ObjectKeyFromObject(gateway), client.ObjectKeyFromObject(dnsPolicy)) @@ -110,7 +111,7 @@ func (r *DNSPolicyReconciler) deleteUnexpectedGatewayHealthCheckProbes(ctx conte return nil } -func (r *DNSPolicyReconciler) expectedHealthCheckProbesForGateway(ctx context.Context, gw common.GatewayWrapper, dnsPolicy *v1alpha1.DNSPolicy) []*v1alpha1.DNSHealthCheckProbe { +func (r *DNSPolicyReconciler) expectedHealthCheckProbesForGateway(ctx context.Context, gw common.GatewayWrapper, dnsPolicy *v1alpha2.DNSPolicy) []*v1alpha1.DNSHealthCheckProbe { log := crlog.FromContext(ctx) var healthChecks []*v1alpha1.DNSHealthCheckProbe if dnsPolicy.Spec.HealthCheck == nil { diff --git a/pkg/controllers/dnspolicy/dnspolicy_healthchecks_test.go b/pkg/controllers/dnspolicy/dnspolicy_healthchecks_test.go index 26257bb8a..32865df79 100644 --- a/pkg/controllers/dnspolicy/dnspolicy_healthchecks_test.go +++ b/pkg/controllers/dnspolicy/dnspolicy_healthchecks_test.go @@ -15,6 +15,7 @@ import ( "github.com/kuadrant/kuadrant-operator/pkg/reconcilers" "github.com/Kuadrant/multicluster-gateway-controller/pkg/apis/v1alpha1" + "github.com/Kuadrant/multicluster-gateway-controller/pkg/apis/v1alpha2" "github.com/Kuadrant/multicluster-gateway-controller/pkg/controllers/gateway" "github.com/Kuadrant/multicluster-gateway-controller/pkg/dns" "github.com/Kuadrant/multicluster-gateway-controller/pkg/utils" @@ -38,7 +39,7 @@ func TestDNSPolicyReconciler_expectedProbesForGateway(t *testing.T) { type args struct { ctx context.Context gw common.GatewayWrapper - dnsPolicy *v1alpha1.DNSPolicy + dnsPolicy *v1alpha2.DNSPolicy } tests := []struct { name string @@ -80,13 +81,13 @@ func TestDNSPolicyReconciler_expectedProbesForGateway(t *testing.T) { }, }, }, - dnsPolicy: &v1alpha1.DNSPolicy{ + dnsPolicy: &v1alpha2.DNSPolicy{ ObjectMeta: controllerruntime.ObjectMeta{ Name: "testdnspolicy", Namespace: "testnamespace", }, - Spec: v1alpha1.DNSPolicySpec{ - HealthCheck: &v1alpha1.HealthCheckSpec{ + Spec: v1alpha2.DNSPolicySpec{ + HealthCheck: &v1alpha2.HealthCheckSpec{ Endpoint: "/", Port: testutil.Pointer(8443), Protocol: testutil.Pointer(v1alpha1.HttpsProtocol), @@ -171,13 +172,13 @@ func TestDNSPolicyReconciler_expectedProbesForGateway(t *testing.T) { }, }, }, - dnsPolicy: &v1alpha1.DNSPolicy{ + dnsPolicy: &v1alpha2.DNSPolicy{ ObjectMeta: controllerruntime.ObjectMeta{ Name: "testdnspolicy", Namespace: "testnamespace", }, - Spec: v1alpha1.DNSPolicySpec{ - HealthCheck: &v1alpha1.HealthCheckSpec{}, + Spec: v1alpha2.DNSPolicySpec{ + HealthCheck: &v1alpha2.HealthCheckSpec{}, }, }, }, @@ -236,9 +237,9 @@ func TestDNSPolicyReconciler_expectedProbesForGateway(t *testing.T) { }, }, }, - dnsPolicy: &v1alpha1.DNSPolicy{ - Spec: v1alpha1.DNSPolicySpec{ - HealthCheck: &v1alpha1.HealthCheckSpec{}, + dnsPolicy: &v1alpha2.DNSPolicy{ + Spec: v1alpha2.DNSPolicySpec{ + HealthCheck: &v1alpha2.HealthCheckSpec{}, }, }, }, @@ -280,13 +281,13 @@ func TestDNSPolicyReconciler_expectedProbesForGateway(t *testing.T) { }, }, }, - dnsPolicy: &v1alpha1.DNSPolicy{ + dnsPolicy: &v1alpha2.DNSPolicy{ ObjectMeta: controllerruntime.ObjectMeta{ Name: "testdnspolicy", Namespace: "testnamespace", }, - Spec: v1alpha1.DNSPolicySpec{ - HealthCheck: &v1alpha1.HealthCheckSpec{}, + Spec: v1alpha2.DNSPolicySpec{ + HealthCheck: &v1alpha2.HealthCheckSpec{}, }, }, }, @@ -338,9 +339,9 @@ func TestDNSPolicyReconciler_expectedProbesForGateway(t *testing.T) { }, }, }, - dnsPolicy: &v1alpha1.DNSPolicy{ - Spec: v1alpha1.DNSPolicySpec{ - HealthCheck: &v1alpha1.HealthCheckSpec{}, + dnsPolicy: &v1alpha2.DNSPolicy{ + Spec: v1alpha2.DNSPolicySpec{ + HealthCheck: &v1alpha2.HealthCheckSpec{}, }, }, }, @@ -368,9 +369,9 @@ func TestDNSPolicyReconciler_expectedProbesForGateway(t *testing.T) { }, }, }, - dnsPolicy: &v1alpha1.DNSPolicy{ - Spec: v1alpha1.DNSPolicySpec{ - HealthCheck: &v1alpha1.HealthCheckSpec{}, + dnsPolicy: &v1alpha2.DNSPolicy{ + Spec: v1alpha2.DNSPolicySpec{ + HealthCheck: &v1alpha2.HealthCheckSpec{}, }, }, }, @@ -391,9 +392,9 @@ func TestDNSPolicyReconciler_expectedProbesForGateway(t *testing.T) { Status: gatewayapiv1.GatewayStatus{}, }, }, - dnsPolicy: &v1alpha1.DNSPolicy{ - Spec: v1alpha1.DNSPolicySpec{ - HealthCheck: &v1alpha1.HealthCheckSpec{}, + dnsPolicy: &v1alpha2.DNSPolicy{ + Spec: v1alpha2.DNSPolicySpec{ + HealthCheck: &v1alpha2.HealthCheckSpec{}, }, }, }, @@ -403,7 +404,7 @@ func TestDNSPolicyReconciler_expectedProbesForGateway(t *testing.T) { name: "no probes when no healthcheck spec defined", fields: fields{}, args: args{ - dnsPolicy: &v1alpha1.DNSPolicy{}, + dnsPolicy: &v1alpha2.DNSPolicy{}, }, want: nil, }, diff --git a/pkg/controllers/dnsrecord/dnsrecord_controller.go b/pkg/controllers/dnsrecord/dnsrecord_controller.go index b38812a8f..05a1b5cdb 100644 --- a/pkg/controllers/dnsrecord/dnsrecord_controller.go +++ b/pkg/controllers/dnsrecord/dnsrecord_controller.go @@ -31,9 +31,10 @@ import ( "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" "github.com/Kuadrant/multicluster-gateway-controller/pkg/_internal/conditions" - "github.com/Kuadrant/multicluster-gateway-controller/pkg/apis/v1alpha1" + "github.com/Kuadrant/multicluster-gateway-controller/pkg/apis/v1alpha2" "github.com/Kuadrant/multicluster-gateway-controller/pkg/dns" ) @@ -57,7 +58,7 @@ type DNSRecordReconciler struct { func (r *DNSRecordReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { _ = log.FromContext(ctx) - previous := &v1alpha1.DNSRecord{} + previous := &v1alpha2.DNSRecord{} err := r.Client.Get(ctx, client.ObjectKey{Namespace: req.Namespace, Name: req.Name}, previous) if err != nil { if err := client.IgnoreNotFound(err); err == nil { @@ -127,91 +128,64 @@ func (r *DNSRecordReconciler) Reconcile(ctx context.Context, req ctrl.Request) ( // SetupWithManager sets up the controller with the Manager. func (r *DNSRecordReconciler) SetupWithManager(mgr ctrl.Manager) error { return ctrl.NewControllerManagedBy(mgr). - For(&v1alpha1.DNSRecord{}). + For(&v1alpha2.DNSRecord{}). + WithEventFilter(predicate.NewPredicateFuncs(func(object client.Object) bool { + dnsRecord, ok := object.(*v1alpha2.DNSRecord) + if ok { + return dnsRecord.GetProviderRef().Kind != v1alpha2.ProviderKindNone + } + return true + })). Complete(r) } // deleteRecord deletes record(s) in the DNSPRovider(i.e. route53) configured by the ManagedZone assigned to this // DNSRecord (dnsRecord.Status.ParentManagedZone). -func (r *DNSRecordReconciler) deleteRecord(ctx context.Context, dnsRecord *v1alpha1.DNSRecord) error { - managedZone := &v1alpha1.ManagedZone{ - ObjectMeta: metav1.ObjectMeta{ - Name: dnsRecord.Spec.ManagedZoneRef.Name, - Namespace: dnsRecord.Namespace, - }, - } - err := r.Get(ctx, client.ObjectKeyFromObject(managedZone), managedZone, &client.GetOptions{}) - if err != nil { - // If the Managed Zone isn't found, just continue - return client.IgnoreNotFound(err) - } - managedZoneReady := meta.IsStatusConditionTrue(managedZone.Status.Conditions, "Ready") - - if !managedZoneReady { - return fmt.Errorf("the managed zone is not in a ready state : %s", managedZone.Name) - } - - dnsProvider, err := r.DNSProvider(ctx, managedZone) +func (r *DNSRecordReconciler) deleteRecord(ctx context.Context, dnsRecord *v1alpha2.DNSRecord) error { + dnsProvider, err := r.DNSProvider(ctx, dnsRecord) if err != nil { return err } - err = dnsProvider.Delete(dnsRecord, managedZone) + err = dnsProvider.Delete(dnsRecord) if err != nil { if strings.Contains(err.Error(), "was not found") || strings.Contains(err.Error(), "notFound") { - log.Log.Info("Record not found in managed zone, continuing", "dnsRecord", dnsRecord.Name, "managedZone", managedZone.Name) + log.Log.Info("Record not found in zone, continuing", "dnsRecord", dnsRecord.Name, "zone", dnsRecord.Spec.ZoneID) return nil } else if strings.Contains(err.Error(), "no endpoints") { - log.Log.Info("DNS record had no endpoint, continuing", "dnsRecord", dnsRecord.Name, "managedZone", managedZone.Name) + log.Log.Info("DNS record had no endpoint, continuing", "dnsRecord", dnsRecord.Name, "zone", dnsRecord.Spec.ZoneID) return nil } return err } - log.Log.Info("Deleted DNSRecord in manage zone", "dnsRecord", dnsRecord.Name, "managedZone", managedZone.Name) + log.Log.Info("Deleted DNSRecord in zone", "dnsRecord", dnsRecord.Name, "zone", dnsRecord.Spec.ZoneID) return nil } // publishRecord publishes record(s) to the DNSPRovider(i.e. route53) configured by the ManagedZone assigned to this // DNSRecord (dnsRecord.Status.ParentManagedZone). -func (r *DNSRecordReconciler) publishRecord(ctx context.Context, dnsRecord *v1alpha1.DNSRecord) error { - - managedZone := &v1alpha1.ManagedZone{ - ObjectMeta: metav1.ObjectMeta{ - Name: dnsRecord.Spec.ManagedZoneRef.Name, - Namespace: dnsRecord.Namespace, - }, - } - err := r.Get(ctx, client.ObjectKeyFromObject(managedZone), managedZone, &client.GetOptions{}) - if err != nil { - return err - } - managedZoneReady := meta.IsStatusConditionTrue(managedZone.Status.Conditions, "Ready") - - if !managedZoneReady { - return fmt.Errorf("the managed zone is not in a ready state : %s", managedZone.Name) - } - +func (r *DNSRecordReconciler) publishRecord(ctx context.Context, dnsRecord *v1alpha2.DNSRecord) error { if dnsRecord.Generation == dnsRecord.Status.ObservedGeneration { - log.Log.V(3).Info("Skipping managed zone to which the DNS dnsRecord is already published", "dnsRecord", dnsRecord.Name, "managedZone", managedZone.Name) + log.Log.V(3).Info("Skipping zone to which the DNS dnsRecord is already published", "dnsRecord", dnsRecord.Name, "zone", dnsRecord.Spec.ZoneID) return nil } - dnsProvider, err := r.DNSProvider(ctx, managedZone) + dnsProvider, err := r.DNSProvider(ctx, dnsRecord) if err != nil { return err } - err = dnsProvider.Ensure(dnsRecord, managedZone) + err = dnsProvider.Ensure(dnsRecord) if err != nil { return err } - log.Log.Info("Published DNSRecord to manage zone", "dnsRecord", dnsRecord.Name, "managedZone", managedZone.Name) + log.Log.Info("Published DNSRecord to zone", "dnsRecord", dnsRecord.Name, "zone", dnsRecord.Spec.ZoneID) return nil } // setDNSRecordCondition adds or updates a given condition in the DNSRecord status.. -func setDNSRecordCondition(dnsRecord *v1alpha1.DNSRecord, conditionType string, status metav1.ConditionStatus, reason, message string) { +func setDNSRecordCondition(dnsRecord *v1alpha2.DNSRecord, conditionType string, status metav1.ConditionStatus, reason, message string) { cond := metav1.Condition{ Type: conditionType, Status: status, diff --git a/pkg/controllers/managedzone/managedzone_controller.go b/pkg/controllers/managedzone/managedzone_controller.go index bed66f846..b7093f78e 100644 --- a/pkg/controllers/managedzone/managedzone_controller.go +++ b/pkg/controllers/managedzone/managedzone_controller.go @@ -31,7 +31,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/log" "github.com/Kuadrant/multicluster-gateway-controller/pkg/_internal/conditions" - "github.com/Kuadrant/multicluster-gateway-controller/pkg/apis/v1alpha1" + "github.com/Kuadrant/multicluster-gateway-controller/pkg/apis/v1alpha2" "github.com/Kuadrant/multicluster-gateway-controller/pkg/dns" ) @@ -52,7 +52,7 @@ type ManagedZoneReconciler struct { func (r *ManagedZoneReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { _ = log.FromContext(ctx) - previous := &v1alpha1.ManagedZone{} + previous := &v1alpha2.ManagedZone{} err := r.Client.Get(ctx, client.ObjectKey{Namespace: req.Namespace, Name: req.Name}, previous) if err != nil { if err := client.IgnoreNotFound(err); err == nil { @@ -155,13 +155,13 @@ func (r *ManagedZoneReconciler) Reconcile(ctx context.Context, req ctrl.Request) // SetupWithManager sets up the controller with the Manager. func (r *ManagedZoneReconciler) SetupWithManager(mgr ctrl.Manager) error { return ctrl.NewControllerManagedBy(mgr). - For(&v1alpha1.ManagedZone{}). - Owns(&v1alpha1.DNSRecord{}). - Owns(&v1alpha1.ManagedZone{}). + For(&v1alpha2.ManagedZone{}). + Owns(&v1alpha2.DNSRecord{}). + Owns(&v1alpha2.ManagedZone{}). Complete(r) } -func (r *ManagedZoneReconciler) publishManagedZone(ctx context.Context, managedZone *v1alpha1.ManagedZone) error { +func (r *ManagedZoneReconciler) publishManagedZone(ctx context.Context, managedZone *v1alpha2.ManagedZone) error { dnsProvider, err := r.DNSProvider(ctx, managedZone) if err != nil { @@ -179,8 +179,8 @@ func (r *ManagedZoneReconciler) publishManagedZone(ctx context.Context, managedZ return nil } -func (r *ManagedZoneReconciler) deleteManagedZone(ctx context.Context, managedZone *v1alpha1.ManagedZone) error { - if managedZone.Spec.ID != "" { +func (r *ManagedZoneReconciler) deleteManagedZone(ctx context.Context, managedZone *v1alpha2.ManagedZone) error { + if managedZone.Spec.ID != nil { log.Log.Info("Skipping deletion of managed zone with provider ID specified in spec", "managedZone", managedZone.Name) return nil } @@ -208,11 +208,11 @@ func (r *ManagedZoneReconciler) deleteManagedZone(ctx context.Context, managedZo return nil } -func (r *ManagedZoneReconciler) getParentZone(ctx context.Context, managedZone *v1alpha1.ManagedZone) (*v1alpha1.ManagedZone, error) { +func (r *ManagedZoneReconciler) getParentZone(ctx context.Context, managedZone *v1alpha2.ManagedZone) (*v1alpha2.ManagedZone, error) { if managedZone.Spec.ParentManagedZone == nil { return nil, nil } - parentZone := &v1alpha1.ManagedZone{} + parentZone := &v1alpha2.ManagedZone{} err := r.Client.Get(ctx, client.ObjectKey{Namespace: managedZone.Namespace, Name: managedZone.Spec.ParentManagedZone.Name}, parentZone) if err != nil { return parentZone, err @@ -220,7 +220,7 @@ func (r *ManagedZoneReconciler) getParentZone(ctx context.Context, managedZone * return parentZone, nil } -func (r *ManagedZoneReconciler) setParentZoneOwner(ctx context.Context, managedZone *v1alpha1.ManagedZone) error { +func (r *ManagedZoneReconciler) setParentZoneOwner(ctx context.Context, managedZone *v1alpha2.ManagedZone) error { parentZone, err := r.getParentZone(ctx, managedZone) if err != nil { return err @@ -237,7 +237,7 @@ func (r *ManagedZoneReconciler) setParentZoneOwner(ctx context.Context, managedZ return err } -func (r *ManagedZoneReconciler) createParentZoneNSRecord(ctx context.Context, managedZone *v1alpha1.ManagedZone) error { +func (r *ManagedZoneReconciler) createParentZoneNSRecord(ctx context.Context, managedZone *v1alpha2.ManagedZone) error { parentZone, err := r.getParentZone(ctx, managedZone) if err != nil { return err @@ -252,19 +252,17 @@ func (r *ManagedZoneReconciler) createParentZoneNSRecord(ctx context.Context, ma for index := range managedZone.Status.NameServers { recordTargets[index] = *managedZone.Status.NameServers[index] } - recordType := string(v1alpha1.NSRecordType) + recordType := string(v1alpha2.NSRecordType) - nsRecord := &v1alpha1.DNSRecord{ + nsRecord := &v1alpha2.DNSRecord{ TypeMeta: metav1.TypeMeta{}, ObjectMeta: metav1.ObjectMeta{ Name: recordName, Namespace: parentZone.Namespace, }, - Spec: v1alpha1.DNSRecordSpec{ - ManagedZoneRef: &v1alpha1.ManagedZoneReference{ - Name: parentZone.Name, - }, - Endpoints: []*v1alpha1.Endpoint{ + Spec: v1alpha2.DNSRecordSpec{ + ProviderRef: managedZone.Spec.ProviderRef, + Endpoints: []*v1alpha2.Endpoint{ { DNSName: recordName, Targets: recordTargets, @@ -286,7 +284,7 @@ func (r *ManagedZoneReconciler) createParentZoneNSRecord(ctx context.Context, ma return nil } -func (r *ManagedZoneReconciler) deleteParentZoneNSRecord(ctx context.Context, managedZone *v1alpha1.ManagedZone) error { +func (r *ManagedZoneReconciler) deleteParentZoneNSRecord(ctx context.Context, managedZone *v1alpha2.ManagedZone) error { parentZone, err := r.getParentZone(ctx, managedZone) if err := client.IgnoreNotFound(err); err != nil { return err @@ -297,7 +295,7 @@ func (r *ManagedZoneReconciler) deleteParentZoneNSRecord(ctx context.Context, ma recordName := managedZone.Spec.DomainName - nsRecord := &v1alpha1.DNSRecord{} + nsRecord := &v1alpha2.DNSRecord{} err = r.Client.Get(ctx, client.ObjectKey{Namespace: parentZone.Namespace, Name: recordName}, nsRecord) if err != nil { if err := client.IgnoreNotFound(err); err == nil { @@ -315,7 +313,7 @@ func (r *ManagedZoneReconciler) deleteParentZoneNSRecord(ctx context.Context, ma return nil } -func (r *ManagedZoneReconciler) parentZoneNSRecordReady(ctx context.Context, managedZone *v1alpha1.ManagedZone) error { +func (r *ManagedZoneReconciler) parentZoneNSRecordReady(ctx context.Context, managedZone *v1alpha2.ManagedZone) error { parentZone, err := r.getParentZone(ctx, managedZone) if err := client.IgnoreNotFound(err); err != nil { return err @@ -326,7 +324,7 @@ func (r *ManagedZoneReconciler) parentZoneNSRecordReady(ctx context.Context, man recordName := managedZone.Spec.DomainName - nsRecord := &v1alpha1.DNSRecord{} + nsRecord := &v1alpha2.DNSRecord{} err = r.Client.Get(ctx, client.ObjectKey{Namespace: parentZone.Namespace, Name: recordName}, nsRecord) if err != nil { if err := client.IgnoreNotFound(err); err == nil { @@ -344,7 +342,7 @@ func (r *ManagedZoneReconciler) parentZoneNSRecordReady(ctx context.Context, man } // setManagedZoneCondition adds or updates a given condition in the ManagedZone status. -func setManagedZoneCondition(managedZone *v1alpha1.ManagedZone, conditionType string, status metav1.ConditionStatus, reason, message string) { +func setManagedZoneCondition(managedZone *v1alpha2.ManagedZone, conditionType string, status metav1.ConditionStatus, reason, message string) { cond := metav1.Condition{ Type: conditionType, Status: status, diff --git a/pkg/dns/aws/dns.go b/pkg/dns/aws/dns.go index 97517163c..ef4d2e65a 100644 --- a/pkg/dns/aws/dns.go +++ b/pkg/dns/aws/dns.go @@ -18,7 +18,9 @@ package aws import ( "fmt" + "net" "strconv" + "strings" "time" "github.com/aws/aws-sdk-go/aws" @@ -31,7 +33,7 @@ import ( kerrors "k8s.io/apimachinery/pkg/util/errors" "sigs.k8s.io/controller-runtime/pkg/log" - "github.com/Kuadrant/multicluster-gateway-controller/pkg/apis/v1alpha1" + "github.com/Kuadrant/multicluster-gateway-controller/pkg/apis/v1alpha2" "github.com/Kuadrant/multicluster-gateway-controller/pkg/dns" ) @@ -46,7 +48,10 @@ const ( type Route53DNSProvider struct { client *InstrumentedRoute53 logger logr.Logger - + // only consider hosted zones ending with this zone id + zoneIDFilter dns.ZoneIDFilter + // only consider hosted zones managing domains ending in this suffix + domainFilter dns.DomainFilter healthCheckReconciler dns.HealthCheckReconciler } @@ -54,13 +59,19 @@ var _ dns.Provider = &Route53DNSProvider{} func NewProviderFromSecret(s *v1.Secret) (*Route53DNSProvider, error) { + if string(s.Data["AWS_ACCESS_KEY_ID"]) == "" || string(s.Data["AWS_SECRET_ACCESS_KEY"]) == "" { + return nil, fmt.Errorf("AWS Provider credentials is empty") + } + + pConfig, err := dns.ConfigFromJSON(s.Data["CONFIG"]) + if err != nil { + return nil, err + } + config := aws.NewConfig() sessionOpts := session.Options{ Config: *config, } - if string(s.Data["AWS_ACCESS_KEY_ID"]) == "" || string(s.Data["AWS_SECRET_ACCESS_KEY"]) == "" { - return nil, fmt.Errorf("AWS Provider credentials is empty") - } sessionOpts.Config.Credentials = credentials.NewStaticCredentials(string(s.Data["AWS_ACCESS_KEY_ID"]), string(s.Data["AWS_SECRET_ACCESS_KEY"]), "") sessionOpts.SharedConfigState = session.SharedConfigDisable @@ -72,9 +83,14 @@ func NewProviderFromSecret(s *v1.Secret) (*Route53DNSProvider, error) { sess.Config.WithRegion(string(s.Data["REGION"])) } + zoneIDFilter := dns.NewZoneIDFilter(pConfig.ZoneIDFilter) + domainFilter := dns.NewDomainFilter(pConfig.DomainFilter) + p := &Route53DNSProvider{ - client: &InstrumentedRoute53{route53.New(sess, config)}, - logger: log.Log.WithName("aws-route53").WithValues("region", config.Region), + client: &InstrumentedRoute53{route53.New(sess, config)}, + logger: log.Log.WithName("aws-route53").WithValues("region", config.Region), + zoneIDFilter: zoneIDFilter, + domainFilter: domainFilter, } if err := validateServiceEndpoints(p); err != nil { @@ -91,18 +107,35 @@ const ( deleteAction action = "DELETE" ) -func (p *Route53DNSProvider) Ensure(record *v1alpha1.DNSRecord, managedZone *v1alpha1.ManagedZone) error { - return p.change(record, managedZone, upsertAction) +func (p *Route53DNSProvider) Ensure(record *v1alpha2.DNSRecord) error { + return p.change(record, upsertAction) } -func (p *Route53DNSProvider) Delete(record *v1alpha1.DNSRecord, managedZone *v1alpha1.ManagedZone) error { - return p.change(record, managedZone, deleteAction) +func (p *Route53DNSProvider) Delete(record *v1alpha2.DNSRecord) error { + return p.change(record, deleteAction) } -func (p *Route53DNSProvider) EnsureManagedZone(zone *v1alpha1.ManagedZone) (dns.ManagedZoneOutput, error) { +func (p *Route53DNSProvider) ListZones() (dns.ZoneList, error) { + var zoneList dns.ZoneList + zones, err := p.zones() + if err != nil { + return zoneList, err + } + for _, zone := range zones { + dnsName := removeTrailingDot(*zone.Name) + zoneID := removeHostedZoneIDPrefix(*zone.Id) + zoneList.Items = append(zoneList.Items, &dns.Zone{ + ID: &zoneID, + DNSName: &dnsName, + }) + } + return zoneList, nil +} + +func (p *Route53DNSProvider) EnsureManagedZone(zone *v1alpha2.ManagedZone) (dns.ManagedZoneOutput, error) { var zoneID string - if zone.Spec.ID != "" { - zoneID = zone.Spec.ID + if zone.Spec.ID != nil { + zoneID = *zone.Spec.ID } else { zoneID = zone.Status.ID } @@ -118,15 +151,18 @@ func (p *Route53DNSProvider) EnsureManagedZone(zone *v1alpha1.ManagedZone) (dns. return managedZoneOutput, err } - _, err = p.client.UpdateHostedZoneComment(&route53.UpdateHostedZoneCommentInput{ - Comment: &zone.Spec.Description, - Id: &zoneID, - }) - if err != nil { - log.Log.Error(err, "failed to update hosted zone comment") + //Only update if we created the managed zone and description is set + if zone.Spec.ID != nil && zone.Spec.Description != nil { + _, err = p.client.UpdateHostedZoneComment(&route53.UpdateHostedZoneCommentInput{ + Comment: zone.Spec.Description, + Id: &zoneID, + }) + if err != nil { + log.Log.Error(err, "failed to update hosted zone comment") + } } - managedZoneOutput.ID = *getResp.HostedZone.Id + managedZoneOutput.ID = removeHostedZoneIDPrefix(*getResp.HostedZone.Id) managedZoneOutput.RecordCount = *getResp.HostedZone.ResourceRecordSetCount managedZoneOutput.NameServers = getResp.DelegationSet.NameServers @@ -142,7 +178,7 @@ func (p *Route53DNSProvider) EnsureManagedZone(zone *v1alpha1.ManagedZone) (dns. CallerReference: &callerRef, Name: &zone.Spec.DomainName, HostedZoneConfig: &route53.HostedZoneConfig{ - Comment: &zone.Spec.Description, + Comment: zone.Spec.Description, PrivateZone: aws.Bool(false), }, }) @@ -156,7 +192,7 @@ func (p *Route53DNSProvider) EnsureManagedZone(zone *v1alpha1.ManagedZone) (dns. return managedZoneOutput, nil } -func (p *Route53DNSProvider) DeleteManagedZone(zone *v1alpha1.ManagedZone) error { +func (p *Route53DNSProvider) DeleteManagedZone(zone *v1alpha2.ManagedZone) error { _, err := p.client.DeleteHostedZone(&route53.DeleteHostedZoneInput{ Id: &zone.Status.ID, }) @@ -185,31 +221,57 @@ func (*Route53DNSProvider) ProviderSpecific() dns.ProviderSpecificLabels { } } -func (p *Route53DNSProvider) change(record *v1alpha1.DNSRecord, managedZone *v1alpha1.ManagedZone, action action) error { +// Zones returns the list of hosted zones. +func (p *Route53DNSProvider) zones() (map[string]*route53.HostedZone, error) { + zones := make(map[string]*route53.HostedZone) + + f := func(resp *route53.ListHostedZonesOutput, lastPage bool) (shouldContinue bool) { + for _, zone := range resp.HostedZones { + if !p.domainFilter.Match(aws.StringValue(zone.Name)) && !p.zoneIDFilter.Match(aws.StringValue(zone.Id)) { + continue + } + zones[aws.StringValue(zone.Id)] = zone + } + return true + } + + err := p.client.route53.ListHostedZonesPages(&route53.ListHostedZonesInput{}, f) + if err != nil { + return nil, fmt.Errorf("failed to list hosted zones: %w", err) + } + + for _, zone := range zones { + log.Log.V(1).Info("Considering zone", "zone.Id", aws.StringValue(zone.Id), "zone.Name", aws.StringValue(zone.Name)) + } + + return zones, nil +} + +func (p *Route53DNSProvider) change(record *v1alpha2.DNSRecord, action action) error { // Configure records. if len(record.Spec.Endpoints) == 0 { return nil } - err := p.updateRecord(record, managedZone.Status.ID, string(action)) + err := p.updateRecord(record, string(action)) if err != nil { - return fmt.Errorf("failed to update record in route53 hosted zone %s: %v", managedZone.Status.ID, err) + return fmt.Errorf("failed to update record in route53 hosted zone %s: %w", *record.Spec.ZoneID, err) } switch action { case upsertAction: - p.logger.Info("Upserted DNS record", "record", record.Spec, "hostedZoneID", managedZone.Status.ID) + p.logger.Info("Upserted DNS record", "record", record.Spec, "hostedZoneID", record.Spec.ZoneID) case deleteAction: - p.logger.Info("Deleted DNS record", "record", record.Spec, "hostedZoneID", managedZone.Status.ID) + p.logger.Info("Deleted DNS record", "record", record.Spec, "hostedZoneID", record.Spec.ZoneID) } return nil } -func (p *Route53DNSProvider) updateRecord(record *v1alpha1.DNSRecord, zoneID, action string) error { +func (p *Route53DNSProvider) updateRecord(record *v1alpha2.DNSRecord, action string) error { if len(record.Spec.Endpoints) == 0 { return fmt.Errorf("no endpoints") } - input := route53.ChangeResourceRecordSetsInput{HostedZoneId: aws.String(zoneID)} + input := route53.ChangeResourceRecordSetsInput{HostedZoneId: aws.String(*record.Spec.ZoneID)} expectedEndpointsMap := make(map[string]struct{}) var changes []*route53.Change @@ -244,14 +306,14 @@ func (p *Route53DNSProvider) updateRecord(record *v1alpha1.DNSRecord, zoneID, ac } resp, err := p.client.ChangeResourceRecordSets(&input) if err != nil { - return fmt.Errorf("couldn't update DNS record %s in zone %s: %v", record.Name, zoneID, err) + return fmt.Errorf("couldn't update DNS record %s in zone %s: %v", record.Name, *record.Spec.ZoneID, err) } - p.logger.Info("Updated DNS record", "record", record, "zone", zoneID, "response", resp) + p.logger.Info("Updated DNS record", "record", record, "zone", *record.Spec.ZoneID, "response", resp) return nil } -func (p *Route53DNSProvider) changeForEndpoint(endpoint *v1alpha1.Endpoint, action string) (*route53.Change, error) { - if endpoint.RecordType != string(v1alpha1.ARecordType) && endpoint.RecordType != string(v1alpha1.CNAMERecordType) && endpoint.RecordType != string(v1alpha1.NSRecordType) { +func (p *Route53DNSProvider) changeForEndpoint(endpoint *v1alpha2.Endpoint, action string) (*route53.Change, error) { + if endpoint.RecordType != string(v1alpha2.ARecordType) && endpoint.RecordType != string(v1alpha2.CNAMERecordType) && endpoint.RecordType != string(v1alpha2.NSRecordType) { return nil, fmt.Errorf("unsupported record type %s", endpoint.RecordType) } domain, targets := endpoint.DNSName, endpoint.Targets @@ -338,3 +400,16 @@ func validateServiceEndpoints(provider *Route53DNSProvider) error { } return kerrors.NewAggregate(errs) } + +// removeTrailingDot ensures that the hostname receives a trailing dot if it hasn't already. +func removeTrailingDot(hostname string) string { + if net.ParseIP(hostname) != nil { + return hostname + } + + return strings.TrimSuffix(hostname, ".") +} + +func removeHostedZoneIDPrefix(id string) string { + return strings.TrimPrefix(id, "/hostedzone/") +} diff --git a/pkg/dns/aws/health.go b/pkg/dns/aws/health.go index 1d726cf97..5289c59dc 100644 --- a/pkg/dns/aws/health.go +++ b/pkg/dns/aws/health.go @@ -11,7 +11,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/log" - "github.com/Kuadrant/multicluster-gateway-controller/pkg/apis/v1alpha1" + "github.com/Kuadrant/multicluster-gateway-controller/pkg/apis/v1alpha2" "github.com/Kuadrant/multicluster-gateway-controller/pkg/dns" ) @@ -39,7 +39,7 @@ func NewRoute53HealthCheckReconciler(client route53iface.Route53API) *Route53Hea } } -func (r *Route53HealthCheckReconciler) Reconcile(ctx context.Context, spec dns.HealthCheckSpec, endpoint *v1alpha1.Endpoint) (dns.HealthCheckResult, error) { +func (r *Route53HealthCheckReconciler) Reconcile(ctx context.Context, spec dns.HealthCheckSpec, endpoint *v1alpha2.Endpoint) (dns.HealthCheckResult, error) { healthCheck, exists, err := r.findHealthCheck(ctx, endpoint) if err != nil { return dns.HealthCheckResult{}, err @@ -68,7 +68,7 @@ func (r *Route53HealthCheckReconciler) Reconcile(ctx context.Context, spec dns.H return dns.NewHealthCheckResult(dns.HealthCheckCreated, fmt.Sprintf("Created health check with ID %s", *healthCheck.Id)), nil } -func (r *Route53HealthCheckReconciler) Delete(ctx context.Context, endpoint *v1alpha1.Endpoint) (dns.HealthCheckResult, error) { +func (r *Route53HealthCheckReconciler) Delete(ctx context.Context, endpoint *v1alpha2.Endpoint) (dns.HealthCheckResult, error) { healthCheck, found, err := r.findHealthCheck(ctx, endpoint) if err != nil { return dns.HealthCheckResult{}, err @@ -89,7 +89,7 @@ func (r *Route53HealthCheckReconciler) Delete(ctx context.Context, endpoint *v1a return dns.NewHealthCheckResult(dns.HealthCheckDeleted, ""), nil } -func (c *Route53HealthCheckReconciler) findHealthCheck(ctx context.Context, endpoint *v1alpha1.Endpoint) (*route53.HealthCheck, bool, error) { +func (c *Route53HealthCheckReconciler) findHealthCheck(ctx context.Context, endpoint *v1alpha2.Endpoint) (*route53.HealthCheck, bool, error) { id, hasId := getHealthCheckId(endpoint) if !hasId { return nil, false, nil @@ -106,7 +106,7 @@ func (c *Route53HealthCheckReconciler) findHealthCheck(ctx context.Context, endp } -func (c *Route53HealthCheckReconciler) createHealthCheck(ctx context.Context, spec dns.HealthCheckSpec, endpoint *v1alpha1.Endpoint) (*route53.HealthCheck, error) { +func (c *Route53HealthCheckReconciler) createHealthCheck(ctx context.Context, spec dns.HealthCheckSpec, endpoint *v1alpha2.Endpoint) (*route53.HealthCheck, error) { address, _ := endpoint.GetAddress() host := endpoint.DNSName @@ -150,7 +150,7 @@ func (c *Route53HealthCheckReconciler) createHealthCheck(ctx context.Context, sp return output.HealthCheck, nil } -func (r *Route53HealthCheckReconciler) updateHealthCheck(ctx context.Context, spec dns.HealthCheckSpec, endpoint *v1alpha1.Endpoint, healthCheck *route53.HealthCheck) (dns.HealthCheckReconciliationResult, error) { +func (r *Route53HealthCheckReconciler) updateHealthCheck(ctx context.Context, spec dns.HealthCheckSpec, endpoint *v1alpha2.Endpoint, healthCheck *route53.HealthCheck) (dns.HealthCheckReconciliationResult, error) { diff := healthCheckDiff(healthCheck, spec, endpoint) if diff == nil { return dns.HealthCheckNoop, nil @@ -169,7 +169,7 @@ func (r *Route53HealthCheckReconciler) updateHealthCheck(ctx context.Context, sp // healthCheckDiff creates a `UpdateHealthCheckInput` object with the fields to // update on healthCheck based on the given spec. // If the health check matches the spec, returns `nil` -func healthCheckDiff(healthCheck *route53.HealthCheck, spec dns.HealthCheckSpec, endpoint *v1alpha1.Endpoint) *route53.UpdateHealthCheckInput { +func healthCheckDiff(healthCheck *route53.HealthCheck, spec dns.HealthCheckSpec, endpoint *v1alpha2.Endpoint) *route53.UpdateHealthCheckInput { var result *route53.UpdateHealthCheckInput // "Lazily" set the value for result only once and only when there is @@ -253,6 +253,6 @@ func valuesEqualWithDefault[T comparable](ptr1, ptr2 *T, defaultValue T) bool { return value1 == value2 } -func getHealthCheckId(endpoint *v1alpha1.Endpoint) (string, bool) { +func getHealthCheckId(endpoint *v1alpha2.Endpoint) (string, bool) { return endpoint.GetProviderSpecific(ProviderSpecificHealthCheckID) } diff --git a/pkg/dns/aws/health_test.go b/pkg/dns/aws/health_test.go index e5d4afa37..9c098bb74 100644 --- a/pkg/dns/aws/health_test.go +++ b/pkg/dns/aws/health_test.go @@ -12,7 +12,7 @@ import ( "github.com/aws/aws-sdk-go/service/route53/route53iface" "github.com/Kuadrant/multicluster-gateway-controller/pkg/_internal/slice" - "github.com/Kuadrant/multicluster-gateway-controller/pkg/apis/v1alpha1" + "github.com/Kuadrant/multicluster-gateway-controller/pkg/apis/v1alpha2" "github.com/Kuadrant/multicluster-gateway-controller/pkg/dns" ) @@ -21,10 +21,10 @@ func TestHealthCheckReconcile(t *testing.T) { name string spec dns.HealthCheckSpec - endpoint *v1alpha1.Endpoint + endpoint *v1alpha2.Endpoint existingHealthChecks []*mockHealthCheck - assertion func(dns.HealthCheckResult, error, *v1alpha1.Endpoint, *mockRoute53API) error + assertion func(dns.HealthCheckResult, error, *v1alpha2.Endpoint, *mockRoute53API) error }{ { name: "New health check created", @@ -32,7 +32,7 @@ func TestHealthCheckReconcile(t *testing.T) { spec: dns.HealthCheckSpec{ Name: "test-health-check", }, - endpoint: &v1alpha1.Endpoint{}, + endpoint: &v1alpha2.Endpoint{}, existingHealthChecks: []*mockHealthCheck{ { HealthCheck: &route53.HealthCheck{ @@ -41,7 +41,7 @@ func TestHealthCheckReconcile(t *testing.T) { }, }, - assertion: func(hcr dns.HealthCheckResult, err error, e *v1alpha1.Endpoint, mra *mockRoute53API) error { + assertion: func(hcr dns.HealthCheckResult, err error, e *v1alpha2.Endpoint, mra *mockRoute53API) error { if hcr.Result != dns.HealthCheckCreated { return fmt.Errorf("unexpected result. Expected Created, but got %s", hcr.Result) } @@ -71,8 +71,8 @@ func TestHealthCheckReconcile(t *testing.T) { Id: "test-0", Path: "/", }, - endpoint: &v1alpha1.Endpoint{ - ProviderSpecific: v1alpha1.ProviderSpecific{ + endpoint: &v1alpha2.Endpoint{ + ProviderSpecific: v1alpha2.ProviderSpecific{ { Name: ProviderSpecificHealthCheckID, Value: "test-0", @@ -94,7 +94,7 @@ func TestHealthCheckReconcile(t *testing.T) { }, }, }, - assertion: func(hcr dns.HealthCheckResult, err error, e *v1alpha1.Endpoint, mra *mockRoute53API) error { + assertion: func(hcr dns.HealthCheckResult, err error, e *v1alpha2.Endpoint, mra *mockRoute53API) error { if err != nil { return fmt.Errorf("unexpected errror %v", err) } @@ -117,11 +117,11 @@ func TestHealthCheckReconcile(t *testing.T) { Id: "test-0", Path: "/", }, - endpoint: &v1alpha1.Endpoint{ + endpoint: &v1alpha2.Endpoint{ DNSName: "test.example.com", - Targets: v1alpha1.Targets{"0.0.0.0"}, + Targets: v1alpha2.Targets{"0.0.0.0"}, SetIdentifier: "0.0.0.0", - ProviderSpecific: v1alpha1.ProviderSpecific{ + ProviderSpecific: v1alpha2.ProviderSpecific{ { Name: ProviderSpecificHealthCheckID, Value: "test-0", @@ -146,7 +146,7 @@ func TestHealthCheckReconcile(t *testing.T) { }, }, }, - assertion: func(hcr dns.HealthCheckResult, err error, e *v1alpha1.Endpoint, mra *mockRoute53API) error { + assertion: func(hcr dns.HealthCheckResult, err error, e *v1alpha2.Endpoint, mra *mockRoute53API) error { if err != nil { return fmt.Errorf("unexpected errror %v", err) } @@ -182,16 +182,16 @@ func TestHealthCheckDelete(t *testing.T) { testCases := []struct { name string - endpoint *v1alpha1.Endpoint + endpoint *v1alpha2.Endpoint existingHealthChecks []*mockHealthCheck - assertion func(dns.HealthCheckResult, error, *v1alpha1.Endpoint, *mockRoute53API) error + assertion func(dns.HealthCheckResult, error, *v1alpha2.Endpoint, *mockRoute53API) error }{ { name: "Test case deleted", - endpoint: &v1alpha1.Endpoint{ - ProviderSpecific: v1alpha1.ProviderSpecific{ + endpoint: &v1alpha2.Endpoint{ + ProviderSpecific: v1alpha2.ProviderSpecific{ { Name: ProviderSpecificHealthCheckID, Value: "test-1", @@ -211,7 +211,7 @@ func TestHealthCheckDelete(t *testing.T) { }, }, - assertion: func(hcr dns.HealthCheckResult, err error, e *v1alpha1.Endpoint, mra *mockRoute53API) error { + assertion: func(hcr dns.HealthCheckResult, err error, e *v1alpha2.Endpoint, mra *mockRoute53API) error { if err != nil { return fmt.Errorf("unexpected error %v", err) } @@ -233,8 +233,8 @@ func TestHealthCheckDelete(t *testing.T) { { name: "Test case not found", - endpoint: &v1alpha1.Endpoint{ - ProviderSpecific: v1alpha1.ProviderSpecific{}, + endpoint: &v1alpha2.Endpoint{ + ProviderSpecific: v1alpha2.ProviderSpecific{}, }, existingHealthChecks: []*mockHealthCheck{ { @@ -244,7 +244,7 @@ func TestHealthCheckDelete(t *testing.T) { }, }, - assertion: func(hcr dns.HealthCheckResult, err error, e *v1alpha1.Endpoint, mra *mockRoute53API) error { + assertion: func(hcr dns.HealthCheckResult, err error, e *v1alpha2.Endpoint, mra *mockRoute53API) error { if err != nil { return fmt.Errorf("unexpected error %v", err) } diff --git a/pkg/dns/dns.go b/pkg/dns/dns.go index 7bc69f7c3..f5b94ed62 100644 --- a/pkg/dns/dns.go +++ b/pkg/dns/dns.go @@ -18,10 +18,11 @@ package dns import ( "context" + "encoding/json" "errors" "regexp" - "github.com/Kuadrant/multicluster-gateway-controller/pkg/apis/v1alpha1" + "github.com/Kuadrant/multicluster-gateway-controller/pkg/apis/v1alpha2" ) const ( @@ -31,22 +32,25 @@ const ( ProviderSpecificGeoCode = "geo-code" ) -type DNSProviderFactory func(ctx context.Context, managedZone *v1alpha1.ManagedZone) (Provider, error) +type DNSProviderFactory func(ctx context.Context, pa v1alpha2.ProviderAccessor) (Provider, error) // Provider knows how to manage DNS zones only as pertains to routing. type Provider interface { // Ensure will create or update record. - Ensure(record *v1alpha1.DNSRecord, managedZone *v1alpha1.ManagedZone) error + Ensure(record *v1alpha2.DNSRecord) error // Delete will delete record. - Delete(record *v1alpha1.DNSRecord, managedZone *v1alpha1.ManagedZone) error + Delete(record *v1alpha2.DNSRecord) error + + // List all zones + ListZones() (ZoneList, error) // Ensure will create or update a managed zone, returns an array of NameServers for that zone. - EnsureManagedZone(managedZone *v1alpha1.ManagedZone) (ManagedZoneOutput, error) + EnsureManagedZone(managedZone *v1alpha2.ManagedZone) (ManagedZoneOutput, error) // Delete will delete a managed zone. - DeleteManagedZone(managedZone *v1alpha1.ManagedZone) error + DeleteManagedZone(managedZone *v1alpha2.ManagedZone) error // Get an instance of HealthCheckReconciler for this provider HealthCheckReconciler() HealthCheckReconciler @@ -65,20 +69,56 @@ type ManagedZoneOutput struct { RecordCount int64 } +type Zone struct { + ID *string + DNSName *string +} + +type ZoneList struct { + Items []*Zone +} + +type ProviderConfig struct { + ZoneIDFilter []string + DomainFilter []string +} + +func ConfigFromJSON(jsonKey []byte) (*ProviderConfig, error) { + var pConfig struct { + ZoneIDFilter []string `json:"zoneIDFilter"` + DomainFilter []string `json:"domainFilter"` + } + if len(jsonKey) > 0 { + if err := json.Unmarshal(jsonKey, &pConfig); err != nil { + return nil, err + } + } + return &ProviderConfig{ + ZoneIDFilter: pConfig.ZoneIDFilter, + }, nil +} + var _ Provider = &FakeProvider{} type FakeProvider struct{} -func (*FakeProvider) Ensure(dnsRecord *v1alpha1.DNSRecord, managedZone *v1alpha1.ManagedZone) error { +func (*FakeProvider) Ensure(_ *v1alpha2.DNSRecord) error { return nil } -func (*FakeProvider) Delete(dnsRecord *v1alpha1.DNSRecord, managedZone *v1alpha1.ManagedZone) error { +func (*FakeProvider) Delete(_ *v1alpha2.DNSRecord) error { return nil } -func (*FakeProvider) EnsureManagedZone(managedZone *v1alpha1.ManagedZone) (ManagedZoneOutput, error) { - return ManagedZoneOutput{}, nil +func (*FakeProvider) ListZones() (ZoneList, error) { + return ZoneList{}, nil +} +func (*FakeProvider) EnsureManagedZone(mz *v1alpha2.ManagedZone) (ManagedZoneOutput, error) { + return ManagedZoneOutput{ + ID: *mz.Spec.ID, + NameServers: nil, + RecordCount: 0, + }, nil } -func (*FakeProvider) DeleteManagedZone(managedZone *v1alpha1.ManagedZone) error { return nil } +func (*FakeProvider) DeleteManagedZone(_ *v1alpha2.ManagedZone) error { return nil } func (*FakeProvider) HealthCheckReconciler() HealthCheckReconciler { return &FakeHealthCheckReconciler{} diff --git a/pkg/dns/dnsprovider/dnsProvider.go b/pkg/dns/dnsprovider/dnsProvider.go index c2cf87b08..75caa28ed 100644 --- a/pkg/dns/dnsprovider/dnsProvider.go +++ b/pkg/dns/dnsprovider/dnsProvider.go @@ -5,17 +5,19 @@ import ( "fmt" v1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/log" - "github.com/Kuadrant/multicluster-gateway-controller/pkg/apis/v1alpha1" + "github.com/Kuadrant/multicluster-gateway-controller/pkg/apis/v1alpha2" "github.com/Kuadrant/multicluster-gateway-controller/pkg/dns" "github.com/Kuadrant/multicluster-gateway-controller/pkg/dns/aws" "github.com/Kuadrant/multicluster-gateway-controller/pkg/dns/google" ) -var errUnsupportedProvider = fmt.Errorf("provider type given is not supported") +var ( + ErrUnsupportedProviderKind = fmt.Errorf("unsupported provider kind") + ErrUnsupportedProviderType = fmt.Errorf("unsupported provider type") +) type providerFactory struct { client.Client @@ -29,37 +31,60 @@ func NewProvider(c client.Client) *providerFactory { } // depending on the provider type specified in the form of a custom secret type https://kubernetes.io/docs/concepts/configuration/secret/#secret-types in the dnsprovider secret it returns a dnsprovider. -func (p *providerFactory) DNSProviderFactory(ctx context.Context, managedZone *v1alpha1.ManagedZone) (dns.Provider, error) { - providerSecret := &v1.Secret{ - ObjectMeta: metav1.ObjectMeta{ - Name: managedZone.Spec.SecretRef.Name, - Namespace: managedZone.Namespace, // must be in same namespace as ManagedZone - }} +func (p *providerFactory) DNSProviderFactory(ctx context.Context, pa v1alpha2.ProviderAccessor) (dns.Provider, error) { + return p.provider(ctx, pa) +} + +func (p *providerFactory) provider(ctx context.Context, pa v1alpha2.ProviderAccessor) (dns.Provider, error) { + switch pa.GetProviderRef().Kind { + case v1alpha2.ProviderKindSecret: + return p.providerFromSecret(ctx, pa.GetProviderRef().Name, pa.GetNamespace()) + case v1alpha2.ProviderKindManagedZone: + return p.providerFromManagedZone(ctx, pa.GetProviderRef().Name, pa.GetNamespace()) + case v1alpha2.ProviderKindNone: + fallthrough + default: + return nil, fmt.Errorf("%w : %s", ErrUnsupportedProviderKind, pa.GetProviderRef().Kind) + } +} - if err := p.Client.Get(ctx, client.ObjectKeyFromObject(providerSecret), providerSecret); err != nil { +func (p *providerFactory) providerFromSecret(ctx context.Context, name, namespace string) (dns.Provider, error) { + var providerSecret v1.Secret + if err := p.Client.Get(ctx, client.ObjectKey{Name: name, Namespace: namespace}, &providerSecret); err != nil { return nil, err } switch providerSecret.Type { case "kuadrant.io/aws": - dnsProvider, err := aws.NewProviderFromSecret(providerSecret) + dnsProvider, err := aws.NewProviderFromSecret(&providerSecret) if err != nil { return nil, fmt.Errorf("unable to create AWS dns provider from secret: %v", err) } - log.Log.V(1).Info("Route53 provider created", "managed zone:", managedZone.Name) + log.Log.V(1).Info("Route53 provider created from secret", "name", name, "namespace", namespace) return dnsProvider, nil case "kuadrant.io/gcp": - dnsProvider, err := google.NewProviderFromSecret(ctx, providerSecret) + dnsProvider, err := google.NewProviderFromSecret(ctx, &providerSecret) if err != nil { return nil, fmt.Errorf("unable to create GCP dns provider from secret: %v", err) } - log.Log.V(1).Info("Google provider created", "managed zone:", managedZone.Name) + log.Log.V(1).Info("Google provider created from secret", "name", name, "namespace", namespace) return dnsProvider, nil default: - return nil, errUnsupportedProvider + return nil, fmt.Errorf("%w : %s", ErrUnsupportedProviderType, providerSecret.Type) } +} +func (p *providerFactory) providerFromManagedZone(ctx context.Context, name, namespace string) (dns.Provider, error) { + var mz v1alpha2.ManagedZone + if err := p.Client.Get(ctx, client.ObjectKey{Name: name, Namespace: namespace}, &mz); err != nil { + return nil, err + } + //Avoid ending up in a loop, a managed zone should not reference another managed zone + if mz.GetProviderRef().Kind == v1alpha2.ProviderKindManagedZone { + return nil, fmt.Errorf("%w : managed zone cannot have a providerRef with kind %s", ErrUnsupportedProviderKind, v1alpha2.ProviderKindManagedZone) + } + return p.provider(ctx, &mz) } diff --git a/pkg/dns/filters.go b/pkg/dns/filters.go new file mode 100644 index 000000000..f9e3f3784 --- /dev/null +++ b/pkg/dns/filters.go @@ -0,0 +1,71 @@ +package dns + +import "strings" + +// ZoneIDFilter holds a list of zone ids to filter by +type ZoneIDFilter struct { + ZoneIDs []string +} + +// NewZoneIDFilter returns a new ZoneIDFilter given a list of zone ids +func NewZoneIDFilter(zoneIDs []string) ZoneIDFilter { + return ZoneIDFilter{zoneIDs} +} + +// Match checks whether a zone matches one of the provided zone ids +func (f ZoneIDFilter) Match(zoneID string) bool { + // An empty filter includes all zones. + if len(f.ZoneIDs) == 0 { + return true + } + + for _, id := range f.ZoneIDs { + if strings.HasSuffix(zoneID, id) { + return true + } + } + + return false +} + +// IsConfigured returns true if DomainFilter is configured, false otherwise +func (f ZoneIDFilter) IsConfigured() bool { + if len(f.ZoneIDs) == 1 { + return f.ZoneIDs[0] != "" + } + return len(f.ZoneIDs) > 0 +} + +// DomainFilter holds a list of domains to filter by +type DomainFilter struct { + DomainNames []string +} + +// NewDomainFilter returns a new DomainFilter given a list of domain names +func NewDomainFilter(domainNames []string) DomainFilter { + return DomainFilter{domainNames} +} + +// Match checks whether a zone matches one of the provided domains +func (f DomainFilter) Match(domainName string) bool { + // An empty filter includes all zones. + if len(f.DomainNames) == 0 { + return true + } + + for _, id := range f.DomainNames { + if strings.HasSuffix(domainName, id) { + return true + } + } + + return false +} + +// IsConfigured returns true if DomainFilter is configured, false otherwise +func (f DomainFilter) IsConfigured() bool { + if len(f.DomainNames) == 1 { + return f.DomainNames[0] != "" + } + return len(f.DomainNames) > 0 +} diff --git a/pkg/dns/google/google.go b/pkg/dns/google/google.go index a269d29c4..6f9f5d2a5 100644 --- a/pkg/dns/google/google.go +++ b/pkg/dns/google/google.go @@ -33,7 +33,7 @@ import ( v1 "k8s.io/api/core/v1" "sigs.k8s.io/controller-runtime/pkg/log" - "github.com/Kuadrant/multicluster-gateway-controller/pkg/apis/v1alpha1" + "github.com/Kuadrant/multicluster-gateway-controller/pkg/apis/v1alpha2" "github.com/Kuadrant/multicluster-gateway-controller/pkg/dns" ) @@ -135,6 +135,10 @@ type GoogleDNSProvider struct { batchChangeSize int // Interval between batch updates. batchChangeInterval time.Duration + // only consider hosted zones ending with this zone id + zoneIDFilter dns.ZoneIDFilter + // only consider hosted zones managing domains ending in this suffix + domainFilter dns.DomainFilter // A client for managing resource record sets resourceRecordSetsClient resourceRecordSetsClientInterface // A client for managing hosted zones @@ -153,6 +157,11 @@ func NewProviderFromSecret(ctx context.Context, s *v1.Secret) (*GoogleDNSProvide return nil, fmt.Errorf("GCP Provider credentials is empty") } + pConfig, err := dns.ConfigFromJSON(s.Data["CONFIG"]) + if err != nil { + return nil, err + } + dnsClient, err := dnsv1.NewService(ctx, option.WithCredentialsJSON(s.Data["GOOGLE"])) if err != nil { return nil, err @@ -160,12 +169,17 @@ func NewProviderFromSecret(ctx context.Context, s *v1.Secret) (*GoogleDNSProvide var project = string(s.Data["PROJECT_ID"]) + zoneIDFilter := dns.NewZoneIDFilter(pConfig.ZoneIDFilter) + domainFilter := dns.NewDomainFilter(pConfig.DomainFilter) + provider := &GoogleDNSProvider{ logger: log.Log.WithName("google-dns").WithValues("project", project), project: project, dryRun: DryRun, batchChangeSize: GoogleBatchChangeSize, batchChangeInterval: GoogleBatchChangeInterval, + zoneIDFilter: zoneIDFilter, + domainFilter: domainFilter, resourceRecordSetsClient: resourceRecordSetsService{dnsClient.ResourceRecordSets}, managedZonesClient: managedZonesService{dnsClient.ManagedZones}, changesClient: changesService{dnsClient.Changes}, @@ -177,15 +191,57 @@ func NewProviderFromSecret(ctx context.Context, s *v1.Secret) (*GoogleDNSProvide // ManagedZones -func (g *GoogleDNSProvider) DeleteManagedZone(managedZone *v1alpha1.ManagedZone) error { +func (p *GoogleDNSProvider) ListZones() (dns.ZoneList, error) { + var zoneList dns.ZoneList + zones, err := p.zones() + if err != nil { + return zoneList, err + } + for _, zone := range zones { + dnsName := removeTrailingDot(zone.DnsName) + zoneList.Items = append(zoneList.Items, &dns.Zone{ + ID: &zone.Name, + DNSName: &dnsName, + }) + } + return zoneList, nil +} + +// Zones returns the list of managed zones. +func (p *GoogleDNSProvider) zones() (map[string]*dnsv1.ManagedZone, error) { + zones := make(map[string]*dnsv1.ManagedZone) + + f := func(resp *dnsv1.ManagedZonesListResponse) error { + for _, zone := range resp.ManagedZones { + if !p.domainFilter.Match(zone.DnsName) && !(p.zoneIDFilter.Match(fmt.Sprintf("%v", zone.Id)) || p.zoneIDFilter.Match(fmt.Sprintf("%v", zone.Name))) { + continue + } + zones[zone.Name] = zone + } + return nil + } + + err := p.managedZonesClient.List(p.project).Pages(p.ctx, f) + if err != nil { + return nil, fmt.Errorf("failed to list managed zones: %w", err) + } + + for _, zone := range zones { + log.Log.V(1).Info("Considering zone", "zone.Name", zone.Name, "zone.DnsName", zone.DnsName) + } + + return zones, nil +} + +func (g *GoogleDNSProvider) DeleteManagedZone(managedZone *v1alpha2.ManagedZone) error { return g.managedZonesClient.Delete(g.project, managedZone.Status.ID).Do() } -func (g *GoogleDNSProvider) EnsureManagedZone(managedZone *v1alpha1.ManagedZone) (dns.ManagedZoneOutput, error) { +func (g *GoogleDNSProvider) EnsureManagedZone(managedZone *v1alpha2.ManagedZone) (dns.ManagedZoneOutput, error) { var zoneID string - if managedZone.Spec.ID != "" { - zoneID = managedZone.Spec.ID + if managedZone.Spec.ID != nil { + zoneID = *managedZone.Spec.ID } else { zoneID = managedZone.Status.ID } @@ -198,12 +254,12 @@ func (g *GoogleDNSProvider) EnsureManagedZone(managedZone *v1alpha1.ManagedZone) return g.createManagedZone(managedZone) } -func (g *GoogleDNSProvider) createManagedZone(managedZone *v1alpha1.ManagedZone) (dns.ManagedZoneOutput, error) { +func (g *GoogleDNSProvider) createManagedZone(managedZone *v1alpha2.ManagedZone) (dns.ManagedZoneOutput, error) { zoneID := strings.Replace(managedZone.Spec.DomainName, ".", "-", -1) zone := dnsv1.ManagedZone{ Name: zoneID, DnsName: ensureTrailingDot(managedZone.Spec.DomainName), - Description: managedZone.Spec.Description, + Description: *managedZone.Spec.Description, } mz, err := g.managedZonesClient.Create(g.project, &zone).Do() if err != nil { @@ -242,12 +298,12 @@ func (g *GoogleDNSProvider) toManagedZoneOutput(mz *dnsv1.ManagedZone) (dns.Mana //DNSRecords -func (g *GoogleDNSProvider) Ensure(record *v1alpha1.DNSRecord, managedZone *v1alpha1.ManagedZone) error { - return g.updateRecord(record, managedZone.Status.ID, upsertAction) +func (g *GoogleDNSProvider) Ensure(record *v1alpha2.DNSRecord) error { + return g.updateRecord(record, upsertAction) } -func (g *GoogleDNSProvider) Delete(record *v1alpha1.DNSRecord, managedZone *v1alpha1.ManagedZone) error { - return g.updateRecord(record, managedZone.Status.ID, deleteAction) +func (g *GoogleDNSProvider) Delete(record *v1alpha2.DNSRecord) error { + return g.updateRecord(record, deleteAction) } func (g *GoogleDNSProvider) HealthCheckReconciler() dns.HealthCheckReconciler { @@ -259,12 +315,15 @@ func (g *GoogleDNSProvider) ProviderSpecific() dns.ProviderSpecificLabels { return dns.ProviderSpecificLabels{} } -func (g *GoogleDNSProvider) updateRecord(dnsRecord *v1alpha1.DNSRecord, zoneID string, action action) error { +func (g *GoogleDNSProvider) updateRecord(dnsRecord *v1alpha2.DNSRecord, action action) error { // When updating records the Google DNS API expects you to delete any existing record and add the new one as part of // the same change request. The record to be deleted must match exactly what currently exists in the provider or the // change request will fail. To make sure we can always remove the records, we first get all records that exist in // the zone and build up the deleting list from `dnsRecord.Status` but use the most recent version of it retrieved // from the provider in the change request. + + zoneID := *dnsRecord.Spec.ZoneID + currentRecords, err := g.getResourceRecordSets(g.ctx, zoneID) if err != nil { return err @@ -417,12 +476,12 @@ func (g *GoogleDNSProvider) getResourceRecordSets(ctx context.Context, zoneID st } // toResourceRecordSets converts a list of endpoints into `ResourceRecordSet` resources. -func toResourceRecordSets(allEndpoints []*v1alpha1.Endpoint) []*dnsv1.ResourceRecordSet { +func toResourceRecordSets(allEndpoints []*v1alpha2.Endpoint) []*dnsv1.ResourceRecordSet { var records []*dnsv1.ResourceRecordSet // Google DNS requires a record to be created per `dnsName`, so the first thing we need to do is group all the // endpoints with the same dnsName together. - endpointMap := make(map[string][]*v1alpha1.Endpoint) + endpointMap := make(map[string][]*v1alpha2.Endpoint) for _, ep := range allEndpoints { endpointMap[ep.DNSName] = append(endpointMap[ep.DNSName], ep) } @@ -453,7 +512,7 @@ func toResourceRecordSets(allEndpoints []*v1alpha1.Endpoint) []*dnsv1.ResourceRe for _, ep := range endpoints { targets := make([]string, len(ep.Targets)) copy(targets, ep.Targets) - if ep.RecordType == string(v1alpha1.CNAMERecordType) { + if ep.RecordType == string(v1alpha2.CNAMERecordType) { targets[0] = ensureTrailingDot(targets[0]) } @@ -505,3 +564,12 @@ func ensureTrailingDot(hostname string) string { return strings.TrimSuffix(hostname, ".") + "." } + +// removeTrailingDot ensures that the hostname receives a trailing dot if it hasn't already. +func removeTrailingDot(hostname string) string { + if net.ParseIP(hostname) != nil { + return hostname + } + + return strings.TrimSuffix(hostname, ".") +} diff --git a/pkg/dns/google/google_test.go b/pkg/dns/google/google_test.go index fc9e1ed84..552a86ff9 100644 --- a/pkg/dns/google/google_test.go +++ b/pkg/dns/google/google_test.go @@ -12,7 +12,7 @@ import ( "github.com/aws/aws-sdk-go/aws" dnsv1 "google.golang.org/api/dns/v1" - "github.com/Kuadrant/multicluster-gateway-controller/pkg/apis/v1alpha1" + "github.com/Kuadrant/multicluster-gateway-controller/pkg/apis/v1alpha2" "github.com/Kuadrant/multicluster-gateway-controller/pkg/dns" ) @@ -133,7 +133,7 @@ func TestGoogleDNSProvider_toManagedZoneOutput(t *testing.T) { func Test_toResourceRecordSets(t *testing.T) { type args struct { - allEndpoints []*v1alpha1.Endpoint + allEndpoints []*v1alpha2.Endpoint } tests := []struct { name string @@ -143,15 +143,15 @@ func Test_toResourceRecordSets(t *testing.T) { { name: "Successful test Geo & weight", args: args{ - allEndpoints: []*v1alpha1.Endpoint{ + allEndpoints: []*v1alpha2.Endpoint{ { DNSName: "2c71gf.lb-4ej5le.unittest.google.hcpapps.net", RecordType: "A", RecordTTL: 60, - Targets: v1alpha1.Targets{ + Targets: v1alpha2.Targets{ "0.0.0.0", }, - ProviderSpecific: v1alpha1.ProviderSpecific{}, + ProviderSpecific: v1alpha2.ProviderSpecific{}, SetIdentifier: "", }, { @@ -159,11 +159,11 @@ func Test_toResourceRecordSets(t *testing.T) { RecordType: "CNAME", SetIdentifier: "2c71gf.lb-4ej5le.unittest.google.hcpapps.net", RecordTTL: 60, - Targets: v1alpha1.Targets{ + Targets: v1alpha2.Targets{ "2c71gf.lb-4ej5le.unittest.google.hcpapps.net", }, - ProviderSpecific: v1alpha1.ProviderSpecific{ - v1alpha1.ProviderSpecificProperty{ + ProviderSpecific: v1alpha2.ProviderSpecific{ + v1alpha2.ProviderSpecificProperty{ Name: "weight", Value: "60", }, @@ -177,8 +177,8 @@ func Test_toResourceRecordSets(t *testing.T) { "europe-west1.lb-4ej5le.unittest.google.hcpapps.net", }, RecordTTL: 300, - ProviderSpecific: v1alpha1.ProviderSpecific{ - v1alpha1.ProviderSpecificProperty{ + ProviderSpecific: v1alpha2.ProviderSpecific{ + v1alpha2.ProviderSpecificProperty{ Name: "geo-code", Value: "europe-west1", }, @@ -254,12 +254,12 @@ func Test_toResourceRecordSets(t *testing.T) { { name: "Successful test no Geo & weight", args: args{ - allEndpoints: []*v1alpha1.Endpoint{ + allEndpoints: []*v1alpha2.Endpoint{ { DNSName: "2c71gf.lb-4ej5le.unittest.google.hcpapps.net", RecordType: "A", RecordTTL: 60, - Targets: v1alpha1.Targets{ + Targets: v1alpha2.Targets{ "0.0.0.0", }, SetIdentifier: "", @@ -269,11 +269,11 @@ func Test_toResourceRecordSets(t *testing.T) { RecordType: "CNAME", SetIdentifier: "2c71gf.lb-4ej5le.unittest.google.hcpapps.net", RecordTTL: 60, - Targets: v1alpha1.Targets{ + Targets: v1alpha2.Targets{ "2c71gf.lb-4ej5le.unittest.google.hcpapps.net", }, - ProviderSpecific: v1alpha1.ProviderSpecific{ - v1alpha1.ProviderSpecificProperty{ + ProviderSpecific: v1alpha2.ProviderSpecific{ + v1alpha2.ProviderSpecificProperty{ Name: "weight", Value: "120", }, @@ -287,8 +287,8 @@ func Test_toResourceRecordSets(t *testing.T) { "default.lb-4ej5le.unittest.google.hcpapps.net", }, RecordTTL: 300, - ProviderSpecific: v1alpha1.ProviderSpecific{ - v1alpha1.ProviderSpecificProperty{ + ProviderSpecific: v1alpha2.ProviderSpecific{ + v1alpha2.ProviderSpecificProperty{ Name: "geo-code", Value: "*", }, @@ -362,12 +362,12 @@ func Test_toResourceRecordSets(t *testing.T) { { name: "Successful test weight round robin with multiple targets", args: args{ - allEndpoints: []*v1alpha1.Endpoint{ + allEndpoints: []*v1alpha2.Endpoint{ { DNSName: "2c71gf.lb-4ej5le.unittest.google.hcpapps.net", RecordType: "A", RecordTTL: 60, - Targets: v1alpha1.Targets{ + Targets: v1alpha2.Targets{ "0.0.0.0", }, SetIdentifier: "", @@ -376,7 +376,7 @@ func Test_toResourceRecordSets(t *testing.T) { DNSName: "lrnse3.lb-4ej5le.unittest.google.hcpapps.net", RecordType: "A", RecordTTL: 60, - Targets: v1alpha1.Targets{ + Targets: v1alpha2.Targets{ "0.0.0.1", }, SetIdentifier: "", @@ -386,11 +386,11 @@ func Test_toResourceRecordSets(t *testing.T) { RecordType: "CNAME", SetIdentifier: "2c71gf.lb-4ej5le.unittest.google.hcpapps.net", RecordTTL: 60, - Targets: v1alpha1.Targets{ + Targets: v1alpha2.Targets{ "2c71gf.lb-4ej5le.unittest.google.hcpapps.net", }, - ProviderSpecific: v1alpha1.ProviderSpecific{ - v1alpha1.ProviderSpecificProperty{ + ProviderSpecific: v1alpha2.ProviderSpecific{ + v1alpha2.ProviderSpecificProperty{ Name: "weight", Value: "120", }, @@ -401,11 +401,11 @@ func Test_toResourceRecordSets(t *testing.T) { RecordType: "CNAME", SetIdentifier: "lrnse3.lb-4ej5le.unittest.google.hcpapps.net", RecordTTL: 60, - Targets: v1alpha1.Targets{ + Targets: v1alpha2.Targets{ "lrnse3.lb-4ej5le.unittest.google.hcpapps.net", }, - ProviderSpecific: v1alpha1.ProviderSpecific{ - v1alpha1.ProviderSpecificProperty{ + ProviderSpecific: v1alpha2.ProviderSpecific{ + v1alpha2.ProviderSpecificProperty{ Name: "weight", Value: "120", }, @@ -419,8 +419,8 @@ func Test_toResourceRecordSets(t *testing.T) { "default.lb-4ej5le.unittest.google.hcpapps.net", }, RecordTTL: 300, - ProviderSpecific: v1alpha1.ProviderSpecific{ - v1alpha1.ProviderSpecificProperty{ + ProviderSpecific: v1alpha2.ProviderSpecific{ + v1alpha2.ProviderSpecificProperty{ Name: "geo-code", Value: "*", }, diff --git a/pkg/dns/health.go b/pkg/dns/health.go index 0f7d47349..b3faf2d03 100644 --- a/pkg/dns/health.go +++ b/pkg/dns/health.go @@ -5,13 +5,13 @@ import ( "reflect" "sync" - "github.com/Kuadrant/multicluster-gateway-controller/pkg/apis/v1alpha1" + "github.com/Kuadrant/multicluster-gateway-controller/pkg/apis/v1alpha2" ) type HealthCheckReconciler interface { - Reconcile(ctx context.Context, spec HealthCheckSpec, endpoint *v1alpha1.Endpoint) (HealthCheckResult, error) + Reconcile(ctx context.Context, spec HealthCheckSpec, endpoint *v1alpha2.Endpoint) (HealthCheckResult, error) - Delete(ctx context.Context, endpoint *v1alpha1.Endpoint) (HealthCheckResult, error) + Delete(ctx context.Context, endpoint *v1alpha2.Endpoint) (HealthCheckResult, error) } type HealthCheckSpec struct { @@ -53,11 +53,11 @@ const HealthCheckProtocolHTTPS HealthCheckProtocol = "HTTPS" type FakeHealthCheckReconciler struct{} -func (*FakeHealthCheckReconciler) Reconcile(ctx context.Context, _ HealthCheckSpec, _ *v1alpha1.Endpoint) (HealthCheckResult, error) { +func (*FakeHealthCheckReconciler) Reconcile(ctx context.Context, _ HealthCheckSpec, _ *v1alpha2.Endpoint) (HealthCheckResult, error) { return HealthCheckResult{HealthCheckCreated, ""}, nil } -func (*FakeHealthCheckReconciler) Delete(ctx context.Context, _ *v1alpha1.Endpoint) (HealthCheckResult, error) { +func (*FakeHealthCheckReconciler) Delete(ctx context.Context, _ *v1alpha2.Endpoint) (HealthCheckResult, error) { return HealthCheckResult{HealthCheckDeleted, ""}, nil } @@ -81,7 +81,7 @@ func NewCachedHealthCheckReconciler(provider Provider, reconciler HealthCheckRec } // Delete implements HealthCheckReconciler -func (r *CachedHealthCheckReconciler) Delete(ctx context.Context, endpoint *v1alpha1.Endpoint) (HealthCheckResult, error) { +func (r *CachedHealthCheckReconciler) Delete(ctx context.Context, endpoint *v1alpha2.Endpoint) (HealthCheckResult, error) { id, ok := r.getHealthCheckID(endpoint) if !ok { return NewHealthCheckResult(HealthCheckNoop, ""), nil @@ -92,7 +92,7 @@ func (r *CachedHealthCheckReconciler) Delete(ctx context.Context, endpoint *v1al } // Reconcile implements HealthCheckReconciler -func (r *CachedHealthCheckReconciler) Reconcile(ctx context.Context, spec HealthCheckSpec, endpoint *v1alpha1.Endpoint) (HealthCheckResult, error) { +func (r *CachedHealthCheckReconciler) Reconcile(ctx context.Context, spec HealthCheckSpec, endpoint *v1alpha2.Endpoint) (HealthCheckResult, error) { id, ok := r.getHealthCheckID(endpoint) if !ok { return r.reconciler.Reconcile(ctx, spec, endpoint) @@ -116,6 +116,6 @@ func (r *CachedHealthCheckReconciler) Reconcile(ctx context.Context, spec Health return r.reconciler.Reconcile(ctx, spec, endpoint) } -func (r *CachedHealthCheckReconciler) getHealthCheckID(endpoint *v1alpha1.Endpoint) (string, bool) { +func (r *CachedHealthCheckReconciler) getHealthCheckID(endpoint *v1alpha2.Endpoint) (string, bool) { return endpoint.GetProviderSpecific(r.provider.ProviderSpecific().HealthCheckID) } diff --git a/pkg/dns/target.go b/pkg/dns/target.go index f00e6dd80..9248dd090 100644 --- a/pkg/dns/target.go +++ b/pkg/dns/target.go @@ -12,11 +12,12 @@ import ( gatewayapiv1 "sigs.k8s.io/gateway-api/apis/v1" "github.com/Kuadrant/multicluster-gateway-controller/pkg/apis/v1alpha1" + "github.com/Kuadrant/multicluster-gateway-controller/pkg/apis/v1alpha2" "github.com/Kuadrant/multicluster-gateway-controller/pkg/utils" ) const ( - DefaultWeight = int(v1alpha1.DefaultWeight) + DefaultWeight = int(v1alpha2.DefaultWeight) DefaultGeo GeoCode = "default" WildcardGeo GeoCode = "*" LabelLBAttributeGeoCode = "kuadrant.io/lb-attribute-geo-code" @@ -26,10 +27,10 @@ const ( type MultiClusterGatewayTarget struct { Gateway *gatewayapiv1.Gateway ClusterGatewayTargets []ClusterGatewayTarget - LoadBalancing *v1alpha1.LoadBalancingSpec + LoadBalancing *v1alpha2.LoadBalancingSpec } -func NewMultiClusterGatewayTarget(gateway *gatewayapiv1.Gateway, clusterGateways []utils.ClusterGateway, loadBalancing *v1alpha1.LoadBalancingSpec) (*MultiClusterGatewayTarget, error) { +func NewMultiClusterGatewayTarget(gateway *gatewayapiv1.Gateway, clusterGateways []utils.ClusterGateway, loadBalancing *v1alpha2.LoadBalancingSpec) (*MultiClusterGatewayTarget, error) { mcg := &MultiClusterGatewayTarget{Gateway: gateway, LoadBalancing: loadBalancing} err := mcg.setClusterGatewayTargets(clusterGateways) return mcg, err @@ -69,7 +70,7 @@ func (t *MultiClusterGatewayTarget) GetDefaultWeight() int { func (t *MultiClusterGatewayTarget) setClusterGatewayTargets(clusterGateways []utils.ClusterGateway) error { var cgTargets []ClusterGatewayTarget for _, cg := range clusterGateways { - var customWeights []*v1alpha1.CustomWeight + var customWeights []*v1alpha2.CustomWeight if t.LoadBalancing != nil && t.LoadBalancing.Weighted != nil { customWeights = t.LoadBalancing.Weighted.Custom } @@ -100,7 +101,7 @@ type ClusterGatewayTarget struct { Weight *int } -func NewClusterGatewayTarget(cg utils.ClusterGateway, defaultGeoCode GeoCode, defaultWeight int, customWeights []*v1alpha1.CustomWeight) (ClusterGatewayTarget, error) { +func NewClusterGatewayTarget(cg utils.ClusterGateway, defaultGeoCode GeoCode, defaultWeight int, customWeights []*v1alpha2.CustomWeight) (ClusterGatewayTarget, error) { target := ClusterGatewayTarget{ ClusterGateway: &cg, } @@ -197,7 +198,7 @@ func dnsHealthCheckProbeName(address, gatewayName, listenerName string) string { return fmt.Sprintf("%s-%s-%s", address, gatewayName, listenerName) } -func (t *ClusterGatewayTarget) setWeight(defaultWeight int, customWeights []*v1alpha1.CustomWeight) error { +func (t *ClusterGatewayTarget) setWeight(defaultWeight int, customWeights []*v1alpha2.CustomWeight) error { weight := defaultWeight for k := range customWeights { cw := customWeights[k] diff --git a/pkg/dns/target_test.go b/pkg/dns/target_test.go index 1b97e2d5a..c29a7dbe3 100644 --- a/pkg/dns/target_test.go +++ b/pkg/dns/target_test.go @@ -12,6 +12,7 @@ import ( gatewayapiv1 "sigs.k8s.io/gateway-api/apis/v1" "github.com/Kuadrant/multicluster-gateway-controller/pkg/apis/v1alpha1" + "github.com/Kuadrant/multicluster-gateway-controller/pkg/apis/v1alpha2" "github.com/Kuadrant/multicluster-gateway-controller/pkg/utils" testutil "github.com/Kuadrant/multicluster-gateway-controller/test/util" ) @@ -29,7 +30,7 @@ func TestNewClusterGatewayTarget(t *testing.T) { clusterGateway utils.ClusterGateway defaultGeoCode GeoCode defaultWeight int - customWeights []*v1alpha1.CustomWeight + customWeights []*v1alpha2.CustomWeight } testCases := []struct { name string @@ -51,7 +52,7 @@ func TestNewClusterGatewayTarget(t *testing.T) { }, defaultWeight: 100, defaultGeoCode: GeoCode("IE"), - customWeights: []*v1alpha1.CustomWeight{}, + customWeights: []*v1alpha2.CustomWeight{}, }, want: ClusterGatewayTarget{ ClusterGateway: &utils.ClusterGateway{ @@ -88,7 +89,7 @@ func TestNewClusterGatewayTarget(t *testing.T) { }, defaultWeight: 100, defaultGeoCode: GeoCode("IE"), - customWeights: []*v1alpha1.CustomWeight{ + customWeights: []*v1alpha2.CustomWeight{ { Selector: &metav1.LabelSelector{ MatchLabels: map[string]string{ @@ -142,7 +143,7 @@ func TestNewMultiClusterGatewayTarget(t *testing.T) { type args struct { gateway *gatewayapiv1.Gateway clusterGateways []utils.ClusterGateway - loadBalancing *v1alpha1.LoadBalancingSpec + loadBalancing *v1alpha2.LoadBalancingSpec } gateway := &gatewayapiv1.Gateway{ ObjectMeta: v1.ObjectMeta{ @@ -252,11 +253,11 @@ func TestNewMultiClusterGatewayTarget(t *testing.T) { ClusterName: clusterName2, }, }, - loadBalancing: &v1alpha1.LoadBalancingSpec{ - Weighted: &v1alpha1.LoadBalancingWeighted{ + loadBalancing: &v1alpha2.LoadBalancingSpec{ + Weighted: &v1alpha2.LoadBalancingWeighted{ DefaultWeight: 255, }, - Geo: &v1alpha1.LoadBalancingGeo{ + Geo: &v1alpha2.LoadBalancingGeo{ DefaultGeo: "IE", }, }, @@ -295,11 +296,11 @@ func TestNewMultiClusterGatewayTarget(t *testing.T) { Weight: testutil.Pointer(255), }, }, - LoadBalancing: &v1alpha1.LoadBalancingSpec{ - Weighted: &v1alpha1.LoadBalancingWeighted{ + LoadBalancing: &v1alpha2.LoadBalancingSpec{ + Weighted: &v1alpha2.LoadBalancingWeighted{ DefaultWeight: 255, }, - Geo: &v1alpha1.LoadBalancingGeo{ + Geo: &v1alpha2.LoadBalancingGeo{ DefaultGeo: "IE", }, }, @@ -336,10 +337,10 @@ func TestNewMultiClusterGatewayTarget(t *testing.T) { ClusterName: clusterName2, }, }, - loadBalancing: &v1alpha1.LoadBalancingSpec{ - Weighted: &v1alpha1.LoadBalancingWeighted{ + loadBalancing: &v1alpha2.LoadBalancingSpec{ + Weighted: &v1alpha2.LoadBalancingWeighted{ DefaultWeight: 255, - Custom: []*v1alpha1.CustomWeight{ + Custom: []*v1alpha2.CustomWeight{ { Selector: &metav1.LabelSelector{ MatchLabels: map[string]string{ @@ -350,7 +351,7 @@ func TestNewMultiClusterGatewayTarget(t *testing.T) { }, }, }, - Geo: &v1alpha1.LoadBalancingGeo{ + Geo: &v1alpha2.LoadBalancingGeo{ DefaultGeo: "IE", }, }, @@ -391,10 +392,10 @@ func TestNewMultiClusterGatewayTarget(t *testing.T) { Weight: testutil.Pointer(255), }, }, - LoadBalancing: &v1alpha1.LoadBalancingSpec{ - Weighted: &v1alpha1.LoadBalancingWeighted{ + LoadBalancing: &v1alpha2.LoadBalancingSpec{ + Weighted: &v1alpha2.LoadBalancingWeighted{ DefaultWeight: 255, - Custom: []*v1alpha1.CustomWeight{ + Custom: []*v1alpha2.CustomWeight{ { Selector: &metav1.LabelSelector{ MatchLabels: map[string]string{ @@ -405,7 +406,7 @@ func TestNewMultiClusterGatewayTarget(t *testing.T) { }, }, }, - Geo: &v1alpha1.LoadBalancingGeo{ + Geo: &v1alpha2.LoadBalancingGeo{ DefaultGeo: "IE", }, }, @@ -513,7 +514,7 @@ func TestClusterGatewayTarget_setWeight(t *testing.T) { testCases := []struct { name string defaultWeight int - customWeights []*v1alpha1.CustomWeight + customWeights []*v1alpha2.CustomWeight gatewayLabels map[string]string want int wantErr bool @@ -522,7 +523,7 @@ func TestClusterGatewayTarget_setWeight(t *testing.T) { name: "sets geo from default", defaultWeight: 255, gatewayLabels: nil, - customWeights: []*v1alpha1.CustomWeight{}, + customWeights: []*v1alpha2.CustomWeight{}, want: 255, wantErr: false, }, @@ -532,7 +533,7 @@ func TestClusterGatewayTarget_setWeight(t *testing.T) { gatewayLabels: map[string]string{ "tstlabel1": "TSTATTR", }, - customWeights: []*v1alpha1.CustomWeight{ + customWeights: []*v1alpha2.CustomWeight{ { Selector: &metav1.LabelSelector{ MatchLabels: map[string]string{ @@ -552,7 +553,7 @@ func TestClusterGatewayTarget_setWeight(t *testing.T) { "tstlabel1": "TSTATTR", "tstlabel2": "TSTATTR2", }, - customWeights: []*v1alpha1.CustomWeight{ + customWeights: []*v1alpha2.CustomWeight{ { Selector: &metav1.LabelSelector{ MatchLabels: map[string]string{ @@ -572,7 +573,7 @@ func TestClusterGatewayTarget_setWeight(t *testing.T) { gatewayLabels: map[string]string{ "tstlabel1": "TSTATTR", }, - customWeights: []*v1alpha1.CustomWeight{ + customWeights: []*v1alpha2.CustomWeight{ { Selector: &metav1.LabelSelector{ MatchLabels: map[string]string{ @@ -592,7 +593,7 @@ func TestClusterGatewayTarget_setWeight(t *testing.T) { gatewayLabels: map[string]string{ "/tstlabel1": "TSTATTR", }, - customWeights: []*v1alpha1.CustomWeight{ + customWeights: []*v1alpha2.CustomWeight{ { Selector: &metav1.LabelSelector{ MatchLabels: map[string]string{ @@ -649,7 +650,7 @@ func TestMultiClusterGatewayTarget_RemoveUnhealthyGatewayAddresses(t *testing.T) type fields struct { Gateway *gatewayapiv1.Gateway ClusterGatewayTargets []ClusterGatewayTarget - LoadBalancing *v1alpha1.LoadBalancingSpec + LoadBalancing *v1alpha2.LoadBalancingSpec } type args struct { probes []*v1alpha1.DNSHealthCheckProbe diff --git a/pkg/policysync/policy_test.go b/pkg/policysync/policy_test.go index 3258a8234..2574dc495 100644 --- a/pkg/policysync/policy_test.go +++ b/pkg/policysync/policy_test.go @@ -7,12 +7,12 @@ import ( gatewayapiv1 "sigs.k8s.io/gateway-api/apis/v1" gatewayapiv1alpha2 "sigs.k8s.io/gateway-api/apis/v1alpha2" - "github.com/Kuadrant/multicluster-gateway-controller/pkg/apis/v1alpha1" + "github.com/Kuadrant/multicluster-gateway-controller/pkg/apis/v1alpha2" ) func TestReflectPolicy(t *testing.T) { - policy := &v1alpha1.DNSPolicy{ - Spec: v1alpha1.DNSPolicySpec{ + policy := &v1alpha2.DNSPolicy{ + Spec: v1alpha2.DNSPolicySpec{ TargetRef: gatewayapiv1alpha2.PolicyTargetReference{ Group: gatewayapiv1.Group("test.io"), Kind: gatewayapiv1.Kind("Test"), diff --git a/test/e2e/dnspolicy_providers_istio_gateway_test.go b/test/e2e/dnspolicy_providers_istio_gateway_test.go new file mode 100644 index 000000000..2ba8703f7 --- /dev/null +++ b/test/e2e/dnspolicy_providers_istio_gateway_test.go @@ -0,0 +1,394 @@ +//go:build e2e + +package e2e + +import ( + "context" + "encoding/json" + "fmt" + "strings" + "time" + + . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" + . "github.com/onsi/gomega/gstruct" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "sigs.k8s.io/controller-runtime/pkg/client" + gatewayapiv1 "sigs.k8s.io/gateway-api/apis/v1" + + "github.com/Kuadrant/multicluster-gateway-controller/pkg/_internal/conditions" + "github.com/Kuadrant/multicluster-gateway-controller/pkg/apis/v1alpha2" + . "github.com/Kuadrant/multicluster-gateway-controller/test/util" +) + +var _ = Describe("DNSPolicy Targeting an Istio Gateway", func() { + + // testID is a randomly generated identifier for the test + // it is used to name resources and/or namespaces so different + // tests can be run in parallel in the same cluster + var testID string + // testNamespace provided namespace in which to run tests (must contain provider secret) + var testNamespace string + // testZoneID provided zone id for the provider zone i.e. Route53 Hosted zone ID or GCP Managed zone Name + var testZoneID string + // testZoneDomainName provided domain name for the testZoneID e.g. e2e.hcpapps.net + var testZoneDomainName string + // testDomainName generated domain for this test e.g. t-e2e-12345.e2e.hcpapps.net + var testDomainName string + // testHostname generated hostname for this test e.g. t-dns-istio.t-e2e-12345.e2e.hcpapps.net + var testHostname gatewayapiv1.Hostname + + var k8sClient client.Client + + var gw *gatewayapiv1.Gateway + var httproute *gatewayapiv1.HTTPRoute + var dnsPolicy *v1alpha2.DNSPolicy + var mz *v1alpha2.ManagedZone + + BeforeEach(func(ctx SpecContext) { + testID = "t-dns-" + tconfig.GenerateName() + //ToDo Have this generate a new namespace instead of using the Hub Namespace and consider using a spoke client. + // This currently still relies on the provider credentials secret being created ahead of time in a target namespace + testNamespace = tconfig.HubNamespace() + testZoneID = tconfig.DNSZoneID() + testZoneDomainName = tconfig.DNSZoneDomainName() + testDomainName = strings.Join([]string{testSuiteID, testZoneDomainName}, ".") + testHostname = gatewayapiv1.Hostname(strings.Join([]string{testID, testDomainName}, ".")) + k8sClient = tconfig.HubClient() + + GinkgoWriter.Printf("[debug] testHostname: '%s'\n", testHostname) + + By("creating an Istio Gateway") + gw = NewGatewayBuilder(testID, IstioGatewayClassName, testNamespace). + WithListener(gatewayapiv1.Listener{ + Name: "http", + Hostname: &testHostname, + Port: 80, + Protocol: gatewayapiv1.HTTPProtocolType, + AllowedRoutes: &gatewayapiv1.AllowedRoutes{ + Namespaces: &gatewayapiv1.RouteNamespaces{ + From: Pointer(gatewayapiv1.NamespacesFromAll), + }, + }, + }).WithLabels(map[string]string{"gw": "t-e2e"}).Gateway + err := k8sClient.Create(ctx, gw) + Expect(err).ToNot(HaveOccurred()) + + By("creating an HTTPRoute") + httproute = &gatewayapiv1.HTTPRoute{ + ObjectMeta: metav1.ObjectMeta{ + Name: testID, + Namespace: testNamespace, + }, + Spec: gatewayapiv1.HTTPRouteSpec{ + CommonRouteSpec: gatewayapiv1.CommonRouteSpec{ + ParentRefs: []gatewayapiv1.ParentReference{{ + Namespace: Pointer(gatewayapiv1.Namespace(testNamespace)), + Name: gatewayapiv1.ObjectName(gw.GetName()), + Kind: Pointer(gatewayapiv1.Kind("Gateway")), + }}, + }, + Hostnames: []gatewayapiv1.Hostname{testHostname}, + Rules: []gatewayapiv1.HTTPRouteRule{{ + BackendRefs: []gatewayapiv1.HTTPBackendRef{{ + BackendRef: gatewayapiv1.BackendRef{ + BackendObjectReference: gatewayapiv1.BackendObjectReference{ + Kind: Pointer(gatewayapiv1.Kind("Service")), + Name: "test", + Port: Pointer(gatewayapiv1.PortNumber(8080)), + }, + }, + }}, + }}, + }, + } + err = k8sClient.Create(ctx, httproute) + Expect(err).ToNot(HaveOccurred()) + }) + + AfterEach(func(ctx SpecContext) { + if dnsPolicy != nil { + err := k8sClient.Delete(ctx, dnsPolicy, + client.PropagationPolicy(metav1.DeletePropagationForeground)) + Expect(client.IgnoreNotFound(err)).ToNot(HaveOccurred()) + Eventually(func(g Gomega) { // wait until it's gone to allow time for DNSRecords to be cleaned up + err := k8sClient.Get(ctx, client.ObjectKeyFromObject(dnsPolicy), dnsPolicy) + g.Expect(err).To(HaveOccurred()) + g.Expect(err).To(MatchError(ContainSubstring("not found"))) + + recordList := &v1alpha2.DNSRecordList{} + err = k8sClient.List(ctx, recordList, &client.MatchingLabels{"kuadrant.io/gateway": gw.GetName()}, &client.ListOptions{Namespace: testNamespace}) + g.Expect(err).NotTo(HaveOccurred()) + g.Expect(recordList.Items).To(BeEmpty()) + }, TestTimeoutMedium, time.Second).Should(Succeed()) + } + if mz != nil { + err := k8sClient.Delete(ctx, mz, + client.PropagationPolicy(metav1.DeletePropagationForeground)) + Expect(client.IgnoreNotFound(err)).ToNot(HaveOccurred()) + } + if httproute != nil { + err := k8sClient.Delete(ctx, httproute, + client.PropagationPolicy(metav1.DeletePropagationForeground)) + Expect(client.IgnoreNotFound(err)).ToNot(HaveOccurred()) + } + if gw != nil { + err := k8sClient.Delete(ctx, gw, + client.PropagationPolicy(metav1.DeletePropagationForeground)) + Expect(client.IgnoreNotFound(err)).ToNot(HaveOccurred()) + } + }) + + Context("ManagedZone Provider", func() { + + BeforeEach(func(ctx SpecContext) { + By("creating a ManagedZone") + mz = NewManagedZoneBuilder(testID, testNamespace). + WithID(testZoneID). + WithDomainName(testDomainName). + WithProviderSecret(tconfig.DNSProviderSecretName()). + ManagedZone + err := k8sClient.Create(ctx, mz) + Expect(err).ToNot(HaveOccurred()) + }) + + It("makes the hostname resolvable when a dnspolicy and httproute are attached", func(ctx SpecContext) { + + By("creating a DNSPolicy with ManagedZone provider") + dnsPolicy = NewDNSPolicyBuilder(testID, testNamespace). + WithTargetGateway(gw.GetName()). + WithProviderManagedZone(mz.GetName()). + WithRoutingStrategy(v1alpha2.SimpleRoutingStrategy). + DNSPolicy + err := k8sClient.Create(ctx, dnsPolicy) + Expect(err).ToNot(HaveOccurred()) + + Eventually(func(g Gomega) { + err := k8sClient.Get(ctx, client.ObjectKeyFromObject(dnsPolicy), dnsPolicy) + g.Expect(err).NotTo(HaveOccurred()) + g.Expect(dnsPolicy.Status.Conditions).To( + ContainElement(MatchFields(IgnoreExtras, Fields{ + "Type": Equal(string(conditions.ConditionTypeReady)), + "Status": Equal(metav1.ConditionTrue), + "Reason": Equal("GatewayDNSEnabled"), + })), + ) + + policyBackRefValue := testNamespace + "/" + dnsPolicy.Name + refs, _ := json.Marshal([]client.ObjectKey{{Name: dnsPolicy.Name, Namespace: testNamespace}}) + policiesBackRefValue := string(refs) + err = k8sClient.Get(ctx, client.ObjectKeyFromObject(gw), gw) + g.Expect(err).NotTo(HaveOccurred()) + g.Expect(gw.Annotations).To(HaveKeyWithValue(DNSPolicyBackRefAnnotation, policyBackRefValue)) + g.Expect(gw.Annotations).To(HaveKeyWithValue(DNSPoliciesBackRefAnnotation, policiesBackRefValue)) + }, TestTimeoutMedium, time.Second).Should(Succeed()) + + expectedRecordName := fmt.Sprintf("%s-%s", gw.GetName(), "http") + Eventually(func(g Gomega) { + dnsrecord := &v1alpha2.DNSRecord{ + ObjectMeta: metav1.ObjectMeta{ + Name: expectedRecordName, + Namespace: testNamespace, + }, + } + err := k8sClient.Get(ctx, client.ObjectKeyFromObject(dnsrecord), dnsrecord) + g.Expect(err).NotTo(HaveOccurred()) + g.Expect(dnsrecord.Status.Conditions).To( + ContainElement(MatchFields(IgnoreExtras, Fields{ + "Type": Equal(string(conditions.ConditionTypeReady)), + "Status": Equal(metav1.ConditionTrue), + })), + ) + g.Expect(dnsrecord.Spec.ZoneID).Should(PointTo(Equal(testZoneID))) + g.Expect(dnsrecord.Spec.ProviderRef).Should(Equal(dnsPolicy.Spec.ProviderRef)) + g.Expect(dnsrecord.Spec.Endpoints).Should(ConsistOf( + PointTo(MatchFields(IgnoreExtras, Fields{ + "DNSName": Equal(string(testHostname)), + "Targets": Not(BeEmpty()), + "RecordType": Equal("A"), + "SetIdentifier": Equal(""), + "RecordTTL": Equal(v1alpha2.TTL(60)), + })), + )) + g.Expect(dnsrecord.Status.Endpoints).Should(ConsistOf( + PointTo(MatchFields(IgnoreExtras, Fields{ + "DNSName": Equal(string(testHostname)), + "Targets": Not(BeEmpty()), + "RecordType": Equal("A"), + "SetIdentifier": Equal(""), + "RecordTTL": Equal(v1alpha2.TTL(60)), + })), + )) + }, TestTimeoutLong, time.Second, ctx).Should(Succeed()) + + By("ensuring the authoritative nameserver resolves the hostname") + // speed up things by using the authoritative nameserver + authoritativeResolver := ResolverForDomainName(testZoneDomainName) + Eventually(func(ctx SpecContext) bool { + c, cancel := context.WithTimeout(ctx, 10*time.Second) + defer cancel() + IPs, err := authoritativeResolver.LookupHost(c, string(testHostname)) + if err != nil { + GinkgoWriter.Printf("[debug] LookupHost error: '%s'\n", err) + } + return err == nil && len(IPs) > 0 + }).WithTimeout(300 * time.Second).WithPolling(10 * time.Second).WithContext(ctx).Should(BeTrue()) + + }) + }) + + Context("Secret Provider", func() { + + It("makes the hostname resolvable when a dnspolicy and httproute are attached", func(ctx SpecContext) { + + By("creating a DNSPolicy with Secret provider") + dnsPolicy = NewDNSPolicyBuilder(testID, testNamespace). + WithTargetGateway(gw.GetName()). + WithProviderSecret(tconfig.DNSProviderSecretName()). + WithRoutingStrategy(v1alpha2.SimpleRoutingStrategy). + DNSPolicy + err := k8sClient.Create(ctx, dnsPolicy) + Expect(err).ToNot(HaveOccurred()) + + Eventually(func(g Gomega) { + err := k8sClient.Get(ctx, client.ObjectKeyFromObject(dnsPolicy), dnsPolicy) + g.Expect(err).NotTo(HaveOccurred()) + g.Expect(dnsPolicy.Status.Conditions).To( + ContainElement(MatchFields(IgnoreExtras, Fields{ + "Type": Equal(string(conditions.ConditionTypeReady)), + "Status": Equal(metav1.ConditionTrue), + "Reason": Equal("GatewayDNSEnabled"), + })), + ) + + policyBackRefValue := testNamespace + "/" + dnsPolicy.Name + refs, _ := json.Marshal([]client.ObjectKey{{Name: dnsPolicy.Name, Namespace: testNamespace}}) + policiesBackRefValue := string(refs) + err = k8sClient.Get(ctx, client.ObjectKeyFromObject(gw), gw) + g.Expect(err).NotTo(HaveOccurred()) + g.Expect(gw.Annotations).To(HaveKeyWithValue(DNSPolicyBackRefAnnotation, policyBackRefValue)) + g.Expect(gw.Annotations).To(HaveKeyWithValue(DNSPoliciesBackRefAnnotation, policiesBackRefValue)) + }, TestTimeoutLong, time.Second).Should(Succeed()) + + expectedRecordName := fmt.Sprintf("%s-%s", gw.GetName(), "http") + Eventually(func(g Gomega) { + dnsrecord := &v1alpha2.DNSRecord{ + ObjectMeta: metav1.ObjectMeta{ + Name: expectedRecordName, + Namespace: testNamespace, + }, + } + err := k8sClient.Get(ctx, client.ObjectKeyFromObject(dnsrecord), dnsrecord) + g.Expect(err).NotTo(HaveOccurred()) + g.Expect(dnsrecord.Status.Conditions).To( + ContainElement(MatchFields(IgnoreExtras, Fields{ + "Type": Equal(string(conditions.ConditionTypeReady)), + "Status": Equal(metav1.ConditionTrue), + })), + ) + g.Expect(dnsrecord.Spec.ZoneID).Should(PointTo(Equal(testZoneID))) + g.Expect(dnsrecord.Spec.ProviderRef).Should(Equal(dnsPolicy.Spec.ProviderRef)) + g.Expect(dnsrecord.Spec.Endpoints).Should(ConsistOf( + PointTo(MatchFields(IgnoreExtras, Fields{ + "DNSName": Equal(string(testHostname)), + "Targets": Not(BeEmpty()), + "RecordType": Equal("A"), + "SetIdentifier": Equal(""), + "RecordTTL": Equal(v1alpha2.TTL(60)), + })), + )) + // We need to wait for the status to be updated otherwise google can leave things behind + g.Expect(dnsrecord.Status.Endpoints).Should(ConsistOf( + PointTo(MatchFields(IgnoreExtras, Fields{ + "DNSName": Equal(string(testHostname)), + "Targets": Not(BeEmpty()), + "RecordType": Equal("A"), + "SetIdentifier": Equal(""), + "RecordTTL": Equal(v1alpha2.TTL(60)), + })), + )) + }, TestTimeoutLong, time.Second, ctx).Should(Succeed()) + + By("ensuring the authoritative nameserver resolves the hostname") + // speed up things by using the authoritative nameserver + authoritativeResolver := ResolverForDomainName(testZoneDomainName) + Eventually(func(ctx SpecContext) bool { + c, cancel := context.WithTimeout(ctx, 10*time.Second) + defer cancel() + IPs, err := authoritativeResolver.LookupHost(c, string(testHostname)) + if err != nil { + GinkgoWriter.Printf("[debug] LookupHost error: '%s'\n", err) + } + return err == nil && len(IPs) > 0 + }).WithTimeout(300 * time.Second).WithPolling(10 * time.Second).WithContext(ctx).Should(BeTrue()) + + }) + }) + + Context("None Provider", func() { + + It("should create dns record with no zone assigned and record should not become ready", func(ctx SpecContext) { + + By("creating a DNSPolicy with None provider") + dnsPolicy = NewDNSPolicyBuilder(testID, testNamespace). + WithTargetGateway(gw.GetName()). + WithProviderNone("external-dns"). + WithRoutingStrategy(v1alpha2.SimpleRoutingStrategy). + DNSPolicy + err := k8sClient.Create(ctx, dnsPolicy) + Expect(err).ToNot(HaveOccurred()) + + Eventually(func(g Gomega) { + err := k8sClient.Get(ctx, client.ObjectKeyFromObject(dnsPolicy), dnsPolicy) + g.Expect(err).NotTo(HaveOccurred()) + g.Expect(dnsPolicy.Status.Conditions).To( + ContainElement(MatchFields(IgnoreExtras, Fields{ + "Type": Equal(string(conditions.ConditionTypeReady)), + "Status": Equal(metav1.ConditionTrue), + "Reason": Equal("GatewayDNSEnabled"), + })), + ) + + policyBackRefValue := testNamespace + "/" + dnsPolicy.Name + refs, _ := json.Marshal([]client.ObjectKey{{Name: dnsPolicy.Name, Namespace: testNamespace}}) + policiesBackRefValue := string(refs) + err = k8sClient.Get(ctx, client.ObjectKeyFromObject(gw), gw) + g.Expect(err).NotTo(HaveOccurred()) + g.Expect(gw.Annotations).To(HaveKeyWithValue(DNSPolicyBackRefAnnotation, policyBackRefValue)) + g.Expect(gw.Annotations).To(HaveKeyWithValue(DNSPoliciesBackRefAnnotation, policiesBackRefValue)) + }, TestTimeoutLong, time.Second).Should(Succeed()) + + expectedRecordName := fmt.Sprintf("%s-%s", gw.GetName(), "http") + Eventually(func(g Gomega) { + dnsrecord := &v1alpha2.DNSRecord{ + ObjectMeta: metav1.ObjectMeta{ + Name: expectedRecordName, + Namespace: testNamespace, + }, + } + err := k8sClient.Get(ctx, client.ObjectKeyFromObject(dnsrecord), dnsrecord) + g.Expect(err).NotTo(HaveOccurred()) + g.Expect(dnsrecord.Status.Conditions).ToNot( + ContainElement(MatchFields(IgnoreExtras, Fields{ + "Type": Equal(string(conditions.ConditionTypeReady)), + })), + ) + g.Expect(dnsrecord.Spec.ZoneID).Should(BeNil()) + g.Expect(dnsrecord.Spec.ProviderRef).Should(Equal(dnsPolicy.Spec.ProviderRef)) + g.Expect(dnsrecord.Spec.Endpoints).Should(ConsistOf( + PointTo(MatchFields(IgnoreExtras, Fields{ + "DNSName": Equal(string(testHostname)), + "Targets": Not(BeEmpty()), + "RecordType": Equal("A"), + "SetIdentifier": Equal(""), + "RecordTTL": Equal(v1alpha2.TTL(60)), + })), + )) + g.Expect(dnsrecord.Status.Endpoints).Should(BeEmpty()) + }, TestTimeoutLong, time.Second, ctx).Should(Succeed()) + + }) + }) + +}) diff --git a/test/e2e/gateway_single_spoke_test.go b/test/e2e/gateway_single_spoke_test.go index fcccb9691..7aeca0234 100644 --- a/test/e2e/gateway_single_spoke_test.go +++ b/test/e2e/gateway_single_spoke_test.go @@ -28,6 +28,7 @@ import ( "github.com/Kuadrant/multicluster-gateway-controller/pkg/_internal/conditions" "github.com/Kuadrant/multicluster-gateway-controller/pkg/apis/v1alpha1" mgcv1alpha1 "github.com/Kuadrant/multicluster-gateway-controller/pkg/apis/v1alpha1" + mgcv1alpha2 "github.com/Kuadrant/multicluster-gateway-controller/pkg/apis/v1alpha2" . "github.com/Kuadrant/multicluster-gateway-controller/test/util" ) @@ -250,25 +251,28 @@ var _ = Describe("Gateway single target cluster", func() { }) When("a DNSPolicy is attached to the Gateway", func() { - var dnsPolicy *mgcv1alpha1.DNSPolicy + var dnsPolicy *mgcv1alpha2.DNSPolicy BeforeEach(func(ctx SpecContext) { By("creating a DNSPolicy in the hub") - - dnsPolicy = &mgcv1alpha1.DNSPolicy{ + dnsPolicy = &mgcv1alpha2.DNSPolicy{ ObjectMeta: metav1.ObjectMeta{ Name: testID, Namespace: tconfig.HubNamespace(), }, - Spec: mgcv1alpha1.DNSPolicySpec{ + Spec: mgcv1alpha2.DNSPolicySpec{ TargetRef: gatewayapiv1alpha2.PolicyTargetReference{ Group: "gateway.networking.k8s.io", Kind: "Gateway", Name: gatewayapiv1.ObjectName(testID), Namespace: Pointer(gatewayapiv1.Namespace(tconfig.HubNamespace())), }, - RoutingStrategy: v1alpha1.LoadBalancedRoutingStrategy, + RoutingStrategy: mgcv1alpha2.LoadBalancedRoutingStrategy, + ProviderRef: mgcv1alpha2.ProviderRef{ + Name: tconfig.DNSProviderSecretName(), + Kind: mgcv1alpha2.ProviderKindSecret, + }, }, } err := tconfig.HubClient().Create(ctx, dnsPolicy) @@ -304,7 +308,7 @@ var _ = Describe("Gateway single target cluster", func() { By("waiting for the DNSRecord to be created and ready in the Hub") { Eventually(func(g Gomega, ctx context.Context) { - dnsrecord := &mgcv1alpha1.DNSRecord{ObjectMeta: metav1.ObjectMeta{ + dnsrecord := &mgcv1alpha2.DNSRecord{ObjectMeta: metav1.ObjectMeta{ Name: fmt.Sprintf("%s-%s", gw.Name, "https"), Namespace: gw.Namespace, }} diff --git a/test/e2e/suite_test.go b/test/e2e/suite_test.go index d99ecf00e..9546a9052 100644 --- a/test/e2e/suite_test.go +++ b/test/e2e/suite_test.go @@ -24,6 +24,14 @@ var ( testSuiteID string ) +const ( + TestTimeoutMedium = time.Second * 10 + TestTimeoutLong = time.Second * 30 + + DNSPoliciesBackRefAnnotation = "kuadrant.io/dnspolicies" + DNSPolicyBackRefAnnotation = "kuadrant.io/dnspolicy" +) + func TestAPIs(t *testing.T) { RegisterFailHandler(Fail) RunSpecs(t, "E2E Tests Suite") diff --git a/test/gateway_integration/suite_test.go b/test/gateway_integration/suite_test.go index 7e2d30b21..6e684cd9c 100644 --- a/test/gateway_integration/suite_test.go +++ b/test/gateway_integration/suite_test.go @@ -38,8 +38,8 @@ import ( gatewayapiv1 "sigs.k8s.io/gateway-api/apis/v1" "github.com/Kuadrant/multicluster-gateway-controller/pkg/apis/v1alpha1" + "github.com/Kuadrant/multicluster-gateway-controller/pkg/apis/v1alpha2" . "github.com/Kuadrant/multicluster-gateway-controller/pkg/controllers/gateway" - "github.com/Kuadrant/multicluster-gateway-controller/pkg/dns" "github.com/Kuadrant/multicluster-gateway-controller/pkg/placement" //+kubebuilder:scaffold:imports ) @@ -48,15 +48,12 @@ import ( // http://onsi.github.io/ginkgo/ to learn more about Ginkgo. var ( - cfg *rest.Config - k8sClient client.Client - testEnv *envtest.Environment - ctx context.Context - cancel context.CancelFunc - logger logr.Logger - providerFactory = func(ctx context.Context, managedZone *v1alpha1.ManagedZone) (dns.Provider, error) { - return &dns.FakeProvider{}, nil - } + cfg *rest.Config + k8sClient client.Client + testEnv *envtest.Environment + ctx context.Context + cancel context.CancelFunc + logger logr.Logger ) func testClient() client.Client { return k8sClient } @@ -100,6 +97,9 @@ var _ = BeforeSuite(func() { err = v1alpha1.AddToScheme(scheme.Scheme) Expect(err).NotTo(HaveOccurred()) + err = v1alpha2.AddToScheme(scheme.Scheme) + Expect(err).NotTo(HaveOccurred()) + err = gatewayapiv1.AddToScheme(scheme.Scheme) Expect(err).NotTo(HaveOccurred()) diff --git a/test/policy_integration/dnspolicy_controller_health_checks_test.go b/test/policy_integration/dnspolicy_controller_health_checks_test.go index 322e6a23f..8de010a41 100644 --- a/test/policy_integration/dnspolicy_controller_health_checks_test.go +++ b/test/policy_integration/dnspolicy_controller_health_checks_test.go @@ -18,6 +18,7 @@ import ( gatewayapiv1 "sigs.k8s.io/gateway-api/apis/v1" "github.com/Kuadrant/multicluster-gateway-controller/pkg/apis/v1alpha1" + "github.com/Kuadrant/multicluster-gateway-controller/pkg/apis/v1alpha2" "github.com/Kuadrant/multicluster-gateway-controller/pkg/dns" "github.com/Kuadrant/multicluster-gateway-controller/pkg/utils" testutil "github.com/Kuadrant/multicluster-gateway-controller/test/util" @@ -26,11 +27,11 @@ import ( var _ = Describe("DNSPolicy Health Checks", func() { var gatewayClass *gatewayapiv1.GatewayClass - var managedZone *v1alpha1.ManagedZone + var managedZone *v1alpha2.ManagedZone var testNamespace string var dnsPolicyBuilder *testutil.DNSPolicyBuilder var gateway *gatewayapiv1.Gateway - var dnsPolicy *v1alpha1.DNSPolicy + var dnsPolicy *v1alpha2.DNSPolicy var lbHash, recordName, wildcardRecordName string BeforeEach(func() { @@ -39,7 +40,13 @@ var _ = Describe("DNSPolicy Health Checks", func() { gatewayClass = testutil.NewTestGatewayClass("foo", "default", "kuadrant.io/bar") Expect(k8sClient.Create(ctx, gatewayClass)).To(Succeed()) - managedZone = testutil.NewManagedZoneBuilder("mz-example-com", testNamespace, "example.com").ManagedZone + managedZone = testutil.NewManagedZoneBuilder("mz-example-com", testNamespace). + WithID("1234"). + WithDomainName("example.com"). + WithDescription("example.com"). + WithProviderSecret("secretname"). + ManagedZone + Expect(k8sClient.Create(ctx, managedZone)).To(Succeed()) gateway = testutil.NewGatewayBuilder(TestGatewayName, gatewayClass.Name, testNamespace). @@ -103,8 +110,9 @@ var _ = Describe("DNSPolicy Health Checks", func() { return k8sClient.Status().Update(ctx, gateway) }, TestTimeoutMedium, TestRetryIntervalMedium).ShouldNot(HaveOccurred()) - dnsPolicyBuilder = testutil.NewDNSPolicyBuilder("test-dns-policy", testNamespace) - dnsPolicyBuilder.WithTargetGateway(TestGatewayName) + dnsPolicyBuilder = testutil.NewDNSPolicyBuilder("test-dns-policy", testNamespace). + WithProviderManagedZone(managedZone.Name). + WithTargetGateway(TestGatewayName) lbHash = dns.ToBase36hash(fmt.Sprintf("%s-%s", gateway.Name, gateway.Namespace)) recordName = fmt.Sprintf("%s-%s", TestGatewayName, TestListenerNameOne) @@ -136,7 +144,7 @@ var _ = Describe("DNSPolicy Health Checks", func() { Context("loadbalanced routing strategy", func() { BeforeEach(func() { - dnsPolicyBuilder.WithRoutingStrategy(v1alpha1.LoadBalancedRoutingStrategy) + dnsPolicyBuilder.WithRoutingStrategy(v1alpha2.LoadBalancedRoutingStrategy) }) Context("with health checks", func() { @@ -155,7 +163,7 @@ var _ = Describe("DNSPolicy Health Checks", func() { It("should create dns records", func() { Eventually(func(g Gomega, ctx context.Context) { - recordList := &v1alpha1.DNSRecordList{} + recordList := &v1alpha2.DNSRecordList{} err := k8sClient.List(ctx, recordList, &client.ListOptions{Namespace: testNamespace}) g.Expect(err).NotTo(HaveOccurred()) g.Expect(recordList.Items).To(HaveLen(2)) @@ -164,15 +172,17 @@ var _ = Describe("DNSPolicy Health Checks", func() { MatchFields(IgnoreExtras, Fields{ "ObjectMeta": HaveField("Name", recordName), "Spec": MatchFields(IgnoreExtras, Fields{ - "ManagedZoneRef": HaveField("Name", "mz-example-com"), - "Endpoints": HaveLen(6), + "ZoneID": Equal(managedZone.Spec.ID), + "ProviderRef": Equal(dnsPolicy.Spec.ProviderRef), + "Endpoints": HaveLen(6), }), }), MatchFields(IgnoreExtras, Fields{ "ObjectMeta": HaveField("Name", wildcardRecordName), "Spec": MatchFields(IgnoreExtras, Fields{ - "ManagedZoneRef": HaveField("Name", "mz-example-com"), - "Endpoints": HaveLen(6), + "ZoneID": Equal(managedZone.Spec.ID), + "ProviderRef": Equal(dnsPolicy.Spec.ProviderRef), + "Endpoints": HaveLen(6), }), }), )) @@ -194,7 +204,7 @@ var _ = Describe("DNSPolicy Health Checks", func() { Context("all unhealthy probes", func() { It("should publish all dns records endpoints", func() { - expectedEndpoints := []*v1alpha1.Endpoint{ + expectedEndpoints := []*v1alpha2.Endpoint{ { DNSName: "2w705o.lb-" + lbHash + ".test.example.com", Targets: []string{ @@ -221,7 +231,7 @@ var _ = Describe("DNSPolicy Health Checks", func() { RecordType: "CNAME", SetIdentifier: "2w705o.lb-" + lbHash + ".test.example.com", RecordTTL: 60, - ProviderSpecific: v1alpha1.ProviderSpecific{ + ProviderSpecific: v1alpha2.ProviderSpecific{ { Name: "weight", Value: "120", @@ -237,7 +247,7 @@ var _ = Describe("DNSPolicy Health Checks", func() { SetIdentifier: "s07c46.lb-" + lbHash + ".test.example.com", RecordTTL: 60, Labels: nil, - ProviderSpecific: v1alpha1.ProviderSpecific{ + ProviderSpecific: v1alpha2.ProviderSpecific{ { Name: "weight", Value: "120", @@ -252,7 +262,7 @@ var _ = Describe("DNSPolicy Health Checks", func() { RecordType: "CNAME", SetIdentifier: "default", RecordTTL: 300, - ProviderSpecific: v1alpha1.ProviderSpecific{ + ProviderSpecific: v1alpha2.ProviderSpecific{ { Name: "geo-code", Value: "*", @@ -301,7 +311,7 @@ var _ = Describe("DNSPolicy Health Checks", func() { return nil }, TestTimeoutMedium, TestRetryIntervalMedium).Should(BeNil()) } - createdDNSRecord := &v1alpha1.DNSRecord{} + createdDNSRecord := &v1alpha2.DNSRecord{} Eventually(func() error { err := k8sClient.Get(ctx, client.ObjectKey{Name: recordName, Namespace: testNamespace}, createdDNSRecord) @@ -320,7 +330,7 @@ var _ = Describe("DNSPolicy Health Checks", func() { Context("some unhealthy probes", func() { It("should publish expected endpoints", func() { - expectedEndpoints := []*v1alpha1.Endpoint{ + expectedEndpoints := []*v1alpha2.Endpoint{ { DNSName: "2w705o.lb-" + lbHash + ".test.example.com", Targets: []string{ @@ -347,7 +357,7 @@ var _ = Describe("DNSPolicy Health Checks", func() { RecordType: "CNAME", SetIdentifier: "2w705o.lb-" + lbHash + ".test.example.com", RecordTTL: 60, - ProviderSpecific: v1alpha1.ProviderSpecific{ + ProviderSpecific: v1alpha2.ProviderSpecific{ { Name: "weight", Value: "120", @@ -363,7 +373,7 @@ var _ = Describe("DNSPolicy Health Checks", func() { SetIdentifier: "s07c46.lb-" + lbHash + ".test.example.com", RecordTTL: 60, Labels: nil, - ProviderSpecific: v1alpha1.ProviderSpecific{ + ProviderSpecific: v1alpha2.ProviderSpecific{ { Name: "weight", Value: "120", @@ -378,7 +388,7 @@ var _ = Describe("DNSPolicy Health Checks", func() { RecordType: "CNAME", SetIdentifier: "default", RecordTTL: 300, - ProviderSpecific: v1alpha1.ProviderSpecific{ + ProviderSpecific: v1alpha2.ProviderSpecific{ { Name: "geo-code", Value: "*", @@ -425,7 +435,7 @@ var _ = Describe("DNSPolicy Health Checks", func() { }, TestTimeoutLong, TestRetryIntervalMedium).Should(BeNil()) // after that verify that in time the endpoints are 5 in the dnsrecord - createdDNSRecord := &v1alpha1.DNSRecord{} + createdDNSRecord := &v1alpha2.DNSRecord{} Eventually(func() error { err := k8sClient.Get(ctx, client.ObjectKey{Name: recordName, Namespace: testNamespace}, createdDNSRecord) if err != nil && k8serrors.IsNotFound(err) { @@ -440,7 +450,7 @@ var _ = Describe("DNSPolicy Health Checks", func() { Context("some unhealthy endpoints for other listener", func() { It("should publish expected endpoints", func() { - expectedEndpoints := []*v1alpha1.Endpoint{ + expectedEndpoints := []*v1alpha2.Endpoint{ { DNSName: "2w705o.lb-" + lbHash + ".test.example.com", Targets: []string{ @@ -467,7 +477,7 @@ var _ = Describe("DNSPolicy Health Checks", func() { RecordType: "CNAME", SetIdentifier: "2w705o.lb-" + lbHash + ".test.example.com", RecordTTL: 60, - ProviderSpecific: v1alpha1.ProviderSpecific{ + ProviderSpecific: v1alpha2.ProviderSpecific{ { Name: "weight", Value: "120", @@ -483,7 +493,7 @@ var _ = Describe("DNSPolicy Health Checks", func() { SetIdentifier: "s07c46.lb-" + lbHash + ".test.example.com", RecordTTL: 60, Labels: nil, - ProviderSpecific: v1alpha1.ProviderSpecific{ + ProviderSpecific: v1alpha2.ProviderSpecific{ { Name: "weight", Value: "120", @@ -498,7 +508,7 @@ var _ = Describe("DNSPolicy Health Checks", func() { RecordType: "CNAME", SetIdentifier: "default", RecordTTL: 300, - ProviderSpecific: v1alpha1.ProviderSpecific{ + ProviderSpecific: v1alpha2.ProviderSpecific{ { Name: "geo-code", Value: "*", @@ -562,7 +572,7 @@ var _ = Describe("DNSPolicy Health Checks", func() { }, TestTimeoutLong, TestRetryIntervalMedium).Should(BeNil()) // after that verify that in time the endpoints are 5 in the dnsrecord - createdDNSRecord := &v1alpha1.DNSRecord{} + createdDNSRecord := &v1alpha2.DNSRecord{} Eventually(func() error { err := k8sClient.Get(ctx, client.ObjectKey{Name: recordName, Namespace: testNamespace}, createdDNSRecord) if err != nil && k8serrors.IsNotFound(err) { diff --git a/test/policy_integration/dnspolicy_controller_multi_cluster_test.go b/test/policy_integration/dnspolicy_controller_multi_cluster_test.go index 2dd61d3d5..7fb2f2ce4 100644 --- a/test/policy_integration/dnspolicy_controller_multi_cluster_test.go +++ b/test/policy_integration/dnspolicy_controller_multi_cluster_test.go @@ -16,7 +16,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client" gatewayapiv1 "sigs.k8s.io/gateway-api/apis/v1" - "github.com/Kuadrant/multicluster-gateway-controller/pkg/apis/v1alpha1" + "github.com/Kuadrant/multicluster-gateway-controller/pkg/apis/v1alpha2" "github.com/Kuadrant/multicluster-gateway-controller/pkg/dns" "github.com/Kuadrant/multicluster-gateway-controller/pkg/utils" testutil "github.com/Kuadrant/multicluster-gateway-controller/test/util" @@ -25,11 +25,11 @@ import ( var _ = Describe("DNSPolicy Multi Cluster", func() { var gatewayClass *gatewayapiv1.GatewayClass - var managedZone *v1alpha1.ManagedZone + var managedZone *v1alpha2.ManagedZone var testNamespace string var dnsPolicyBuilder *testutil.DNSPolicyBuilder var gateway *gatewayapiv1.Gateway - var dnsPolicy *v1alpha1.DNSPolicy + var dnsPolicy *v1alpha2.DNSPolicy var lbHash, recordName, wildcardRecordName string BeforeEach(func() { @@ -38,7 +38,12 @@ var _ = Describe("DNSPolicy Multi Cluster", func() { gatewayClass = testutil.NewTestGatewayClass("foo", "default", "kuadrant.io/bar") Expect(k8sClient.Create(ctx, gatewayClass)).To(Succeed()) - managedZone = testutil.NewManagedZoneBuilder("mz-example-com", testNamespace, "example.com").ManagedZone + managedZone = testutil.NewManagedZoneBuilder("mz-example-com", testNamespace). + WithID("1234"). + WithDomainName("example.com"). + WithDescription("example.com"). + WithProviderSecret("secretname"). + ManagedZone Expect(k8sClient.Create(ctx, managedZone)).To(Succeed()) gateway = testutil.NewGatewayBuilder(TestGatewayName, gatewayClass.Name, testNamespace). @@ -102,8 +107,9 @@ var _ = Describe("DNSPolicy Multi Cluster", func() { return k8sClient.Status().Update(ctx, gateway) }, TestTimeoutMedium, TestRetryIntervalMedium).ShouldNot(HaveOccurred()) - dnsPolicyBuilder = testutil.NewDNSPolicyBuilder("test-dns-policy", testNamespace) - dnsPolicyBuilder.WithTargetGateway(TestGatewayName) + dnsPolicyBuilder = testutil.NewDNSPolicyBuilder("test-dns-policy", testNamespace). + WithProviderManagedZone(managedZone.Name). + WithTargetGateway(TestGatewayName) lbHash = dns.ToBase36hash(fmt.Sprintf("%s-%s", gateway.Name, gateway.Namespace)) recordName = fmt.Sprintf("%s-%s", TestGatewayName, TestListenerNameOne) @@ -133,14 +139,14 @@ var _ = Describe("DNSPolicy Multi Cluster", func() { Context("simple routing strategy", func() { BeforeEach(func() { - dnsPolicyBuilder.WithRoutingStrategy(v1alpha1.SimpleRoutingStrategy) + dnsPolicyBuilder.WithRoutingStrategy(v1alpha2.SimpleRoutingStrategy) dnsPolicy = dnsPolicyBuilder.DNSPolicy Expect(k8sClient.Create(ctx, dnsPolicy)).To(Succeed()) }) It("should create dns records", func() { Eventually(func(g Gomega, ctx context.Context) { - recordList := &v1alpha1.DNSRecordList{} + recordList := &v1alpha2.DNSRecordList{} err := k8sClient.List(ctx, recordList, &client.ListOptions{Namespace: testNamespace}) g.Expect(err).NotTo(HaveOccurred()) g.Expect(recordList.Items).To(HaveLen(2)) @@ -149,14 +155,15 @@ var _ = Describe("DNSPolicy Multi Cluster", func() { MatchFields(IgnoreExtras, Fields{ "ObjectMeta": HaveField("Name", recordName), "Spec": MatchFields(IgnoreExtras, Fields{ - "ManagedZoneRef": HaveField("Name", "mz-example-com"), + "ZoneID": Equal(managedZone.Spec.ID), + "ProviderRef": Equal(dnsPolicy.Spec.ProviderRef), "Endpoints": ConsistOf( PointTo(MatchFields(IgnoreExtras, Fields{ "DNSName": Equal(TestHostOne), "Targets": ContainElements(TestIPAddressOne, TestIPAddressTwo), "RecordType": Equal("A"), "SetIdentifier": Equal(""), - "RecordTTL": Equal(v1alpha1.TTL(60)), + "RecordTTL": Equal(v1alpha2.TTL(60)), })), ), }), @@ -164,14 +171,15 @@ var _ = Describe("DNSPolicy Multi Cluster", func() { MatchFields(IgnoreExtras, Fields{ "ObjectMeta": HaveField("Name", wildcardRecordName), "Spec": MatchFields(IgnoreExtras, Fields{ - "ManagedZoneRef": HaveField("Name", "mz-example-com"), + "ZoneID": Equal(managedZone.Spec.ID), + "ProviderRef": Equal(dnsPolicy.Spec.ProviderRef), "Endpoints": ConsistOf( PointTo(MatchFields(IgnoreExtras, Fields{ "DNSName": Equal(TestHostWildcard), "Targets": ContainElements(TestIPAddressOne, TestIPAddressTwo), "RecordType": Equal("A"), "SetIdentifier": Equal(""), - "RecordTTL": Equal(v1alpha1.TTL(60)), + "RecordTTL": Equal(v1alpha2.TTL(60)), })), ), }), @@ -185,7 +193,7 @@ var _ = Describe("DNSPolicy Multi Cluster", func() { Context("loadbalanced routing strategy", func() { BeforeEach(func() { - dnsPolicyBuilder.WithRoutingStrategy(v1alpha1.LoadBalancedRoutingStrategy) + dnsPolicyBuilder.WithRoutingStrategy(v1alpha2.LoadBalancedRoutingStrategy) }) Context("weighted", func() { @@ -198,7 +206,7 @@ var _ = Describe("DNSPolicy Multi Cluster", func() { It("should create dns records", func() { Eventually(func(g Gomega, ctx context.Context) { - recordList := &v1alpha1.DNSRecordList{} + recordList := &v1alpha2.DNSRecordList{} err := k8sClient.List(ctx, recordList, &client.ListOptions{Namespace: testNamespace}) g.Expect(err).NotTo(HaveOccurred()) g.Expect(recordList.Items).To(HaveLen(2)) @@ -207,52 +215,53 @@ var _ = Describe("DNSPolicy Multi Cluster", func() { MatchFields(IgnoreExtras, Fields{ "ObjectMeta": HaveField("Name", recordName), "Spec": MatchFields(IgnoreExtras, Fields{ - "ManagedZoneRef": HaveField("Name", "mz-example-com"), + "ZoneID": Equal(managedZone.Spec.ID), + "ProviderRef": Equal(dnsPolicy.Spec.ProviderRef), "Endpoints": ConsistOf( PointTo(MatchFields(IgnoreExtras, Fields{ "DNSName": Equal("2w705o.lb-" + lbHash + ".test.example.com"), "Targets": ConsistOf(TestIPAddressTwo), "RecordType": Equal("A"), "SetIdentifier": Equal(""), - "RecordTTL": Equal(v1alpha1.TTL(60)), + "RecordTTL": Equal(v1alpha2.TTL(60)), })), PointTo(MatchFields(IgnoreExtras, Fields{ "DNSName": Equal("default.lb-" + lbHash + ".test.example.com"), "Targets": ConsistOf("2w705o.lb-" + lbHash + ".test.example.com"), "RecordType": Equal("CNAME"), "SetIdentifier": Equal("2w705o.lb-" + lbHash + ".test.example.com"), - "RecordTTL": Equal(v1alpha1.TTL(60)), - "ProviderSpecific": Equal(v1alpha1.ProviderSpecific{{Name: "weight", Value: "120"}}), + "RecordTTL": Equal(v1alpha2.TTL(60)), + "ProviderSpecific": Equal(v1alpha2.ProviderSpecific{{Name: "weight", Value: "120"}}), })), PointTo(MatchFields(IgnoreExtras, Fields{ "DNSName": Equal("default.lb-" + lbHash + ".test.example.com"), "Targets": ConsistOf("s07c46.lb-" + lbHash + ".test.example.com"), "RecordType": Equal("CNAME"), "SetIdentifier": Equal("s07c46.lb-" + lbHash + ".test.example.com"), - "RecordTTL": Equal(v1alpha1.TTL(60)), - "ProviderSpecific": Equal(v1alpha1.ProviderSpecific{{Name: "weight", Value: "120"}}), + "RecordTTL": Equal(v1alpha2.TTL(60)), + "ProviderSpecific": Equal(v1alpha2.ProviderSpecific{{Name: "weight", Value: "120"}}), })), PointTo(MatchFields(IgnoreExtras, Fields{ "DNSName": Equal("s07c46.lb-" + lbHash + ".test.example.com"), "Targets": ConsistOf(TestIPAddressOne), "RecordType": Equal("A"), "SetIdentifier": Equal(""), - "RecordTTL": Equal(v1alpha1.TTL(60)), + "RecordTTL": Equal(v1alpha2.TTL(60)), })), PointTo(MatchFields(IgnoreExtras, Fields{ "DNSName": Equal("lb-" + lbHash + ".test.example.com"), "Targets": ConsistOf("default.lb-" + lbHash + ".test.example.com"), "RecordType": Equal("CNAME"), "SetIdentifier": Equal("default"), - "RecordTTL": Equal(v1alpha1.TTL(300)), - "ProviderSpecific": Equal(v1alpha1.ProviderSpecific{{Name: "geo-code", Value: "*"}}), + "RecordTTL": Equal(v1alpha2.TTL(300)), + "ProviderSpecific": Equal(v1alpha2.ProviderSpecific{{Name: "geo-code", Value: "*"}}), })), PointTo(MatchFields(IgnoreExtras, Fields{ "DNSName": Equal(TestHostOne), "Targets": ConsistOf("lb-" + lbHash + ".test.example.com"), "RecordType": Equal("CNAME"), "SetIdentifier": Equal(""), - "RecordTTL": Equal(v1alpha1.TTL(300)), + "RecordTTL": Equal(v1alpha2.TTL(300)), })), ), }), @@ -260,52 +269,53 @@ var _ = Describe("DNSPolicy Multi Cluster", func() { MatchFields(IgnoreExtras, Fields{ "ObjectMeta": HaveField("Name", wildcardRecordName), "Spec": MatchFields(IgnoreExtras, Fields{ - "ManagedZoneRef": HaveField("Name", "mz-example-com"), + "ZoneID": Equal(managedZone.Spec.ID), + "ProviderRef": Equal(dnsPolicy.Spec.ProviderRef), "Endpoints": ConsistOf( PointTo(MatchFields(IgnoreExtras, Fields{ "DNSName": Equal("2w705o.lb-" + lbHash + ".example.com"), "Targets": ConsistOf(TestIPAddressTwo), "RecordType": Equal("A"), "SetIdentifier": Equal(""), - "RecordTTL": Equal(v1alpha1.TTL(60)), + "RecordTTL": Equal(v1alpha2.TTL(60)), })), PointTo(MatchFields(IgnoreExtras, Fields{ "DNSName": Equal("default.lb-" + lbHash + ".example.com"), "Targets": ConsistOf("2w705o.lb-" + lbHash + ".example.com"), "RecordType": Equal("CNAME"), "SetIdentifier": Equal("2w705o.lb-" + lbHash + ".example.com"), - "RecordTTL": Equal(v1alpha1.TTL(60)), - "ProviderSpecific": Equal(v1alpha1.ProviderSpecific{{Name: "weight", Value: "120"}}), + "RecordTTL": Equal(v1alpha2.TTL(60)), + "ProviderSpecific": Equal(v1alpha2.ProviderSpecific{{Name: "weight", Value: "120"}}), })), PointTo(MatchFields(IgnoreExtras, Fields{ "DNSName": Equal("default.lb-" + lbHash + ".example.com"), "Targets": ConsistOf("s07c46.lb-" + lbHash + ".example.com"), "RecordType": Equal("CNAME"), "SetIdentifier": Equal("s07c46.lb-" + lbHash + ".example.com"), - "RecordTTL": Equal(v1alpha1.TTL(60)), - "ProviderSpecific": Equal(v1alpha1.ProviderSpecific{{Name: "weight", Value: "120"}}), + "RecordTTL": Equal(v1alpha2.TTL(60)), + "ProviderSpecific": Equal(v1alpha2.ProviderSpecific{{Name: "weight", Value: "120"}}), })), PointTo(MatchFields(IgnoreExtras, Fields{ "DNSName": Equal("s07c46.lb-" + lbHash + ".example.com"), "Targets": ConsistOf(TestIPAddressOne), "RecordType": Equal("A"), "SetIdentifier": Equal(""), - "RecordTTL": Equal(v1alpha1.TTL(60)), + "RecordTTL": Equal(v1alpha2.TTL(60)), })), PointTo(MatchFields(IgnoreExtras, Fields{ "DNSName": Equal("lb-" + lbHash + ".example.com"), "Targets": ConsistOf("default.lb-" + lbHash + ".example.com"), "RecordType": Equal("CNAME"), "SetIdentifier": Equal("default"), - "RecordTTL": Equal(v1alpha1.TTL(300)), - "ProviderSpecific": Equal(v1alpha1.ProviderSpecific{{Name: "geo-code", Value: "*"}}), + "RecordTTL": Equal(v1alpha2.TTL(300)), + "ProviderSpecific": Equal(v1alpha2.ProviderSpecific{{Name: "geo-code", Value: "*"}}), })), PointTo(MatchFields(IgnoreExtras, Fields{ "DNSName": Equal(TestHostWildcard), "Targets": ConsistOf("lb-" + lbHash + ".example.com"), "RecordType": Equal("CNAME"), "SetIdentifier": Equal(""), - "RecordTTL": Equal(v1alpha1.TTL(300)), + "RecordTTL": Equal(v1alpha2.TTL(300)), })), ), }), @@ -328,7 +338,7 @@ var _ = Describe("DNSPolicy Multi Cluster", func() { It("should create dns records", func() { Eventually(func(g Gomega, ctx context.Context) { - recordList := &v1alpha1.DNSRecordList{} + recordList := &v1alpha2.DNSRecordList{} err := k8sClient.List(ctx, recordList, &client.ListOptions{Namespace: testNamespace}) g.Expect(err).NotTo(HaveOccurred()) g.Expect(recordList.Items).To(HaveLen(2)) @@ -337,60 +347,61 @@ var _ = Describe("DNSPolicy Multi Cluster", func() { MatchFields(IgnoreExtras, Fields{ "ObjectMeta": HaveField("Name", recordName), "Spec": MatchFields(IgnoreExtras, Fields{ - "ManagedZoneRef": HaveField("Name", "mz-example-com"), + "ZoneID": Equal(managedZone.Spec.ID), + "ProviderRef": Equal(dnsPolicy.Spec.ProviderRef), "Endpoints": ConsistOf( PointTo(MatchFields(IgnoreExtras, Fields{ "DNSName": Equal("2w705o.lb-" + lbHash + ".test.example.com"), "Targets": ConsistOf(TestIPAddressTwo), "RecordType": Equal("A"), "SetIdentifier": Equal(""), - "RecordTTL": Equal(v1alpha1.TTL(60)), + "RecordTTL": Equal(v1alpha2.TTL(60)), })), PointTo(MatchFields(IgnoreExtras, Fields{ "DNSName": Equal("ie.lb-" + lbHash + ".test.example.com"), "Targets": ConsistOf("2w705o.lb-" + lbHash + ".test.example.com"), "RecordType": Equal("CNAME"), "SetIdentifier": Equal("2w705o.lb-" + lbHash + ".test.example.com"), - "RecordTTL": Equal(v1alpha1.TTL(60)), - "ProviderSpecific": Equal(v1alpha1.ProviderSpecific{{Name: "weight", Value: "120"}}), + "RecordTTL": Equal(v1alpha2.TTL(60)), + "ProviderSpecific": Equal(v1alpha2.ProviderSpecific{{Name: "weight", Value: "120"}}), })), PointTo(MatchFields(IgnoreExtras, Fields{ "DNSName": Equal("ie.lb-" + lbHash + ".test.example.com"), "Targets": ConsistOf("s07c46.lb-" + lbHash + ".test.example.com"), "RecordType": Equal("CNAME"), "SetIdentifier": Equal("s07c46.lb-" + lbHash + ".test.example.com"), - "RecordTTL": Equal(v1alpha1.TTL(60)), - "ProviderSpecific": Equal(v1alpha1.ProviderSpecific{{Name: "weight", Value: "120"}}), + "RecordTTL": Equal(v1alpha2.TTL(60)), + "ProviderSpecific": Equal(v1alpha2.ProviderSpecific{{Name: "weight", Value: "120"}}), })), PointTo(MatchFields(IgnoreExtras, Fields{ "DNSName": Equal("s07c46.lb-" + lbHash + ".test.example.com"), "Targets": ConsistOf(TestIPAddressOne), "RecordType": Equal("A"), "SetIdentifier": Equal(""), - "RecordTTL": Equal(v1alpha1.TTL(60)), + "RecordTTL": Equal(v1alpha2.TTL(60)), })), PointTo(MatchFields(IgnoreExtras, Fields{ "DNSName": Equal("lb-" + lbHash + ".test.example.com"), "Targets": ConsistOf("ie.lb-" + lbHash + ".test.example.com"), "RecordType": Equal("CNAME"), "SetIdentifier": Equal("IE"), - "RecordTTL": Equal(v1alpha1.TTL(300)), - "ProviderSpecific": Equal(v1alpha1.ProviderSpecific{{Name: "geo-code", Value: "IE"}}), + "RecordTTL": Equal(v1alpha2.TTL(300)), + "ProviderSpecific": Equal(v1alpha2.ProviderSpecific{{Name: "geo-code", Value: "IE"}}), })), PointTo(MatchFields(IgnoreExtras, Fields{ "DNSName": Equal("lb-" + lbHash + ".test.example.com"), "Targets": ConsistOf("ie.lb-" + lbHash + ".test.example.com"), "RecordType": Equal("CNAME"), "SetIdentifier": Equal("default"), - "RecordTTL": Equal(v1alpha1.TTL(300)), - "ProviderSpecific": Equal(v1alpha1.ProviderSpecific{{Name: "geo-code", Value: "*"}}), + "RecordTTL": Equal(v1alpha2.TTL(300)), + "ProviderSpecific": Equal(v1alpha2.ProviderSpecific{{Name: "geo-code", Value: "*"}}), })), PointTo(MatchFields(IgnoreExtras, Fields{ "DNSName": Equal(TestHostOne), "Targets": ConsistOf("lb-" + lbHash + ".test.example.com"), "RecordType": Equal("CNAME"), "SetIdentifier": Equal(""), - "RecordTTL": Equal(v1alpha1.TTL(300)), + "RecordTTL": Equal(v1alpha2.TTL(300)), })), ), }), @@ -398,60 +409,61 @@ var _ = Describe("DNSPolicy Multi Cluster", func() { MatchFields(IgnoreExtras, Fields{ "ObjectMeta": HaveField("Name", wildcardRecordName), "Spec": MatchFields(IgnoreExtras, Fields{ - "ManagedZoneRef": HaveField("Name", "mz-example-com"), + "ZoneID": Equal(managedZone.Spec.ID), + "ProviderRef": Equal(dnsPolicy.Spec.ProviderRef), "Endpoints": ConsistOf( PointTo(MatchFields(IgnoreExtras, Fields{ "DNSName": Equal("2w705o.lb-" + lbHash + ".example.com"), "Targets": ConsistOf(TestIPAddressTwo), "RecordType": Equal("A"), "SetIdentifier": Equal(""), - "RecordTTL": Equal(v1alpha1.TTL(60)), + "RecordTTL": Equal(v1alpha2.TTL(60)), })), PointTo(MatchFields(IgnoreExtras, Fields{ "DNSName": Equal("ie.lb-" + lbHash + ".example.com"), "Targets": ConsistOf("2w705o.lb-" + lbHash + ".example.com"), "RecordType": Equal("CNAME"), "SetIdentifier": Equal("2w705o.lb-" + lbHash + ".example.com"), - "RecordTTL": Equal(v1alpha1.TTL(60)), - "ProviderSpecific": Equal(v1alpha1.ProviderSpecific{{Name: "weight", Value: "120"}}), + "RecordTTL": Equal(v1alpha2.TTL(60)), + "ProviderSpecific": Equal(v1alpha2.ProviderSpecific{{Name: "weight", Value: "120"}}), })), PointTo(MatchFields(IgnoreExtras, Fields{ "DNSName": Equal("ie.lb-" + lbHash + ".example.com"), "Targets": ConsistOf("s07c46.lb-" + lbHash + ".example.com"), "RecordType": Equal("CNAME"), "SetIdentifier": Equal("s07c46.lb-" + lbHash + ".example.com"), - "RecordTTL": Equal(v1alpha1.TTL(60)), - "ProviderSpecific": Equal(v1alpha1.ProviderSpecific{{Name: "weight", Value: "120"}}), + "RecordTTL": Equal(v1alpha2.TTL(60)), + "ProviderSpecific": Equal(v1alpha2.ProviderSpecific{{Name: "weight", Value: "120"}}), })), PointTo(MatchFields(IgnoreExtras, Fields{ "DNSName": Equal("s07c46.lb-" + lbHash + ".example.com"), "Targets": ConsistOf(TestIPAddressOne), "RecordType": Equal("A"), "SetIdentifier": Equal(""), - "RecordTTL": Equal(v1alpha1.TTL(60)), + "RecordTTL": Equal(v1alpha2.TTL(60)), })), PointTo(MatchFields(IgnoreExtras, Fields{ "DNSName": Equal("lb-" + lbHash + ".example.com"), "Targets": ConsistOf("ie.lb-" + lbHash + ".example.com"), "RecordType": Equal("CNAME"), "SetIdentifier": Equal("IE"), - "RecordTTL": Equal(v1alpha1.TTL(300)), - "ProviderSpecific": Equal(v1alpha1.ProviderSpecific{{Name: "geo-code", Value: "IE"}}), + "RecordTTL": Equal(v1alpha2.TTL(300)), + "ProviderSpecific": Equal(v1alpha2.ProviderSpecific{{Name: "geo-code", Value: "IE"}}), })), PointTo(MatchFields(IgnoreExtras, Fields{ "DNSName": Equal("lb-" + lbHash + ".example.com"), "Targets": ConsistOf("ie.lb-" + lbHash + ".example.com"), "RecordType": Equal("CNAME"), "SetIdentifier": Equal("default"), - "RecordTTL": Equal(v1alpha1.TTL(300)), - "ProviderSpecific": Equal(v1alpha1.ProviderSpecific{{Name: "geo-code", Value: "*"}}), + "RecordTTL": Equal(v1alpha2.TTL(300)), + "ProviderSpecific": Equal(v1alpha2.ProviderSpecific{{Name: "geo-code", Value: "*"}}), })), PointTo(MatchFields(IgnoreExtras, Fields{ "DNSName": Equal(TestHostWildcard), "Targets": ConsistOf("lb-" + lbHash + ".example.com"), "RecordType": Equal("CNAME"), "SetIdentifier": Equal(""), - "RecordTTL": Equal(v1alpha1.TTL(300)), + "RecordTTL": Equal(v1alpha2.TTL(300)), })), ), }), diff --git a/test/policy_integration/dnspolicy_controller_single_cluster_test.go b/test/policy_integration/dnspolicy_controller_single_cluster_test.go index be0a00c17..c137269d3 100644 --- a/test/policy_integration/dnspolicy_controller_single_cluster_test.go +++ b/test/policy_integration/dnspolicy_controller_single_cluster_test.go @@ -14,7 +14,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client" gatewayapiv1 "sigs.k8s.io/gateway-api/apis/v1" - "github.com/Kuadrant/multicluster-gateway-controller/pkg/apis/v1alpha1" + "github.com/Kuadrant/multicluster-gateway-controller/pkg/apis/v1alpha2" "github.com/Kuadrant/multicluster-gateway-controller/pkg/dns" testutil "github.com/Kuadrant/multicluster-gateway-controller/test/util" ) @@ -22,11 +22,11 @@ import ( var _ = Describe("DNSPolicy Single Cluster", func() { var gatewayClass *gatewayapiv1.GatewayClass - var managedZone *v1alpha1.ManagedZone + var managedZone *v1alpha2.ManagedZone var testNamespace string var dnsPolicyBuilder *testutil.DNSPolicyBuilder var gateway *gatewayapiv1.Gateway - var dnsPolicy *v1alpha1.DNSPolicy + var dnsPolicy *v1alpha2.DNSPolicy var lbHash, recordName, wildcardRecordName string BeforeEach(func() { @@ -35,7 +35,12 @@ var _ = Describe("DNSPolicy Single Cluster", func() { gatewayClass = testutil.NewTestGatewayClass("foo", "default", "kuadrant.io/bar") Expect(k8sClient.Create(ctx, gatewayClass)).To(Succeed()) - managedZone = testutil.NewManagedZoneBuilder("mz-example-com", testNamespace, "example.com").ManagedZone + managedZone = testutil.NewManagedZoneBuilder("mz-example-com", testNamespace). + WithID("1234"). + WithDomainName("example.com"). + WithDescription("example.com"). + WithProviderSecret("secretname"). + ManagedZone Expect(k8sClient.Create(ctx, managedZone)).To(Succeed()) gateway = testutil.NewGatewayBuilder(TestGatewayName, gatewayClass.Name, testNamespace). @@ -73,8 +78,9 @@ var _ = Describe("DNSPolicy Single Cluster", func() { return k8sClient.Status().Update(ctx, gateway) }, TestTimeoutMedium, TestRetryIntervalMedium).Should(Succeed()) - dnsPolicyBuilder = testutil.NewDNSPolicyBuilder("test-dns-policy", testNamespace) - dnsPolicyBuilder.WithTargetGateway(TestGatewayName) + dnsPolicyBuilder = testutil.NewDNSPolicyBuilder("test-dns-policy", testNamespace). + WithProviderManagedZone(managedZone.Name). + WithTargetGateway(TestGatewayName) lbHash = dns.ToBase36hash(fmt.Sprintf("%s-%s", gateway.Name, gateway.Namespace)) recordName = fmt.Sprintf("%s-%s", TestGatewayName, TestListenerNameOne) @@ -104,14 +110,14 @@ var _ = Describe("DNSPolicy Single Cluster", func() { Context("simple routing strategy", func() { BeforeEach(func() { - dnsPolicyBuilder.WithRoutingStrategy(v1alpha1.SimpleRoutingStrategy) + dnsPolicyBuilder.WithRoutingStrategy(v1alpha2.SimpleRoutingStrategy) dnsPolicy = dnsPolicyBuilder.DNSPolicy Expect(k8sClient.Create(ctx, dnsPolicy)).To(Succeed()) }) It("should create dns records", func() { Eventually(func(g Gomega, ctx context.Context) { - recordList := &v1alpha1.DNSRecordList{} + recordList := &v1alpha2.DNSRecordList{} err := k8sClient.List(ctx, recordList, &client.ListOptions{Namespace: testNamespace}) g.Expect(err).NotTo(HaveOccurred()) g.Expect(recordList.Items).To(HaveLen(2)) @@ -120,14 +126,15 @@ var _ = Describe("DNSPolicy Single Cluster", func() { MatchFields(IgnoreExtras, Fields{ "ObjectMeta": HaveField("Name", recordName), "Spec": MatchFields(IgnoreExtras, Fields{ - "ManagedZoneRef": HaveField("Name", "mz-example-com"), + "ZoneID": Equal(managedZone.Spec.ID), + "ProviderRef": Equal(dnsPolicy.Spec.ProviderRef), "Endpoints": ConsistOf( PointTo(MatchFields(IgnoreExtras, Fields{ "DNSName": Equal(TestHostOne), "Targets": ContainElements(TestIPAddressOne, TestIPAddressTwo), "RecordType": Equal("A"), "SetIdentifier": Equal(""), - "RecordTTL": Equal(v1alpha1.TTL(60)), + "RecordTTL": Equal(v1alpha2.TTL(60)), })), ), }), @@ -135,14 +142,15 @@ var _ = Describe("DNSPolicy Single Cluster", func() { MatchFields(IgnoreExtras, Fields{ "ObjectMeta": HaveField("Name", wildcardRecordName), "Spec": MatchFields(IgnoreExtras, Fields{ - "ManagedZoneRef": HaveField("Name", "mz-example-com"), + "ZoneID": Equal(managedZone.Spec.ID), + "ProviderRef": Equal(dnsPolicy.Spec.ProviderRef), "Endpoints": ConsistOf( PointTo(MatchFields(IgnoreExtras, Fields{ "DNSName": Equal(TestHostWildcard), "Targets": ContainElements(TestIPAddressOne, TestIPAddressTwo), "RecordType": Equal("A"), "SetIdentifier": Equal(""), - "RecordTTL": Equal(v1alpha1.TTL(60)), + "RecordTTL": Equal(v1alpha2.TTL(60)), })), ), }), @@ -156,14 +164,14 @@ var _ = Describe("DNSPolicy Single Cluster", func() { Context("loadbalanced routing strategy", func() { BeforeEach(func() { - dnsPolicyBuilder.WithRoutingStrategy(v1alpha1.LoadBalancedRoutingStrategy) + dnsPolicyBuilder.WithRoutingStrategy(v1alpha2.LoadBalancedRoutingStrategy) dnsPolicy = dnsPolicyBuilder.DNSPolicy Expect(k8sClient.Create(ctx, dnsPolicy)).To(Succeed()) }) It("should create dns records", func() { Eventually(func(g Gomega, ctx context.Context) { - recordList := &v1alpha1.DNSRecordList{} + recordList := &v1alpha2.DNSRecordList{} err := k8sClient.List(ctx, recordList, &client.ListOptions{Namespace: testNamespace}) g.Expect(err).NotTo(HaveOccurred()) g.Expect(recordList.Items).To(HaveLen(2)) @@ -172,37 +180,38 @@ var _ = Describe("DNSPolicy Single Cluster", func() { MatchFields(IgnoreExtras, Fields{ "ObjectMeta": HaveField("Name", recordName), "Spec": MatchFields(IgnoreExtras, Fields{ - "ManagedZoneRef": HaveField("Name", "mz-example-com"), + "ZoneID": Equal(managedZone.Spec.ID), + "ProviderRef": Equal(dnsPolicy.Spec.ProviderRef), "Endpoints": ConsistOf( PointTo(MatchFields(IgnoreExtras, Fields{ "DNSName": Equal("19sc9b.lb-" + lbHash + ".test.example.com"), "Targets": ConsistOf(TestIPAddressOne, TestIPAddressTwo), "RecordType": Equal("A"), "SetIdentifier": Equal(""), - "RecordTTL": Equal(v1alpha1.TTL(60)), + "RecordTTL": Equal(v1alpha2.TTL(60)), })), PointTo(MatchFields(IgnoreExtras, Fields{ "DNSName": Equal("default.lb-" + lbHash + ".test.example.com"), "Targets": ConsistOf("19sc9b.lb-" + lbHash + ".test.example.com"), "RecordType": Equal("CNAME"), "SetIdentifier": Equal("19sc9b.lb-" + lbHash + ".test.example.com"), - "RecordTTL": Equal(v1alpha1.TTL(60)), - "ProviderSpecific": Equal(v1alpha1.ProviderSpecific{{Name: "weight", Value: "120"}}), + "RecordTTL": Equal(v1alpha2.TTL(60)), + "ProviderSpecific": Equal(v1alpha2.ProviderSpecific{{Name: "weight", Value: "120"}}), })), PointTo(MatchFields(IgnoreExtras, Fields{ "DNSName": Equal("lb-" + lbHash + ".test.example.com"), "Targets": ConsistOf("default.lb-" + lbHash + ".test.example.com"), "RecordType": Equal("CNAME"), "SetIdentifier": Equal("default"), - "RecordTTL": Equal(v1alpha1.TTL(300)), - "ProviderSpecific": Equal(v1alpha1.ProviderSpecific{{Name: "geo-code", Value: "*"}}), + "RecordTTL": Equal(v1alpha2.TTL(300)), + "ProviderSpecific": Equal(v1alpha2.ProviderSpecific{{Name: "geo-code", Value: "*"}}), })), PointTo(MatchFields(IgnoreExtras, Fields{ "DNSName": Equal(TestHostOne), "Targets": ConsistOf("lb-" + lbHash + ".test.example.com"), "RecordType": Equal("CNAME"), "SetIdentifier": Equal(""), - "RecordTTL": Equal(v1alpha1.TTL(300)), + "RecordTTL": Equal(v1alpha2.TTL(300)), })), ), }), @@ -210,37 +219,38 @@ var _ = Describe("DNSPolicy Single Cluster", func() { MatchFields(IgnoreExtras, Fields{ "ObjectMeta": HaveField("Name", wildcardRecordName), "Spec": MatchFields(IgnoreExtras, Fields{ - "ManagedZoneRef": HaveField("Name", "mz-example-com"), + "ZoneID": Equal(managedZone.Spec.ID), + "ProviderRef": Equal(dnsPolicy.Spec.ProviderRef), "Endpoints": ContainElements( PointTo(MatchFields(IgnoreExtras, Fields{ "DNSName": Equal("19sc9b.lb-" + lbHash + ".example.com"), "Targets": ConsistOf(TestIPAddressOne, TestIPAddressTwo), "RecordType": Equal("A"), "SetIdentifier": Equal(""), - "RecordTTL": Equal(v1alpha1.TTL(60)), + "RecordTTL": Equal(v1alpha2.TTL(60)), })), PointTo(MatchFields(IgnoreExtras, Fields{ "DNSName": Equal("default.lb-" + lbHash + ".example.com"), "Targets": ConsistOf("19sc9b.lb-" + lbHash + ".example.com"), "RecordType": Equal("CNAME"), "SetIdentifier": Equal("19sc9b.lb-" + lbHash + ".example.com"), - "RecordTTL": Equal(v1alpha1.TTL(60)), - "ProviderSpecific": Equal(v1alpha1.ProviderSpecific{{Name: "weight", Value: "120"}}), + "RecordTTL": Equal(v1alpha2.TTL(60)), + "ProviderSpecific": Equal(v1alpha2.ProviderSpecific{{Name: "weight", Value: "120"}}), })), PointTo(MatchFields(IgnoreExtras, Fields{ "DNSName": Equal("lb-" + lbHash + ".example.com"), "Targets": ConsistOf("default.lb-" + lbHash + ".example.com"), "RecordType": Equal("CNAME"), "SetIdentifier": Equal("default"), - "RecordTTL": Equal(v1alpha1.TTL(300)), - "ProviderSpecific": Equal(v1alpha1.ProviderSpecific{{Name: "geo-code", Value: "*"}}), + "RecordTTL": Equal(v1alpha2.TTL(300)), + "ProviderSpecific": Equal(v1alpha2.ProviderSpecific{{Name: "geo-code", Value: "*"}}), })), PointTo(MatchFields(IgnoreExtras, Fields{ "DNSName": Equal(TestHostWildcard), "Targets": ConsistOf("lb-" + lbHash + ".example.com"), "RecordType": Equal("CNAME"), "SetIdentifier": Equal(""), - "RecordTTL": Equal(v1alpha1.TTL(300)), + "RecordTTL": Equal(v1alpha2.TTL(300)), })), ), }), diff --git a/test/policy_integration/dnspolicy_controller_test.go b/test/policy_integration/dnspolicy_controller_test.go index 8755a41cd..f5c31d6a4 100644 --- a/test/policy_integration/dnspolicy_controller_test.go +++ b/test/policy_integration/dnspolicy_controller_test.go @@ -19,6 +19,7 @@ import ( "github.com/Kuadrant/multicluster-gateway-controller/pkg/_internal/conditions" "github.com/Kuadrant/multicluster-gateway-controller/pkg/apis/v1alpha1" + "github.com/Kuadrant/multicluster-gateway-controller/pkg/apis/v1alpha2" . "github.com/Kuadrant/multicluster-gateway-controller/pkg/controllers/dnspolicy" "github.com/Kuadrant/multicluster-gateway-controller/pkg/utils" testutil "github.com/Kuadrant/multicluster-gateway-controller/test/util" @@ -27,11 +28,11 @@ import ( var _ = Describe("DNSPolicy", func() { var gatewayClass *gatewayapiv1.GatewayClass - var managedZone *v1alpha1.ManagedZone + var managedZone *v1alpha2.ManagedZone var testNamespace string var dnsPolicyBuilder *testutil.DNSPolicyBuilder var gateway *gatewayapiv1.Gateway - var dnsPolicy *v1alpha1.DNSPolicy + var dnsPolicy *v1alpha2.DNSPolicy var recordName, wildcardRecordName string BeforeEach(func() { @@ -40,10 +41,16 @@ var _ = Describe("DNSPolicy", func() { gatewayClass = testutil.NewTestGatewayClass("foo", "default", "kuadrant.io/bar") Expect(k8sClient.Create(ctx, gatewayClass)).To(Succeed()) - managedZone = testutil.NewManagedZoneBuilder("mz-example-com", testNamespace, "example.com").ManagedZone + managedZone = testutil.NewManagedZoneBuilder("mz-example-com", testNamespace). + WithID("1234"). + WithDomainName("example.com"). + WithDescription("example.com"). + WithProviderSecret("secretname"). + ManagedZone Expect(k8sClient.Create(ctx, managedZone)).To(Succeed()) - dnsPolicyBuilder = testutil.NewDNSPolicyBuilder("test-dns-policy", testNamespace) + dnsPolicyBuilder = testutil.NewDNSPolicyBuilder("test-dns-policy", testNamespace). + WithProviderManagedZone(managedZone.Name) }) AfterEach(func() { @@ -71,7 +78,7 @@ var _ = Describe("DNSPolicy", func() { BeforeEach(func() { dnsPolicy = dnsPolicyBuilder. WithTargetGateway("test-gateway"). - WithRoutingStrategy(v1alpha1.SimpleRoutingStrategy). + WithRoutingStrategy(v1alpha2.SimpleRoutingStrategy). DNSPolicy Expect(k8sClient.Create(ctx, dnsPolicy)).To(Succeed()) }) @@ -173,8 +180,8 @@ var _ = Describe("DNSPolicy", func() { }, TestTimeoutMedium, TestRetryIntervalMedium).Should(Succeed()) // expect no dns records - Consistently(func() []v1alpha1.DNSRecord { - dnsRecords := v1alpha1.DNSRecordList{} + Consistently(func() []v1alpha2.DNSRecord { + dnsRecords := v1alpha2.DNSRecordList{} err := k8sClient.List(ctx, &dnsRecords, client.InNamespace(dnsPolicy.GetNamespace())) Expect(err).ToNot(HaveOccurred()) return dnsRecords.Items @@ -204,7 +211,7 @@ var _ = Describe("DNSPolicy", func() { Gateway dnsPolicy = dnsPolicyBuilder. WithTargetGateway(testGatewayName). - WithRoutingStrategy(v1alpha1.SimpleRoutingStrategy). + WithRoutingStrategy(v1alpha2.SimpleRoutingStrategy). DNSPolicy Expect(k8sClient.Create(ctx, gateway)).To(Succeed()) @@ -212,8 +219,8 @@ var _ = Describe("DNSPolicy", func() { }) It("should not create a dns record", func() { - Consistently(func() []v1alpha1.DNSRecord { // DNS record exists - dnsRecords := v1alpha1.DNSRecordList{} + Consistently(func() []v1alpha2.DNSRecord { // DNS record exists + dnsRecords := v1alpha2.DNSRecordList{} err := k8sClient.List(ctx, &dnsRecords, client.InNamespace(dnsPolicy.GetNamespace())) Expect(err).ToNot(HaveOccurred()) return dnsRecords.Items @@ -257,7 +264,7 @@ var _ = Describe("DNSPolicy", func() { WithHTTPListener(TestListenerNameWildcard, TestHostWildcard). Gateway dnsPolicy = dnsPolicyBuilder.WithTargetGateway(TestGatewayName). - WithRoutingStrategy(v1alpha1.SimpleRoutingStrategy). + WithRoutingStrategy(v1alpha2.SimpleRoutingStrategy). DNSPolicy Expect(k8sClient.Create(ctx, gateway)).To(Succeed()) @@ -380,7 +387,7 @@ var _ = Describe("DNSPolicy", func() { patch := client.MergeFrom(existingGateway.DeepCopy()) existingGateway.Spec.Listeners = newListeners - rec := &v1alpha1.DNSRecord{} + rec := &v1alpha2.DNSRecord{} if err := k8sClient.Patch(ctx, existingGateway, patch); err != nil { return err } @@ -435,7 +442,7 @@ var _ = Describe("DNSPolicy", func() { It("should remove dns record reference on policy deletion even if gateway is removed", func() { Eventually(func() error { // DNS record exists - return k8sClient.Get(ctx, client.ObjectKey{Name: recordName, Namespace: testNamespace}, &v1alpha1.DNSRecord{}) + return k8sClient.Get(ctx, client.ObjectKey{Name: recordName, Namespace: testNamespace}, &v1alpha2.DNSRecord{}) }, TestTimeoutMedium, TestRetryIntervalMedium).Should(Succeed()) err := k8sClient.Delete(ctx, gateway) @@ -445,7 +452,7 @@ var _ = Describe("DNSPolicy", func() { Expect(client.IgnoreNotFound(err)).ToNot(HaveOccurred()) Eventually(func() error { // DNS record removed - return k8sClient.Get(ctx, client.ObjectKey{Name: recordName, Namespace: testNamespace}, &v1alpha1.DNSRecord{}) + return k8sClient.Get(ctx, client.ObjectKey{Name: recordName, Namespace: testNamespace}, &v1alpha2.DNSRecord{}) }, TestTimeoutMedium, TestRetryIntervalMedium).Should(MatchError(ContainSubstring("not found"))) }) diff --git a/test/policy_integration/managedzone_controller_test.go b/test/policy_integration/managedzone_controller_test.go index e8f346e4f..343a3651b 100644 --- a/test/policy_integration/managedzone_controller_test.go +++ b/test/policy_integration/managedzone_controller_test.go @@ -23,26 +23,27 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "sigs.k8s.io/controller-runtime/pkg/client" - "github.com/Kuadrant/multicluster-gateway-controller/pkg/apis/v1alpha1" + "github.com/Kuadrant/multicluster-gateway-controller/pkg/apis/v1alpha2" testutil "github.com/Kuadrant/multicluster-gateway-controller/test/util" //+kubebuilder:scaffold:imports ) var _ = Describe("ManagedZoneReconciler", func() { Context("testing ManagedZone controller", func() { - var managedZone *v1alpha1.ManagedZone + var managedZone *v1alpha2.ManagedZone BeforeEach(func() { - managedZone = &v1alpha1.ManagedZone{ + managedZone = &v1alpha2.ManagedZone{ ObjectMeta: metav1.ObjectMeta{ Name: testutil.Domain, Namespace: defaultNS, }, - Spec: v1alpha1.ManagedZoneSpec{ - ID: testutil.Domain, + Spec: v1alpha2.ManagedZoneSpec{ + ID: testutil.Pointer(testutil.Domain), DomainName: testutil.Domain, - SecretRef: &v1alpha1.SecretRef{ + ProviderRef: v1alpha2.ProviderRef{ Name: providerCredential, + Kind: v1alpha2.ProviderKindSecret, }, }, } @@ -50,7 +51,7 @@ var _ = Describe("ManagedZoneReconciler", func() { AfterEach(func() { // Clean up managedZones - mzList := &v1alpha1.ManagedZoneList{} + mzList := &v1alpha2.ManagedZoneList{} err := k8sClient.List(ctx, mzList, client.InNamespace(defaultNS)) Expect(err).NotTo(HaveOccurred()) for _, mz := range mzList.Items { @@ -62,7 +63,7 @@ var _ = Describe("ManagedZoneReconciler", func() { It("should accept a managed zone for this controller and allow deletion", func() { Expect(k8sClient.Create(ctx, managedZone)).To(BeNil()) - createdMZ := &v1alpha1.ManagedZone{} + createdMZ := &v1alpha2.ManagedZone{} Eventually(func() error { return k8sClient.Get(ctx, client.ObjectKey{Namespace: managedZone.Namespace, Name: managedZone.Name}, createdMZ) @@ -80,13 +81,13 @@ var _ = Describe("ManagedZoneReconciler", func() { }) It("should reject a managed zone with an invalid domain name", func() { - invalidDomainNameManagedZone := &v1alpha1.ManagedZone{ + invalidDomainNameManagedZone := &v1alpha2.ManagedZone{ ObjectMeta: metav1.ObjectMeta{ Name: "invalid_domain", Namespace: defaultNS, }, - Spec: v1alpha1.ManagedZoneSpec{ - ID: "invalid_domain", + Spec: v1alpha2.ManagedZoneSpec{ + ID: testutil.Pointer("invalid_domain"), DomainName: "invalid_domain", }, } diff --git a/test/policy_integration/suite_test.go b/test/policy_integration/suite_test.go index 0b48c4685..a362afae7 100644 --- a/test/policy_integration/suite_test.go +++ b/test/policy_integration/suite_test.go @@ -42,6 +42,7 @@ import ( "github.com/kuadrant/kuadrant-operator/pkg/reconcilers" "github.com/Kuadrant/multicluster-gateway-controller/pkg/apis/v1alpha1" + "github.com/Kuadrant/multicluster-gateway-controller/pkg/apis/v1alpha2" . "github.com/Kuadrant/multicluster-gateway-controller/pkg/controllers/dnshealthcheckprobe" . "github.com/Kuadrant/multicluster-gateway-controller/pkg/controllers/dnspolicy" . "github.com/Kuadrant/multicluster-gateway-controller/pkg/controllers/managedzone" @@ -61,7 +62,7 @@ var ( ctx context.Context cancel context.CancelFunc logger logr.Logger - providerFactory = func(ctx context.Context, managedZone *v1alpha1.ManagedZone) (dns.Provider, error) { + providerFactory = func(ctx context.Context, providerAccessor v1alpha2.ProviderAccessor) (dns.Provider, error) { return &dns.FakeProvider{}, nil } ) @@ -108,6 +109,9 @@ var _ = BeforeSuite(func() { err = v1alpha1.AddToScheme(scheme.Scheme) Expect(err).NotTo(HaveOccurred()) + err = v1alpha2.AddToScheme(scheme.Scheme) + Expect(err).NotTo(HaveOccurred()) + err = gatewayapiv1.AddToScheme(scheme.Scheme) Expect(err).NotTo(HaveOccurred()) diff --git a/test/util/helper.go b/test/util/helper.go index cf95380bc..7e4b8af1b 100644 --- a/test/util/helper.go +++ b/test/util/helper.go @@ -18,6 +18,7 @@ import ( gatewayapiv1 "sigs.k8s.io/gateway-api/apis/v1" "github.com/Kuadrant/multicluster-gateway-controller/pkg/apis/v1alpha1" + "github.com/Kuadrant/multicluster-gateway-controller/pkg/apis/v1alpha2" ) const ( @@ -124,6 +125,7 @@ func GetValidTestScheme() *runtime.Scheme { _ = gatewayapiv1.AddToScheme(scheme) _ = corev1.AddToScheme(scheme) _ = v1alpha1.AddToScheme(scheme) + _ = v1alpha2.AddToScheme(scheme) _ = certman.AddToScheme(scheme) return scheme } diff --git a/test/util/suite_config.go b/test/util/suite_config.go index 371bf1607..4caf0b479 100644 --- a/test/util/suite_config.go +++ b/test/util/suite_config.go @@ -25,6 +25,7 @@ import ( gatewayapiv1 "sigs.k8s.io/gateway-api/apis/v1" mgcv1alpha1 "github.com/Kuadrant/multicluster-gateway-controller/pkg/apis/v1alpha1" + mgcv1alpha2 "github.com/Kuadrant/multicluster-gateway-controller/pkg/apis/v1alpha2" ) const ( @@ -122,6 +123,10 @@ func (cfg *SuiteConfig) Build() error { if err != nil { return err } + err = mgcv1alpha2.AddToScheme(scheme.Scheme) + if err != nil { + return err + } err = certmanv1.AddToScheme(scheme.Scheme) if err != nil { return err diff --git a/test/util/test_dnspolicy_types.go b/test/util/test_dnspolicy_types.go index 958def82f..03da37ec0 100644 --- a/test/util/test_dnspolicy_types.go +++ b/test/util/test_dnspolicy_types.go @@ -8,21 +8,22 @@ import ( gatewayapiv1alpha2 "sigs.k8s.io/gateway-api/apis/v1alpha2" "github.com/Kuadrant/multicluster-gateway-controller/pkg/apis/v1alpha1" + "github.com/Kuadrant/multicluster-gateway-controller/pkg/apis/v1alpha2" ) // DNSPolicyBuilder wrapper for DNSPolicy builder helper type DNSPolicyBuilder struct { - *v1alpha1.DNSPolicy + *v1alpha2.DNSPolicy } func NewDNSPolicyBuilder(name, ns string) *DNSPolicyBuilder { return &DNSPolicyBuilder{ - &v1alpha1.DNSPolicy{ + &v1alpha2.DNSPolicy{ ObjectMeta: metav1.ObjectMeta{ Name: name, Namespace: ns, }, - Spec: v1alpha1.DNSPolicySpec{}, + Spec: v1alpha2.DNSPolicySpec{}, }, } } @@ -32,17 +33,22 @@ func (t *DNSPolicyBuilder) WithTargetRef(targetRef gatewayapiv1alpha2.PolicyTarg return t } -func (t *DNSPolicyBuilder) WithHealthCheck(healthCheck v1alpha1.HealthCheckSpec) *DNSPolicyBuilder { +func (t *DNSPolicyBuilder) WithProviderRef(providerRef v1alpha2.ProviderRef) *DNSPolicyBuilder { + t.Spec.ProviderRef = providerRef + return t +} + +func (t *DNSPolicyBuilder) WithHealthCheck(healthCheck v1alpha2.HealthCheckSpec) *DNSPolicyBuilder { t.Spec.HealthCheck = &healthCheck return t } -func (t *DNSPolicyBuilder) WithLoadBalancing(loadBalancing v1alpha1.LoadBalancingSpec) *DNSPolicyBuilder { +func (t *DNSPolicyBuilder) WithLoadBalancing(loadBalancing v1alpha2.LoadBalancingSpec) *DNSPolicyBuilder { t.Spec.LoadBalancing = &loadBalancing return t } -func (t *DNSPolicyBuilder) WithRoutingStrategy(strategy v1alpha1.RoutingStrategy) *DNSPolicyBuilder { +func (t *DNSPolicyBuilder) WithRoutingStrategy(strategy v1alpha2.RoutingStrategy) *DNSPolicyBuilder { t.Spec.RoutingStrategy = strategy return t } @@ -59,10 +65,33 @@ func (t *DNSPolicyBuilder) WithTargetGateway(gwName string) *DNSPolicyBuilder { }) } +//ProviderRef + +func (t *DNSPolicyBuilder) WithProviderManagedZone(mzName string) *DNSPolicyBuilder { + return t.WithProviderRef(v1alpha2.ProviderRef{ + Name: mzName, + Kind: v1alpha2.ProviderKindManagedZone, + }) +} + +func (t *DNSPolicyBuilder) WithProviderSecret(secretName string) *DNSPolicyBuilder { + return t.WithProviderRef(v1alpha2.ProviderRef{ + Name: secretName, + Kind: v1alpha2.ProviderKindSecret, + }) +} + +func (t *DNSPolicyBuilder) WithProviderNone(name string) *DNSPolicyBuilder { + return t.WithProviderRef(v1alpha2.ProviderRef{ + Name: name, + Kind: v1alpha2.ProviderKindNone, + }) +} + //HealthCheck func (t *DNSPolicyBuilder) WithHealthCheckFor(endpoint string, port *int, protocol v1alpha1.HealthProtocol, failureThreshold *int) *DNSPolicyBuilder { - return t.WithHealthCheck(v1alpha1.HealthCheckSpec{ + return t.WithHealthCheck(v1alpha2.HealthCheckSpec{ Endpoint: endpoint, Port: port, Protocol: &protocol, @@ -76,55 +105,89 @@ func (t *DNSPolicyBuilder) WithHealthCheckFor(endpoint string, port *int, protoc //LoadBalancing -func (t *DNSPolicyBuilder) WithLoadBalancingWeighted(lbWeighted v1alpha1.LoadBalancingWeighted) *DNSPolicyBuilder { +func (t *DNSPolicyBuilder) WithLoadBalancingWeighted(lbWeighted v1alpha2.LoadBalancingWeighted) *DNSPolicyBuilder { if t.Spec.LoadBalancing == nil { - t.Spec.LoadBalancing = &v1alpha1.LoadBalancingSpec{} + t.Spec.LoadBalancing = &v1alpha2.LoadBalancingSpec{} } t.Spec.LoadBalancing.Weighted = &lbWeighted return t } -func (t *DNSPolicyBuilder) WithLoadBalancingGeo(lbGeo v1alpha1.LoadBalancingGeo) *DNSPolicyBuilder { +func (t *DNSPolicyBuilder) WithLoadBalancingGeo(lbGeo v1alpha2.LoadBalancingGeo) *DNSPolicyBuilder { if t.Spec.LoadBalancing == nil { - t.Spec.LoadBalancing = &v1alpha1.LoadBalancingSpec{} + t.Spec.LoadBalancing = &v1alpha2.LoadBalancingSpec{} } t.Spec.LoadBalancing.Geo = &lbGeo return t } -func (t *DNSPolicyBuilder) WithLoadBalancingWeightedFor(defaultWeight v1alpha1.Weight, custom []*v1alpha1.CustomWeight) *DNSPolicyBuilder { - return t.WithLoadBalancingWeighted(v1alpha1.LoadBalancingWeighted{ +func (t *DNSPolicyBuilder) WithLoadBalancingWeightedFor(defaultWeight v1alpha2.Weight, custom []*v1alpha2.CustomWeight) *DNSPolicyBuilder { + return t.WithLoadBalancingWeighted(v1alpha2.LoadBalancingWeighted{ DefaultWeight: defaultWeight, Custom: custom, }) } func (t *DNSPolicyBuilder) WithLoadBalancingGeoFor(defaultGeo string) *DNSPolicyBuilder { - return t.WithLoadBalancingGeo(v1alpha1.LoadBalancingGeo{ + return t.WithLoadBalancingGeo(v1alpha2.LoadBalancingGeo{ DefaultGeo: defaultGeo, }) } // ManagedZoneBuilder wrapper for ManagedZone builder helper type ManagedZoneBuilder struct { - *v1alpha1.ManagedZone + *v1alpha2.ManagedZone } -func NewManagedZoneBuilder(name, ns, domainName string) *ManagedZoneBuilder { +func NewManagedZoneBuilder(name, ns string) *ManagedZoneBuilder { return &ManagedZoneBuilder{ - &v1alpha1.ManagedZone{ + &v1alpha2.ManagedZone{ ObjectMeta: metav1.ObjectMeta{ Name: name, Namespace: ns, }, - Spec: v1alpha1.ManagedZoneSpec{ - ID: "1234", - DomainName: domainName, - Description: domainName, - SecretRef: &v1alpha1.SecretRef{ - Name: "secretname", - }, - }, + Spec: v1alpha2.ManagedZoneSpec{}, }, } } + +func (t *ManagedZoneBuilder) WithID(id string) *ManagedZoneBuilder { + t.Spec.ID = &id + return t +} + +func (t *ManagedZoneBuilder) WithDomainName(domainName string) *ManagedZoneBuilder { + t.Spec.DomainName = domainName + return t +} + +func (t *ManagedZoneBuilder) WithDescription(description string) *ManagedZoneBuilder { + t.Spec.Description = &description + return t +} + +func (t *ManagedZoneBuilder) WithProviderRef(providerRef v1alpha2.ProviderRef) *ManagedZoneBuilder { + t.Spec.ProviderRef = providerRef + return t +} + +func (t *ManagedZoneBuilder) WithProviderManagedZone(mzName string) *ManagedZoneBuilder { + return t.WithProviderRef(v1alpha2.ProviderRef{ + Name: mzName, + Kind: v1alpha2.ProviderKindManagedZone, + }) +} + +func (t *ManagedZoneBuilder) WithProviderSecret(secretName string) *ManagedZoneBuilder { + return t.WithProviderRef(v1alpha2.ProviderRef{ + Name: secretName, + Kind: v1alpha2.ProviderKindSecret, + }) +} + +func (t *ManagedZoneBuilder) WithProviderNone(secretName string) *ManagedZoneBuilder { + return t.WithProviderRef(v1alpha2.ProviderRef{ + Name: secretName, + Kind: v1alpha2.ProviderKindNone, + }) +}