You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/agent/worker/executor_test.go

153 lines
4.9 KiB
Go

package worker
import (
"context"
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"strconv"
"syscall"
"testing"
"time"
"git.luoli.live/root/virt/agent/auth"
)
func validRequest(operationID string) Request {
requestTarget := "/v1/vms/123e4567-e89b-42d3-a456-426614174000/power"
body := `{"operation_id":"` + operationID + `","action":"reboot"}`
return Request{
Version: ProtocolVersion,
Method: "POST",
RequestTarget: requestTarget,
Body: body,
Actor: auth.Actor{UserID: 1, CanManage: true, OperationID: operationID},
OperationID: operationID,
Fingerprint: Fingerprint("POST", requestTarget, []byte(body)),
}
}
func TestRequestRequiresExactActorOperationIdentity(t *testing.T) {
request := validRequest("operation-worker-identity")
if err := request.Validate(); err != nil {
t.Fatalf("valid request: %v", err)
}
missing := request
missing.Actor.OperationID = ""
if err := missing.Validate(); err == nil {
t.Fatal("missing actor operation ID was accepted")
}
mismatch := request
mismatch.Actor.OperationID = "operation-worker-other"
if err := mismatch.Validate(); err == nil {
t.Fatal("mismatched actor operation ID was accepted")
}
}
func TestReceiptPublicationIsImmutable(t *testing.T) {
path := filepath.Join(t.TempDir(), "operation-receipt", workerReceiptName)
request := validRequest("operation-immutable-receipt")
first := Response{
Version: ProtocolVersion, OperationID: request.OperationID, Fingerprint: request.Fingerprint,
Status: "succeeded", Result: json.RawMessage(`{"accepted":true}`),
}
if err := WriteReceipt(path, first); err != nil {
t.Fatal(err)
}
second := first
second.Result = json.RawMessage(`{"accepted":false}`)
if err := WriteReceipt(path, second); err == nil {
t.Fatal("second receipt replaced immutable completion")
}
stored, err := ReadReceipt(path)
if err != nil || string(stored.Result) != `{"accepted":true}` {
t.Fatalf("stored receipt = %#v err=%v", stored, err)
}
}
func TestExistingOperationDirectoryNeverSpawnsSecondWorker(t *testing.T) {
temp := t.TempDir()
executable := filepath.Join(temp, "must-not-run")
marker := filepath.Join(temp, "spawned")
script := "#!/bin/sh\n: > " + strconv.Quote(marker) + "\nexit 0\n"
if err := os.WriteFile(executable, []byte(script), 0o700); err != nil {
t.Fatal(err)
}
configPath := filepath.Join(temp, "config.json")
if err := os.WriteFile(configPath, []byte(`{}`), 0o600); err != nil {
t.Fatal(err)
}
stateDir := filepath.Join(temp, "workers")
executor, err := NewSubprocessExecutor(executable, configPath, stateDir)
if err != nil {
t.Fatal(err)
}
request := validRequest("operation-existing-directory")
if err := os.Mkdir(filepath.Join(stateDir, request.OperationID), 0o700); err != nil {
t.Fatal(err)
}
_, err = executor.Execute(context.Background(), request)
var workerErr *Error
if !errors.As(err, &workerErr) || workerErr.Code != ResultUnconfirmed || !workerErr.EffectMayHaveApplied {
t.Fatalf("existing directory result = %#v err=%v", workerErr, err)
}
if _, statErr := os.Stat(marker); !errors.Is(statErr, os.ErrNotExist) {
t.Fatalf("duplicate worker was spawned: %v", statErr)
}
}
func TestCancellationReapsHelperBeforeExecuteReturns(t *testing.T) {
temp := t.TempDir()
executable := filepath.Join(temp, "blocking-worker")
pidPath := filepath.Join(temp, "worker.pid")
script := fmt.Sprintf("#!/bin/sh\necho $$ > %s\ntrap 'exit 0' TERM INT\nwhile :; do sleep 1; done\n", strconv.Quote(pidPath))
if err := os.WriteFile(executable, []byte(script), 0o700); err != nil {
t.Fatal(err)
}
configPath := filepath.Join(temp, "config.json")
if err := os.WriteFile(configPath, []byte(`{}`), 0o600); err != nil {
t.Fatal(err)
}
executor, err := NewSubprocessExecutor(executable, configPath, filepath.Join(temp, "workers"))
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithCancel(context.Background())
done := make(chan error, 1)
go func() {
_, executeErr := executor.Execute(ctx, validRequest("operation-cancel-reap"))
done <- executeErr
}()
deadline := time.Now().Add(10 * time.Second)
var pid int
for {
pidBytes, readErr := os.ReadFile(pidPath)
if readErr == nil {
if _, scanErr := fmt.Sscanf(string(pidBytes), "%d", &pid); scanErr == nil && pid > 0 {
break
}
}
if readErr != nil && !errors.Is(readErr, os.ErrNotExist) {
t.Fatal(readErr)
}
if time.Now().After(deadline) {
t.Fatalf("helper did not publish a valid pid: %v", readErr)
}
time.Sleep(time.Millisecond)
}
cancel()
err = <-done
var workerErr *Error
if !errors.As(err, &workerErr) || workerErr.Code != ResultUnconfirmed {
t.Fatalf("canceled worker result = %#v err=%v", workerErr, err)
}
if err := syscall.Kill(pid, 0); !errors.Is(err, syscall.ESRCH) {
t.Fatalf("Execute returned before worker was reaped; kill(0) err=%v", err)
}
if _, statErr := os.Stat(pidPath); statErr != nil {
t.Fatalf("worker pid evidence disappeared: %v", statErr)
}
}