diff --git a/pkg/mosconfig/network.go b/pkg/mosconfig/network.go index e4247e2..fca5cf1 100644 --- a/pkg/mosconfig/network.go +++ b/pkg/mosconfig/network.go @@ -147,26 +147,22 @@ func (mos *Mos) DefaultNic() (string, error) { // Setup port forward rules for a container. Must be called with the // mos.NetLock held. mos.setupSimpleNet() takes that lock. func (mos *Mos) setupPortFwd(t *Target) error { - // TODO - we need the name of the host nic nic, err := mos.DefaultNic() if err != nil { return errors.Wrapf(err, "Failed to find default nic") } - ipaddr := "" - if t.Network.Address != "" { - ipaddr = t.Network.Address - } else if t.Network.Address6 != "" { - ipaddr = "[" + t.Network.Address6 + "]" - } else { - return fmt.Errorf("No usable address for port forward destination") + ipaddr, err := t.Ipaddr() + if err != nil { + return err } for _, p := range t.Network.Ports { destaddr := strings.Split(ipaddr, "/")[0] // 192.168.2.0/24 destaddr = fmt.Sprintf("%s:%d", destaddr, p.ContainerPort) cmd := []string{ "iptables", "-t", "nat", "-A", "PREROUTING", "-p", "tcp", - "-m", "tcp", "-i", nic, "--dport", fmt.Sprintf("%d", p.HostPort), - "-j", "DNAT", "--to-destination", destaddr} + "-i", nic, "--dport", fmt.Sprintf("%d", p.HostPort), + "-j", "DNAT", "--to-destination", destaddr, + "-m", "comment", "--comment", t.ServiceName} if err := utils.RunCommand(cmd...); err != nil { return errors.Wrapf(err, "Failed setting up port forward for %#v", p) } @@ -187,12 +183,47 @@ func (mos *Mos) SetupTargetNetwork(t *Target) ([]string, error) { } } +func (t *Target) Ipaddr() (string, error) { + if t.Network.Address != "" { + return t.Network.Address, nil + } + if t.Network.Address6 != "" { + return "[" + t.Network.Address6 + "]", nil + } + + return "", fmt.Errorf("No usable address for port forward destination") +} + func (mos *Mos) StopTargetNetwork(t *Target) error { mos.NetLock.Lock() defer mos.NetLock.Unlock() + ipaddr := "" + nic := "" for _, p := range t.Network.Ports { - // TODO - remove the iptables rule for this port + if ipaddr == "" { + var err error + ipaddr, err = t.Ipaddr() + if err != nil { + return err + } + nic, err = mos.DefaultNic() + if err != nil { + return errors.Wrapf(err, "Failed to find default nic") + } + } + + destaddr := strings.Split(ipaddr, "/")[0] // 192.168.2.0/24 + destaddr = fmt.Sprintf("%s:%d", destaddr, p.ContainerPort) + + cmd := []string{ + "iptables", "-t", "nat", "-D", "PREROUTING", "-p", "tcp", + "-i", nic, "--dport", fmt.Sprintf("%d", p.HostPort), + "-j", "DNAT", "--to-destination", destaddr, + "-m", "comment", "--comment", t.ServiceName} + if err := utils.RunCommand(cmd...); err != nil { + return errors.Wrapf(err, "Failed setting up port forward for %#v", p) + } delete(mos.Manifest.UsedPorts, p.HostPort) }