Skip to content
Open
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ Notable changes to Innerwall, newest first. Versions follow semantic versioning;

## Unreleased

- **A control-plane shutdown records every open stream's workload offline** (#113). Shutdown gives open agent calls ten seconds to end, which sync streams never do on their own, and then ends them; it returned without waiting for their handlers, and `serve` closed its database connections while the handlers were writing their workloads' offline marks, so marks failed with `closed pool` (logged as `marking workload offline`) and those workloads went on reading as they did while connected until their agents next connected. Once it has ended the streams, shutdown now waits for every agent call's handler to return, for at most five seconds more, before the connections close; a handler still running then is logged once at warning level, and what it still writes fails as before. A stop with agents connected takes at most fifteen seconds, up from ten. Nothing in the agent, the wire contract, or the schema changes.
- **A change to enforced outside the simulation review shows the evidence and asks for the acknowledgment** (#94). The fleet's **Change mode for selected…** and the **change…** beside the mode on the workload page set any mode in one step, enforced included: a workload enrolled minutes earlier, with no flows and no time in simulation, could be enforced with one click, with no verdict and no acknowledgment, while the review's promotion asks for one past any verdict that is not safe. A change to enforced from either dialog now reads, for each workload it would move, the verdict the review composes for that workload alone over the review's default range (the last 24 hours), with the same reads and the same composition, and draws the review's verdict block. When every such workload's verdict is safe, the change is one step, as a promotion is. Otherwise the block counts them ("No simulation evidence for N of M selected", "Not safe to enforce for N of M selected"), lists the workloads behind each count with the review's reason, and the confirm, "Enforce anyway on N workloads", writes nothing until one acknowledgment for the selection is checked. While the evidence is read, or if it cannot be, nothing is written. The dialog stays the deliberate way to enforce what the review would not offer, such as a re-enrolled host whose previous identity earned enforcement. Changes to visibility or simulation stay one step. Console only: `innerwall workload set-mode` and `POST /api/v1/mode-changes` still accept a change to enforced with no evidence and no acknowledgment. ADR-0001 takes a dated amendment.

## v0.5.2 — an entry admits what it says, and renewal survives a suspend
Expand Down
41 changes: 38 additions & 3 deletions cmd/innerwall/serve.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"errors"
"flag"
"fmt"
"io"
"io/fs"
"log/slog"
"net"
Expand Down Expand Up @@ -39,6 +40,16 @@ const (
serverKeyFile = "server.key"
)

// shutdownGrace is how long shutdown gives open agent calls and operator
// requests to end on their own once the listeners stop accepting.
const shutdownGrace = 10 * time.Second

// handlerExitGrace is how long shutdown then waits, once it has ended the
// agent calls still open, for their handlers to return before the store
// closes. A sync stream's handler writes its workload's offline mark on
// the way out, a write the gateway bounds at five seconds of its own.
const handlerExitGrace = 5 * time.Second

// renderer narrows the engine to the authoring service's interface.
type renderer struct{ eng *compiler.Engine }

Expand Down Expand Up @@ -127,6 +138,12 @@ func gatewayCredentials(ctx context.Context, backend authorityBackend, cfg gatew
}

func runServe(ctx context.Context, args []string) error {
return serve(ctx, args, os.Stderr)
}

// serve is runServe with the log written to logOut, so a test can read
// what the control plane logged.
func serve(ctx context.Context, args []string, logOut io.Writer) error {
fs := flag.NewFlagSet("innerwall serve", flag.ContinueOnError)
listen := fs.String("listen", defaultListen, "address for the agent gateway (gRPC over TLS)")
operatorListen := fs.String("operator-listen", defaultOperatorListen, "address for the operator surface (REST/JSON façade and console, TLS only)")
Expand Down Expand Up @@ -155,7 +172,7 @@ func runServe(ctx context.Context, args []string) error {
return fmt.Errorf("--gateway-advertise-address: %w", err)
}

log := slog.New(slog.NewTextHandler(os.Stderr, nil))
log := slog.New(slog.NewTextHandler(logOut, nil))
slog.SetDefault(log)

url, err := databaseURL(*dbURL)
Expand Down Expand Up @@ -287,8 +304,12 @@ func runServe(ctx context.Context, args []string) error {
select {
case <-ctx.Done():
log.Info("shutting down")
stopCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
stopCtx, cancel := context.WithTimeout(context.Background(), shutdownGrace)
defer cancel()
// GracefulStop returns only once every agent call's handler has
// returned, its exit path included, and serve returns, closing the
// store, only after that: what a handler writes on its way out, a
// sync stream's offline mark, finds the store open (#113).
done := make(chan struct{})
go func() { grpcServer.GracefulStop(); close(done) }()
if err := httpServer.Shutdown(stopCtx); err != nil {
Expand All @@ -297,7 +318,21 @@ func runServe(ctx context.Context, args []string) error {
select {
case <-done:
case <-stopCtx.Done():
grpcServer.Stop()
// Sync streams do not end on their own. Stop ends every call
// still open but does not wait for the handlers; GracefulStop,
// still running, does, so done is waited on again, for at most
// handlerExitGrace. Stop runs on its own goroutine: once every
// connection is gone, GracefulStop waits for the handlers
// holding the lock Stop takes, and a stuck handler must not
// hold shutdown past the bound.
go grpcServer.Stop()
exit := time.NewTimer(handlerExitGrace)
defer exit.Stop()
select {
case <-done:
case <-exit.C:
log.Warn("agent calls still running at the end of shutdown; closing the store, so what they still write fails", "waited", handlerExitGrace.String())
}
}
return nil
case err := <-errc:
Expand Down
9 changes: 8 additions & 1 deletion cmd/innerwall/serve_grace_integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,10 +40,17 @@ func reservePort(t *testing.T) string {
// with the given flags, and returns once the agent gateway accepts
// connections. The returned function stops it and waits for it to return.
func startServe(t *testing.T, gateway string, args ...string) (stop func()) {
t.Helper()
return startServeLogging(t, gateway, os.Stderr, args...)
}

// startServeLogging is startServe with the control plane's log written to
// logOut.
func startServeLogging(t *testing.T, gateway string, logOut io.Writer, args ...string) (stop func()) {
t.Helper()
ctx, cancel := context.WithCancel(context.Background())
done := make(chan error, 1)
go func() { done <- runServe(ctx, append([]string{"--listen", gateway}, args...)) }()
go func() { done <- serve(ctx, append([]string{"--listen", gateway}, args...), logOut) }()
deadline := time.Now().Add(10 * time.Second)
for {
c, err := net.Dial("tcp", gateway)
Expand Down
171 changes: 171 additions & 0 deletions cmd/innerwall/serve_shutdown_integration_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,171 @@
package main

import (
"context"
"fmt"
"io"
"log/slog"
"net/url"
"os"
"strings"
"sync"
"testing"
"time"

"github.com/innerwall-dev/innerwall/internal/agent/credential"
"github.com/innerwall-dev/innerwall/internal/agent/enforce"
agentsync "github.com/innerwall-dev/innerwall/internal/agent/sync"
"github.com/innerwall-dev/innerwall/internal/ca/fileca"
"github.com/innerwall-dev/innerwall/internal/enroll"
innerwallv1 "github.com/innerwall-dev/innerwall/internal/gen/innerwall/v1"
"github.com/innerwall-dev/innerwall/internal/identity"
"github.com/innerwall-dev/innerwall/internal/storetest"
)

// logBuffer collects a log written from many goroutines.
type logBuffer struct {
mu sync.Mutex
b strings.Builder
}

func (l *logBuffer) Write(p []byte) (int, error) {
l.mu.Lock()
defer l.mu.Unlock()
return l.b.Write(p)
}

func (l *logBuffer) String() string {
l.mu.Lock()
defer l.mu.Unlock()
return l.b.String()
}

// TestServeShutdownMarksStreamsOffline stops the control plane, as
// `innerwall serve` builds it, while agents hold their sync streams. Every
// stream's end must be recorded before the process lets go of the
// database: by the time serve returns, each workload reads offline with
// a last-seen instant from the shutdown, and the log carries no failed
// offline mark. The store is given fewer connections than there are
// streams, so the marks queue for a connection as the streams end, which
// is where a store closed under them refuses them.
func TestServeShutdownMarksStreamsOffline(t *testing.T) {
const agents = 4
st := storetest.Open(t)
dbURL, err := url.Parse(os.Getenv(storetest.EnvDatabaseURL))
if err != nil {
t.Fatal(err)
}
q := dbURL.Query()
q.Set("pool_max_conns", "2")
dbURL.RawQuery = q.Encode()
caDir := t.TempDir()
gateway := reservePort(t)
flags := []string{"--operator-listen", reservePort(t), "--ca-dir", caDir, "--init-ca", "--database-url", dbURL.String()}
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
defer cancel()

logs := &logBuffer{}
stop := startServeLogging(t, gateway, logs, flags...)
stopped := false
defer func() {
if !stopped {
stop()
}
}()
plain, _, err := (&enroll.Service{Store: st}).MintToken(ctx, "shutdown", nil, 0)
if err != nil {
t.Fatal(err)
}
authority, err := fileca.Open(caDir)
if err != nil {
t.Fatal(err)
}
bootstrap, err := authority.Bundle(ctx)
if err != nil {
t.Fatal(err)
}

ids := make([]identity.WorkloadID, 0, agents)
daemonCtx, stopDaemons := context.WithCancel(ctx)
var daemons sync.WaitGroup
defer func() { stopDaemons(); daemons.Wait() }()
for i := range agents {
key, err := credential.GenerateKey()
if err != nil {
t.Fatal(err)
}
facts := &innerwallv1.HostFacts{Hostname: fmt.Sprintf("shutdown-%d", i)}
enrolled, err := credential.Enroll(ctx, key, credential.EnrollOptions{Server: gateway, Token: plain, BootstrapCA: bootstrap, Facts: facts})
if err != nil {
t.Fatal(err)
}
creds := credential.Store{Dir: t.TempDir()}
if err := creds.Save(key, enrolled.CertificatePEM, enrolled.BundlePEM); err != nil {
t.Fatal(err)
}
holder, err := credential.LoadHolder(creds)
if err != nil {
t.Fatal(err)
}
daemon := agentsync.New(agentsync.Config{
Server: gateway,
Holder: holder,
Store: &enforce.MemoryStore{},
Facts: func() *innerwallv1.HostFacts { return facts },
BackoffBase: 50 * time.Millisecond,
BackoffCap: 250 * time.Millisecond,
Log: slog.New(slog.NewTextHandler(io.Discard, nil)),
})
daemons.Add(1)
go func() { defer daemons.Done(); _ = daemon.Run(daemonCtx) }()
ids = append(ids, enrolled.WorkloadID)
}

// Every stream is open and settled: its snapshot applied and
// acknowledged, and the instant it was sent recorded.
for _, id := range ids {
deadline := time.Now().Add(15 * time.Second)
for {
w, err := st.LookupWorkload(ctx, id)
if err != nil {
t.Fatal(err)
}
if w.SyncState == innerwallv1.SyncState_SYNC_STATE_SYNCED && w.LastSnapshotSentAt != nil {
break
}
if time.Now().After(deadline) {
t.Fatalf("workload %v did not sync; workload = %+v", id, w)
}
time.Sleep(20 * time.Millisecond)
}
}

// Stop the control plane with the agents still connected.
began := time.Now()
stop()
stopped = true
returned := time.Now()

for _, id := range ids {
w, err := st.LookupWorkload(ctx, id)
if err != nil {
t.Fatal(err)
}
if w.SyncState != innerwallv1.SyncState_SYNC_STATE_OFFLINE {
t.Errorf("workload %v: sync state after shutdown = %v, want offline", id, w.SyncState)
continue
}
if w.LastSeenAt == nil || w.LastSeenAt.Before(began) || w.LastSeenAt.After(returned) {
t.Errorf("workload %v: last seen %v, want the shutdown's offline mark, between %v and %v", id, w.LastSeenAt, began, returned)
}
}
out := logs.String()
if !strings.Contains(out, "control plane serving") {
t.Fatalf("the control plane's log was not captured:\n%s", out)
}
for _, bad := range []string{"marking workload offline", "closed pool"} {
if strings.Contains(out, bad) {
t.Errorf("the log carries %q:\n%s", bad, out)
}
}
}
2 changes: 2 additions & 0 deletions docs/reference/innerwall-cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@ Runs the agent gateway (enrollment, renewal, the sync stream, flow reports) and

`--tls-hosts` takes effect only when a certificate is generated: the server certificate when `--init-ca` creates the authority, and the operator certificate when none is persisted or the persisted one has expired. A certificate that already exists is kept as it is, whatever the flag says now ([multi-host evaluation](../deploy/multi-host-evaluation.md#name-the-control-plane-before-the-first-start)). To change the hosts the server certificate names afterwards, issue a new one with [`ca issue-server`](#ca-issue-server) and restart.

On `SIGINT` or `SIGTERM`, `serve` stops accepting connections and gives open agent calls and operator requests ten seconds to end. Sync streams do not end on their own, so it then ends them and waits up to five seconds more for their handlers to record each workload offline, and only then closes its database connections: allow the process at least fifteen seconds to stop before it is killed. A second signal changes nothing.

## migrate

```sh
Expand Down
Loading