github.com/SagerNet/gvisor@v0.0.0-20210707092255-7731c139d75c/runsc/cmd/ps.go (about) 1 // Copyright 2018 The gVisor Authors. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package cmd 16 17 import ( 18 "context" 19 "fmt" 20 21 "github.com/google/subcommands" 22 "github.com/SagerNet/gvisor/pkg/sentry/control" 23 "github.com/SagerNet/gvisor/runsc/config" 24 "github.com/SagerNet/gvisor/runsc/container" 25 "github.com/SagerNet/gvisor/runsc/flag" 26 ) 27 28 // PS implements subcommands.Command for the "ps" command. 29 type PS struct { 30 format string 31 } 32 33 // Name implements subcommands.Command.Name. 34 func (*PS) Name() string { 35 return "ps" 36 } 37 38 // Synopsis implements subcommands.Command.Synopsis. 39 func (*PS) Synopsis() string { 40 return "ps displays the processes running inside a container" 41 } 42 43 // Usage implements subcommands.Command.Usage. 44 func (*PS) Usage() string { 45 return "<container-id> [ps options]" 46 } 47 48 // SetFlags implements subcommands.Command.SetFlags. 49 func (ps *PS) SetFlags(f *flag.FlagSet) { 50 f.StringVar(&ps.format, "format", "table", "output format. Select one of: table or json (default: table)") 51 } 52 53 // Execute implements subcommands.Command.Execute. 54 func (ps *PS) Execute(ctx context.Context, f *flag.FlagSet, args ...interface{}) subcommands.ExitStatus { 55 if f.NArg() != 1 { 56 f.Usage() 57 return subcommands.ExitUsageError 58 } 59 60 id := f.Arg(0) 61 conf := args[0].(*config.Config) 62 63 c, err := container.Load(conf.RootDir, container.FullID{ContainerID: id}, container.LoadOpts{}) 64 if err != nil { 65 Fatalf("loading sandbox: %v", err) 66 } 67 pList, err := c.Processes() 68 if err != nil { 69 Fatalf("getting processes for container: %v", err) 70 } 71 72 switch ps.format { 73 case "table": 74 fmt.Println(control.ProcessListToTable(pList)) 75 case "json": 76 o, err := control.PrintPIDsJSON(pList) 77 if err != nil { 78 Fatalf("generating JSON: %v", err) 79 } 80 fmt.Println(o) 81 default: 82 Fatalf("unsupported format: %s", ps.format) 83 } 84 85 return subcommands.ExitSuccess 86 }