docker

package module
v0.0.0-...-f8b2181 Latest Latest
Warning

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

Go to latest
Published: Nov 19, 2015 License: Apache-2.0 Imports: 16 Imported by: 0

README

Golang Docker client

GoDoc

This is a fork of the samalba/dockerclient library. It adds missing API calls such as wait, commit, and attach as well as a splitter for Docker stream events (like containers stdout and stderr). The fork also removes event callbacks and tests against a Docker installation rather than mocks.

Example:

package main

import (
	"fmt"
	"os"
	"time"

	"github.com/yhat/go-docker"
)

func SayHi() error {
	timeout := 3 * time.Second

	cli, err := docker.NewDefaultClient(timeout)
	if err != nil {
		return err
	}

	// create a container
	config := &docker.ContainerConfig{
		Image: "ubuntu:14.04",
		Cmd:   []string{"echo", "hello from docker land"},
	}
	cid, err := cli.CreateContainer(config, "myimage")
	if err != nil {
		return err
	}

	// always remember to clean up after yourself
	defer cli.RemoveContainer(cid, true, false)

	// attach to the container
	streamOpts := &docker.AttachOptions{Stream: true, Stdout: true, Stderr: true}
	stream, err := cli.Attach(cid, streamOpts)
	if err != nil {
		return err
	}
	defer stream.Close()

	// concurrently write stream to stdout and stderr
	go docker.SplitStream(stream, os.Stdout, os.Stderr)

	// start the container
	err = cli.StartContainer(cid, &docker.HostConfig{})
	if err != nil {
		return err
	}

	// wait for the container to exit
	statusCode, err := cli.Wait(cid)
	if err != nil {
		return err
	}
	if statusCode != 0 {
		return fmt.Errorf("process returned bad status code: %d", statusCode)
	}

	return nil
}

func main() {
	if err := SayHi(); err != nil {
		panic(err)
	}
}

Documentation

Index

Constants

View Source
const (
	StdinStream  byte = 0
	StdoutStream      = 1
	StderrStream      = 2
)
View Source
const (
	ChangeModify = iota
	ChangeAdd
	ChangeDelete
)
View Source
const APIVersion = "v1.17"

Variables

This section is empty.

Functions

func SplitStream

func SplitStream(stream io.Reader, stdout, stderr io.Writer) error

SplitStream splits docker stream data into stdout and stderr. For specifications see http://goo.gl/Dnbcye

Types

type AttachOptions

type AttachOptions struct {
	Logs   bool
	Stream bool
	Stdin  bool
	Stdout bool
	Stderr bool
}

type AuthConfig

type AuthConfig struct {
	Username string `json:"username,omitempty"`
	Password string `json:"password,omitempty"`
	Email    string `json:"email,omitempty"`
}

AuthConfig hold parameters for authenticating with the docker registry

type BlkioStatEntry

type BlkioStatEntry struct {
	Major uint64 `json:"major"`
	Minor uint64 `json:"minor"`
	Op    string `json:"op"`
	Value uint64 `json:"value"`
}

type BlkioStats

type BlkioStats struct {
	// number of bytes tranferred to and from the block device
	IoServiceBytesRecursive []BlkioStatEntry `json:"io_service_bytes_recursive"`
	IoServicedRecursive     []BlkioStatEntry `json:"io_serviced_recursive"`
	IoQueuedRecursive       []BlkioStatEntry `json:"io_queue_recursive"`
	IoServiceTimeRecursive  []BlkioStatEntry `json:"io_service_time_recursive"`
	IoWaitTimeRecursive     []BlkioStatEntry `json:"io_wait_time_recursive"`
	IoMergedRecursive       []BlkioStatEntry `json:"io_merged_recursive"`
	IoTimeRecursive         []BlkioStatEntry `json:"io_time_recursive"`
	SectorsRecursive        []BlkioStatEntry `json:"sectors_recursive"`
}

type ChangeType

type ChangeType int

type Client

type Client struct {
	URL        *url.URL
	HTTPClient *http.Client
	TLSConfig  *tls.Config
}

func NewClient

func NewClient(daemonURL string, tlsConfig *tls.Config, timeout time.Duration) (*Client, error)

func NewDefaultClient

func NewDefaultClient(timeout time.Duration) (*Client, error)

NewDefaultClient provides an arch specific default docker client. On linux it connects to the default docker socket, on OS X it looks for boot2docker environment variables.

func (*Client) Attach

func (client *Client) Attach(cid string, options *AttachOptions) (io.ReadCloser, error)

Attach returns the stdout and stderr stream of a stopped or running container. It is the callers responsibility to close the returned stream. Use SplitStream to parse stdout and stderr.

func (*Client) Changes

func (client *Client) Changes(cid string) ([]ContainerChange, error)

Changes provides a list of changes made to a container.

func (*Client) Commit

func (client *Client) Commit(options *CommitOptions, config *ContainerConfig) (string, error)

func (*Client) ContainerLogs

func (client *Client) ContainerLogs(id string, options *LogOptions) (io.ReadCloser, error)

func (*Client) Copy

func (client *Client) Copy(cid, resource string) (TarReader, error)

Copy copies files or folders from a container. It is the caller's responsiblity to call Close on returned TarReader.

func (*Client) CreateContainer

func (client *Client) CreateContainer(config *ContainerConfig, name string) (string, error)

func (*Client) DoRequest

func (client *Client) DoRequest(method string, path string, body io.Reader) (*http.Response, error)

func (*Client) Exec

func (client *Client) Exec(config *ExecConfig) (string, error)

func (*Client) History

func (client *Client) History(id string) ([]ImageLayer, error)

func (*Client) Info

func (client *Client) Info() (*Info, error)

func (*Client) InspectContainer

func (client *Client) InspectContainer(id string) (*ContainerInfo, error)

func (*Client) InspectImage

func (client *Client) InspectImage(name string) (ImageInfo, error)

func (*Client) KillContainer

func (client *Client) KillContainer(id, signal string) error

func (*Client) ListContainers

func (client *Client) ListContainers(all bool, size bool, filters string) ([]Container, error)

func (*Client) ListImages

func (client *Client) ListImages(all bool) ([]*Image, error)

func (*Client) LoadImage

func (client *Client) LoadImage(reader io.Reader) error

func (*Client) MonitorStats

func (client *Client) MonitorStats(id string) (*Stats, error)

func (*Client) NewRequest

func (client *Client) NewRequest(method string, path string, body io.Reader) (*http.Request, error)

func (*Client) PauseContainer

func (client *Client) PauseContainer(id string) error

func (*Client) PullImage

func (client *Client) PullImage(name string, auth *AuthConfig) error

func (*Client) Push

func (client *Client) Push(name, tag string, auth *AuthConfig) error

func (*Client) RemoveContainer

func (client *Client) RemoveContainer(id string, force, volumes bool) error

func (*Client) RemoveImage

func (client *Client) RemoveImage(name string) ([]*ImageDelete, error)

func (*Client) RestartContainer

func (client *Client) RestartContainer(id string, timeout int) error

func (*Client) StartContainer

func (client *Client) StartContainer(id string, config *HostConfig) error

func (*Client) StopContainer

func (client *Client) StopContainer(id string, timeout int) error

func (*Client) Tag

func (client *Client) Tag(imgId string, ops *TagOptions) error

func (*Client) UnpauseContainer

func (client *Client) UnpauseContainer(id string) error

func (*Client) Version

func (client *Client) Version() (*Version, error)

func (*Client) Wait

func (client *Client) Wait(cid string) (int, error)

Wait blocks until a container has exited. Wait returns the StatusCode of the exited process.

type CommitOptions

type CommitOptions struct {
	Container string
	Repo      string
	Tag       string
	Comment   string
	Author    string
}

type Container

type Container struct {
	Id         string
	Names      []string
	Image      string
	Command    string
	Created    int64
	Status     string
	Ports      []Port
	SizeRw     int64
	SizeRootFs int64
}

type ContainerChange

type ContainerChange struct {
	Kind int
	Path string
}

type ContainerConfig

type ContainerConfig struct {
	Hostname        string
	Domainname      string
	User            string
	Memory          int64
	MemorySwap      int64
	CpuShares       int64
	Cpuset          string
	AttachStdin     bool
	AttachStdout    bool
	AttachStderr    bool
	PortSpecs       []string
	ExposedPorts    map[string]struct{}
	Tty             bool
	OpenStdin       bool
	StdinOnce       bool
	Env             []string
	Cmd             []string
	Image           string
	Volumes         map[string]struct{}
	WorkingDir      string
	Entrypoint      []string
	NetworkDisabled bool
	OnBuild         []string

	// This is used only by the create command
	HostConfig HostConfig
}

type ContainerInfo

type ContainerInfo struct {
	Id      string
	Created string
	Path    string
	Name    string
	Args    []string
	ExecIDs []string
	Config  *ContainerConfig
	State   struct {
		Running    bool
		Paused     bool
		Restarting bool
		Pid        int
		ExitCode   int
		StartedAt  time.Time
		FinishedAt time.Time
		Ghost      bool
	}
	Image           string
	NetworkSettings struct {
		IpAddress   string
		IpPrefixLen int
		Gateway     string
		Bridge      string
		Ports       map[string][]PortBinding
	}
	SysInitPath    string
	ResolvConfPath string
	Volumes        map[string]string
	HostConfig     *HostConfig
}

type CpuStats

type CpuStats struct {
	CpuUsage       CpuUsage       `json:"cpu_usage"`
	SystemUsage    uint64         `json:"system_cpu_usage"`
	ThrottlingData ThrottlingData `json:"throttling_data,omitempty"`
}

type CpuUsage

type CpuUsage struct {
	// Total CPU time consumed.
	// Units: nanoseconds.
	TotalUsage uint64 `json:"total_usage"`
	// Total CPU time consumed per core.
	// Units: nanoseconds.
	PercpuUsage []uint64 `json:"percpu_usage"`
	// Time spent by tasks of the cgroup in kernel mode.
	// Units: nanoseconds.
	UsageInKernelmode uint64 `json:"usage_in_kernelmode"`
	// Time spent by tasks of the cgroup in user mode.
	// Units: nanoseconds.
	UsageInUsermode uint64 `json:"usage_in_usermode"`
}

type Error

type Error struct {
	StatusCode int
	Status     string
	// contains filtered or unexported fields
}

func (*Error) Error

func (e *Error) Error() string

type Event

type Event struct {
	Id     string
	Status string
	From   string
	Time   int64
}

type ExecConfig

type ExecConfig struct {
	AttachStdin  bool
	AttachStdout bool
	AttachStderr bool
	Tty          bool
	Cmd          []string
	Container    string
	Detach       bool
}

type HostConfig

type HostConfig struct {
	Binds           []string
	ContainerIDFile string
	LxcConf         []map[string]string
	Privileged      bool
	PortBindings    map[string][]PortBinding
	Links           []string
	PublishAllPorts bool
	Dns             []string
	DnsSearch       []string
	VolumesFrom     []string
	NetworkMode     string
	RestartPolicy   RestartPolicy
	Memory          int64
	MemorySwap      int64
	CpuShares       int64
	CpuPeriod       int64
	CpusetCpus      string
	CpusetMems      string
}

type Image

type Image struct {
	Created     int64
	Id          string
	ParentId    string
	RepoTags    []string
	Size        int64
	VirtualSize int64
}

type ImageDelete

type ImageDelete struct {
	Deleted  string
	Untagged string
}

type ImageInfo

type ImageInfo struct {
	Created   string
	Container string
	Id        string
	Parent    string
	Size      int
}

returned by InspectImage

type ImageLayer

type ImageLayer struct {
	Id        string
	Created   int64
	CreatedBy string
	Comment   string
	Size      int64
	Tags      []string
}

returned by History

type Info

type Info struct {
	ID              string
	Containers      int64
	DockerRootDir   string
	Driver          string
	DriverStatus    [][]string
	ExecutionDriver string
	Images          int64
	KernelVersion   string
	OperatingSystem string
	NCPU            int64
	MemTotal        int64
	Name            string
	Labels          []string
}

type LogOptions

type LogOptions struct {
	Follow     bool
	Stdout     bool
	Stderr     bool
	Timestamps bool
	Tail       int64
}

type MemDetails

type MemDetails struct {
	TotalPgmajFault         uint64 `json:"total_pgmajfault"`
	Cache                   uint64 `json:"cache"`
	MappedFile              uint64 `json:"mapped_file"`
	TotalInactiveFile       uint64 `json:"total_inactive_file"`
	PgpgOut                 uint64 `json:"pgpgout"`
	Rss                     uint64 `json:"rss"`
	TotalMappedFile         uint64 `json:"total_mapped_file"`
	Writeback               uint64 `json:"writeback"`
	Unevictable             uint64 `json:"unevictable"`
	PgpgIn                  uint64 `json:"pgpgin"`
	TotalUnevictable        uint64 `json:"total_unevictable"`
	PgmajFault              uint64 `json:"pgmajfault"`
	TotalRss                uint64 `json:"total_rss"`
	TotalRssHuge            uint64 `json:"total_rss_huge"`
	TotalWriteback          uint64 `json:"total_writeback"`
	TotalInactiveAnon       uint64 `json:"total_inactive_anon"`
	RssHuge                 uint64 `json:"rss_huge"`
	HierarchicalMemoryLimit uint64 `json:"hierarchical_memory_limit"`
	TotalPgFault            uint64 `json:"total_pgfault"`
	TotalActiveFile         uint64 `json:"total_active_file"`
	ActiveAnon              uint64 `json:"active_anon"`
	TotalActiveAnon         uint64 `json:"total_active_anon"`
	TotalPgpgOut            uint64 `json:"total_pgpgout"`
	TotalCache              uint64 `json:"total_cache"`
	InactiveAnon            uint64 `json:"inactive_anon"`
	ActiveFile              uint64 `json:"active_file"`
	PgFault                 uint64 `json:"pgfault"`
	InactiveFile            uint64 `json:"inactive_file"`
	TotalPgpgIn             uint64 `json:"total_pgpgin"`
}

type MemoryStats

type MemoryStats struct {
	Usage    uint64     `json:"usage"`
	MaxUsage uint64     `json:"max_usage"`
	Stats    MemDetails `json:"stats"`
	Failcnt  uint64     `json:"failcnt"`
	Limit    uint64     `json:"limit"`
}

type NetworkStats

type NetworkStats struct {
	RxBytes   uint64 `json:"rx_bytes"`
	RxPackets uint64 `json:"rx_packets"`
	RxErrors  uint64 `json:"rx_errors"`
	RxDropped uint64 `json:"rx_dropped"`
	TxBytes   uint64 `json:"tx_bytes"`
	TxPackets uint64 `json:"tx_packets"`
	TxErrors  uint64 `json:"tx_errors"`
	TxDropped uint64 `json:"tx_dropped"`
}

type Port

type Port struct {
	IP          string
	PrivatePort int
	PublicPort  int
	Type        string
}

type PortBinding

type PortBinding struct {
	HostIp   string
	HostPort string
}

type RespContainersCreate

type RespContainersCreate struct {
	Id       string
	Warnings []string
}

type RestartPolicy

type RestartPolicy struct {
	Name              string
	MaximumRetryCount int64
}

type Stats

type Stats struct {
	Read         time.Time    `json:"read"`
	NetworkStats NetworkStats `json:"network,omitempty"`
	CpuStats     CpuStats     `json:"cpu_stats,omitempty"`
	MemoryStats  MemoryStats  `json:"memory_stats,omitempty"`
	BlkioStats   BlkioStats   `json:"blkio_stats,omitempty"`
}

type TagOptions

type TagOptions struct {
	Repo  string
	Force bool
	Tag   string
}

type TarReader

type TarReader struct {
	*tar.Reader
	// contains filtered or unexported fields
}

TarReader wraps tar.Reader with a close method.

func (TarReader) Close

func (tr TarReader) Close() error

type ThrottlingData

type ThrottlingData struct {
	// Number of periods with throttling active
	Periods uint64 `json:"periods"`
	// Number of periods when the container hit its throttling limit.
	ThrottledPeriods uint64 `json:"throttled_periods"`
	// Aggregate time the container was throttled for in nanoseconds.
	ThrottledTime uint64 `json:"throttled_time"`
}

type Version

type Version struct {
	Version   string
	GitCommit string
	GoVersion string
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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