package instancectl import ( "context" "encoding/json" "net/http" "net/http/httptest" "strings" "sync" "testing" "time" ) // set changes one answer under the fake's lock, for a test whose unit // moves on while a handler polls. func (f *fakeCtl) set(prefix, out string) { f.mu.Lock() f.answers[prefix] = out f.mu.Unlock() } const cmdShowAll = "show -p InvocationID,ActiveState,SubState,Result,ExecMainStatus,ExecMainCode" func fastCmd(s *Server) { s.cmdPollEvery = 5 * time.Millisecond s.cmdWaitBound = 300 * time.Millisecond s.cmdStartBound = 300 * time.Millisecond } func TestCmdStartsWithoutBlockingAndAnswersTheNewInvocation(t *testing.T) { ctl := &fakeCtl{answers: map[string]string{ "show -p ActiveState --value": "inactive\n", "show -p InvocationID --value": "old\n", }} ctl.onStart = func() { ctl.set("show -p InvocationID --value", "new\n") } _, c := newServer(t, ctl, fastCmd) resp := post(t, c, "/cmd?host=h.example.com&memory_max=536870912") if resp.StatusCode != 200 { t.Fatalf("status %d", resp.StatusCode) } var out StartResponse if err := json.NewDecoder(resp.Body).Decode(&out); err != nil || out.InvocationID != "new" { t.Fatalf("response %+v, %v", out, err) } calls := ctl.joined() for _, want := range []string{"set-property --runtime carlos-instances-h.example.com.slice", "start --no-block carlos-instance-cmd@h.example.com.service"} { if !strings.Contains(calls, want) { t.Errorf("missing %q in\n%s", want, calls) } } if strings.Contains(calls, "stop ") { t.Errorf("a started command was stopped:\n%s", calls) } } func TestCmdRefusesAUnitStillLoaded(t *testing.T) { for _, state := range []string{"active", "activating", "deactivating"} { ctl := &fakeCtl{answers: map[string]string{"show -p ActiveState --value": state + "\n"}} _, c := newServer(t, ctl, fastCmd) resp := post(t, c, "/cmd?host=h.example.com&memory_max=536870912") if resp.StatusCode != http.StatusConflict { t.Errorf("%s: status %d, want 409", state, resp.StatusCode) } if strings.Contains(ctl.joined(), "start ") { t.Errorf("%s: a loaded unit was started again:\n%s", state, ctl.joined()) } if strings.Contains(ctl.joined(), "stop ") { t.Errorf("%s: a loaded unit was stopped:\n%s", state, ctl.joined()) } } } func TestCmdConcurrentStartsForOneHostAreOneStartAndOneRefusal(t *testing.T) { ctl := &fakeCtl{answers: map[string]string{ "show -p ActiveState --value": "inactive\n", "show -p InvocationID --value": "old\n", }} // The start loads the unit and gives it a new invocation, as systemd does. ctl.onStart = func() { ctl.set("show -p ActiveState --value", "active\n") ctl.set("show -p InvocationID --value", "new\n") } _, c := newServer(t, ctl, fastCmd) codes := make([]int, 2) var wg sync.WaitGroup for i := range codes { wg.Add(1) go func() { defer wg.Done() codes[i] = post(t, c, "/cmd?host=h.example.com&memory_max=536870912").StatusCode }() } wg.Wait() ok, conflict := 0, 0 for _, code := range codes { switch code { case 200: ok++ case http.StatusConflict: conflict++ } } if ok != 1 || conflict != 1 { t.Fatalf("statuses %v, want one 200 and one 409", codes) } if strings.Contains(ctl.joined(), "stop ") { t.Errorf("the started unit was stopped:\n%s", ctl.joined()) } } func TestCmdResetsAFailedUnitBeforeTheStart(t *testing.T) { ctl := &fakeCtl{answers: map[string]string{ "show -p ActiveState --value": "failed\n", "show -p InvocationID --value": "old\n", }} ctl.onStart = func() { ctl.set("show -p InvocationID --value", "new\n") } _, c := newServer(t, ctl, fastCmd) if resp := post(t, c, "/cmd?host=h.example.com&memory_max=536870912"); resp.StatusCode != 200 { t.Fatalf("status %d", resp.StatusCode) } calls := ctl.joined() if r, s := strings.Index(calls, "reset-failed carlos-instance-cmd@"), strings.Index(calls, "start --no-block"); r < 0 || s < 0 || r > s { t.Errorf("reset-failed must come before the start:\n%s", calls) } } func TestCmdStopsAUnitThatNeverReportsAnInvocation(t *testing.T) { ctl := &fakeCtl{answers: map[string]string{ "show -p ActiveState --value": "inactive\n", "show -p InvocationID --value": "old\n", }} _, c := newServer(t, ctl, fastCmd) if resp := post(t, c, "/cmd?host=h.example.com&memory_max=536870912"); resp.StatusCode != http.StatusBadGateway { t.Fatalf("status %d, want 502", resp.StatusCode) } if !strings.Contains(ctl.joined(), "stop carlos-instance-cmd@h.example.com.service") { t.Errorf("the unit was not stopped:\n%s", ctl.joined()) } } func getStatus(t *testing.T, c *http.Client, path string) CmdStatus { t.Helper() resp, err := c.Get("http://unix" + path) if err != nil { t.Fatal(err) } defer resp.Body.Close() if resp.StatusCode != 200 { t.Fatalf("GET %s: status %d", path, resp.StatusCode) } var st CmdStatus if err := json.NewDecoder(resp.Body).Decode(&st); err != nil { t.Fatal(err) } return st } func TestCmdStatusLongPollsUntilDone(t *testing.T) { ctl := &fakeCtl{answers: map[string]string{ cmdShowAll: "InvocationID=inv1\nActiveState=activating\nSubState=start\nResult=success\nExecMainStatus=0\nExecMainCode=0\n", }} _, c := newServer(t, ctl, fastCmd) go func() { time.Sleep(50 * time.Millisecond) ctl.set(cmdShowAll, "InvocationID=inv1\nActiveState=active\nSubState=exited\nResult=success\nExecMainStatus=3\nExecMainCode=1\n") }() st := getStatus(t, c, "/cmd/h.example.com?invocation=inv1") if st.State != CmdDone || st.Status != "3" || st.Code != "1" || st.InvocationID != "inv1" { t.Fatalf("status = %+v", st) } } func TestCmdStatusAnswersRunningAtTheBound(t *testing.T) { ctl := &fakeCtl{answers: map[string]string{ cmdShowAll: "InvocationID=inv1\nActiveState=activating\nSubState=start\nResult=success\nExecMainStatus=0\nExecMainCode=0\n", }} _, c := newServer(t, ctl, fastCmd) start := time.Now() if st := getStatus(t, c, "/cmd/h.example.com?invocation=inv1"); st.State != CmdRunning { t.Fatalf("status = %+v", st) } if took := time.Since(start); took < 250*time.Millisecond { t.Errorf("answered running after %s, before the bound", took) } } func TestCmdStatusDoneCoversFailedAndInactive(t *testing.T) { for _, show := range []string{ "InvocationID=inv1\nActiveState=failed\nSubState=failed\nResult=exit-code\nExecMainStatus=1\nExecMainCode=1\n", "InvocationID=inv1\nActiveState=inactive\nSubState=dead\nResult=success\nExecMainStatus=0\nExecMainCode=1\n", } { ctl := &fakeCtl{answers: map[string]string{cmdShowAll: show}} _, c := newServer(t, ctl, fastCmd) if st := getStatus(t, c, "/cmd/h.example.com?invocation=inv1"); st.State != CmdDone { t.Errorf("%q: state %s, want done", show, st.State) } } } func TestCmdStatusIsGoneForAnotherInvocation(t *testing.T) { for _, show := range []string{ "InvocationID=inv2\nActiveState=active\nSubState=exited\nResult=success\nExecMainStatus=0\nExecMainCode=1\n", "InvocationID=\nActiveState=inactive\nSubState=dead\nResult=success\nExecMainStatus=0\nExecMainCode=0\n", } { ctl := &fakeCtl{answers: map[string]string{cmdShowAll: show}} _, c := newServer(t, ctl, fastCmd) if st := getStatus(t, c, "/cmd/h.example.com?invocation=inv1"); st.State != CmdGone { t.Errorf("%q: state %s, want gone", show, st.State) } } } func TestCmdRoutesRefuseWithClaimControlArmed(t *testing.T) { called := false s := &Server{ClaimStop: http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}), Systemctl: func(context.Context, ...string) (string, error) { called = true; return "", nil }} for _, req := range []*http.Request{ httptest.NewRequest(http.MethodPost, "/cmd?host=app.example&memory_max=536870912", nil), httptest.NewRequest(http.MethodGet, "/cmd/app.example?invocation=x", nil), } { w := httptest.NewRecorder() s.Handler().ServeHTTP(w, req) if w.Code != http.StatusServiceUnavailable { t.Errorf("%s %s: status %d", req.Method, req.URL, w.Code) } } if called { t.Fatal("a cmd route reached systemctl with claim control armed") } } func TestClientCmdAndCmdStatus(t *testing.T) { ctl := &fakeCtl{answers: map[string]string{ "show -p ActiveState --value": "inactive\n", "show -p InvocationID --value": "old\n", cmdShowAll: "InvocationID=new\nActiveState=failed\nSubState=failed\nResult=exit-code\nExecMainStatus=2\nExecMainCode=1\n", }} ctl.onStart = func() { ctl.set("show -p InvocationID --value", "new\n") } _, cl := newClient(t, ctl, fastCmd) inv, err := cl.Cmd(context.Background(), "h.example.com", 536870912) if err != nil || inv != "new" { t.Fatalf("Cmd = %q, %v", inv, err) } st, err := cl.CmdStatus(context.Background(), "h.example.com", inv) if err != nil || st.State != CmdDone || st.Status != "2" { t.Fatalf("CmdStatus = %+v, %v", st, err) } }