containers

package module
v0.4.5 Latest Latest
Warning

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

Go to latest
Published: Feb 28, 2024 License: MIT Imports: 14 Imported by: 6

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/go-simple-container.

To install it, run:

go get github.com/taubyte/go-simple-container

Usage

Basic Example
import (
    ci "github.com/taubyte/go-simple-container"
    "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/go-simple-container/gc"
    ci "github.com/taubyte/go-simple-container" 
)

// 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

Examples

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")
	ErrorImageBuildResCopy    = errors.New("copying response from image build failed")
	ErrorImagePullStatus      = errors.New("copying pull status failed")

	ErrorContainerOptions = errors.New("container options failed")
	ErrorContainerCreate  = errors.New("creating container failed")
)

Image Method Errors

View Source
var (
	ErrorContainerStart   = errors.New("start container failed")
	ErrorContainerWait    = errors.New("container wait failed")
	ErrorClientWait       = errors.New("client wait failed")
	ErrorContainerInspect = errors.New("inspecting container failed")
	ErrorExitCode         = errors.New("exit-code")
	ErrorContainerLogs    = errors.New("getting container logs failed")
)

Container Method Errors

View Source
var (
	ForceRebuild = false
)

Functions

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 Client

type Client struct {
	*client.Client
}

Client wraps the methods of the docker Client.

func New

func New() (dockerClient *Client, err error)

New creates a new dockerClient with default Options.

Example
package main

import (
	"fmt"

	containers "github.com/taubyte/go-simple-container"
)

var client *containers.Client
var err error

func main() {
	// create new docker client
	client, err = containers.New()
	if err != nil {
		return
	}

	fmt.Println("success")
}
Output:

success

func (*Client) Clean

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

Clean removes all docker images that match the given filter, and max age.

func (*Client) Image

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

Image initializes the given image, and attempts to pull the container from docker hub. If the Build() Option is provided then the given DockerFile tarball is built and returned.

Example
package main

import (
	"bytes"
	"context"
	"fmt"

	containers "github.com/taubyte/go-simple-container"
)

var image *containers.Image

func main() {
	// create new docker client
	client, err := containers.New()
	if err != nil {
		return
	}

	// declare new docker image `node` from docker hub public image `node`
	image, err = client.Image(context.Background(), "node")
	if err != nil {
		return
	}

	dockerFileTarBall := bytes.NewBuffer(nil)

	// Build a custom image using a Dockerfile tarball.
	// This will error because we are sending nil bytes. Refer to README for how to build this tarball.
	image, err = client.Image(context.Background(), "custom/test:version1", containers.Build(dockerFileTarBall))
	if err == nil {
		return
	}

	fmt.Println("success")
}
Output:

success

type Container

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

Container wraps the methods of the docker container.

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.

Example
package main

import (
	"bytes"
	"context"
	"fmt"

	containers "github.com/taubyte/go-simple-container"
)

func main() {
	// create new docker client
	client, err := containers.New()
	if err != nil {
		return
	}

	ctx := context.Background()

	// declare new docker image `node` from docker hub public image `node`
	image, err := client.Image(ctx, "node")
	if err != nil {
		return
	}

	// declare container options to set environment variable, and command to be run by container
	options := []containers.ContainerOption{
		containers.Variable("KEY", "value"),
		containers.Command([]string{"echo", "Hello World"}),
	}

	// create container from the image
	container, err := image.Instantiate(ctx, options...)
	if err != nil {
		return
	}

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

	var buf bytes.Buffer

	// read logs from the ran container
	buf.ReadFrom(logs.Combined())

	fmt.Println(buf.String())
}
Output:

Hello World

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 Image

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

Image wraps the methods of the docker image.

func (*Image) Instantiate

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

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

Example
package main

import (
	"context"
	"fmt"

	containers "github.com/taubyte/go-simple-container"
)

var container *containers.Container

func main() {
	// create new docker client
	client, err := containers.New()
	if err != nil {
		return
	}

	ctx := context.Background()

	// declare new docker image `node` from docker hub public image `node`
	image, err := client.Image(ctx, "node")
	if err != nil {
		return
	}

	// declare container options to set environment variable, and command to be run by container
	options := []containers.ContainerOption{
		containers.Variable("KEY", "value"),
		containers.Command([]string{"echo", "Hello World"}),
	}

	// create container from the image
	container, err = image.Instantiate(ctx, options...)
	if err != nil {
		return
	}

	fmt.Println("success")
}
Output:

success

func (*Image) Name

func (i *Image) Name() string

Name returns the name of the image

func (*Image) Pull

func (i *Image) Pull(ctx context.Context) (*Image, error)

Pull retrieves latest changes to the image from docker hub.

type ImageOption

type ImageOption func(*Image) 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

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.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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