dockerclient

package
v0.4.0-rc2 Latest Latest
Warning

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

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

README

Docker client library in Go

GoDoc

Well maintained docker client library.

How to use it?

Here is an example showing how to use it:

package main

import (
	"github.com/samalba/dockerclient"
	"log"
	"time"
	"os"
)

// Callback used to listen to Docker's events
func eventCallback(event *dockerclient.Event, ec chan error, args ...interface{}) {
	log.Printf("Received event: %#v\n", *event)
}

func main() {
	// Init the client
	docker, _ := dockerclient.NewDockerClient("unix:///var/run/docker.sock", nil)

	// Get only running containers
	containers, err := docker.ListContainers(false, false, "")
	if err != nil {
		log.Fatal(err)
	}
	for _, c := range containers {
		log.Println(c.Id, c.Names)
	}

	// Inspect the first container returned
	if len(containers) > 0 {
		id := containers[0].Id
		info, _ := docker.InspectContainer(id)
		log.Println(info)
	}

	// Build a docker image
	// some.tar contains the build context (Dockerfile any any files it needs to add/copy)
	dockerBuildContext, err := os.Open("some.tar")
	defer dockerBuildContext.Close()
	buildImageConfig := &dockerclient.BuildImage{
			Context:        dockerBuildContext,
			RepoName:       "your_image_name",
			SuppressOutput: false,
	}
	reader, err := docker.BuildImage(buildImageConfig)
	if err != nil {
		log.Fatal(err)
	}

	// Create a container
	containerConfig := &dockerclient.ContainerConfig{
		Image: "ubuntu:14.04",
		Cmd:   []string{"bash"},
		AttachStdin: true,
		Tty:   true}
	containerId, err := docker.CreateContainer(containerConfig, "foobar")
	if err != nil {
		log.Fatal(err)
	}

	// Start the container
	hostConfig := &dockerclient.HostConfig{}
	err = docker.StartContainer(containerId, hostConfig)
	if err != nil {
		log.Fatal(err)
	}

	// Stop the container (with 5 seconds timeout)
	docker.StopContainer(containerId, 5)

	// Listen to events
	docker.StartMonitorEvents(eventCallback, nil)

	// Hold the execution to look at the events coming
	time.Sleep(3600 * time.Second)
}

Maintainers

List of people you can ping for feedback on Pull Requests or any questions.

Documentation

Index

Constants

View Source
const (
	APIVersion = "v1.15"
)

Variables

View Source
var (
	ErrNotFound = errors.New("Not found")
)

Functions

This section is empty.

Types

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 BuildImage

type BuildImage struct {
	Config         *ConfigFile
	DockerfileName string
	Context        io.Reader
	RemoteURL      string
	RepoName       string
	SuppressOutput bool
	NoCache        bool
	Remove         bool
	ForceRemove    bool
	Pull           bool
	Memory         int64
	MemorySwap     int64
	CpuShares      int64
	CpuPeriod      int64
	CpuQuota       int64
	CpuSetCpus     string
	CpuSetMems     string
	CgroupParent   string
}

type Callback

type Callback func(*Event, chan error, ...interface{})

type Client

type Client interface {
	Info() (*Info, error)
	ListContainers(all, size bool, filters string) ([]Container, error)
	InspectContainer(id string) (*ContainerInfo, error)
	InspectImage(id string) (*ImageInfo, error)
	CreateContainer(config *ContainerConfig, name string) (string, error)
	ContainerLogs(id string, options *LogOptions) (io.ReadCloser, error)
	ContainerChanges(id string) ([]*ContainerChanges, error)
	Exec(config *ExecConfig) (string, error)
	StartContainer(id string, config *HostConfig) error
	StopContainer(id string, timeout int) error
	RestartContainer(id string, timeout int) error
	KillContainer(id, signal string) error
	Wait(id string) <-chan WaitResult
	// MonitorEvents takes options and an optional stop channel, and returns
	// an EventOrError channel. If an error is ever sent, then no more
	// events will be sent. If a stop channel is provided, events will stop
	// being monitored after the stop channel is closed.
	MonitorEvents(options *MonitorEventsOptions, stopChan <-chan struct{}) (<-chan EventOrError, error)
	StartMonitorEvents(cb Callback, ec chan error, args ...interface{})
	StopAllMonitorEvents()
	StartMonitorStats(id string, cb StatCallback, ec chan error, args ...interface{})
	StopAllMonitorStats()
	TagImage(nameOrID string, repo string, tag string, force bool) error
	Version() (*Version, error)
	PullImage(name string, auth *AuthConfig) error
	LoadImage(reader io.Reader) error
	RemoveContainer(id string, force, volumes bool) error
	ListImages(all bool) ([]*Image, error)
	RemoveImage(name string) ([]*ImageDelete, error)
	PauseContainer(name string) error
	UnpauseContainer(name string) error
	RenameContainer(oldName string, newName string) error
	ImportImage(source string, repository string, tag string, tar io.Reader) (io.ReadCloser, error)
	BuildImage(image *BuildImage) (io.ReadCloser, error)
}

type ConfigFile

type ConfigFile struct {
	Configs map[string]AuthConfig `json:"configs,omitempty"`
	// contains filtered or unexported fields
}

ConfigFile holds parameters for authenticating during a BuildImage request

type Container

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

type ContainerChanges

type ContainerChanges struct {
	Path string
	Kind int
}

type ContainerConfig

type ContainerConfig struct {
	Hostname        string
	Domainname      string
	User            string
	AttachStdin     bool
	AttachStdout    bool
	AttachStderr    bool
	ExposedPorts    map[string]struct{}
	Tty             bool
	OpenStdin       bool
	StdinOnce       bool
	Env             []string
	Cmd             []string
	Image           string
	Volumes         map[string]struct{}
	VolumeDriver    string
	WorkingDir      string
	Entrypoint      []string
	NetworkDisabled bool
	MacAddress      string
	OnBuild         []string
	Labels          map[string]string

	// FIXME: The following fields have been removed since API v1.18
	Memory     int64
	MemorySwap int64
	CpuShares  int64
	Cpuset     string
	PortSpecs  []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           *State
	Image           string
	NetworkSettings struct {
		IPAddress   string `json:"IpAddress"`
		IPPrefixLen int    `json:"IpPrefixLen"`
		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 DeviceMapping

type DeviceMapping struct {
	PathOnHost        string `json:"PathOnHost"`
	PathInContainer   string `json:"PathInContainer"`
	CgroupPermissions string `json:"CgroupPermissions"`
}

type DockerClient

type DockerClient struct {
	URL        *url.URL
	HTTPClient *http.Client
	TLSConfig  *tls.Config
	// contains filtered or unexported fields
}

func NewDockerClient

func NewDockerClient(daemonUrl string, tlsConfig *tls.Config) (*DockerClient, error)

func NewDockerClientTimeout

func NewDockerClientTimeout(daemonUrl string, tlsConfig *tls.Config, timeout time.Duration) (*DockerClient, error)

func (*DockerClient) BuildImage

func (client *DockerClient) BuildImage(image *BuildImage) (io.ReadCloser, error)

func (*DockerClient) ContainerChanges

func (client *DockerClient) ContainerChanges(id string) ([]*ContainerChanges, error)

func (*DockerClient) ContainerLogs

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

func (*DockerClient) CreateContainer

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

func (*DockerClient) Exec

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

func (*DockerClient) ImportImage

func (client *DockerClient) ImportImage(source string, repository string, tag string, tar io.Reader) (io.ReadCloser, error)

func (*DockerClient) Info

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

func (*DockerClient) InspectContainer

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

func (*DockerClient) InspectImage

func (client *DockerClient) InspectImage(id string) (*ImageInfo, error)

func (*DockerClient) KillContainer

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

func (*DockerClient) ListContainers

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

func (*DockerClient) ListImages

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

func (*DockerClient) LoadImage

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

func (*DockerClient) MonitorEvents

func (client *DockerClient) MonitorEvents(options *MonitorEventsOptions, stopChan <-chan struct{}) (<-chan EventOrError, error)

func (*DockerClient) PauseContainer

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

func (*DockerClient) PullImage

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

func (*DockerClient) RemoveContainer

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

func (*DockerClient) RemoveImage

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

func (*DockerClient) RenameContainer

func (client *DockerClient) RenameContainer(oldName string, newName string) error

func (*DockerClient) RestartContainer

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

func (*DockerClient) StartContainer

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

func (*DockerClient) StartMonitorEvents

func (client *DockerClient) StartMonitorEvents(cb Callback, ec chan error, args ...interface{})

func (*DockerClient) StartMonitorStats

func (client *DockerClient) StartMonitorStats(id string, cb StatCallback, ec chan error, args ...interface{})

func (*DockerClient) StopAllMonitorEvents

func (client *DockerClient) StopAllMonitorEvents()

func (*DockerClient) StopAllMonitorStats

func (client *DockerClient) StopAllMonitorStats()

func (*DockerClient) StopContainer

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

func (*DockerClient) TagImage

func (client *DockerClient) TagImage(nameOrID string, repo string, tag string, force bool) error

func (*DockerClient) UnpauseContainer

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

func (*DockerClient) Version

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

func (*DockerClient) Wait

func (client *DockerClient) Wait(id string) <-chan WaitResult

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 EventOrError

type EventOrError struct {
	Event
	Error error
}

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
	Memory          int64
	MemorySwap      int64
	CpuShares       int64
	CpuPeriod       int64
	CpusetCpus      string
	CpusetMems      string
	CpuQuota        int64
	BlkioWeight     int64
	OomKillDisable  bool
	Privileged      bool
	PortBindings    map[string][]PortBinding
	Links           []string
	PublishAllPorts bool
	Dns             []string
	DnsSearch       []string
	ExtraHosts      []string
	VolumesFrom     []string
	Devices         []DeviceMapping
	NetworkMode     string
	IpcMode         string
	PidMode         string
	UTSMode         string
	CapAdd          []string
	CapDrop         []string
	RestartPolicy   RestartPolicy
	SecurityOpt     []string
	ReadonlyRootfs  bool
	Ulimits         []Ulimit
	LogConfig       LogConfig
	CgroupParent    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 {
	Architecture    string
	Author          string
	Comment         string
	Config          *ContainerConfig
	Container       string
	ContainerConfig *ContainerConfig
	Created         time.Time
	DockerVersion   string
	Id              string
	Os              string
	Parent          string
	Size            int64
	VirtualSize     int64
}

type Info

type Info struct {
	ID                 string
	Containers         int64
	Driver             string
	DriverStatus       [][]string
	ExecutionDriver    string
	Images             int64
	KernelVersion      string
	OperatingSystem    string
	NCPU               int64
	MemTotal           int64
	Name               string
	Labels             []string
	Debug              interface{}
	NFd                int64
	NGoroutines        int64
	SystemTime         string
	NEventsListener    int64
	InitPath           string
	InitSha1           string
	IndexServerAddress string
	MemoryLimit        interface{}
	SwapLimit          interface{}
	IPv4Forwarding     interface{}
	BridgeNfIptables   bool
	BridgeNfIp6tables  bool
	DockerRootDir      string
	HttpProxy          string
	HttpsProxy         string
	NoProxy            string
}

Info is the struct returned by /info The API is currently in flux, so Debug, MemoryLimit, SwapLimit, and IPv4Forwarding are interfaces because in docker 1.6.1 they are 0 or 1 but in master they are bools.

type LogConfig

type LogConfig struct {
	Type   string            `json:"type"`
	Config map[string]string `json:"config"`
}

type LogOptions

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

type MemoryStats

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

type MonitorEventsFilters

type MonitorEventsFilters struct {
	Event     string `json:",omitempty"`
	Image     string `json:",omitempty"`
	Container string `json:",omitempty"`
}

type MonitorEventsOptions

type MonitorEventsOptions struct {
	Since   int
	Until   int
	Filters *MonitorEventsFilters `json:",omitempty"`
}

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 StatCallback

type StatCallback func(string, *Stats, chan error, ...interface{})

type State

type State struct {
	Running    bool
	Paused     bool
	Restarting bool
	OOMKilled  bool
	Dead       bool
	Pid        int
	ExitCode   int
	Error      string // contains last known error when starting the container
	StartedAt  time.Time
	FinishedAt time.Time
	Ghost      bool
}

func (*State) StateString

func (s *State) StateString() string

StateString returns a single string to describe state Stoken from docker/docker/daemon/state.go

func (*State) String

func (s *State) String() string

String returns a human-readable description of the state Stoken from docker/docker/daemon/state.go

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 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"`
}

The following are types for the API stats endpoint

type Ulimit

type Ulimit struct {
	Name string `json:"name"`
	Soft uint64 `json:"soft"`
	Hard uint64 `json:"hard"`
}

type Version

type Version struct {
	ApiVersion    string
	Arch          string
	GitCommit     string
	GoVersion     string
	KernelVersion string
	Os            string
	Version       string
}

type WaitResult

type WaitResult struct {
	ExitCode int
	Error    error
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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