@@ -22,6 +22,7 @@ import (
22
22
"os"
23
23
"os/exec"
24
24
"path/filepath"
25
+ pkgruntime "runtime"
25
26
"syscall"
26
27
"time"
27
28
"unsafe"
@@ -37,6 +38,7 @@ import (
37
38
"github.com/containerd/fifo"
38
39
"github.com/containerd/ttrpc"
39
40
"github.com/containerd/typeurl"
41
+ "github.com/containernetworking/plugins/pkg/ns"
40
42
firecracker "github.com/firecracker-microvm/firecracker-go-sdk"
41
43
models "github.com/firecracker-microvm/firecracker-go-sdk/client/models"
42
44
ptypes "github.com/gogo/protobuf/types"
@@ -52,6 +54,7 @@ import (
52
54
const (
53
55
defaultVsockPort = 10789
54
56
supportedMountFSType = "ext4"
57
+ namedNetNSPath = "/var/run/netns/"
55
58
)
56
59
57
60
// implements shimapi
@@ -683,7 +686,7 @@ func (s *service) startVM(ctx context.Context,
683
686
s .machineCID = cid
684
687
685
688
log .G (ctx ).Info ("starting instance" )
686
- if err := s .machine . Start (vmmCtx ); err != nil {
689
+ if err := s .netNSStartVM (vmmCtx , vmConfig ); err != nil {
687
690
return nil , err
688
691
}
689
692
@@ -702,6 +705,30 @@ func (s *service) startVM(ctx context.Context,
702
705
return apiClient , nil
703
706
}
704
707
708
+ // netNSStartVM starts the firecracker process with the network namespace
709
+ // specified in the VM config. If the namespace is not specified, the process
710
+ // is started in the default network namespace.
711
+ func (s * service ) netNSStartVM (vmmCtx context.Context , vmConfig * proto.FirecrackerConfig ) error {
712
+ netNSName := netNSFromProto (vmConfig )
713
+ if netNSName == "" {
714
+ return s .machine .Start (vmmCtx )
715
+ }
716
+ // Get the network namespace handle.
717
+ netNS , err := ns .GetNS (namedNetNSPath + netNSName )
718
+ if err != nil {
719
+ return errors .Wrapf (err , "unable to find netns %s" , netNSName )
720
+ }
721
+ // It's unsafe to switch network namespaces without locking down the OS
722
+ // thread. Lock it for the start VM operation.
723
+ pkgruntime .LockOSThread ()
724
+ defer pkgruntime .UnlockOSThread ()
725
+
726
+ return netNS .Do (func (_ ns.NetNS ) error {
727
+ // Start the firecracker process in the target network namespace.
728
+ return s .machine .Start (vmmCtx )
729
+ })
730
+ }
731
+
705
732
func (s * service ) stopVM () error {
706
733
return s .machine .StopVMM ()
707
734
}
0 commit comments