Skip to content

Conversation

@cfergeau
Copy link
Collaborator

@cfergeau cfergeau commented Oct 8, 2025

The previous commits added a VfkitMagic property which for now defaults to
true for backwards compatibility with older gvproxy versions. However, this
default was not used when unmarshalling a json vm configuration made with
an older vfkit version. This could cause unexpected issues with networking.

This commit sets VfkitMagic to true by default when unmarshalling json.

Summary by CodeRabbit

  • Bug Fixes

    • Improved backward compatibility when loading network device configuration: a compatibility flag is now inferred from the presence of a Unix socket path so older configs continue to behave as expected.
  • New Features

    • Added a public API to retrieve network device entries from a virtual machine.
  • Refactor

    • Consolidated device-filtering logic into a single reusable implementation.
  • Tests

    • Added tests covering backwards-compatibility behavior for network devices.

@openshift-ci openshift-ci bot requested review from anjannath and lstocchi October 8, 2025 15:21
@openshift-ci
Copy link

openshift-ci bot commented Oct 8, 2025

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by:
Once this PR has been reviewed and has the lgtm label, please assign baude for approval. For more information see the Code Review Process.

The full list of commands accepted by this bot can be found here.

Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

@coderabbitai
Copy link

coderabbitai bot commented Oct 8, 2025

Walkthrough

Unmarshal for VirtioNet now pre-sets VfkitMagic = true before JSON decoding and clears it after decoding when UnixSocketPath is empty. Added generic device filter and a VirtioNetDevices getter. Tests updated to use slices.Contains and a new backwards-compatibility test was added.

Changes

Cohort / File(s) Summary
VirtioNet JSON unmarshal
pkg/config/json.go
Pre-initialize VfkitMagic = true before JSON unmarshal; after unmarshalling set VfkitMagic = false if UnixSocketPath is empty to preserve backward compatibility.
Device helpers / getters
pkg/config/config.go
Add generic FilterDevices[V VMComponent](vm *VirtualMachine) []V; refactor existing getters to use it; add func (vm *VirtualMachine) VirtioNetDevices() []*VirtioNet.
Tests and helpers
pkg/config/json_test.go
Replace local contains helper with slices.Contains; add helper testVirtioNetVfkitMagicJson and TestVirtioNetBackwardsCompat to validate VfkitMagic defaulting, explicit defaults, and explicit overrides.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant Caller
  participant VirtioNet as VirtioNet.unmarshalVirtioNet
  participant JSON as encoding/json

  Caller->>VirtioNet: unmarshalVirtioNet(jsonData)
  Note over VirtioNet: set VfkitMagic = true (pre-unmarshal)
  VirtioNet->>JSON: json.Unmarshal into struct
  JSON-->>VirtioNet: populated fields
  alt UnixSocketPath == ""
    Note over VirtioNet: set VfkitMagic = false (post-unmarshal)
  else UnixSocketPath != ""
    Note over VirtioNet: keep VfkitMagic as set/provided
  end
  VirtioNet-->>Caller: return VirtioNet config
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested labels

lgtm, approved

Suggested reviewers

  • praveenkumar

Poem

A hop, a whisk, a JSON cheer,
VfkitMagic wakes, then calms when clear.
Devices filtered, helpers in line,
Tests hum softly — compatibility fine. 🐰✨

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 40.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The PR title "json: Add backward compatibility with VfkitMagic" accurately reflects the primary objective and main changes described in the PR objectives. The changes to json.go and supporting tests in json_test.go directly address the backward compatibility issue with VfkitMagic, where the default value was not being applied during JSON unmarshalling of VM configurations from older vfkit versions. While the changeset also includes refactoring in config.go (introducing a generic FilterDevices helper and adding VirtioNetDevices getter), these appear to be secondary supporting or infrastructure changes rather than the core purpose of the PR. The title is clear, specific, and concisely communicates the main objective without unnecessary detail.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5b9220a and 32f1dac.

📒 Files selected for processing (2)
  • pkg/config/json.go (2 hunks)
  • pkg/config/json_test.go (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • pkg/config/json_test.go
  • pkg/config/json.go
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (4)
  • GitHub Check: build (macos-14)
  • GitHub Check: build (macos-15)
  • GitHub Check: build (macos-13)
  • GitHub Check: lint

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (2)
pkg/config/json_test.go (2)

7-7: LGTM! Good refactor to use standard library.

Replacing the custom contains function with slices.Contains from the standard library improves maintainability and reduces code duplication.

Also applies to: 28-28


333-367: Consider adding test case for overridden vfkitMagic.

The test effectively validates backward compatibility by checking:

  1. JSON without vfkitMagic defaults to true (lines 334-349)
  2. Explicit vfkitMagic: false is respected (lines 351-366)

However, consider adding a third test case to verify the post-unmarshal override logic in json.go lines 127-130: JSON with vfkitMagic: true but empty unixSocketPath should result in VfkitMagic: false after unmarshalling.

Example test case:

/* Check that vfkitMagic is forced to false when unixSocketPath is empty */
jsonStr = `{"vcpus":3,"memoryBytes":4194304000,"bootloader":{"kind":"linuxBootloader","vmlinuzPath":"/vmlinuz","initrdPath":"/initrd","kernelCmdLine":"console=hvc0"},"devices":[{"kind":"virtionet","nat":true,"vfkitMagic":true,"macAddress":"00:11:22:33:44:55"}]}`

err = json.Unmarshal([]byte(jsonStr), &unmarshalledVM)
require.NoError(t, err)

// vfkitMagic should be false since unixSocketPath is empty
virtioNet := unmarshalledVM.Devices[0].(*VirtioNet)
require.False(t, virtioNet.VfkitMagic)
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ac40bbe and 746de49.

📒 Files selected for processing (2)
  • pkg/config/json.go (2 hunks)
  • pkg/config/json_test.go (3 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
pkg/config/json_test.go (3)
pkg/vf/vm.go (1)
  • VirtualMachine (17-20)
pkg/config/config.go (1)
  • VirtualMachine (28-36)
pkg/config/virtio.go (1)
  • VirtioNetNew (406-419)
🔇 Additional comments (2)
pkg/config/json.go (2)

113-114: LGTM! Correct approach for backward compatibility.

Setting the default value before unmarshalling ensures that older JSON configurations (which lack the vfkitMagic field) will default to true, preserving backward compatibility with older gvproxy versions. If the field is present in the JSON, it will be overwritten during unmarshalling.


127-130: Verify that overriding explicit vfkitMagic values is intentional.

This code forces VfkitMagic to false when UnixSocketPath is empty, even if the JSON explicitly sets vfkitMagic: true. While the comment explains the rationale ("vfkitMagic is only useful in combination with unixSocketPath"), this behavior overrides explicit user intent from the JSON configuration.

Please confirm:

  1. This override is intentional and aligns with the domain requirements
  2. This behavior is documented or will be made clear to users
  3. There are no valid use cases for vfkitMagic=true without a socket path

If this override is intentional, consider adding a test case that verifies this behavior (JSON with vfkitMagic: true but no unixSocketPath should result in VfkitMagic: false after unmarshalling).

// vfkitMagic is only useful in combination with unixSocketPath
if dev.UnixSocketPath == "" {
dev.VfkitMagic = false
}
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does it break anything if we keep the default true value?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think it should because this field is only used when UnixSocketPath is set.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This breaks one of the test cases:

--- FAIL: TestJSON (0.00s)
    --- FAIL: TestJSON/json (0.00s)
        --- FAIL: TestJSON/json/TestAllVirtioDevices (0.00s)
            json_test.go:402: 
                	Error Trace:	/var/home/teuf/dev/vfkit/pkg/config/json_test.go:402
                	            				/var/home/teuf/dev/vfkit/pkg/config/json_test.go:374
                	Error:      	Not equal: 
                	            	expected: config.VirtualMachine{Vcpus:0x3, Memory:0xfa000000, Bootloader:(*config.LinuxBootloader)(0xc00019e540), Devices:[]config.VirtioDevice{(*config.VirtioSerial)(0xc00019e570), (*config.VirtioInput)(0xc000029970), (*config.VirtioGPU)(0xc0000186c0), (*config.VirtioNet)(0xc000015400), (*config.VirtioRng)(0x8ea820), (*config.VirtioBlk)(0xc000015440), (*config.VirtioVsock)(0xc00007c9a0), (*config.VirtioFs)(0xc00007c9c0), (*config.USBMassStorage)(0xc00019e5d0), (*config.RosettaShare)(0xc000010b40), (*config.NetworkBlockDevice)(0xc0000d0ff0)}, Timesync:(*config.TimeSync)(nil), Ignition:(*config.Ignition)(nil), Nested:false}
                	            	actual  : config.VirtualMachine{Vcpus:0x3, Memory:0xfa000000, Bootloader:(*config.LinuxBootloader)(0xc0001b61b0), Devices:[]config.VirtioDevice{(*config.VirtioSerial)(0xc0001b6240), (*config.VirtioInput)(0xc0001ba6d0), (*config.VirtioGPU)(0xc0000189d8), (*config.VirtioNet)(0xc0000d10e0), (*config.VirtioRng)(0x8ea820), (*config.VirtioBlk)(0xc000015640), (*config.VirtioVsock)(0xc00007cb60), (*config.VirtioFs)(0xc00007cb80), (*config.USBMassStorage)(0xc0001b6a50), (*config.RosettaShare)(0xc000010ff0), (*config.NetworkBlockDevice)(0xc0000d1130)}, Timesync:(*config.TimeSync)(nil), Ignition:(*config.Ignition)(nil), Nested:false}
                	            	
                	            	Diff:
                	            	--- Expected
                	            	+++ Actual
                	            	@@ -32,3 +32,3 @@
                	            	    UnixSocketPath: (string) "",
                	            	-   VfkitMagic: (bool) false
                	            	+   VfkitMagic: (bool) true
                	            	   }),
                	Test:       	TestJSON/json/TestAllVirtioDevices
FAIL
FAIL	github.com/crc-org/vfkit/pkg/config	0.009s
FAIL

We could change the default even in the !unixsocketpath case, but then there are more tests to modify, json serialization of a virtionet device will always have vfkitMagic set even when it’s not used, …
In my opinion it’s preferrable to keep the default to false when unixSocketPath is not used.

skipFields []string
expectedJSON string
}

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It will help to add a comment that this old json does not include vfkitMagic and parsing it should use the default value.

require.NoError(t, err)
require.True(t, dev.VfkitMagic)

require.Equal(t, *vm, unmarshalledVM)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It will will help to comment about the check - I think what you try to do here is verify that json from older version is manipulated to match json created by current version.

Signed-off-by: Christophe Fergeau <[email protected]>
This allows VirtioInputDevices/VirtioGPUs/… to share the same code.
This commit also adds a VirtioNetDevices method which will be used in
the next commit.

Signed-off-by: Christophe Fergeau <[email protected]>
Copy link
Collaborator Author

@cfergeau cfergeau left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think I’ve addressed most of the comments. Some of the suggested comments might still be missing, let me know which ones I forgot :)

// vfkitMagic is only useful in combination with unixSocketPath
if dev.UnixSocketPath == "" {
dev.VfkitMagic = false
}
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This breaks one of the test cases:

--- FAIL: TestJSON (0.00s)
    --- FAIL: TestJSON/json (0.00s)
        --- FAIL: TestJSON/json/TestAllVirtioDevices (0.00s)
            json_test.go:402: 
                	Error Trace:	/var/home/teuf/dev/vfkit/pkg/config/json_test.go:402
                	            				/var/home/teuf/dev/vfkit/pkg/config/json_test.go:374
                	Error:      	Not equal: 
                	            	expected: config.VirtualMachine{Vcpus:0x3, Memory:0xfa000000, Bootloader:(*config.LinuxBootloader)(0xc00019e540), Devices:[]config.VirtioDevice{(*config.VirtioSerial)(0xc00019e570), (*config.VirtioInput)(0xc000029970), (*config.VirtioGPU)(0xc0000186c0), (*config.VirtioNet)(0xc000015400), (*config.VirtioRng)(0x8ea820), (*config.VirtioBlk)(0xc000015440), (*config.VirtioVsock)(0xc00007c9a0), (*config.VirtioFs)(0xc00007c9c0), (*config.USBMassStorage)(0xc00019e5d0), (*config.RosettaShare)(0xc000010b40), (*config.NetworkBlockDevice)(0xc0000d0ff0)}, Timesync:(*config.TimeSync)(nil), Ignition:(*config.Ignition)(nil), Nested:false}
                	            	actual  : config.VirtualMachine{Vcpus:0x3, Memory:0xfa000000, Bootloader:(*config.LinuxBootloader)(0xc0001b61b0), Devices:[]config.VirtioDevice{(*config.VirtioSerial)(0xc0001b6240), (*config.VirtioInput)(0xc0001ba6d0), (*config.VirtioGPU)(0xc0000189d8), (*config.VirtioNet)(0xc0000d10e0), (*config.VirtioRng)(0x8ea820), (*config.VirtioBlk)(0xc000015640), (*config.VirtioVsock)(0xc00007cb60), (*config.VirtioFs)(0xc00007cb80), (*config.USBMassStorage)(0xc0001b6a50), (*config.RosettaShare)(0xc000010ff0), (*config.NetworkBlockDevice)(0xc0000d1130)}, Timesync:(*config.TimeSync)(nil), Ignition:(*config.Ignition)(nil), Nested:false}
                	            	
                	            	Diff:
                	            	--- Expected
                	            	+++ Actual
                	            	@@ -32,3 +32,3 @@
                	            	    UnixSocketPath: (string) "",
                	            	-   VfkitMagic: (bool) false
                	            	+   VfkitMagic: (bool) true
                	            	   }),
                	Test:       	TestJSON/json/TestAllVirtioDevices
FAIL
FAIL	github.com/crc-org/vfkit/pkg/config	0.009s
FAIL

We could change the default even in the !unixsocketpath case, but then there are more tests to modify, json serialization of a virtionet device will always have vfkitMagic set even when it’s not used, …
In my opinion it’s preferrable to keep the default to false when unixSocketPath is not used.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 746de49 and 4e49fa2.

📒 Files selected for processing (3)
  • pkg/config/config.go (1 hunks)
  • pkg/config/json.go (2 hunks)
  • pkg/config/json_test.go (3 hunks)
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-10-12T15:51:07.560Z
Learnt from: nirs
PR: crc-org/vfkit#0
File: :0-0
Timestamp: 2025-10-12T15:51:07.560Z
Learning: In the vfkit virtio-net code (pkg/vf/virtionet.go), the connectUnixPath function change was about closing the connection after duplication (since conn.File() already duplicates the fd), not about introducing the duplication itself.

Applied to files:

  • pkg/config/json.go
🧬 Code graph analysis (2)
pkg/config/json_test.go (3)
pkg/config/config.go (1)
  • VirtualMachine (28-36)
pkg/vf/vm.go (1)
  • VirtualMachine (17-20)
pkg/config/virtio.go (1)
  • VirtioNetNew (406-419)
pkg/config/config.go (3)
pkg/vf/vm.go (1)
  • VirtualMachine (17-20)
pkg/config/virtio.go (4)
  • VirtioGPU (45-48)
  • VirtioVsock (52-61)
  • VirtioInput (35-37)
  • VirtioNet (99-108)
pkg/vf/virtio.go (3)
  • VirtioGPU (30-30)
  • VirtioVsock (28-28)
  • VirtioInput (29-29)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: build (macos-14)
  • GitHub Check: build (macos-15)
  • GitHub Check: build (macos-13)
🔇 Additional comments (4)
pkg/config/config.go (1)

164-188: LGTM! Clean refactoring with generics.

The introduction of FilterDevices[V VMComponent] eliminates repetitive type-checking logic and provides a consistent pattern for device filtering. The new VirtioNetDevices accessor aligns well with the existing device getters and supports the VFKit magic handling tested in json_test.go.

pkg/config/json.go (2)

113-114: LGTM! Backward-compatible default.

Setting VfkitMagic = true before unmarshalling ensures that older vfkit-generated JSON configurations (which lack this field) will default to the compatible behavior.


127-130: Correct: VfkitMagic tied to UnixSocketPath presence.

Forcing VfkitMagic = false when UnixSocketPath is empty correctly enforces that this field is only meaningful in combination with a unix socket connection.

Based on learnings: this field is only used when UnixSocketPath is set.

pkg/config/json_test.go (1)

7-7: LGTM! Modern stdlib usage.

Replacing the custom contains helper with slices.Contains from the standard library is a good modernization.

Also applies to: 28-28

Comment on lines 333 to 369
func testVirtioNetVfkitMagicJson(t *testing.T, vfkitMagic bool) {
jsonTemplate := `{"vcpus":3,"memoryBytes":4194304000,"bootloader":{"kind":"linuxBootloader","vmlinuzPath":"/vmlinuz","initrdPath":"/initrd","kernelCmdLine":"console=hvc0"},"devices":[{"kind":"virtionet","nat":false,"unixSocketPath":"/some/path/to/socket","macAddress":"00:11:22:33:44:55"%s}]}`
var jsonStr string
var unmarshalledVM VirtualMachine

if vfkitMagic {
jsonStr = fmt.Sprintf(jsonTemplate, ``)
} else {
jsonStr = fmt.Sprintf(jsonTemplate, `,"vfkitMagic":false`)
}
err := json.Unmarshal([]byte(jsonStr), &unmarshalledVM)
require.NoError(t, err)
netDevs := unmarshalledVM.VirtioNetDevices()
require.Len(t, netDevs, 1)
require.Equal(t, netDevs[0].VfkitMagic, vfkitMagic)

vm := newLinuxVM(t)
dev, err := VirtioNetNew("00:11:22:33:44:55")
require.NoError(t, err)
dev.SetUnixSocketPath("/some/path/to/socket")
if !vfkitMagic {
dev.VfkitMagic = false
}
err = vm.AddDevice(dev)
require.NoError(t, err)
require.Equal(t, dev.VfkitMagic, vfkitMagic)

require.Equal(t, *vm, unmarshalledVM)
}

func TestVirtioNetBackwardsCompat(t *testing.T) {
/* Check that the vfkitMagic default is true when deserializing json */
t.Run("VfkitMagicJsonDefault", func(t *testing.T) { testVirtioNetVfkitMagicJson(t, true) })

/* Check that the vfkitMagic default can be overridden */
t.Run("VfkitMagicJsonDefaultOverride", func(t *testing.T) { testVirtioNetVfkitMagicJson(t, false) })
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion | 🟠 Major

Add test coverage for empty UnixSocketPath.

The tests verify backward compatibility when UnixSocketPath is set, but don't cover the case where UnixSocketPath is empty. The logic in json.go (lines 127-130) clears VfkitMagic when UnixSocketPath is empty, which should be tested to ensure that even if JSON explicitly sets "vfkitMagic": true, it gets overridden to false when there's no socket path.

Add a third test case:

/* Check that vfkitMagic is cleared when UnixSocketPath is empty */
t.Run("VfkitMagicClearedWhenNoSocket", func(t *testing.T) {
	jsonStr := `{"vcpus":3,"memoryBytes":4194304000,"bootloader":{"kind":"linuxBootloader","vmlinuzPath":"/vmlinuz","initrdPath":"/initrd","kernelCmdLine":"console=hvc0"},"devices":[{"kind":"virtionet","nat":false,"macAddress":"00:11:22:33:44:55","vfkitMagic":true}]}`
	var unmarshalledVM VirtualMachine
	err := json.Unmarshal([]byte(jsonStr), &unmarshalledVM)
	require.NoError(t, err)
	netDevs := unmarshalledVM.VirtioNetDevices()
	require.Len(t, netDevs, 1)
	require.False(t, netDevs[0].VfkitMagic, "VfkitMagic should be false when UnixSocketPath is empty")
})
🤖 Prompt for AI Agents
In pkg/config/json_test.go around lines 333-369, add a third subtest that
verifies VfkitMagic is cleared when UnixSocketPath is empty: unmarshal a JSON
payload for a virtio-net device that explicitly sets "vfkitMagic": true but
omits unixSocketPath, assert Unmarshal succeeds, assert there is one VirtioNet
device, and assert that device.VfkitMagic is false; place the new
t.Run("VfkitMagicClearedWhenNoSocket", ...) alongside the two existing runs.

@nirs nirs self-requested a review October 17, 2025 16:35
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
pkg/config/json_test.go (1)

355-355: Swap argument order in require.Equal for better error messages.

The require.Equal function expects (expected, actual) order. Lines 355 and 366 have the arguments reversed, which will produce confusing error messages when tests fail.

Apply this diff:

-	require.Equal(t, netDevs[0].VfkitMagic, vfkitMagic)
+	require.Equal(t, vfkitMagic, netDevs[0].VfkitMagic)

And:

-	require.Equal(t, dev.VfkitMagic, vfkitMagic)
+	require.Equal(t, vfkitMagic, dev.VfkitMagic)

Also applies to: 366-366

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4e49fa2 and 5b9220a.

📒 Files selected for processing (2)
  • pkg/config/json.go (2 hunks)
  • pkg/config/json_test.go (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • pkg/config/json.go
🧰 Additional context used
🧬 Code graph analysis (1)
pkg/config/json_test.go (2)
pkg/config/config.go (1)
  • VirtualMachine (28-36)
pkg/config/virtio.go (1)
  • VirtioNetNew (406-419)
🔇 Additional comments (1)
pkg/config/json_test.go (1)

7-7: LGTM! Good refactor to use standard library.

Using slices.Contains from the standard library is cleaner and more maintainable than a custom contains function.

Also applies to: 28-28

Comment on lines +371 to +380
func TestVirtioNetBackwardsCompat(t *testing.T) {
/* Check that the vfkitMagic default is true when deserializing json */
t.Run("VfkitMagicJsonDefault", func(t *testing.T) { testVirtioNetVfkitMagicJson(t, true, true) })

/* Check that the vfkitMagic default can be overridden */
t.Run("VfkitMagicJsonDefaultOverride", func(t *testing.T) { testVirtioNetVfkitMagicJson(t, false, false) })

/* Check that explicitly setting vfkitMagic to true works as expected */
t.Run("VfkitMagicJsonExplicitDefault", func(t *testing.T) { testVirtioNetVfkitMagicJson(t, true, false) })
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion | 🟠 Major

Add test coverage for empty UnixSocketPath case.

The tests verify backward compatibility when UnixSocketPath is set, but don't cover the case where UnixSocketPath is empty. According to the PR description and the logic in json.go, VfkitMagic should be cleared when UnixSocketPath is empty. This scenario should be tested to ensure the backward compatibility logic works correctly.

Add a fourth subtest:

/* Check that vfkitMagic is cleared when UnixSocketPath is empty */
t.Run("VfkitMagicClearedWhenNoSocket", func(t *testing.T) {
	jsonStr := `{"vcpus":3,"memoryBytes":4194304000,"bootloader":{"kind":"linuxBootloader","vmlinuzPath":"/vmlinuz","initrdPath":"/initrd","kernelCmdLine":"console=hvc0"},"devices":[{"kind":"virtionet","nat":false,"macAddress":"00:11:22:33:44:55","vfkitMagic":true}]}`
	var unmarshalledVM VirtualMachine
	err := json.Unmarshal([]byte(jsonStr), &unmarshalledVM)
	require.NoError(t, err)
	netDevs := unmarshalledVM.VirtioNetDevices()
	require.Len(t, netDevs, 1)
	require.False(t, netDevs[0].VfkitMagic, "VfkitMagic should be false when UnixSocketPath is empty")
})

Based on learnings.

🤖 Prompt for AI Agents
In pkg/config/json_test.go around lines 371 to 380, add a fourth subtest to
TestVirtioNetBackwardsCompat that verifies VfkitMagic is cleared when
UnixSocketPath is empty: create a JSON string representing a VM with a
virtio-net device that has vfkitMagic true but no unixSocketPath, unmarshal into
VirtualMachine, assert no error, get VirtioNetDevices(), assert length 1 and
assert the device's VfkitMagic is false; place this subtest alongside the
existing three using t.Run with the name "VfkitMagicClearedWhenNoSocket".

The previous commits added a VfkitMagic property which for now defaults
to true for backwards compatibility with older gvproxy versions.
However, this default was not used when unmarshalling a json vm
configuration made with an older vfkit version. This could cause
unexpected issues with networking.

This commit sets VfkitMagic to true by default when unmarshalling json.

Signed-off-by: Christophe Fergeau <[email protected]>
Assisted-by: CodeRabbit.ai
Signed-off-by: Christophe Fergeau <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants