diff --git a/README.md b/README.md index cf1b5d9..7a88a38 100644 --- a/README.md +++ b/README.md @@ -296,8 +296,10 @@ hosts: # (two hosts without `network:` both have the fleet's, so they overlap too). Either field may be set; # the other falls back to the fleet-level `network:`. node-02: - provider: digitalocean - address: auto + provider: static + address: 192.0.2.11 # DNS records that follow a service on this host point here (needs an IP) + incus_remote: node-02 # optional: the Incus remote that reaches this host; a migration's + # target_host: node-02 goes to it (docs/daemon.md, "Moving an instance") network: ipv4_cidr: 10.0.101.0/24 # This host's part of the mesh (below): its WireGuard public key, as its daemon's plan reports it. @@ -305,6 +307,7 @@ hosts: # names) and endpoint (host[:port]; otherwise this host's address and mesh.listen_port). mesh: public_key: +# reconcile brings each host up on its own, in name order; one failing does not stop the others. # The host a service without `host:` runs on: required with two or more hosts (with one, that host is # the default). Each host's daemon runs with `serve --host-name ` and applies only its own # services: see docs/daemon.md, "Several hosts". @@ -318,13 +321,19 @@ daemon: flags: "--addr 10.0.100.1:8686 --enable-apply" # Records the plan diffs against the provider and a deploy tag applies (create or update, never delete), -# beyond the computed apex + wildcard A. Each names its own zone. +# beyond the computed apex + wildcard A (which point at the default host). Each names its own zone. +# With several hosts, DNS follows the host: a record with `service:` belongs to that service's host, and +# only that host's daemon writes it (an A/AAAA one leaves `value:` out and gets the host's address); a +# service off the default host routed under `domain:` gets an A record at its host; every other record is +# the default host's. Wildcards tied to a service, and records two hosts would claim, are refused. +# See docs/daemon.md, "DNS with several hosts". dns_records: - zone: example.com type: MX name: inbound # inbound.example.com value: inbound.example.com. # the mail host priority: 10 + # - {type: A, name: git, service: gitea} # git.example.com -> gitea's host (its address: must be an IP) # Local snapshots, kept by Incus itself (no host timer): the default for every volume a service declares. # A volume's own `snapshots:` replaces it; `snapshots: {}` on a volume turns them off for it. Absent here diff --git a/cmd/native-ops/main.go b/cmd/native-ops/main.go index f207997..d899651 100644 --- a/cmd/native-ops/main.go +++ b/cmd/native-ops/main.go @@ -166,6 +166,34 @@ func handleValidateCommand(ctx context.Context, args []string) { fmt.Printf(" • Hosts: %d (%v)\n", len(summary.Hosts), summary.Hosts) fmt.Printf(" • Services: %d (%v)\n", len(summary.Services), summary.Services) fmt.Printf(" • Templates: %d (%v)\n", len(summary.Templates), summary.Templates) + // With several hosts, what each host's daemon plans and applies. + if len(summary.PerHost) >= 2 { + for _, h := range summary.PerHost { + def := "" + if h.Default { + def = ", default host" + } + fmt.Printf(" • Host %s (%s%s)\n", h.Name, orDash(h.Address), def) + fmt.Printf(" services: %s\n", orDash(strings.Join(h.Services, ", "))) + if len(h.DNS) == 0 { + fmt.Printf(" dns: -\n") + } + for i, r := range h.DNS { + label := " " + if i == 0 { + label = "dns: " + } + fmt.Printf(" %s%s\n", label, r) + } + } + } +} + +func orDash(s string) string { + if s == "" { + return "-" + } + return s } func handleReconcileCommand(ctx context.Context, args []string) { @@ -553,19 +581,28 @@ func handleDNSCommand(ctx context.Context, args []string) { } logf := func(format string, a ...any) { fmt.Printf(format+"\n", a...) } - if err := syncDeclaredRecords(ctx, fleet, dnsProv, logf); err != nil { + // Every host's records: this is the operator's tool, not a daemon, so it is not limited to one host's share. + services, err := config.LoadServices(*configDir, "") + if err != nil && len(fleet.Hosts) >= 2 { + log.Fatalf("Load services (the DNS records of a fleet of several hosts follow their services): %v", err) + } + if err := syncDeclaredRecords(ctx, fleet, services, dnsProv, logf); err != nil { log.Fatal(err) } } -// syncDeclaredRecords creates or updates the records declared in fleet.yml (`dns_records:`), zone by -// zone. A sync never deletes a record it was not told about. `dns sync` and the daemon's -// POST /v1/dns/sync both use it. -func syncDeclaredRecords(ctx context.Context, fleet *config.FleetConfig, dnsProv provider.DNSProvider, logf func(string, ...any)) error { - byZone, err := fleet.DNSRecordsByZone() +// syncDeclaredRecords creates or updates the fleet's DNS records (fleet.yml's `dns_records:`, with each +// record tied to a service pointing at that service's host, and the records of the routes of services off +// the default host), zone by zone. A sync never deletes a record it was not told about. +func syncDeclaredRecords(ctx context.Context, fleet *config.FleetConfig, services []*config.ServiceConfig, dnsProv provider.DNSProvider, logf func(string, ...any)) error { + all, err := fleet.DNSRecordsByHost(services) if err != nil { return fmt.Errorf("dns_records: %w", err) } + byZone := map[string][]config.DNSRecordConfig{} + for _, r := range all { + byZone[r.Zone] = append(byZone[r.Zone], r.DNSRecordConfig) + } zones := make([]string, 0, len(byZone)) for z := range byZone { zones = append(zones, z) diff --git a/cmd/native-ops/serve.go b/cmd/native-ops/serve.go index 667cbb8..bf4bf58 100644 --- a/cmd/native-ops/serve.go +++ b/cmd/native-ops/serve.go @@ -479,6 +479,8 @@ func newDaemon(cfg daemonConfig) (*server.Server, func(), error) { opts.ResumeFile = filepath.Join(cfg.StateDir, "deploy-resume.json") opts.Flags = cfg.Flags } + // A deploy tag records fleet.yml's hosts and their Incus remotes, for a migration by target_host. + opts.HostRemotesFile, opts.HostName = filepath.Join(cfg.StateDir, "host-remotes.json"), cfg.HostName if cfg.EnableBackup { opts.BackupScheduleDir = filepath.Join(cfg.StateDir, "backup-schedule") opts.Backup, opts.Restore = backupSource(cfg.Exec, cfg.Pool, lookup, cfg.HostName), restoreSource(cfg.Exec, cfg.Pool, lookup, cfg.HostName) diff --git a/docs/daemon.md b/docs/daemon.md index 16aa969..2ca9dd3 100644 --- a/docs/daemon.md +++ b/docs/daemon.md @@ -51,7 +51,7 @@ the host, or by your IaC. It is not something a person sets up by hand. | `PATCH /v1/instances/{name}/labels` | deployer | change a tenant instance's labels live (`{"set": {...}, "remove": [...]}`), as a job; no restart | | `POST /v1/instances/{name}/resize` | deployer | a live `limits.cpu`/`limits.memory` change, as a job; no restart | | `POST /v1/instances/{name}/suspend` | deployer | replace the published route with a static 503 naming a reason, as a job, without touching the instance; undone by asking for the instance again (`PUT`), which always republishes the normal route | -| `POST /v1/instances/{name}/migrate` | admin, or a token scoped to the instance | on the source host: move a tenant instance and its volumes to another host (`{"target_remote": "..."}`), as a job; on success its route here is dropped and the copy here is marked migrated ([Moving an instance to another host](#moving-an-instance-to-another-host)) | +| `POST /v1/instances/{name}/migrate` | admin, or a token scoped to the instance | on the source host: move a tenant instance and its volumes to another host (`{"target_remote": "..."}`, or `{"target_host": "..."}`, a `fleet.yml` host whose `incus_remote` is used), as a job; on success its route here is dropped and the copy here is marked migrated ([Moving an instance to another host](#moving-an-instance-to-another-host)) | | `GET /v1/instances/{name}/export-spec` | viewer | the instance's spec (image, limits, volumes, health, domain, route directives, labels), never its environment, for the target host to adopt | | `POST /v1/instances/{name}/adopt` | admin, or a token scoped to the instance | on the target host: take over an instance a migration put there (check it, record the spec, publish the route), as a job; refused if it is not there | | `POST /v1/instances/{name}/finalize-migration` | admin, or a token scoped to the instance | on the source host: delete the stopped copy of an instance it migrated away, as a job, once the target is verified | @@ -312,7 +312,7 @@ planned. Once applied, the same commit plans to nothing. That includes the netwo | What | Declared in | Planned as | Applied | |---|---|---|---| -| DNS records | `fleet.yml` `dns_records` (each names its zone) | `dns-create` / `dns-update`, diffed against the provider (read only) | through the built-in provider; the zone is read again first, and if it moved since the plan the apply refuses ("plan again") | +| DNS records | `fleet.yml` `dns_records` (each names its zone); with several hosts, only those that point at this daemon's host ([DNS with several hosts](#dns-with-several-hosts)) | `dns-create` / `dns-update`, diffed against the provider (read only) | through the built-in provider; the zone is read again first, and if it moved since the plan the apply refuses ("plan again") | | The edge's main Caddyfile | `edge/Caddyfile` | `edge-caddyfile`, with the lines added and removed; its content is in the hash | validated, reloaded, and rolled back if Caddy rejects it | | Host ports | a service's `forwards:` | `publish-port` / `remove-port` on that service | an Incus proxy device per forward | | The instance bridge | `fleet.yml` `network:`, or the host's own `hosts..network:` | checked only | never: the daemon does not re-address a live bridge, so a difference **blocks** the plan. With more than one host in `fleet.yml`, each daemon checks the bridge of the host it is (`--host-name`, see [Several hosts](#several-hosts)) | @@ -410,7 +410,7 @@ manager, or an admin) runs the sequence: ```bash # 1. on the SOURCE daemon: copy the instance and its volumes to the target, stop the source, start and check the target -curl -X POST "$SOURCE/v1/instances/cust-one/migrate" -d '{"target_remote": "host-b"}' # 202, a job: wait for it +curl -X POST "$SOURCE/v1/instances/cust-one/migrate" -d '{"target_host": "host-b"}' # 202, a job: wait for it (or "target_remote") # 2. on the SOURCE daemon: the spec the target needs (never the environment) curl "$SOURCE/v1/instances/cust-one/export-spec" # {"name", "spec", "migrated_to"} # 3. on the TARGET daemon: take the instance over, with that spec @@ -432,6 +432,11 @@ curl -X POST "$SOURCE/v1/instances/cust-one/finalize-migration" -d '{}' source with its copy of the volumes. `resume: true` continues an interrupted run onto the stopped copy it left on the target. Refused (`409 not_migratable`) for an instance that mounts a host path, has no recorded spec, or was already migrated. +- **`target_host`** names the target by its `fleet.yml` host: the daemon resolves it to that host's + `hosts..incus_remote`, as the `fleet.yml` of the last deploy tag it applied gives it (a deploy + records the hosts and their remotes in the state directory). It is refused when no deploy recorded the + hosts yet, when the host is not in them or has no `incus_remote`, when it is this daemon's own host, and + with `target_remote` beside it. `target_remote` still works without `fleet.yml`. - **`target_remote`** is an Incus remote configured **on the source host** for the daemon's user (`incus remote add host-b https://:8443 ...`, trusted on the target), the same remotes the CLI's `--target` names. The copy is pushed directly from the source to the target, so **the two hosts must reach @@ -807,8 +812,10 @@ host: host-b # must name an entry of hosts:; left out, the service i - **A plan is one host's share.** It plans the services of its host (their `host:`, else `default_host`) and lists every other service as one line, `- db (skipped: on host host-b)`, without reading anything about it from the host. A host that runs the edge instance applies `edge/Caddyfile` to it; a host without - one, when the edge service is pinned to another host, notes that instead of being blocked. `dns_records` are the fleet's, so only the default host's daemon plans and applies them; - the others note it. + one, when the edge service is pinned to another host, notes that instead of being blocked. +- **DNS follows the host.** Each daemon plans and applies only the DNS records that point at its own host, + so two daemons never write the same record (below). Its plan names, per other host, the records that + host's daemon does (`note: dns: host host-b's daemon plans and applies A db.example.com, ...`). - **Each host checks its own bridge.** The plan checks the live bridge against that host's network (its `hosts..network`, else the fleet's `network:`), and apply's launches make sure of that bridge, never the fleet's or another host's. @@ -820,9 +827,52 @@ host: host-b # must name an entry of hosts:; left out, the service i one. A `--host-name` that is not in `hosts:` is refused the same way, and apply checks again that every service it changes is its host's. The CLI's `plan` and `apply` take `--host-name` and follow the same rule; `reconcile --deploy-services` (one host over SSH) is refused for several hosts. +- **`validate` shows each host's share**: with two or more hosts it lists, per host, its address, its + services and the DNS records that point at it. - **A single-host fleet is unchanged.** With one entry in `hosts:` (or none) that host is the default, `--host-name` may be left out, and plans, their text and their hashes are exactly as before. +### DNS with several hosts + +Which host's daemon writes a record: + +| Record | Points at | Written by | +|---|---|---| +| `domain:`'s apex and wildcard (`A @`, `A *`) | the default host | `reconcile`, as before | +| a `dns_records` entry with `service: ` | that service's host (`host:`, else `default_host`); an `A`/`AAAA` record leaves `value:` out and gets the host's `address:` | that host's daemon | +| a route (`routing.domain`) of a service **not** on the default host, under `domain:` | an `A` record of that name at its host's `address:` (the wildcard points at the default host, so without it the name would reach the wrong host) | that host's daemon | +| any other `dns_records` entry (no `service:`) | its `value:`, as written | the default host's daemon | + +```yaml +# fleet.yml +domain: example.com +dns_records: + - {type: A, name: mail, service: mailer} # mailer's host's address + - {type: MX, name: "@", value: mail.example.com., priority: 10, service: mailer} # follows mailer + - {type: TXT, name: "@", value: "v=spf1 mx -all"} # the default host's +``` + +Refused by `validate` and blocking the plan, with a message that says why: + +- a record tied to a service whose name is a **wildcard** (it would claim the names of other hosts' + services), and a service off the default host **routed at a wildcard** or at the domain's apex; +- a record **two hosts would claim** (the same zone, name and type, or a `CNAME` beside any record of + its name, with different hosts), including a record that collides with `domain:`'s apex or wildcard; +- a record tied to a service that does not exist, an `A`/`AAAA` record tied to a service that also gives + `value:`, and one whose host has no IP address of that family in `hosts..address`. + +A route outside `domain:`'s zone gets no record of its own: declare it in `dns_records` with `service:`. +`native-ops dns sync` (an operator's tool, not a daemon) writes every host's records. A fleet of one +host has nothing to split: its records, plans and hashes are as before. + +### Reconcile with several hosts + +`native-ops reconcile` brings each host up on its own, in the order of their names: each with its own +address, SSH user and port, and bridge. A host that fails (it cannot be provisioned, or SSH never +answers) is logged, the others carry on, and the run fails at the end naming every host that failed. +The fleet's `domain:` points at the default host, whatever order the hosts are in. With one host the +output and errors are exactly as before. + **One tag, every daemon.** A deploy tag is sent to every host's daemon by a CI matrix, one job per host with that host's URL and token ([ci-examples/deploy-hosts.yml](ci-examples/deploy-hosts.yml)): @@ -1063,6 +1113,7 @@ Everything the daemon keeps is in `--state-dir` (default `/var/lib/native-ops`, | `audit.log` | one JSON line per request and per finished job (never a value or credential) | | `bin/` | the daemon's binary, the previous one, and the upgrade markers (see above) | | `deploy-resume.json` | a deploy that upgraded the daemon to `fleet.yml`'s pin, until the new binary resumes it | +| `host-remotes.json` | `fleet.yml`'s hosts and their `incus_remote`, from the last deploy tag: where a migration's `target_host` goes | All files are 0600. Back the directory up if losing approvals, job history or users matters to you; tokens and secrets can be re-created from the git server. @@ -1127,7 +1178,9 @@ record. Normally services reach a host through an approved apply. Done: services pinned to hosts, with one daemon per host applying its own share and checking its own bridge subnet ([Several hosts](#several-hosts)), driven by a CI matrix, and a WireGuard mesh between them -([Mesh between hosts](#mesh-between-hosts)). Next: `native-ops remote` fanning a plan or apply out to each -host's daemon and gathering the results; DNS and reconcile per host, backups keyed by host; instance migrate and previews as jobs; a live view of -a running job; and per-user API tokens. The API is versioned (`/v1`) so a separate fleet manager can +([Mesh between hosts](#mesh-between-hosts)); DNS that follows each service's host and reconcile per host +([DNS with several hosts](#dns-with-several-hosts)); backups keyed by host; instance migrate as a job, with +`target_host` resolved through `incus_remote`. Next: `native-ops remote` fanning a plan or apply out to each +host's daemon and gathering the results; previews as jobs; a live view of a running job; and per-user API +tokens. The API is versioned (`/v1`) so a separate fleet manager can depend on it. diff --git a/pkg/config/config.go b/pkg/config/config.go index c9c0da8..5272cce 100644 --- a/pkg/config/config.go +++ b/pkg/config/config.go @@ -52,6 +52,10 @@ type DNSRecordConfig struct { Value string `yaml:"value"` TTL int `yaml:"ttl,omitempty"` Priority int `yaml:"priority,omitempty"` + // Service ties the record to a service: it follows that service's host (its `host:`, else the default + // host), and only that host's daemon plans and applies it. An A or AAAA record tied to a service leaves + // Value out: it is the host's `address:`. A record tied to no service belongs to the default host. + Service string `yaml:"service,omitempty"` } // DNSRecordsByZone groups the declared records by zone (fleet.domain when a record omits it). It errors @@ -300,11 +304,13 @@ type ProxmoxConfig struct { } type HostConfig struct { - Provider string `yaml:"provider"` // "digitalocean", "proxmox", "static" - Address string `yaml:"address"` - SSHUser string `yaml:"ssh_user"` - SSHPort int `yaml:"ssh_port"` - IncusRemote string `yaml:"incus_remote"` // optional Incus remote name + Provider string `yaml:"provider"` // "digitalocean", "proxmox", "static" + Address string `yaml:"address"` + SSHUser string `yaml:"ssh_user"` + SSHPort int `yaml:"ssh_port"` + // IncusRemote is the Incus remote, as the other hosts name it, that reaches this host: a migration to + // it (POST /v1/instances/{name}/migrate with target_host) goes to this remote. Optional. + IncusRemote string `yaml:"incus_remote,omitempty"` // Network overrides the fleet-level `network:` for this host; a field left empty falls back to it. // Each host needs its own subnet (LoadFleetConfig refuses two that overlap). Network *NetworkConfig `yaml:"network,omitempty"` diff --git a/pkg/config/dns.go b/pkg/config/dns.go new file mode 100644 index 0000000..bc4021d --- /dev/null +++ b/pkg/config/dns.go @@ -0,0 +1,194 @@ +package config + +import ( + "fmt" + "net/netip" + "sort" + "strings" +) + +// DNS follows the host. In a fleet of several hosts each daemon writes only the DNS records that point at +// its own host, so two daemons never write the same record: +// +// - a record tied to a service (a dns_records entry with `service:`) belongs to that service's host, and +// an A or AAAA record of it points at that host's `address:`; +// - a service on a host other than the default one, routed at a name under fleet.yml's `domain:`, gets +// an A record of that name pointing at its host (the domain's apex and wildcard point at the default +// host, so without it the name would reach the wrong host); +// - every other record (dns_records without `service:`) belongs to the default host. +// +// A fleet of one host has nothing to split: its records are planned exactly as before. + +// HostDNSRecord is a DNS record of the fleet, with the host whose daemon writes it. +type HostDNSRecord struct { + DNSRecordConfig + // Zone is the record's zone (DNSRecordConfig.Zone, or fleet.yml's domain). + Zone string + // Host is the host whose daemon plans and applies the record; "" in a fleet.yml without hosts:. + Host string + // From says where the record comes from: "dns_records", or "service 's route". + From string +} + +// Key is what makes two records the same record to a zone: zone, name and type. +func (r HostDNSRecord) Key() string { + return strings.ToLower(r.Zone) + "\x00" + strings.ToLower(r.Name) + "\x00" + strings.ToUpper(r.Type) +} + +// HostAddress is a host's address as fleet.yml gives it, when that is an IP address (not "auto", not a +// name, not empty). +func (f *FleetConfig) HostAddress(host string) (netip.Addr, bool) { + h, ok := f.Hosts[host] + if !ok { + return netip.Addr{}, false + } + a, err := netip.ParseAddr(strings.TrimSpace(h.Address)) + return a, err == nil +} + +// DNSRecordsByHost is every DNS record the fleet's daemons write, each with its host (see the rules +// above), dns_records first in the order fleet.yml declares them, then the routes' records by service. +// services are all the repository's services. It refuses +// what no rule can place: a record tied to a service that does not exist, a record tied to a service that +// names a wildcard, a wildcard route on a host other than the default one, an A or AAAA record whose host +// has no address of that family, and the same record claimed by two hosts. +func (f *FleetConfig) DNSRecordsByHost(services []*ServiceConfig) ([]HostDNSRecord, error) { + byName := map[string]*ServiceConfig{} + for _, s := range services { + byName[s.Name] = s + } + defaultHost := f.DefaultHostName() + var out []HostDNSRecord + + for _, r := range f.DNSRecords { + zone := strings.TrimSpace(r.Zone) + if zone == "" { + zone = strings.TrimSpace(f.Domain) + } + if zone == "" { + return nil, fmt.Errorf("dns record %s %s has no zone and fleet.domain is empty", r.Type, r.Name) + } + rec := HostDNSRecord{DNSRecordConfig: r, Zone: zone, Host: defaultHost, From: "dns_records"} + if r.Service == "" { + out = append(out, rec) + continue + } + what := fmt.Sprintf("dns_records %s %s (service %s)", r.Type, recordName(r.Name, zone), r.Service) + svc, ok := byName[r.Service] + if !ok { + return nil, fmt.Errorf("%s: there is no service %q in services/", what, r.Service) + } + if strings.Contains(r.Name, "*") { + return nil, fmt.Errorf("%s: a record tied to a service cannot be a wildcard: it would claim every name under it, those of other hosts' services included; name it, or leave service: out so it stays with the default host", what) + } + rec.Host = f.HostOf(svc) + if isAddressType(r.Type) { + if strings.TrimSpace(r.Value) != "" { + return nil, fmt.Errorf("%s: leave value out: an %s record tied to a service points at its host's address", what, strings.ToUpper(r.Type)) + } + v, err := f.addressFor(rec.Host, r.Type) + if err != nil { + return nil, fmt.Errorf("%s: %w", what, err) + } + rec.Value = v + } + out = append(out, rec) + } + + // A service off the default host, routed under the fleet's domain, needs its own A record: the + // domain's wildcard points at the default host. + if len(f.Hosts) >= 2 { + names := make([]string, 0, len(services)) + for _, s := range services { + names = append(names, s.Name) + } + sort.Strings(names) + for _, name := range names { + svc := byName[name] + host := f.HostOf(svc) + rt := svc.Routing + if host == defaultHost || rt == nil || rt.External || strings.TrimSpace(rt.Domain) == "" { + continue + } + domain := strings.ToLower(strings.TrimSuffix(strings.TrimSpace(rt.Domain), ".")) + if strings.Contains(domain, "*") { + return nil, fmt.Errorf("service %s on host %s is routed at the wildcard %s: a wildcard record would claim the names of the other hosts' services (the fleet's wildcard points at the default host, %s); route it at a name, or move it to the default host", name, host, domain, defaultHost) + } + zone := strings.ToLower(strings.TrimSuffix(strings.TrimSpace(f.Domain), ".")) + if zone == "" || !strings.HasSuffix(domain, "."+zone) { + if zone != "" && domain == zone { + return nil, fmt.Errorf("service %s on host %s is routed at %s, the fleet's apex, which points at the default host %s; route it at a name under it, or move it to the default host", name, host, domain, defaultHost) + } + // Outside the fleet's zone: its record is the repository's to declare (a dns_records entry + // with service:), since the zone it lives in is not known here. + continue + } + v, err := f.addressFor(host, "A") + if err != nil { + return nil, fmt.Errorf("service %s is routed at %s on host %s: %w", name, domain, host, err) + } + out = append(out, HostDNSRecord{ + DNSRecordConfig: DNSRecordConfig{Type: "A", Name: strings.TrimSuffix(domain, "."+zone), Value: v, Service: name}, + Zone: strings.TrimSpace(f.Domain), Host: host, From: "service " + name + "'s route", + }) + } + } + + // No record may be claimed by two hosts: two daemons would each write it, the last one winning. A + // CNAME is the only record of its name, so it conflicts with any type. The domain's apex and wildcard A + // are the default host's (reconcile writes them). + owner := map[string]HostDNSRecord{} + claim := func(r HostDNSRecord, key string) error { + if o, ok := owner[key]; ok && o.Host != r.Host { + return fmt.Errorf("%s %s is claimed by host %s (%s) and host %s (%s): one record can point at one host; give it to one of them", r.Type, recordName(r.Name, r.Zone), o.Host, o.From, r.Host, r.From) + } + if _, ok := owner[key]; !ok { + owner[key] = r + } + return nil + } + if d := strings.TrimSpace(f.Domain); d != "" && defaultHost != "" { + for _, n := range []string{"@", "*"} { + r := HostDNSRecord{DNSRecordConfig: DNSRecordConfig{Type: "A", Name: n}, Zone: d, Host: defaultHost, From: "reconcile, for domain:"} + owner[r.Key()] = r + } + } + for _, r := range out { + if err := claim(r, r.Key()); err != nil { + return nil, err + } + } + for _, r := range out { + zn := strings.ToLower(r.Zone) + "\x00" + strings.ToLower(r.Name) + "\x00" + for k, o := range owner { + if strings.HasPrefix(k, zn) && o.Host != r.Host && (strings.EqualFold(r.Type, "CNAME") || strings.EqualFold(o.Type, "CNAME")) { + return nil, fmt.Errorf("%s %s (host %s, %s) and %s %s (host %s, %s): a CNAME is the only record of its name, and these point at different hosts", r.Type, recordName(r.Name, r.Zone), r.Host, r.From, o.Type, recordName(o.Name, o.Zone), o.Host, o.From) + } + } + } + + return out, nil +} + +// addressFor is the host's address for an A (IPv4) or AAAA (IPv6) record. +func (f *FleetConfig) addressFor(host, typ string) (string, error) { + a, ok := f.HostAddress(host) + if !ok { + return "", fmt.Errorf("host %s has no IP address in fleet.yml (hosts.%s.address), and the record points at it; set it", host, host) + } + if strings.EqualFold(typ, "A") != a.Is4() { + return "", fmt.Errorf("host %s's address %s is not an %s address", host, a, map[bool]string{true: "IPv4 (A)", false: "IPv6 (AAAA)"}[strings.EqualFold(typ, "A")]) + } + return a.String(), nil +} + +func isAddressType(t string) bool { + return strings.EqualFold(t, "A") || strings.EqualFold(t, "AAAA") +} + +func recordName(name, zone string) string { + if name == "@" { + return zone + } + return name + "." + zone +} diff --git a/pkg/config/dns_test.go b/pkg/config/dns_test.go new file mode 100644 index 0000000..2ac46aa --- /dev/null +++ b/pkg/config/dns_test.go @@ -0,0 +1,109 @@ +package config + +import ( + "strings" + "testing" +) + +func twoHosts() *FleetConfig { + return &FleetConfig{Domain: "example.com", DefaultHost: "h1", Hosts: map[string]HostConfig{ + "h1": {Address: "192.0.2.10"}, + "h2": {Address: "2001:db8::2"}, + "h3": {Address: "auto"}, + }} +} + +func TestDNSRecordsFollowTheirServicesHost(t *testing.T) { + f := twoHosts() + f.DNSRecords = []DNSRecordConfig{ + {Type: "TXT", Name: "@", Value: "hello"}, + {Type: "AAAA", Name: "db", Service: "db"}, + {Type: "CNAME", Name: "www", Value: "web.example.com.", Service: "web"}, + } + svcs := []*ServiceConfig{{Name: "web"}, {Name: "db", Host: "h2"}} + got, err := f.DNSRecordsByHost(svcs) + if err != nil { + t.Fatal(err) + } + var s []string + for _, r := range got { + s = append(s, r.Host+" "+r.Type+" "+r.Name+" "+r.Value) + } + if want := "h1 TXT @ hello|h2 AAAA db 2001:db8::2|h1 CNAME www web.example.com."; strings.Join(s, "|") != want { + t.Fatalf("got %q, want %q", strings.Join(s, "|"), want) + } + + // One host: everything is that host's, as before (and a service-tied A still resolves). + one := &FleetConfig{Domain: "example.com", Hosts: map[string]HostConfig{"only": {Address: "192.0.2.10"}}, + DNSRecords: []DNSRecordConfig{{Type: "MX", Name: "@", Value: "mx.example.com.", Priority: 10}}} + got, err = one.DNSRecordsByHost([]*ServiceConfig{{Name: "web", Routing: &RoutingConfig{Domain: "web.example.com"}}}) + if err != nil || len(got) != 1 || got[0].Host != "only" { + t.Fatalf("a single host's records are its own, and its routes add none: %+v %v", got, err) + } +} + +func TestDNSRecordsNoHostCanOwnAreRefused(t *testing.T) { + svcs := []*ServiceConfig{{Name: "web"}, {Name: "db", Host: "h2"}, {Name: "q", Host: "h3"}} + cases := map[string]struct { + records []DNSRecordConfig + svcs []*ServiceConfig + want string + }{ + "no such service": {[]DNSRecordConfig{{Type: "A", Name: "x", Service: "nope"}}, svcs, `no service "nope"`}, + "a tied wildcard": {[]DNSRecordConfig{{Type: "TXT", Name: "*", Value: "x", Service: "web"}}, svcs, "cannot be a wildcard"}, + "a value on tied A": {[]DNSRecordConfig{{Type: "A", Name: "x", Value: "192.0.2.99", Service: "web"}}, svcs, "leave value out"}, + "no address": {[]DNSRecordConfig{{Type: "A", Name: "x", Service: "q"}}, svcs, "host h3 has no IP address"}, + "wrong family": {[]DNSRecordConfig{{Type: "A", Name: "x", Service: "db"}}, svcs, "not an IPv4 (A) address"}, + "two hosts": {[]DNSRecordConfig{{Type: "TXT", Name: "x", Value: "a"}, {Type: "TXT", Name: "x", Value: "b", Service: "db"}}, svcs, "claimed by host h1 (dns_records) and host h2 (dns_records)"}, + "a CNAME across": {[]DNSRecordConfig{{Type: "CNAME", Name: "x", Value: "y.", Service: "web"}, {Type: "AAAA", Name: "x", Service: "db"}}, svcs, "a CNAME is the only record of its name"}, + "a route wildcard": {nil, []*ServiceConfig{{Name: "w", Host: "h2", Routing: &RoutingConfig{Domain: "*.example.com"}}}, "routed at the wildcard"}, + "a route at apex": {nil, []*ServiceConfig{{Name: "w", Host: "h1x", Routing: &RoutingConfig{Domain: "example.com"}}}, "the fleet's apex"}, + "a route, no addr": {nil, []*ServiceConfig{{Name: "w", Host: "h3", Routing: &RoutingConfig{Domain: "w.example.com"}}}, "host h3 has no IP address"}, + "route vs record": {[]DNSRecordConfig{{Type: "A", Name: "w", Value: "192.0.2.1"}}, []*ServiceConfig{{Name: "w", Host: "h4", Routing: &RoutingConfig{Domain: "w.example.com"}}}, "claimed by host h1 (dns_records) and host h4 (service w's route)"}, + } + for name, c := range cases { + t.Run(name, func(t *testing.T) { + f := twoHosts() + f.Hosts["h1x"] = HostConfig{Address: "192.0.2.12"} + f.Hosts["h4"] = HostConfig{Address: "192.0.2.14"} + f.DNSRecords = c.records + if _, err := f.DNSRecordsByHost(c.svcs); err == nil || !strings.Contains(err.Error(), c.want) { + t.Fatalf("want an error with %q, got %v", c.want, err) + } + }) + } +} + +// A route off the default host under the fleet's domain gets its own A record; an external route, a +// route on the default host and a route outside the zone get none. +func TestRoutesOffTheDefaultHostGetTheirOwnRecord(t *testing.T) { + f := twoHosts() + f.Hosts["h4"] = HostConfig{Address: "192.0.2.14"} + got, err := f.DNSRecordsByHost([]*ServiceConfig{ + {Name: "a", Host: "h4", Routing: &RoutingConfig{Domain: "a.example.com"}}, + {Name: "b", Host: "h4", Routing: &RoutingConfig{Domain: "*.example.com", External: true}}, + {Name: "c", Routing: &RoutingConfig{Domain: "c.example.com"}}, + {Name: "d", Host: "h4", Routing: &RoutingConfig{Domain: "d.example.org"}}, + }) + if err != nil || len(got) != 1 || got[0].Host != "h4" || got[0].Name != "a" || got[0].Value != "192.0.2.14" || got[0].Zone != "example.com" { + t.Fatalf("got %+v %v", got, err) + } +} + +func TestIncusRemoteIsChecked(t *testing.T) { + for name, c := range map[string]struct { + hosts map[string]HostConfig + want string + }{ + "local": {map[string]HostConfig{"a": {IncusRemote: "local"}}, "not the name of an Incus remote"}, + "spaces": {map[string]HostConfig{"a": {IncusRemote: "host b"}}, "not the name of an Incus remote"}, + "shared": {map[string]HostConfig{"a": {IncusRemote: "r"}, "b": {IncusRemote: "r"}}, "both have incus_remote"}, + "fine": {map[string]HostConfig{"a": {IncusRemote: "host-a"}, "b": {IncusRemote: "host-b"}}, ""}, + } { + f := &FleetConfig{Hosts: c.hosts, DefaultHost: "a"} + err := f.ValidateHosts() + if (c.want == "") != (err == nil) || (err != nil && !strings.Contains(err.Error(), c.want)) { + t.Errorf("%s: want %q, got %v", name, c.want, err) + } + } +} diff --git a/pkg/config/hosts.go b/pkg/config/hosts.go index a118779..10518f1 100644 --- a/pkg/config/hosts.go +++ b/pkg/config/hosts.go @@ -3,6 +3,7 @@ package config import ( "errors" "fmt" + "regexp" "sort" "strings" @@ -64,6 +65,20 @@ func (f *FleetConfig) ValidateHosts() error { if len(names) >= 2 && f.DefaultHost == "" { return fmt.Errorf("fleet.yml has %d hosts (%s) and no default_host: a service without `host:` must belong to exactly one of them, and with more than one host none is the obvious choice; set default_host: to one of them", len(names), strings.Join(names, ", ")) } + remoteOf := map[string]string{} + for _, name := range names { + r := f.Hosts[name].IncusRemote + if r == "" { + continue + } + if !incusRemoteRe.MatchString(r) || r == "local" { + return fmt.Errorf("hosts.%s.incus_remote %q is not the name of an Incus remote (letters, digits, dots, dashes and underscores; not \"local\", which is every host itself)", name, r) + } + if other, ok := remoteOf[r]; ok { + return fmt.Errorf("hosts.%s and hosts.%s both have incus_remote %q: a remote reaches one host", other, name, r) + } + remoteOf[r] = name + } if f.Daemon != nil { if v, ok := serveflags.Value(strings.Fields(f.Daemon.Flags), "host-name"); ok { switch { @@ -122,6 +137,9 @@ func (f *FleetConfig) DaemonHost(hostName string) (host string, filtered bool, e return hostName, true, nil } +// incusRemoteRe is the shape of an Incus remote's name that a migration accepts (see incus.ValidName). +var incusRemoteRe = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]{0,62}$`) + func listOrNone(names []string) string { if len(names) == 0 { return "none" diff --git a/pkg/engine/deployer.go b/pkg/engine/deployer.go index d68191a..7c34528 100644 --- a/pkg/engine/deployer.go +++ b/pkg/engine/deployer.go @@ -31,6 +31,9 @@ type Deployer struct { // zones they may name. dns DNSFunc dnsZoneLimit []string + // fleetServices are all the repository's services, when a plan is of the whole fleet: the DNS records + // tied to a service follow its host, whichever host's share the plan is. + fleetServices []*config.ServiceConfig // bind, when set, is mixed into a plan's hash: a digest of everything the manifest says that the // plan does not print (environment values, hook bodies, health checks), so that the hash of a // plan covers what apply would really do. See WithBindKey. diff --git a/pkg/engine/dns_per_host_test.go b/pkg/engine/dns_per_host_test.go new file mode 100644 index 0000000..5c4065a --- /dev/null +++ b/pkg/engine/dns_per_host_test.go @@ -0,0 +1,170 @@ +package engine + +import ( + "context" + "sort" + "strings" + "testing" + + "github.com/theta42/native-ops/pkg/provider" +) + +// DNS follows the host: each daemon plans the records that point at its own host, and the default host +// also those tied to no service. Two daemons never plan the same record. + +const dnsTwoHostFleet = "name: f\ndomain: example.com\ndns_provider: fake\ndefault_host: h1\n" + + "hosts:\n h1: {provider: static, address: 192.0.2.10}\n h2: {provider: static, address: 192.0.2.11, network: {ipv4_cidr: 10.0.101.0/24}}\n" + + "dns_records:\n" + + " - {type: TXT, name: \"@\", value: v=spf1 -all}\n" + // tied to nothing: h1's + " - {type: A, name: mail, service: db}\n" + // db is on h2: points at h2 + " - {type: MX, name: \"@\", value: mail.example.com., priority: 10, service: db}\n" + // h2's, value kept + " - {type: A, name: git, service: web}\n" // web is on h1 (no host:) + +var dnsTwoHostServices = map[string]string{ + "web": "name: web\nimage: gitea:latest\nrouting: {domain: web.example.com, upstream_port: 80}\n", + "db": "name: db\nimage: postgres:16\nhost: h2\n", + "app": "name: app\nimage: app:latest\nhost: h2\nrouting: {domain: app.example.com, upstream_port: 80}\n", + "ext": "name: ext\nimage: app:latest\nhost: h2\nrouting: {domain: \"*.example.com\", upstream_port: 80, external: true}\n", +} + +// planDNSOf plans host's share and returns the DNS changes it would make ("TYPE name value"). +func planDNSOf(t *testing.T, dir, host string, dns *zoneStore) (*FleetPlan, []string) { + t.Helper() + fp, err := PlanFleet(context.Background(), hostSimFor(t, host), dir, "", WithBindKey([]byte("k")), WithHostName(host), WithDNS(dns.fn(), nil)) + if err != nil { + t.Fatalf("plan %s: %v", host, err) + } + if fp.Network == nil || len(fp.Network.Blockers) > 0 { + t.Fatalf("plan %s:\n%s", host, fp.Render()) + } + var out []string + for _, c := range fp.Network.Changes { + if strings.HasPrefix(c.Kind, "dns-") { + out = append(out, c.Detail) + } + } + sort.Strings(out) + return fp, out +} + +func TestEachDaemonPlansTheDNSThatPointsAtItsHost(t *testing.T) { + dir := shareTree(t, dnsTwoHostFleet, dnsTwoHostServices) + dns := &zoneStore{zones: map[string][]provider.DNSRecord{}} + + p1, h1 := planDNSOf(t, dir, "h1", dns) + p2, h2 := planDNSOf(t, dir, "h2", dns) + want1 := []string{"A git.example.com 192.0.2.10", "TXT example.com v=spf1 -all"} + want2 := []string{"A app.example.com 192.0.2.11", "A mail.example.com 192.0.2.11", "MX example.com mail.example.com. priority 10"} + if strings.Join(h1, "|") != strings.Join(want1, "|") { + t.Errorf("h1 plans %q, want %q", h1, want1) + } + if strings.Join(h2, "|") != strings.Join(want2, "|") { + t.Errorf("h2 plans %q, want %q", h2, want2) + } + + // No record is planned by both: the same type and name never appears in both shares. + seen := map[string]string{} + for host, recs := range map[string][]string{"h1": h1, "h2": h2} { + for _, r := range recs { + f := strings.Fields(r) + key := f[0] + " " + f[1] + if other, ok := seen[key]; ok { + t.Fatalf("%s is planned by %s and %s", key, other, host) + } + seen[key] = host + } + } + + // Each says which host does the others. + n1, n2 := strings.Join(p1.Network.Notes, "\n"), strings.Join(p2.Network.Notes, "\n") + if !strings.Contains(n1, "host h2's daemon plans and applies A mail.example.com, MX example.com, A app.example.com") { + t.Errorf("h1 should name h2's records:\n%s", p1.Render()) + } + if !strings.Contains(n2, "host h1's daemon plans and applies TXT example.com, A git.example.com") { + t.Errorf("h2 should name h1's records:\n%s", p2.Render()) + } +} + +// Plan and apply on each host, then nothing is left on either; and neither daemon writes the other's. +func TestPerHostDNSIsAppliedAndThenSettled(t *testing.T) { + dir := shareTree(t, dnsTwoHostFleet, dnsTwoHostServices) + dns := &zoneStore{zones: map[string][]provider.DNSRecord{}} + for _, host := range []string{"h2", "h1"} { + fp, _ := planDNSOf(t, dir, host, dns) + before := dns.writes + sim := hostSimFor(t, host) + d := newTestDeployer(sim) + d.SetDNS(dns.fn(), nil) + if err := d.ApplyPlan(context.Background(), dir, fp); err != nil { + t.Fatalf("apply %s: %v", host, err) + } + if host == "h2" && dns.writes-before != 3 { + t.Fatalf("h2 writes its 3 records, wrote %d: %+v", dns.writes-before, dns.zones) + } + if host == "h1" && dns.writes-before != 2 { + t.Fatalf("h1 writes its 2 records, wrote %d: %+v", dns.writes-before, dns.zones) + } + } + for _, host := range []string{"h1", "h2"} { + if _, again := planDNSOf(t, dir, host, dns); len(again) != 0 { + t.Fatalf("%s: once applied, nothing is left to do: %q", host, again) + } + } + if len(dns.zones["example.com"]) != 5 { + t.Fatalf("the zone holds both hosts' records: %+v", dns.zones) + } +} + +// A record that no single host can own blocks the plan (and validate refuses it). +func TestDNSNoSingleHostCanOwnIsRefused(t *testing.T) { + cases := map[string]struct{ fleet, want string }{ + "a wildcard tied to a service": {" - {type: A, name: \"*.db\", service: db}\n", "cannot be a wildcard"}, + "two hosts claim one name": {" - {type: A, name: x, service: db}\n - {type: A, name: x, service: web}\n", "claimed by host h2"}, + "the apex off the default": {" - {type: A, name: \"@\", service: db}\n", "claimed by host h1 (reconcile, for domain:) and host h2"}, + } + for name, c := range cases { + t.Run(name, func(t *testing.T) { + fleet := strings.SplitAfter(dnsTwoHostFleet, "dns_records:\n")[0] + c.fleet + dir := shareTree(t, fleet, map[string]string{"web": dnsTwoHostServices["web"], "db": dnsTwoHostServices["db"]}) + for _, host := range []string{"h1", "h2"} { + fp, err := PlanFleet(context.Background(), hostSimFor(t, host), dir, "", WithHostName(host)) + if err != nil { + t.Fatal(err) + } + if !fp.Blocked() || !strings.Contains(strings.Join(fp.Network.Blockers, "\n"), c.want) { + t.Fatalf("%s: the plan must be blocked with %q:\n%s", host, c.want, fp.Render()) + } + } + if _, err := NewReconciler(dir, nil).Validate(context.Background()); err == nil || !strings.Contains(err.Error(), c.want) { + t.Fatalf("validate must refuse it with %q: %v", c.want, err) + } + }) + } + // A wildcard route on a host other than the default one. + dir := shareTree(t, strings.SplitAfter(dnsTwoHostFleet, "dns_records:\n")[0]+" - {type: TXT, name: t, value: x}\n", + map[string]string{"w": "name: w\nimage: app:latest\nhost: h2\nrouting: {domain: \"*.apps.example.com\", upstream_port: 80}\n"}) + if _, err := NewReconciler(dir, nil).Validate(context.Background()); err == nil || !strings.Contains(err.Error(), "wildcard *.apps.example.com") { + t.Fatalf("a wildcard route off the default host must be refused: %v", err) + } +} + +// validate reports each host's share. +func TestValidateReportsEachHostsShare(t *testing.T) { + dir := shareTree(t, dnsTwoHostFleet, dnsTwoHostServices) + s, err := NewReconciler(dir, nil).Validate(context.Background()) + if err != nil { + t.Fatal(err) + } + if len(s.PerHost) != 2 || s.PerHost[0].Name != "h1" || !s.PerHost[0].Default || s.PerHost[1].Name != "h2" { + t.Fatalf("got %+v", s.PerHost) + } + if got := strings.Join(s.PerHost[1].Services, ","); got != "app,db,ext" { + t.Errorf("h2's services: %s", got) + } + if got := strings.Join(s.PerHost[1].DNS, "|"); got != "A mail.example.com 192.0.2.11|MX example.com mail.example.com.|A app.example.com 192.0.2.11" { + t.Errorf("h2's DNS: %s", got) + } + if got := strings.Join(s.PerHost[0].DNS, "|"); got != "TXT example.com v=spf1 -all|A git.example.com 192.0.2.10" { + t.Errorf("h1's DNS: %s", got) + } +} diff --git a/pkg/engine/host_share_test.go b/pkg/engine/host_share_test.go index 2bf3d87..3822ae7 100644 --- a/pkg/engine/host_share_test.go +++ b/pkg/engine/host_share_test.go @@ -285,7 +285,7 @@ func TestApplyRefusesAPlanThatIsNotThisHostsShare(t *testing.T) { } } -func TestOnlyTheDefaultHostDoesTheFleetsDNSAndTheEdgeHostItsCaddyfile(t *testing.T) { +func TestTheDefaultHostDoesTheUntiedDNSAndTheEdgeHostItsCaddyfile(t *testing.T) { fleet := twoHostFleet + "dns_provider: fake\ndns_records:\n - {zone: example.com, type: TXT, name: \"@\", value: hello}\n" dir := shareTree(t, fleet, map[string]string{ "edge": "name: edge\nimage: edge:latest\nhost: h1\n", @@ -298,8 +298,8 @@ func TestOnlyTheDefaultHostDoesTheFleetsDNSAndTheEdgeHostItsCaddyfile(t *testing t.Fatal(err) } - // h2 has no edge instance: the Caddyfile is h1's to apply, not a blocker on h2; and dns_records are - // the default host's. + // h2 has no edge instance: the Caddyfile is h1's to apply, not a blocker on h2; and a dns_records entry + // tied to no service is the default host's. sim2 := hostSimFor(t, "h2") delete(sim2.ctrs, "edge") p2 := planShare(t, sim2, dir, "h2") @@ -307,13 +307,13 @@ func TestOnlyTheDefaultHostDoesTheFleetsDNSAndTheEdgeHostItsCaddyfile(t *testing t.Fatalf("h2's plan must not be blocked by h1's edge:\n%s", p2.Render()) } notes := strings.Join(p2.Network.Notes, "\n") - if !strings.Contains(notes, "applied by host h1's daemon") || !strings.Contains(notes, "default host, h1") { + if !strings.Contains(notes, "applied by host h1's daemon") || !strings.Contains(notes, "host h1's daemon plans and applies TXT example.com") { t.Fatalf("h2 should say h1 does these:\n%s", p2.Render()) } // h1 (the default host) plans the records itself (here: without a provider, the usual note). p1 := planShare(t, newHostSim(t), dir, "h1") - if strings.Contains(strings.Join(p1.Network.Notes, "\n"), "default host, h1") { + if strings.Contains(strings.Join(p1.Network.Notes, "\n"), "dns: host") { t.Fatalf("h1 is the default host and plans the records:\n%s", p1.Render()) } } diff --git a/pkg/engine/network.go b/pkg/engine/network.go index be1cdfd..6778a0b 100644 --- a/pkg/engine/network.go +++ b/pkg/engine/network.go @@ -86,7 +86,7 @@ func (d *Deployer) PlanNetwork(ctx context.Context, fleet *config.FleetConfig, c if err := d.planEdgeCaddyfile(ctx, n, configDir, services); err != nil { return nil, err } - d.planDNS(ctx, n, fleet) + d.planDNS(ctx, n, fleet, services) if d.bind != nil { b, _ := json.Marshal(struct{ Caddyfile string }{n.edgeCaddyfile}) n.bind = d.bind(b) @@ -174,23 +174,45 @@ func (d *Deployer) planEdgeCaddyfile(ctx context.Context, n *NetworkPlan, config return nil } -// planDNS plans fleet.yml's dns_records against the provider. It only ever creates or updates: a record the -// manifest does not mention is never deleted (mail and verification records live beside these). -func (d *Deployer) planDNS(ctx context.Context, n *NetworkPlan, fleet *config.FleetConfig) { - if len(fleet.DNSRecords) == 0 { +// planDNS plans the fleet's DNS records against the provider: fleet.yml's dns_records, and the records +// of the routes of services off the default host (see config.FleetConfig.DNSRecordsByHost). In a fleet of +// several hosts it plans only the records that point at this daemon's host (and, on the default host, those +// tied to no service), and notes which host does each of the others, so two daemons never write the same +// record. It only ever creates or updates: a record the manifest does not mention is never deleted (mail +// and verification records live beside these). +func (d *Deployer) planDNS(ctx context.Context, n *NetworkPlan, fleet *config.FleetConfig, services []*config.ServiceConfig) { + if d.fleetServices != nil { + services = d.fleetServices + } + all, err := fleet.DNSRecordsByHost(services) + if err != nil { + n.block("dns_records: %v", err) return } - // dns_records are the fleet's, not a host's: in a fleet of several hosts only the default host's - // daemon plans and applies them, so two daemons never write the same zone. - if s := d.share; s != nil && s.host != s.defaultHost { - n.note("dns_records are planned and applied by the daemon of the default host, %s", s.defaultHost) + if len(all) == 0 { return } - byZone, err := fleet.DNSRecordsByZone() - if err != nil { - n.block("dns_records: %v", err) + mine, others := all, map[string][]string{} + if s := d.share; s != nil { + mine = nil + for _, r := range all { + if r.Host == s.host { + mine = append(mine, r) + continue + } + others[r.Host] = append(others[r.Host], r.Type+" "+dnsName(r.Name, r.Zone)) + } + } + for _, h := range sortedZones(others) { + n.note("dns: host %s's daemon plans and applies %s (they point at host %s)", h, strings.Join(others[h], ", "), h) + } + if len(mine) == 0 { return } + byZone := map[string][]config.DNSRecordConfig{} + for _, r := range mine { + byZone[r.Zone] = append(byZone[r.Zone], r.DNSRecordConfig) + } zones := sortedZones(byZone) if fleet.Domain != "" { for _, r := range byZone[strings.ToLower(fleet.Domain)] { @@ -244,12 +266,15 @@ func (d *Deployer) planDNS(ctx context.Context, n *NetworkPlan, fleet *config.Fl } } -func dnsDetail(zone string, r provider.DNSRecord) string { - name := r.Name + "." + zone - if r.Name == "@" { - name = zone +func dnsName(name, zone string) string { + if name == "@" { + return zone } - s := fmt.Sprintf("%s %s %s", r.Type, name, r.Value) + return name + "." + zone +} + +func dnsDetail(zone string, r provider.DNSRecord) string { + s := fmt.Sprintf("%s %s %s", r.Type, dnsName(r.Name, zone), r.Value) if r.Priority > 0 { s += fmt.Sprintf(" priority %d", r.Priority) } diff --git a/pkg/engine/plan.go b/pkg/engine/plan.go index 6ea7431..d6a4205 100644 --- a/pkg/engine/plan.go +++ b/pkg/engine/plan.go @@ -568,7 +568,7 @@ var ErrBadConfig = errors.New("invalid configuration") // // When fleet.yml names several hosts, the plan is this daemon's share (WithHostName): the services of // the other hosts are listed as skipped and never planned against this host, and the fleet-wide work -// that another host's daemon does (dns_records: the default host's) is left to it. Without a host name +// that another host's daemon does (the DNS records that point at another host) is left to it. Without a host name // such a fleet is refused, rather than every host's services being planned here. func PlanFleet(ctx context.Context, exec remote.Executor, configDir, service string, opts ...PlanOption) (*FleetPlan, error) { fleet, err := config.LoadFleetConfig(configDir) @@ -588,6 +588,9 @@ func PlanFleet(ctx context.Context, exec remote.Executor, configDir, service str return nil, err } d.share = share + if service == "" { + d.fleetServices = services + } fp := &FleetPlan{Services: []*ServicePlan{}} if share != nil { fp.Host = share.host @@ -632,7 +635,7 @@ func HostServices(fleet *config.FleetConfig, services []*config.ServiceConfig, h // hostShare is what a plan of one host's share knows about the rest of the fleet. type hostShare struct { host string // the host this daemon is - defaultHost string // fleet.yml's default host: its daemon does the fleet-wide work (dns_records) + defaultHost string // fleet.yml's default host: its daemon writes the DNS records tied to no service others map[string]string // the services of other hosts, by name, with their host } diff --git a/pkg/engine/reconcile_test.go b/pkg/engine/reconcile_test.go new file mode 100644 index 0000000..17a94db --- /dev/null +++ b/pkg/engine/reconcile_test.go @@ -0,0 +1,260 @@ +package engine + +import ( + "bytes" + "context" + "errors" + "flag" + "fmt" + "io" + "log" + "os" + "path/filepath" + "sort" + "strings" + "sync" + "testing" + "time" + + "github.com/theta42/native-ops/pkg/config" + "github.com/theta42/native-ops/pkg/provider" + "github.com/theta42/native-ops/pkg/remote" +) + +var updateGolden = flag.Bool("update", false, "rewrite the golden files in testdata/") + +// hostExec is a recording fake for one host's SSH session: every command it is asked to run, in order. +type hostExec struct { + mu sync.Mutex + host string + cmds []string +} + +func (h *hostExec) Run(_ context.Context, cmd string) (string, error) { + h.mu.Lock() + defer h.mu.Unlock() + h.cmds = append(h.cmds, cmd) + return "", nil +} +func (h *hostExec) RunWithInput(ctx context.Context, cmd string, _ io.Reader) (string, error) { + return h.Run(ctx, cmd) +} +func (h *hostExec) WriteFile(context.Context, string, []byte, os.FileMode) error { return nil } +func (h *hostExec) Close() error { return nil } + +// recDNS records every zone sync. +type recDNS struct { + provider.DNSProvider + syncs []string + err error +} + +func (f *recDNS) SyncRecords(_ context.Context, zone string, rs []provider.DNSRecord) error { + var parts []string + for _, r := range rs { + parts = append(parts, r.Type+" "+r.Name+" "+r.Value) + } + f.syncs = append(f.syncs, zone+": "+strings.Join(parts, ", ")) + return f.err +} + +// reconcileWorld is a Reconciler wired to fakes: one recording executor per host address, the ones that +// refuse SSH, and a recording DNS provider. Its log is captured. +type reconcileWorld struct { + r *Reconciler + local *hostExec + hosts map[string]*hostExec // by address + refuse map[string]bool // addresses whose SSH never answers + dns *recDNS + dialLog []string +} + +func newReconcileWorld(t *testing.T, dir string) *reconcileWorld { + t.Helper() + w := &reconcileWorld{local: &hostExec{host: "local"}, hosts: map[string]*hostExec{}, refuse: map[string]bool{}, dns: &recDNS{}} + r := NewReconciler(dir, w.local) + r.sshCreds = func() ([]byte, string, bool) { return []byte("test-key"), "ssh-ed25519 AAAA test", false } + r.dialSSH = func(host string, port int, user string, _ []byte) (remote.Executor, error) { + w.dialLog = append(w.dialLog, fmt.Sprintf("dial %s@%s:%d", user, host, port)) + if w.refuse[host] { + return nil, errors.New("connection refused") + } + if w.hosts[host] == nil { + w.hosts[host] = &hostExec{host: host} + } + return w.hosts[host], nil + } + r.waitSSH = func(context.Context, string, int, time.Duration) error { return nil } + r.sshRetryDelay = 0 + r.dnsFor = func(*config.FleetConfig) (provider.DNSProvider, error) { return w.dns, nil } + w.r = r + return w +} + +// run reconciles and returns everything observable: the log, the error, the SSH dials, the DNS syncs and +// the commands run on each host. +func (w *reconcileWorld) run(t *testing.T) string { + t.Helper() + var buf bytes.Buffer + flags, out := log.Flags(), log.Writer() + log.SetFlags(0) + log.SetOutput(&buf) + err := w.r.Reconcile(context.Background()) + log.SetFlags(flags) + log.SetOutput(out) + + var sb strings.Builder + sb.WriteString("--- log\n") + sb.WriteString(strings.ReplaceAll(buf.String(), w.r.configDir, "")) + fmt.Fprintf(&sb, "--- error\n%v\n", err) + sb.WriteString("--- ssh\n") + for _, d := range w.dialLog { + sb.WriteString(d + "\n") + } + sb.WriteString("--- dns\n") + for _, s := range w.dns.syncs { + sb.WriteString(s + "\n") + } + execs := []*hostExec{w.local} + var addrs []string + for a := range w.hosts { + addrs = append(addrs, a) + } + sort.Strings(addrs) + for _, a := range addrs { + execs = append(execs, w.hosts[a]) + } + for _, e := range execs { + fmt.Fprintf(&sb, "--- commands on %s\n", e.host) + for _, c := range e.cmds { + sb.WriteString(c + "\n") + } + } + return sb.String() +} + +func checkGolden(t *testing.T, name, got string) { + t.Helper() + path := filepath.Join("testdata", name) + if *updateGolden { + if err := os.WriteFile(path, []byte(got), 0o644); err != nil { + t.Fatal(err) + } + return + } + want, err := os.ReadFile(path) + if err != nil { + t.Fatalf("%v (run with -update to create it)", err) + } + if got != string(want) { + t.Fatalf("%s differs from the golden output.\n--- got\n%s\n--- want\n%s", name, got, want) + } +} + +// A single-host fleet reconciles exactly as it did when reconcile kept one primaryHostIP: the golden +// files were generated from main before the per-host loop (with only the fakes wired in). +func TestReconcileASingleHostIsUnchanged(t *testing.T) { + const fleet = "name: f\ndomain: example.com\ndns_provider: fake\nhosts:\n only: {provider: static, address: 198.51.100.10, ssh_user: ops, ssh_port: 2222}\n" + cases := []struct { + name, fleet string + deploy bool + dnsErr error + refuse bool + }{ + {name: "ssh", fleet: fleet}, + {name: "ssh-deploy-services", fleet: fleet, deploy: true}, + {name: "dns-fails", fleet: fleet, dnsErr: errors.New("403 forbidden")}, + {name: "ssh-fails", fleet: fleet, refuse: true}, + {name: "local", fleet: "name: f\ndomain: example.com\ndns_provider: fake\nhosts:\n only: {provider: static, address: 127.0.0.1}\n", deploy: true}, + {name: "no-address", fleet: "name: f\nhosts:\n only: {provider: proxmox}\n", deploy: true}, + {name: "no-hosts", fleet: "name: f\n", deploy: true}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + dir := shareTree(t, c.fleet, nil) + w := newReconcileWorld(t, dir) + w.r.DeployServices = c.deploy + w.dns.err = c.dnsErr + if c.refuse { + w.refuse["198.51.100.10"] = true + } + checkGolden(t, "reconcile-single-host-"+c.name+".golden", w.run(t)) + }) + } +} + +const reconcileTwoHosts = "name: f\ndomain: example.com\ndns_provider: fake\ndefault_host: zeta\n" + + "hosts:\n" + + " zeta: {provider: static, address: 198.51.100.20}\n" + + " alpha: {provider: static, address: 198.51.100.10, ssh_user: ops, ssh_port: 2222, network: {ipv4_cidr: 10.0.101.0/24}}\n" + +// Each host is reconciled on its own, in the order of their names, with its own SSH user, port and +// bridge; the fleet domain points at the default host whatever order the hosts come in. +func TestReconcileEachHostOnItsOwn(t *testing.T) { + for i := 0; i < 5; i++ { // map order must not matter + w := newReconcileWorld(t, shareTree(t, reconcileTwoHosts, nil)) + out := w.run(t) + if !strings.Contains(out, "--- error\n\n") { + t.Fatalf("both hosts reconcile:\n%s", out) + } + if got := strings.Join(w.dialLog, "|"); got != "dial ops@198.51.100.10:2222|dial root@198.51.100.20:22" { + t.Fatalf("each host on its own SSH user and port, in name order: %s", got) + } + if got := strings.Join(w.dns.syncs, "|"); got != "example.com: A @ 198.51.100.20, A * 198.51.100.20" { + t.Fatalf("the domain points at the default host zeta, not the last one reconciled: %s", got) + } + a, z := strings.Join(w.hosts["198.51.100.10"].cmds, "\n"), strings.Join(w.hosts["198.51.100.20"].cmds, "\n") + if !strings.Contains(a, "10.0.101.1/24") || strings.Contains(a, "10.0.100.1/24") || !strings.Contains(z, "10.0.100.1/24") || strings.Contains(z, "10.0.101.1/24") { + t.Fatalf("each host is bootstrapped with its own bridge:\nalpha:\n%s\nzeta:\n%s", a, z) + } + if len(w.local.cmds) != 0 { + t.Fatalf("nothing runs on the machine reconcile runs on: %q", w.local.cmds) + } + } +} + +// A host that fails is reported, and the others are still reconciled. +func TestReconcileAHostThatFailsDoesNotStopTheOthers(t *testing.T) { + w := newReconcileWorld(t, shareTree(t, reconcileTwoHosts, nil)) + w.refuse["198.51.100.10"] = true // alpha, reconciled first + out := w.run(t) + if !strings.Contains(out, "1 of 2 hosts failed: host alpha: init SSH executor to 198.51.100.10: connection refused") { + t.Fatalf("the run fails naming alpha:\n%s", out) + } + if !strings.Contains(out, "Host alpha failed: init SSH executor") || !strings.Contains(out, "the other hosts carry on") { + t.Fatalf("the log says alpha failed and the others carry on:\n%s", out) + } + if z := w.hosts["198.51.100.20"]; z == nil || len(z.cmds) == 0 { + t.Fatalf("zeta is still bootstrapped:\n%s", out) + } + if len(w.dns.syncs) != 1 { + t.Fatalf("the default host zeta is up, so its DNS is synced: %q", w.dns.syncs) + } + + // The default host failing (sorted last): alpha is still bootstrapped, and the run names zeta. + w = newReconcileWorld(t, shareTree(t, reconcileTwoHosts, nil)) + w.refuse["198.51.100.20"] = true + out = w.run(t) + if !strings.Contains(out, "1 of 2 hosts failed: host zeta: init SSH executor to 198.51.100.20") || len(w.hosts["198.51.100.10"].cmds) == 0 { + t.Fatalf("alpha is bootstrapped and zeta named:\n%s", out) + } + + // Both failing: both are named. + w = newReconcileWorld(t, shareTree(t, reconcileTwoHosts, nil)) + w.refuse["198.51.100.10"], w.refuse["198.51.100.20"] = true, true + out = w.run(t) + if !strings.Contains(out, "2 of 2 hosts failed: host alpha: ") || !strings.Contains(out, "host zeta: init SSH executor to 198.51.100.20") { + t.Fatalf("both hosts are named:\n%s", out) + } +} + +// A DNS provider that cannot be set up fails the run at the end with several hosts, after every host was +// brought up (with one host it stops the run where it is, as it always did: see the golden files). +func TestReconcileSeveralHostsDNSFailureIsReportedAtTheEnd(t *testing.T) { + w := newReconcileWorld(t, shareTree(t, reconcileTwoHosts, nil)) + w.r.dnsFor = func(*config.FleetConfig) (provider.DNSProvider, error) { return nil, errors.New("no DNS token") } + out := w.run(t) + if !strings.Contains(out, "hosts reconciled, but DNS sync failed: no DNS token") || len(w.hosts) != 2 { + t.Fatalf("got:\n%s", out) + } +} diff --git a/pkg/engine/reconciler.go b/pkg/engine/reconciler.go index 4353ea1..4cea5f9 100644 --- a/pkg/engine/reconciler.go +++ b/pkg/engine/reconciler.go @@ -5,6 +5,7 @@ import ( "crypto/ed25519" "crypto/rand" "encoding/pem" + "errors" "fmt" "log" "net" @@ -36,6 +37,14 @@ type Reconciler struct { hostMgr *HostManager // DeployServices also deploys every service directly, bypassing the daemon's approval gate. DeployServices bool + + // The ways reconcile reaches the world, replaced by tests: SSH credentials, an SSH session to a host, + // waiting for a host's SSH port, the pause between SSH attempts, and the fleet's DNS provider. + sshCreds func() (priv []byte, pub string, generated bool) + dialSSH func(host string, port int, user string, key []byte) (remote.Executor, error) + waitSSH func(ctx context.Context, host string, port int, timeout time.Duration) error + sshRetryDelay time.Duration + dnsFor func(fleet *config.FleetConfig) (provider.DNSProvider, error) } func NewReconciler(configDir string, exec remote.Executor) *Reconciler { @@ -44,6 +53,32 @@ func NewReconciler(configDir string, exec remote.Executor) *Reconciler { exec: exec, deployer: NewDeployer(exec), hostMgr: NewHostManager(), + sshCreds: LoadSSHCredentials, + dialSSH: func(host string, port int, user string, key []byte) (remote.Executor, error) { + return remote.NewSSHExecutor(host, port, user, key) + }, + waitSSH: waitForSSH, + sshRetryDelay: 3 * time.Second, + dnsFor: fleetDNSProvider(configDir), + } +} + +// fleetDNSProvider is the DNS provider fleet.yml's dns_provider names: DigitalOcean, or a script plugin in +// the config repo. +func fleetDNSProvider(configDir string) func(fleet *config.FleetConfig) (provider.DNSProvider, error) { + return func(fleet *config.FleetConfig) (provider.DNSProvider, error) { + if fleet.DNSProvider == "digitalocean" || fleet.DNSProvider == "do" { + do, err := digitalocean.New("") + if err != nil { + return nil, fmt.Errorf("DO DNS init: %w", err) + } + return do, nil + } + p, err := plugin.NewScriptDNSProvider(fleet.DNSProvider, configDir) + if err != nil { + return nil, fmt.Errorf("custom DNS plugin init: %w", err) + } + return p, nil } } @@ -55,6 +90,18 @@ type PlanSummary struct { Hosts []string Services []string Templates []string + // PerHost is what each host's daemon plans and applies, in the order of the hosts' names: its services + // and the DNS records that point at it. Empty when fleet.yml has no hosts:. + PerHost []HostSummary +} + +// HostSummary is one host's share of the fleet. +type HostSummary struct { + Name string + Address string + Default bool // the default host: services without host: and DNS records tied to no service + Services []string // sorted + DNS []string // "TYPE name value", as fleet.yml declares them (dns_records first, then routes) } // Validate loads and validates all configuration files and returns a PlanSummary. @@ -78,9 +125,8 @@ func (r *Reconciler) Validate(ctx context.Context) (*PlanSummary, error) { DNSProvider: fleet.DNSProvider, } - for hostName := range fleet.Hosts { - summary.Hosts = append(summary.Hosts, hostName) - } + summary.Hosts = fleet.HostNames() + var services []*config.ServiceConfig // Validate services servicesDir := filepath.Join(r.configDir, "services") @@ -99,10 +145,36 @@ func (r *Reconciler) Validate(ctx context.Context) (*PlanSummary, error) { return nil, fmt.Errorf("invalid service %s: %w", svcPath, err) } summary.Services = append(summary.Services, svc.Name) + if svc.Name == "" { + svc.Name = e.Name() + } + services = append(services, svc) } } } + // Each host's share: its services, and the DNS records that point at it (refusing a record no host can + // own alone). + records, err := fleet.DNSRecordsByHost(services) + if err != nil { + return nil, fmt.Errorf("fleet.yml dns: %w", err) + } + for _, name := range summary.Hosts { + hs := HostSummary{Name: name, Address: fleet.Hosts[name].Address, Default: name == fleet.DefaultHostName()} + for _, svc := range services { + if fleet.HostOf(svc) == name { + hs.Services = append(hs.Services, svc.Name) + } + } + sort.Strings(hs.Services) + for _, r := range records { + if r.Host == name { + hs.DNS = append(hs.DNS, strings.TrimSpace(r.Type+" "+dnsName(r.Name, r.Zone)+" "+r.Value)) + } + } + summary.PerHost = append(summary.PerHost, hs) + } + // Validate templates templatesDir := filepath.Join(r.configDir, "templates") if entries, err := os.ReadDir(templatesDir); err == nil { @@ -209,7 +281,37 @@ func waitForSSH(ctx context.Context, host string, port int, timeout time.Duratio return fmt.Errorf("timed out waiting for SSH port %s", addr) } -// Reconcile executes Level 0 host verification/creation, DNS sync, and Level 1 service deployment. +// hostRun is one host's reconcile: what it found, and how it failed. +type hostRun struct { + name string + ip string // the host's public address; "" when it has none (not provisioned by reconcile, no address:) + user string + port int + err error + // net is the host's bridge; exec and deployer reach the host (over SSH once it was bootstrapped). + net config.NetworkConfig + exec remote.Executor + deployer *Deployer +} + +// sshAccess is the SSH user and port a host is reached on: its own, else root and 22. +func sshAccess(h config.HostConfig) (string, int) { + user, port := "root", 22 + if h.SSHUser != "" { + user = h.SSHUser + } + if h.SSHPort > 0 { + port = h.SSHPort + } + return user, port +} + +// Reconcile brings each of fleet.yml's hosts up on its own, in the order of their names: Level 0 (the host +// exists: provisioned with its daemon from cloud-init, or adopted at its address), then the fleet's DNS, +// then each host's Incus runtime over SSH. With several hosts a host that fails is reported and the +// others carry on; the run fails at the end, naming every host that failed. The fleet's `domain:` (its +// apex and wildcard) points at the default host. Services are deployed by each host's daemon, or here +// with the break-glass DeployServices (a single host only). func (r *Reconciler) Reconcile(ctx context.Context) error { log.Printf("==> [GitOps] Starting complete fleet reconciliation from %s\n", r.configDir) @@ -224,200 +326,93 @@ func (r *Reconciler) Reconcile(ctx context.Context) error { return fmt.Errorf("--deploy-services deploys every service to one host, and fleet.yml has %d hosts; deploy through each host's daemon (a deploy tag), which applies only that host's services", len(fleet.Hosts)) } - privKeyPEM, pubKeyStr, generatedKey := LoadSSHCredentials() - var primaryHostIP, primaryHostName string - var hostSSHUser string = "root" - var hostSSHPort int = 22 - - // 1. Level 0: Reconcile Cloud / Hypervisor Hosts - for hostName, hostCfg := range fleet.Hosts { - log.Printf("==> [GitOps] Reconciling host: %s (provider=%s)\n", hostName, hostCfg.Provider) - - if hostCfg.SSHUser != "" { - hostSSHUser = hostCfg.SSHUser - } - if hostCfg.SSHPort > 0 { - hostSSHPort = hostCfg.SSHPort - } - - if hostCfg.Address != "" && hostCfg.Address != "auto" { - primaryHostIP = hostCfg.Address - primaryHostName = hostName - continue + privKeyPEM, pubKeyStr, generatedKey := r.sshCreds() + names := fleet.HostNames() + several := len(names) >= 2 + // failed reports a host's failure. With one host it is the run's error, as it always was; with several + // the other hosts carry on and the run fails at the end. + failed := func(h *hostRun, err error) error { + h.err = err + if !several { + return err } + log.Printf(" Host %s failed: %v (the other hosts carry on; the run will fail at the end)\n", h.name, err) + return nil + } - // Query provider to see if host exists - if hostCfg.Provider == "digitalocean" || hostCfg.Provider == "do" { - do, err := digitalocean.New("") - if err != nil { - return fmt.Errorf("digitalocean provider init: %w", err) - } - hosts, err := do.ListHosts(ctx) - if err != nil { - return fmt.Errorf("list hosts: %w", err) - } - existing, action, err := classifyHost(hosts, hostName) - if err != nil { + // 1. Level 0: each host exists. + runs := make([]*hostRun, 0, len(names)) + for _, name := range names { + hostCfg := fleet.Hosts[name] + h := &hostRun{name: name} + h.user, h.port = sshAccess(hostCfg) + runs = append(runs, h) + log.Printf("==> [GitOps] Reconciling host: %s (provider=%s)\n", name, hostCfg.Provider) + if h.ip, err = r.provisionHost(ctx, fleet, name, hostCfg, h.user, h.port, privKeyPEM, pubKeyStr, generatedKey); err != nil { + if err := failed(h, err); err != nil { return err } - switch action { - case hostUse: - primaryHostIP = existing.PublicIP - primaryHostName = hostName - log.Printf(" Host %s already active at IP %s\n", hostName, primaryHostIP) - case hostWait: - log.Printf(" Host %s (id %s) is still provisioning; waiting for it instead of creating another\n", hostName, existing.ID) - h, err := waitHostActive(ctx, do, existing.ID, 5*time.Minute, 5*time.Second) - if err != nil { - return err - } - primaryHostIP = h.PublicIP - primaryHostName = hostName - } - - // A host that exists must be reachable with our credentials. If it is not, - // stop and say so: reconcile never destroys or rebuilds a host on its own. - if primaryHostIP != "" && len(privKeyPEM) > 0 { - testExec, testErr := remote.NewSSHExecutor(primaryHostIP, hostSSHPort, hostSSHUser, privKeyPEM) - if testErr == nil { - if _, err := testExec.Run(ctx, "true"); err != nil { - testErr = err - } - testExec.Close() - } - if testErr != nil { - return fmt.Errorf("host %s (%s) exists but SSH verification failed: %v. Not destroying or re-provisioning it automatically (it may hold data): fix the SSH key or user, or remove the host yourself if you want it rebuilt", hostName, primaryHostIP, testErr) - } - } - - // Not found: provision it - if primaryHostIP == "" { - log.Printf(" Host %s not found. Provisioning with cloud-init...\n", hostName) - spec := config.HostSpec{ - Name: hostName, - Provider: "digitalocean", - Size: fleet.Providers.DigitalOcean.DefaultSize, - Region: fleet.Providers.DigitalOcean.Region, - } - // The cloud-init opens the firewall for this host's own bridge, and, with fleet.yml's daemon - // section, installs the daemon. - var di *DaemonInstall - if fleet.Daemon != nil { - if di, err = DaemonInstallFor(fleet.Daemon); err != nil { - return fmt.Errorf("provision host %s: daemon: %w", hostName, err) - } - // With several hosts each daemon must know which it is; its unit carries that - // (a deploy's daemon.flags keep it, see pkg/serveflags). - if len(fleet.Hosts) >= 2 { - di.ServeFlags = strings.TrimSpace(di.ServeFlags + " --host-name " + hostName) - if err := di.Validate(); err != nil { - return fmt.Errorf("provision host %s: daemon: %w", hostName, err) - } - } - } - ud, err := GenerateCloudInitUserDataFor(pubKeyStr, fleet.HostNetwork(hostName), di) - if err != nil { - return fmt.Errorf("provision host %s: %w", hostName, err) - } - spec.UserData = ud - if di != nil { - log.Printf(" The host's cloud-init installs the native-ops daemon %s\n", fleet.Daemon.Version) - } - // A throwaway key is acceptable here: this run uses it to SSH in. But a failure to - // register the key must stop the run BEFORE a droplet nobody can log in to is created. - if err := r.hostMgr.PrepareAccess(ctx, &spec, pubKeyStr, generatedKey, true); err != nil { - return fmt.Errorf("provision host %s: %w", hostName, err) - } - newHost, err := r.hostMgr.CreateHost(ctx, spec) - if err != nil { - return fmt.Errorf("provision host %s: %w", hostName, err) - } - primaryHostIP = newHost.PublicIP - primaryHostName = hostName - } } } - // 2. Sync DNS. A failure is remembered and returned at the end: services can - // still be deployed, but the run must not report success with stale DNS. + // 2. Sync the fleet domain's DNS to the default host. A failure is remembered and returned at the end: + // the hosts can still be brought up, but the run must not report success with stale DNS. var dnsErr error - if primaryHostIP != "" && fleet.Domain != "" { - log.Printf("==> [GitOps] Syncing DNS records for %s -> %s\n", fleet.Domain, primaryHostIP) - var dnsProv provider.DNSProvider - if fleet.DNSProvider == "digitalocean" || fleet.DNSProvider == "do" { - do, err := digitalocean.New("") - if err != nil { - return fmt.Errorf("DO DNS init: %w", err) - } - dnsProv = do - } else { - p, err := plugin.NewScriptDNSProvider(fleet.DNSProvider, r.configDir) - if err != nil { - return fmt.Errorf("custom DNS plugin init: %w", err) - } - dnsProv = p + dnsHost := hostRunOf(runs, fleet.DefaultHostName()) + if several && fleet.Domain != "" && dnsHost != nil && dnsHost.err != nil { + dnsErr = fmt.Errorf("%s points at the default host %s, which failed", fleet.Domain, dnsHost.name) + log.Printf("==> [GitOps] Not syncing DNS for %s: the default host %s failed\n", fleet.Domain, dnsHost.name) + } else if dnsHost != nil && dnsHost.ip != "" && fleet.Domain != "" { + log.Printf("==> [GitOps] Syncing DNS records for %s -> %s\n", fleet.Domain, dnsHost.ip) + dnsProv, err := r.dnsFor(fleet) + if err != nil && !several { + return err + } + if err == nil { + err = syncDNS(ctx, dnsProv, fleet.Domain, dnsHost.ip) } - if dnsErr = syncDNS(ctx, dnsProv, fleet.Domain, primaryHostIP); dnsErr != nil { + if dnsErr = err; dnsErr != nil { log.Printf(" DNS sync failed: %v (continuing with services; the run will fail at the end)\n", dnsErr) } else { log.Printf(" DNS synchronized successfully.\n") } } - // 3. Level 1: Reconcile Declarative Services - // The bridge is the host's own `network:` (fleet.yml's, or the host's override). - hostNet := fleet.HostNetwork(primaryHostName) - if primaryHostName == "" { - hostNet, _ = fleet.LocalNetwork("") - } - deployer := r.deployer - if hostNet.BridgeName != "" { - if err := deployer.SetNetwork(hostNet); err != nil { - return fmt.Errorf("host %s: %w", primaryHostName, err) - } - } - var activeExec remote.Executor = r.exec - - // If target host is remote and we have an SSH key, execute deployments over SSH - if primaryHostIP != "" && primaryHostIP != "127.0.0.1" && primaryHostIP != "localhost" && len(privKeyPEM) > 0 { - log.Printf("==> [GitOps] Connecting to host %s:%d via SSH (%s)...\n", primaryHostIP, hostSSHPort, hostSSHUser) - if err := waitForSSH(ctx, primaryHostIP, hostSSHPort, 120*time.Second); err != nil { - return fmt.Errorf("wait for host SSH: %w", err) + // 3. Level 1: each host's Incus runtime, over SSH. + for _, h := range runs { + if h.err != nil { + continue } - - // Allow cloud-init to insert authorized_keys if just booted - var sshExec *remote.SSHExecutor - var sshErr error - for attempt := 1; attempt <= 10; attempt++ { - sshExec, sshErr = remote.NewSSHExecutor(primaryHostIP, hostSSHPort, hostSSHUser, privKeyPEM) - if sshErr == nil { - break + if err := r.bootstrapHost(ctx, fleet, h, privKeyPEM); err != nil { + if err := failed(h, err); err != nil { + return err } - time.Sleep(3 * time.Second) } - if sshErr != nil { - return fmt.Errorf("init SSH executor to %s: %w", primaryHostIP, sshErr) + if h.exec != nil && h.exec != r.exec { + defer h.exec.Close() } - defer sshExec.Close() - activeExec = sshExec - - // Pre-flight host initialization - log.Printf("==> [GitOps] Verifying host runtime on %s...\n", primaryHostIP) - bootstrap, err := hostBootstrapCommands(hostNet) - if err != nil { - return fmt.Errorf("host %s: %w", primaryHostName, err) + } + var hostErrs []error + for _, h := range runs { + if h.err != nil { + hostErrs = append(hostErrs, fmt.Errorf("host %s: %w", h.name, h.err)) } - for _, cmd := range bootstrap { - _, _ = sshExec.Run(ctx, cmd) + } + if len(hostErrs) > 0 { + err := fmt.Errorf("%d of %d hosts failed: %w", len(hostErrs), len(runs), errors.Join(hostErrs...)) + if dnsErr != nil { + err = fmt.Errorf("%w; and DNS sync failed: %v", err, dnsErr) } + return err + } - bridge, _, _ := hostNet.Bridge() - diag, _ := sshExec.Run(ctx, "echo '--- NETWORK ---'; incus network show "+bridge+"; echo '--- DEFAULT PROFILE ---'; incus profile show default; echo '--- STORAGE ---'; incus storage list") - log.Printf("==> [GitOps] Host runtime diagnostics:\n%s\n", diag) - - deployer = NewDeployer(sshExec) + // The break-glass deploy has at most one host (several are refused above), or none: then it runs here. + deployer, activeExec := r.deployer, r.exec + if len(runs) == 1 { + deployer, activeExec = runs[0].deployer, runs[0].exec + } else if hostNet, _ := fleet.LocalNetwork(""); hostNet.BridgeName != "" { if err := deployer.SetNetwork(hostNet); err != nil { - return fmt.Errorf("host %s: %w", primaryHostName, err) + return fmt.Errorf("host : %w", err) // as before the per-host loop, which named no host here } } @@ -488,3 +483,177 @@ func (r *Reconciler) Reconcile(ctx context.Context) error { log.Printf("==> [GitOps] Full fleet reconciliation completed successfully!\n") return nil } + +func hostRunOf(runs []*hostRun, name string) *hostRun { + for _, h := range runs { + if h.name == name { + return h + } + } + return nil +} + +// provisionHost makes sure one host exists and returns its public address: the one fleet.yml gives, or the +// provider's (creating the host, with its daemon from cloud-init, when there is none). "" means the host +// has no address reconcile knows (a provider it does not provision). +func (r *Reconciler) provisionHost(ctx context.Context, fleet *config.FleetConfig, hostName string, hostCfg config.HostConfig, sshUser string, sshPort int, privKeyPEM []byte, pubKeyStr string, generatedKey bool) (string, error) { + if hostCfg.Address != "" && hostCfg.Address != "auto" { + return hostCfg.Address, nil + } + if hostCfg.Provider != "digitalocean" && hostCfg.Provider != "do" { + return "", nil + } + var ip string + // Query provider to see if host exists + do, err := digitalocean.New("") + if err != nil { + return "", fmt.Errorf("digitalocean provider init: %w", err) + } + hosts, err := do.ListHosts(ctx) + if err != nil { + return "", fmt.Errorf("list hosts: %w", err) + } + existing, action, err := classifyHost(hosts, hostName) + if err != nil { + return "", err + } + switch action { + case hostUse: + ip = existing.PublicIP + log.Printf(" Host %s already active at IP %s\n", hostName, ip) + case hostWait: + log.Printf(" Host %s (id %s) is still provisioning; waiting for it instead of creating another\n", hostName, existing.ID) + h, err := waitHostActive(ctx, do, existing.ID, 5*time.Minute, 5*time.Second) + if err != nil { + return "", err + } + ip = h.PublicIP + } + + // A host that exists must be reachable with our credentials. If it is not, + // stop and say so: reconcile never destroys or rebuilds a host on its own. + if ip != "" && len(privKeyPEM) > 0 { + testExec, testErr := r.dialSSH(ip, sshPort, sshUser, privKeyPEM) + if testErr == nil { + if _, err := testExec.Run(ctx, "true"); err != nil { + testErr = err + } + testExec.Close() + } + if testErr != nil { + return "", fmt.Errorf("host %s (%s) exists but SSH verification failed: %v. Not destroying or re-provisioning it automatically (it may hold data): fix the SSH key or user, or remove the host yourself if you want it rebuilt", hostName, ip, testErr) + } + } + if ip != "" { + return ip, nil + } + + // Not found: provision it + log.Printf(" Host %s not found. Provisioning with cloud-init...\n", hostName) + spec := config.HostSpec{ + Name: hostName, + Provider: "digitalocean", + Size: fleet.Providers.DigitalOcean.DefaultSize, + Region: fleet.Providers.DigitalOcean.Region, + } + // The cloud-init opens the firewall for this host's own bridge, and, with fleet.yml's daemon + // section, installs the daemon. + var di *DaemonInstall + if fleet.Daemon != nil { + if di, err = DaemonInstallFor(fleet.Daemon); err != nil { + return "", fmt.Errorf("provision host %s: daemon: %w", hostName, err) + } + // With several hosts each daemon must know which it is; its unit carries that + // (a deploy's daemon.flags keep it, see pkg/serveflags). + if len(fleet.Hosts) >= 2 { + di.ServeFlags = strings.TrimSpace(di.ServeFlags + " --host-name " + hostName) + if err := di.Validate(); err != nil { + return "", fmt.Errorf("provision host %s: daemon: %w", hostName, err) + } + } + } + ud, err := GenerateCloudInitUserDataFor(pubKeyStr, fleet.HostNetwork(hostName), di) + if err != nil { + return "", fmt.Errorf("provision host %s: %w", hostName, err) + } + spec.UserData = ud + if di != nil { + log.Printf(" The host's cloud-init installs the native-ops daemon %s\n", fleet.Daemon.Version) + } + // A throwaway key is acceptable here: this run uses it to SSH in. But a failure to + // register the key must stop the run BEFORE a droplet nobody can log in to is created. + if err := r.hostMgr.PrepareAccess(ctx, &spec, pubKeyStr, generatedKey, true); err != nil { + return "", fmt.Errorf("provision host %s: %w", hostName, err) + } + newHost, err := r.hostMgr.CreateHost(ctx, spec) + if err != nil { + return "", fmt.Errorf("provision host %s: %w", hostName, err) + } + return newHost.PublicIP, nil +} + +// bootstrapHost prepares one host's Incus runtime over SSH (when it has a remote address and there is a +// key) and sets h's executor and deployer for it. A host reconcile cannot reach (no address, or the +// local machine) keeps the reconciler's own executor. +func (r *Reconciler) bootstrapHost(ctx context.Context, fleet *config.FleetConfig, h *hostRun, privKeyPEM []byte) error { + // The bridge is the host's own `network:` (fleet.yml's, or the host's override). + h.net = fleet.HostNetwork(h.name) + if h.ip == "" { + h.net, _ = fleet.LocalNetwork("") + } + h.deployer, h.exec = r.deployer, r.exec + if len(fleet.Hosts) >= 2 { + h.deployer = NewDeployer(r.exec) + } + if h.net.BridgeName != "" { + if err := h.deployer.SetNetwork(h.net); err != nil { + return fmt.Errorf("host %s: %w", h.name, err) + } + } + if h.ip == "" || h.ip == "127.0.0.1" || h.ip == "localhost" || len(privKeyPEM) == 0 { + if len(fleet.Hosts) >= 2 { + log.Printf(" Host %s is not reached over SSH (no address reconcile knows, the local machine, or no SSH key); its runtime is not bootstrapped from here\n", h.name) + } + return nil + } + + log.Printf("==> [GitOps] Connecting to host %s:%d via SSH (%s)...\n", h.ip, h.port, h.user) + if err := r.waitSSH(ctx, h.ip, h.port, 120*time.Second); err != nil { + return fmt.Errorf("wait for host SSH: %w", err) + } + + // Allow cloud-init to insert authorized_keys if just booted + var sshExec remote.Executor + var sshErr error + for attempt := 1; attempt <= 10; attempt++ { + sshExec, sshErr = r.dialSSH(h.ip, h.port, h.user, privKeyPEM) + if sshErr == nil { + break + } + time.Sleep(r.sshRetryDelay) + } + if sshErr != nil { + return fmt.Errorf("init SSH executor to %s: %w", h.ip, sshErr) + } + h.exec = sshExec + + // Pre-flight host initialization + log.Printf("==> [GitOps] Verifying host runtime on %s...\n", h.ip) + bootstrap, err := hostBootstrapCommands(h.net) + if err != nil { + return fmt.Errorf("host %s: %w", h.name, err) + } + for _, cmd := range bootstrap { + _, _ = sshExec.Run(ctx, cmd) + } + + bridge, _, _ := h.net.Bridge() + diag, _ := sshExec.Run(ctx, "echo '--- NETWORK ---'; incus network show "+bridge+"; echo '--- DEFAULT PROFILE ---'; incus profile show default; echo '--- STORAGE ---'; incus storage list") + log.Printf("==> [GitOps] Host runtime diagnostics:\n%s\n", diag) + + h.deployer = NewDeployer(sshExec) + if err := h.deployer.SetNetwork(h.net); err != nil { + return fmt.Errorf("host %s: %w", h.name, err) + } + return nil +} diff --git a/pkg/engine/testdata/reconcile-single-host-dns-fails.golden b/pkg/engine/testdata/reconcile-single-host-dns-fails.golden new file mode 100644 index 0000000..8ad193a --- /dev/null +++ b/pkg/engine/testdata/reconcile-single-host-dns-fails.golden @@ -0,0 +1,39 @@ +--- log +==> [GitOps] Starting complete fleet reconciliation from +==> [GitOps] Reconciling host: only (provider=static) +==> [GitOps] Syncing DNS records for example.com -> 198.51.100.10 + DNS sync failed: 403 forbidden (continuing with services; the run will fail at the end) +==> [GitOps] Connecting to host 198.51.100.10:2222 via SSH (ops)... +==> [GitOps] Verifying host runtime on 198.51.100.10... +==> [GitOps] Host runtime diagnostics: + +--- error +hosts reconciled, but DNS sync failed: 403 forbidden +--- ssh +dial ops@198.51.100.10:2222 +--- dns +example.com: A @ 198.51.100.10, A * 198.51.100.10 +--- commands on local +--- commands on 198.51.100.10 +chage -I -1 -m 0 -M 99999 -E -1 root || true +[ "$(passwd -S root 2>/dev/null | awk '{print $2}')" = P ] && passwd -d root || true +which cloud-init >/dev/null 2>&1 && cloud-init status --wait || true +which incus >/dev/null 2>&1 || (apt-get update && apt-get install -y incus) +incus profile show default >/dev/null 2>&1 || incus admin init --auto +incus storage list | grep -q default || incus storage create default dir || true +incus profile device show default | grep -q 'path: /' || incus profile device add default root disk path=/ pool=default || true +[ "$(sysctl -n net.ipv4.ip_forward 2>/dev/null)" = 1 ] || sysctl -w net.ipv4.ip_forward=1 || true +iptables -t nat -C POSTROUTING -s 10.0.100.0/24 -j MASQUERADE 2>/dev/null || iptables -t nat -A POSTROUTING -s 10.0.100.0/24 -j MASQUERADE || true +iptables -C FORWARD -i incusbr0 -j ACCEPT 2>/dev/null || iptables -I FORWARD -i incusbr0 -j ACCEPT 2>/dev/null || true +iptables -C FORWARD -o incusbr0 -j ACCEPT 2>/dev/null || iptables -I FORWARD -o incusbr0 -j ACCEPT 2>/dev/null || true +iptables -C INPUT -i incusbr0 -j ACCEPT 2>/dev/null || iptables -I INPUT -i incusbr0 -j ACCEPT 2>/dev/null || true +which ufw >/dev/null 2>&1 && (ufw allow in on incusbr0; ufw route allow in on incusbr0; ufw route allow out on incusbr0) || true +incus network show incusbr0 >/dev/null 2>&1 || incus network create incusbr0 || true +[ "$(incus network get 'incusbr0' 'ipv4.address' 2>/dev/null)" = '10.0.100.1/24' ] || { n="$(incus list --format csv --columns n 2>/dev/null)" && [ -z "$n" ] && incus network set 'incusbr0' 'ipv4.address=10.0.100.1/24'; } || true +[ "$(incus network get 'incusbr0' 'ipv4.nat' 2>/dev/null)" = 'true' ] || incus network set 'incusbr0' 'ipv4.nat=true' || true +[ "$(incus network get 'incusbr0' 'ipv6.address' 2>/dev/null)" = 'none' ] || incus network set 'incusbr0' 'ipv6.address=none' || true +[ "$(incus network get 'incusbr0' 'dns.mode' 2>/dev/null)" = 'managed' ] || incus network set 'incusbr0' 'dns.mode=managed' || true +[ "$(incus network get 'incusbr0' 'raw.dnsmasq' 2>/dev/null)" = 'server=1.1.1.1' ] || incus network set 'incusbr0' 'raw.dnsmasq=server=1.1.1.1' || true +incus profile device show default | grep -q 'network: incusbr0' || incus profile device add default eth0 nic network=incusbr0 name=eth0 || true +incus remote list | grep -q ' docker ' || incus remote add docker https://docker.io --protocol=oci --public || true +echo '--- NETWORK ---'; incus network show incusbr0; echo '--- DEFAULT PROFILE ---'; incus profile show default; echo '--- STORAGE ---'; incus storage list diff --git a/pkg/engine/testdata/reconcile-single-host-local.golden b/pkg/engine/testdata/reconcile-single-host-local.golden new file mode 100644 index 0000000..a5d6f9a --- /dev/null +++ b/pkg/engine/testdata/reconcile-single-host-local.golden @@ -0,0 +1,16 @@ +--- log +==> [GitOps] Starting complete fleet reconciliation from +==> [GitOps] Reconciling host: only (provider=static) +==> [GitOps] Syncing DNS records for example.com -> 127.0.0.1 + DNS synchronized successfully. +==> [GitOps] --deploy-services: deploying services directly, without the daemon's plan approval +==> [GitOps] Edge container diagnostics: + +==> [GitOps] Full fleet reconciliation completed successfully! +--- error + +--- ssh +--- dns +example.com: A @ 127.0.0.1, A * 127.0.0.1 +--- commands on local +sleep 10; echo '--- TAIL 40 CADDY LOG ---'; incus exec edge -- tail -n 40 /var/log/caddy.log || true diff --git a/pkg/engine/testdata/reconcile-single-host-no-address.golden b/pkg/engine/testdata/reconcile-single-host-no-address.golden new file mode 100644 index 0000000..0034ad4 --- /dev/null +++ b/pkg/engine/testdata/reconcile-single-host-no-address.golden @@ -0,0 +1,13 @@ +--- log +==> [GitOps] Starting complete fleet reconciliation from +==> [GitOps] Reconciling host: only (provider=proxmox) +==> [GitOps] --deploy-services: deploying services directly, without the daemon's plan approval +==> [GitOps] Edge container diagnostics: + +==> [GitOps] Full fleet reconciliation completed successfully! +--- error + +--- ssh +--- dns +--- commands on local +sleep 10; echo '--- TAIL 40 CADDY LOG ---'; incus exec edge -- tail -n 40 /var/log/caddy.log || true diff --git a/pkg/engine/testdata/reconcile-single-host-no-hosts.golden b/pkg/engine/testdata/reconcile-single-host-no-hosts.golden new file mode 100644 index 0000000..fa9308d --- /dev/null +++ b/pkg/engine/testdata/reconcile-single-host-no-hosts.golden @@ -0,0 +1,12 @@ +--- log +==> [GitOps] Starting complete fleet reconciliation from +==> [GitOps] --deploy-services: deploying services directly, without the daemon's plan approval +==> [GitOps] Edge container diagnostics: + +==> [GitOps] Full fleet reconciliation completed successfully! +--- error + +--- ssh +--- dns +--- commands on local +sleep 10; echo '--- TAIL 40 CADDY LOG ---'; incus exec edge -- tail -n 40 /var/log/caddy.log || true diff --git a/pkg/engine/testdata/reconcile-single-host-ssh-deploy-services.golden b/pkg/engine/testdata/reconcile-single-host-ssh-deploy-services.golden new file mode 100644 index 0000000..2a5c6c7 --- /dev/null +++ b/pkg/engine/testdata/reconcile-single-host-ssh-deploy-services.golden @@ -0,0 +1,44 @@ +--- log +==> [GitOps] Starting complete fleet reconciliation from +==> [GitOps] Reconciling host: only (provider=static) +==> [GitOps] Syncing DNS records for example.com -> 198.51.100.10 + DNS synchronized successfully. +==> [GitOps] Connecting to host 198.51.100.10:2222 via SSH (ops)... +==> [GitOps] Verifying host runtime on 198.51.100.10... +==> [GitOps] Host runtime diagnostics: + +==> [GitOps] --deploy-services: deploying services directly, without the daemon's plan approval +==> [GitOps] Edge container diagnostics: + +==> [GitOps] Full fleet reconciliation completed successfully! +--- error + +--- ssh +dial ops@198.51.100.10:2222 +--- dns +example.com: A @ 198.51.100.10, A * 198.51.100.10 +--- commands on local +--- commands on 198.51.100.10 +chage -I -1 -m 0 -M 99999 -E -1 root || true +[ "$(passwd -S root 2>/dev/null | awk '{print $2}')" = P ] && passwd -d root || true +which cloud-init >/dev/null 2>&1 && cloud-init status --wait || true +which incus >/dev/null 2>&1 || (apt-get update && apt-get install -y incus) +incus profile show default >/dev/null 2>&1 || incus admin init --auto +incus storage list | grep -q default || incus storage create default dir || true +incus profile device show default | grep -q 'path: /' || incus profile device add default root disk path=/ pool=default || true +[ "$(sysctl -n net.ipv4.ip_forward 2>/dev/null)" = 1 ] || sysctl -w net.ipv4.ip_forward=1 || true +iptables -t nat -C POSTROUTING -s 10.0.100.0/24 -j MASQUERADE 2>/dev/null || iptables -t nat -A POSTROUTING -s 10.0.100.0/24 -j MASQUERADE || true +iptables -C FORWARD -i incusbr0 -j ACCEPT 2>/dev/null || iptables -I FORWARD -i incusbr0 -j ACCEPT 2>/dev/null || true +iptables -C FORWARD -o incusbr0 -j ACCEPT 2>/dev/null || iptables -I FORWARD -o incusbr0 -j ACCEPT 2>/dev/null || true +iptables -C INPUT -i incusbr0 -j ACCEPT 2>/dev/null || iptables -I INPUT -i incusbr0 -j ACCEPT 2>/dev/null || true +which ufw >/dev/null 2>&1 && (ufw allow in on incusbr0; ufw route allow in on incusbr0; ufw route allow out on incusbr0) || true +incus network show incusbr0 >/dev/null 2>&1 || incus network create incusbr0 || true +[ "$(incus network get 'incusbr0' 'ipv4.address' 2>/dev/null)" = '10.0.100.1/24' ] || { n="$(incus list --format csv --columns n 2>/dev/null)" && [ -z "$n" ] && incus network set 'incusbr0' 'ipv4.address=10.0.100.1/24'; } || true +[ "$(incus network get 'incusbr0' 'ipv4.nat' 2>/dev/null)" = 'true' ] || incus network set 'incusbr0' 'ipv4.nat=true' || true +[ "$(incus network get 'incusbr0' 'ipv6.address' 2>/dev/null)" = 'none' ] || incus network set 'incusbr0' 'ipv6.address=none' || true +[ "$(incus network get 'incusbr0' 'dns.mode' 2>/dev/null)" = 'managed' ] || incus network set 'incusbr0' 'dns.mode=managed' || true +[ "$(incus network get 'incusbr0' 'raw.dnsmasq' 2>/dev/null)" = 'server=1.1.1.1' ] || incus network set 'incusbr0' 'raw.dnsmasq=server=1.1.1.1' || true +incus profile device show default | grep -q 'network: incusbr0' || incus profile device add default eth0 nic network=incusbr0 name=eth0 || true +incus remote list | grep -q ' docker ' || incus remote add docker https://docker.io --protocol=oci --public || true +echo '--- NETWORK ---'; incus network show incusbr0; echo '--- DEFAULT PROFILE ---'; incus profile show default; echo '--- STORAGE ---'; incus storage list +sleep 10; echo '--- TAIL 40 CADDY LOG ---'; incus exec edge -- tail -n 40 /var/log/caddy.log || true diff --git a/pkg/engine/testdata/reconcile-single-host-ssh-fails.golden b/pkg/engine/testdata/reconcile-single-host-ssh-fails.golden new file mode 100644 index 0000000..e9404de --- /dev/null +++ b/pkg/engine/testdata/reconcile-single-host-ssh-fails.golden @@ -0,0 +1,22 @@ +--- log +==> [GitOps] Starting complete fleet reconciliation from +==> [GitOps] Reconciling host: only (provider=static) +==> [GitOps] Syncing DNS records for example.com -> 198.51.100.10 + DNS synchronized successfully. +==> [GitOps] Connecting to host 198.51.100.10:2222 via SSH (ops)... +--- error +init SSH executor to 198.51.100.10: connection refused +--- ssh +dial ops@198.51.100.10:2222 +dial ops@198.51.100.10:2222 +dial ops@198.51.100.10:2222 +dial ops@198.51.100.10:2222 +dial ops@198.51.100.10:2222 +dial ops@198.51.100.10:2222 +dial ops@198.51.100.10:2222 +dial ops@198.51.100.10:2222 +dial ops@198.51.100.10:2222 +dial ops@198.51.100.10:2222 +--- dns +example.com: A @ 198.51.100.10, A * 198.51.100.10 +--- commands on local diff --git a/pkg/engine/testdata/reconcile-single-host-ssh.golden b/pkg/engine/testdata/reconcile-single-host-ssh.golden new file mode 100644 index 0000000..8b21c79 --- /dev/null +++ b/pkg/engine/testdata/reconcile-single-host-ssh.golden @@ -0,0 +1,40 @@ +--- log +==> [GitOps] Starting complete fleet reconciliation from +==> [GitOps] Reconciling host: only (provider=static) +==> [GitOps] Syncing DNS records for example.com -> 198.51.100.10 + DNS synchronized successfully. +==> [GitOps] Connecting to host 198.51.100.10:2222 via SSH (ops)... +==> [GitOps] Verifying host runtime on 198.51.100.10... +==> [GitOps] Host runtime diagnostics: + +==> [GitOps] Hosts and DNS reconciled. Services are deployed through the daemon: plan and apply an approved plan (native-ops remote plan / apply). Pass --deploy-services to deploy them directly over SSH instead (break-glass: no plan, approval or job record). +--- error + +--- ssh +dial ops@198.51.100.10:2222 +--- dns +example.com: A @ 198.51.100.10, A * 198.51.100.10 +--- commands on local +--- commands on 198.51.100.10 +chage -I -1 -m 0 -M 99999 -E -1 root || true +[ "$(passwd -S root 2>/dev/null | awk '{print $2}')" = P ] && passwd -d root || true +which cloud-init >/dev/null 2>&1 && cloud-init status --wait || true +which incus >/dev/null 2>&1 || (apt-get update && apt-get install -y incus) +incus profile show default >/dev/null 2>&1 || incus admin init --auto +incus storage list | grep -q default || incus storage create default dir || true +incus profile device show default | grep -q 'path: /' || incus profile device add default root disk path=/ pool=default || true +[ "$(sysctl -n net.ipv4.ip_forward 2>/dev/null)" = 1 ] || sysctl -w net.ipv4.ip_forward=1 || true +iptables -t nat -C POSTROUTING -s 10.0.100.0/24 -j MASQUERADE 2>/dev/null || iptables -t nat -A POSTROUTING -s 10.0.100.0/24 -j MASQUERADE || true +iptables -C FORWARD -i incusbr0 -j ACCEPT 2>/dev/null || iptables -I FORWARD -i incusbr0 -j ACCEPT 2>/dev/null || true +iptables -C FORWARD -o incusbr0 -j ACCEPT 2>/dev/null || iptables -I FORWARD -o incusbr0 -j ACCEPT 2>/dev/null || true +iptables -C INPUT -i incusbr0 -j ACCEPT 2>/dev/null || iptables -I INPUT -i incusbr0 -j ACCEPT 2>/dev/null || true +which ufw >/dev/null 2>&1 && (ufw allow in on incusbr0; ufw route allow in on incusbr0; ufw route allow out on incusbr0) || true +incus network show incusbr0 >/dev/null 2>&1 || incus network create incusbr0 || true +[ "$(incus network get 'incusbr0' 'ipv4.address' 2>/dev/null)" = '10.0.100.1/24' ] || { n="$(incus list --format csv --columns n 2>/dev/null)" && [ -z "$n" ] && incus network set 'incusbr0' 'ipv4.address=10.0.100.1/24'; } || true +[ "$(incus network get 'incusbr0' 'ipv4.nat' 2>/dev/null)" = 'true' ] || incus network set 'incusbr0' 'ipv4.nat=true' || true +[ "$(incus network get 'incusbr0' 'ipv6.address' 2>/dev/null)" = 'none' ] || incus network set 'incusbr0' 'ipv6.address=none' || true +[ "$(incus network get 'incusbr0' 'dns.mode' 2>/dev/null)" = 'managed' ] || incus network set 'incusbr0' 'dns.mode=managed' || true +[ "$(incus network get 'incusbr0' 'raw.dnsmasq' 2>/dev/null)" = 'server=1.1.1.1' ] || incus network set 'incusbr0' 'raw.dnsmasq=server=1.1.1.1' || true +incus profile device show default | grep -q 'network: incusbr0' || incus profile device add default eth0 nic network=incusbr0 name=eth0 || true +incus remote list | grep -q ' docker ' || incus remote add docker https://docker.io --protocol=oci --public || true +echo '--- NETWORK ---'; incus network show incusbr0; echo '--- DEFAULT PROFILE ---'; incus profile show default; echo '--- STORAGE ---'; incus storage list diff --git a/pkg/server/deploy.go b/pkg/server/deploy.go index 19acba9..cfa7d63 100644 --- a/pkg/server/deploy.go +++ b/pkg/server/deploy.go @@ -103,6 +103,10 @@ func (s *Server) startDeploy(tag, actor string, resume *deployResume) (Job, erro if err := s.followBackupSchedule(root, logf); err != nil { return err } + // fleet.yml's hosts and their incus_remote: where a migration by target_host goes. + if err := s.followHostRemotes(root, logf); err != nil { + return err + } pctx, cancel := context.WithTimeout(ctx, 2*time.Minute) fp, err := s.opts.Plan(pctx, root, "") diff --git a/pkg/server/host_remotes.go b/pkg/server/host_remotes.go new file mode 100644 index 0000000..c7866a5 --- /dev/null +++ b/pkg/server/host_remotes.go @@ -0,0 +1,111 @@ +package server + +import ( + "encoding/json" + "errors" + "fmt" + "os" + "path/filepath" + "sort" + "strings" + + "github.com/theta42/native-ops/pkg/config" + "github.com/theta42/native-ops/pkg/engine" + "github.com/theta42/native-ops/pkg/incus" +) + +// A migration names where the instance goes by an Incus remote configured on the source host +// (target_remote), or by the fleet.yml host it goes to (target_host): fleet.yml's hosts..incus_remote +// is the remote that reaches that host. The daemon learns the remotes from the fleet.yml of each deploy tag +// it applies, and keeps them in HostRemotesFile, so a migration needs no config tree of its own. + +// hostRemotes is what HostRemotesFile holds: each host of fleet.yml with the Incus remote that reaches it +// ("" when fleet.yml gives none). +type hostRemotes struct { + Hosts map[string]string `json:"hosts"` +} + +// followHostRemotes records the hosts and their Incus remotes from a deploy tag's fleet.yml. A fleet.yml +// without hosts: removes the record. +func (s *Server) followHostRemotes(root string, logf func(string, ...any)) error { + if s.opts.HostRemotesFile == "" { + return nil + } + fleet, err := config.LoadFleetConfig(root) + if err != nil { + return err + } + if len(fleet.Hosts) == 0 { + if err := os.Remove(s.opts.HostRemotesFile); err != nil && !errors.Is(err, os.ErrNotExist) { + return fmt.Errorf("host remotes: %w", err) + } + return nil + } + rec := hostRemotes{Hosts: map[string]string{}} + var named []string + for _, name := range fleet.HostNames() { + rec.Hosts[name] = fleet.Hosts[name].IncusRemote + if r := fleet.Hosts[name].IncusRemote; r != "" { + named = append(named, name+" -> "+r) + } + } + b, err := json.MarshalIndent(rec, "", " ") + if err != nil { + return err + } + if err := os.MkdirAll(filepath.Dir(s.opts.HostRemotesFile), 0o700); err != nil { + return fmt.Errorf("host remotes: %w", err) + } + tmp := s.opts.HostRemotesFile + ".tmp" + if err := os.WriteFile(tmp, append(b, '\n'), 0o600); err != nil { + return fmt.Errorf("host remotes: %w", err) + } + if err := os.Rename(tmp, s.opts.HostRemotesFile); err != nil { + return fmt.Errorf("host remotes: %w", err) + } + if len(named) > 0 && len(fleet.Hosts) >= 2 { + logf("migrations by target_host go to the Incus remotes fleet.yml names: %s", strings.Join(named, ", ")) + } + return nil +} + +// targetRemoteOf resolves a migration's target_host to the Incus remote fleet.yml gives it. The error is +// what the caller is told (a 400 or 409). +func (s *Server) targetRemoteOf(host string) (string, int, error) { + if !incus.ValidName(host) { + return "", 400, errors.New("target_host must be the name of a host in fleet.yml's hosts:") + } + if s.opts.HostName != "" && host == s.opts.HostName { + return "", 400, fmt.Errorf("target_host %q is this host", host) + } + if s.opts.HostRemotesFile == "" { + return "", 409, errors.New("this daemon does not record fleet.yml's hosts (it does not deploy tags); give target_remote instead") + } + b, err := os.ReadFile(s.opts.HostRemotesFile) + if errors.Is(err, os.ErrNotExist) { + return "", 409, errors.New("this daemon has not deployed a fleet.yml with hosts: yet, so it does not know their Incus remotes; give target_remote instead") + } + if err != nil { + return "", 500, fmt.Errorf("read the hosts' Incus remotes: %w", err) + } + var rec hostRemotes + if err := json.Unmarshal(b, &rec); err != nil { + return "", 500, fmt.Errorf("read the hosts' Incus remotes: %w", err) + } + remote, ok := rec.Hosts[host] + if !ok { + names := make([]string, 0, len(rec.Hosts)) + for n := range rec.Hosts { + names = append(names, n) + } + sort.Strings(names) + return "", 400, fmt.Errorf("target_host %q is not a host of the fleet.yml this daemon last deployed (%s)", host, strings.Join(names, ", ")) + } + if remote == "" { + return "", 409, fmt.Errorf("fleet.yml gives host %s no incus_remote (hosts.%s.incus_remote); set it, or give target_remote instead", host, host) + } + if remote == engine.LocalRemote { + return "", 400, fmt.Errorf("fleet.yml's hosts.%s.incus_remote is %q, which is this host", host, remote) + } + return remote, 0, nil +} diff --git a/pkg/server/host_remotes_test.go b/pkg/server/host_remotes_test.go new file mode 100644 index 0000000..449e4d3 --- /dev/null +++ b/pkg/server/host_remotes_test.go @@ -0,0 +1,113 @@ +package server + +import ( + "os" + "path/filepath" + "strings" + "testing" + + "github.com/theta42/native-ops/pkg/engine" +) + +const remotesFleet = "name: f\ndefault_host: h1\nhosts:\n" + + " h1: {provider: static, incus_remote: host-one}\n" + + " h2: {provider: static, incus_remote: host-two, network: {ipv4_cidr: 10.0.101.0/24}}\n" + + " h3: {provider: static, network: {ipv4_cidr: 10.0.102.0/24}}\n" + +// followRemotes records the hosts' remotes a deploy's fleet.yml declares, as a deploy does. +func followRemotes(t *testing.T, rig *instRig, fleetYML string) string { + t.Helper() + root := t.TempDir() + if err := os.WriteFile(filepath.Join(root, "fleet.yml"), []byte(fleetYML), 0o644); err != nil { + t.Fatal(err) + } + var log []string + if err := rig.srv.followHostRemotes(root, func(f string, a ...any) { log = append(log, f) }); err != nil { + t.Fatal(err) + } + return strings.Join(log, "\n") +} + +// A migration may name its target by fleet.yml host: the daemon resolves it to the host's incus_remote, +// as the last deploy tag's fleet.yml gives it. +func TestMigrateByTargetHostGoesToItsIncusRemote(t *testing.T) { + rig := newMigrateRig(t) + rig.srv.opts.HostRemotesFile = filepath.Join(t.TempDir(), "host-remotes.json") + rig.srv.opts.HostName = "h1" + + // Before any deploy recorded the hosts, target_host cannot be resolved. + res, body := rig.do2(t, "POST", "/v1/instances/demo-old/migrate", rig.scoped, map[string]any{"target_host": "h2"}) + if res.StatusCode != 409 || !strings.Contains(body, "give target_remote") { + t.Fatalf("no deploy yet: %d %s", res.StatusCode, body) + } + + followRemotes(t, rig, remotesFleet) + res, body = rig.do2(t, "POST", "/v1/instances/demo-old/migrate", rig.scoped, map[string]any{"target_host": "h2", "resume": true}) + if res.StatusCode != 202 { + t.Fatalf("%d %s", res.StatusCode, body) + } + rig.wait(t, body, JobSucceeded) + if len(rig.ops.migrates) != 1 || rig.ops.migrates[0] != (engine.MigrateRequest{TargetRemote: "host-two", Resume: true}) { + t.Fatalf("target_host h2 must reach the host as its remote host-two: %+v", rig.ops.migrates) + } + + for name, c := range map[string]struct { + body map[string]any + code int + want string + }{ + "both": {map[string]any{"target_host": "h2", "target_remote": "host-two"}, 400, "not both"}, + "unknown host": {map[string]any{"target_host": "h9"}, 400, "not a host of the fleet.yml"}, + "no remote": {map[string]any{"target_host": "h3"}, 409, "hosts.h3.incus_remote"}, + "this host": {map[string]any{"target_host": "h1"}, 400, "is this host"}, + "a bad name": {map[string]any{"target_host": "h 2"}, 400, "target_host"}, + } { + res, body := rig.do2(t, "POST", "/v1/instances/demo-old/migrate", rig.scoped, c.body) + if res.StatusCode != c.code || !strings.Contains(body, c.want) { + t.Errorf("%s: want %d %q, got %d %s", name, c.code, c.want, res.StatusCode, body) + } + } + if len(rig.ops.migrates) != 1 { + t.Fatalf("no refused request reaches the host: %+v", rig.ops.migrates) + } + + // The role gate is the endpoint's: target_host changes nothing about who may migrate. + for name, tok := range map[string]string{"viewer": rig.viewer, "an unscoped deployer": rig.deployer} { + if res, body := rig.do2(t, "POST", "/v1/instances/demo-old/migrate", tok, map[string]any{"target_host": "h2"}); res.StatusCode != 403 { + t.Errorf("%s must be refused: %d %s", name, res.StatusCode, body) + } + } + + // A later deploy without hosts: forgets them. + followRemotes(t, rig, "name: f\n") + if res, body := rig.do2(t, "POST", "/v1/instances/demo-old/migrate", rig.scoped, map[string]any{"target_host": "h2"}); res.StatusCode != 409 { + t.Fatalf("hosts forgotten: %d %s", res.StatusCode, body) + } +} + +// A daemon that does not record the hosts refuses target_host and keeps taking target_remote. +func TestMigrateByTargetHostNeedsTheRecord(t *testing.T) { + rig := newMigrateRig(t) + res, body := rig.do2(t, "POST", "/v1/instances/demo-old/migrate", rig.scoped, map[string]any{"target_host": "h2"}) + if res.StatusCode != 409 || !strings.Contains(body, "does not record") { + t.Fatalf("%d %s", res.StatusCode, body) + } +} + +func TestADeployTagRecordsTheHostsIncusRemotes(t *testing.T) { + src := &fakeSource{protected: true, tree: tgz(t, entry{name: "fleet.yml", body: remotesFleet}, entry{name: "services/web/service.yml", body: "image: x\n"})} + file := filepath.Join(t.TempDir(), "host-remotes.json") + rig := newApplyRigWith(t, func(o *Options) { + o.Deploy, o.DeployTags = src, "deploy-*" + o.HostRemotesFile = file + }) + res, body := rig.post(t, "/v1/deploy", rig.deployerToken, "application/json", []byte(`{"tag":"deploy-1"}`)) + if res.StatusCode != 202 { + t.Fatalf("%d %s", res.StatusCode, body) + } + rig.waitJob(t, jobID(t, body), JobSucceeded) + b, err := os.ReadFile(file) + if err != nil || !strings.Contains(string(b), `"h2": "host-two"`) || !strings.Contains(string(b), `"h3": ""`) { + t.Fatalf("the deploy must record the hosts' remotes: %s %v", b, err) + } +} diff --git a/pkg/server/migrate.go b/pkg/server/migrate.go index abb6417..266132f 100644 --- a/pkg/server/migrate.go +++ b/pkg/server/migrate.go @@ -56,17 +56,38 @@ func (s *Server) instanceInScope(w http.ResponseWriter, r *http.Request, name, o return true } -// handleInstanceMigrate is POST /v1/instances/{name}/migrate {"target_remote": "...", "resume": false}. +// migrateBody is the body of POST /v1/instances/{name}/migrate: where to (an Incus remote configured on +// this host, or a host of fleet.yml, whose incus_remote is that remote) and whether to resume. +type migrateBody struct { + engine.MigrateRequest + TargetHost string `json:"target_host,omitempty"` +} + +// handleInstanceMigrate is POST /v1/instances/{name}/migrate +// {"target_remote": "...", "resume": false} or {"target_host": "...", ...}. func (s *Server) handleInstanceMigrate(w http.ResponseWriter, r *http.Request) { name := r.PathValue("name") if !incus.ValidName(name) { writeError(w, http.StatusBadRequest, "bad_request", "not a valid instance name") return } - var req engine.MigrateRequest - if !readJSON(w, r, &req) { + var body migrateBody + if !readJSON(w, r, &body) { return } + req := body.MigrateRequest + if body.TargetHost != "" { + if req.TargetRemote != "" { + writeError(w, http.StatusBadRequest, "bad_request", "give target_host or target_remote, not both") + return + } + remote, code, err := s.targetRemoteOf(body.TargetHost) + if err != nil { + writeError(w, code, "bad_target_host", err.Error()) + return + } + req.TargetRemote = remote + } if err := req.Validate(); err != nil { writeError(w, http.StatusBadRequest, "bad_request", err.Error()) return diff --git a/pkg/server/migrate_test.go b/pkg/server/migrate_test.go index 0045e3d..f78936b 100644 --- a/pkg/server/migrate_test.go +++ b/pkg/server/migrate_test.go @@ -123,7 +123,7 @@ func TestMigrateIsRefusedForWhatCannotMove(t *testing.T) { "this host": {nil, "demo-old", map[string]any{"target_remote": "local"}, 400, "this host"}, "a bad remote": {nil, "demo-old", map[string]any{"target_remote": "host b"}, 400, "target_remote"}, "no remote": {nil, "demo-old", map[string]any{}, 400, "target_remote"}, - "an unknown field": {nil, "demo-old", map[string]any{"target_remote": "host-b", "target_host": "x"}, 400, "bad_request"}, + "an unknown field": {nil, "demo-old", map[string]any{"target_remote": "host-b", "target_hots": "x"}, 400, "bad_request"}, } for name, tc := range cases { t.Run(name, func(t *testing.T) { diff --git a/pkg/server/server.go b/pkg/server/server.go index 324e01e..152efb7 100644 --- a/pkg/server/server.go +++ b/pkg/server/server.go @@ -85,6 +85,11 @@ type Options struct { // BackupScheduleDir, with Backup and Jobs, is where the daemon keeps the backup schedule a deploy // tag's fleet.yml declared (backup.schedule); RunBackupSchedule runs it (see backup_schedule.go). BackupScheduleDir string + // HostRemotesFile is where a deploy records fleet.yml's hosts and their incus_remote, so a migration can + // name its target by host (target_host). Empty: target_host is refused, target_remote still works. + HostRemotesFile string + // HostName is which of fleet.yml's hosts this daemon is (--host-name); empty when it was not told. + HostName string // Users, with Sessions, enables local sign-in for the UI (POST /api/login, GET /api/session). OIDC, // with Sessions, adds a generic OpenID Connect sign-in. Either way a signed-in person may call the // API with a session cookie instead of a pasted token; API tokens keep working unchanged.