From 46abc5ce3ade4c006e80541da40f12ed908a7b15 Mon Sep 17 00:00:00 2001 From: Josh Wolf Date: Tue, 20 Aug 2024 10:26:57 -0400 Subject: [PATCH] deconflict networks before creating (#172) #171 introduced a bug where duplicate networks were being sent to the daemon request when additional networks were specified. this adds deduplication before sending the request and adds a test --- internal/harness/k3s/k3s.go | 24 ++++++++++++----- .../provider/harness_k3s_resource_test.go | 27 +++++++++++++++++++ 2 files changed, 45 insertions(+), 6 deletions(-) diff --git a/internal/harness/k3s/k3s.go b/internal/harness/k3s/k3s.go index d8068f6..0529084 100644 --- a/internal/harness/k3s/k3s.go +++ b/internal/harness/k3s/k3s.go @@ -98,7 +98,7 @@ func (h *k3s) Create(ctx context.Context) error { } if err := h.startSandbox(ctx, cli, kresp); err != nil { - return fmt.Errorf("starting sandbox: %w", err) + return fmt.Errorf("creating sandbox: %w", err) } return nil @@ -263,12 +263,24 @@ func (h *k3s) startSandbox(ctx context.Context, cli *docker.Client, resp *docker return fmt.Errorf("getting kubeconfig: %w", err) } - // Attach the sandbox to all networks the k3s service is also part of + networks := make(map[string]struct{}) + for _, nw := range h.Sandbox.Networks { + networks[nw.ID] = struct{}{} + } + + // Attach the sandbox to any networks k3s is also a part of, excluding any + // invalid networks or networks already attached (the daemon cannot deconflict + // these) for nn, nw := range resp.NetworkSettings.Networks { - h.Sandbox.Networks = append(h.Sandbox.Networks, docker.NetworkAttachment{ - Name: nn, - ID: nw.NetworkID, - }) + if nn == "" { + continue + } + if _, ok := networks[nn]; !ok { + h.Sandbox.Networks = append(h.Sandbox.Networks, docker.NetworkAttachment{ + Name: nn, + ID: nw.NetworkID, + }) + } } h.Sandbox.Name = resp.Name + "-sandbox" diff --git a/internal/provider/harness_k3s_resource_test.go b/internal/provider/harness_k3s_resource_test.go index 2d9336e..37d7bc9 100644 --- a/internal/provider/harness_k3s_resource_test.go +++ b/internal/provider/harness_k3s_resource_test.go @@ -253,6 +253,33 @@ resource "imagetest_feature" "test" { cmd = "kubectl get po -A" }, ] +} + `, + }, + }, + "with additional networks": { + // Create testing + { + ExpectNonEmptyPlan: true, + Config: ` +data "imagetest_inventory" "this" {} + +resource "imagetest_harness_k3s" "test" { + name = "test" + inventory = data.imagetest_inventory.this + networks = { "bridge" = { name = "bridge" } } +} + +resource "imagetest_feature" "test" { + name = "Simple k3s based test" + description = "Test that we can attach existing networks" + harness = imagetest_harness_k3s.test + steps = [ + { + name = "Access cluster" + cmd = "kubectl get po -A" + }, + ] } `, },