Skip to content

Commit fe7cfd2

Browse files
feat(agent): adopt-routes records the routes older agents left unrecorded (part of #490)
Agents up to 0.1.0-alpha.3 wrote routes without a record, so the reconciler never moves them. Docker gives containers new addresses when it restarts (three daemon restarts of Docker 29 shuffled six containers three ways), and such a route then sends its traffic to whatever container took its old address. shipkeep-agent adopt-routes records each of those routes, for the server installer's migration to run while the agent is stopped and before Docker restarts. A route is recorded only when every address it proxies to belongs to a running managed container of the route's own application, by its shipkeep.application label. A route whose traffic already goes elsewhere is named, never recorded as right. Nothing is written to Caddy. Signed-off-by: samuel mbabhazi <[email protected]>
1 parent 661f966 commit fe7cfd2

9 files changed

Lines changed: 648 additions & 3 deletions

File tree

‎agent/cmd/shipkeep-agent/adopt.go‎

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
package main
2+
3+
import (
4+
"context"
5+
"flag"
6+
"fmt"
7+
"io"
8+
"maps"
9+
"slices"
10+
"time"
11+
12+
"github.com/shipkeepdev/shipkeep/agent/internal/actions"
13+
"github.com/shipkeepdev/shipkeep/agent/internal/caddy"
14+
"github.com/shipkeepdev/shipkeep/agent/internal/config"
15+
"github.com/shipkeepdev/shipkeep/agent/internal/docker"
16+
"github.com/shipkeepdev/shipkeep/agent/internal/journal"
17+
)
18+
19+
// exitRefused: some routes could not be tied to their containers and were left without a record.
20+
const exitRefused = 5
21+
22+
// adoptTimeout bounds the whole adoption: a few reads of Caddy and Docker, and one write per route.
23+
const adoptTimeout = 2 * time.Minute
24+
25+
// runAdoptRoutes records the routes that agents up to 0.1.0-alpha.3 wrote without a record, so
26+
// that they follow their containers (ADR 0017). The server installer's migration runs it as the
27+
// agent's account, with the agent stopped and before Docker restarts (ADR 0028); the journal's lock
28+
// refuses it while an agent runs. It prints application ids and reason codes, never addresses.
29+
func runAdoptRoutes(ctx context.Context, args []string, stdout, stderr io.Writer) int {
30+
fs := flag.NewFlagSet("shipkeep-agent adopt-routes", flag.ContinueOnError)
31+
fs.SetOutput(stderr)
32+
path := fs.String("config", config.DefaultPath, "path to agent.yaml")
33+
if err := fs.Parse(args); err != nil {
34+
return exitUsage
35+
}
36+
if fs.NArg() > 0 || *path == "" {
37+
_, _ = fmt.Fprintln(stderr, "shipkeep-agent adopt-routes: unexpected arguments")
38+
return exitUsage
39+
}
40+
cfg, err := config.Load(*path, config.Default(), false)
41+
if err == nil {
42+
err = cfg.Validate()
43+
}
44+
if err != nil {
45+
_, _ = fmt.Fprintln(stderr, "shipkeep-agent adopt-routes:", err)
46+
return exitConfig
47+
}
48+
ctx, cancel := context.WithTimeout(ctx, adoptTimeout)
49+
defer cancel()
50+
adoption, err := adoptRoutes(ctx, cfg)
51+
if err != nil {
52+
_, _ = fmt.Fprintln(stderr, "shipkeep-agent adopt-routes:", err)
53+
return exitError
54+
}
55+
_, _ = fmt.Fprintf(stdout, "routes: %d already followed, %d adopted, %d refused\n", len(adoption.Followed), len(adoption.Adopted), len(adoption.Refused))
56+
for _, application := range slices.Sorted(maps.Keys(adoption.Refused)) {
57+
_, _ = fmt.Fprintf(stdout, "refused: application %s (%s)\n", application, adoption.Refused[application])
58+
}
59+
if len(adoption.Refused) > 0 {
60+
return exitRefused
61+
}
62+
return exitOK
63+
}
64+
65+
func adoptRoutes(ctx context.Context, cfg config.Config) (actions.Adoption, error) {
66+
store, err := journal.Open(ctx, cfg.Paths.StateDir)
67+
if err != nil {
68+
return actions.Adoption{}, fmt.Errorf("open the journal (is the agent stopped?): %w", err)
69+
}
70+
defer func() { _ = store.Close() }()
71+
engine, err := docker.New(cfg.Docker.Host)
72+
if err != nil {
73+
return actions.Adoption{}, fmt.Errorf("docker: %w", err)
74+
}
75+
router, err := caddy.New(cfg.Caddy.AdminSocket)
76+
if err != nil {
77+
return actions.Adoption{}, fmt.Errorf("caddy: %w", err)
78+
}
79+
adoption, err := actions.AdoptRoutes(ctx, router, engine, &actions.RouteBook{Store: store}, time.Now())
80+
if err != nil {
81+
return actions.Adoption{}, fmt.Errorf("adopt routes: %w", err)
82+
}
83+
return adoption, nil
84+
}
Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,114 @@
1+
package main
2+
3+
import (
4+
"bytes"
5+
"context"
6+
"net"
7+
"net/http"
8+
"os"
9+
"path/filepath"
10+
"strings"
11+
"testing"
12+
13+
"github.com/shipkeepdev/shipkeep/agent/internal/journal"
14+
)
15+
16+
// serveUnix serves handler on a Unix socket at path until the test ends.
17+
func serveUnix(t *testing.T, path string, handler http.Handler) {
18+
t.Helper()
19+
listener, err := (&net.ListenConfig{}).Listen(t.Context(), "unix", path)
20+
if err != nil {
21+
t.Fatal(err)
22+
}
23+
server := &http.Server{Handler: handler} //nolint:gosec // test server on a private socket
24+
go func() { _ = server.Serve(listener) }()
25+
t.Cleanup(func() { _ = server.Close() })
26+
}
27+
28+
// legacyNode is a server as an agent of 0.1.0-alpha.3 left it: Caddy with two routes and no
29+
// record, Docker with the API container at the first route's address and another application's
30+
// container at the second one's.
31+
func legacyNode(t *testing.T) (config, stateDir string) {
32+
t.Helper()
33+
dir, err := os.MkdirTemp("", "sk-adopt")
34+
if err != nil {
35+
t.Fatal(err)
36+
}
37+
t.Cleanup(func() { _ = os.RemoveAll(dir) })
38+
stateDir = filepath.Join(dir, "state")
39+
docker := http.NewServeMux()
40+
docker.HandleFunc("GET /v1.47/containers/json", func(w http.ResponseWriter, _ *http.Request) {
41+
_, _ = w.Write([]byte(`[{"Id":"c1","Names":["/sk-api-1"]},{"Id":"c2","Names":["/sk-web-1"]}]`))
42+
})
43+
inspected := map[string]string{
44+
"c1": `{"Id":"c1","Config":{"Labels":{"sk.managed":"true","shipkeep.application":"api-prod"}},"State":{"Running":true},"NetworkSettings":{"Networks":{"sk-env-a":{"IPAddress":"172.18.0.5"}}}}`,
45+
"c2": `{"Id":"c2","Config":{"Labels":{"sk.managed":"true","shipkeep.application":"web-prod"}},"State":{"Running":true},"NetworkSettings":{"Networks":{"sk-env-a":{"IPAddress":"172.18.0.6"}}}}`,
46+
}
47+
docker.HandleFunc("GET /v1.47/containers/{id}/json", func(w http.ResponseWriter, r *http.Request) {
48+
body, ok := inspected[r.PathValue("id")]
49+
if !ok {
50+
http.NotFound(w, r)
51+
return
52+
}
53+
_, _ = w.Write([]byte(body))
54+
})
55+
serveUnix(t, filepath.Join(dir, "docker.sock"), docker)
56+
caddy := http.NewServeMux()
57+
caddy.HandleFunc("GET /config/apps/http/servers/shipkeep/routes", func(w http.ResponseWriter, _ *http.Request) {
58+
_, _ = w.Write([]byte(`[{"@id":"sk-route-api-prod","match":[{"host":["api.example.com"]}],"handle":[{"handler":"reverse_proxy","upstreams":[{"dial":"172.18.0.5:8080"}]}],"terminal":true},` +
59+
`{"@id":"sk-route-blog-prod","match":[{"host":["blog.example.com"]}],"handle":[{"handler":"reverse_proxy","upstreams":[{"dial":"172.18.0.6:8080"}]}],"terminal":true}]`))
60+
})
61+
serveUnix(t, filepath.Join(dir, "caddy.sock"), caddy)
62+
config = filepath.Join(dir, "agent.yaml")
63+
body := "control_plane:\n address: cp.example.com:7443\n ca_fingerprint: " + fingerprint + "\npaths:\n state_dir: " + stateDir +
64+
"\ndocker:\n host: unix://" + filepath.Join(dir, "docker.sock") + "\ncaddy:\n admin_socket: " + filepath.Join(dir, "caddy.sock") + "\n"
65+
if err := os.WriteFile(config, []byte(body), 0o600); err != nil {
66+
t.Fatal(err)
67+
}
68+
return config, stateDir
69+
}
70+
71+
func TestAdoptRoutesRecordsWhatItCanTieAndNamesTheRest(t *testing.T) {
72+
config, stateDir := legacyNode(t)
73+
var stdout, stderr bytes.Buffer
74+
code := run(context.Background(), []string{"adopt-routes", "--config", config}, &stdout, &stderr)
75+
if code != exitRefused {
76+
t.Fatalf("exit %d, stdout %q, stderr %q", code, stdout.String(), stderr.String())
77+
}
78+
want := "routes: 0 already followed, 1 adopted, 1 refused\nrefused: application blog-prod (other_application)\n"
79+
if stdout.String() != want {
80+
t.Fatalf("stdout = %q, want %q", stdout.String(), want)
81+
}
82+
if strings.Contains(stdout.String()+stderr.String(), "172.18.") {
83+
t.Fatal("an address was printed")
84+
}
85+
store, err := journal.Open(context.Background(), stateDir)
86+
if err != nil {
87+
t.Fatal(err)
88+
}
89+
defer func() { _ = store.Close() }()
90+
routes, err := store.RecordedRoutes(context.Background())
91+
if err != nil || len(routes) != 1 || routes[0] != "sk-route-api-prod" {
92+
t.Fatalf("recorded = %v, %v", routes, err)
93+
}
94+
// The agent holds the journal: adoption waits for it to stop rather than race it.
95+
if code := run(context.Background(), []string{"adopt-routes", "--config", config}, &bytes.Buffer{}, &stderr); code != exitError || !strings.Contains(stderr.String(), "is the agent stopped") {
96+
t.Fatalf("with the journal held: exit %d, stderr %q", code, stderr.String())
97+
}
98+
}
99+
100+
func TestAdoptRoutesRefusesBadArguments(t *testing.T) {
101+
t.Parallel()
102+
for _, args := range [][]string{
103+
{"adopt-routes", "extra"},
104+
{"adopt-routes", "--config", ""},
105+
{"adopt-routes", "--unknown"},
106+
} {
107+
if code := run(context.Background(), args, &bytes.Buffer{}, &bytes.Buffer{}); code != exitUsage {
108+
t.Errorf("%v: exit %d, want %d", args, code, exitUsage)
109+
}
110+
}
111+
if code := run(context.Background(), []string{"adopt-routes", "--config", filepath.Join(t.TempDir(), "absent.yaml")}, &bytes.Buffer{}, &bytes.Buffer{}); code != exitConfig {
112+
t.Errorf("missing configuration: exit %d, want %d", code, exitConfig)
113+
}
114+
}

‎agent/cmd/shipkeep-agent/main.go‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,9 @@ func run(ctx context.Context, args []string, stdout, stderr io.Writer) int {
7979
if len(args) > 0 && args[0] == "upgrade-guard" {
8080
return runUpgradeGuard(args[1:], stderr)
8181
}
82+
if len(args) > 0 && args[0] == "adopt-routes" {
83+
return runAdoptRoutes(ctx, args[1:], stdout, stderr)
84+
}
8285
opts, err := parseFlags(args, stderr)
8386
if err != nil {
8487
return exitUsage
Lines changed: 175 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,175 @@
1+
package actions
2+
3+
import (
4+
"context"
5+
"fmt"
6+
"net/netip"
7+
"slices"
8+
"strings"
9+
"time"
10+
11+
"github.com/shipkeepdev/shipkeep/agent/internal/caddy"
12+
"github.com/shipkeepdev/shipkeep/agent/internal/docker"
13+
"github.com/shipkeepdev/shipkeep/agent/internal/journal"
14+
)
15+
16+
// ApplicationLabel is the label the control plane gives every container of an application: the
17+
// application's id, which is also the id of the application's route.
18+
const ApplicationLabel = "shipkeep.application"
19+
20+
// Why a route was not adopted. Codes only: never an address, a name or an error text.
21+
const (
22+
// AdoptNoContainer: no running managed container has an address the route proxies to.
23+
AdoptNoContainer = "no_running_container"
24+
// AdoptOtherApplication: the container at an address the route proxies to belongs to another
25+
// application, or to none. The route already sends its traffic elsewhere.
26+
AdoptOtherApplication = "other_application"
27+
// AdoptUnexpected: the route is not one an agent writes (an upstream that is not a private
28+
// address and port, the same address twice, or weights out of range).
29+
AdoptUnexpected = "unexpected_route"
30+
)
31+
32+
// RouteLister lists the routes of the Shipkeep server; the Caddy client implements it.
33+
type RouteLister interface {
34+
Routes(ctx context.Context) ([]caddy.Route, error)
35+
}
36+
37+
// Inventory lists and inspects the managed containers; the Docker engine implements it.
38+
type Inventory interface {
39+
Containers
40+
ManagedContainers(ctx context.Context) ([]docker.ContainerSummary, error)
41+
}
42+
43+
// Adoption is what AdoptRoutes found: the routes already followed, the routes it recorded, and the
44+
// routes it could not tie to their containers, by Shipkeep route id, with why.
45+
type Adoption struct {
46+
Followed, Adopted []string
47+
Refused map[string]string
48+
}
49+
50+
// AdoptRoutes records the routes that agents up to 0.1.0-alpha.3 wrote without a record (ADR
51+
// 0017), so that from now on they follow their containers when Docker gives them other addresses.
52+
// It runs once, from the installer's migration, while the agent is stopped and before Docker
53+
// restarts: until then each container still has the address the route was given.
54+
//
55+
// A route is adopted only when every address it proxies to is the address of a running managed
56+
// container of the route's own application, by its label, so that a route whose traffic already
57+
// goes elsewhere is never recorded as right. Such a route, and any other it cannot read, is left
58+
// as it is and named in Refused: its application is deployed again to give it a record. A route
59+
// whose record matches what Caddy holds is already followed. Nothing is written to Caddy.
60+
func AdoptRoutes(ctx context.Context, routes RouteLister, containers Inventory, book *RouteBook, now time.Time) (Adoption, error) {
61+
listed, err := routes.Routes(ctx)
62+
if err != nil {
63+
return Adoption{}, fmt.Errorf("list routes: %w", err)
64+
}
65+
owners, err := addressOwners(ctx, containers)
66+
if err != nil {
67+
return Adoption{}, err
68+
}
69+
defer book.lock()()
70+
adoption := Adoption{Refused: map[string]string{}}
71+
for _, route := range listed {
72+
application, ok := caddy.RouteName(route.ID)
73+
if !ok || !routeID.MatchString(application) || len(route.Handle) != 1 || route.Handle[0].Handler != "reverse_proxy" {
74+
// Not a Shipkeep route, or one with nothing to follow: the agent's 503 answer, the
75+
// maintenance page.
76+
continue
77+
}
78+
record, found, err := book.Store.RouteRecord(ctx, route.ID)
79+
if err != nil {
80+
return adoption, fmt.Errorf("read route record: %w", err)
81+
}
82+
if _, ours := written(route, record); found && ours {
83+
adoption.Followed = append(adoption.Followed, application)
84+
continue
85+
}
86+
upstreams, reason := adopted(route.Handle[0], application, owners)
87+
if reason != "" {
88+
adoption.Refused[application] = reason
89+
continue
90+
}
91+
next := journal.RouteRecord{Upstreams: upstreams, Written: [][]string{dials(route)}}
92+
if err := book.Store.SetRouteRecord(ctx, route.ID, next, now); err != nil {
93+
return adoption, fmt.Errorf("record route: %w", err)
94+
}
95+
adoption.Adopted = append(adoption.Adopted, application)
96+
}
97+
return adoption, nil
98+
}
99+
100+
// addressOwner is the running managed container at an address.
101+
type addressOwner struct {
102+
name, application string
103+
// shared marks an address two containers report: neither is taken for it.
104+
shared bool
105+
}
106+
107+
// addressOwners maps each running managed container's service address to the container.
108+
func addressOwners(ctx context.Context, containers Inventory) (map[netip.Addr]addressOwner, error) {
109+
summaries, err := containers.ManagedContainers(ctx)
110+
if err != nil {
111+
return nil, fmt.Errorf("list containers: %w", err)
112+
}
113+
owners := map[netip.Addr]addressOwner{}
114+
for _, summary := range summaries {
115+
if len(summary.Names) == 0 {
116+
continue
117+
}
118+
name := strings.TrimPrefix(summary.Names[0], "/")
119+
if !resourceName.MatchString(name) {
120+
continue
121+
}
122+
container, err := containers.Container(ctx, summary.ID)
123+
if err != nil {
124+
// Docker did not answer, or the container went away: nothing is recorded on a guess.
125+
return nil, fmt.Errorf("inspect container: %w", err)
126+
}
127+
address, ok := serviceAddress(container)
128+
if !ok {
129+
continue
130+
}
131+
if _, taken := owners[address]; taken {
132+
owners[address] = addressOwner{shared: true}
133+
continue
134+
}
135+
owners[address] = addressOwner{name: name, application: container.Config.Labels[ApplicationLabel]}
136+
}
137+
return owners, nil
138+
}
139+
140+
// adopted lists the upstreams of a route's handler as a record keeps them, or says why it cannot.
141+
func adopted(handler caddy.Handler, application string, owners map[netip.Addr]addressOwner) ([]journal.RouteUpstream, string) {
142+
if len(handler.Upstreams) == 0 || len(handler.Upstreams) > maxUpstreams {
143+
return nil, AdoptUnexpected
144+
}
145+
weights := installedWeights(handler)
146+
if handler.LoadBalancing != nil && len(weights) != len(handler.Upstreams) {
147+
return nil, AdoptUnexpected
148+
}
149+
upstreams := make([]journal.RouteUpstream, 0, len(handler.Upstreams))
150+
for index, upstream := range handler.Upstreams {
151+
dial, err := netip.ParseAddrPort(upstream.Dial)
152+
if err != nil || dial.Port() == 0 || !dial.Addr().IsPrivate() || dial.String() != upstream.Dial {
153+
return nil, AdoptUnexpected
154+
}
155+
weight := 1
156+
if weights != nil {
157+
weight = weights[index]
158+
}
159+
if weight < 1 || weight > maxWeight {
160+
return nil, AdoptUnexpected
161+
}
162+
owner, ok := owners[dial.Addr()]
163+
switch {
164+
case !ok:
165+
return nil, AdoptNoContainer
166+
case owner.shared || owner.application != application:
167+
return nil, AdoptOtherApplication
168+
}
169+
if slices.ContainsFunc(upstreams, func(u journal.RouteUpstream) bool { return u.Container == owner.name && u.Port == dial.Port() }) {
170+
return nil, AdoptUnexpected
171+
}
172+
upstreams = append(upstreams, journal.RouteUpstream{Container: owner.name, Port: dial.Port(), Weight: weight})
173+
}
174+
return upstreams, ""
175+
}

0 commit comments

Comments
 (0)