Skip to content

Commit

Permalink
virtionet: Cleanup unix sockets on signals
Browse files Browse the repository at this point in the history
Adds adhoc signal catching to remove the unix socket file vfkit created.
This should be moved to a higher level/made more generic/...
  • Loading branch information
cfergeau committed Jul 10, 2023
1 parent d2efc33 commit b078d8a
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 2 deletions.
3 changes: 2 additions & 1 deletion pkg/vf/virtio.go
Original file line number Diff line number Diff line change
Expand Up @@ -251,7 +251,8 @@ func AddToVirtualMachineConfig(dev config.VirtioDevice, vmConfig *vzVirtualMachi
case *config.VirtioFs:
return (*VirtioFs)(d).AddToVirtualMachineConfig(vmConfig)
case *config.VirtioNet:
return (*VirtioNet)(d).AddToVirtualMachineConfig(vmConfig)
dev := VirtioNet{VirtioNet: d}
return dev.AddToVirtualMachineConfig(vmConfig)
case *config.VirtioRng:
return (*VirtioRng)(d).AddToVirtualMachineConfig(vmConfig)
case *config.VirtioSerial:
Expand Down
35 changes: 34 additions & 1 deletion pkg/vf/virtionet.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"fmt"
"net"
"os"
"os/signal"
"path/filepath"
"syscall"

Expand All @@ -13,7 +14,10 @@ import (
log "github.com/sirupsen/logrus"
)

type VirtioNet config.VirtioNet
type VirtioNet struct {
*config.VirtioNet
localAddr *net.UnixAddr
}

func localUnixSocketPath() (string, error) {
homeDir, err := os.UserHomeDir()
Expand Down Expand Up @@ -83,7 +87,9 @@ func (dev *VirtioNet) connectUnixPath() error {
}

dev.Socket = fd
dev.localAddr = &localAddr
dev.UnixSocketPath = ""
registerExitHandler(func() { _ = dev.Shutdown() })
return nil
}

Expand Down Expand Up @@ -139,3 +145,30 @@ func (dev *VirtioNet) AddToVirtualMachineConfig(vmConfig *vzVirtualMachineConfig

return nil
}

func (dev *VirtioNet) Shutdown() error {
if dev.localAddr != nil {
if err := os.Remove(dev.localAddr.Name); err != nil {
return err
}
}
if dev.Socket != nil {
if err := dev.Socket.Close(); err != nil {
return err
}
}

return nil
}

func registerExitHandler(handler func()) {
sigChan := make(chan os.Signal, 2)
signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM, syscall.SIGINT)
go func() {
for sig := range sigChan {
log.Printf("captured %v, calling exit handlers and exiting..", sig)
handler()
os.Exit(1)
}
}()
}

0 comments on commit b078d8a

Please sign in to comment.