Example #1
0
func SetupPortMaps(containerip string, maps []pod.UserContainerPort) error {
	if disableIptables || len(maps) == 0 {
		return nil
	}

	for _, m := range maps {
		var proto string

		if strings.EqualFold(m.Protocol, "udp") {
			proto = "udp"
		} else {
			proto = "tcp"
		}

		natArgs := []string{"-p", proto, "-m", proto, "--dport",
			strconv.Itoa(m.HostPort), "-j", "DNAT", "--to-destination",
			net.JoinHostPort(containerip, strconv.Itoa(m.ContainerPort))}

		if iptables.PortMapExists("HYPER", natArgs) {
			return nil
		}

		if iptables.PortMapUsed("HYPER", natArgs) {
			return fmt.Errorf("Host port %d has aleady been used", m.HostPort)
		}

		err := iptables.OperatePortMap(iptables.Insert, "HYPER", natArgs)
		if err != nil {
			return err
		}

		err = PortMapper.AllocateMap(m.Protocol, m.HostPort, containerip, m.ContainerPort)
		if err != nil {
			return err
		}

		filterArgs := []string{"-d", containerip, "-p", proto, "-m", proto,
			"--dport", strconv.Itoa(m.ContainerPort), "-j", "ACCEPT"}
		if output, err := iptables.Raw(append([]string{"-I", "HYPER"}, filterArgs...)...); err != nil {
			return fmt.Errorf("Unable to setup forward rule in HYPER chain: %s", err)
		} else if len(output) != 0 {
			return &iptables.ChainError{Chain: "HYPER", Output: output}
		}
	}
	/* forbid to map ports twice */
	return nil
}
Example #2
0
func SetupPortMaps(vmId string, index int, containerip string, maps []pod.UserContainerPort) error {
	if len(maps) == 0 {
		return nil
	}

	for _, m := range maps {
		var proto string

		if strings.EqualFold(m.Protocol, "udp") {
			proto = "udp"
		} else {
			proto = "tcp"
		}

		if iptables.PortMapExists(proto, strconv.Itoa(m.HostPort)) {
			return nil
		}

		rule := virtualbox.PFRule{}
		rule.Proto = virtualbox.PFProto(proto)
		rule.HostIP = nil
		rule.HostPort = uint16(m.HostPort)
		rule.GuestIP = net.ParseIP(containerip)
		rule.GuestPort = uint16(m.ContainerPort)
		err := virtualbox.SetNATPF(vmId, 1, vmId, rule)
		if err != nil {
			return err
		}

		err = portMapper.AllocateMap(m.Protocol, m.HostPort, containerip, m.ContainerPort)
		if err != nil {
			return err
		}
	}
	/* forbid to map ports twice */
	return nil
}