github.com/containerd/nerdctl@v1.7.7/pkg/cmd/container/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 container
    18  
    19  import (
    20  	"context"
    21  	"fmt"
    22  	"time"
    23  
    24  	"github.com/containerd/containerd"
    25  	"github.com/containerd/log"
    26  	"github.com/containerd/nerdctl/pkg/api/types"
    27  	"github.com/containerd/nerdctl/pkg/containerinspector"
    28  	"github.com/containerd/nerdctl/pkg/formatter"
    29  	"github.com/containerd/nerdctl/pkg/idutil/containerwalker"
    30  	"github.com/containerd/nerdctl/pkg/inspecttypes/dockercompat"
    31  )
    32  
    33  // Inspect prints detailed information for each container in `containers`.
    34  func Inspect(ctx context.Context, client *containerd.Client, containers []string, options types.ContainerInspectOptions) error {
    35  	f := &containerInspector{
    36  		mode: options.Mode,
    37  	}
    38  
    39  	walker := &containerwalker.ContainerWalker{
    40  		Client:  client,
    41  		OnFound: f.Handler,
    42  	}
    43  
    44  	err := walker.WalkAll(ctx, containers, true)
    45  	if len(f.entries) > 0 {
    46  		if formatErr := formatter.FormatSlice(options.Format, options.Stdout, f.entries); formatErr != nil {
    47  			log.L.Error(formatErr)
    48  		}
    49  	}
    50  	return err
    51  }
    52  
    53  type containerInspector struct {
    54  	mode    string
    55  	entries []interface{}
    56  }
    57  
    58  func (x *containerInspector) Handler(ctx context.Context, found containerwalker.Found) error {
    59  	ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
    60  	defer cancel()
    61  
    62  	n, err := containerinspector.Inspect(ctx, found.Container)
    63  	if err != nil {
    64  		return err
    65  	}
    66  	switch x.mode {
    67  	case "native":
    68  		x.entries = append(x.entries, n)
    69  	case "dockercompat":
    70  		d, err := dockercompat.ContainerFromNative(n)
    71  		if err != nil {
    72  			return err
    73  		}
    74  		x.entries = append(x.entries, d)
    75  	default:
    76  		return fmt.Errorf("unknown mode %q", x.mode)
    77  	}
    78  	return nil
    79  }