network.go 5.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
/*
Copyright 2019 The Kubernetes Authors All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package oci

import (
	"fmt"
M
Medya Gh 已提交
21
	"net"
22 23
	"os/exec"
	"runtime"
M
Medya Gh 已提交
24
	"strconv"
25 26
	"strings"

M
Medya Gh 已提交
27
	"github.com/golang/glog"
28 29 30 31 32
	"github.com/pkg/errors"
)

// RoutableHostIPFromInside returns the ip/dns of the host that container lives on
// is routable from inside the container
M
Medya Gh 已提交
33
func RoutableHostIPFromInside(ociBin string, containerName string) (net.IP, error) {
34
	if ociBin != Docker {
M
Medya Gh 已提交
35
		return nil, fmt.Errorf("RoutableHostIPFromInside is currently only implemented for docker https://github.com/containers/libpod/issues/5205")
36 37
	}
	if runtime.GOOS == "linux" {
M
Medya Gh 已提交
38
		return dockerGatewayIP()
39
	}
M
Medya Gh 已提交
40 41
	// for windows and mac, the gateway ip is not routable so we use dns trick.
	return digDNS(ociBin, containerName, "host.docker.internal")
42 43
}

M
Medya Gh 已提交
44 45
// digDNS will get the IP record for a dns
func digDNS(ociBin, containerName, dns string) (net.IP, error) {
M
Medya Gh 已提交
46 47
	rr, err := cli.RunCmd(exec.Command(ociBin, "exec", "-t", containerName, "dig", "+short", dns))
	ip := net.ParseIP(strings.TrimSpace(rr.Stdout.String()))
48
	if err != nil {
M
Medya Gh 已提交
49
		return ip, errors.Wrapf(err, "resolve dns to ip")
50
	}
51

M
Medya Gh 已提交
52
	glog.Infof("got host ip for mount in container by digging dns: %s", ip.String())
M
Medya Gh 已提交
53 54
	return ip, nil
}
55

M
Medya Gh 已提交
56 57 58
// dockerGatewayIP gets the default gateway ip for the docker bridge on the user's host machine
// gets the ip from user's host docker
func dockerGatewayIP() (net.IP, error) {
M
Medya Gh 已提交
59
	rr, err := cli.RunCmd(exec.Command(Docker, "network", "ls", "--filter", "name=bridge", "--format", "{{.ID}}"))
M
Medya Gh 已提交
60
	if err != nil {
M
Medya Gh 已提交
61
		return nil, errors.Wrapf(err, "get network bridge")
M
Medya Gh 已提交
62
	}
63

M
Medya Gh 已提交
64 65 66
	bridgeID := strings.TrimSpace(rr.Stdout.String())
	rr, err = cli.RunCmd(exec.Command(Docker, "inspect",
		"--format", "{{(index .IPAM.Config 0).Gateway}}", bridgeID))
67
	if err != nil {
M
Medya Gh 已提交
68
		return nil, errors.Wrapf(err, "inspect IP bridge network %q.", bridgeID)
69
	}
70

M
Medya Gh 已提交
71
	ip := net.ParseIP(strings.TrimSpace(rr.Stdout.String()))
M
Medya Gh 已提交
72 73
	glog.Infof("got host ip for mount in container by inspect docker network: %s", ip.String())
	return ip, nil
74
}
M
Medya Gh 已提交
75

76 77
// ForwardedPort will return port mapping for a container using cli.
// example : ForwardedPort("docker", "minikube", "22")
M
Medya Gh 已提交
78 79 80
// will return the docker assigned port:
// 32769, nil
// only supports TCP ports
81
func ForwardedPort(ociBinary string, ociID string, contPort int) (int, error) {
M
Medya Gh 已提交
82
	var rr *RunResult
M
Medya Gh 已提交
83
	var err error
84

M
Medya Gh 已提交
85 86
	if ociBinary == Podman {
		//podman inspect -f "{{range .NetworkSettings.Ports}}{{if eq .ContainerPort "80"}}{{.HostPort}}{{end}}{{end}}"
M
Medya Gh 已提交
87
		rr, err = cli.RunCmd(exec.Command(ociBinary, "inspect", "-f", fmt.Sprintf("{{range .NetworkSettings.Ports}}{{if eq .ContainerPort %s}}{{.HostPort}}{{end}}{{end}}", fmt.Sprint(contPort)), ociID))
M
Medya Gh 已提交
88
		if err != nil {
M
Medya Gh 已提交
89
			return 0, errors.Wrapf(err, "get port %d for %q", contPort, ociID)
M
Medya Gh 已提交
90 91
		}
	} else {
M
Medya Gh 已提交
92
		rr, err = cli.RunCmd(exec.Command(ociBinary, "inspect", "-f", fmt.Sprintf("'{{(index (index .NetworkSettings.Ports \"%d/tcp\") 0).HostPort}}'", contPort), ociID))
M
Medya Gh 已提交
93
		if err != nil {
M
Medya Gh 已提交
94
			return 0, errors.Wrapf(err, "get port %d for %q", contPort, ociID)
M
Medya Gh 已提交
95 96 97
		}
	}

M
Medya Gh 已提交
98
	o := strings.TrimSpace(rr.Stdout.String())
M
Medya Gh 已提交
99 100
	o = strings.Trim(o, "'")
	p, err := strconv.Atoi(o)
101

M
Medya Gh 已提交
102 103 104
	if err != nil {
		return p, errors.Wrapf(err, "convert host-port %q to number", p)
	}
105

M
Medya Gh 已提交
106 107 108 109 110 111 112 113 114 115 116 117 118
	return p, nil
}

// ContainerIPs returns ipv4,ipv6, error of a container by their name
func ContainerIPs(ociBinary string, name string) (string, string, error) {
	if ociBinary == Podman {
		return podmanConttainerIP(name)
	}
	return dockerContainerIP(name)
}

// podmanConttainerIP returns ipv4, ipv6 of container or error
func podmanConttainerIP(name string) (string, string, error) {
M
Medya Gh 已提交
119
	rr, err := cli.RunCmd(exec.Command(Podman, "inspect",
M
Medya Gh 已提交
120
		"-f", "{{.NetworkSettings.IPAddress}}",
M
Medya Gh 已提交
121
		name))
M
Medya Gh 已提交
122 123 124
	if err != nil {
		return "", "", errors.Wrapf(err, "podman inspect ip %s", name)
	}
M
Medya Gh 已提交
125
	output := strings.TrimSpace(rr.Stdout.String())
M
Medya Gh 已提交
126 127 128 129 130 131 132 133 134 135 136 137 138
	if err == nil && output == "" { // podman returns empty for 127.0.0.1
		return DefaultBindIPV4, "", nil
	}
	return output, "", nil
}

// dockerContainerIP returns ipv4, ipv6 of container or error
func dockerContainerIP(name string) (string, string, error) {
	// retrieve the IP address of the node using docker inspect
	lines, err := inspect(Docker, name, "{{range .NetworkSettings.Networks}}{{.IPAddress}},{{.GlobalIPv6Address}}{{end}}")
	if err != nil {
		return "", "", errors.Wrap(err, "inspecting NetworkSettings.Networks")
	}
139

M
Medya Gh 已提交
140 141 142
	if len(lines) != 1 {
		return "", "", errors.Errorf("IPs output should only be one line, got %d lines", len(lines))
	}
143

M
Medya Gh 已提交
144 145 146 147
	ips := strings.Split(lines[0], ",")
	if len(ips) != 2 {
		return "", "", errors.Errorf("container addresses should have 2 values, got %d values: %+v", len(ips), ips)
	}
148

M
Medya Gh 已提交
149 150
	return ips[0], ips[1], nil
}