RunTask is a utility function for running a task and returning the result.
(ctx context.Context, c containerd.Container)
| 31 | |
| 32 | // RunTask is a utility function for running a task and returning the result. |
| 33 | func RunTask(ctx context.Context, c containerd.Container) (*CommandResult, error) { |
| 34 | var stdout bytes.Buffer |
| 35 | var stderr bytes.Buffer |
| 36 | |
| 37 | task, err := c.NewTask(ctx, cio.NewCreator(cio.WithStreams(nil, &stdout, &stderr))) |
| 38 | if err != nil { |
| 39 | return nil, err |
| 40 | } |
| 41 | |
| 42 | exitCh, err := task.Wait(ctx) |
| 43 | if err != nil { |
| 44 | return nil, err |
| 45 | } |
| 46 | |
| 47 | err = task.Start(ctx) |
| 48 | if err != nil { |
| 49 | return nil, err |
| 50 | } |
| 51 | |
| 52 | select { |
| 53 | case exitStatus := <-exitCh: |
| 54 | if err := exitStatus.Error(); err != nil { |
| 55 | return nil, err |
| 56 | } |
| 57 | |
| 58 | _, err := task.Delete(ctx) |
| 59 | if err != nil { |
| 60 | return nil, err |
| 61 | } |
| 62 | |
| 63 | return &CommandResult{ |
| 64 | Stdout: stdout.String(), |
| 65 | Stderr: stderr.String(), |
| 66 | ExitCode: exitStatus.ExitCode(), |
| 67 | }, nil |
| 68 | case <-ctx.Done(): |
| 69 | return nil, ctx.Err() |
| 70 | } |
| 71 | } |