Merge pull request #3288 from Ace-Tang/easy-shim

ctr: make ctr shim command easy to use
This commit is contained in:
Phil Estes 2019-05-17 15:40:39 +02:00 committed by GitHub
commit b99a66c267
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -23,9 +23,12 @@ import (
"fmt" "fmt"
"io/ioutil" "io/ioutil"
"net" "net"
"path/filepath"
"github.com/containerd/console" "github.com/containerd/console"
"github.com/containerd/containerd/cmd/ctr/commands" "github.com/containerd/containerd/cmd/ctr/commands"
"github.com/containerd/containerd/namespaces"
"github.com/containerd/containerd/runtime/v2/shim"
"github.com/containerd/containerd/runtime/v2/task" "github.com/containerd/containerd/runtime/v2/task"
"github.com/containerd/ttrpc" "github.com/containerd/ttrpc"
"github.com/containerd/typeurl" "github.com/containerd/typeurl"
@ -61,8 +64,8 @@ var Command = cli.Command{
Usage: "interact with a shim directly", Usage: "interact with a shim directly",
Flags: []cli.Flag{ Flags: []cli.Flag{
cli.StringFlag{ cli.StringFlag{
Name: "socket", Name: "id",
Usage: "socket on which to connect to the shim", Usage: "container id",
}, },
}, },
Subcommands: []cli.Command{ Subcommands: []cli.Command{
@ -116,7 +119,7 @@ var stateCommand = cli.Command{
return err return err
} }
r, err := service.State(gocontext.Background(), &task.StateRequest{ r, err := service.State(gocontext.Background(), &task.StateRequest{
ID: context.Args().First(), ID: context.GlobalString("id"),
}) })
if err != nil { if err != nil {
return err return err
@ -226,20 +229,30 @@ var execCommand = cli.Command{
} }
func getTaskService(context *cli.Context) (task.TaskService, error) { func getTaskService(context *cli.Context) (task.TaskService, error) {
bindSocket := context.GlobalString("socket") id := context.GlobalString("id")
if bindSocket == "" { if id == "" {
return nil, errors.New("socket path must be specified") return nil, fmt.Errorf("container id must be specified")
} }
ns := context.GlobalString("namespace")
conn, err := net.Dial("unix", "\x00"+bindSocket) // /containerd-shim/ns/id/shim.sock is the old way to generate shim socket,
if err != nil { // compatible it
return nil, err s1 := filepath.Join(string(filepath.Separator), "containerd-shim", ns, id, "shim.sock")
} // this should not error, ctr always get a default ns
ctx := namespaces.WithNamespace(gocontext.Background(), ns)
s2, _ := shim.SocketAddress(ctx, id)
for _, socket := range []string{s1, s2} {
conn, err := net.Dial("unix", "\x00"+socket)
if err == nil {
client := ttrpc.NewClient(conn) client := ttrpc.NewClient(conn)
// TODO(stevvooe): This actually leaks the connection. We were leaking it // TODO(stevvooe): This actually leaks the connection. We were leaking it
// before, so may not be a huge deal. // before, so may not be a huge deal.
return task.NewTaskClient(client), nil return task.NewTaskClient(client), nil
}
}
return nil, fmt.Errorf("fail to connect to container %s's shim", id)
} }