File: config.go

package info (click to toggle)
golang-github-containers-common 0.50.1%2Bds1-4
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 4,440 kB
  • sloc: makefile: 118; sh: 46
file content (289 lines) | stat: -rw-r--r-- 8,230 bytes parent folder | download
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
//go:build linux || freebsd
// +build linux freebsd

package netavark

import (
	"encoding/json"
	"errors"
	"fmt"
	"net"
	"os"
	"path/filepath"
	"strconv"
	"time"

	internalutil "github.com/containers/common/libnetwork/internal/util"
	"github.com/containers/common/libnetwork/types"
	"github.com/containers/common/pkg/util"
	"github.com/containers/storage/pkg/stringid"
)

// NetworkCreate will take a partial filled Network and fill the
// missing fields. It creates the Network and returns the full Network.
func (n *netavarkNetwork) 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, false)
	if err != nil {
		return types.Network{}, err
	}
	// add the new network to the map
	n.networks[network.Name] = network
	return *network, nil
}

func (n *netavarkNetwork) networkCreate(newNetwork *types.Network, defaultNet bool) (*types.Network, error) {
	// if no driver is set use the default one
	if newNetwork.Driver == "" {
		newNetwork.Driver = types.DefaultNetworkDriver
	}
	if !defaultNet {
		// 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 newNetwork.ID != "" {
			return nil, fmt.Errorf("ID can not be set for network create: %w", types.ErrInvalidArg)
		}

		// generate random network ID
		var i int
		for i = 0; i < 1000; i++ {
			id := stringid.GenerateNonCryptoID()
			if _, err := n.getNetwork(id); err != nil {
				newNetwork.ID = id
				break
			}
		}
		if i == 1000 {
			return nil, errors.New("failed to create random network ID")
		}
	}

	err := internalutil.CommonNetworkCreate(n, newNetwork)
	if err != nil {
		return nil, err
	}

	err = validateIPAMDriver(newNetwork)
	if err != nil {
		return nil, err
	}

	// Only get the used networks for validation if we do not create the default network.
	// The default network should not be validated against used subnets, we have to ensure
	// that this network can always be created even when a subnet is already used on the host.
	// This could happen if you run a container on this net, then the cni interface will be
	// created on the host and "block" this subnet from being used again.
	// Therefore the next podman command tries to create the default net again and it would
	// fail because it thinks the network is used on the host.
	var usedNetworks []*net.IPNet
	if !defaultNet && newNetwork.Driver == types.BridgeNetworkDriver {
		usedNetworks, err = internalutil.GetUsedSubnets(n)
		if err != nil {
			return nil, err
		}
	}

	switch newNetwork.Driver {
	case types.BridgeNetworkDriver:
		err = internalutil.CreateBridge(n, newNetwork, usedNetworks, n.defaultsubnetPools)
		if err != nil {
			return nil, err
		}
		// validate the given options, we do not need them but just check to make sure they are valid
		for key, value := range newNetwork.Options {
			switch key {
			case types.MTUOption:
				_, err = internalutil.ParseMTU(value)
				if err != nil {
					return nil, err
				}

			case types.VLANOption:
				_, err = internalutil.ParseVlan(value)
				if err != nil {
					return nil, err
				}

			case types.IsolateOption:
				val, err := strconv.ParseBool(value)
				if err != nil {
					return nil, err
				}
				// rust only support "true" or "false" while go can parse 1 and 0 as well so we need to change it
				newNetwork.Options[types.IsolateOption] = strconv.FormatBool(val)
			default:
				return nil, fmt.Errorf("unsupported bridge network option %s", key)
			}
		}
	case types.MacVLANNetworkDriver:
		err = createMacvlan(newNetwork)
		if err != nil {
			return nil, err
		}
	default:
		return nil, fmt.Errorf("unsupported driver %s: %w", newNetwork.Driver, types.ErrInvalidArg)
	}

	// when we do not have ipam we must disable dns
	internalutil.IpamNoneDisableDNS(newNetwork)

	// add gateway when not internal or dns enabled
	addGateway := !newNetwork.Internal || newNetwork.DNSEnabled
	err = internalutil.ValidateSubnets(newNetwork, addGateway, usedNetworks)
	if err != nil {
		return nil, err
	}

	newNetwork.Created = time.Now()

	if !defaultNet {
		confPath := filepath.Join(n.networkConfigDir, newNetwork.Name+".json")
		f, err := os.Create(confPath)
		if err != nil {
			return nil, err
		}
		defer f.Close()
		enc := json.NewEncoder(f)
		enc.SetIndent("", "     ")
		err = enc.Encode(newNetwork)
		if err != nil {
			return nil, err
		}
	}

	return newNetwork, nil
}

func createMacvlan(network *types.Network) error {
	if network.NetworkInterface != "" {
		interfaceNames, err := internalutil.GetLiveNetworkNames()
		if err != nil {
			return err
		}
		if !util.StringInSlice(network.NetworkInterface, interfaceNames) {
			return fmt.Errorf("parent interface %s does not exist", network.NetworkInterface)
		}
	}

	// we already validated the drivers before so we just have to set the default here
	switch network.IPAMOptions[types.Driver] {
	case "":
		if len(network.Subnets) == 0 {
			return fmt.Errorf("macvlan driver needs at least one subnet specified, DHCP is not yet supported with netavark")
		}
		network.IPAMOptions[types.Driver] = types.HostLocalIPAMDriver
	case types.HostLocalIPAMDriver:
		if len(network.Subnets) == 0 {
			return fmt.Errorf("macvlan driver needs at least one subnet specified, when the host-local ipam driver is set")
		}
	}

	// validate the given options, we do not need them but just check to make sure they are valid
	for key, value := range network.Options {
		switch key {
		case types.ModeOption:
			if !util.StringInSlice(value, types.ValidMacVLANModes) {
				return fmt.Errorf("unknown macvlan mode %q", value)
			}
		case types.MTUOption:
			_, err := internalutil.ParseMTU(value)
			if err != nil {
				return err
			}
		default:
			return fmt.Errorf("unsupported macvlan network option %s", key)
		}
	}
	return nil
}

// NetworkRemove will remove the Network with the given name or ID.
// It does not ensure that the network is unused.
func (n *netavarkNetwork) 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.Name == n.defaultNetwork {
		return fmt.Errorf("default network %s cannot be removed", n.defaultNetwork)
	}

	file := filepath.Join(n.networkConfigDir, network.Name+".json")
	// make sure to not error for ErrNotExist
	if err := os.Remove(file); err != nil && !errors.Is(err, os.ErrNotExist) {
		return err
	}
	delete(n.networks, network.Name)
	return nil
}

// 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 *netavarkNetwork) 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) {
				continue outer
			}
		}
		networks = append(networks, *net)
	}
	return networks, nil
}

// NetworkInspect will return the Network with the given name or ID.
func (n *netavarkNetwork) 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, nil
}

func validateIPAMDriver(n *types.Network) error {
	ipamDriver := n.IPAMOptions[types.Driver]
	switch ipamDriver {
	case "", types.HostLocalIPAMDriver:
	case types.NoneIPAMDriver:
		if len(n.Subnets) > 0 {
			return errors.New("none ipam driver is set but subnets are given")
		}
	case types.DHCPIPAMDriver:
		return errors.New("dhcp ipam driver is not yet supported with netavark")
	default:
		return fmt.Errorf("unsupported ipam driver %q", ipamDriver)
	}
	return nil
}