summaryrefslogtreecommitdiff
path: root/server/sandbox_network.go
blob: 15cf99c8f92c07ce8596ce2d61b527664ec135e7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package server

import (
	"fmt"
	"net"

	"github.com/kubernetes-incubator/cri-o/libkpod/sandbox"
	"github.com/sirupsen/logrus"
	"k8s.io/kubernetes/pkg/kubelet/network/hostport"
)

// networkStart sets up the sandbox's network and returns the pod IP on success
// or an error
func (s *Server) networkStart(hostNetwork bool, sb *sandbox.Sandbox) (string, error) {
	if hostNetwork {
		return s.BindAddress(), nil
	}

	podNetwork := newPodNetwork(sb)
	err := s.netPlugin.SetUpPod(podNetwork)
	if err != nil {
		return "", fmt.Errorf("failed to create pod network sandbox %s(%s): %v", sb.Name(), sb.ID(), err)
	}

	var ip string
	if ip, err = s.netPlugin.GetPodNetworkStatus(podNetwork); err != nil {
		return "", fmt.Errorf("failed to get network status for pod sandbox %s(%s): %v", sb.Name(), sb.ID(), err)
	}

	if len(sb.PortMappings()) > 0 {
		ip4 := net.ParseIP(ip).To4()
		if ip4 == nil {
			return "", fmt.Errorf("failed to get valid ipv4 address for sandbox %s(%s)", sb.Name(), sb.ID())
		}

		if err = s.hostportManager.Add(sb.ID(), &hostport.PodPortMapping{
			Name:         sb.Name(),
			PortMappings: sb.PortMappings(),
			IP:           ip4,
			HostNetwork:  false,
		}, "lo"); err != nil {
			return "", fmt.Errorf("failed to add hostport mapping for sandbox %s(%s): %v", sb.Name(), sb.ID(), err)
		}

	}
	return ip, nil
}

// networkStop cleans up and removes a pod's network.  It is best-effort and
// must call the network plugin even if the network namespace is already gone
func (s *Server) networkStop(hostNetwork bool, sb *sandbox.Sandbox) error {
	if !hostNetwork {
		if err := s.hostportManager.Remove(sb.ID(), &hostport.PodPortMapping{
			Name:         sb.Name(),
			PortMappings: sb.PortMappings(),
			HostNetwork:  false,
		}); err != nil {
			logrus.Warnf("failed to remove hostport for pod sandbox %s(%s): %v",
				sb.Name(), sb.ID(), err)
		}

		podNetwork := newPodNetwork(sb)
		if err := s.netPlugin.TearDownPod(podNetwork); err != nil {
			logrus.Warnf("failed to destroy network for pod sandbox %s(%s): %v",
				sb.Name(), sb.ID(), err)
		}
	}

	return nil
}