Skip to content
quarry Artifact [5784089a69]
Login

Artifact [5784089a69]

Artifact 5784089a69951cfc2e27fdc5d66e8032c822ebc19956bc92e3d879b69fda2f75:


package main

import (
	"os"
	"path/filepath"
	"slices"
	"testing"
)

func writeProc(t *testing.T, dir, name, body string) {
	t.Helper()
	p := filepath.Join(dir, name)
	if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
		t.Fatal(err)
	}
	if err := os.WriteFile(p, []byte(body), 0o644); err != nil {
		t.Fatal(err)
	}
}

const (
	psiCalm   = "some avg10=0.50 avg60=0.10 avg300=0.00 total=1\nfull avg10=0.00 avg60=0.00 avg300=0.00 total=0\n"
	psiHot    = "some avg10=12.50 avg60=3.00 avg300=1.00 total=1\nfull avg10=9.00 avg60=0.00 avg300=0.00 total=0\n"
	memPlenty = "MemTotal: 16000000 kB\nMemAvailable:    8000000 kB\n"
	memShort  = "MemTotal: 16000000 kB\nMemAvailable:    1000000 kB\n"
)

func TestMemoryPressureReadsPSIAndMemAvailable(t *testing.T) {
	cases := []struct {
		name, psi, mem string
		want           bool
	}{
		{"calm", psiCalm, memPlenty, false},
		{"stalled", psiHot, memPlenty, true},
		{"short of memory", psiCalm, memShort, true},
		{"no psi, plenty", "", memPlenty, false},
		{"no psi, short", "", memShort, true},
		{"just over the stall threshold", "some avg10=10.01 avg60=0 avg300=0 total=0\n", memPlenty, true},
		{"at the stall threshold", "some avg10=10.00 avg60=0 avg300=0 total=0\n", memPlenty, false},
	}
	for _, c := range cases {
		dir := t.TempDir()
		if c.psi != "" {
			writeProc(t, dir, "pressure/memory", c.psi)
		}
		writeProc(t, dir, "meminfo", c.mem)
		if got := memoryPressure(dir); got != c.want {
			t.Errorf("FAIL: %s: pressure=%v, want %v", c.name, got, c.want)
		}
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

// Off Linux (or with /proc unreadable) there is nothing to read and so
// nothing to wait on.
func TestNoProcMeansNoMemoryPressure(t *testing.T) {
	if memoryPressure(filepath.Join(t.TempDir(), "absent")) {
		t.Errorf("FAIL: an unreadable /proc reads as pressure")
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

// Each signal that is up is named; none up is an empty list.
func TestMaintLoadNamesEverySignalThatIsUp(t *testing.T) {
	s := loadSources{zitBusy: func() bool { return true }, memory: func() bool { return true },
		deploy: func() bool { return true }, backup: func() bool { return true }}
	if got := s.reasons(); len(got) != 4 {
		t.Errorf("FAIL: %v, want four reasons", got)
	}
	s.memory, s.backup = func() bool { return false }, func() bool { return false }
	got := s.reasons()
	if len(got) != 2 || slices.Contains(got, maintWaitMemory) || !slices.Contains(got, maintWaitDeploy) || !slices.Contains(got, maintWaitZit) {
		t.Errorf("FAIL: %v, want the store gate and the deploy", got)
	}
	if got := (loadSources{}).reasons(); len(got) != 0 {
		t.Errorf("FAIL: nil probes read as load: %v", got)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}