Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions csi-driver/cmd/mds-agent/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import (
"flag"
"net"
"os"
"os/exec"
"os/signal"
"strconv"
"syscall"
Expand Down Expand Up @@ -80,6 +81,22 @@ func reconcilePaths(ctx context.Context, conn lvol.Connection, hostNQN string) (
return nvmeof.ReconcilePaths(ctx, connector, nil, conn, opts...)
}

const (
// stateDevice is the state disk QEMU attaches with serial pnfs-state.
stateDevice = "/dev/disk/by-id/virtio-pnfs-state"
// gateFile lets the image's nfsd units start.
gateFile = "/run/mds/active"
// stateTmpfiles recreates what the state mount hides.
stateTmpfiles = "/usr/lib/tmpfiles.d/pnfs.conf"

activateRetryInterval = 2 * time.Second
)

// runCommand runs one command in the guest and returns its combined output.
func runCommand(ctx context.Context, name string, args ...string) ([]byte, error) {
return exec.CommandContext(ctx, name, args...).CombinedOutput()
}

func run(ctx context.Context, listen, stateDir string, watchdog, pathInterval time.Duration) error {
// No host NQN function: the identity arrives with every call, decided by
// the operator and resolved by the runner.
Expand All @@ -101,6 +118,19 @@ func run(ctx context.Context, listen, stateDir string, watchdog, pathInterval ti
healthpb.RegisterHealthServer(server, healthServer)

mounter := mountutils.New("")
// A guest image built for the warm standby leaves the state disk unmounted
// and nfsd stopped until it is promoted. Nothing promotes the only metadata
// server, so it activates itself.
activation := agent.Activation{
StateDevice: stateDevice,
StateDir: stateDir,
GateFile: gateFile,
Tmpfiles: stateTmpfiles,
Mounted: mounter.IsMountPoint,
Run: runCommand,
Log: agent.KlogLogger{},
}
go activation.ActivateUntilDone(ctx, activateRetryInterval)
go agent.Report(ctx, healthServer, agent.Health{
StateDir: stateDir,
Mounted: mounter.IsMountPoint,
Expand Down
128 changes: 128 additions & 0 deletions csi-driver/internal/mds/agent/activate.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
// Making the guest the active metadata server at boot, when it is the only one.
//
// A guest image built for the warm standby boots without its state mounted and
// without nfsd, which wait for a gate file the agent creates on promotion. With
// no standby there is nothing to promote it, so the agent activates the guest
// itself. On an image that still mounts the state disk and starts nfsd at boot,
// every step finds its work done.

package agent

import (
"context"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"time"
)

// The units started, in this order: nfsd reads the client-recovery database
// through nfsdcld the moment its threads start.
var activationUnits = []string{"nfsdcld.service", "nfs-mountd.service", "nfs-server.service"}

// blkidNothingFound is blkid's exit status for a device with no filesystem.
const blkidNothingFound = 2

// Command runs one command and returns its combined output. An error that has
// an ExitCode method reports the command's exit status.
type Command func(ctx context.Context, name string, args ...string) ([]byte, error)

// Activation is what activating the guest touches.
type Activation struct {
// StateDevice is the state disk, StateDir where it is mounted.
StateDevice string
StateDir string
// GateFile lets the guest's nfsd units start.
GateFile string
// Tmpfiles recreates what the state mount hides, when the image has it.
Tmpfiles string
Mounted func(dir string) (bool, error)
Run Command
Log Logger
}

// Activate makes the guest serve: the state disk mounted, the gate open, and
// nfsd started.
func (a Activation) Activate(ctx context.Context) error {
if err := a.mountState(ctx); err != nil {
return err
}
if a.Tmpfiles != "" {
if _, err := os.Stat(a.Tmpfiles); err == nil {
if err := a.run(ctx, "systemd-tmpfiles", "--create", a.Tmpfiles); err != nil {
return err
}
}
}
if err := os.MkdirAll(filepath.Dir(a.GateFile), 0o755); err != nil {
return fmt.Errorf("creating the gate file's directory: %w", err)
}
if err := os.WriteFile(a.GateFile, nil, 0o644); err != nil {
return fmt.Errorf("creating the gate file: %w", err)
}
for _, unit := range activationUnits {
if err := a.run(ctx, "systemctl", "start", unit); err != nil {
return err
}
}
return nil
}

// mountState mounts the state disk unless it is mounted already, formatting it
// only when blkid finds no filesystem on it. A blkid that fails otherwise has
// not read the disk, and formatting then would destroy the client-recovery
// database.
func (a Activation) mountState(ctx context.Context) error {
mounted, err := a.Mounted(a.StateDir)
if err != nil {
return fmt.Errorf("inspecting %s: %w", a.StateDir, err)
}
if mounted {
return nil
}
out, err := a.Run(ctx, "blkid", "-p", "-o", "value", "-s", "TYPE", a.StateDevice)
var exit interface{ ExitCode() int }
switch {
case err == nil && strings.TrimSpace(string(out)) != "":
case err != nil && errors.As(err, &exit) && exit.ExitCode() == blkidNothingFound:
if err := a.run(ctx, "mkfs.ext4", "-q", a.StateDevice); err != nil {
return err
}
default:
return fmt.Errorf("reading the state disk %s: %w (%s)", a.StateDevice, err, strings.TrimSpace(string(out)))
}
if err := os.MkdirAll(a.StateDir, 0o755); err != nil {
return fmt.Errorf("creating %s: %w", a.StateDir, err)
}
return a.run(ctx, "mount", "-t", "ext4", "-o", "noatime", a.StateDevice, a.StateDir)
}

func (a Activation) run(ctx context.Context, name string, args ...string) error {
if out, err := a.Run(ctx, name, args...); err != nil {
return fmt.Errorf("%s %s: %w (%s)", name, strings.Join(args, " "), err, strings.TrimSpace(string(out)))
}
return nil
}

// ActivateUntilDone retries Activate until it succeeds or ctx ends.
func (a Activation) ActivateUntilDone(ctx context.Context, interval time.Duration) {
for {
err := a.Activate(ctx)
if err == nil {
if a.Log != nil {
a.Log.Infof("the guest is active: state disk mounted at %s, nfsd started", a.StateDir)
}
return
}
if a.Log != nil {
a.Log.Warningf("activating the guest: %v", err)
}
select {
case <-ctx.Done():
return
case <-time.After(interval):
}
}
}
118 changes: 118 additions & 0 deletions csi-driver/internal/mds/agent/activate_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
package agent

import (
"context"
"errors"
"os"
"path/filepath"
"slices"
"strings"
"testing"
)

// exitError is a failed command with an exit status, as exec.ExitError is.
type exitError int

func (e exitError) Error() string { return "exit status " + string(rune('0'+int(e))) }
func (e exitError) ExitCode() int { return int(e) }

// guest is a fake guest: the commands it ran, whether its state is mounted, and
// what blkid finds on the state disk.
type guest struct {
ran []string
mounted bool
blkid func() ([]byte, error)
}

func (g *guest) run(_ context.Context, name string, args ...string) ([]byte, error) {
cmd := strings.Join(append([]string{name}, args...), " ")
g.ran = append(g.ran, cmd)
switch name {
case "blkid":
return g.blkid()
case "mount":
g.mounted = true
}
return nil, nil
}

func (g *guest) ranAny(prefix string) bool {
return slices.ContainsFunc(g.ran, func(c string) bool { return strings.HasPrefix(c, prefix) })
}

func activation(t *testing.T, g *guest) Activation {
t.Helper()
return Activation{
StateDevice: "/dev/disk/by-id/virtio-pnfs-state",
StateDir: filepath.Join(t.TempDir(), "var", "lib", "nfs"),
GateFile: filepath.Join(t.TempDir(), "mds", "active"),
Tmpfiles: "/usr/lib/tmpfiles.d/pnfs.conf",
Mounted: func(string) (bool, error) { return g.mounted, nil },
Run: g.run,
}
}

// Regression: 2026-11-11-standby-guest-never-activated. The guest image moved
// to a warm-standby boot: no state mount, and nfsd gated on /run/mds/active,
// which only a promotion creates. Nothing on this operator promotes, so every
// metadata server built from the moving pnfsos tag stayed unhealthy with "the
// state disk is not mounted" until its boot deadline restarted the pod, and
// pNFS was down on every cluster that picked the image up.
func TestAGuestBootedAsAStandbyIsActivated(t *testing.T) {
g := &guest{blkid: func() ([]byte, error) { return []byte("ext4\n"), nil }}
a := activation(t, g)

if err := a.Activate(context.Background()); err != nil {
t.Fatalf("Activate: %v", err)
}
if !g.mounted {
t.Error("the state disk was not mounted")
}
if _, err := os.Stat(a.GateFile); err != nil {
t.Errorf("the gate file was not created: %v", err)
}
if !g.ranAny("systemctl start nfs-server.service") {
t.Errorf("nfsd was not started; ran %q", g.ran)
}
if g.ranAny("mkfs") {
t.Error("a state disk carrying a filesystem was formatted")
}
}

// A blank state disk, as on a first boot, is formatted before it is mounted.
func TestABlankStateDiskIsFormattedFirst(t *testing.T) {
g := &guest{blkid: func() ([]byte, error) { return nil, exitError(2) }}
if err := activation(t, g).Activate(context.Background()); err != nil {
t.Fatalf("Activate: %v", err)
}
mkfs := slices.IndexFunc(g.ran, func(c string) bool { return strings.HasPrefix(c, "mkfs.ext4") })
mount := slices.IndexFunc(g.ran, func(c string) bool { return strings.HasPrefix(c, "mount") })
if mkfs < 0 || mount < mkfs {
t.Errorf("want mkfs.ext4 before mount; ran %q", g.ran)
}
}

// blkid failing to read the disk says nothing about whether it holds a
// filesystem. Formatting then would destroy the client-recovery database, so
// activation fails and is retried instead.
func TestAnUnreadableStateDiskIsNeverFormatted(t *testing.T) {
g := &guest{blkid: func() ([]byte, error) { return nil, exitError(4) }}
if err := activation(t, g).Activate(context.Background()); err == nil {
t.Error("Activate succeeded on a state disk blkid could not read")
}
if g.ranAny("mkfs") {
t.Errorf("an unreadable state disk was formatted; ran %q", g.ran)
}
}

// An image that mounts the state disk and starts nfsd at boot is left as it is:
// nothing is mounted again, and starting running units changes nothing.
func TestAGuestAlreadyServingIsLeftAsItIs(t *testing.T) {
g := &guest{mounted: true, blkid: func() ([]byte, error) { return nil, errors.New("not called") }}
if err := activation(t, g).Activate(context.Background()); err != nil {
t.Fatalf("Activate: %v", err)
}
if g.ranAny("blkid") || g.ranAny("mount") || g.ranAny("mkfs") {
t.Errorf("a mounted state disk was touched; ran %q", g.ran)
}
}
Loading
Loading