github.com/containerd/nerdctl@v1.7.7/cmd/nerdctl/container_wait.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 main
    18  
    19  import (
    20  	"github.com/containerd/containerd"
    21  	"github.com/containerd/nerdctl/pkg/api/types"
    22  	"github.com/containerd/nerdctl/pkg/clientutil"
    23  	"github.com/containerd/nerdctl/pkg/cmd/container"
    24  	"github.com/spf13/cobra"
    25  )
    26  
    27  func newWaitCommand() *cobra.Command {
    28  	var waitCommand = &cobra.Command{
    29  		Use:               "wait [flags] CONTAINER [CONTAINER, ...]",
    30  		Args:              cobra.MinimumNArgs(1),
    31  		Short:             "Block until one or more containers stop, then print their exit codes.",
    32  		RunE:              containerWaitAction,
    33  		ValidArgsFunction: waitShellComplete,
    34  		SilenceUsage:      true,
    35  		SilenceErrors:     true,
    36  	}
    37  	return waitCommand
    38  }
    39  
    40  func processContainerWaitOptions(cmd *cobra.Command) (types.ContainerWaitOptions, error) {
    41  	globalOptions, err := processRootCmdFlags(cmd)
    42  	if err != nil {
    43  		return types.ContainerWaitOptions{}, err
    44  	}
    45  	return types.ContainerWaitOptions{
    46  		Stdout:   cmd.OutOrStdout(),
    47  		GOptions: globalOptions,
    48  	}, nil
    49  }
    50  
    51  func containerWaitAction(cmd *cobra.Command, args []string) error {
    52  	options, err := processContainerWaitOptions(cmd)
    53  	if err != nil {
    54  		return err
    55  	}
    56  
    57  	client, ctx, cancel, err := clientutil.NewClient(cmd.Context(), options.GOptions.Namespace, options.GOptions.Address)
    58  	if err != nil {
    59  		return err
    60  	}
    61  	defer cancel()
    62  
    63  	return container.Wait(ctx, client, args, options)
    64  }
    65  
    66  func waitShellComplete(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
    67  	// show running container names
    68  	statusFilterFn := func(st containerd.ProcessStatus) bool {
    69  		return st == containerd.Running
    70  	}
    71  	return shellCompleteContainerNames(cmd, statusFilterFn)
    72  }