containers

package
v1.1.10 Latest Latest
Warning

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

Go to latest
Published: Mar 8, 2026 License: BSD-3-Clause Imports: 14 Imported by: 0

README

taubyte/go-simple-container

Release License Go Report Card GoDoc Discord

An abstraction layer over the docker api client. Goal: make it simple to use containers from go.

Installation

The import path for the package is github.com/taubyte/tau/pkg/containers.

To install it, run:

go get github.com/taubyte/tau/pkg/containers

Usage

Basic Example
import (
    ci "github.com/taubyte/tau/pkg/containers"
    "context"
)

ctx := context.Background()

// Create an new client
client, err := ci.New()
if err != nil{
    return err
}

// Using `node` image for our container
dockerImage := "node"

// Initialize docker image with our given image name
image, err := client.Image(ctx, dockerImage)
if err != nil{
    return err
}

// Commands we will be running
commands := []string{"echo","Hello World!"}

// Mount Volume Option 
volume := ci.Volume("/sourcePath","/containerPath")

// Add Environment Variable Option
variable := ci.Variable("KEY","value")

// Instantiate the container with commands we will run
container, err := image.Instantiate(
    ctx,
    ci.Command(commands),
    // options
    volume, 
    variable
)
if err != nil{
    return err
}

// Run container 
logs, err := container.Run(ctx)
if err != nil{
    return err
}

// Create new byte buffer 
var buf bytes.Buffer

// Read logs 
buf.ReadFrom(logs.Combined())

// Set output to the string value of the buffer 
output := buf.String()

// Close the log Reader
logs.Close()

Using Your Own Dockerfile
  • Create a Dockerfile in a directory with any dependencies that you may need for the Dockerfile, the file must be named Dockerfile. This is case sensitive.

  • run: $ tar cvf <docker_tarball_name>.tar -C <directory>/ .

  • Docker expects Dockerfile and any files you need to build the container image inside a tar file.

    • Using embed:
    //go:embed <docker_tarball_name>.tar
    var tarballData []byte 
    
    imageOption := containers.Build(bytes.NewBuffer(tarballData))
    
    • Using a file:
    tarball, err := os.Open("<path_to>/<docker_tarball_name.tar>")
    if err != nil{
        return err
    }
    defer tarball.Close()
    
    imageOption := containers.Build(tarball)
    
  • Create the image with a custom image name, and the the ImageOption

    • The image name must follow the convention <Organization>/<Repo_Name>:Version
    • All characters must be lower case
client.Image(context.Background(),"taubyte/testrepo:version1",imageOption)
Creating a Garbage Collector
import ( 
    "github.com/taubyte/tau/pkg/containers/gc"
    ci "github.com/taubyte/tau/pkg/containers" 
)

// Create new docker client 
client, err := ci.New()
if err != nil{
    return err
}

// Create a context with cancel func, calling the cancel func will end the garbage collector go routine.
ctx, ctxC := context.WithCancel(context.Background())

// Create new garbage collector
gc.New(ctx, gc.Interval(20 * time.Second), gc.MaxAge(10 *time.Second ))

Running Tests

If running tests for the first time, from directory run:

cd tests 
go generate

Then run

$ go test -v

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrorImageOptions         = errors.New("image options failed")
	ErrorImageBuild           = errors.New("building image failed")
	ErrorImagePull            = errors.New("pulling image failed")
	ErrorClientPull           = errors.New("client pull failed")
	ErrorImageBuildDockerFile = errors.New("building Dockerfile failed")
	ErrorContainerOptions     = errors.New("container options failed")
	ErrorContainerCreate      = errors.New("creating container failed")
	ErrorContainerStart       = errors.New("start container failed")
	ErrorContainerWait        = errors.New("container wait failed")
	ErrorContainerInspect     = errors.New("inspecting container failed")
	ErrorExitCode             = errors.New("exit-code")
	ErrorContainerLogs        = errors.New("getting container logs failed")
	ErrBackendNotAvailable    = errors.New("backend not available on this platform")
)
View Source
var (
	ForceRebuild = false
)

Functions

func AvailableBackends added in v1.1.10

func AvailableBackends() []core.BackendType

AvailableBackends returns all registered backends

func NewBackend added in v1.1.10

func NewBackend(config core.BackendConfig) (core.Backend, error)

NewBackend creates a backend instance using the registered factory from core

func NewFilter

func NewFilter(key, value string) filters.Args

New Filter returns a filter argument to perform key value Lookups on docker host.

Types

type BuildStatus

type BuildStatus struct {
	Stream      string `json:"stream"`
	Error       string `json:"error"`
	ErrorDetail struct {
		Message string `json:"message"`
	} `json:"errorDetail"`
}

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client wraps the methods of the docker Client. It now uses a Backend internally for container operations.

func New

func New(options ...Option) (dockerClient *Client, err error)

New creates a new dockerClient with default Options. Backend is initialized immediately (Docker first, fallback to containerd).

func (*Client) Clean

func (c *Client) Clean(ctx context.Context, age time.Duration, filter filters.Args) error

Clean removes images older than age that match the given filter. Implemented for the Docker backend; other backends return an error.

func (*Client) Close added in v1.1.10

func (c *Client) Close() error

Close is a no-op for backward compatibility. The backend handles its own lifecycle and doesn't need explicit closing.

func (*Client) Image

func (c *Client) Image(ctx context.Context, name string, options ...ImageOption) (image *DockerImage, err error)

Image initializes the given image. It tries to pull from the registry first to get the latest; if pull fails and the image exists locally, that image is used. If the Build() Option is provided then the given DockerFile tarball is built and returned.

type Container

type Container struct {
	// contains filtered or unexported fields
}

Container wraps the methods of the docker container. It now uses a Backend internally for container operations.

func (*Container) Cleanup

func (c *Container) Cleanup(ctx context.Context) error

Cleanup removes the container from the docker host client.

func (*Container) Run

func (c *Container) Run(ctx context.Context) (*MuxedReadCloser, error)

Run starts the container and waits for the container to exit before returning the container logs. Logs are returned even when the container exits with a non-zero status so callers can inspect build output (e.g. compiler errors).

func (*Container) Wait

func (c *Container) Wait(ctx context.Context) error

Wait calls the ContainerWait method for the container, and returns once a response has been received. If there is an error response then wait will return the error

type ContainerOption

type ContainerOption func(*Container) error

ContainerOption is a function to set configuration to the Container object.

func Command

func Command(cmd []string) ContainerOption

Command sets the commands to be run by the container after being built.

func Shell

func Shell(cmd []string) ContainerOption

Shell sets the shell-form of RUN, CMD, ENTRYPOINT

func Variable

func Variable(key, value string) ContainerOption

Variable sets an environment variable in the container.

func Variables

func Variables(vars map[string]string) ContainerOption

Variables sets multiple environment variables in the container.

func Volume

func Volume(sourcePath, containerPath string) ContainerOption

Volume sets local directories to be volumed in the container.

func WorkDir

func WorkDir(workDir string) ContainerOption

WorkDir sets the working directory of the container, where calls will be made.

type DockerImage added in v1.1.10

type DockerImage struct {
	// contains filtered or unexported fields
}

DockerImage wraps the methods of the docker image. It now uses a Backend internally for image operations.

func (*DockerImage) Exists added in v1.1.10

func (i *DockerImage) Exists(ctx context.Context) bool

Exists checks if the image exists locally without pulling

func (*DockerImage) Instantiate added in v1.1.10

func (i *DockerImage) Instantiate(ctx context.Context, options ...ContainerOption) (*Container, error)

Instantiate sets given options and creates the container from the docker image.

func (*DockerImage) Name added in v1.1.10

func (i *DockerImage) Name() string

Name returns the name of the image

func (*DockerImage) Pull added in v1.1.10

func (i *DockerImage) Pull(ctx context.Context, statusChan chan<- PullStatus) (*DockerImage, error)

Pull retrieves latest changes to the image from docker hub.

type ImageOption

type ImageOption func(*DockerImage) error

ImageOption is a function to set configuration to the Image object.

func Build

func Build(tarball io.Reader) ImageOption

Build returns an ImageOption to build a tarball of a Dockerfile

func Dockerfile

func Dockerfile(dockerfile string) ImageOption

func Output

func Output(output io.Writer) ImageOption

type MuxedReadCloser

type MuxedReadCloser struct {
	// contains filtered or unexported fields
}

MuxedReadCloser wraps the Read/Close methods for muxed logs.

func (*MuxedReadCloser) Close

func (mx *MuxedReadCloser) Close() error

func (*MuxedReadCloser) Combined

func (mx *MuxedReadCloser) Combined() io.ReadCloser

Combined returns the Stderr, and Stdout combined container logs.

func (*MuxedReadCloser) Separated

func (mx *MuxedReadCloser) Separated() (stdOut io.ReadCloser, stdErr io.ReadCloser)

Separated returns both the standard Out and Error logs of the container.

type Option

type Option func(*Client) error

func Verbose

func Verbose() Option

do not show progress output

type PullStatus

type PullStatus struct {
	Status         string `json:"status"`
	ProgressDetail struct {
		Current int `json:"current"`
		Total   int `json:"total"`
	} `json:"progressDetail"`
	Id          string `json:"id"`
	Error       string `json:"error"`
	ErrorDetail struct {
		Message string `json:"message"`
	} `json:"errorDetail"`
}

Directories

Path Synopsis
backends
containerd
Package containerd provides a containerd backend implementation for container operations.
Package containerd provides a containerd backend implementation for container operations.
docker
Package docker provides a Docker backend implementation for container operations.
Package docker provides a Docker backend implementation for container operations.
Package core provides core interfaces and types for container backends This package is separate from the main containers package to avoid import cycles
Package core provides core interfaces and types for container backends This package is separate from the main containers package to avoid import cycles

Jump to

Keyboard shortcuts

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