narwhal

package module
v0.10.1 Latest Latest
Warning

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

Go to latest
Published: Feb 25, 2021 License: Apache-2.0 Imports: 20 Imported by: 1

README

Narwhal!

Go Reference

Narwhal is a simplistic wrapper around the Docker Go API.

Examples

For full examples and usage see pkg.go.dev.

// Create a client
client := narwhal.DockerClient()

// Create a container
containerID, err := narwhal.CreateContainer(ctx, client, os.Stdout, narwhal.ContainerDefinition{
  Image: "ubuntu:latest",
})

// Start a container
err := narwhal.StartContainer(ctx, client, containerID)

// Copy a file into a container
f, err := ioutil.TempFile("./", "tmpfile")
err = narwhal.UploadFile(ctx, client, containerID, "/tmp/tmpfile", f.Name())

// Execute a command in a container
err := narwhal.ExecShell(ctx, client, containerID, "echo 'Hello world!'", &narwhal.ExecShellOptions{})

Documentation

Overview

Package narwhal provides functions for high-level operations on Docker containers.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func BuildImageWithArchive

func BuildImageWithArchive(ctx context.Context, client *docker.Client, pullOutput io.Writer, cd *ContainerDefinition, repository, tag, localFile, remotePath string) error

func CountLayersInImage

func CountLayersInImage(ctx context.Context, client *docker.Client, imageID string) (int, error)

func CreateContainer added in v0.5.0

func CreateContainer(ctx context.Context, client *docker.Client, pullOutput io.Writer, containerDef *ContainerDefinition) (containerID string, err error)

CreateContainer creates a new container from the provided definition.

Example
package main

import (
	"context"
	"fmt"
	"os"

	"github.com/docker/distribution/uuid"
	"github.com/yourbase/narwhal"
)

var (
	ctx    = context.Background()
	client = narwhal.DockerClient()
)

func randomDefinition() *narwhal.ContainerDefinition {
	return &narwhal.ContainerDefinition{
		Label: uuid.Generate().String(),
		Image: "ubuntu:latest",
	}
}

func main() {
	containerID, err := narwhal.CreateContainer(ctx, client, os.Stdout, randomDefinition())
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println("Container created!")

	defer narwhal.RemoveContainerAndVolumes(ctx, client, containerID)

}
Output:

Container created!

func DockerClient deprecated

func DockerClient() *docker.Client

DockerClient returns a globally initialized Docker client.

Deprecated: Construct your own client.

func FindContainer

func FindContainer(ctx context.Context, client *docker.Client, cd *ContainerDefinition) (containerID string, _ error)

FindContainer searches for a container that matches the definition. If the container is not found, it returns an error for which IsContainerNotFound returns true.

func FindDockerImagesByTagPrefix

func FindDockerImagesByTagPrefix(ctx context.Context, client *docker.Client, imageName string) ([]docker.APIImages, error)

func IPv4Address

func IPv4Address(ctx context.Context, client *docker.Client, containerID string) (net.IP, error)

IPv4Address finds the IP address of a running container.

func IsContainerNotFound

func IsContainerNotFound(e error) bool

IsContainerNotFound reports whether the error indicates the container wasn't found.

func IsRunning added in v0.3.1

func IsRunning(ctx context.Context, client *docker.Client, containerID string) (bool, error)

IsRunning check if a container is running by its ID

func MkdirAll

func MkdirAll(ctx context.Context, client *docker.Client, containerID string, path string, opts *MkdirOptions) error

MkdirAll ensures that the given directory and all its parents directories exist. The container does not have to be running.

func PullImage

func PullImage(ctx context.Context, client *docker.Client, output io.Writer, c *ContainerDefinition, authConfig docker.AuthConfiguration) error

PullImage unconditionally pulls the image for the given container definition.

func PullImageIfNotHere

func PullImageIfNotHere(ctx context.Context, client *docker.Client, output io.Writer, c *ContainerDefinition, authConfig docker.AuthConfiguration) error

PullImageIfNotHere pulls the image for the given container definition if it is not present in the Docker daemon's storage.

func RemoveContainerAndVolumes

func RemoveContainerAndVolumes(ctx context.Context, client *docker.Client, containerID string) error

RemoveContainerAndVolumes removes the given container and any associated volumes.

func SquashImage

func SquashImage(ctx context.Context, client *docker.Client, repo, tag string) error

SquashImage takes a docker image with multiple layers and squashes it into a single layer. SquashImage takes advantage of the fact that docker squashes layers into a single later when exported from a container Note: It can take minutes to export the container. Please consider this when setting context.Context.

func StartContainer

func StartContainer(ctx context.Context, client *docker.Client, containerID string, healthCheckPort int) error

StartContainer starts an already created container. If the container is already running, this function no-ops. If healthCheckPort is not zero, then this function will wait until the given container port accepts TCP connections or the Context is cancelled.

Example
package main

import (
	"context"
	"fmt"
	"os"

	"github.com/docker/distribution/uuid"
	"github.com/yourbase/narwhal"
)

var (
	ctx    = context.Background()
	client = narwhal.DockerClient()
)

func randomDefinition() *narwhal.ContainerDefinition {
	return &narwhal.ContainerDefinition{
		Label: uuid.Generate().String(),
		Image: "ubuntu:latest",
	}
}

func main() {
	containerID, err := narwhal.CreateContainer(ctx, client, os.Stdout, randomDefinition())
	if err != nil {
		fmt.Println(err)
		return
	}
	defer narwhal.RemoveContainerAndVolumes(ctx, client, containerID)

	if err := narwhal.StartContainer(ctx, client, containerID, 0); err != nil {
		fmt.Println(err)
		return
	}

	if isRunning, err := narwhal.IsRunning(ctx, client, containerID); err != nil {
		fmt.Println(err)
		return
	} else if isRunning {
		fmt.Println("Container is running!")
	}

}
Output:

Container is running!

func Upload

func Upload(ctx context.Context, client *docker.Client, containerID string, remotePath string, content io.Reader, header *tar.Header) error

Upload writes the given content to a path inside the container. header.Name is entirely ignored. The parent directory is created if it does not exist. remotePath must be absolute.

func UploadFile

func UploadFile(ctx context.Context, client *docker.Client, containerID string, remotePath string, localPath string) error

UploadFile sends the content of localFile (a host filesystem path) into remotePath (a path to a directory inside the container) with the given fileName. The parent directory is created if it does not exist. remotePath must be absolute.

Example
package main

import (
	"context"
	"fmt"
	"io/ioutil"
	"os"

	"github.com/docker/distribution/uuid"
	"github.com/yourbase/narwhal"
)

var (
	ctx    = context.Background()
	client = narwhal.DockerClient()
)

func randomDefinition() *narwhal.ContainerDefinition {
	return &narwhal.ContainerDefinition{
		Label: uuid.Generate().String(),
		Image: "ubuntu:latest",
	}
}

func main() {
	containerID, err := narwhal.CreateContainer(ctx, client, os.Stdout, randomDefinition())
	if err != nil {
		fmt.Println(err)
		return
	}
	defer narwhal.RemoveContainerAndVolumes(ctx, client, containerID)

	if err := narwhal.StartContainer(ctx, client, containerID, 0); err != nil {
		fmt.Println(err)
		return
	}

	f, err := ioutil.TempFile("./", "tmpfile")
	if err != nil {
		fmt.Println(err)
		return
	}
	defer os.Remove(f.Name())

	if err := narwhal.UploadFile(ctx, client, containerID, "/tmp/tmpfile", f.Name()); err != nil {
		fmt.Println(err)
		return
	}

	fmt.Println("File uploaded!")

}
Output:

File uploaded!

func Write added in v0.6.0

func Write(ctx context.Context, client *docker.Client, containerID string, remotePath string, content io.Reader, header *tar.Header) error

Write writes the given content to a path inside the container. header.Name is entirely ignored. The parent directory must exist or Write will return an error. remotePath must be absolute.

func WriteFile added in v0.6.0

func WriteFile(ctx context.Context, client *docker.Client, containerID string, remotePath string, localPath string) error

WriteFile sends the content of localFile (a host filesystem path) into remotePath (a path to a directory inside the container) with the given fileName. The parent directory must exist or Write will return an error. remotePath must be absolute.

Types

type ContainerDefinition

type ContainerDefinition struct {
	// Image is a reference to a Docker image. Must not be empty.
	Image string
	// Label is unique text inserted into the Docker container name. May be empty.
	Label string
	// Namespace is a prefix for the Docker container name. May be empty.
	Namespace string

	// Argv specifies the command to run as PID 1 in the container.
	Argv []string
	// Deprecated: use Argv.
	Command string

	// Ports is a list of "HOST:CONTAINER" port mappings. The mappings may
	// optionally end in "/tcp" or "/udp" to indicate the protocol.
	Ports []string
	// If HealthCheckPort is not zero, the matching container TCP port will be
	// made available at the returned Container.HealthCheckAddr address.
	HealthCheckPort int

	Mounts      []docker.HostMount
	Environment []string
	WorkDir     string
	Privileged  bool
	ExecUserID  string
	ExecGroupID string
}

A ContainerDefinition specifies a container to create.

func (*ContainerDefinition) ImageName

func (c *ContainerDefinition) ImageName() string

func (*ContainerDefinition) ImageNameWithTag

func (c *ContainerDefinition) ImageNameWithTag() string

func (*ContainerDefinition) ImageTag

func (c *ContainerDefinition) ImageTag() string

type MkdirOptions added in v0.6.0

type MkdirOptions struct {
	// Perm specifies the permission bits for any created directories.
	// If zero, then 0755 is used. If you really want to force no permissions,
	// then use os.ModeDir.
	Perm os.FileMode
	// UID specifies the owner of any created directories.
	// Defaults to root.
	UID int
	// GID specifies the group of any created directories.
	// Defaults to root.
	GID int
}

MkdirOptions specifies optional parameters to MkdirAll.

Directories

Path Synopsis
internal

Jump to

Keyboard shortcuts

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