diff --git a/lib/instances/fork_tap_release_linux_test.go b/lib/instances/fork_tap_release_linux_test.go new file mode 100644 index 000000000..0c28ea638 --- /dev/null +++ b/lib/instances/fork_tap_release_linux_test.go @@ -0,0 +1,65 @@ +package instances + +import ( + "os" + "testing" + + "github.com/kernel/hypeman/lib/network" + "github.com/nrednav/cuid2" + "github.com/stretchr/testify/require" + "github.com/vishvananda/netlink" +) + +func TestRecoveryReleasesOnlyUnambiguousKernelTAP(t *testing.T) { + if os.Geteuid() != 0 { + t.Skip("creating a TAP requires CAP_NET_ADMIN") + } + if _, err := os.Stat("/dev/net/tun"); os.IsNotExist(err) { + t.Skip("no TUN device") + } + for _, tc := range []struct { + name string + sharedName, persisted bool + }{ + {"own name, no allocation", false, false}, + {"shared name, no allocation", true, false}, + {"own name, persisted allocation", false, true}, + {"shared name, persisted allocation", true, true}, + } { + t.Run(tc.name, func(t *testing.T) { + m, _ := setupTestManager(t) + id := cuid2.Generate() + createPendingForkWithoutAllocation(t, m, id) + if tc.persisted { + meta, err := m.loadMetadata(id) + require.NoError(t, err) + meta.IP, meta.MAC = "10.10.10.2", "02:00:00:00:00:01" + require.NoError(t, m.saveMetadata(meta)) + alloc, err := m.networkManager.GetAllocation(t.Context(), id) + require.NoError(t, err) + require.NotNil(t, alloc) + } + tap := &netlink.Tuntap{ + LinkAttrs: netlink.LinkAttrs{Name: network.GenerateTAPName(id)}, + Mode: netlink.TUNTAP_MODE_TAP, + } + require.NoError(t, netlink.LinkAdd(tap)) + t.Cleanup(func() { _ = netlink.LinkDel(tap) }) + if tc.sharedName { + // A second guest can share the short TAP name, so the TAP may + // be its own. It is left for the TAP reconciler. + require.NoError(t, os.Mkdir(m.paths.InstanceDir(id+"-other"), 0755)) + } + + m.RecoverInterruptedForks(t.Context()) + require.NoDirExists(t, m.paths.InstanceDir(id)) + _, err := netlink.LinkByName(tap.Name) + if tc.sharedName { + require.NoError(t, err) + return + } + var notFound netlink.LinkNotFoundError + require.ErrorAs(t, err, ¬Found) + }) + } +} diff --git a/lib/instances/fork_tap_release_test.go b/lib/instances/fork_tap_release_test.go new file mode 100644 index 000000000..75f7bdec6 --- /dev/null +++ b/lib/instances/fork_tap_release_test.go @@ -0,0 +1,42 @@ +package instances + +import ( + "context" + "errors" + "testing" + + "github.com/kernel/hypeman/lib/network" + "github.com/stretchr/testify/require" +) + +type failingTAPRelease struct { + network.Manager + ids []string +} + +func (r *failingTAPRelease) ReleaseByInstanceID(_ context.Context, id string) error { + r.ids = append(r.ids, id) + return errors.New("TAP busy") +} + +func createPendingForkWithoutAllocation(t *testing.T, m *manager, fork string) { + t.Helper() + savePendingForkFixture(t, m, fork, true, func(stored *StoredMetadata) { stored.NetworkEnabled = true }) + alloc, err := m.networkManager.GetAllocation(t.Context(), fork) + require.NoError(t, err) + require.Nil(t, alloc) +} + +// The TAP reconciler deletes a TAP that no live instance claims, so a fork is +// not kept for one that could not be released. +func TestRecoveryDeletesForkWhenTAPReleaseFails(t *testing.T) { + m, _ := setupTestManager(t) + const fork = "fork-tap-busy" + createPendingForkWithoutAllocation(t, m, fork) + release := &failingTAPRelease{Manager: m.networkManager} + m.networkManager = release + + m.RecoverInterruptedForks(t.Context()) + require.Equal(t, []string{fork}, release.ids) + require.NoDirExists(t, m.paths.InstanceDir(fork)) +} diff --git a/lib/network/README.md b/lib/network/README.md index 6ae944ff6..a037b7f9b 100644 --- a/lib/network/README.md +++ b/lib/network/README.md @@ -312,7 +312,7 @@ identity reservation. ### Unlocked Operations - **TAP creation**: Runs outside the allocation mutex so concurrent forks can create TAPs in parallel - **RecreateAllocation**: Safe without allocation lock - protected by instance-level locking, doesn't allocate IPs -- **ReleaseAllocation**: Safe without allocation lock - deletes TAP device and serializes with tc updates +- **ReleaseAllocation**: Serializes with tc updates and leaves the TAP alone if another guest has the same short interface name, even when the caller has a persisted allocation. - **Read operations** (GetAllocation, ListAllocations, NameExists): No lock needed - eventual consistency is acceptable ### Why This Works diff --git a/lib/network/allocate.go b/lib/network/allocate.go index 23512d0c3..89bed4cf7 100644 --- a/lib/network/allocate.go +++ b/lib/network/allocate.go @@ -7,9 +7,11 @@ import ( mathrand "math/rand" "net" "os" + "runtime" "strings" "time" + "github.com/kernel/hypeman/lib/hypervisor" "github.com/kernel/hypeman/lib/logger" "go.opentelemetry.io/otel/attribute" ) @@ -119,7 +121,7 @@ func (m *manager) CreateAllocation(ctx context.Context, req AllocateRequest) (*N // Note: No lock needed - this operation: // 1. Doesn't allocate new IPs (reuses existing from snapshot) // 2. Is already protected by instance-level locking -// 3. Uses deterministic TAP names that can't conflict +// 3. Checks the short TAP name before replacing any existing link. func (m *manager) RecreateAllocation(ctx context.Context, instanceID string, downloadBps, uploadBps int64) error { log := logger.FromContext(ctx) @@ -138,6 +140,10 @@ func (m *manager) RecreateAllocation(ctx context.Context, instanceID string, dow return nil } + if err := m.checkTAPAvailable(instanceID, alloc.TAPDevice); err != nil { + return err + } + // 2. Get default network details (same self-healing behavior as CreateAllocation). networkCtx, networkSpanEnd := startNetworkStep(ctx, "network.get_default_network", attribute.String("operation", "get_default_network"), @@ -233,6 +239,9 @@ func (m *manager) reserveAllocationIdentityLocked(ctx context.Context, network * } tap := GenerateTAPName(req.InstanceID) + if err := m.checkTAPAvailable(req.InstanceID, tap); err != nil { + return nil, err + } _, ipNet, _ := net.ParseCIDR(network.Subnet) netmask := fmt.Sprintf("%d.%d.%d.%d", ipNet.Mask[0], ipNet.Mask[1], ipNet.Mask[2], ipNet.Mask[3]) @@ -376,14 +385,9 @@ func (m *manager) applyRateLimitAsync(ctx context.Context, req rateLimitRequest) // ReleaseByInstanceID is a best-effort fallback for cases where the full Allocation // can't be derived (e.g. metadata read failure during stop, or rollback after a // CreateAllocation that succeeded but where downstream metadata writes failed). -// It deletes the TAP device using the deterministic name from the instance ID and -// the persisted class ID if available. +// It uses the same ownership check as release with a persisted allocation. func (m *manager) ReleaseByInstanceID(ctx context.Context, instanceID string) error { - return m.ReleaseAllocation(ctx, &Allocation{ - InstanceID: instanceID, - TAPDevice: GenerateTAPName(instanceID), - ClassID: m.loadClassID(instanceID), - }) + return m.ReleaseAllocation(ctx, &Allocation{InstanceID: instanceID, TAPDevice: GenerateTAPName(instanceID)}) } // ReleaseAllocation cleans up network allocation (shutdown/delete) @@ -402,14 +406,13 @@ func (m *manager) ReleaseAllocation(ctx context.Context, alloc *Allocation) erro } m.forgetPendingAllocation(alloc.InstanceID) - // 1. Delete TAP device (best effort), using the TAP's live tc filter for HTB cleanup. + // 1. Delete TAP device using the TAP's live tc filter for HTB cleanup. // Serialize with async tc setup so queued rate-limit work cannot race with // class removal and leave stale bridge state behind. if err := m.deleteTAPDeviceForInstanceSerialized(ctx, alloc.InstanceID, alloc.TAPDevice); err != nil { - log.WarnContext(ctx, "failed to delete TAP device", "tap", alloc.TAPDevice, "error", err) - } else { - m.recordTAPOperation(ctx, "delete") + return fmt.Errorf("release TAP %s: %w", alloc.TAPDevice, err) } + m.recordTAPOperation(ctx, "delete") log.InfoContext(ctx, "released network", "instance_id", alloc.InstanceID, @@ -425,10 +428,60 @@ func (m *manager) deleteTAPDeviceSerialized(ctx context.Context, tapName string) return m.deleteTAPDevice(ctx, tapName) } +// Check before creation as well as release: a new guest must not claim the +// link between a previous guest's ownership check and its deletion. +func (m *manager) checkTAPAvailable(instanceID, tap string) error { + other, err := m.conflictingTAPGuest(instanceID, tap) + if err != nil { + return err + } + if other != "" { + return fmt.Errorf("TAP name %s also matches guest %s", tap, other) + } + return nil +} + +// Match directories rather than allocations: a guest may not have saved its IP yet. +func (m *manager) conflictingTAPGuest(instanceID, tap string) (string, error) { + if runtime.GOOS != "linux" { // vmnet does not use TAPs. + return "", nil + } + defer hypervisor.LockSnapshotSourceAliasReaders()() + guests, err := os.ReadDir(m.paths.GuestsDir()) + if err != nil && !os.IsNotExist(err) { + return "", err + } + for _, guest := range guests { + if !guest.IsDir() { + continue + } + id := guest.Name() + if id != instanceID && GenerateTAPName(id) == tap { + return id, nil + } + } + return "", nil +} + func (m *manager) deleteTAPDeviceForInstanceSerialized(ctx context.Context, instanceID, tapName string) error { m.tcMu.Lock() defer m.tcMu.Unlock() - if err := m.deleteTAPDevice(ctx, tapName); err != nil { + other, err := m.conflictingTAPGuest(instanceID, tapName) + if err != nil { + return err + } + if other != "" { + // A missing TAP is already released; never delete a live, ambiguous link. + links, err := net.Interfaces() + if err != nil { + return err + } + for _, link := range links { + if link.Name == tapName { + return fmt.Errorf("cannot release %s: also matches guest %s", tapName, other) + } + } + } else if err := m.deleteTAPDevice(ctx, tapName); err != nil { return err } m.clearClassID(instanceID) diff --git a/lib/network/bridge_linux.go b/lib/network/bridge_linux.go index e2afd312a..355194eff 100644 --- a/lib/network/bridge_linux.go +++ b/lib/network/bridge_linux.go @@ -1304,8 +1304,11 @@ func deriveClassID(tapName string) string { func (m *manager) deleteTAPDevice(ctx context.Context, tapName string) error { link, err := netlink.LinkByName(tapName) if err != nil { - // TAP doesn't exist, nothing to do - return nil + var notFound netlink.LinkNotFoundError + if errors.As(err, ¬Found) { + return nil + } + return err } // A pin left behind points at a MAC no guest uses and is replaced when diff --git a/lib/network/bridge_linux_test.go b/lib/network/bridge_linux_test.go index f01d2c53a..46fc71c2f 100644 --- a/lib/network/bridge_linux_test.go +++ b/lib/network/bridge_linux_test.go @@ -17,6 +17,16 @@ import ( "github.com/vishvananda/netlink" ) +func TestTAPReservationRefusesCollidingGuestWithoutAllocation(t *testing.T) { + p := paths.New(t.TempDir()) + require.NoError(t, os.MkdirAll(p.InstanceDir("abcdefgh-source"), 0755)) + m := &manager{paths: p, config: &config.Config{}} + nw := newDefaultNetwork("br-test", "10.10.10.0/30", "10.10.10.1") + _, err := m.reserveAllocationIdentityLocked(t.Context(), nw, AllocateRequest{InstanceID: "abcdefgh-child", InstanceName: "child"}) + require.ErrorContains(t, err, "also matches guest abcdefgh-source") + require.Empty(t, m.pendingAllocations) +} + func TestParseBridgeFilters(t *testing.T) { output := `filter parent 1: protocol all pref 1 basic chain 0 filter parent 1: protocol all pref 1 basic chain 0 handle 0x1 flowid 1:a3f2 diff --git a/lib/network/manager_test.go b/lib/network/manager_test.go index b9e0699cb..9199e19b6 100644 --- a/lib/network/manager_test.go +++ b/lib/network/manager_test.go @@ -143,6 +143,13 @@ func TestDefaultNetworkCacheReturnsCopy(t *testing.T) { assert.Equal(t, "hm0", m.cachedDefaultNetwork().Bridge) } +func TestReleaseByInstanceIDWithMissingSharedTAP(t *testing.T) { + p := paths.New(t.TempDir()) + require.NoError(t, os.MkdirAll(p.InstanceDir("abcdefgh-other"), 0755)) + m := &manager{paths: p} + require.NoError(t, m.ReleaseByInstanceID(t.Context(), "abcdefgh-fork")) +} + func TestGenerateTAPName(t *testing.T) { tests := []struct { name string