github.com/containerd/nerdctl@v1.7.7/pkg/containerinspector/containerinspector.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 containerinspector
    18  
    19  import (
    20  	"context"
    21  
    22  	"github.com/containerd/containerd"
    23  	"github.com/containerd/errdefs"
    24  	"github.com/containerd/log"
    25  	"github.com/containerd/nerdctl/pkg/inspecttypes/native"
    26  	"github.com/containerd/typeurl/v2"
    27  )
    28  
    29  func Inspect(ctx context.Context, container containerd.Container) (*native.Container, error) {
    30  	info, err := container.Info(ctx)
    31  	if err != nil {
    32  		return nil, err
    33  	}
    34  	n := &native.Container{
    35  		Container: info,
    36  	}
    37  	id := container.ID()
    38  
    39  	n.Spec, err = typeurl.UnmarshalAny(info.Spec)
    40  	if err != nil {
    41  		log.G(ctx).WithError(err).WithField("id", id).Warnf("failed to inspect Spec")
    42  		return n, nil
    43  	}
    44  	task, err := container.Task(ctx, nil)
    45  	if err != nil {
    46  		if !errdefs.IsNotFound(err) {
    47  			log.G(ctx).WithError(err).WithField("id", id).Warnf("failed to inspect Task")
    48  		}
    49  		return n, nil
    50  	}
    51  	n.Process = &native.Process{
    52  		Pid: int(task.Pid()),
    53  	}
    54  	st, err := task.Status(ctx)
    55  	if err != nil {
    56  		log.G(ctx).WithError(err).WithField("id", id).Warnf("failed to inspect Status")
    57  		return n, nil
    58  	}
    59  	n.Process.Status = st
    60  	netNS, err := InspectNetNS(ctx, n.Process.Pid)
    61  	if err != nil {
    62  		log.G(ctx).WithError(err).WithField("id", id).Warnf("failed to inspect NetNS")
    63  		return n, nil
    64  	}
    65  	n.Process.NetNS = netNS
    66  	return n, nil
    67  }