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