github.com/containerd/containerd@v22.0.0-20200918172823-438c87b8e050+incompatible/cmd/ctr/commands/tasks/ps.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 tasks
    18  
    19  import (
    20  	"fmt"
    21  	"os"
    22  	"text/tabwriter"
    23  
    24  	"github.com/containerd/containerd/cmd/ctr/commands"
    25  	"github.com/containerd/typeurl"
    26  	"github.com/pkg/errors"
    27  	"github.com/urfave/cli"
    28  )
    29  
    30  var psCommand = cli.Command{
    31  	Name:      "ps",
    32  	Usage:     "list processes for container",
    33  	ArgsUsage: "CONTAINER",
    34  	Action: func(context *cli.Context) error {
    35  		id := context.Args().First()
    36  		if id == "" {
    37  			return errors.New("container id must be provided")
    38  		}
    39  		client, ctx, cancel, err := commands.NewClient(context)
    40  		if err != nil {
    41  			return err
    42  		}
    43  		defer cancel()
    44  		container, err := client.LoadContainer(ctx, id)
    45  		if err != nil {
    46  			return err
    47  		}
    48  		task, err := container.Task(ctx, nil)
    49  		if err != nil {
    50  			return err
    51  		}
    52  		processes, err := task.Pids(ctx)
    53  		if err != nil {
    54  			return err
    55  		}
    56  		w := tabwriter.NewWriter(os.Stdout, 1, 8, 4, ' ', 0)
    57  		fmt.Fprintln(w, "PID\tINFO")
    58  		for _, ps := range processes {
    59  			var info interface{} = "-"
    60  			if ps.Info != nil {
    61  				info, err = typeurl.UnmarshalAny(ps.Info)
    62  				if err != nil {
    63  					return err
    64  				}
    65  			}
    66  			if _, err := fmt.Fprintf(w, "%d\t%+v\n", ps.Pid, info); err != nil {
    67  				return err
    68  			}
    69  		}
    70  		return w.Flush()
    71  	},
    72  }