Debian Codegraph @

internal/vsutil/vsutil.go

raw
1 // Package vsutil provides added functionality for package vsock-internal use.
2 package vsutil
3
4 import (
5 "net"
6 "os"
7 "testing"
8
9 "github.com/FuturFusion/vsock"
10 )
11
12 // IsHypervisor detects if this machine is a hypervisor by determining if
13 // /dev/vsock is available, and then if its context ID matches the one assigned
14 // to hosts.
15 func IsHypervisor(t *testing.T) bool {
16 t.Helper()
17
18 cid, err := vsock.ContextID()
19 if err != nil {
20 SkipDeviceError(t, err)
21
22 t.Fatalf("failed to retrieve context ID: %v", err)
23 }
24
25 return cid == vsock.Host
26 }
27
28 // SkipDeviceError skips this test if err is related to a failure to access the
29 // /dev/vsock device.
30 func SkipDeviceError(t *testing.T, err error) {
31 t.Helper()
32
33 // Unwrap net.OpError if needed.
34 // TODO(mdlayher): errors.Unwrap in Go 1.13.
35 if nerr, ok := err.(*net.OpError); ok {
36 err = nerr.Err
37 }
38
39 if os.IsNotExist(err) {
40 t.Skipf("skipping, vsock device does not exist (try: 'modprobe vhost_vsock'): %v", err)
41 }
42 if os.IsPermission(err) {
43 t.Skipf("skipping, permission denied (try: 'chmod 666 /dev/vsock'): %v", err)
44 }
45 }
46
47 // SkipHostIntegration skips this test if this machine is a host and cannot
48 // perform a given test.
49 func SkipHostIntegration(t *testing.T) {
50 t.Helper()
51
52 if IsHypervisor(t) {
53 t.Skip("skipping, this integration test must be run in a guest")
54 }
55 }