github.com/containerd/nerdctl/v2@v2.0.0-beta.5.0.20240520001846-b5758f54fa28/pkg/cmd/network/inspect.go (about) 1 /* 2 Copyright The containerd Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package network 18 19 import ( 20 "context" 21 "encoding/json" 22 "fmt" 23 24 "github.com/containerd/log" 25 "github.com/containerd/nerdctl/v2/pkg/api/types" 26 "github.com/containerd/nerdctl/v2/pkg/formatter" 27 "github.com/containerd/nerdctl/v2/pkg/idutil/netwalker" 28 "github.com/containerd/nerdctl/v2/pkg/inspecttypes/dockercompat" 29 "github.com/containerd/nerdctl/v2/pkg/inspecttypes/native" 30 "github.com/containerd/nerdctl/v2/pkg/netutil" 31 ) 32 33 func Inspect(ctx context.Context, options types.NetworkInspectOptions) error { 34 globalOptions := options.GOptions 35 e, err := netutil.NewCNIEnv(globalOptions.CNIPath, globalOptions.CNINetConfPath) 36 37 if err != nil { 38 return err 39 } 40 if options.Mode != "native" && options.Mode != "dockercompat" { 41 return fmt.Errorf("unknown mode %q", options.Mode) 42 } 43 44 var result []interface{} 45 walker := netwalker.NetworkWalker{ 46 Client: e, 47 OnFound: func(ctx context.Context, found netwalker.Found) error { 48 if found.MatchCount > 1 { 49 return fmt.Errorf("multiple IDs found with provided prefix: %s", found.Req) 50 } 51 r := &native.Network{ 52 CNI: json.RawMessage(found.Network.Bytes), 53 NerdctlID: found.Network.NerdctlID, 54 NerdctlLabels: found.Network.NerdctlLabels, 55 File: found.Network.File, 56 } 57 switch options.Mode { 58 case "native": 59 result = append(result, r) 60 case "dockercompat": 61 compat, err := dockercompat.NetworkFromNative(r) 62 if err != nil { 63 return err 64 } 65 result = append(result, compat) 66 } 67 return nil 68 }, 69 } 70 71 // `network inspect` doesn't support pseudo network. 72 err = walker.WalkAll(ctx, options.Networks, true, false) 73 if len(result) > 0 { 74 if formatErr := formatter.FormatSlice(options.Format, options.Stdout, result); formatErr != nil { 75 log.G(ctx).Error(formatErr) 76 } 77 } 78 return err 79 }