Debian Codegraph @

libcni/api.go

raw
1 // Copyright 2015 CNI authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package libcni
16
17 // Note this is the actual implementation of the CNI specification, which
18 // is reflected in the SPEC.md file.
19 // it is typically bundled into runtime providers (i.e. containerd or cri-o would use this
20 // before calling runc or hcsshim). It is also bundled into CNI providers as well, for example,
21 // to add an IP to a container, to parse the configuration of the CNI and so on.
22
23 import (
24 "context"
25 "encoding/json"
26 "errors"
27 "fmt"
28 "os"
29 "path/filepath"
30 "sort"
31 "strings"
32
33 "github.com/containernetworking/cni/pkg/invoke"
34 "github.com/containernetworking/cni/pkg/types"
35 "github.com/containernetworking/cni/pkg/types/create"
36 "github.com/containernetworking/cni/pkg/utils"
37 "github.com/containernetworking/cni/pkg/version"
38 )
39
40 var (
41 CacheDir = "/var/lib/cni"
42 // slightly awkward wording to preserve anyone matching on error strings
43 ErrorCheckNotSupp = fmt.Errorf("does not support the CHECK command")
44 )
45
46 const (
47 CNICacheV1 = "cniCacheV1"
48 )
49
50 // A RuntimeConf holds the arguments to one invocation of a CNI plugin
51 // excepting the network configuration, with the nested exception that
52 // the `runtimeConfig` from the network configuration is included
53 // here.
54 type RuntimeConf struct {
55 ContainerID string
56 NetNS string
57 IfName string
58 Args [][2]string
59 // A dictionary of capability-specific data passed by the runtime
60 // to plugins as top-level keys in the 'runtimeConfig' dictionary
61 // of the plugin's stdin data. libcni will ensure that only keys
62 // in this map which match the capabilities of the plugin are passed
63 // to the plugin
64 CapabilityArgs map[string]interface{}
65
66 // DEPRECATED. Will be removed in a future release.
67 CacheDir string
68 }
69
70 // Use PluginConfig instead of NetworkConfig, the NetworkConfig
71 // backwards-compat alias will be removed in a future release.
72 type NetworkConfig = PluginConfig
73
74 type PluginConfig struct {
75 Network *types.PluginConf
76 Bytes []byte
77 }
78
79 type NetworkConfigList struct {
80 Name string
81 CNIVersion string
82 DisableCheck bool
83 DisableGC bool
84 LoadOnlyInlinedPlugins bool
85 Plugins []*PluginConfig
86 Bytes []byte
87 }
88
89 type NetworkAttachment struct {
90 ContainerID string
91 Network string
92 IfName string
93 Config []byte
94 NetNS string
95 CniArgs [][2]string
96 CapabilityArgs map[string]interface{}
97 }
98
99 type GCArgs struct {
100 ValidAttachments []types.GCAttachment
101 }
102
103 type CNI interface {
104 AddNetworkList(ctx context.Context, net *NetworkConfigList, rt *RuntimeConf) (types.Result, error)
105 CheckNetworkList(ctx context.Context, net *NetworkConfigList, rt *RuntimeConf) error
106 DelNetworkList(ctx context.Context, net *NetworkConfigList, rt *RuntimeConf) error
107 GetNetworkListCachedResult(net *NetworkConfigList, rt *RuntimeConf) (types.Result, error)
108 GetNetworkListCachedConfig(net *NetworkConfigList, rt *RuntimeConf) ([]byte, *RuntimeConf, error)
109
110 AddNetwork(ctx context.Context, net *PluginConfig, rt *RuntimeConf) (types.Result, error)
111 CheckNetwork(ctx context.Context, net *PluginConfig, rt *RuntimeConf) error
112 DelNetwork(ctx context.Context, net *PluginConfig, rt *RuntimeConf) error
113 GetNetworkCachedResult(net *PluginConfig, rt *RuntimeConf) (types.Result, error)
114 GetNetworkCachedConfig(net *PluginConfig, rt *RuntimeConf) ([]byte, *RuntimeConf, error)
115
116 ValidateNetworkList(ctx context.Context, net *NetworkConfigList) ([]string, error)
117 ValidateNetwork(ctx context.Context, net *PluginConfig) ([]string, error)
118
119 GCNetworkList(ctx context.Context, net *NetworkConfigList, args *GCArgs) error
120 GetStatusNetworkList(ctx context.Context, net *NetworkConfigList) error
121
122 GetCachedAttachments(containerID string) ([]*NetworkAttachment, error)
123
124 GetVersionInfo(ctx context.Context, pluginType string) (version.PluginInfo, error)
125 }
126
127 type CNIConfig struct {
128 Path []string
129 exec invoke.Exec
130 cacheDir string
131 }
132
133 // CNIConfig implements the CNI interface
134 var _ CNI = &CNIConfig{}
135
136 // NewCNIConfig returns a new CNIConfig object that will search for plugins
137 // in the given paths and use the given exec interface to run those plugins,
138 // or if the exec interface is not given, will use a default exec handler.
139 func NewCNIConfig(path []string, exec invoke.Exec) *CNIConfig {
140 return NewCNIConfigWithCacheDir(path, "", exec)
141 }
142
143 // NewCNIConfigWithCacheDir returns a new CNIConfig object that will search for plugins
144 // in the given paths use the given exec interface to run those plugins,
145 // or if the exec interface is not given, will use a default exec handler.
146 // The given cache directory will be used for temporary data storage when needed.
147 func NewCNIConfigWithCacheDir(path []string, cacheDir string, exec invoke.Exec) *CNIConfig {
148 return &CNIConfig{
149 Path: path,
150 cacheDir: cacheDir,
151 exec: exec,
152 }
153 }
154
155 func buildOneConfig(name, cniVersion string, orig *PluginConfig, prevResult types.Result, rt *RuntimeConf) (*PluginConfig, error) {
156 var err error
157
158 inject := map[string]interface{}{
159 "name": name,
160 "cniVersion": cniVersion,
161 }
162 // Add previous plugin result
163 if prevResult != nil {
164 inject["prevResult"] = prevResult
165 }
166
167 // Ensure every config uses the same name and version
168 orig, err = InjectConf(orig, inject)
169 if err != nil {
170 return nil, err
171 }
172 if rt != nil {
173 return injectRuntimeConfig(orig, rt)
174 }
175
176 return orig, nil
177 }
178
179 // This function takes a libcni RuntimeConf structure and injects values into
180 // a "runtimeConfig" dictionary in the CNI network configuration JSON that
181 // will be passed to the plugin on stdin.
182 //
183 // Only "capabilities arguments" passed by the runtime are currently injected.
184 // These capabilities arguments are filtered through the plugin's advertised
185 // capabilities from its config JSON, and any keys in the CapabilityArgs
186 // matching plugin capabilities are added to the "runtimeConfig" dictionary
187 // sent to the plugin via JSON on stdin. For example, if the plugin's
188 // capabilities include "portMappings", and the CapabilityArgs map includes a
189 // "portMappings" key, that key and its value are added to the "runtimeConfig"
190 // dictionary to be passed to the plugin's stdin.
191 func injectRuntimeConfig(orig *PluginConfig, rt *RuntimeConf) (*PluginConfig, error) {
192 var err error
193
194 rc := make(map[string]interface{})
195 for capability, supported := range orig.Network.Capabilities {
196 if !supported {
197 continue
198 }
199 if data, ok := rt.CapabilityArgs[capability]; ok {
200 rc[capability] = data
201 }
202 }
203
204 if len(rc) > 0 {
205 orig, err = InjectConf(orig, map[string]interface{}{"runtimeConfig": rc})
206 if err != nil {
207 return nil, err
208 }
209 }
210
211 return orig, nil
212 }
213
214 // ensure we have a usable exec if the CNIConfig was not given one
215 func (c *CNIConfig) ensureExec() invoke.Exec {
216 if c.exec == nil {
217 c.exec = &invoke.DefaultExec{
218 RawExec: &invoke.RawExec{Stderr: os.Stderr},
219 PluginDecoder: version.PluginDecoder{},
220 }
221 }
222 return c.exec
223 }
224
225 type cachedInfo struct {
226 Kind string `json:"kind"`
227 ContainerID string `json:"containerId"`
228 Config []byte `json:"config"`
229 IfName string `json:"ifName"`
230 NetworkName string `json:"networkName"`
231 NetNS string `json:"netns,omitempty"`
232 CniArgs [][2]string `json:"cniArgs,omitempty"`
233 CapabilityArgs map[string]interface{} `json:"capabilityArgs,omitempty"`
234 RawResult map[string]interface{} `json:"result,omitempty"`
235 Result types.Result `json:"-"`
236 }
237
238 // getCacheDir returns the cache directory in this order:
239 // 1) global cacheDir from CNIConfig object
240 // 2) deprecated cacheDir from RuntimeConf object
241 // 3) fall back to default cache directory
242 func (c *CNIConfig) getCacheDir(rt *RuntimeConf) string {
243 if c.cacheDir != "" {
244 return c.cacheDir
245 }
246 if rt.CacheDir != "" {
247 return rt.CacheDir
248 }
249 return CacheDir
250 }
251
252 func (c *CNIConfig) getCacheFilePath(netName string, rt *RuntimeConf) (string, error) {
253 if netName == "" || rt.ContainerID == "" || rt.IfName == "" {
254 return "", fmt.Errorf("cache file path requires network name (%q), container ID (%q), and interface name (%q)", netName, rt.ContainerID, rt.IfName)
255 }
256 return filepath.Join(c.getCacheDir(rt), "results", fmt.Sprintf("%s-%s-%s", netName, rt.ContainerID, rt.IfName)), nil
257 }
258
259 func (c *CNIConfig) cacheAdd(result types.Result, config []byte, netName string, rt *RuntimeConf) error {
260 cached := cachedInfo{
261 Kind: CNICacheV1,
262 ContainerID: rt.ContainerID,
263 Config: config,
264 IfName: rt.IfName,
265 NetworkName: netName,
266 NetNS: rt.NetNS,
267 CniArgs: rt.Args,
268 CapabilityArgs: rt.CapabilityArgs,
269 }
270
271 // We need to get type.Result into cachedInfo as JSON map
272 // Marshal to []byte, then Unmarshal into cached.RawResult
273 data, err := json.Marshal(result)
274 if err != nil {
275 return err
276 }
277
278 err = json.Unmarshal(data, &cached.RawResult)
279 if err != nil {
280 return err
281 }
282
283 newBytes, err := json.Marshal(&cached)
284 if err != nil {
285 return err
286 }
287
288 fname, err := c.getCacheFilePath(netName, rt)
289 if err != nil {
290 return err
291 }
292 if err := os.MkdirAll(filepath.Dir(fname), 0o700); err != nil {
293 return err
294 }
295
296 return os.WriteFile(fname, newBytes, 0o600)
297 }
298
299 func (c *CNIConfig) cacheDel(netName string, rt *RuntimeConf) error {
300 fname, err := c.getCacheFilePath(netName, rt)
301 if err != nil {
302 // Ignore error
303 return nil
304 }
305 return os.Remove(fname)
306 }
307
308 func (c *CNIConfig) getCachedConfig(netName string, rt *RuntimeConf) ([]byte, *RuntimeConf, error) {
309 var bytes []byte
310
311 fname, err := c.getCacheFilePath(netName, rt)
312 if err != nil {
313 return nil, nil, err
314 }
315 bytes, err = os.ReadFile(fname)
316 if err != nil {
317 // Ignore read errors; the cached result may not exist on-disk
318 return nil, nil, nil
319 }
320
321 unmarshaled := cachedInfo{}
322 if err := json.Unmarshal(bytes, &unmarshaled); err != nil {
323 return nil, nil, fmt.Errorf("failed to unmarshal cached network %q config: %w", netName, err)
324 }
325 if unmarshaled.Kind != CNICacheV1 {
326 return nil, nil, fmt.Errorf("read cached network %q config has wrong kind: %v", netName, unmarshaled.Kind)
327 }
328
329 newRt := *rt
330 if unmarshaled.CniArgs != nil {
331 newRt.Args = unmarshaled.CniArgs
332 }
333 newRt.CapabilityArgs = unmarshaled.CapabilityArgs
334
335 return unmarshaled.Config, &newRt, nil
336 }
337
338 func (c *CNIConfig) getLegacyCachedResult(netName, cniVersion string, rt *RuntimeConf) (types.Result, error) {
339 fname, err := c.getCacheFilePath(netName, rt)
340 if err != nil {
341 return nil, err
342 }
343 data, err := os.ReadFile(fname)
344 if err != nil {
345 // Ignore read errors; the cached result may not exist on-disk
346 return nil, nil
347 }
348
349 // Load the cached result
350 result, err := create.CreateFromBytes(data)
351 if err != nil {
352 return nil, err
353 }
354
355 // Convert to the config version to ensure plugins get prevResult
356 // in the same version as the config. The cached result version
357 // should match the config version unless the config was changed
358 // while the container was running.
359 result, err = result.GetAsVersion(cniVersion)
360 if err != nil {
361 return nil, fmt.Errorf("failed to convert cached result to config version %q: %w", cniVersion, err)
362 }
363 return result, nil
364 }
365
366 func (c *CNIConfig) getCachedResult(netName, cniVersion string, rt *RuntimeConf) (types.Result, error) {
367 fname, err := c.getCacheFilePath(netName, rt)
368 if err != nil {
369 return nil, err
370 }
371 fdata, err := os.ReadFile(fname)
372 if err != nil {
373 // Ignore read errors; the cached result may not exist on-disk
374 return nil, nil
375 }
376
377 cachedInfo := cachedInfo{}
378 if err := json.Unmarshal(fdata, &cachedInfo); err != nil || cachedInfo.Kind != CNICacheV1 {
379 return c.getLegacyCachedResult(netName, cniVersion, rt)
380 }
381
382 newBytes, err := json.Marshal(&cachedInfo.RawResult)
383 if err != nil {
384 return nil, fmt.Errorf("failed to marshal cached network %q config: %w", netName, err)
385 }
386
387 // Load the cached result
388 result, err := create.CreateFromBytes(newBytes)
389 if err != nil {
390 return nil, err
391 }
392
393 // Convert to the config version to ensure plugins get prevResult
394 // in the same version as the config. The cached result version
395 // should match the config version unless the config was changed
396 // while the container was running.
397 result, err = result.GetAsVersion(cniVersion)
398 if err != nil {
399 return nil, fmt.Errorf("failed to convert cached result to config version %q: %w", cniVersion, err)
400 }
401 return result, nil
402 }
403
404 // GetNetworkListCachedResult returns the cached Result of the previous
405 // AddNetworkList() operation for a network list, or an error.
406 func (c *CNIConfig) GetNetworkListCachedResult(list *NetworkConfigList, rt *RuntimeConf) (types.Result, error) {
407 return c.getCachedResult(list.Name, list.CNIVersion, rt)
408 }
409
410 // GetNetworkCachedResult returns the cached Result of the previous
411 // AddNetwork() operation for a network, or an error.
412 func (c *CNIConfig) GetNetworkCachedResult(net *PluginConfig, rt *RuntimeConf) (types.Result, error) {
413 return c.getCachedResult(net.Network.Name, net.Network.CNIVersion, rt)
414 }
415
416 // GetNetworkListCachedConfig copies the input RuntimeConf to output
417 // RuntimeConf with fields updated with info from the cached Config.
418 func (c *CNIConfig) GetNetworkListCachedConfig(list *NetworkConfigList, rt *RuntimeConf) ([]byte, *RuntimeConf, error) {
419 return c.getCachedConfig(list.Name, rt)
420 }
421
422 // GetNetworkCachedConfig copies the input RuntimeConf to output
423 // RuntimeConf with fields updated with info from the cached Config.
424 func (c *CNIConfig) GetNetworkCachedConfig(net *PluginConfig, rt *RuntimeConf) ([]byte, *RuntimeConf, error) {
425 return c.getCachedConfig(net.Network.Name, rt)
426 }
427
428 // GetCachedAttachments returns a list of network attachments from the cache.
429 // The returned list will be filtered by the containerID if the value is not empty.
430 func (c *CNIConfig) GetCachedAttachments(containerID string) ([]*NetworkAttachment, error) {
431 dirPath := filepath.Join(c.getCacheDir(&RuntimeConf{}), "results")
432 entries, err := os.ReadDir(dirPath)
433 if err != nil {
434 if os.IsNotExist(err) {
435 return nil, nil
436 }
437 return nil, err
438 }
439
440 fileNames := make([]string, 0, len(entries))
441 for _, e := range entries {
442 fileNames = append(fileNames, e.Name())
443 }
444 sort.Strings(fileNames)
445
446 attachments := []*NetworkAttachment{}
447 for _, fname := range fileNames {
448 if len(containerID) > 0 {
449 part := fmt.Sprintf("-%s-", containerID)
450 pos := strings.Index(fname, part)
451 if pos <= 0 || pos+len(part) >= len(fname) {
452 continue
453 }
454 }
455
456 cacheFile := filepath.Join(dirPath, fname)
457 bytes, err := os.ReadFile(cacheFile)
458 if err != nil {
459 continue
460 }
461
462 cachedInfo := cachedInfo{}
463
464 if err := json.Unmarshal(bytes, &cachedInfo); err != nil {
465 continue
466 }
467 if cachedInfo.Kind != CNICacheV1 {
468 continue
469 }
470 if len(containerID) > 0 && cachedInfo.ContainerID != containerID {
471 continue
472 }
473 if cachedInfo.IfName == "" || cachedInfo.NetworkName == "" {
474 continue
475 }
476
477 attachments = append(attachments, &NetworkAttachment{
478 ContainerID: cachedInfo.ContainerID,
479 Network: cachedInfo.NetworkName,
480 IfName: cachedInfo.IfName,
481 Config: cachedInfo.Config,
482 NetNS: cachedInfo.NetNS,
483 CniArgs: cachedInfo.CniArgs,
484 CapabilityArgs: cachedInfo.CapabilityArgs,
485 })
486 }
487 return attachments, nil
488 }
489
490 func (c *CNIConfig) addNetwork(ctx context.Context, name, cniVersion string, net *PluginConfig, prevResult types.Result, rt *RuntimeConf) (types.Result, error) {
491 c.ensureExec()
492 pluginPath, err := c.exec.FindInPath(net.Network.Type, c.Path)
493 if err != nil {
494 return nil, err
495 }
496 if err := utils.ValidateContainerID(rt.ContainerID); err != nil {
497 return nil, err
498 }
499 if err := utils.ValidateNetworkName(name); err != nil {
500 return nil, err
501 }
502 if err := utils.ValidateInterfaceName(rt.IfName); err != nil {
503 return nil, err
504 }
505
506 newConf, err := buildOneConfig(name, cniVersion, net, prevResult, rt)
507 if err != nil {
508 return nil, err
509 }
510
511 return invoke.ExecPluginWithResult(ctx, pluginPath, newConf.Bytes, c.args("ADD", rt), c.exec)
512 }
513
514 // AddNetworkList executes a sequence of plugins with the ADD command
515 func (c *CNIConfig) AddNetworkList(ctx context.Context, list *NetworkConfigList, rt *RuntimeConf) (types.Result, error) {
516 var err error
517 var result types.Result
518 for _, net := range list.Plugins {
519 result, err = c.addNetwork(ctx, list.Name, list.CNIVersion, net, result, rt)
520 if err != nil {
521 return nil, fmt.Errorf("plugin %s failed (add): %w", pluginDescription(net.Network), err)
522 }
523 }
524
525 if err = c.cacheAdd(result, list.Bytes, list.Name, rt); err != nil {
526 return nil, fmt.Errorf("failed to set network %q cached result: %w", list.Name, err)
527 }
528
529 return result, nil
530 }
531
532 func (c *CNIConfig) checkNetwork(ctx context.Context, name, cniVersion string, net *PluginConfig, prevResult types.Result, rt *RuntimeConf) error {
533 c.ensureExec()
534 pluginPath, err := c.exec.FindInPath(net.Network.Type, c.Path)
535 if err != nil {
536 return err
537 }
538
539 newConf, err := buildOneConfig(name, cniVersion, net, prevResult, rt)
540 if err != nil {
541 return err
542 }
543
544 return invoke.ExecPluginWithoutResult(ctx, pluginPath, newConf.Bytes, c.args("CHECK", rt), c.exec)
545 }
546
547 // CheckNetworkList executes a sequence of plugins with the CHECK command
548 func (c *CNIConfig) CheckNetworkList(ctx context.Context, list *NetworkConfigList, rt *RuntimeConf) error {
549 // CHECK was added in CNI spec version 0.4.0 and higher
550 if gtet, err := version.GreaterThanOrEqualTo(list.CNIVersion, "0.4.0"); err != nil {
551 return err
552 } else if !gtet {
553 return fmt.Errorf("configuration version %q %w", list.CNIVersion, ErrorCheckNotSupp)
554 }
555
556 if list.DisableCheck {
557 return nil
558 }
559
560 cachedResult, err := c.getCachedResult(list.Name, list.CNIVersion, rt)
561 if err != nil {
562 return fmt.Errorf("failed to get network %q cached result: %w", list.Name, err)
563 }
564
565 for _, net := range list.Plugins {
566 if err := c.checkNetwork(ctx, list.Name, list.CNIVersion, net, cachedResult, rt); err != nil {
567 return err
568 }
569 }
570
571 return nil
572 }
573
574 func (c *CNIConfig) delNetwork(ctx context.Context, name, cniVersion string, net *PluginConfig, prevResult types.Result, rt *RuntimeConf) error {
575 c.ensureExec()
576 pluginPath, err := c.exec.FindInPath(net.Network.Type, c.Path)
577 if err != nil {
578 return err
579 }
580
581 newConf, err := buildOneConfig(name, cniVersion, net, prevResult, rt)
582 if err != nil {
583 return err
584 }
585
586 return invoke.ExecPluginWithoutResult(ctx, pluginPath, newConf.Bytes, c.args("DEL", rt), c.exec)
587 }
588
589 // DelNetworkList executes a sequence of plugins with the DEL command
590 func (c *CNIConfig) DelNetworkList(ctx context.Context, list *NetworkConfigList, rt *RuntimeConf) error {
591 var cachedResult types.Result
592
593 // Cached result on DEL was added in CNI spec version 0.4.0 and higher
594 if gtet, err := version.GreaterThanOrEqualTo(list.CNIVersion, "0.4.0"); err != nil {
595 return err
596 } else if gtet {
597 if cachedResult, err = c.getCachedResult(list.Name, list.CNIVersion, rt); err != nil {
598 _ = c.cacheDel(list.Name, rt)
599 cachedResult = nil
600 }
601 }
602
603 for i := len(list.Plugins) - 1; i >= 0; i-- {
604 net := list.Plugins[i]
605 if err := c.delNetwork(ctx, list.Name, list.CNIVersion, net, cachedResult, rt); err != nil {
606 return fmt.Errorf("plugin %s failed (delete): %w", pluginDescription(net.Network), err)
607 }
608 }
609
610 _ = c.cacheDel(list.Name, rt)
611
612 return nil
613 }
614
615 func pluginDescription(net *types.PluginConf) string {
616 if net == nil {
617 return "<missing>"
618 }
619 pluginType := net.Type
620 out := fmt.Sprintf("type=%q", pluginType)
621 name := net.Name
622 if name != "" {
623 out += fmt.Sprintf(" name=%q", name)
624 }
625 return out
626 }
627
628 // AddNetwork executes the plugin with the ADD command
629 func (c *CNIConfig) AddNetwork(ctx context.Context, net *PluginConfig, rt *RuntimeConf) (types.Result, error) {
630 result, err := c.addNetwork(ctx, net.Network.Name, net.Network.CNIVersion, net, nil, rt)
631 if err != nil {
632 return nil, err
633 }
634
635 if err = c.cacheAdd(result, net.Bytes, net.Network.Name, rt); err != nil {
636 return nil, fmt.Errorf("failed to set network %q cached result: %w", net.Network.Name, err)
637 }
638
639 return result, nil
640 }
641
642 // CheckNetwork executes the plugin with the CHECK command
643 func (c *CNIConfig) CheckNetwork(ctx context.Context, net *PluginConfig, rt *RuntimeConf) error {
644 // CHECK was added in CNI spec version 0.4.0 and higher
645 if gtet, err := version.GreaterThanOrEqualTo(net.Network.CNIVersion, "0.4.0"); err != nil {
646 return err
647 } else if !gtet {
648 return fmt.Errorf("configuration version %q %w", net.Network.CNIVersion, ErrorCheckNotSupp)
649 }
650
651 cachedResult, err := c.getCachedResult(net.Network.Name, net.Network.CNIVersion, rt)
652 if err != nil {
653 return fmt.Errorf("failed to get network %q cached result: %w", net.Network.Name, err)
654 }
655 return c.checkNetwork(ctx, net.Network.Name, net.Network.CNIVersion, net, cachedResult, rt)
656 }
657
658 // DelNetwork executes the plugin with the DEL command
659 func (c *CNIConfig) DelNetwork(ctx context.Context, net *PluginConfig, rt *RuntimeConf) error {
660 var cachedResult types.Result
661
662 // Cached result on DEL was added in CNI spec version 0.4.0 and higher
663 if gtet, err := version.GreaterThanOrEqualTo(net.Network.CNIVersion, "0.4.0"); err != nil {
664 return err
665 } else if gtet {
666 cachedResult, err = c.getCachedResult(net.Network.Name, net.Network.CNIVersion, rt)
667 if err != nil {
668 return fmt.Errorf("failed to get network %q cached result: %w", net.Network.Name, err)
669 }
670 }
671
672 if err := c.delNetwork(ctx, net.Network.Name, net.Network.CNIVersion, net, cachedResult, rt); err != nil {
673 return err
674 }
675 _ = c.cacheDel(net.Network.Name, rt)
676 return nil
677 }
678
679 // ValidateNetworkList checks that a configuration is reasonably valid.
680 // - all the specified plugins exist on disk
681 // - every plugin supports the desired version.
682 //
683 // Returns a list of all capabilities supported by the configuration, or error
684 func (c *CNIConfig) ValidateNetworkList(ctx context.Context, list *NetworkConfigList) ([]string, error) {
685 version := list.CNIVersion
686
687 // holding map for seen caps (in case of duplicates)
688 caps := map[string]interface{}{}
689
690 errs := []error{}
691 for _, net := range list.Plugins {
692 if err := c.validatePlugin(ctx, net.Network.Type, version); err != nil {
693 errs = append(errs, err)
694 }
695 for c, enabled := range net.Network.Capabilities {
696 if !enabled {
697 continue
698 }
699 caps[c] = struct{}{}
700 }
701 }
702
703 if len(errs) > 0 {
704 return nil, fmt.Errorf("%v", errs)
705 }
706
707 // make caps list
708 cc := make([]string, 0, len(caps))
709 for c := range caps {
710 cc = append(cc, c)
711 }
712
713 return cc, nil
714 }
715
716 // ValidateNetwork checks that a configuration is reasonably valid.
717 // It uses the same logic as ValidateNetworkList)
718 // Returns a list of capabilities
719 func (c *CNIConfig) ValidateNetwork(ctx context.Context, net *PluginConfig) ([]string, error) {
720 caps := []string{}
721 for c, ok := range net.Network.Capabilities {
722 if ok {
723 caps = append(caps, c)
724 }
725 }
726 if err := c.validatePlugin(ctx, net.Network.Type, net.Network.CNIVersion); err != nil {
727 return nil, err
728 }
729 return caps, nil
730 }
731
732 // validatePlugin checks that an individual plugin's configuration is sane
733 func (c *CNIConfig) validatePlugin(ctx context.Context, pluginName, expectedVersion string) error {
734 c.ensureExec()
735 pluginPath, err := c.exec.FindInPath(pluginName, c.Path)
736 if err != nil {
737 return err
738 }
739 if expectedVersion == "" {
740 expectedVersion = "0.1.0"
741 }
742
743 vi, err := invoke.GetVersionInfo(ctx, pluginPath, c.exec)
744 if err != nil {
745 return err
746 }
747 for _, vers := range vi.SupportedVersions() {
748 if vers == expectedVersion {
749 return nil
750 }
751 }
752 return fmt.Errorf("plugin %s does not support config version %q", pluginName, expectedVersion)
753 }
754
755 // GetVersionInfo reports which versions of the CNI spec are supported by
756 // the given plugin.
757 func (c *CNIConfig) GetVersionInfo(ctx context.Context, pluginType string) (version.PluginInfo, error) {
758 c.ensureExec()
759 pluginPath, err := c.exec.FindInPath(pluginType, c.Path)
760 if err != nil {
761 return nil, err
762 }
763
764 return invoke.GetVersionInfo(ctx, pluginPath, c.exec)
765 }
766
767 // GCNetworkList will do two things
768 // - dump the list of cached attachments, and issue deletes as necessary
769 // - issue a GC to the underlying plugins (if the version is high enough)
770 func (c *CNIConfig) GCNetworkList(ctx context.Context, list *NetworkConfigList, args *GCArgs) error {
771 // If DisableGC is set, then don't bother GCing at all.
772 if list.DisableGC {
773 return nil
774 }
775
776 // First, get the list of cached attachments
777 cachedAttachments, err := c.GetCachedAttachments("")
778 if err != nil {
779 return nil
780 }
781
782 var validAttachments map[types.GCAttachment]interface{}
783 if args != nil {
784 validAttachments = make(map[types.GCAttachment]interface{}, len(args.ValidAttachments))
785 for _, a := range args.ValidAttachments {
786 validAttachments[a] = nil
787 }
788 }
789
790 var errs []error
791
792 for _, cachedAttachment := range cachedAttachments {
793 if cachedAttachment.Network != list.Name {
794 continue
795 }
796 // we found this attachment
797 gca := types.GCAttachment{
798 ContainerID: cachedAttachment.ContainerID,
799 IfName: cachedAttachment.IfName,
800 }
801 if _, ok := validAttachments[gca]; ok {
802 continue
803 }
804 // otherwise, this attachment wasn't valid and we should issue a CNI DEL
805 rt := RuntimeConf{
806 ContainerID: cachedAttachment.ContainerID,
807 NetNS: cachedAttachment.NetNS,
808 IfName: cachedAttachment.IfName,
809 Args: cachedAttachment.CniArgs,
810 CapabilityArgs: cachedAttachment.CapabilityArgs,
811 }
812 if err := c.DelNetworkList(ctx, list, &rt); err != nil {
813 errs = append(errs, fmt.Errorf("failed to delete stale attachment %s %s: %w", rt.ContainerID, rt.IfName, err))
814 }
815 }
816
817 // now, if the version supports it, issue a GC
818 if gt, _ := version.GreaterThanOrEqualTo(list.CNIVersion, "1.1.0"); gt {
819 inject := map[string]interface{}{
820 "name": list.Name,
821 "cniVersion": list.CNIVersion,
822 }
823 if args != nil {
824 inject["cni.dev/valid-attachments"] = args.ValidAttachments
825 // #1101: spec used incorrect variable name
826 inject["cni.dev/attachments"] = args.ValidAttachments
827 }
828
829 for _, plugin := range list.Plugins {
830 // build config here
831 pluginConfig, err := InjectConf(plugin, inject)
832 if err != nil {
833 errs = append(errs, fmt.Errorf("failed to generate configuration to GC plugin %s: %w", plugin.Network.Type, err))
834 }
835 if err := c.gcNetwork(ctx, pluginConfig); err != nil {
836 errs = append(errs, fmt.Errorf("failed to GC plugin %s: %w", plugin.Network.Type, err))
837 }
838 }
839 }
840
841 return errors.Join(errs...)
842 }
843
844 func (c *CNIConfig) gcNetwork(ctx context.Context, net *PluginConfig) error {
845 c.ensureExec()
846 pluginPath, err := c.exec.FindInPath(net.Network.Type, c.Path)
847 if err != nil {
848 return err
849 }
850 args := c.args("GC", &RuntimeConf{})
851
852 return invoke.ExecPluginWithoutResult(ctx, pluginPath, net.Bytes, args, c.exec)
853 }
854
855 func (c *CNIConfig) GetStatusNetworkList(ctx context.Context, list *NetworkConfigList) error {
856 // If the version doesn't support status, abort.
857 if gt, _ := version.GreaterThanOrEqualTo(list.CNIVersion, "1.1.0"); !gt {
858 return nil
859 }
860
861 inject := map[string]interface{}{
862 "name": list.Name,
863 "cniVersion": list.CNIVersion,
864 }
865
866 for _, plugin := range list.Plugins {
867 // build config here
868 pluginConfig, err := InjectConf(plugin, inject)
869 if err != nil {
870 return fmt.Errorf("failed to generate configuration to get plugin STATUS %s: %w", plugin.Network.Type, err)
871 }
872 if err := c.getStatusNetwork(ctx, pluginConfig); err != nil {
873 return err // Don't collect errors here, so we return a clean error code.
874 }
875 }
876 return nil
877 }
878
879 func (c *CNIConfig) getStatusNetwork(ctx context.Context, net *PluginConfig) error {
880 c.ensureExec()
881 pluginPath, err := c.exec.FindInPath(net.Network.Type, c.Path)
882 if err != nil {
883 return err
884 }
885 args := c.args("STATUS", &RuntimeConf{})
886
887 return invoke.ExecPluginWithoutResult(ctx, pluginPath, net.Bytes, args, c.exec)
888 }
889
890 // =====
891 func (c *CNIConfig) args(action string, rt *RuntimeConf) *invoke.Args {
892 return &invoke.Args{
893 Command: action,
894 ContainerID: rt.ContainerID,
895 NetNS: rt.NetNS,
896 PluginArgs: rt.Args,
897 IfName: rt.IfName,
898 Path: strings.Join(c.Path, string(os.PathListSeparator)),
899 }
900 }