diff --git a/cmd/main.go b/cmd/main.go
index 2ad940b3..55113f5e 100644
--- a/cmd/main.go
+++ b/cmd/main.go
@@ -189,6 +189,10 @@ func main() {
// Ensure defaults are applied even if the decoded config was empty/partial.
// (The scheme defaulting may already have done this, but this makes it explicit.)
config.SetObjectDefaults_DNSOperator(&serverConfig)
+ if err := serverConfig.Controllers.DNSZoneReplicator.ZoneClaims.Validate(); err != nil {
+ setupLog.Error(err, "invalid server config")
+ os.Exit(1)
+ }
setupLog.Info("server config", "config", serverConfig)
@@ -371,14 +375,24 @@ func main() {
// --- register controllers BEFORE starting provider/manager ---
if err := (&controller.DNSRecordSetReplicator{
DownstreamClient: downstreamCluster.GetClient(),
+ ZoneClaims: serverConfig.Controllers.DNSZoneReplicator.ZoneClaims.Enabled,
}).SetupWithManager(mcmgr, downstreamCluster); err != nil {
setupLog.Error(err, "unable to create controller", "controller", "DNSRecordSetReplicator")
os.Exit(1)
}
- if err := (&controller.DNSZoneReplicator{
+ zoneReplicator := &controller.DNSZoneReplicator{
DownstreamClient: downstreamCluster.GetClient(),
AccountingNamespace: serverConfig.DownstreamResourceManagement.DNSZoneAccountingNamespace,
- }).SetupWithManager(mcmgr, downstreamCluster); err != nil {
+ }
+ if claims := serverConfig.Controllers.DNSZoneReplicator.ZoneClaims; claims.Enabled {
+ zoneReplicator.ZoneClaims = &controller.ZoneClaims{
+ Reader: downstreamCluster.GetAPIReader(),
+ Writer: downstreamCluster.GetClient(),
+ Namespace: serverConfig.DownstreamResourceManagement.DNSZoneAccountingNamespace,
+ MaxEntries: claims.MaxEntries,
+ }
+ }
+ if err := zoneReplicator.SetupWithManager(mcmgr, downstreamCluster); err != nil {
setupLog.Error(err, "unable to create controller", "controller", "DNSZoneReplicator")
os.Exit(1)
}
diff --git a/config/rbac/role.yaml b/config/rbac/role.yaml
index 262d28dc..7f8fab82 100644
--- a/config/rbac/role.yaml
+++ b/config/rbac/role.yaml
@@ -96,6 +96,14 @@ rules:
- delete
- patch
- update
+- apiGroups:
+ - dns.networking.miloapis.com
+ resources:
+ - zoneclaimsets
+ verbs:
+ - create
+ - get
+ - update
- apiGroups:
- events.k8s.io
resources:
diff --git a/docs/agent/llms-full.txt b/docs/agent/llms-full.txt
index 952a3328..6f3a8a11 100644
--- a/docs/agent/llms-full.txt
+++ b/docs/agent/llms-full.txt
@@ -31,10 +31,15 @@ and a Programmed condition (whether it is live in the DNS backend).
Reasons on Programmed fall into a few buckets:
- Self-clearing, no customer action needed: Pending,
+ PendingPreviousZoneRemoval (the zone holds its domain and waits a few
+ minutes for another project's zone to stop serving),
PendingDomainVerification (but see below — this one still needs the
customer to act on a different object).
- Needs a person to act, and never clears by itself: NotOwner, Conflict,
- DNSZoneInUse.
+ InvalidDomain.
+- DNSZoneInUse: another zone holds the domain. With zone claims on, the
+ zone retries every minute and starts serving once the other zone is
+ deleted; if the other zone is the customer's own, they can delete it.
- Depends on the message: PDNSError. The same reason covers a value the
customer typed wrong, a zone still coming up, and a backend hiccup —
read the message, don't stop at the reason code.
diff --git a/docs/architecture/conditions.md b/docs/architecture/conditions.md
index 2c22b512..ffaddd8e 100644
--- a/docs/architecture/conditions.md
+++ b/docs/architecture/conditions.md
@@ -62,7 +62,10 @@ retrying, and keeps failing, for as long as the cause stands.
|---|---|---|---|
| `NotOwner` | per-record `Programmed` | Another record set claimed this owner name first and holds it. | Whoever owns one of the two record sets removes their claim. |
| `Conflict` | per-record `Programmed` | The backend refuses this record because it cannot coexist with data already at the name, such as a `CNAME` beside other types. | Remove the conflicting data, or move the record to another name. |
-| `DNSZoneInUse` | zone `Accepted` and `Programmed` | Another zone already claims this domain. | Release the other zone, or use a different domain. |
+| `DNSZoneInUse` | zone `Accepted` and `Programmed` | Another zone already claims this domain. With zone claims on, the message says whether another project's zone holds the same name, a parent, or a child, and the zone is retried every minute. | Delete the other zone if it's yours, or use a different domain. With zone claims on, the zone starts serving once the other zone is deleted. |
+| `InvalidDomain` | zone `Accepted` and `Programmed` | With zone claims on, the zone's name is a public suffix, such as `co.uk`. | Create the zone for a domain registered under the suffix. |
+| `ClaimSetFull` | zone `Accepted` and `Programmed` | With zone claims on, the zone's registered domain already holds `zoneClaims.maxEntries` zones. Retried every minute. | An operator raises the limit, or zones under the domain are deleted. |
+| `PendingPreviousZoneRemoval` | zone `Accepted` and `Programmed` | With zone claims on, the zone holds its domain and waits for another project's overlapping zone to stop serving. Retried every 10 seconds. | Nobody. It clears once the other zone's served copy is gone, normally within a few minutes. |
| `TargetUnresolved` | ALIAS record set `TargetResolved` | An ALIAS target resolves to no A or AAAA address, so the name answers SERVFAIL. The record is still `Programmed`. | Whoever owns the target restores it, or the record set points at a live target. |
`NotOwner` is the one most often mistaken for a transient state. It is not.
diff --git a/docs/architecture/zone-claims/README.md b/docs/architecture/zone-claims/README.md
index 3faa27b1..77cd469a 100644
--- a/docs/architecture/zone-claims/README.md
+++ b/docs/architecture/zone-claims/README.md
@@ -213,7 +213,9 @@ Consequences:
With `zoneClaims.enabled` on, the replicator's `DNSZone` reconcile admits a zone
-in `ensureZoneClaim`:
+in `admitZoneClaim`, before it writes the zone's exact-name accounting
+ConfigMap, so a refused zone never takes the ConfigMap from the project that
+holds the name:
1. Compute the registered domain. If there's none, refuse with `InvalidDomain`.
2. Get the claim set with the uncached reader. If it doesn't exist, build it
@@ -226,22 +228,40 @@ in `ensureZoneClaim`:
4. Copy the zone's `spec.grants` to its entry, skipping a self-grant on an
entry with `handedOverTo`.
5. Run `normalize` and `evaluate`, and update the set with the resourceVersion
- you read. On a conflict, go back to step 2.
+ you read. On a conflict, go back to step 2. If the entry that blocks this
+ zone is bound to a zone that no longer exists and whose shadow zone is gone
+ too, drop that entry and evaluate again. An entry whose zone is gone but
+ whose shadow remains, such as a zone deleted with its finalizer removed, is
+ kept, so no other project serves an overlapping name beside the orphaned
+ shadow.
6. Act on the entry's state:
- - `Active`: continue to `ensureDomain`, `ensureDomainRef`, and the
- verification gate if it's enabled. Before `ensureDownstreamZone`, check
- that no other shadow zone for the same `spec.domainName` exists in the
- authoritative cluster. If one does, report `Accepted=False` with reason
- `PendingPreviousZoneRemoval` and wait for its deletion event.
- - `Contested`: delete the shadow zone if one exists, set `Accepted=False`
- and `Programmed=False`, and stop.
+ - `Active`: check every other entry in the set that isn't `Active`, belongs
+ to another project, is bound to a zone, and has the same name, a parent,
+ or a child. If any of those zones still has a shadow zone, read with the
+ uncached reader, report `Accepted=False` with reason
+ `PendingPreviousZoneRemoval` and retry every 10 seconds. Otherwise,
+ continue to `ensureDomain`, `ensureDomainRef`, the verification gate if
+ it's enabled, and `ensureDownstreamZone`.
+ - `Contested`: set `Accepted=False` and `Programmed=False`, and delete the
+ shadow zone if one exists. Once the uncached reader confirms the shadow
+ is gone, delete the zone's own exact-name accounting ConfigMap, if the
+ zone owns it, so the zone now `Active` for the name can take it. Stop.
+
+After `ensureDownstreamZone` creates or updates the shadow, the reconcile runs
+admission again. If the entry is no longer `Active`, or an overlapping zone
+of another project now has a shadow, it deletes the shadow it just wrote and
+reports the refusal or the wait. A zone that loses its claim withdraws its
+shadow on its own next reconcile. Admission and the shadow write aren't
+atomic, so this narrows the window in which two projects serve overlapping
+names to the time between the shadow write and the second check.
The backend identifies a zone only by name: `EnsureZone` does nothing if the
name exists, and deleting a shadow deletes the backend zone by name. The
shadow check in step 6 keeps a name from changing hands while the old shadow
still exists. Without it, after a handover or a release, the new zone's shadow
could adopt the old backend zone, or lose it when the old shadow is deleted.
-The check uses a field index on shadow zones by `spec.domainName`.
+The check reads each overlapping zone's shadow by name; it doesn't use an
+index.
On zone deletion:
@@ -256,9 +276,12 @@ requeues each set at its earliest `reservedUntil` to expire reservations.
A `Contested` entry has no shadow zone. When a zone that was serving becomes
`Contested`, after a handover or a release, its shadow is deleted. Its records
-stay upstream, so its project can still export them. The record set replicator
-mirrors record sets only for a zone that's `Accepted=True`, so a contested
-project's records never reach the backend zone that another project serves.
+stay upstream, so its project can still export them. The zone is refused
+before its shadow is deleted, and the record set replicator doesn't mirror the
+record sets of a refused zone into the authoritative cluster; it retries them
+every minute. The downstream record set controller also programs a record set
+only through its own project's shadow zone, so a contested project's records
+never reach the backend zone that another project serves.
## The verification gate
@@ -316,7 +339,7 @@ Other `Accepted=False` reasons from admission:
|--------|---------|
| `InvalidDomain` | The zone's name is a public suffix and has no registered domain. |
| `ClaimSetFull` | The registered domain's claim set is at `zoneClaims.maxEntries`. |
-| `PendingPreviousZoneRemoval` | The zone's entry is `Active`, and the previous zone's shadow for the name is still being removed. |
+| `PendingPreviousZoneRemoval` | The zone's entry is `Active`, and an overlapping zone of another project that lost its claim still has a shadow zone. |
| `PendingDomainVerification` | The gate is on and no covering `Domain` is `Verified`. |
## Grants
@@ -399,7 +422,7 @@ With `zoneClaims.enabled` off, the replicator admits zones by exact name:
name in the accounting namespace, with `owner: //`.
With the setting on, the replicator builds claim sets from those ConfigMaps
-lazily. When `ensureZoneClaim` finds no claim set for a registered domain, it
+lazily. When `admitZoneClaim` finds no claim set for a registered domain, it
lists the accounting ConfigMaps whose names are that domain or under it and
builds the set from them:
@@ -421,7 +444,8 @@ builds the set from them:
stops the other.
While the setting is on, the replicator keeps writing the exact-name ConfigMap
-for each admitted zone and deletes it with the zone. Turning the setting off
+for each admitted zone, and deletes it with the zone or once the zone loses
+its claim and its shadow is gone. Turning the setting off
returns to exact-name admission, with a ConfigMap for every zone admitted in the
meantime. A zone that claim sets refused because it's under or over another
project's zone is admitted by exact name again, and with the verification gate
@@ -460,7 +484,7 @@ setting.
|-------|---------|-------------|
| `controllers.dnsZoneReplicator.zoneClaims.enabled` | `false` | Admit zones through claim sets. Off: admit by exact name with accounting ConfigMaps. |
| `controllers.dnsZoneReplicator.zoneClaims.reservationPeriod` | `0` | How long a deleted zone's name stays reserved for its project. `0` turns reservations off. |
-| `controllers.dnsZoneReplicator.zoneClaims.maxEntries` | `256` | The most entries one claim set holds. |
+| `controllers.dnsZoneReplicator.zoneClaims.maxEntries` | `256` | The most entries one claim set holds, from 1 to 1024. The `ZoneClaimSet` schema holds at most 1024, and the operator refuses to start with a larger value. |
| `controllers.dnsZoneReplicator.grants.enabled` | `false` | Honor grants and handovers in `spec.grants`. |
| `controllers.dnsZoneReplicator.requireDomainVerification` | `true` | Wait for a verified `Domain` before serving an `Active` zone. The operator refuses to start with `false` while `zoneClaims.enabled` is `false`. |
diff --git a/internal/agent/catalog.go b/internal/agent/catalog.go
index b9ccf4bb..7aa7a407 100644
--- a/internal/agent/catalog.go
+++ b/internal/agent/catalog.go
@@ -153,6 +153,15 @@ var catalog = []ReasonInfo{
Skill: SkillRecordNotProgrammed,
ExpectedDuration: windowBackendProgramming,
},
+ {
+ Reason: sharedutil.ReasonPendingPreviousZoneRemoval,
+ ConditionTypes: []string{sharedutil.CondAccepted, sharedutil.CondProgrammed},
+ Actionability: ActionabilityTransient,
+ Explanation: "This zone now holds its domain, and is waiting for another project's zone that " +
+ "overlaps it to stop serving. It starts serving on its own within a few minutes.",
+ Remediation: remediationWait,
+ ExpectedDuration: windowBackendProgramming,
+ },
{
Reason: sharedutil.ReasonPendingDomainVerification,
ConditionTypes: []string{sharedutil.CondAccepted, sharedutil.CondProgrammed},
@@ -185,6 +194,18 @@ var catalog = []ReasonInfo{
"delete or rename the loser.",
Skill: SkillRecordNotOwner,
},
+ {
+ Reason: sharedutil.ReasonDNSZoneInUse,
+ ConditionTypes: []string{sharedutil.CondAccepted, sharedutil.CondProgrammed},
+ Actionability: ActionabilityUser,
+ Explanation: "Another zone already holds this domain, so this one is not served. When zone " +
+ "claims are on, the message says whether the other zone holds the same name, a parent, " +
+ "or a child, and this zone is retried every minute and starts serving once that zone is " +
+ "deleted. When zone claims are off, it is not retried.",
+ Remediation: "If the zone holding the domain is yours, delete it or use a different domain. " +
+ "Otherwise, with zone claims on, this zone serves once the other zone is deleted; with " +
+ "them off, delete and recreate this zone after that.",
+ },
// ------------------------------------------------------------- conflict
// Actionability here is the default only. classifyConflict in diagnose.go
@@ -217,13 +238,20 @@ var catalog = []ReasonInfo{
// --------------------------------------------------------------- platform
{
- Reason: sharedutil.ReasonDNSZoneInUse,
- ConditionTypes: []string{sharedutil.CondAccepted},
+ Reason: sharedutil.ReasonClaimSetFull,
+ ConditionTypes: []string{sharedutil.CondAccepted, sharedutil.CondProgrammed},
Actionability: ActionabilityPlatform,
- Explanation: "Another zone already owns this domain in Datum's records, so this one cannot be " +
- "provisioned. This is not something a customer can see or cause from their own project.",
+ Explanation: "The registered domain this zone belongs to already holds the most zones Datum " +
+ "records for one domain, so this zone cannot be admitted. It is retried every minute.",
Remediation: remediationEscalate,
},
+ {
+ Reason: sharedutil.ReasonInvalidDomain,
+ ConditionTypes: []string{sharedutil.CondAccepted, sharedutil.CondProgrammed},
+ Actionability: ActionabilityUser,
+ Explanation: "The zone's name is a public suffix, such as co.uk, which no single zone can claim.",
+ Remediation: "Create the zone for a domain registered under the suffix instead, such as example.co.uk.",
+ },
}
// byReason indexes the catalog, rendering each entry's window in the same
diff --git a/internal/agent/catalog_test.go b/internal/agent/catalog_test.go
index ca22de3f..de576291 100644
--- a/internal/agent/catalog_test.go
+++ b/internal/agent/catalog_test.go
@@ -24,6 +24,9 @@ func TestCatalogCoversEveryKnownReason(t *testing.T) {
sharedutil.ReasonPDNSError,
sharedutil.ReasonConflict,
sharedutil.ReasonPendingDomainVerification,
+ sharedutil.ReasonInvalidDomain,
+ sharedutil.ReasonClaimSetFull,
+ sharedutil.ReasonPendingPreviousZoneRemoval,
}
for _, reason := range want {
if _, ok := ExplainReason(reason); !ok {
@@ -32,6 +35,19 @@ func TestCatalogCoversEveryKnownReason(t *testing.T) {
}
}
+func TestDNSZoneInUseIsTheCustomersToActOn(t *testing.T) {
+ info, ok := ExplainReason(sharedutil.ReasonDNSZoneInUse)
+ if !ok {
+ t.Fatal("catalog has no entry for DNSZoneInUse")
+ }
+ if info.Actionability != ActionabilityUser {
+ t.Errorf("actionability = %s, want %s", info.Actionability, ActionabilityUser)
+ }
+ if info.Remediation == remediationEscalate {
+ t.Error("remediation tells the customer to escalate, but a refused zone serves once the other zone is deleted")
+ }
+}
+
// TestTransientReasonsThatSayWaitDeclareAWindow pins that "wait" is always a
// falsifiable claim: any entry telling the customer this clears on its own
// declares how long that should take, so ActionabilityAt has something to
diff --git a/internal/agent/copy_test.go b/internal/agent/copy_test.go
index 13519038..55789595 100644
--- a/internal/agent/copy_test.go
+++ b/internal/agent/copy_test.go
@@ -301,7 +301,7 @@ func diagnosisFixtures() map[string]Diagnosis {
condAt(sharedutil.CondProgrammed, "False", sharedutil.ReasonPending, "waiting", stale)))
out["zone-platform"] = DiagnoseZoneAt(stagingNow, zone("example.com",
- cond(sharedutil.CondAccepted, "False", sharedutil.ReasonDNSZoneInUse, "already claimed")))
+ cond(sharedutil.CondAccepted, "False", sharedutil.ReasonClaimSetFull, "claim set full")))
notOwner := recordSet("www", []dnsv1alpha1.RecordEntry{{Name: "www"}},
ownerStatus("www.example.com.", cond(sharedutil.CondProgrammed, "False", sharedutil.ReasonNotOwner, "taken")))
diff --git a/internal/agent/diagnose_test.go b/internal/agent/diagnose_test.go
index 12d75e61..798d8f6e 100644
--- a/internal/agent/diagnose_test.go
+++ b/internal/agent/diagnose_test.go
@@ -42,9 +42,9 @@ func TestDiagnoseZone(t *testing.T) {
},
"platform fault": {
zone: zone("example.com",
- cond(sharedutil.CondAccepted, "False", sharedutil.ReasonDNSZoneInUse, "already claimed")),
+ cond(sharedutil.CondAccepted, "False", sharedutil.ReasonClaimSetFull, "claim set full")),
wantHealthy: false,
- wantReason: sharedutil.ReasonDNSZoneInUse,
+ wantReason: sharedutil.ReasonClaimSetFull,
wantActionability: ActionabilityPlatform,
},
}
diff --git a/internal/cmd/dns/util/shared.go b/internal/cmd/dns/util/shared.go
index bcd539fd..56611222 100644
--- a/internal/cmd/dns/util/shared.go
+++ b/internal/cmd/dns/util/shared.go
@@ -17,16 +17,17 @@ const (
CondProgrammed = sharedutil.CondProgrammed
CondDiscovered = sharedutil.CondDiscovered
- ReasonAccepted = sharedutil.ReasonAccepted
- ReasonPending = sharedutil.ReasonPending
- ReasonInvalidDNSRecordSet = sharedutil.ReasonInvalidDNSRecordSet
- ReasonProgrammed = sharedutil.ReasonProgrammed
- ReasonDiscovered = sharedutil.ReasonDiscovered
- ReasonDNSZoneInUse = sharedutil.ReasonDNSZoneInUse
- ReasonNotOwner = sharedutil.ReasonNotOwner
- ReasonPDNSError = sharedutil.ReasonPDNSError
- ReasonConflict = sharedutil.ReasonConflict
- ReasonPendingDomainVerification = sharedutil.ReasonPendingDomainVerification
+ ReasonAccepted = sharedutil.ReasonAccepted
+ ReasonPending = sharedutil.ReasonPending
+ ReasonInvalidDNSRecordSet = sharedutil.ReasonInvalidDNSRecordSet
+ ReasonProgrammed = sharedutil.ReasonProgrammed
+ ReasonDiscovered = sharedutil.ReasonDiscovered
+ ReasonDNSZoneInUse = sharedutil.ReasonDNSZoneInUse
+ ReasonNotOwner = sharedutil.ReasonNotOwner
+ ReasonPDNSError = sharedutil.ReasonPDNSError
+ ReasonConflict = sharedutil.ReasonConflict
+ ReasonPendingDomainVerification = sharedutil.ReasonPendingDomainVerification
+ ReasonPendingPreviousZoneRemoval = sharedutil.ReasonPendingPreviousZoneRemoval
StatusOK = sharedutil.StatusOK
StatusPending = sharedutil.StatusPending
diff --git a/internal/cmd/dns/zone/create.go b/internal/cmd/dns/zone/create.go
index 582084e3..e1909f2b 100644
--- a/internal/cmd/dns/zone/create.go
+++ b/internal/cmd/dns/zone/create.go
@@ -244,6 +244,7 @@ func waitForNameservers(ctx context.Context, c client.Client, name, domain strin
var assigned []string
var rejected error
+ var rejectedReason string
var lastErr error
consecutive := 0
@@ -268,9 +269,10 @@ func waitForNameservers(ctx context.Context, c client.Client, name, domain strin
// An admission-rejected zone will never get nameservers; waiting
// out the timeout would hide the reason it failed.
if accepted := apimeta.FindStatusCondition(z.Status.Conditions, util.CondAccepted); accepted != nil &&
- accepted.Status == metav1.ConditionFalse {
+ accepted.Status == metav1.ConditionFalse && accepted.Reason != util.ReasonPendingPreviousZoneRemoval {
rejected = util.NewCLIError(util.ExitInvalid,
fmt.Sprintf("the zone was rejected: %s", accepted.Message))
+ rejectedReason = accepted.Reason
return false, rejected
}
@@ -286,6 +288,13 @@ func waitForNameservers(ctx context.Context, c client.Client, name, domain strin
checkOnIt := "the zone was created — check on it with:\n datumctl dns zone describe " + domain
switch {
+ case rejected != nil && rejectedReason == util.ReasonDNSZoneInUse:
+ return nil, util.NewCLIError(util.ExitInvalid, rejected.Error()).
+ WithFix("another zone holds this domain. If that zone is yours, delete it. This zone can\n" +
+ " start serving once the other zone is gone; " + checkOnIt + "\n" +
+ " To give up on it, remove it with:\n" +
+ " datumctl dns zone delete " + domain).
+ WithCause(rejected)
case rejected != nil:
// DNSZoneInUse and its siblings are terminal: the object was created,
// is parked on Accepted=False, and will stay there. The user now owns
diff --git a/internal/cmd/dns/zone/create_test.go b/internal/cmd/dns/zone/create_test.go
index 61edec4a..b01f1597 100644
--- a/internal/cmd/dns/zone/create_test.go
+++ b/internal/cmd/dns/zone/create_test.go
@@ -276,6 +276,13 @@ func TestCreateWaitStopsOnRejection(t *testing.T) {
if !strings.Contains(err.Error(), "DNSZone claimed by another resource") {
t.Errorf("error = %q, want the server's message", err.Error())
}
+ var ce *util.CLIError
+ if !asCLIError(err, &ce) {
+ t.Fatalf("error is not a CLIError: %v", err)
+ }
+ if !strings.Contains(ce.Fix(), "start serving once the other zone is gone") {
+ t.Errorf("fix = %q, want it to say the zone can still serve", ce.Fix())
+ }
}
func TestCreateWaitTimeout(t *testing.T) {
@@ -574,3 +581,40 @@ func TestCreateRejectsAnOversizedLabel(t *testing.T) {
t.Errorf("error = %q, want it to name the label limit", err.Error())
}
}
+
+func TestCreateKeepsWaitingWhileAnotherProjectsZoneIsWithdrawn(t *testing.T) {
+ fixedSuffix(t)
+ fastPolling(t)
+
+ gets := 0
+ c := newFakeClientWith(t, interceptor.Funcs{
+ Get: func(ctx context.Context, cl client.WithWatch, key client.ObjectKey, obj client.Object, opts ...client.GetOption) error {
+ if err := cl.Get(ctx, key, obj, opts...); err != nil {
+ return err
+ }
+ if z, isZone := obj.(*dnsv1alpha1.DNSZone); isZone {
+ gets++
+ if gets < 3 {
+ z.Status.Conditions = []metav1.Condition{{
+ Type: "Accepted",
+ Status: metav1.ConditionFalse,
+ Reason: util.ReasonPendingPreviousZoneRemoval,
+ Message: "Waiting for another project's zone for example.com to stop serving.",
+ LastTransitionTime: metav1.Now(),
+ }}
+ return nil
+ }
+ z.Status.Nameservers = []string{"ns1.example.net.", "ns2.example.net."}
+ }
+ return nil
+ },
+ }, zoneClass(DefaultZoneClass))
+ h := newHarness(t, c)
+
+ if err := h.run("zone", "create", "example.com", "--timeout", "5s"); err != nil {
+ t.Fatalf("zone create: %v", err)
+ }
+ if !strings.Contains(h.out.String(), "ns1.example.net.") {
+ t.Errorf("output = %q, want the nameservers once the wait ends", h.out.String())
+ }
+}
diff --git a/internal/config/config.go b/internal/config/config.go
index 4772dba6..5f1c3d92 100644
--- a/internal/config/config.go
+++ b/internal/config/config.go
@@ -1,6 +1,8 @@
package config
import (
+ "fmt"
+
multiclusterproviders "go.miloapis.com/milo/pkg/multicluster-runtime"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/rest"
@@ -25,6 +27,42 @@ type DNSOperator struct {
// +k8s:deepcopy-gen=true
type ControllersConfig struct {
DNSRecordSetPowerDNS DNSRecordSetPowerDNSControllerConfig `json:"dnsRecordSetPowerDNS"`
+
+ DNSZoneReplicator DNSZoneReplicatorControllerConfig `json:"dnsZoneReplicator"`
+}
+
+// DNSZoneReplicatorControllerConfig tunes the controller that admits DNSZones
+// and mirrors them into the authoritative cluster.
+// +k8s:deepcopy-gen=true
+type DNSZoneReplicatorControllerConfig struct {
+ ZoneClaims ZoneClaimsConfig `json:"zoneClaims"`
+}
+
+// ZoneClaimsConfig controls admission through claim sets, which refuse a zone
+// for the same name as, a parent of, or a child of another project's zone.
+// +k8s:deepcopy-gen=true
+type ZoneClaimsConfig struct {
+ // Enabled admits zones through claim sets. When false, zones are admitted
+ // by exact name only.
+ Enabled bool `json:"enabled"`
+
+ // MaxEntries is the most entries one claim set holds, from 1 to 1024.
+ //
+ // +default=256
+ MaxEntries int `json:"maxEntries"`
+}
+
+// MaxZoneClaimEntries is the ZoneClaimSet schema's limit on entries.
+const MaxZoneClaimEntries = 1024
+
+func (c ZoneClaimsConfig) Validate() error {
+ if !c.Enabled {
+ return nil
+ }
+ if c.MaxEntries < 1 || c.MaxEntries > MaxZoneClaimEntries {
+ return fmt.Errorf("controllers.dnsZoneReplicator.zoneClaims.maxEntries must be from 1 to %d, got %d", MaxZoneClaimEntries, c.MaxEntries)
+ }
+ return nil
}
// DNSRecordSetPowerDNSControllerConfig tunes the controller that programs
diff --git a/internal/config/zoneclaims_test.go b/internal/config/zoneclaims_test.go
new file mode 100644
index 00000000..628375b5
--- /dev/null
+++ b/internal/config/zoneclaims_test.go
@@ -0,0 +1,37 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+
+package config
+
+import "testing"
+
+func TestZoneClaimsDefaultToOff(t *testing.T) {
+ var c DNSOperator
+ SetObjectDefaults_DNSOperator(&c)
+ claims := c.Controllers.DNSZoneReplicator.ZoneClaims
+ if claims.Enabled {
+ t.Error("zone claims are on by default")
+ }
+ if claims.MaxEntries != 256 {
+ t.Errorf("maxEntries defaults to %d, want 256", claims.MaxEntries)
+ }
+ if err := claims.Validate(); err != nil {
+ t.Errorf("the default config is invalid: %v", err)
+ }
+}
+
+func TestZoneClaimsRefuseACapTheSchemaCannotHold(t *testing.T) {
+ for _, n := range []int{0, -1, MaxZoneClaimEntries + 1} {
+ if err := (ZoneClaimsConfig{Enabled: true, MaxEntries: n}).Validate(); err == nil {
+ t.Errorf("maxEntries %d was accepted", n)
+ }
+ }
+ if err := (ZoneClaimsConfig{Enabled: true, MaxEntries: MaxZoneClaimEntries}).Validate(); err != nil {
+ t.Errorf("maxEntries %d was refused: %v", MaxZoneClaimEntries, err)
+ }
+}
+
+func TestZoneClaimsIgnoreTheCapWhileOff(t *testing.T) {
+ if err := (ZoneClaimsConfig{MaxEntries: MaxZoneClaimEntries + 1}).Validate(); err != nil {
+ t.Errorf("a disabled config was refused: %v", err)
+ }
+}
diff --git a/internal/config/zz_generated.deepcopy.go b/internal/config/zz_generated.deepcopy.go
index 3d69882f..83a27c7b 100644
--- a/internal/config/zz_generated.deepcopy.go
+++ b/internal/config/zz_generated.deepcopy.go
@@ -15,6 +15,7 @@ import (
func (in *ControllersConfig) DeepCopyInto(out *ControllersConfig) {
*out = *in
in.DNSRecordSetPowerDNS.DeepCopyInto(&out.DNSRecordSetPowerDNS)
+ out.DNSZoneReplicator = in.DNSZoneReplicator
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ControllersConfig.
@@ -79,6 +80,22 @@ func (in *DNSRecordSetPowerDNSControllerConfig) DeepCopy() *DNSRecordSetPowerDNS
return out
}
+// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
+func (in *DNSZoneReplicatorControllerConfig) DeepCopyInto(out *DNSZoneReplicatorControllerConfig) {
+ *out = *in
+ out.ZoneClaims = in.ZoneClaims
+}
+
+// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DNSZoneReplicatorControllerConfig.
+func (in *DNSZoneReplicatorControllerConfig) DeepCopy() *DNSZoneReplicatorControllerConfig {
+ if in == nil {
+ return nil
+ }
+ out := new(DNSZoneReplicatorControllerConfig)
+ in.DeepCopyInto(out)
+ return out
+}
+
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *DiscoveryConfig) DeepCopyInto(out *DiscoveryConfig) {
*out = *in
@@ -108,3 +125,18 @@ func (in *DownstreamResourceManagementConfig) DeepCopy() *DownstreamResourceMana
in.DeepCopyInto(out)
return out
}
+
+// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
+func (in *ZoneClaimsConfig) DeepCopyInto(out *ZoneClaimsConfig) {
+ *out = *in
+}
+
+// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ZoneClaimsConfig.
+func (in *ZoneClaimsConfig) DeepCopy() *ZoneClaimsConfig {
+ if in == nil {
+ return nil
+ }
+ out := new(ZoneClaimsConfig)
+ in.DeepCopyInto(out)
+ return out
+}
diff --git a/internal/config/zz_generated.defaults.go b/internal/config/zz_generated.defaults.go
index a95f2b24..a922c562 100644
--- a/internal/config/zz_generated.defaults.go
+++ b/internal/config/zz_generated.defaults.go
@@ -36,4 +36,7 @@ func SetObjectDefaults_DNSOperator(in *DNSOperator) {
panic(err)
}
}
+ if in.Controllers.DNSZoneReplicator.ZoneClaims.MaxEntries == 0 {
+ in.Controllers.DNSZoneReplicator.ZoneClaims.MaxEntries = 256
+ }
}
diff --git a/internal/controller/conditions.go b/internal/controller/conditions.go
index 8bd595de..fef39a35 100644
--- a/internal/controller/conditions.go
+++ b/internal/controller/conditions.go
@@ -17,19 +17,22 @@ const (
CondDiscovered = "Discovered"
CondTargetResolved = "TargetResolved"
- ReasonAccepted = "Accepted"
- ReasonPending = "Pending"
- ReasonInvalidDNSRecordSet = "InvalidDNSRecordSet"
- ReasonProgrammed = "Programmed"
- ReasonDiscovered = "Discovered"
- ReasonDNSZoneInUse = "DNSZoneInUse"
- ReasonNotOwner = "NotOwner"
- ReasonPDNSError = "PDNSError"
- ReasonConflict = "Conflict"
- ReasonPendingDomainVerification = "PendingDomainVerification"
- ReasonTargetResolved = "TargetResolved"
- ReasonTargetUnresolved = "TargetUnresolved"
- ReasonTargetLookupFailed = "TargetLookupFailed"
+ ReasonAccepted = "Accepted"
+ ReasonPending = "Pending"
+ ReasonInvalidDNSRecordSet = "InvalidDNSRecordSet"
+ ReasonProgrammed = "Programmed"
+ ReasonDiscovered = "Discovered"
+ ReasonDNSZoneInUse = "DNSZoneInUse"
+ ReasonNotOwner = "NotOwner"
+ ReasonPDNSError = "PDNSError"
+ ReasonConflict = "Conflict"
+ ReasonPendingDomainVerification = "PendingDomainVerification"
+ ReasonInvalidDomain = "InvalidDomain"
+ ReasonClaimSetFull = "ClaimSetFull"
+ ReasonPendingPreviousZoneRemoval = "PendingPreviousZoneRemoval"
+ ReasonTargetResolved = "TargetResolved"
+ ReasonTargetUnresolved = "TargetUnresolved"
+ ReasonTargetLookupFailed = "TargetLookupFailed"
)
const (
diff --git a/internal/controller/dnsrecordset_replicator_controller.go b/internal/controller/dnsrecordset_replicator_controller.go
index 5476526e..0377aafa 100644
--- a/internal/controller/dnsrecordset_replicator_controller.go
+++ b/internal/controller/dnsrecordset_replicator_controller.go
@@ -31,6 +31,7 @@ import (
type DNSRecordSetReplicator struct {
mgr mcmanager.Manager
DownstreamClient client.Client
+ ZoneClaims bool
}
const rsFinalizer = "dns.networking.miloapis.com/finalize-dnsrecordset"
@@ -138,6 +139,11 @@ func (r *DNSRecordSetReplicator) Reconcile(ctx context.Context, req mcreconcile.
return ctrl.Result{}, nil
}
+ if r.ZoneClaims && zoneRefused(&zone) {
+ lg.V(1).Info("referenced DNSZone is refused; skipping downstream programming", "dnsZone", zone.Name)
+ return ctrl.Result{RequeueAfter: zoneClaimRetryInterval}, nil
+ }
+
// Ensure OwnerReference to upstream DNSZone (same ns).
// We return early after setting OwnerReference to ensure we reconcile with
// the fresh object that has the updated owner metadata.
diff --git a/internal/controller/dnszone_replicator_controller.go b/internal/controller/dnszone_replicator_controller.go
index 929f4bc7..43e6aaa1 100644
--- a/internal/controller/dnszone_replicator_controller.go
+++ b/internal/controller/dnszone_replicator_controller.go
@@ -42,6 +42,9 @@ type DNSZoneReplicator struct {
DownstreamClient client.Client
// AccountingNamespace is the downstream namespace used for DNSZone ownership accounting.
AccountingNamespace string
+ // ZoneClaims admits zones through claim sets when set. Nil admits by
+ // exact name only.
+ ZoneClaims *ZoneClaims
}
const dnsZoneFinalizer = "dns.networking.miloapis.com/finalize-dnszone"
@@ -53,11 +56,18 @@ const dnsZoneFinalizer = "dns.networking.miloapis.com/finalize-dnszone"
// +kubebuilder:rbac:groups=dns.networking.miloapis.com,resources=dnsrecordsets/status,verbs=get;update;patch
// +kubebuilder:rbac:groups=networking.datumapis.com,resources=domains,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=networking.datumapis.com,resources=domains/status,verbs=get;list;watch
+// +kubebuilder:rbac:groups=dns.networking.miloapis.com,resources=zoneclaimsets,verbs=get;create;update
// +kubebuilder:rbac:groups=core,resources=namespaces,verbs=get;list;watch;create;update;patch
// +kubebuilder:rbac:groups=core,resources=configmaps,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=events.k8s.io,resources=events,verbs=create;patch
-func (r *DNSZoneReplicator) Reconcile(ctx context.Context, req mcreconcile.Request) (ctrl.Result, error) {
+func (r *DNSZoneReplicator) Reconcile(ctx context.Context, req mcreconcile.Request) (result ctrl.Result, err error) {
+ admitted := false
+ defer func() {
+ if admitted && err == nil && result.IsZero() {
+ result.RequeueAfter = zoneClaimRetryInterval
+ }
+ }()
lg := log.FromContext(ctx).WithValues("cluster", req.ClusterName, "namespace", req.Namespace, "name", req.Name)
ctx = log.IntoContext(ctx, lg)
lg.V(1).Info("reconcile start")
@@ -139,6 +149,12 @@ func (r *DNSZoneReplicator) Reconcile(ctx context.Context, req mcreconcile.Reque
// Cleanup zone accounting configmap once downstream is confirmed gone
lg.Info("downstream DNSZone confirmed deleted", "namespace", md.Namespace, "name", md.Name)
+ if r.ZoneClaims != nil {
+ if err := r.ZoneClaims.Release(ctx, zoneClaimFor(string(req.ClusterName), &upstream)); err != nil {
+ lg.Error(err, "failed to release zone claim; will retry")
+ return ctrl.Result{}, err
+ }
+ }
owner := fmt.Sprintf("%s/%s/%s", req.ClusterName, upstream.Namespace, upstream.Name)
if cerr := r.cleanupZoneAccounting(ctx, &upstream, owner); cerr != nil && !apierrors.IsNotFound(cerr) {
lg.Error(cerr, "failed to cleanup accounting configmap; will retry")
@@ -201,6 +217,17 @@ func (r *DNSZoneReplicator) Reconcile(ctx context.Context, req mcreconcile.Reque
return ctrl.Result{}, err
}
+ // Claims decide before the exact-name record, so a refused zone never
+ // takes the record from a project that holds the name.
+ if r.ZoneClaims != nil {
+ res, ok, cerr := r.admitZoneClaim(ctx, upstreamCl.GetClient(), strategy, eventClient, string(req.ClusterName), &upstream)
+ if cerr != nil || !ok {
+ return res, cerr
+ }
+ // A release or a dropped claim can demote this zone without touching it.
+ admitted = true
+ }
+
// 3) Ensure downstream shadow (only after class presence check)
owner := fmt.Sprintf("%s/%s/%s", req.ClusterName, upstream.Namespace, upstream.Name)
if owned, aerr := r.ensureZoneAccounting(ctx, &upstream, owner); aerr != nil {
@@ -245,6 +272,9 @@ func (r *DNSZoneReplicator) Reconcile(ctx context.Context, req mcreconcile.Reque
upstream.Name,
)
}
+ if r.ZoneClaims != nil {
+ return ctrl.Result{RequeueAfter: zoneClaimRetryInterval}, nil
+ }
return ctrl.Result{}, nil
}
// Ensure a matching Domain exists in the upstream cluster for this zone's domain name.
@@ -283,6 +313,17 @@ func (r *DNSZoneReplicator) Reconcile(ctx context.Context, req mcreconcile.Reque
}
return ctrl.Result{}, err
}
+ if r.ZoneClaims != nil {
+ // Admission and shadow creation aren't atomic: a demotion or an
+ // overlapping zone's handoff between them withdraws the shadow.
+ res, ok, cerr := r.admitZoneClaim(ctx, upstreamCl.GetClient(), strategy, eventClient, string(req.ClusterName), &upstream)
+ if cerr != nil || !ok {
+ if cerr == nil {
+ _, cerr = r.deleteShadowZone(ctx, strategy, &upstream)
+ }
+ return res, cerr
+ }
+ }
// 4) First, refresh upstream status from downstream (populate nameservers)
if err := r.updateStatus(ctx, upstreamCl.GetClient(), strategy, &upstream); err != nil {
@@ -943,6 +984,12 @@ func markPendingDomainVerification(upstream *dnsv1alpha1.DNSZone, zoneClass dnsv
func (r *DNSZoneReplicator) SetupWithManager(mgr mcmanager.Manager, downstreamCl cluster.Cluster) error {
r.mgr = mgr
+ if r.ZoneClaims != nil && r.ZoneClaims.ZoneGone == nil {
+ r.ZoneClaims.ZoneGone = r.zoneGone
+ }
+ if r.ZoneClaims != nil && r.ZoneClaims.ZoneServed == nil {
+ r.ZoneClaims.ZoneServed = r.zoneServed
+ }
// Register field indexes used by this controller when listing DNSRecordSets
if err := mgr.GetFieldIndexer().IndexField(context.Background(),
diff --git a/internal/controller/zoneclaim_admission.go b/internal/controller/zoneclaim_admission.go
new file mode 100644
index 00000000..ac87fe93
--- /dev/null
+++ b/internal/controller/zoneclaim_admission.go
@@ -0,0 +1,424 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+
+package controller
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "slices"
+ "time"
+
+ corev1 "k8s.io/api/core/v1"
+ apiequality "k8s.io/apimachinery/pkg/api/equality"
+ apierrors "k8s.io/apimachinery/pkg/api/errors"
+ apimeta "k8s.io/apimachinery/pkg/api/meta"
+ metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+ "k8s.io/client-go/util/retry"
+ ctrl "sigs.k8s.io/controller-runtime"
+ "sigs.k8s.io/controller-runtime/pkg/client"
+ "sigs.k8s.io/controller-runtime/pkg/log"
+ "sigs.k8s.io/multicluster-runtime/pkg/multicluster"
+
+ dnsv1alpha1 "go.miloapis.com/dns/api/v1alpha1"
+ downstreamclient "go.miloapis.com/dns/internal/downstreamclient"
+)
+
+const (
+ zoneClaimRetryInterval = time.Minute
+ zoneWithdrawalRetryInterval = 10 * time.Second
+)
+
+var (
+ errInvalidDomain = errors.New("zone name has no registered domain")
+ errClaimSetFull = errors.New("claim set is full")
+ errStillServed = errors.New("an overlapping zone of another project is still served")
+)
+
+type ZoneClaims struct {
+ // Reader must be uncached: every update is guarded by the resourceVersion
+ // it read.
+ Reader client.Reader
+ Writer client.Writer
+ Namespace string
+ MaxEntries int
+
+ // ZoneGone reports whether the zone bound to an entry no longer exists.
+ // It returns false unless the zone is definitely gone.
+ ZoneGone func(ctx context.Context, zone dnsv1alpha1.ZoneClaimZone) (bool, error)
+
+ // ZoneServed reports whether the zone bound to an entry still has a shadow.
+ // It returns true unless the shadow is definitely gone.
+ ZoneServed func(ctx context.Context, zone dnsv1alpha1.ZoneClaimZone) (bool, error)
+
+ now func() metav1.Time
+}
+
+func (z *ZoneClaims) timeNow() metav1.Time {
+ if z.now != nil {
+ return z.now()
+ }
+ return metav1.Now()
+}
+
+func zoneClaimFor(cluster string, zone *dnsv1alpha1.DNSZone) dnsv1alpha1.ZoneClaimEntry {
+ cluster = zoneOwnerKey(cluster)
+ return dnsv1alpha1.ZoneClaimEntry{
+ Name: normalizeDomainName(zone.Spec.DomainName),
+ Project: &dnsv1alpha1.ZoneClaimProject{Name: cluster},
+ Zone: &dnsv1alpha1.ZoneClaimZone{
+ Cluster: cluster,
+ Namespace: zone.Namespace,
+ Name: zone.Name,
+ UID: string(zone.UID),
+ },
+ }
+}
+
+func boundTo(e dnsv1alpha1.ZoneClaimEntry, zone *dnsv1alpha1.ZoneClaimZone) bool {
+ if e.Zone == nil {
+ return false
+ }
+ if e.Zone.UID != "" {
+ return e.Zone.UID == zone.UID
+ }
+ return e.Zone.Cluster == zone.Cluster && e.Zone.Namespace == zone.Namespace && e.Zone.Name == zone.Name
+}
+
+func (z *ZoneClaims) Admit(ctx context.Context, claim dnsv1alpha1.ZoneClaimEntry) (entry dnsv1alpha1.ZoneClaimEntry, blocker *dnsv1alpha1.ZoneClaimEntry, err error) {
+ setName, err := registeredDomain(claim.Name)
+ if err != nil {
+ return entry, nil, fmt.Errorf("%w: %w", errInvalidDomain, err)
+ }
+ var final []dnsv1alpha1.ZoneClaimEntry
+ err = retry.RetryOnConflict(retry.DefaultRetry, func() error {
+ set, exists, err := z.get(ctx, setName)
+ if err != nil {
+ return err
+ }
+ now := z.timeNow()
+ read := set.Spec.Entries
+ entries := read
+ i := slices.IndexFunc(entries, func(e dnsv1alpha1.ZoneClaimEntry) bool { return boundTo(e, claim.Zone) })
+ if i < 0 {
+ if len(entries) >= z.MaxEntries {
+ return errClaimSetFull
+ }
+ claim.Since = now
+ entries = append(slices.Clone(entries), claim)
+ i = len(entries) - 1
+ } else if entries[i].Zone.UID == "" {
+ entries = slices.Clone(entries)
+ bound := *entries[i].Zone
+ bound.UID = claim.Zone.UID
+ entries[i].Zone = &bound
+ }
+ for {
+ entries = evaluateZoneClaims(entries, now)
+ b := blockerOf(entries, i)
+ if b < 0 || entries[b].Zone == nil || entries[b].OperatorSeeded {
+ break
+ }
+ gone, err := z.ZoneGone(ctx, *entries[b].Zone)
+ if err != nil {
+ return err
+ }
+ if !gone {
+ break
+ }
+ if z.ZoneServed != nil {
+ served, err := z.ZoneServed(ctx, *entries[b].Zone)
+ if err != nil {
+ return err
+ }
+ if served {
+ log.FromContext(ctx).V(1).Info("keeping the claim of a deleted zone whose shadow remains",
+ "claimSet", setName, "name", entries[b].Name, "zone", entries[b].Zone)
+ break
+ }
+ }
+ log.FromContext(ctx).Info("dropping the claim of a zone that no longer exists",
+ "claimSet", setName, "name", entries[b].Name, "zone", entries[b].Zone)
+ entries = slices.Delete(slices.Clone(entries), b, b+1)
+ if b < i {
+ i--
+ }
+ }
+ if !exists || !apiequality.Semantic.DeepEqual(read, entries) {
+ set.Spec.Entries = entries
+ if err := z.write(ctx, set, exists); err != nil {
+ return err
+ }
+ }
+ final = entries
+ entry = entries[i]
+ blocker = nil
+ if b := blockerOf(entries, i); b >= 0 {
+ blocker = &entries[b]
+ }
+ return nil
+ })
+ if err != nil || entry.State != dnsv1alpha1.ZoneClaimActive {
+ return entry, blocker, err
+ }
+ blocker, err = z.stillServed(ctx, entry, final)
+ if err == nil && blocker != nil {
+ err = errStillServed
+ }
+ return entry, blocker, err
+}
+
+// stillServed returns a zone of another project that overlaps entry, lost its
+// claim, and still has a shadow. Entry waits for it so two projects never serve
+// overlapping names at once.
+func (z *ZoneClaims) stillServed(ctx context.Context, entry dnsv1alpha1.ZoneClaimEntry, entries []dnsv1alpha1.ZoneClaimEntry) (*dnsv1alpha1.ZoneClaimEntry, error) {
+ if z.ZoneServed == nil {
+ return nil, nil
+ }
+ for _, e := range entries {
+ if e.State == dnsv1alpha1.ZoneClaimActive || e.Zone == nil || e.OperatorSeeded || sameClaimProject(e, entry) {
+ continue
+ }
+ if e.Name != entry.Name && !domainCovers(e.Name, entry.Name) && !domainCovers(entry.Name, e.Name) {
+ continue
+ }
+ served, err := z.ZoneServed(ctx, *e.Zone)
+ if err != nil {
+ return nil, err
+ }
+ if served {
+ return &e, nil
+ }
+ }
+ return nil, nil
+}
+
+func (z *ZoneClaims) Release(ctx context.Context, claim dnsv1alpha1.ZoneClaimEntry) error {
+ setName, err := registeredDomain(claim.Name)
+ if err != nil {
+ return nil
+ }
+ return retry.RetryOnConflict(retry.DefaultRetry, func() error {
+ set, exists, err := z.get(ctx, setName)
+ if err != nil || !exists {
+ return err
+ }
+ i := slices.IndexFunc(set.Spec.Entries, func(e dnsv1alpha1.ZoneClaimEntry) bool { return boundTo(e, claim.Zone) })
+ if i < 0 {
+ return nil
+ }
+ set.Spec.Entries = evaluateZoneClaims(slices.Delete(slices.Clone(set.Spec.Entries), i, i+1), z.timeNow())
+ return z.write(ctx, set, true)
+ })
+}
+
+func (z *ZoneClaims) get(ctx context.Context, name string) (*dnsv1alpha1.ZoneClaimSet, bool, error) {
+ set := &dnsv1alpha1.ZoneClaimSet{}
+ err := z.Reader.Get(ctx, client.ObjectKey{Namespace: z.Namespace, Name: name}, set)
+ if apierrors.IsNotFound(err) {
+ set = &dnsv1alpha1.ZoneClaimSet{}
+ set.Namespace = z.Namespace
+ set.Name = name
+ return set, false, nil
+ }
+ return set, err == nil, err
+}
+
+// write creates or updates the set at the resourceVersion it was read with.
+// A create that loses a race reports a conflict so the caller reads again.
+func (z *ZoneClaims) write(ctx context.Context, set *dnsv1alpha1.ZoneClaimSet, exists bool) error {
+ if exists {
+ return z.Writer.Update(ctx, set)
+ }
+ err := z.Writer.Create(ctx, set)
+ if apierrors.IsAlreadyExists(err) {
+ return apierrors.NewConflict(dnsv1alpha1.GroupVersion.WithResource("zoneclaimsets").GroupResource(), set.Name, err)
+ }
+ return err
+}
+
+// blockerOf returns the index of the earlier entry that left entries[i]
+// Contested, or -1.
+func blockerOf(entries []dnsv1alpha1.ZoneClaimEntry, i int) int {
+ e := entries[i]
+ if e.State != dnsv1alpha1.ZoneClaimContested {
+ return -1
+ }
+ for j := range i {
+ b := entries[j]
+ if b.State == dnsv1alpha1.ZoneClaimContested {
+ continue
+ }
+ switch {
+ case e.Reason == dnsv1alpha1.ZoneClaimDuplicateZoneInProject:
+ if b.State == dnsv1alpha1.ZoneClaimActive && b.Name == e.Name && sameClaimProject(b, e) {
+ return j
+ }
+ case b.Name == e.BlockedBy && !sameClaimProject(b, e) && (!b.PreexistingOverlap || !e.PreexistingOverlap):
+ return j
+ }
+ }
+ return -1
+}
+
+// zoneClaimMessage explains a Contested entry without naming the other
+// project, so a refusal doesn't reveal who uses a domain.
+func zoneClaimMessage(e dnsv1alpha1.ZoneClaimEntry, blocker *dnsv1alpha1.ZoneClaimEntry) string {
+ switch e.Reason {
+ case dnsv1alpha1.ZoneClaimClaimedByAnotherProject:
+ return fmt.Sprintf("%s is claimed by another project.", e.BlockedBy)
+ case dnsv1alpha1.ZoneClaimParentClaimedByAnotherProject:
+ return fmt.Sprintf("%s, a parent of %s, is claimed by another project.", e.BlockedBy, e.Name)
+ case dnsv1alpha1.ZoneClaimChildClaimedByAnotherProject:
+ return fmt.Sprintf("%s, under %s, is claimed by another project.", e.BlockedBy, e.Name)
+ case dnsv1alpha1.ZoneClaimDuplicateZoneInProject:
+ if blocker != nil && blocker.Zone != nil {
+ return fmt.Sprintf("Zone %s/%s in this project already serves %s.", blocker.Zone.Namespace, blocker.Zone.Name, e.Name)
+ }
+ return fmt.Sprintf("Another zone in this project already serves %s.", e.Name)
+ }
+ return fmt.Sprintf("%s is claimed by another project.", e.Name)
+}
+
+// admitZoneClaim reports admitted=false when the zone must not be served, after
+// recording why on the zone. The refusal is recorded before the shadow is
+// deleted so the record set replicator stops recreating the shadow's record
+// sets.
+func (r *DNSZoneReplicator) admitZoneClaim(ctx context.Context, c client.Client, strategy downstreamclient.ResourceStrategy, events EventClient, cluster string, upstream *dnsv1alpha1.DNSZone) (ctrl.Result, bool, error) {
+ entry, blocker, err := r.ZoneClaims.Admit(ctx, zoneClaimFor(cluster, upstream))
+ switch {
+ case errors.Is(err, errInvalidDomain):
+ msg := fmt.Sprintf("%s is a public suffix, so no zone can claim it.", upstream.Spec.DomainName)
+ return ctrl.Result{}, false, r.refuseZone(ctx, c, events, upstream, ReasonInvalidDomain, msg)
+ case errors.Is(err, errClaimSetFull):
+ msg := fmt.Sprintf("The claim set for %s holds its maximum number of zones.", upstream.Spec.DomainName)
+ return ctrl.Result{RequeueAfter: zoneClaimRetryInterval}, false, r.refuseZone(ctx, c, events, upstream, ReasonClaimSetFull, msg)
+ case errors.Is(err, errStillServed):
+ msg := fmt.Sprintf("Waiting for another project's zone for %s to stop serving.", blocker.Name)
+ _, err := r.patchNotReady(ctx, c, upstream, ReasonPendingPreviousZoneRemoval, msg)
+ return ctrl.Result{RequeueAfter: zoneWithdrawalRetryInterval}, false, err
+ case err != nil:
+ return ctrl.Result{}, false, err
+ case entry.State != dnsv1alpha1.ZoneClaimActive:
+ if err := r.refuseZone(ctx, c, events, upstream, ReasonDNSZoneInUse, zoneClaimMessage(entry, blocker)); err != nil {
+ return ctrl.Result{}, false, err
+ }
+ res := ctrl.Result{RequeueAfter: zoneClaimRetryInterval}
+ gone, err := r.deleteShadowZone(ctx, strategy, upstream)
+ if err != nil || !gone {
+ return res, false, err
+ }
+ owner := fmt.Sprintf("%s/%s/%s", cluster, upstream.Namespace, upstream.Name)
+ return res, false, r.cleanupZoneAccounting(ctx, upstream, owner)
+ }
+ return ctrl.Result{}, true, nil
+}
+
+func (r *DNSZoneReplicator) refuseZone(ctx context.Context, c client.Client, events EventClient, upstream *dnsv1alpha1.DNSZone, reason, msg string) error {
+ changed, err := r.patchNotReady(ctx, c, upstream, reason, msg)
+ if err != nil || !changed {
+ return err
+ }
+ emitZoneEvent(ctx, events,
+ ZoneEventData{Zone: upstream, FailReason: msg},
+ corev1.EventTypeWarning,
+ EventReasonZoneProgrammingFailed,
+ ActivityTypeZoneProgrammingFailed,
+ "DNSZone %q programming failed: %s",
+ upstream.Name, msg,
+ )
+ return nil
+}
+
+func (r *DNSZoneReplicator) patchNotReady(ctx context.Context, c client.Client, upstream *dnsv1alpha1.DNSZone, reason, msg string) (bool, error) {
+ base := upstream.DeepCopy()
+ changed := false
+ for _, t := range []string{CondAccepted, CondProgrammed} {
+ if apimeta.SetStatusCondition(&upstream.Status.Conditions, metav1.Condition{
+ Type: t,
+ Status: metav1.ConditionFalse,
+ Reason: reason,
+ Message: msg,
+ ObservedGeneration: upstream.Generation,
+ }) {
+ changed = true
+ }
+ }
+ if !changed {
+ return false, nil
+ }
+ return true, c.Status().Patch(ctx, upstream, client.MergeFrom(base))
+}
+
+// deleteShadowZone reports gone=true once an uncached read confirms the shadow
+// no longer exists.
+func (r *DNSZoneReplicator) deleteShadowZone(ctx context.Context, strategy downstreamclient.ResourceStrategy, upstream *dnsv1alpha1.DNSZone) (bool, error) {
+ md, err := strategy.ObjectMetaFromUpstreamObject(ctx, upstream)
+ if err != nil {
+ return false, err
+ }
+ shadow := &dnsv1alpha1.DNSZone{}
+ shadow.Namespace = md.Namespace
+ shadow.Name = md.Name
+ if err := r.DownstreamClient.Delete(ctx, shadow); err == nil {
+ log.FromContext(ctx).Info("deleted the shadow zone of a contested zone", "namespace", md.Namespace, "name", md.Name)
+ } else if !apierrors.IsNotFound(err) {
+ return false, err
+ }
+ err = r.ZoneClaims.Reader.Get(ctx, client.ObjectKeyFromObject(shadow), &dnsv1alpha1.DNSZone{})
+ if apierrors.IsNotFound(err) {
+ return true, nil
+ }
+ return false, err
+}
+
+func (r *DNSZoneReplicator) zoneGone(ctx context.Context, zone dnsv1alpha1.ZoneClaimZone) (bool, error) {
+ cl, err := r.mgr.GetCluster(ctx, multicluster.ClusterName(zone.Cluster))
+ if err != nil {
+ log.FromContext(ctx).V(1).Info("cannot reach the cluster of a blocking zone; keeping its claim", "zone", zone, "error", err.Error())
+ return false, nil
+ }
+ var current dnsv1alpha1.DNSZone
+ err = cl.GetAPIReader().Get(ctx, client.ObjectKey{Namespace: zone.Namespace, Name: zone.Name}, ¤t)
+ if apierrors.IsNotFound(err) {
+ return true, nil
+ }
+ if err != nil {
+ log.FromContext(ctx).V(1).Info("cannot read a blocking zone; keeping its claim", "zone", zone, "error", err.Error())
+ return false, nil
+ }
+ return zone.UID != "" && string(current.UID) != zone.UID, nil
+}
+
+func (r *DNSZoneReplicator) zoneServed(ctx context.Context, zone dnsv1alpha1.ZoneClaimZone) (bool, error) {
+ cl, err := r.mgr.GetCluster(ctx, multicluster.ClusterName(zone.Cluster))
+ if err != nil {
+ log.FromContext(ctx).V(1).Info("cannot reach the cluster of an overlapping zone; assuming it is still served", "zone", zone, "error", err.Error())
+ return true, nil
+ }
+ strategy := downstreamclient.NewMappedNamespaceResourceStrategy(multicluster.ClusterName(zone.Cluster), cl.GetClient(), r.DownstreamClient)
+ md, err := strategy.ObjectMetaFromUpstreamObject(ctx, &metav1.ObjectMeta{Namespace: zone.Namespace, Name: zone.Name})
+ if apierrors.IsNotFound(err) {
+ return false, nil
+ }
+ if err != nil {
+ log.FromContext(ctx).V(1).Info("cannot find the shadow of an overlapping zone; assuming it is still served", "zone", zone, "error", err.Error())
+ return true, nil
+ }
+ err = r.ZoneClaims.Reader.Get(ctx, client.ObjectKey{Namespace: md.Namespace, Name: md.Name}, &dnsv1alpha1.DNSZone{})
+ if apierrors.IsNotFound(err) {
+ return false, nil
+ }
+ if err != nil {
+ log.FromContext(ctx).V(1).Info("cannot read the shadow of an overlapping zone; assuming it is still served", "zone", zone, "error", err.Error())
+ }
+ return true, nil
+}
+
+func zoneRefused(zone *dnsv1alpha1.DNSZone) bool {
+ accepted := apimeta.FindStatusCondition(zone.Status.Conditions, CondAccepted)
+ if accepted == nil || accepted.Status != metav1.ConditionFalse {
+ return false
+ }
+ return accepted.Reason == ReasonDNSZoneInUse
+}
diff --git a/internal/controller/zoneclaim_admission_test.go b/internal/controller/zoneclaim_admission_test.go
new file mode 100644
index 00000000..0ccf9625
--- /dev/null
+++ b/internal/controller/zoneclaim_admission_test.go
@@ -0,0 +1,308 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+
+package controller
+
+import (
+ "context"
+ "errors"
+ "os"
+ "path/filepath"
+ "sync"
+ "testing"
+
+ corev1 "k8s.io/api/core/v1"
+ metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+ "k8s.io/apimachinery/pkg/runtime"
+ "k8s.io/apimachinery/pkg/types"
+ "sigs.k8s.io/controller-runtime/pkg/client"
+ "sigs.k8s.io/controller-runtime/pkg/client/fake"
+ "sigs.k8s.io/controller-runtime/pkg/envtest"
+
+ dnsv1alpha1 "go.miloapis.com/dns/api/v1alpha1"
+)
+
+const claimTestNS = "accounting"
+
+func claimTestZone(cluster, name, domain string) dnsv1alpha1.ZoneClaimEntry {
+ z := &dnsv1alpha1.DNSZone{}
+ z.Namespace = "default"
+ z.Name = name
+ z.UID = types.UID(cluster + "-" + name)
+ z.Spec.DomainName = domain
+ return zoneClaimFor(cluster, z)
+}
+
+func newClaimTestClaims(t *testing.T, gone map[string]bool, objs ...client.Object) (*ZoneClaims, client.Client) {
+ t.Helper()
+ scheme := runtime.NewScheme()
+ if err := dnsv1alpha1.AddToScheme(scheme); err != nil {
+ t.Fatal(err)
+ }
+ cl := fake.NewClientBuilder().WithScheme(scheme).WithObjects(objs...).Build()
+ return &ZoneClaims{
+ Reader: cl,
+ Writer: cl,
+ Namespace: claimTestNS,
+ MaxEntries: 256,
+ ZoneGone: func(_ context.Context, z dnsv1alpha1.ZoneClaimZone) (bool, error) {
+ return gone[z.UID], nil
+ },
+ now: func() metav1.Time { return claimNow },
+ }, cl
+}
+
+func claimSetEntries(t *testing.T, cl client.Client, name string) []dnsv1alpha1.ZoneClaimEntry {
+ t.Helper()
+ var set dnsv1alpha1.ZoneClaimSet
+ if err := cl.Get(context.Background(), client.ObjectKey{Namespace: claimTestNS, Name: name}, &set); err != nil {
+ t.Fatal(err)
+ }
+ return set.Spec.Entries
+}
+
+func TestAdmitRefusesAChildOfAnotherProjectsZone(t *testing.T) {
+ z, cl := newClaimTestClaims(t, nil)
+ ctx := context.Background()
+ parent := claimTestZone("p1", "parent", "example.com")
+ child := claimTestZone("p2", "child", "Shop.Example.com.")
+
+ got, _, err := z.Admit(ctx, parent)
+ if err != nil || got.State != dnsv1alpha1.ZoneClaimActive {
+ t.Fatalf("parent = %s, %v; want Active", got.State, err)
+ }
+ got, blocker, err := z.Admit(ctx, child)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got.State != dnsv1alpha1.ZoneClaimContested || got.Reason != dnsv1alpha1.ZoneClaimParentClaimedByAnotherProject || got.BlockedBy != "example.com" {
+ t.Fatalf("child = %+v, want Contested by example.com", got)
+ }
+ if blocker == nil || blocker.Zone.UID != parent.Zone.UID {
+ t.Fatalf("blocker = %+v, want the parent's entry", blocker)
+ }
+ if want := "example.com, a parent of shop.example.com, is claimed by another project."; zoneClaimMessage(got, blocker) != want {
+ t.Errorf("message = %q, want %q", zoneClaimMessage(got, blocker), want)
+ }
+
+ if again, _, err := z.Admit(ctx, child); err != nil || again.State != dnsv1alpha1.ZoneClaimContested {
+ t.Fatalf("re-admitting the child = %s, %v", again.State, err)
+ }
+ if n := len(claimSetEntries(t, cl, "example.com")); n != 2 {
+ t.Fatalf("set has %d entries after re-admission, want 2", n)
+ }
+}
+
+func TestAdmitLetsOneProjectServeSeveralLevels(t *testing.T) {
+ z, _ := newClaimTestClaims(t, nil)
+ for _, c := range []dnsv1alpha1.ZoneClaimEntry{
+ claimTestZone("p1", "apex", "example.com"),
+ claimTestZone("p1", "shop", "shop.example.com"),
+ } {
+ if got, _, err := z.Admit(context.Background(), c); err != nil || got.State != dnsv1alpha1.ZoneClaimActive {
+ t.Fatalf("%s = %s, %v; want Active", c.Name, got.State, err)
+ }
+ }
+}
+
+func TestAdmitDropsTheClaimOfAZoneThatNoLongerExists(t *testing.T) {
+ stale := claimTestZone("p1", "parent", "example.com")
+ z, cl := newClaimTestClaims(t, map[string]bool{stale.Zone.UID: true})
+ ctx := context.Background()
+ if _, _, err := z.Admit(ctx, stale); err != nil {
+ t.Fatal(err)
+ }
+ got, _, err := z.Admit(ctx, claimTestZone("p2", "child", "shop.example.com"))
+ if err != nil || got.State != dnsv1alpha1.ZoneClaimActive {
+ t.Fatalf("child = %+v, %v; want Active once the stale parent is dropped", got, err)
+ }
+ if entries := claimSetEntries(t, cl, "example.com"); len(entries) != 1 || entries[0].Name != "shop.example.com" {
+ t.Fatalf("entries = %+v, want only the child", entries)
+ }
+}
+
+func TestAdmitKeepsTheClaimOfAZoneThatStillExists(t *testing.T) {
+ z, cl := newClaimTestClaims(t, map[string]bool{})
+ ctx := context.Background()
+ if _, _, err := z.Admit(ctx, claimTestZone("p1", "parent", "example.com")); err != nil {
+ t.Fatal(err)
+ }
+ if got, _, _ := z.Admit(ctx, claimTestZone("p2", "child", "shop.example.com")); got.State != dnsv1alpha1.ZoneClaimContested {
+ t.Fatalf("child = %s, want Contested", got.State)
+ }
+ if n := len(claimSetEntries(t, cl, "example.com")); n != 2 {
+ t.Fatalf("set has %d entries, want 2", n)
+ }
+}
+
+func TestAdmitBindsAnImportedEntryAndRecordsItsUID(t *testing.T) {
+ zone := claimTestZone("p1", "apex", "example.com")
+ imported := zone
+ importedZone := *zone.Zone
+ importedZone.UID = ""
+ imported.Zone = &importedZone
+ imported.State = dnsv1alpha1.ZoneClaimActive
+ imported.Since = claimArrived
+ set := &dnsv1alpha1.ZoneClaimSet{}
+ set.Namespace = claimTestNS
+ set.Name = "example.com"
+ set.Spec.Entries = []dnsv1alpha1.ZoneClaimEntry{imported}
+ z, cl := newClaimTestClaims(t, nil, set)
+
+ if got, _, err := z.Admit(context.Background(), zone); err != nil || got.State != dnsv1alpha1.ZoneClaimActive {
+ t.Fatalf("admit = %s, %v; want Active", got.State, err)
+ }
+ entries := claimSetEntries(t, cl, "example.com")
+ if len(entries) != 1 || entries[0].Zone.UID != zone.Zone.UID {
+ t.Fatalf("entries = %+v, want the imported entry bound to UID %s", entries, zone.Zone.UID)
+ }
+}
+
+func TestAdmitRefusesAPublicSuffix(t *testing.T) {
+ z, _ := newClaimTestClaims(t, nil)
+ if _, _, err := z.Admit(context.Background(), claimTestZone("p1", "suffix", "co.uk")); !errors.Is(err, errInvalidDomain) {
+ t.Fatalf("err = %v, want errInvalidDomain", err)
+ }
+}
+
+func TestAdmitRefusesAnEntryPastTheCap(t *testing.T) {
+ z, cl := newClaimTestClaims(t, nil)
+ z.MaxEntries = 1
+ ctx := context.Background()
+ if _, _, err := z.Admit(ctx, claimTestZone("p1", "apex", "example.com")); err != nil {
+ t.Fatal(err)
+ }
+ if _, _, err := z.Admit(ctx, claimTestZone("p2", "shop", "shop.example.com")); !errors.Is(err, errClaimSetFull) {
+ t.Fatalf("err = %v, want errClaimSetFull", err)
+ }
+ if _, _, err := z.Admit(ctx, claimTestZone("p1", "apex", "example.com")); err != nil {
+ t.Fatalf("re-admitting a recorded zone at the cap: %v", err)
+ }
+ if n := len(claimSetEntries(t, cl, "example.com")); n != 1 {
+ t.Fatalf("set has %d entries, want 1", n)
+ }
+}
+
+func TestReleaseAdmitsTheNextWaitingZone(t *testing.T) {
+ z, cl := newClaimTestClaims(t, nil)
+ ctx := context.Background()
+ parent := claimTestZone("p1", "parent", "example.com")
+ child := claimTestZone("p2", "child", "shop.example.com")
+ for _, c := range []dnsv1alpha1.ZoneClaimEntry{parent, child} {
+ if _, _, err := z.Admit(ctx, c); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := z.Release(ctx, parent); err != nil {
+ t.Fatal(err)
+ }
+ entries := claimSetEntries(t, cl, "example.com")
+ if len(entries) != 1 || entries[0].Name != "shop.example.com" || entries[0].State != dnsv1alpha1.ZoneClaimActive {
+ t.Fatalf("entries = %+v, want the child Active alone", entries)
+ }
+ if err := z.Release(ctx, claimTestZone("p3", "absent", "other.example.org")); err != nil {
+ t.Fatalf("releasing a zone with no claim set: %v", err)
+ }
+}
+
+func TestZoneClaimMessages(t *testing.T) {
+ contested := func(reason dnsv1alpha1.ZoneClaimReason, blockedBy string) dnsv1alpha1.ZoneClaimEntry {
+ return dnsv1alpha1.ZoneClaimEntry{Name: "shop.example.com", State: dnsv1alpha1.ZoneClaimContested, Reason: reason, BlockedBy: blockedBy}
+ }
+ duplicate := claimTestZone("p1", "first", "shop.example.com")
+ for _, tc := range []struct {
+ entry dnsv1alpha1.ZoneClaimEntry
+ blocker *dnsv1alpha1.ZoneClaimEntry
+ want string
+ }{
+ {contested(dnsv1alpha1.ZoneClaimClaimedByAnotherProject, "shop.example.com"), nil, "shop.example.com is claimed by another project."},
+ {contested(dnsv1alpha1.ZoneClaimParentClaimedByAnotherProject, "example.com"), nil, "example.com, a parent of shop.example.com, is claimed by another project."},
+ {contested(dnsv1alpha1.ZoneClaimChildClaimedByAnotherProject, "a.shop.example.com"), nil, "a.shop.example.com, under shop.example.com, is claimed by another project."},
+ {contested(dnsv1alpha1.ZoneClaimDuplicateZoneInProject, ""), &duplicate, "Zone default/first in this project already serves shop.example.com."},
+ } {
+ if got := zoneClaimMessage(tc.entry, tc.blocker); got != tc.want {
+ t.Errorf("%s: got %q, want %q", tc.entry.Reason, got, tc.want)
+ }
+ }
+}
+
+// TestConcurrentAdmissionAtAPIServer admits a parent and a child from two
+// projects at the same moment, many times, against a real API server.
+func TestConcurrentAdmissionAtAPIServer(t *testing.T) {
+ assets := os.Getenv("KUBEBUILDER_ASSETS")
+ if assets == "" {
+ t.Skip("set KUBEBUILDER_ASSETS to admit zones concurrently against the API server")
+ }
+ environment := &envtest.Environment{
+ BinaryAssetsDirectory: assets,
+ CRDDirectoryPaths: []string{filepath.Join("..", "..", "config", "crd-authoritative")},
+ ErrorIfCRDPathMissing: true,
+ }
+ cfg, err := environment.Start()
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() {
+ if err := environment.Stop(); err != nil {
+ t.Error(err)
+ }
+ })
+ scheme := runtime.NewScheme()
+ if err := dnsv1alpha1.AddToScheme(scheme); err != nil {
+ t.Fatal(err)
+ }
+ if err := corev1.AddToScheme(scheme); err != nil {
+ t.Fatal(err)
+ }
+ cl, err := client.New(cfg, client.Options{Scheme: scheme})
+ if err != nil {
+ t.Fatal(err)
+ }
+ ctx := context.Background()
+ if err := cl.Create(ctx, &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: claimTestNS}}); err != nil {
+ t.Fatal(err)
+ }
+ z := &ZoneClaims{
+ Reader: cl,
+ Writer: cl,
+ Namespace: claimTestNS,
+ MaxEntries: 256,
+ ZoneGone: func(context.Context, dnsv1alpha1.ZoneClaimZone) (bool, error) { return false, nil },
+ }
+
+ for round := range 20 {
+ domain := "example" + string(rune('a'+round)) + ".com"
+ claims := []dnsv1alpha1.ZoneClaimEntry{
+ claimTestZone("p1", "parent", domain),
+ claimTestZone("p2", "child", "shop."+domain),
+ }
+ results := make([]dnsv1alpha1.ZoneClaimEntry, len(claims))
+ errs := make([]error, len(claims))
+ var start, done sync.WaitGroup
+ start.Add(1)
+ for i := range claims {
+ done.Add(1)
+ go func() {
+ defer done.Done()
+ start.Wait()
+ results[i], _, errs[i] = z.Admit(ctx, claims[i])
+ }()
+ }
+ start.Done()
+ done.Wait()
+ active := 0
+ for i := range claims {
+ if errs[i] != nil {
+ t.Fatalf("round %d: admitting %s: %v", round, claims[i].Name, errs[i])
+ }
+ if results[i].State == dnsv1alpha1.ZoneClaimActive {
+ active++
+ }
+ }
+ if active != 1 {
+ t.Fatalf("round %d: %d of the parent and child are Active, want exactly 1: %+v", round, active, results)
+ }
+ if entries := claimSetEntries(t, cl, domain); len(entries) != 2 {
+ t.Fatalf("round %d: set has %d entries, want 2", round, len(entries))
+ }
+ }
+}
diff --git a/internal/controller/zoneclaim_handoff_test.go b/internal/controller/zoneclaim_handoff_test.go
new file mode 100644
index 00000000..80845761
--- /dev/null
+++ b/internal/controller/zoneclaim_handoff_test.go
@@ -0,0 +1,465 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+
+package controller
+
+import (
+ "context"
+ "testing"
+ "time"
+
+ networkingv1alpha "go.datum.net/network-services-operator/api/v1alpha"
+ corev1 "k8s.io/api/core/v1"
+ apierrors "k8s.io/apimachinery/pkg/api/errors"
+ apimeta "k8s.io/apimachinery/pkg/api/meta"
+ metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+ "k8s.io/apimachinery/pkg/runtime"
+ "k8s.io/apimachinery/pkg/types"
+ "k8s.io/client-go/rest"
+ ctrl "sigs.k8s.io/controller-runtime"
+ "sigs.k8s.io/controller-runtime/pkg/client"
+ "sigs.k8s.io/controller-runtime/pkg/client/fake"
+ "sigs.k8s.io/controller-runtime/pkg/client/interceptor"
+ "sigs.k8s.io/controller-runtime/pkg/cluster"
+ "sigs.k8s.io/multicluster-runtime/pkg/multicluster"
+ mcreconcile "sigs.k8s.io/multicluster-runtime/pkg/reconcile"
+
+ dnsv1alpha1 "go.miloapis.com/dns/api/v1alpha1"
+)
+
+const handoffAccountingNS = "accounting"
+
+type projectCluster struct {
+ cluster.Cluster
+ client client.Client
+ scheme *runtime.Scheme
+}
+
+func (c projectCluster) GetClient() client.Client { return c.client }
+func (c projectCluster) GetAPIReader() client.Reader { return c.client }
+func (c projectCluster) GetScheme() *runtime.Scheme { return c.scheme }
+func (c projectCluster) GetConfig() *rest.Config {
+ return &rest.Config{Host: "http://127.0.0.1:1", Timeout: time.Millisecond}
+}
+
+type projectsManager struct {
+ fakeClusterManager
+ clusters map[string]projectCluster
+}
+
+func (m *projectsManager) GetCluster(_ context.Context, name multicluster.ClusterName) (cluster.Cluster, error) {
+ if c, ok := m.clusters[string(name)]; ok {
+ return c, nil
+ }
+ return nil, multicluster.ErrClusterNotFound
+}
+
+type handoff struct {
+ t *testing.T
+ scheme *runtime.Scheme
+ mgr *projectsManager
+ downstream client.Client
+ zones *DNSZoneReplicator
+ records *DNSRecordSetReplicator
+}
+
+func newHandoff(t *testing.T, projects ...string) *handoff {
+ t.Helper()
+ scheme := newTestScheme(t)
+ if err := networkingv1alpha.AddToScheme(scheme); err != nil {
+ t.Fatal(err)
+ }
+ h := &handoff{t: t, scheme: scheme, mgr: &projectsManager{clusters: map[string]projectCluster{}}}
+ for _, p := range projects {
+ ns := &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "default", UID: types.UID(p + "-default")}}
+ class := &dnsv1alpha1.DNSZoneClass{ObjectMeta: metav1.ObjectMeta{Name: "public"}}
+ domain := &networkingv1alpha.Domain{
+ ObjectMeta: metav1.ObjectMeta{Namespace: "default", Name: "example.com"},
+ Spec: networkingv1alpha.DomainSpec{DomainName: "example.com"},
+ Status: networkingv1alpha.DomainStatus{Conditions: []metav1.Condition{
+ {Type: networkingv1alpha.DomainConditionVerified, Status: metav1.ConditionTrue},
+ }},
+ }
+ cl := fake.NewClientBuilder().WithScheme(scheme).
+ WithStatusSubresource(&dnsv1alpha1.DNSZone{}, &dnsv1alpha1.DNSRecordSet{}, &networkingv1alpha.Domain{}).
+ WithObjects(ns, class, domain).
+ WithIndex(&networkingv1alpha.Domain{}, "spec.domainName", func(o client.Object) []string {
+ return []string{o.(*networkingv1alpha.Domain).Spec.DomainName}
+ }).
+ WithIndex(&dnsv1alpha1.DNSRecordSet{}, "spec.dnsZoneRef.name", func(o client.Object) []string {
+ return []string{o.(*dnsv1alpha1.DNSRecordSet).Spec.DNSZoneRef.Name}
+ }).
+ Build()
+ h.mgr.clusters[p] = projectCluster{client: cl, scheme: scheme}
+ }
+ h.downstream = fake.NewClientBuilder().WithScheme(scheme).WithInterceptorFuncs(interceptor.Funcs{
+ Create: func(ctx context.Context, c client.WithWatch, obj client.Object, opts ...client.CreateOption) error {
+ obj.SetCreationTimestamp(metav1.Now())
+ return c.Create(ctx, obj, opts...)
+ },
+ }).Build()
+ h.zones = &DNSZoneReplicator{
+ mgr: h.mgr,
+ DownstreamClient: h.downstream,
+ AccountingNamespace: handoffAccountingNS,
+ ZoneClaims: &ZoneClaims{
+ Reader: h.downstream,
+ Writer: h.downstream,
+ Namespace: handoffAccountingNS,
+ MaxEntries: 256,
+ },
+ }
+ h.zones.ZoneClaims.ZoneGone = h.zones.zoneGone
+ h.zones.ZoneClaims.ZoneServed = h.zones.zoneServed
+ h.records = &DNSRecordSetReplicator{mgr: h.mgr, DownstreamClient: h.downstream, ZoneClaims: true}
+ return h
+}
+
+func (h *handoff) client(project string) client.Client { return h.mgr.clusters[project].client }
+
+func (h *handoff) createZone(project, name, domain string) {
+ h.t.Helper()
+ z := &dnsv1alpha1.DNSZone{
+ ObjectMeta: metav1.ObjectMeta{Namespace: "default", Name: name, UID: types.UID(project + "-" + name), Finalizers: []string{dnsZoneFinalizer}},
+ Spec: dnsv1alpha1.DNSZoneSpec{DomainName: domain, DNSZoneClassName: "public"},
+ }
+ if err := h.client(project).Create(context.Background(), z); err != nil {
+ h.t.Fatal(err)
+ }
+}
+
+func (h *handoff) reconcileZone(project, name string) ctrl.Result {
+ h.t.Helper()
+ res, err := h.zones.Reconcile(context.Background(), mcreconcile.Request{
+ ClusterName: multicluster.ClusterName(project),
+ Request: ctrl.Request{NamespacedName: types.NamespacedName{Namespace: "default", Name: name}},
+ })
+ if err != nil {
+ h.t.Fatalf("reconcile %s/%s: %v", project, name, err)
+ }
+ return res
+}
+
+func (h *handoff) reconcileRecordSet(project, name string) ctrl.Result {
+ h.t.Helper()
+ res, err := h.records.Reconcile(context.Background(), mcreconcile.Request{
+ ClusterName: multicluster.ClusterName(project),
+ Request: ctrl.Request{NamespacedName: types.NamespacedName{Namespace: "default", Name: name}},
+ })
+ if err != nil {
+ h.t.Fatalf("reconcile record set %s/%s: %v", project, name, err)
+ }
+ return res
+}
+
+func (h *handoff) zone(project, name string) *dnsv1alpha1.DNSZone {
+ h.t.Helper()
+ var z dnsv1alpha1.DNSZone
+ if err := h.client(project).Get(context.Background(), client.ObjectKey{Namespace: "default", Name: name}, &z); err != nil {
+ h.t.Fatal(err)
+ }
+ return &z
+}
+
+func (h *handoff) shadowNamespace(project string) string { return "ns-" + project + "-default" }
+
+func (h *handoff) shadowExists(project, name string) bool {
+ h.t.Helper()
+ err := h.downstream.Get(context.Background(), client.ObjectKey{Namespace: h.shadowNamespace(project), Name: name}, &dnsv1alpha1.DNSZone{})
+ if apierrors.IsNotFound(err) {
+ return false
+ }
+ if err != nil {
+ h.t.Fatal(err)
+ }
+ return true
+}
+
+func (h *handoff) deleteZone(project, name string) {
+ h.t.Helper()
+ ctx := context.Background()
+ if err := h.client(project).Delete(ctx, h.zone(project, name)); err != nil {
+ h.t.Fatal(err)
+ }
+ h.reconcileZone(project, name)
+ shadow := &dnsv1alpha1.DNSZone{ObjectMeta: metav1.ObjectMeta{Namespace: h.shadowNamespace(project), Name: name}}
+ if err := h.downstream.Delete(ctx, shadow); client.IgnoreNotFound(err) != nil {
+ h.t.Fatal(err)
+ }
+ h.reconcileZone(project, name)
+ if err := h.client(project).Get(ctx, client.ObjectKey{Namespace: "default", Name: name}, &dnsv1alpha1.DNSZone{}); !apierrors.IsNotFound(err) {
+ h.t.Fatalf("zone %s/%s still exists after its shadow was removed: %v", project, name, err)
+ }
+}
+
+func (h *handoff) admitted(project, name string) {
+ h.t.Helper()
+ if res := h.reconcileZone(project, name); res.RequeueAfter != zoneClaimRetryInterval {
+ h.t.Errorf("%s/%s requeues after %s, want %s so a lost claim is noticed", project, name, res.RequeueAfter, zoneClaimRetryInterval)
+ }
+ if !h.shadowExists(project, name) {
+ h.t.Errorf("%s/%s has no shadow, want it serving", project, name)
+ }
+}
+
+func (h *handoff) refused(project, name string) {
+ h.t.Helper()
+ if res := h.reconcileZone(project, name); res.RequeueAfter != zoneClaimRetryInterval {
+ h.t.Errorf("%s/%s requeues after %s, want %s", project, name, res.RequeueAfter, zoneClaimRetryInterval)
+ }
+ if h.shadowExists(project, name) {
+ h.t.Errorf("%s/%s still has a shadow while refused", project, name)
+ }
+ cond := apimeta.FindStatusCondition(h.zone(project, name).Status.Conditions, CondAccepted)
+ if cond == nil || cond.Status != metav1.ConditionFalse || cond.Reason != ReasonDNSZoneInUse {
+ h.t.Errorf("%s/%s Accepted = %+v, want False/DNSZoneInUse", project, name, cond)
+ }
+}
+
+func TestZoneClaimHandoffThroughTheControllers(t *testing.T) {
+ h := newHandoff(t, "p1", "p2")
+ h.createZone("p1", "apex", "example.com")
+ h.createZone("p2", "sub", "sub.example.com")
+ h.createZone("p1", "deep", "a.sub.example.com")
+
+ h.admitted("p1", "apex")
+ h.refused("p2", "sub")
+ h.admitted("p1", "deep")
+
+ rs := &dnsv1alpha1.DNSRecordSet{
+ ObjectMeta: metav1.ObjectMeta{Namespace: "default", Name: "www", UID: "p1-www"},
+ Spec: dnsv1alpha1.DNSRecordSetSpec{
+ DNSZoneRef: corev1.LocalObjectReference{Name: "deep"},
+ RecordType: dnsv1alpha1.RRTypeA,
+ Records: []dnsv1alpha1.RecordEntry{{Name: "www", A: &dnsv1alpha1.ARecordSpec{Content: "192.0.2.1"}}},
+ },
+ }
+ if err := h.client("p1").Create(context.Background(), rs); err != nil {
+ t.Fatal(err)
+ }
+
+ h.deleteZone("p1", "apex")
+
+ h.refused("p1", "deep")
+ var res ctrl.Result
+ for range 3 {
+ res = h.reconcileRecordSet("p1", "www")
+ }
+ if res.RequeueAfter != zoneClaimRetryInterval {
+ t.Errorf("record set under the refused zone requeues after %s, want %s", res.RequeueAfter, zoneClaimRetryInterval)
+ }
+ var mirrored dnsv1alpha1.DNSRecordSetList
+ if err := h.downstream.List(context.Background(), &mirrored); err != nil {
+ t.Fatal(err)
+ }
+ if len(mirrored.Items) != 0 {
+ t.Errorf("the refused zone's record sets were mirrored downstream: %d", len(mirrored.Items))
+ }
+
+ h.admitted("p2", "sub")
+}
+
+func TestASameNameZoneRetriesWhileClaimsAreOn(t *testing.T) {
+ h := newHandoff(t, "p1", "p2")
+ h.createZone("p1", "first", "example.com")
+ h.createZone("p2", "second", "example.com")
+
+ h.admitted("p1", "first")
+ if res := h.reconcileZone("p2", "second"); res.RequeueAfter != zoneClaimRetryInterval {
+ t.Errorf("a same-name zone requeues after %s, want %s", res.RequeueAfter, zoneClaimRetryInterval)
+ }
+
+ h.deleteZone("p1", "first")
+ h.admitted("p2", "second")
+}
+
+func TestASameNameZoneIsNotRetriedWhileClaimsAreOff(t *testing.T) {
+ h := newHandoff(t, "p1", "p2")
+ h.zones.ZoneClaims = nil
+ h.createZone("p1", "first", "example.com")
+ h.createZone("p2", "second", "example.com")
+
+ h.reconcileZone("p1", "first")
+ if res := h.reconcileZone("p2", "second"); !res.IsZero() {
+ t.Errorf("a same-name zone requeues with claims off: %+v", res)
+ }
+ cond := apimeta.FindStatusCondition(h.zone("p2", "second").Status.Conditions, CondAccepted)
+ if cond == nil || cond.Reason != ReasonDNSZoneInUse {
+ t.Errorf("Accepted = %+v, want DNSZoneInUse", cond)
+ }
+}
+
+func TestAWinnerWaitsForTheDemotedZoneToStopServing(t *testing.T) {
+ h := newHandoff(t, "p1", "p2")
+ h.createZone("p1", "apex", "example.com")
+ h.createZone("p2", "sub", "sub.example.com")
+ h.createZone("p1", "deep", "a.sub.example.com")
+ h.admitted("p1", "apex")
+ h.refused("p2", "sub")
+ h.admitted("p1", "deep")
+
+ h.deleteZone("p1", "apex")
+
+ if res := h.reconcileZone("p2", "sub"); res.RequeueAfter != zoneWithdrawalRetryInterval {
+ t.Errorf("p2/sub requeues after %s, want %s", res.RequeueAfter, zoneWithdrawalRetryInterval)
+ }
+ if h.shadowExists("p2", "sub") {
+ t.Error("p2/sub serves while p1's a.sub.example.com still serves")
+ }
+ cond := apimeta.FindStatusCondition(h.zone("p2", "sub").Status.Conditions, CondAccepted)
+ if cond == nil || cond.Status != metav1.ConditionFalse || cond.Reason != ReasonPendingPreviousZoneRemoval {
+ t.Errorf("p2/sub Accepted = %+v, want False/PendingPreviousZoneRemoval", cond)
+ }
+ if !h.shadowExists("p1", "deep") {
+ t.Fatal("p1/deep stopped serving before its own reconcile")
+ }
+
+ h.refused("p1", "deep")
+ h.admitted("p2", "sub")
+}
+
+func TestZoneServedUnlessTheShadowIsDefinitelyGone(t *testing.T) {
+ h := newHandoff(t, "p1")
+ h.createZone("p1", "apex", "example.com")
+ h.admitted("p1", "apex")
+ ctx := context.Background()
+ for _, tc := range []struct {
+ name string
+ zone dnsv1alpha1.ZoneClaimZone
+ want bool
+ }{
+ {"shadow exists", dnsv1alpha1.ZoneClaimZone{Cluster: "p1", Namespace: "default", Name: "apex"}, true},
+ {"no shadow", dnsv1alpha1.ZoneClaimZone{Cluster: "p1", Namespace: "default", Name: "other"}, false},
+ {"namespace gone", dnsv1alpha1.ZoneClaimZone{Cluster: "p1", Namespace: "gone", Name: "apex"}, false},
+ {"cluster unreachable", dnsv1alpha1.ZoneClaimZone{Cluster: "p9", Namespace: "default", Name: "apex"}, true},
+ } {
+ got, err := h.zones.zoneServed(ctx, tc.zone)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got != tc.want {
+ t.Errorf("%s: served = %v, want %v", tc.name, got, tc.want)
+ }
+ }
+}
+
+func TestARefusedZoneDoesNotLockTheOwnerOutOfItsSubdomain(t *testing.T) {
+ h := newHandoff(t, "p1", "p2")
+ h.createZone("p1", "apex", "example.com")
+ h.createZone("p2", "sub", "sub.example.com")
+ h.createZone("p1", "mine", "sub.example.com")
+
+ h.admitted("p1", "apex")
+ h.refused("p2", "sub")
+ h.admitted("p1", "mine")
+}
+
+func TestADemotedZoneReleasesItsExactName(t *testing.T) {
+ h := newHandoff(t, "p1", "p2")
+ h.createZone("p1", "apex", "example.com")
+ h.createZone("p2", "sub", "sub.example.com")
+ h.createZone("p1", "mine", "sub.example.com")
+ h.admitted("p1", "apex")
+ h.refused("p2", "sub")
+ h.admitted("p1", "mine")
+
+ h.deleteZone("p1", "apex")
+
+ h.refused("p1", "mine")
+ h.admitted("p2", "sub")
+
+ h.deleteZone("p2", "sub")
+ err := h.downstream.Get(context.Background(), client.ObjectKey{Namespace: handoffAccountingNS, Name: "sub.example.com"}, &corev1.ConfigMap{})
+ if !apierrors.IsNotFound(err) {
+ t.Errorf("sub.example.com is still recorded after its last zone was deleted: %v", err)
+ }
+ h.admitted("p1", "mine")
+}
+
+func TestAZoneDemotedWhileCreatingItsShadowWithdraws(t *testing.T) {
+ h := newHandoff(t, "p1", "p2")
+ h.createZone("p1", "apex", "example.com")
+ h.createZone("p2", "sub", "sub.example.com")
+ h.createZone("p1", "deep", "a.sub.example.com")
+ h.admitted("p1", "apex")
+ h.refused("p2", "sub")
+
+ raced := false
+ racing := interceptor.NewClient(h.downstream.(client.WithWatch), interceptor.Funcs{
+ Create: func(ctx context.Context, c client.WithWatch, obj client.Object, opts ...client.CreateOption) error {
+ if _, ok := obj.(*dnsv1alpha1.DNSZone); ok && obj.GetName() == "deep" && !raced {
+ raced = true
+ h.deleteZone("p1", "apex")
+ h.reconcileZone("p2", "sub")
+ }
+ return c.Create(ctx, obj, opts...)
+ },
+ })
+ h.zones.DownstreamClient = racing
+ h.zones.ZoneClaims.Reader = racing
+ h.zones.ZoneClaims.Writer = racing
+
+ h.reconcileZone("p1", "deep")
+ if !raced {
+ t.Fatal("p1/deep never created its shadow")
+ }
+ if h.shadowExists("p1", "deep") && h.shadowExists("p2", "sub") {
+ t.Error("p1 and p2 both serve overlapping names")
+ }
+}
+
+func TestAnOrphanedShadowKeepsItsClaim(t *testing.T) {
+ h := newHandoff(t, "p1", "p2")
+ h.createZone("p1", "deep", "a.sub.example.com")
+ h.createZone("p2", "sub", "sub.example.com")
+ h.admitted("p1", "deep")
+ h.refused("p2", "sub")
+
+ ctx := context.Background()
+ deep := h.zone("p1", "deep")
+ deep.Finalizers = nil
+ if err := h.client("p1").Update(ctx, deep); err != nil {
+ t.Fatal(err)
+ }
+ if err := h.client("p1").Delete(ctx, deep); err != nil {
+ t.Fatal(err)
+ }
+ if !h.shadowExists("p1", "deep") {
+ t.Fatal("p1/deep's shadow is gone, want it orphaned")
+ }
+
+ h.refused("p2", "sub")
+}
+
+func TestAZoneRefusedForAFullClaimSetTakesNoName(t *testing.T) {
+ h := newHandoff(t, "p1", "p2")
+ h.zones.ZoneClaims.MaxEntries = 1
+ h.createZone("p1", "apex", "example.com")
+ h.createZone("p2", "sub", "sub.example.com")
+ h.createZone("p1", "mine", "sub.example.com")
+ h.admitted("p1", "apex")
+ h.reconcileZone("p2", "sub")
+
+ h.zones.ZoneClaims.MaxEntries = 256
+ h.admitted("p1", "mine")
+}
+
+func TestZoneServedReadsTheShadowUncached(t *testing.T) {
+ h := newHandoff(t, "p1")
+ h.createZone("p1", "apex", "example.com")
+ h.admitted("p1", "apex")
+ h.zones.DownstreamClient = interceptor.NewClient(h.downstream.(client.WithWatch), interceptor.Funcs{
+ Get: func(ctx context.Context, c client.WithWatch, key client.ObjectKey, obj client.Object, opts ...client.GetOption) error {
+ if _, ok := obj.(*dnsv1alpha1.DNSZone); ok {
+ return apierrors.NewNotFound(dnsv1alpha1.GroupVersion.WithResource("dnszones").GroupResource(), key.Name)
+ }
+ return c.Get(ctx, key, obj, opts...)
+ },
+ })
+ served, err := h.zones.zoneServed(context.Background(), dnsv1alpha1.ZoneClaimZone{Cluster: "p1", Namespace: "default", Name: "apex"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !served {
+ t.Error("a shadow missing from the cache is read as gone")
+ }
+}
diff --git a/internal/controller/zoneclaim_refusal_test.go b/internal/controller/zoneclaim_refusal_test.go
new file mode 100644
index 00000000..0b68e924
--- /dev/null
+++ b/internal/controller/zoneclaim_refusal_test.go
@@ -0,0 +1,277 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+
+package controller
+
+import (
+ "context"
+ "errors"
+ "testing"
+ "time"
+
+ corev1 "k8s.io/api/core/v1"
+ apierrors "k8s.io/apimachinery/pkg/api/errors"
+ apimeta "k8s.io/apimachinery/pkg/api/meta"
+ metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+ "k8s.io/apimachinery/pkg/runtime"
+ "k8s.io/apimachinery/pkg/types"
+ "sigs.k8s.io/controller-runtime/pkg/client"
+ "sigs.k8s.io/controller-runtime/pkg/client/fake"
+ "sigs.k8s.io/controller-runtime/pkg/cluster"
+ "sigs.k8s.io/multicluster-runtime/pkg/multicluster"
+
+ dnsv1alpha1 "go.miloapis.com/dns/api/v1alpha1"
+)
+
+const refusalShadowNS = "ns-p1"
+
+type refusalFixture struct {
+ r *DNSZoneReplicator
+ upstream client.Client
+ downstream client.Client
+ strategy fakeStrategy
+ zone *dnsv1alpha1.DNSZone
+}
+
+func newRefusalFixture(t *testing.T, claims *ZoneClaims, name, domain string) refusalFixture {
+ t.Helper()
+ scheme := runtime.NewScheme()
+ if err := dnsv1alpha1.AddToScheme(scheme); err != nil {
+ t.Fatal(err)
+ }
+ if err := corev1.AddToScheme(scheme); err != nil {
+ t.Fatal(err)
+ }
+ zone := &dnsv1alpha1.DNSZone{}
+ zone.Namespace = "default"
+ zone.Name = name
+ zone.UID = types.UID("p1-" + name)
+ zone.Spec.DomainName = domain
+ shadow := &dnsv1alpha1.DNSZone{}
+ shadow.Namespace = refusalShadowNS
+ shadow.Name = name
+ shadow.Spec.DomainName = domain
+
+ upstream := fake.NewClientBuilder().WithScheme(scheme).WithStatusSubresource(&dnsv1alpha1.DNSZone{}).WithObjects(zone.DeepCopy()).Build()
+ downstream := fake.NewClientBuilder().WithScheme(scheme).WithObjects(shadow).Build()
+ return refusalFixture{
+ r: &DNSZoneReplicator{DownstreamClient: downstream, AccountingNamespace: "accounting", ZoneClaims: claims},
+ upstream: upstream,
+ downstream: downstream,
+ strategy: fakeStrategy{namespace: refusalShadowNS, name: name, client: downstream},
+ zone: zone,
+ }
+}
+
+func (f refusalFixture) admit(t *testing.T) (bool, time.Duration) {
+ t.Helper()
+ got, ok, err := f.r.admitZoneClaim(context.Background(), f.upstream, f.strategy, nil, "p1", f.zone)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return ok, got.RequeueAfter
+}
+
+func (f refusalFixture) shadowExists(t *testing.T) bool {
+ t.Helper()
+ err := f.downstream.Get(context.Background(), client.ObjectKey{Namespace: refusalShadowNS, Name: f.zone.Name}, &dnsv1alpha1.DNSZone{})
+ if apierrors.IsNotFound(err) {
+ return false
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
+ return true
+}
+
+func (f refusalFixture) stored(t *testing.T) *dnsv1alpha1.DNSZone {
+ t.Helper()
+ var z dnsv1alpha1.DNSZone
+ if err := f.upstream.Get(context.Background(), client.ObjectKeyFromObject(f.zone), &z); err != nil {
+ t.Fatal(err)
+ }
+ return &z
+}
+
+func assertRefused(t *testing.T, z *dnsv1alpha1.DNSZone, reason string) {
+ t.Helper()
+ for _, c := range []string{CondAccepted, CondProgrammed} {
+ cond := apimeta.FindStatusCondition(z.Status.Conditions, c)
+ if cond == nil || cond.Status != metav1.ConditionFalse || cond.Reason != reason {
+ t.Errorf("%s = %+v, want False/%s", c, cond, reason)
+ }
+ }
+}
+
+func TestAServingZoneDemotedByAReleaseLosesItsShadow(t *testing.T) {
+ claims, _ := newClaimTestClaims(t, nil)
+ ctx := context.Background()
+ apex := claimTestZone("p1", "apex", "example.com")
+ sub := claimTestZone("p2", "sub", "sub.example.com")
+ deep := claimTestZone("p1", "deep", "a.sub.example.com")
+ for _, c := range []dnsv1alpha1.ZoneClaimEntry{apex, sub, deep} {
+ if _, _, err := claims.Admit(ctx, c); err != nil {
+ t.Fatal(err)
+ }
+ }
+ f := newRefusalFixture(t, claims, "deep", "a.sub.example.com")
+ if ok, _ := f.admit(t); !ok {
+ t.Fatal("a.sub.example.com is refused while its own project serves example.com")
+ }
+
+ if err := claims.Release(ctx, apex); err != nil {
+ t.Fatal(err)
+ }
+ ok, after := f.admit(t)
+ if ok {
+ t.Fatal("a.sub.example.com is still admitted under another project's sub.example.com")
+ }
+ if after != zoneClaimRetryInterval {
+ t.Errorf("requeue after %s, want %s", after, zoneClaimRetryInterval)
+ }
+ if f.shadowExists(t) {
+ t.Error("the demoted zone's shadow still serves")
+ }
+ assertRefused(t, f.stored(t), ReasonDNSZoneInUse)
+ if !zoneRefused(f.stored(t)) {
+ t.Error("the record set replicator would keep mirroring the demoted zone's record sets")
+ }
+}
+
+func TestReadmittingAnUnchangedClaimWritesNothing(t *testing.T) {
+ claims, cl := newClaimTestClaims(t, nil)
+ ctx := context.Background()
+ zone := claimTestZone("p1", "apex", "example.com")
+ if _, _, err := claims.Admit(ctx, zone); err != nil {
+ t.Fatal(err)
+ }
+ var before, after dnsv1alpha1.ZoneClaimSet
+ key := client.ObjectKey{Namespace: claimTestNS, Name: "example.com"}
+ if err := cl.Get(ctx, key, &before); err != nil {
+ t.Fatal(err)
+ }
+ if _, _, err := claims.Admit(ctx, zone); err != nil {
+ t.Fatal(err)
+ }
+ if err := cl.Get(ctx, key, &after); err != nil {
+ t.Fatal(err)
+ }
+ if after.ResourceVersion != before.ResourceVersion {
+ t.Errorf("resourceVersion moved from %s to %s on an unchanged admission", before.ResourceVersion, after.ResourceVersion)
+ }
+}
+
+func TestAPublicSuffixZoneIsRefused(t *testing.T) {
+ claims, _ := newClaimTestClaims(t, nil)
+ f := newRefusalFixture(t, claims, "suffix", "co.uk")
+ ok, after := f.admit(t)
+ if ok {
+ t.Fatal("a zone for co.uk was admitted")
+ }
+ if after != 0 {
+ t.Errorf("requeue after %s, want none", after)
+ }
+ assertRefused(t, f.stored(t), ReasonInvalidDomain)
+}
+
+func TestAZoneRefusedForAFullClaimSetRetries(t *testing.T) {
+ claims, _ := newClaimTestClaims(t, nil)
+ claims.MaxEntries = 1
+ if _, _, err := claims.Admit(context.Background(), claimTestZone("p2", "other", "example.com")); err != nil {
+ t.Fatal(err)
+ }
+ f := newRefusalFixture(t, claims, "shop", "shop.example.com")
+ ok, after := f.admit(t)
+ if ok {
+ t.Fatal("a zone past the cap was admitted")
+ }
+ if after != zoneClaimRetryInterval {
+ t.Errorf("requeue after %s, want %s", after, zoneClaimRetryInterval)
+ }
+ assertRefused(t, f.stored(t), ReasonClaimSetFull)
+}
+
+func TestZoneRefusedOnlyForClaimReasons(t *testing.T) {
+ for _, tc := range []struct {
+ status metav1.ConditionStatus
+ reason string
+ want bool
+ }{
+ {metav1.ConditionFalse, ReasonDNSZoneInUse, true},
+ {metav1.ConditionFalse, ReasonInvalidDomain, false},
+ {metav1.ConditionFalse, ReasonClaimSetFull, false},
+ {metav1.ConditionFalse, ReasonPending, false},
+ {metav1.ConditionTrue, ReasonAccepted, false},
+ } {
+ z := &dnsv1alpha1.DNSZone{}
+ apimeta.SetStatusCondition(&z.Status.Conditions, metav1.Condition{Type: CondAccepted, Status: tc.status, Reason: tc.reason})
+ if got := zoneRefused(z); got != tc.want {
+ t.Errorf("%s/%s refused = %v, want %v", tc.status, tc.reason, got, tc.want)
+ }
+ }
+ if zoneRefused(&dnsv1alpha1.DNSZone{}) {
+ t.Error("a zone with no Accepted condition is refused")
+ }
+}
+
+type readerCluster struct {
+ cluster.Cluster
+ reader client.Reader
+}
+
+func (c readerCluster) GetAPIReader() client.Reader { return c.reader }
+
+type oneClusterManager struct {
+ fakeClusterManager
+ cl cluster.Cluster
+ err error
+}
+
+func (m *oneClusterManager) GetCluster(context.Context, multicluster.ClusterName) (cluster.Cluster, error) {
+ return m.cl, m.err
+}
+
+type failingReader struct{ client.Reader }
+
+func (failingReader) Get(context.Context, client.ObjectKey, client.Object, ...client.GetOption) error {
+ return apierrors.NewServiceUnavailable("unavailable")
+}
+
+func TestZoneGoneOnlyWhenTheZoneIsDefinitelyGone(t *testing.T) {
+ scheme := runtime.NewScheme()
+ if err := dnsv1alpha1.AddToScheme(scheme); err != nil {
+ t.Fatal(err)
+ }
+ live := &dnsv1alpha1.DNSZone{}
+ live.Namespace = "default"
+ live.Name = "live"
+ live.UID = "uid-live"
+ present := fake.NewClientBuilder().WithScheme(scheme).WithObjects(live).Build()
+ ref := func(name, uid string) dnsv1alpha1.ZoneClaimZone {
+ return dnsv1alpha1.ZoneClaimZone{Cluster: "p1", Namespace: "default", Name: name, UID: uid}
+ }
+
+ for _, tc := range []struct {
+ name string
+ mgr *oneClusterManager
+ zone dnsv1alpha1.ZoneClaimZone
+ want bool
+ }{
+ {"deleted", &oneClusterManager{cl: readerCluster{reader: present}}, ref("missing", "uid-x"), true},
+ {"recreated", &oneClusterManager{cl: readerCluster{reader: present}}, ref("live", "uid-old"), true},
+ {"same zone", &oneClusterManager{cl: readerCluster{reader: present}}, ref("live", "uid-live"), false},
+ {"imported without a UID", &oneClusterManager{cl: readerCluster{reader: present}}, ref("live", ""), false},
+ {"cluster unreachable", &oneClusterManager{err: errors.New("no such cluster")}, ref("missing", "uid-x"), false},
+ {"read fails", &oneClusterManager{cl: readerCluster{reader: failingReader{}}}, ref("missing", "uid-x"), false},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ r := &DNSZoneReplicator{mgr: tc.mgr}
+ got, err := r.zoneGone(context.Background(), tc.zone)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got != tc.want {
+ t.Errorf("gone = %v, want %v", got, tc.want)
+ }
+ })
+ }
+}
diff --git a/internal/dns/util/conditions.go b/internal/dns/util/conditions.go
index bd40d1c3..2652403c 100644
--- a/internal/dns/util/conditions.go
+++ b/internal/dns/util/conditions.go
@@ -36,16 +36,19 @@ const (
// neither the CLI plugin nor the dns-mcp server pulls in the controller's
// dependency tree just to spell a reason string.
const (
- ReasonAccepted = "Accepted"
- ReasonPending = "Pending"
- ReasonInvalidDNSRecordSet = "InvalidDNSRecordSet"
- ReasonProgrammed = "Programmed"
- ReasonDiscovered = "Discovered"
- ReasonDNSZoneInUse = "DNSZoneInUse"
- ReasonNotOwner = "NotOwner"
- ReasonPDNSError = "PDNSError"
- ReasonConflict = "Conflict"
- ReasonPendingDomainVerification = "PendingDomainVerification"
+ ReasonAccepted = "Accepted"
+ ReasonPending = "Pending"
+ ReasonInvalidDNSRecordSet = "InvalidDNSRecordSet"
+ ReasonProgrammed = "Programmed"
+ ReasonDiscovered = "Discovered"
+ ReasonDNSZoneInUse = "DNSZoneInUse"
+ ReasonNotOwner = "NotOwner"
+ ReasonPDNSError = "PDNSError"
+ ReasonConflict = "Conflict"
+ ReasonPendingDomainVerification = "PendingDomainVerification"
+ ReasonInvalidDomain = "InvalidDomain"
+ ReasonClaimSetFull = "ClaimSetFull"
+ ReasonPendingPreviousZoneRemoval = "PendingPreviousZoneRemoval"
)
const (