github.com/lalkh/containerd@v1.4.3/cmd/ctr/commands/tasks/attach.go (about) 1 /* 2 Copyright The containerd Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package tasks 18 19 import ( 20 "github.com/containerd/console" 21 "github.com/containerd/containerd/cio" 22 "github.com/containerd/containerd/cmd/ctr/commands" 23 "github.com/sirupsen/logrus" 24 "github.com/urfave/cli" 25 ) 26 27 var attachCommand = cli.Command{ 28 Name: "attach", 29 Usage: "attach to the IO of a running container", 30 ArgsUsage: "CONTAINER", 31 Action: func(context *cli.Context) error { 32 client, ctx, cancel, err := commands.NewClient(context) 33 if err != nil { 34 return err 35 } 36 defer cancel() 37 container, err := client.LoadContainer(ctx, context.Args().First()) 38 if err != nil { 39 return err 40 } 41 spec, err := container.Spec(ctx) 42 if err != nil { 43 return err 44 } 45 var ( 46 con console.Console 47 tty = spec.Process.Terminal 48 ) 49 if tty { 50 con = console.Current() 51 defer con.Reset() 52 if err := con.SetRaw(); err != nil { 53 return err 54 } 55 } 56 task, err := container.Task(ctx, cio.NewAttach(cio.WithStdio)) 57 if err != nil { 58 return err 59 } 60 defer task.Delete(ctx) 61 62 statusC, err := task.Wait(ctx) 63 if err != nil { 64 return err 65 } 66 67 if tty { 68 if err := HandleConsoleResize(ctx, task, con); err != nil { 69 logrus.WithError(err).Error("console resize") 70 } 71 } else { 72 sigc := commands.ForwardAllSignals(ctx, task) 73 defer commands.StopCatch(sigc) 74 } 75 76 ec := <-statusC 77 code, _, err := ec.Result() 78 if err != nil { 79 return err 80 } 81 if code != 0 { 82 return cli.NewExitError("", int(code)) 83 } 84 return nil 85 }, 86 }