network.go 6.4 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 35 36 37 38 39
	if ociBin == Docker {
		if runtime.GOOS == "linux" {
			return dockerGatewayIP()
		}
		// for windows and mac, the gateway ip is not routable so we use dns trick.
		return digDNS(ociBin, containerName, "host.docker.internal")
40
	}
41

42
	if runtime.GOOS == "linux" {
43
		return containerGatewayIP(ociBin, containerName)
44
	}
45 46

	return nil, fmt.Errorf("RoutableHostIPFromInside is currently only implemented for linux")
47 48
}

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

M
Medya Gh 已提交
57
	glog.Infof("got host ip for mount in container by digging dns: %s", ip.String())
M
Medya Gh 已提交
58 59
	return ip, nil
}
60

M
Medya Gh 已提交
61 62 63
// 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 已提交
64
	rr, err := runCmd(exec.Command(Docker, "network", "ls", "--filter", "name=bridge", "--format", "{{.ID}}"))
M
Medya Gh 已提交
65
	if err != nil {
M
Medya Gh 已提交
66
		return nil, errors.Wrapf(err, "get network bridge")
M
Medya Gh 已提交
67
	}
68

M
Medya Gh 已提交
69
	bridgeID := strings.TrimSpace(rr.Stdout.String())
70
	rr, err = runCmd(exec.Command(Docker, "network", "inspect",
M
Medya Gh 已提交
71
		"--format", "{{(index .IPAM.Config 0).Gateway}}", bridgeID))
72
	if err != nil {
M
Medya Gh 已提交
73
		return nil, errors.Wrapf(err, "inspect IP bridge network %q.", bridgeID)
74
	}
75

M
Medya Gh 已提交
76
	ip := net.ParseIP(strings.TrimSpace(rr.Stdout.String()))
M
Medya Gh 已提交
77 78
	glog.Infof("got host ip for mount in container by inspect docker network: %s", ip.String())
	return ip, nil
79
}
M
Medya Gh 已提交
80

81 82
// containerGatewayIP gets the default gateway ip for the container
func containerGatewayIP(ociBin, containerName string) (net.IP, error) {
83
	rr, err := runCmd(exec.Command(ociBin, "container", "inspect", "--format", "{{.NetworkSettings.Gateway}}", containerName))
84 85 86 87 88 89 90
	if err != nil {
		return nil, errors.Wrapf(err, "inspect gateway")
	}
	ip := net.ParseIP(strings.TrimSpace(rr.Stdout.String()))
	return ip, nil
}

91 92
// ForwardedPort will return port mapping for a container using cli.
// example : ForwardedPort("docker", "minikube", "22")
M
Medya Gh 已提交
93 94 95
// will return the docker assigned port:
// 32769, nil
// only supports TCP ports
M
Medya Gh 已提交
96
func ForwardedPort(ociBin string, ociID string, contPort int) (int, error) {
M
Medya Gh 已提交
97
	var rr *RunResult
M
Medya Gh 已提交
98
	var err error
99

M
Medya Gh 已提交
100
	if ociBin == Podman {
101
		rr, err = runCmd(exec.Command(ociBin, "container", "inspect", "-f", fmt.Sprintf("{{range .NetworkSettings.Ports}}{{if eq .ContainerPort %s}}{{.HostPort}}{{end}}{{end}}", fmt.Sprint(contPort)), ociID))
M
Medya Gh 已提交
102
		if err != nil {
M
Medya Gh 已提交
103
			return 0, errors.Wrapf(err, "get port %d for %q", contPort, ociID)
M
Medya Gh 已提交
104 105
		}
	} else {
106
		rr, err = runCmd(exec.Command(ociBin, "container", "inspect", "-f", fmt.Sprintf("'{{(index (index .NetworkSettings.Ports \"%d/tcp\") 0).HostPort}}'", contPort), ociID))
M
Medya Gh 已提交
107
		if err != nil {
M
Medya Gh 已提交
108
			return 0, errors.Wrapf(err, "get port %d for %q", contPort, ociID)
M
Medya Gh 已提交
109 110 111
		}
	}

M
Medya Gh 已提交
112
	o := strings.TrimSpace(rr.Stdout.String())
M
Medya Gh 已提交
113 114
	o = strings.Trim(o, "'")
	p, err := strconv.Atoi(o)
115

M
Medya Gh 已提交
116 117 118
	if err != nil {
		return p, errors.Wrapf(err, "convert host-port %q to number", p)
	}
119

M
Medya Gh 已提交
120 121 122 123
	return p, nil
}

// ContainerIPs returns ipv4,ipv6, error of a container by their name
M
Medya Gh 已提交
124 125
func ContainerIPs(ociBin string, name string) (string, string, error) {
	if ociBin == Podman {
126
		return podmanContainerIP(name)
M
Medya Gh 已提交
127 128 129 130
	}
	return dockerContainerIP(name)
}

131 132 133
// podmanContainerIP returns ipv4, ipv6 of container or error
func podmanContainerIP(name string) (string, string, error) {
	rr, err := runCmd(exec.Command(Podman, "container", "inspect",
M
Medya Gh 已提交
134
		"-f", "{{.NetworkSettings.IPAddress}}",
M
Medya Gh 已提交
135
		name))
M
Medya Gh 已提交
136 137 138
	if err != nil {
		return "", "", errors.Wrapf(err, "podman inspect ip %s", name)
	}
M
Medya Gh 已提交
139
	output := strings.TrimSpace(rr.Stdout.String())
M
Medya Gh 已提交
140 141 142 143 144 145 146 147 148 149 150 151 152
	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")
	}
153

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

M
Medya Gh 已提交
158 159 160 161
	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)
	}
162

M
Medya Gh 已提交
163 164
	return ips[0], ips[1], nil
}
J
Jose Donizetti 已提交
165 166 167

// CreateNetwork creates a network
func CreateNetwork(name, ipRange string) error {
168 169 170 171
	// check if the network already exists
	if networkExists(name) {
		return nil
	}
J
Jose Donizetti 已提交
172 173

	subnet := fmt.Sprintf("--subnet=%s", ipRange)
P
compile  
Priya Wadhwa 已提交
174
	_, err := runCmd(exec.Command(Docker, "network", "create", "--driver=bridge", subnet, name))
J
Jose Donizetti 已提交
175 176 177 178 179 180 181
	if err != nil {
		return errors.Wrapf(err, "error creating network")
	}

	return nil
}

P
compile  
Priya Wadhwa 已提交
182 183 184
// removeNetwork removes a network
func removeNetwork(name string) error {
	if !networkExists(name) {
185 186
		return nil
	}
J
Jose Donizetti 已提交
187
	_, err := runCmd(exec.Command(Docker, "network", "remove", name))
188 189 190 191 192
	return err
}

func networkExists(name string) bool {
	rr, err := runCmd(exec.Command(Docker, "network", "ls", "--format", "{{.Name}}"))
J
Jose Donizetti 已提交
193
	if err != nil {
P
compile  
Priya Wadhwa 已提交
194 195
		glog.Warningf("error listing networks: %v", err)
		return false
J
Jose Donizetti 已提交
196
	}
197 198 199 200 201 202 203
	networks := strings.Split(rr.Output(), "\n")
	for _, n := range networks {
		if n == name {
			return true
		}
	}
	return false
J
Jose Donizetti 已提交
204
}