| 1 | + | package tty |
| 2 | + | |
| 3 | + | import ( |
| 4 | + | "context" |
| 5 | + | "os" |
| 6 | + | "os/signal" |
| 7 | + | "time" |
| 8 | + | |
| 9 | + | "github.com/docker/cli/cli/streams" |
| 10 | + | "github.com/docker/docker/api/types" |
| 11 | + | dockerclient "github.com/docker/docker/client" |
| 12 | + | mobysignal "github.com/moby/sys/signal" |
| 13 | + | "github.com/sirupsen/logrus" |
| 14 | + | ) |
| 15 | + | |
| 16 | + | func StartResizing( |
| 17 | + | ctx context.Context, |
| 18 | + | out *streams.Out, |
| 19 | + | client dockerclient.ContainerAPIClient, |
| 20 | + | contID string, |
| 21 | + | ) { |
| 22 | + | go func() { |
| 23 | + | for retry := 0; retry < 10; retry++ { |
| 24 | + | if err := resize(ctx, out, client, contID); err == nil { |
| 25 | + | return |
| 26 | + | } |
| 27 | + | time.Sleep(time.Duration(retry+1) * 10 * time.Millisecond) |
| 28 | + | } |
| 29 | + | logrus.Warn("Cannot resize TTY") |
| 30 | + | }() |
| 31 | + | |
| 32 | + | sigchan := make(chan os.Signal, 1) |
| 33 | + | signal.Notify(sigchan, mobysignal.SIGWINCH) |
| 34 | + | go func() { |
| 35 | + | for range sigchan { |
| 36 | + | resize(ctx, out, client, contID) |
| 37 | + | } |
| 38 | + | }() |
| 39 | + | } |
| 40 | + | |
| 41 | + | func resize( |
| 42 | + | ctx context.Context, |
| 43 | + | out *streams.Out, |
| 44 | + | client dockerclient.ContainerAPIClient, |
| 45 | + | contID string, |
| 46 | + | ) error { |
| 47 | + | height, width := out.GetTtySize() |
| 48 | + | if height == 0 && width == 0 { |
| 49 | + | return nil |
| 50 | + | } |
| 51 | + | |
| 52 | + | if err := client.ContainerResize(ctx, contID, types.ResizeOptions{Height: height, Width: width}); err != nil { |
| 53 | + | logrus.WithError(err).Debug("TTY resize error") |
| 54 | + | return err |
| 55 | + | } |
| 56 | + | |
| 57 | + | return nil |
| 58 | + | } |
| 59 | + | |