gvisor.dev/gvisor@v0.0.0-20240520182842-f9d4d51c7e0f/runsc/cmd/state.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 "encoding/json" 20 "os" 21 22 "github.com/google/subcommands" 23 "gvisor.dev/gvisor/pkg/log" 24 "gvisor.dev/gvisor/runsc/cmd/util" 25 "gvisor.dev/gvisor/runsc/config" 26 "gvisor.dev/gvisor/runsc/container" 27 "gvisor.dev/gvisor/runsc/flag" 28 ) 29 30 // State implements subcommands.Command for the "state" command. 31 type State struct{} 32 33 // Name implements subcommands.Command.Name. 34 func (*State) Name() string { 35 return "state" 36 } 37 38 // Synopsis implements subcommands.Command.Synopsis. 39 func (*State) Synopsis() string { 40 return "get the state of a container" 41 } 42 43 // Usage implements subcommands.Command.Usage. 44 func (*State) Usage() string { 45 return `state [flags] <container id> - get the state of a container` 46 } 47 48 // SetFlags implements subcommands.Command.SetFlags. 49 func (*State) SetFlags(*flag.FlagSet) {} 50 51 // Execute implements subcommands.Command.Execute. 52 func (*State) Execute(_ context.Context, f *flag.FlagSet, args ...any) subcommands.ExitStatus { 53 if f.NArg() != 1 { 54 f.Usage() 55 return subcommands.ExitUsageError 56 } 57 58 id := f.Arg(0) 59 conf := args[0].(*config.Config) 60 61 c, err := container.Load(conf.RootDir, container.FullID{ContainerID: id}, container.LoadOpts{}) 62 if err != nil { 63 util.Fatalf("loading container: %v", err) 64 } 65 66 state := c.State() 67 log.Debugf("Returning state for container %q: %+v", c.ID, state) 68 69 // Write json-encoded state directly to stdout. 70 encoder := json.NewEncoder(os.Stdout) 71 encoder.SetIndent("", " ") 72 if err := encoder.Encode(state); err != nil { 73 util.Fatalf("error marshaling container state: %v", err) 74 } 75 return subcommands.ExitSuccess 76 }