Skip to content
This repository was archived by the owner on Mar 9, 2022. It is now read-only.

Commit 5cb4744

Browse files
committed
Fix portforward for host network.
Signed-off-by: Lantao Liu <[email protected]>
1 parent 19882b8 commit 5cb4744

File tree

1 file changed

+21
-6
lines changed

1 file changed

+21
-6
lines changed

pkg/server/sandbox_portforward.go

Lines changed: 21 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -53,8 +53,23 @@ func (c *criService) portForward(id string, port int32, stream io.ReadWriteClose
5353
if err != nil {
5454
return errors.Wrapf(err, "failed to find sandbox %q in store", id)
5555
}
56-
if s.NetNS == nil || s.NetNS.Closed() {
57-
return errors.Errorf("network namespace for sandbox %q is closed", id)
56+
var netNSDo func(func(ns.NetNS) error) error
57+
// netNSPath is the network namespace path for logging.
58+
var netNSPath string
59+
securityContext := s.Config.GetLinux().GetSecurityContext()
60+
hostNet := securityContext.GetNamespaceOptions().GetNetwork() == runtime.NamespaceMode_NODE
61+
if !hostNet {
62+
if s.NetNS == nil || s.NetNS.Closed() {
63+
return errors.Errorf("network namespace for sandbox %q is closed", id)
64+
}
65+
netNSDo = s.NetNS.GetNs().Do
66+
netNSPath = s.NetNS.GetPath()
67+
} else {
68+
// Run the function directly for host network.
69+
netNSDo = func(do func(_ ns.NetNS) error) error {
70+
return do(nil)
71+
}
72+
netNSPath = "host"
5873
}
5974

6075
socat, err := exec.LookPath("socat")
@@ -65,8 +80,8 @@ func (c *criService) portForward(id string, port int32, stream io.ReadWriteClose
6580
// Check https://linux.die.net/man/1/socat for meaning of the options.
6681
args := []string{socat, "-", fmt.Sprintf("TCP4:localhost:%d", port)}
6782

68-
logrus.Infof("Executing port forwarding command %q in network namespace %q", strings.Join(args, " "), s.NetNS.GetPath())
69-
err = s.NetNS.GetNs().Do(func(_ ns.NetNS) error {
83+
logrus.Infof("Executing port forwarding command %q in network namespace %q", strings.Join(args, " "), netNSPath)
84+
err = netNSDo(func(_ ns.NetNS) error {
7085
cmd := exec.Command(args[0], args[1:]...)
7186
cmd.Stdout = stream
7287

@@ -95,12 +110,12 @@ func (c *criService) portForward(id string, port int32, stream io.ReadWriteClose
95110
}()
96111

97112
if err := cmd.Run(); err != nil {
98-
return errors.Errorf("nsenter command returns error: %v, stderr: %q", err, stderr.String())
113+
return errors.Errorf("socat command returns error: %v, stderr: %q", err, stderr.String())
99114
}
100115
return nil
101116
})
102117
if err != nil {
103-
return errors.Wrapf(err, "failed to execute portforward in network namespace %s", s.NetNS.GetPath())
118+
return errors.Wrapf(err, "failed to execute portforward in network namespace %q", netNSPath)
104119
}
105120
logrus.Infof("Finish port forwarding for %q port %d", id, port)
106121

0 commit comments

Comments
 (0)