summaryrefslogtreecommitdiff
path: root/libpod/network/cni/config.go
blob: 44842c6647317c41912840f4f1b104ad8bc989c4 (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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
// +build linux

package cni

import (
	"net"
	"os"

	"github.com/containers/podman/v3/libpod/define"
	"github.com/containers/podman/v3/libpod/network/types"
	"github.com/containers/podman/v3/libpod/network/util"
	pkgutil "github.com/containers/podman/v3/pkg/util"
	"github.com/pkg/errors"
	"github.com/sirupsen/logrus"
	"github.com/vishvananda/netlink"
)

// NetworkCreate will take a partial filled Network and fill the
// missing fields. It creates the Network and returns the full Network.
func (n *cniNetwork) NetworkCreate(net types.Network) (types.Network, error) {
	n.lock.Lock()
	defer n.lock.Unlock()
	err := n.loadNetworks()
	if err != nil {
		return types.Network{}, err
	}
	network, err := n.networkCreate(net, true)
	if err != nil {
		return types.Network{}, err
	}
	// add the new network to the map
	n.networks[network.libpodNet.Name] = network
	return *network.libpodNet, nil
}

func (n *cniNetwork) networkCreate(net types.Network, writeToDisk bool) (*network, error) {
	// if no driver is set use the default one
	if net.Driver == "" {
		net.Driver = types.DefaultNetworkDriver
	}

	// FIXME: Should we use a different type for network create without the ID field?
	// the caller is not allowed to set a specific ID
	if net.ID != "" {
		return nil, errors.Wrap(define.ErrInvalidArg, "ID can not be set for network create")
	}

	if net.Labels == nil {
		net.Labels = map[string]string{}
	}
	if net.Options == nil {
		net.Options = map[string]string{}
	}
	if net.IPAMOptions == nil {
		net.IPAMOptions = map[string]string{}
	}

	var name string
	var err error
	// validate the name when given
	if net.Name != "" {
		if !define.NameRegex.MatchString(net.Name) {
			return nil, errors.Wrapf(define.RegexError, "network name %s invalid", net.Name)
		}
		if _, ok := n.networks[net.Name]; ok {
			return nil, errors.Wrapf(define.ErrNetworkExists, "network name %s already used", net.Name)
		}
	} else {
		name, err = n.getFreeDeviceName()
		if err != nil {
			return nil, err
		}
		net.Name = name
	}

	usedNetworks, err := n.getUsedSubnets()
	if err != nil {
		return nil, err
	}

	switch net.Driver {
	case types.BridgeNetworkDriver:
		// if the name was created with getFreeDeviceName set the interface to it as well
		if name != "" && net.NetworkInterface == "" {
			net.NetworkInterface = name
		}
		err = n.createBridge(&net, usedNetworks)
		if err != nil {
			return nil, err
		}
	case types.MacVLANNetworkDriver:
		err = createMacVLAN(&net)
		if err != nil {
			return nil, err
		}
	default:
		return nil, errors.Wrapf(define.ErrInvalidArg, "unsupported driver %s", net.Driver)
	}

	for i := range net.Subnets {
		err := validateSubnet(&net.Subnets[i], !net.Internal, usedNetworks)
		if err != nil {
			return nil, err
		}
		if util.IsIPv6(net.Subnets[i].Subnet.IP) {
			net.IPv6Enabled = true
		}
	}

	// generate the network ID
	net.ID = getNetworkIDFromName(net.Name)

	// FIXME: Should this be a hard error?
	if net.DNSEnabled && net.Internal && hasDNSNamePlugin(n.cniPluginDirs) {
		logrus.Warnf("dnsname and internal networks are incompatible. dnsname plugin not configured for network %s", net.Name)
		net.DNSEnabled = false
	}

	cniConf, path, err := n.createCNIConfigListFromNetwork(&net, writeToDisk)
	if err != nil {
		return nil, err
	}
	return &network{cniNet: cniConf, libpodNet: &net, filename: path}, nil
}

// NetworkRemove will remove the Network with the given name or ID.
// It does not ensure that the network is unused.
func (n *cniNetwork) NetworkRemove(nameOrID string) error {
	n.lock.Lock()
	defer n.lock.Unlock()
	err := n.loadNetworks()
	if err != nil {
		return err
	}

	network, err := n.getNetwork(nameOrID)
	if err != nil {
		return err
	}

	// Removing the default network is not allowed.
	if network.libpodNet.Name == n.defaultNetwork {
		return errors.Errorf("default network %s cannot be removed", n.defaultNetwork)
	}

	// Remove the bridge network interface on the host.
	if network.libpodNet.Driver == types.BridgeNetworkDriver {
		link, err := netlink.LinkByName(network.libpodNet.NetworkInterface)
		if err == nil {
			err = netlink.LinkDel(link)
			// only log the error, it is not fatal
			if err != nil {
				logrus.Infof("failed to remove network interface %s: %v", network.libpodNet.NetworkInterface, err)
			}
		}
	}

	file := network.filename
	delete(n.networks, network.libpodNet.Name)

	return os.Remove(file)
}

// NetworkList will return all known Networks. Optionally you can
// supply a list of filter functions. Only if a network matches all
// functions it is returned.
func (n *cniNetwork) NetworkList(filters ...types.FilterFunc) ([]types.Network, error) {
	n.lock.Lock()
	defer n.lock.Unlock()
	err := n.loadNetworks()
	if err != nil {
		return nil, err
	}

	networks := make([]types.Network, 0, len(n.networks))
outer:
	for _, net := range n.networks {
		for _, filter := range filters {
			// All filters have to match, if one does not match we can skip to the next network.
			if !filter(*net.libpodNet) {
				continue outer
			}
		}
		networks = append(networks, *net.libpodNet)
	}
	return networks, nil
}

// NetworkInspect will return the Network with the given name or ID.
func (n *cniNetwork) NetworkInspect(nameOrID string) (types.Network, error) {
	n.lock.Lock()
	defer n.lock.Unlock()
	err := n.loadNetworks()
	if err != nil {
		return types.Network{}, err
	}

	network, err := n.getNetwork(nameOrID)
	if err != nil {
		return types.Network{}, err
	}
	return *network.libpodNet, nil
}

func createMacVLAN(network *types.Network) error {
	if network.Internal {
		return errors.New("internal is not supported with macvlan")
	}
	if network.NetworkInterface != "" {
		interfaceNames, err := util.GetLiveNetworkNames()
		if err != nil {
			return err
		}
		if !pkgutil.StringInSlice(network.NetworkInterface, interfaceNames) {
			return errors.Errorf("parent interface %s does not exists", network.NetworkInterface)
		}
	}
	if len(network.Subnets) == 0 {
		network.IPAMOptions["driver"] = types.DHCPIPAMDriver
	} else {
		network.IPAMOptions["driver"] = types.HostLocalIPAMDriver
	}
	return nil
}

func (n *cniNetwork) createBridge(network *types.Network, usedNetworks []*net.IPNet) error {
	if network.NetworkInterface != "" {
		bridges := n.getBridgeInterfaceNames()
		if pkgutil.StringInSlice(network.NetworkInterface, bridges) {
			return errors.Errorf("bridge name %s already in use", network.NetworkInterface)
		}
		if !define.NameRegex.MatchString(network.NetworkInterface) {
			return errors.Wrapf(define.RegexError, "bridge name %s invalid", network.NetworkInterface)
		}
	} else {
		var err error
		network.NetworkInterface, err = n.getFreeDeviceName()
		if err != nil {
			return err
		}
	}

	if len(network.Subnets) == 0 {
		freeSubnet, err := n.getFreeIPv4NetworkSubnet(usedNetworks)
		if err != nil {
			return err
		}
		network.Subnets = append(network.Subnets, *freeSubnet)
	}
	// ipv6 enabled means dual stack, check if we already have
	// a ipv4 or ipv6 subnet and add one if not.
	if network.IPv6Enabled {
		ipv4 := false
		ipv6 := false
		for _, subnet := range network.Subnets {
			if util.IsIPv6(subnet.Subnet.IP) {
				ipv6 = true
			}
			if util.IsIPv4(subnet.Subnet.IP) {
				ipv4 = true
			}
		}
		if !ipv4 {
			freeSubnet, err := n.getFreeIPv4NetworkSubnet(usedNetworks)
			if err != nil {
				return err
			}
			network.Subnets = append(network.Subnets, *freeSubnet)
		}
		if !ipv6 {
			freeSubnet, err := n.getFreeIPv6NetworkSubnet(usedNetworks)
			if err != nil {
				return err
			}
			network.Subnets = append(network.Subnets, *freeSubnet)
		}
	}
	network.IPAMOptions["driver"] = types.HostLocalIPAMDriver
	return nil
}

// validateSubnet will validate a given Subnet. It checks if the
// given gateway and lease range are part of this subnet. If the
// gateway is empty and addGateway is true it will get the first
// available ip in the subnet assigned.
func validateSubnet(s *types.Subnet, addGateway bool, usedNetworks []*net.IPNet) error {
	if s == nil {
		return errors.New("subnet is nil")
	}
	if s.Subnet.IP == nil {
		return errors.New("subnet ip is nil")
	}

	// Reparse to ensure subnet is valid.
	// Do not use types.ParseCIDR() because we want the ip to be
	// the network address and not a random ip in the subnet.
	_, net, err := net.ParseCIDR(s.Subnet.String())
	if err != nil {
		return errors.Wrap(err, "subnet invalid")
	}

	// check that the new subnet does not conflict with existing ones
	if util.NetworkIntersectsWithNetworks(net, usedNetworks) {
		return errors.Errorf("subnet %s is already used on the host or by another config", net.String())
	}

	s.Subnet = types.IPNet{IPNet: *net}
	if s.Gateway != nil {
		if !s.Subnet.Contains(s.Gateway) {
			return errors.Errorf("gateway %s not in subnet %s", s.Gateway, &s.Subnet)
		}
	} else if addGateway {
		ip, err := util.FirstIPInSubnet(net)
		if err != nil {
			return err
		}
		s.Gateway = ip
	}
	if s.LeaseRange != nil {
		if s.LeaseRange.StartIP != nil && !s.Subnet.Contains(s.LeaseRange.StartIP) {
			return errors.Errorf("lease range start ip %s not in subnet %s", s.LeaseRange.StartIP, &s.Subnet)
		}
		if s.LeaseRange.EndIP != nil && !s.Subnet.Contains(s.LeaseRange.EndIP) {
			return errors.Errorf("lease range end ip %s not in subnet %s", s.LeaseRange.EndIP, &s.Subnet)
		}
	}
	return nil
}