Fix portforward for host network.

Signed-off-by: Lantao Liu <lantaol@google.com>
This commit is contained in:
Lantao Liu 2018-04-17 07:41:23 +00:00
parent 19882b8028
commit 5cb4744f27

View File

@ -53,8 +53,23 @@ func (c *criService) portForward(id string, port int32, stream io.ReadWriteClose
if err != nil { if err != nil {
return errors.Wrapf(err, "failed to find sandbox %q in store", id) return errors.Wrapf(err, "failed to find sandbox %q in store", id)
} }
if s.NetNS == nil || s.NetNS.Closed() { var netNSDo func(func(ns.NetNS) error) error
return errors.Errorf("network namespace for sandbox %q is closed", id) // netNSPath is the network namespace path for logging.
var netNSPath string
securityContext := s.Config.GetLinux().GetSecurityContext()
hostNet := securityContext.GetNamespaceOptions().GetNetwork() == runtime.NamespaceMode_NODE
if !hostNet {
if s.NetNS == nil || s.NetNS.Closed() {
return errors.Errorf("network namespace for sandbox %q is closed", id)
}
netNSDo = s.NetNS.GetNs().Do
netNSPath = s.NetNS.GetPath()
} else {
// Run the function directly for host network.
netNSDo = func(do func(_ ns.NetNS) error) error {
return do(nil)
}
netNSPath = "host"
} }
socat, err := exec.LookPath("socat") socat, err := exec.LookPath("socat")
@ -65,8 +80,8 @@ func (c *criService) portForward(id string, port int32, stream io.ReadWriteClose
// Check https://linux.die.net/man/1/socat for meaning of the options. // Check https://linux.die.net/man/1/socat for meaning of the options.
args := []string{socat, "-", fmt.Sprintf("TCP4:localhost:%d", port)} args := []string{socat, "-", fmt.Sprintf("TCP4:localhost:%d", port)}
logrus.Infof("Executing port forwarding command %q in network namespace %q", strings.Join(args, " "), s.NetNS.GetPath()) logrus.Infof("Executing port forwarding command %q in network namespace %q", strings.Join(args, " "), netNSPath)
err = s.NetNS.GetNs().Do(func(_ ns.NetNS) error { err = netNSDo(func(_ ns.NetNS) error {
cmd := exec.Command(args[0], args[1:]...) cmd := exec.Command(args[0], args[1:]...)
cmd.Stdout = stream cmd.Stdout = stream
@ -95,12 +110,12 @@ func (c *criService) portForward(id string, port int32, stream io.ReadWriteClose
}() }()
if err := cmd.Run(); err != nil { if err := cmd.Run(); err != nil {
return errors.Errorf("nsenter command returns error: %v, stderr: %q", err, stderr.String()) return errors.Errorf("socat command returns error: %v, stderr: %q", err, stderr.String())
} }
return nil return nil
}) })
if err != nil { if err != nil {
return errors.Wrapf(err, "failed to execute portforward in network namespace %s", s.NetNS.GetPath()) return errors.Wrapf(err, "failed to execute portforward in network namespace %q", netNSPath)
} }
logrus.Infof("Finish port forwarding for %q port %d", id, port) logrus.Infof("Finish port forwarding for %q port %d", id, port)