Files
ilkerandClaude Opus 5.5 71b30a8ac3 setup: install onto a libvirt host
The second setup backend, SITE_KIND=libvirt:

  libvirt   reaches the KVM host as root (or a sudo login) with the
            provisioner key, pinning its host key the first time; checks
            libvirt, /dev/kvm, the management bridge, qemu-img and curl,
            and installs none of them; puts a directory pool and the cloud
            image in place. On a host that is the control plane itself it
            authorises its own key for root.
  template  builds a head image: the cloud image copied, a build VM with a
            seed made here, the same golden.yml as Proxmox (now shared as
            bakeHead), its disk kept under a new name per build - heads'
            disks are overlays on it, so it is never rewritten in place.
  config    sites.yaml (kind libvirt, the pinned known_hosts), the unit's
            environment file, site.auto.tfvars naming the image.
  verify    the same checks by using them, and discovery through the
            provider with the settings the portal reads.

The libvirt module no longer takes the host's name: setup writes its
configuration before it has reached the host. Placement is held to one
host by comparing the hosts it chose with each other.

deploy/site.env.libvirt.example is held to its own validation, like the
Proxmox one. The interactive installer refuses a non-Proxmox site and
points at -yes -config. Tests cover the fields, what config writes and
that the portal can build a provider from it, every site.auto.tfvars
variable being declared by its environment (both backends), and the
host key pinned once and held to.

Not yet run against a real host end to end.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 12:48:53 +01:00

469 lines
15 KiB
Go

package setup
import (
"context"
"errors"
"fmt"
"net"
"net/http"
"net/url"
"os"
"path"
"sort"
"strings"
"time"
"golang.org/x/crypto/ssh"
)
const (
discoveryUser = "hpcod@pve"
discoveryID = "discovery"
terraformUser = "root@pam"
terraformID = "hpcod-tf"
imageSourceURL = "https://dl.rockylinux.org/pub/rocky/9/images/x86_64/"
)
// Storage is one datastore as Proxmox reports it.
type Storage struct {
ID string
Type string
Content []string
}
// Holds reports whether the datastore takes a content type.
func (s Storage) Holds(t string) bool {
for _, c := range s.Content {
if c == t {
return true
}
}
return false
}
// Probe is what the form learns from Proxmox before asking anything else,
// so that a node or a datastore is picked from what exists rather than
// typed and found wrong twenty minutes later.
type Probe struct {
Version string
Major int
Nodes []string
Storages []Storage
Zones []string
}
// Connect signs in with whatever credentials were given: root's password,
// or else the Terraform token (the one with the rights setup needs).
func Connect(ctx context.Context, s Site, c Credentials) (*PVE, error) {
insecure := s["PVE_INSECURE_TLS"] == "true"
switch {
case c.Password != "":
return PVEWithPassword(ctx, s["PVE_ENDPOINT"], insecure, terraformUser, c.Password)
case c.TerraformToken != "":
return PVEWithToken(s["PVE_ENDPOINT"], insecure, c.TerraformToken), nil
case c.DiscoveryToken != "":
return PVEWithToken(s["PVE_ENDPOINT"], insecure, c.DiscoveryToken), nil
}
return nil, errors.New("no Proxmox credentials: give root's password, or the tokens")
}
// ProbeProxmox signs in and reads what the form offers as choices. Its
// error is the first thing the operator sees when the address, the
// certificate or the password is wrong, so it says which.
func ProbeProxmox(ctx context.Context, s Site, c Credentials) (*Probe, error) {
ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
p, err := Connect(ctx, s, c)
if err != nil {
return nil, explainPVE(err, s)
}
pr := &Probe{}
if pr.Version, pr.Major, err = p.Version(ctx); err != nil {
return nil, explainPVE(err, s)
}
if pr.Major < 8 {
return nil, fmt.Errorf("Proxmox VE %s; the SDN this uses needs 8 or later", pr.Version)
}
if pr.Nodes, err = p.Nodes(ctx); err != nil {
return nil, explainPVE(err, s)
}
var st []struct {
Storage string `json:"storage"`
Type string `json:"type"`
Content string `json:"content"`
}
if err := p.Get(ctx, "/storage", &st); err != nil {
return nil, explainPVE(err, s)
}
for _, x := range st {
pr.Storages = append(pr.Storages, Storage{ID: x.Storage, Type: x.Type, Content: strings.Split(x.Content, ",")})
}
sort.Slice(pr.Storages, func(i, j int) bool { return pr.Storages[i].ID < pr.Storages[j].ID })
var zs []struct {
Zone string `json:"zone"`
}
if err := p.Get(ctx, "/cluster/sdn/zones", &zs); err == nil {
for _, z := range zs {
pr.Zones = append(pr.Zones, z.Zone)
}
}
return pr, nil
}
// explainPVE turns the usual failures into what to do about them.
func explainPVE(err error, s Site) error {
var pe *PVEError
var ne net.Error
switch {
case errors.As(err, &pe) && pe.Status == 401:
return fmt.Errorf("Proxmox refused the credentials (401): wrong password, or a token that does not exist")
case errors.As(err, &pe) && pe.Status == 403:
return fmt.Errorf("signed in, but not allowed (403) at %s: the token needs more rights", pe.Path)
case strings.Contains(err.Error(), "certificate"):
return fmt.Errorf("the API's certificate is not trusted; set \"Accept a self-signed certificate\" to true (%v)", err)
case errors.As(err, &ne) || strings.Contains(err.Error(), "connection refused") || strings.Contains(err.Error(), "no such host"):
return fmt.Errorf("cannot reach %s: %v", s["PVE_ENDPOINT"], err)
}
return err
}
// --- SSH ----------------------------------------------------------------------
// dialSSH connects without checking the host key, as the Terraform
// provider and the build already do for these hosts: the hypervisor and
// freshly cloned heads, on the management network.
func dialSSH(ctx context.Context, addr, user string, auth ...ssh.AuthMethod) (*ssh.Client, error) {
return dialSSHWith(ctx, addr, user, ssh.InsecureIgnoreHostKey(), auth...) //nolint:gosec // see above
}
// dialSSHWith is dialSSH with the host key checked by hostKey.
func dialSSHWith(ctx context.Context, addr, user string, hostKey ssh.HostKeyCallback, auth ...ssh.AuthMethod) (*ssh.Client, error) {
if !strings.Contains(addr, ":") {
addr += ":22"
}
cfg := &ssh.ClientConfig{
User: user,
Auth: auth,
HostKeyCallback: hostKey,
Timeout: 10 * time.Second,
}
d := net.Dialer{Timeout: 10 * time.Second}
conn, err := d.DialContext(ctx, "tcp", addr)
if err != nil {
return nil, err
}
c, chans, reqs, err := ssh.NewClientConn(conn, addr, cfg)
if err != nil {
conn.Close()
return nil, err
}
return ssh.NewClient(c, chans, reqs), nil
}
// sshRun runs one command and returns its combined output.
func sshRun(c *ssh.Client, cmd string) (string, error) {
s, err := c.NewSession()
if err != nil {
return "", err
}
defer s.Close()
out, err := s.CombinedOutput(cmd)
if err != nil {
return string(out), fmt.Errorf("%s: %w: %s", firstLine(cmd), err, strings.TrimSpace(string(out)))
}
return string(out), nil
}
// PVESSH reaches the hypervisor as root with the provisioner key.
func (e *Env) PVESSH(ctx context.Context) (*ssh.Client, error) {
signer, err := e.Signer()
if err != nil {
return nil, err
}
return dialSSH(ctx, e.Site["PVE_HOST"], "root", ssh.PublicKeys(signer))
}
// --- the step ---------------------------------------------------------------
// stepProxmox prepares the hypervisor: SSH access, two tokens written where
// they are used, the SDN zone, the content types on the datastores, and
// the cloud image. Each part checks first and changes only what is
// missing, and reads back what it changed.
func stepProxmox(ctx context.Context, e *Env) error {
if err := e.moveFlatTemplate(); err != nil {
return err
}
s := e.Site
insecure := s["PVE_INSECURE_TLS"] == "true"
// A simulated Proxmox's root password is ours, kept from when it was made.
if s.Sim() && e.Creds.Password == "" {
e.Creds.Password = envValue(e.P(SimPassFile), "PVESIM_ROOT_PASSWORD")
}
// 1. Root SSH with the provisioner key.
if err := e.ensurePVESSH(ctx); err != nil {
return err
}
// 2. The tokens. An existing one that still works is kept.
envf := EtcDir + "/env"
disc := envValue(e.P(envf), s.TokenVar())
wroteDisc := false
if !tokenWorks(ctx, s, disc) {
disc = e.Creds.DiscoveryToken
if disc == "" && e.Creds.Password != "" {
admin, err := Connect(ctx, s, e.Creds)
if err != nil {
return explainPVE(err, s)
}
if err := admin.Get(ctx, "/access/users/"+url.PathEscape(discoveryUser), &struct{}{}); err != nil {
if err := admin.Post(ctx, "/access/users", url.Values{
"userid": {discoveryUser}, "comment": {"HPC-on-Demand discovery"}}, nil); err != nil {
return fmt.Errorf("creating %s: %w", discoveryUser, err)
}
}
if err := admin.Put(ctx, "/access/acl", url.Values{
"path": {"/"}, "users": {discoveryUser}, "roles": {"PVEAuditor"}}); err != nil {
return fmt.Errorf("granting PVEAuditor to %s: %w", discoveryUser, err)
}
if disc, err = admin.CreateToken(ctx, discoveryUser, discoveryID, "hpcod discovery"); err != nil {
return err
}
e.Logf("created token %s!%s (PVEAuditor)", discoveryUser, discoveryID)
}
if !tokenWorks(ctx, s, disc) {
return fmt.Errorf("no working discovery token: give root's password, or paste one")
}
if err := setEnvValue(e, envf, s.TokenVar(), disc); err != nil {
return err
}
wroteDisc = true
}
e.Logf("discovery token accepted, in %s", envf)
tf := ""
if raw, err := os.ReadFile(e.P(s.SecretsTFVars())); err == nil {
tf = tfvarString(string(raw), "pve_token")
}
if !tokenWorks(ctx, s, tf) {
tf = e.Creds.TerraformToken
if tf == "" && e.Creds.Password != "" {
admin, err := Connect(ctx, s, e.Creds)
if err != nil {
return explainPVE(err, s)
}
// root, because a raw PCI passthrough - how a GPU reaches a
// compute node - is refused by Proxmox to everyone else.
if tf, err = admin.CreateToken(ctx, terraformUser, terraformID, "hpcod Terraform"); err != nil {
return err
}
e.Logf("created token %s!%s", terraformUser, terraformID)
}
if !tokenWorks(ctx, s, tf) {
return fmt.Errorf("no working Terraform token: give root's password, or paste one")
}
body := "# Written by `hpcod setup`. The token Terraform builds clusters with.\n" +
fmt.Sprintf("pve_token = %q\n", tf)
if err := e.writeFile(s.SecretsTFVars(), []byte(body), 0o640, owner); err != nil {
return err
}
}
e.Logf("Terraform token accepted, in %s", s.SecretsTFVars())
// From here on, the Terraform token does the work: it exists now
// whichever way setup was given access.
p := PVEWithToken(s["PVE_ENDPOINT"], insecure, tf)
node := s["PVE_NODE"]
if err := p.Get(ctx, "/nodes/"+node+"/status", &struct{}{}); err != nil {
return fmt.Errorf("no node %q on this Proxmox: %w", node, err)
}
// 3. The SDN zone, of the type the site's nodes need.
if err := ensureZone(ctx, p, s, e.Logf); err != nil {
return err
}
// 4. Content types. `content` replaces the list, so the new type is
// added to what is there - writing it alone would quietly stop the
// datastore holding what it held before.
if _, err := p.StorageContent(ctx, s["PVE_DATASTORE"]); err != nil {
return fmt.Errorf("no datastore %q: %w", s["PVE_DATASTORE"], err)
}
imgStore, imgRest, _ := strings.Cut(s["PVE_IMAGE"], ":")
for _, want := range [][2]string{{s["PVE_SNIPPET_DATASTORE"], "snippets"}, {imgStore, "import"}} {
if err := addContent(ctx, p, want[0], want[1]); err != nil {
return err
}
e.Logf("%s holds %s", want[0], want[1])
}
// 5. The cloud image the head template starts from.
has := func() bool {
vols, _ := p.Volumes(ctx, node, imgStore, "import")
for _, v := range vols {
if v == s["PVE_IMAGE"] {
return true
}
}
return false
}
if !has() {
file := path.Base(imgRest)
e.Logf("downloading %s to %s (a few minutes)", file, imgStore)
var upid string
if err := p.Post(ctx, "/nodes/"+node+"/storage/"+imgStore+"/download-url", url.Values{
"content": {"import"}, "filename": {file}, "url": {imageSourceURL + file}}, &upid); err != nil {
return fmt.Errorf("asking Proxmox to download %s: %w", file, err)
}
if err := p.WaitTask(ctx, node, upid, 20*time.Minute); err != nil {
return err
}
if !has() {
return fmt.Errorf("%s did not arrive", s["PVE_IMAGE"])
}
}
e.Logf("cloud image %s present", s["PVE_IMAGE"])
// The portal reads its token when it starts.
if wroteDisc && e.Root == "" {
if _, err := e.run(ctx, "", "systemctl", "is-active", "--quiet", Unit); err == nil {
e.Logf("restarting the portal for the new discovery token")
return stepStart(ctx, e)
}
}
return nil
}
// ensurePVESSH makes root SSH with the provisioner key work, installing the
// key with root's password if it has one.
func (e *Env) ensurePVESSH(ctx context.Context) error {
if c, err := e.PVESSH(ctx); err == nil {
c.Close()
e.Logf("root SSH to %s with the provisioner key", e.Site["PVE_HOST"])
return nil
}
pub, err := e.PublicKey()
if err != nil {
return err
}
if e.Creds.Password == "" {
return fmt.Errorf("cannot log in as root on %s with the provisioner key. There, as root:\n"+
" echo '%s' >> /root/.ssh/authorized_keys\nthen run setup again", e.Site["PVE_HOST"], pub)
}
c, err := dialSSH(ctx, e.Site["PVE_HOST"], "root", sshPassword(e.Creds.Password)...)
if err != nil {
return fmt.Errorf("root SSH to %s with the password failed (is password login allowed?): %w", e.Site["PVE_HOST"], err)
}
// On Proxmox /root/.ssh/authorized_keys is a link into /etc/pve, which
// is what makes the key good on every node of the cluster.
_, err = sshRun(c, fmt.Sprintf(
"mkdir -p /root/.ssh && touch /root/.ssh/authorized_keys && "+
"(grep -qxF '%[1]s' /root/.ssh/authorized_keys || echo '%[1]s' >> /root/.ssh/authorized_keys)", pub))
c.Close()
if err != nil {
return err
}
k, err := e.PVESSH(ctx)
if err != nil {
return fmt.Errorf("installed the key, and it is still refused: %w", err)
}
k.Close()
e.Logf("installed the provisioner key for root on %s", e.Site["PVE_HOST"])
return nil
}
// sshPassword answers both ways a server may ask for a password.
func sshPassword(pw string) []ssh.AuthMethod {
return []ssh.AuthMethod{ssh.Password(pw),
ssh.KeyboardInteractive(func(_, _ string, qs []string, _ []bool) ([]string, error) {
a := make([]string, len(qs))
for i := range a {
a[i] = pw
}
return a, nil
})}
}
func addContent(ctx context.Context, p *PVE, storage, t string) error {
have, err := p.StorageContent(ctx, storage)
if err != nil {
return fmt.Errorf("no datastore %q: %w", storage, err)
}
for _, c := range have {
if c == t {
return nil
}
}
if err := p.Put(ctx, "/storage/"+storage, url.Values{"content": {strings.Join(append(have, t), ",")}}); err != nil {
return fmt.Errorf("enabling %s on %s: %w", t, storage, err)
}
have, _ = p.StorageContent(ctx, storage)
for _, c := range have {
if c == t {
return nil
}
}
return fmt.Errorf("%s still does not hold %s", storage, t)
}
// tokenWorks checks a token by using it.
func tokenWorks(ctx context.Context, s Site, token string) bool {
if token == "" || strings.Contains(token, "CHANGE_ME") {
return false
}
p := PVEWithToken(s["PVE_ENDPOINT"], s["PVE_INSECURE_TLS"] == "true", token)
ctx, cancel := context.WithTimeout(ctx, 15*time.Second)
defer cancel()
return p.Get(ctx, "/nodes", &[]struct{}{}) == nil
}
// envValue reads KEY's value from a KEY=value file.
func envValue(path, key string) string {
raw, err := os.ReadFile(path)
if err != nil {
return ""
}
for _, l := range strings.Split(string(raw), "\n") {
if k, v, ok := strings.Cut(strings.TrimSpace(l), "="); ok && k == key {
return v
}
}
return ""
}
// setEnvValue replaces or adds KEY's line, keeping the rest of the file.
func setEnvValue(e *Env, path, key, value string) error {
raw, _ := os.ReadFile(e.P(path))
var out []string
for _, l := range strings.Split(strings.TrimRight(string(raw), "\n"), "\n") {
if k, _, ok := strings.Cut(l, "="); (ok && k == key) || l == "" {
continue
}
out = append(out, l)
}
out = append(out, key+"="+value)
if err := e.writeFile(path, []byte(strings.Join(out, "\n")+"\n"), 0o640, rootGroup); err != nil {
return err
}
if envValue(e.P(path), key) != value {
return fmt.Errorf("%s did not take %s", path, key)
}
return nil
}
// httpStatus is the status code of a GET, or 0 when nothing answered.
func httpStatus(ctx context.Context, u string) int {
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
if err != nil {
return 0
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return 0
}
resp.Body.Close()
return resp.StatusCode
}