Skip to content

Commit

Permalink
example/linux: Add vsock testing
Browse files Browse the repository at this point in the history
This commit adds a VZ_VSOCK_PORT to indicate a virtio-vsock port to
connect to after the VM has finished booting.
The example code tries to call ConnectToPort every 10 seconds, and when
the connection succeeds, it sends 'hello VM' to that connection.
`nc --listen --vsock $VZ_VSOCK_PORT` needs to be run on the VM for the
connection test to work.
  • Loading branch information
cfergeau committed Sep 26, 2022
1 parent 1943ee1 commit fd9f5cc
Showing 1 changed file with 47 additions and 0 deletions.
47 changes: 47 additions & 0 deletions example/linux/main.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
package main

import (
"fmt"
l "log"
"os"
"os/signal"
"strconv"
"strings"
"syscall"
"time"

"github.com/Code-Hex/vz/v2"
"github.com/pkg/term/termios"
Expand Down Expand Up @@ -135,6 +138,42 @@ func main() {
errCh <- err
}
})
vsockCh := make(chan *vz.VirtioSocketConnection, 1)
go func() {
vsockPortStr := os.Getenv("VZ_VSOCK_PORT")
if vsockPortStr == "" {
return
}
vsockPort, err := strconv.Atoi(vsockPortStr)
if err != nil {
log.Fatalf("Could not convert %s to int", vsockPortStr)
}
vsockConnected := func(conn *vz.VirtioSocketConnection, err error) {
if err != nil {
log.Println("vsock connection error:", err)
return
}
log.Println("vsock connection succeeded")
vsockCh <- conn
/*
// Running conn.Write from the callback passed to ConnectToPort works
if _, err := conn.Write([]byte("hello VM")); err != nil {
log.Println("sending 'hello VM' failed:", err)
return
}
*/
// `nc --listen --vsock $vsockPort` in the VM closes when this function returns.
// This indicates `conn` was closed.
}
for {
time.Sleep(10 * time.Second)
for _, vsock := range vm.SocketDevices() {
// Wait until `nc --listen --vsock $vsockPort` is running inside the VM
fmt.Printf("Trying to connect to vsock port %d", vsockPort)
vsock.ConnectToPort(uint32(vsockPort), vsockConnected)
}
}
}()

for {
select {
Expand All @@ -153,6 +192,14 @@ func main() {
log.Println("stopped successfully")
return
}
case conn := <-vsockCh:
// fails with `sending 'hello VM' failed: write : bad
// file descriptor` if VirtioSocketConnection.dup() is
// not used
if _, err := conn.Write([]byte("hello VM")); err != nil {
log.Println("sending 'hello VM' failed:", err)
return
}
case err := <-errCh:
log.Println("in start:", err)
}
Expand Down

0 comments on commit fd9f5cc

Please sign in to comment.