Files
ilkerandClaude Opus 5 47db704f1b hpcod: the longest step in a build now says it is still working
Waiting for a head node's portal is where a build spends most of its
time - the machine is installing and configuring itself - and it
wrote one line and then nothing for up to ten minutes. Silence is
indistinguishable from a hang. Somebody watching the log concluded
the build had stopped, twice, and both times it was working
correctly and finished a few minutes later.

It now reports what it is waiting on and for how long, every few
attempts rather than on a clock of its own, so the pacing follows
whatever interval the caller chose: half a minute apart at the ten
seconds a build uses, and still present in a test whose whole budget
is shorter than that. A portal that answers at once still prints
nothing, because there was nothing to wait for.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-22 10:49:25 +02:00

227 lines
7.0 KiB
Go

package provision
import (
"context"
"crypto/tls"
"encoding/pem"
"fmt"
"io"
"os"
"path/filepath"
"sort"
"time"
"gopkg.in/yaml.v3"
)
// Publishing is what makes a built cluster reachable at its own name.
//
// It was a script somebody ran by hand, and when building moved into the
// portal nothing called it any more - so clusters were built, worked, and
// could not be reached, which is how a running cluster came to answer
// with the control plane's front page.
//
// Two things go into the registry: where the portal is, and the
// certificate the proxy will accept from it and nothing else.
// Registry is where the proxy reads its routing from.
type Registry struct {
Path string // the YAML file
CertDir string // where each cluster's pinned certificate is kept
}
type registryFile struct {
Clusters []registryEntry `yaml:"clusters"`
}
type registryEntry struct {
ID int `yaml:"id"`
Portal string `yaml:"portal"`
Cert string `yaml:"cert"`
}
// Publish records a cluster's portal and pins the certificate it is
// presenting now.
//
// Pinning on first sight is a real trust decision and this is the moment
// to make it: the machine was created seconds ago, at an address this
// control plane assigned, on a network it runs. From here on a different
// certificate means a different machine, and the proxy refuses it - which
// is the property worth having, and the one a shared internal CA would
// not give.
func (r Registry) Publish(ctx context.Context, clusterID int16, addr string) error {
cert, err := firstCertificate(ctx, addr)
if err != nil {
return err
}
if err := os.MkdirAll(r.CertDir, 0o750); err != nil {
return err
}
certPath := filepath.Join(r.CertDir, fmt.Sprintf("c%03d.crt", clusterID))
pemBytes := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: cert})
if err := os.WriteFile(certPath, pemBytes, 0o644); err != nil {
return err
}
return r.upsert(int(clusterID), addr, certPath)
}
// Unpublish removes a cluster from the registry, so its name stops
// resolving to a machine that is no longer there.
func (r Registry) Unpublish(clusterID int16) error {
doc, err := r.read()
if err != nil {
return err
}
out := doc.Clusters[:0]
for _, e := range doc.Clusters {
if e.ID != int(clusterID) {
out = append(out, e)
}
}
doc.Clusters = out
return r.write(doc)
}
func (r Registry) upsert(id int, addr, certPath string) error {
doc, err := r.read()
if err != nil {
return err
}
found := false
for i := range doc.Clusters {
if doc.Clusters[i].ID == id {
doc.Clusters[i] = registryEntry{ID: id, Portal: addr, Cert: certPath}
found = true
break
}
}
if !found {
doc.Clusters = append(doc.Clusters, registryEntry{ID: id, Portal: addr, Cert: certPath})
}
sort.Slice(doc.Clusters, func(i, j int) bool { return doc.Clusters[i].ID < doc.Clusters[j].ID })
return r.write(doc)
}
func (r Registry) read() (*registryFile, error) {
raw, err := os.ReadFile(r.Path)
if os.IsNotExist(err) {
return &registryFile{}, nil
}
if err != nil {
return nil, err
}
var doc registryFile
if err := yaml.Unmarshal(raw, &doc); err != nil {
return nil, fmt.Errorf("%s: %w", r.Path, err)
}
return &doc, nil
}
// write replaces the file atomically. The proxy re-reads it whenever it
// changes, and half a file would take every cluster offline.
func (r Registry) write(doc *registryFile) error {
body, err := yaml.Marshal(doc)
if err != nil {
return err
}
header := []byte("# Written by hpcod when a cluster is built. Do not edit by hand.\n")
tmp := r.Path + ".tmp"
if err := os.WriteFile(tmp, append(header, body...), 0o644); err != nil {
return err
}
return os.Rename(tmp, r.Path)
}
// firstCertificate connects to the portal and returns what it presents.
//
// The handshake is deliberately unverified: there is nothing to verify
// against yet, and capturing the certificate is the whole purpose of the
// call. Nothing is sent over this connection and nothing read from it is
// trusted - the bytes become the pin that every later connection is
// checked against, and any change from here on is refused.
func firstCertificate(ctx context.Context, addr string) ([]byte, error) {
d := &tls.Dialer{Config: &tls.Config{
InsecureSkipVerify: true, //nolint:gosec // capture-to-pin; see above
MinVersion: tls.VersionTLS12,
}}
conn, err := d.DialContext(ctx, "tcp", addr)
if err != nil {
return nil, fmt.Errorf("reaching the portal at %s: %w", addr, err)
}
defer conn.Close()
state := conn.(*tls.Conn).ConnectionState()
if len(state.PeerCertificates) == 0 {
return nil, fmt.Errorf("%s presented no certificate", addr)
}
return state.PeerCertificates[0].Raw, nil
}
// waitForPortal gives the head time to finish booting and configuring
// itself. Publishing the moment Terraform returns would pin nothing,
// because nothing is listening yet.
func waitForPortal(ctx context.Context, addr string, every, limit time.Duration, progress io.Writer) error {
// Say something while waiting. This is the longest step in a build by
// a wide margin - the head is installing and configuring itself - and
// it used to write one line and then nothing for up to ten minutes.
// Silence is indistinguishable from a hang, and the person watching
// the log reasonably concluded the build had stopped.
//
// Every few attempts rather than every N seconds, so the reporting
// keeps pace with whatever the caller chose: half a minute apart at
// the ten-second interval a build uses, and still present in a test
// whose whole budget is shorter than that.
const reportEvery = 3
started := time.Now()
attempts := 0
deadline := started.Add(limit)
var last error
for time.Now().Before(deadline) {
// Bound the attempt, not just the loop. A dial to an address that
// routes nowhere does not fail: it hangs until the operating
// system gives up, which is about seventy-five seconds. One of
// those inside a ten-minute wait costs eight attempts, and a few
// of them can swallow the whole budget without the loop ever
// noticing it is being starved.
//
// Never longer than the budget has left, either, or the last
// attempt outlives the deadline it was checked against.
per := every
if left := time.Until(deadline); left < per {
per = left
}
attempt, cancel := context.WithTimeout(ctx, per)
_, err := firstCertificate(attempt, addr)
cancel()
if err == nil {
return nil
}
last = err
attempts++
if progress != nil && attempts%reportEvery == 0 {
fmt.Fprintf(progress, " still waiting after %s: %v\n",
time.Since(started).Round(time.Second), last)
}
// And the pause between attempts is bounded the same way. It was
// not, so a wait of 200ms with a 10s interval slept for the full
// ten seconds before rechecking a deadline that had passed in the
// first fifth of a second.
pause := every
if left := time.Until(deadline); left < pause {
pause = left
}
if pause <= 0 {
break
}
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(pause):
}
}
return fmt.Errorf("the portal at %s did not come up: %w", addr, last)
}