github.com/ttpreport/gvisor-ligolo@v0.0.0-20240123134145-a858404967ba/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 "github.com/ttpreport/gvisor-ligolo/pkg/log" 24 "github.com/ttpreport/gvisor-ligolo/runsc/cmd/util" 25 "github.com/ttpreport/gvisor-ligolo/runsc/config" 26 "github.com/ttpreport/gvisor-ligolo/runsc/container" 27 "github.com/ttpreport/gvisor-ligolo/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 log.Debugf("Returning state for container %+v", c) 66 67 state := c.State() 68 log.Debugf("State: %+v", state) 69 70 // Write json-encoded state directly to stdout. 71 b, err := json.MarshalIndent(state, "", " ") 72 if err != nil { 73 util.Fatalf("marshaling container state: %v", err) 74 } 75 if _, err := os.Stdout.Write(b); err != nil { 76 util.Fatalf("Error writing to stdout: %v", err) 77 } 78 return subcommands.ExitSuccess 79 }