dockerexec

package module
v0.1.5 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 17, 2023 License: BSD-3-Clause Imports: 14 Imported by: 0

README

dockerexec

Go Reference

An "os/exec" like interface for running a command in a container, and being able to easily interact with stdin, stdout, and other adjustments.

Usage

$ go get github.com/segevfiner/dockerexec

Example:

package main

import (
    "fmt"

    "github.com/docker/docker/client"
    "github.com/segevfiner/dockerexec"
)

func main() {
    // You might want to use client.WithVersion in production
    dockerClient, err := client.NewClientWithOpts(client.WithAPIVersionNegotiation(), client.FromEnv)
    if err != nil {
        panic(err)
    }

    cmd := dockerexec.Command(dockerClient, "ubuntu:focal", "sh", "-c", "echo Hello, World!")
    output, err := cmd.Output()
    if err != nil {
        panic(err)
    }

    fmt.Printf("%s", output)
}

License

BSD-3-Clause.

Documentation

Overview

Package dockerexec runs a command in a container. It wraps the Docker API to make it easier to remap stdin and stdout, connect I/O with pipes, and do other adjustments.

Essentially an "os/exec" like interface for running a command in a container.

Example
package main

import (
	"fmt"

	"github.com/docker/docker/client"
	"github.com/segevfiner/dockerexec"
)

func main() {
	// You might want to use client.WithVersion in production
	dockerClient, err := client.NewClientWithOpts(client.WithAPIVersionNegotiation(), client.FromEnv)
	if err != nil {
		panic(err)
	}

	cmd := dockerexec.Command(dockerClient, "ubuntu:focal", "sh", "-c", "echo Hello, World!")
	output, err := cmd.Output()
	if err != nil {
		panic(err)
	}

	fmt.Printf("%s", output)
}
Output:

Hello, World!

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Cmd

type Cmd struct {
	// The configuration of the container to be ran.
	//
	// Some properties are handled specially:
	//     * HostConfig.AutoRemove default to true.
	//	   * Config.StdinOnce defaults to true, and you should be careful unsetting it (https://github.com/moby/moby/issues/38457).
	//	   * Config.OpenStdin will be set automatically as needed.
	Config           *container.Config
	HostConfig       *container.HostConfig
	Networkingconfig *network.NetworkingConfig
	Platform         *specs.Platform
	ContainerName    string

	// Stdin specifies the container's standard input.
	//
	// If Stdin is nil, the container will receive no input.
	//
	// During the execution of the container a separate goroutine reads from Stdin and
	// delivers that data to the container. In this case, Wait does not complete until the goroutine
	// stops copying, either because it has reached the end of Stdin (EOF or a read error) or
	// because writing to the container.
	Stdin io.Reader

	// Stdout and Stderr specify the container's standard output and error.
	//
	// If either is nil, the corresponding output will be discarded.
	//
	// While using Config.Tty, only a single stream of output is available in Stdout. Setting Stderr
	// will panic.
	//
	// During the execution of the container a separate goroutine reads from the container and
	// delivers that data to the corresponding Writer. In this case, Wait does not complete until
	// the goroutine reaches EOF or encounters an error.
	Stdout io.Writer
	Stderr io.Writer

	// ContainerID is the ID of the container, once started.
	ContainerID string

	// Warnings contains any warnings from creating the container.
	//
	// You should consider logging these.
	Warnings []string

	// StatusCode contains the status code of the container, available after a call to Wait or Run.
	StatusCode int64
	// contains filtered or unexported fields
}

Cmd represents a container being prepared or run.

A Cmd cannot be reused after calling its Run, Output or CombinedOutput methods.

func Command

func Command(cli client.APIClient, image string, name string, arg ...string) *Cmd

Command returns the Cmd struct to execute the named program inside the given image with the given arguments.

func CommandContext

func CommandContext(ctx context.Context, cli client.APIClient, image string, name string, arg ...string) *Cmd

CommandContext is like Command but includes a context.

The provided context is used to kill the container (by calling ContainerKill) if the context becomes done before the container completes on its own.

func (*Cmd) CombinedOutput

func (c *Cmd) CombinedOutput() ([]byte, error)

CombinedOutput runs the container and returns its combined standard output and standard error.

func (*Cmd) Output

func (c *Cmd) Output() ([]byte, error)

Output runs the container and returns its standard output. Any returned error will usually be of type *ExitError. If c.Stderr was nil, Output populates ExitError.Stderr.

func (*Cmd) Run

func (c *Cmd) Run() error

Run starts the specified container and waits for it to complete.

The returned error is nil if the container runs, has no problems copying stdin, stdout, and stderr, and exits with a zero exit status.

If the container starts but does not complete successfully, the error is of type *ExitError. Other error types may be returned for other situations.

func (*Cmd) Start

func (c *Cmd) Start() error

Start starts the specified container but does not wait for it to complete.

If Start returns successfully, the c.ContainerID field will be set.

The Wait method will return the exit code and release associated resources once the container exits.

func (*Cmd) StderrPipe

func (c *Cmd) StderrPipe() (io.ReadCloser, error)

StderrPipe returns a pipe that will be connected to the container's standard error when the container starts.

Wait will close the pipe after seeing the container exit, so most callers need not close the pipe themselves. It is thus incorrect to call Wait before all reads from the pipe have completed. For the same reason, it is incorrect to use Run when using StderrPipe. See the StdoutPipe example for idiomatic usage.

func (*Cmd) StdinPipe

func (c *Cmd) StdinPipe() (io.WriteCloser, error)

StdinPipe returns a pipe that will be connected to the container's standard input when the container starts. The pipe will be closed automatically after Wait sees the container exit. A caller need only call Close to force the pipe to close sooner. For example, if the container being run will not exit until standard input is closed, the caller must close the pipe.

func (*Cmd) StdoutPipe

func (c *Cmd) StdoutPipe() (io.ReadCloser, error)

StdoutPipe returns a pipe that will be connected to the container's standard output when the container starts.

Wait will close the pipe after seeing the container exit, so most callers need not close the pipe themselves. It is thus incorrect to call Wait before all reads from the pipe have completed. For the same reason, it is incorrect to call Run when using StdoutPipe. See the example for idiomatic usage.

func (*Cmd) String

func (c *Cmd) String() string

String returns a human-readable description of c. It is intended only for debugging.

func (*Cmd) Wait

func (c *Cmd) Wait() error

Wait waits for the container to exit and waits for any copying to stdin or copying from stdout or stderr to complete.

The container must have been started by Start.

The returned error is nil if the container runs, has no problems copying stdin, stdout, and stderr, and exits with a zero exit status.

If the container fails to run or doesn't complete successfully, the error is of type *ExitError. Other error types may be returned for I/O problems.

Wait also waits for the respective I/O loop copying to or from the container to complete.

Wait releases any resources associated with the Cmd.

type ExitError

type ExitError struct {
	StatusCode int64

	// Stderr holds a subset of the standard error output from the
	// Cmd.Output method if standard error was not otherwise being
	// collected.
	//
	// If the error output is long, Stderr may contain only a prefix
	// and suffix of the output, with the middle replaced with
	// text about the number of omitted bytes.
	//
	// Stderr is provided for debugging, for inclusion in error messages.
	// Users with other needs should redirect Cmd.Stderr as needed.
	Stderr []byte
}

An ExitError reports an unsuccessful exit by a container.

func (*ExitError) Error

func (e *ExitError) Error() string

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL