Attach attaches stdin, stdout, and stderr to a running container.
(ctx context.Context, client *containerd.Client, req string, options types.ContainerAttachOptions)
| 40 | |
| 41 | // Attach attaches stdin, stdout, and stderr to a running container. |
| 42 | func Attach(ctx context.Context, client *containerd.Client, req string, options types.ContainerAttachOptions) error { |
| 43 | // Find the container. |
| 44 | var container containerd.Container |
| 45 | var cStatus containerd.Status |
| 46 | |
| 47 | walker := &containerwalker.ContainerWalker{ |
| 48 | Client: client, |
| 49 | OnFound: func(ctx context.Context, found containerwalker.Found) error { |
| 50 | container = found.Container |
| 51 | return nil |
| 52 | }, |
| 53 | } |
| 54 | n, err := walker.Walk(ctx, req) |
| 55 | if err != nil { |
| 56 | return fmt.Errorf("error when trying to find the container: %w", err) |
| 57 | } |
| 58 | if n == 0 { |
| 59 | return fmt.Errorf("no container is found given the string: %s", req) |
| 60 | } else if n > 1 { |
| 61 | return fmt.Errorf("more than one containers are found given the string: %s", req) |
| 62 | } |
| 63 | |
| 64 | defer func() { |
| 65 | containerLabels, err := container.Labels(ctx) |
| 66 | if err != nil { |
| 67 | log.G(ctx).WithError(err).Errorf("failed to getting container labels: %s", err) |
| 68 | return |
| 69 | } |
| 70 | rm, err := containerutil.DecodeContainerRmOptLabel(containerLabels[labels.ContainerAutoRemove]) |
| 71 | if err != nil { |
| 72 | log.G(ctx).WithError(err).Errorf("failed to decode string to bool value: %s", err) |
| 73 | return |
| 74 | } |
| 75 | if rm && cStatus.Status == containerd.Stopped { |
| 76 | if err = RemoveContainer(ctx, container, options.GOptions, true, true, client); err != nil { |
| 77 | log.L.WithError(err).Warnf("failed to remove container %s: %s", req, err) |
| 78 | } |
| 79 | } |
| 80 | }() |
| 81 | |
| 82 | // Attach to the container. |
| 83 | var task containerd.Task |
| 84 | detachC := make(chan struct{}) |
| 85 | spec, err := container.Spec(ctx) |
| 86 | if err != nil { |
| 87 | return fmt.Errorf("failed to get the OCI runtime spec for the container: %w", err) |
| 88 | } |
| 89 | var ( |
| 90 | opt cio.Opt |
| 91 | con console.Console |
| 92 | ) |
| 93 | if spec.Process.Terminal { |
| 94 | con, err = consoleutil.Current() |
| 95 | if err != nil { |
| 96 | return err |
| 97 | } |
| 98 | defer con.Reset() |
| 99 |
no test coverage detected
searching dependent graphs…