func main() { client, err := docker.NewVersionedClient("unix:///var/run/docker.sock", "1.17") if err != nil { fmt.Println(err.Error()) return } fi, err := os.OpenFile("/data/test", os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0420) if err != nil { log.Panicln(err) } cpOptions := docker.CopyFromContainerOptions{ OutputStream: fi, Container: "omega-abc", Resource: "/data/test/", } err = client.CopyFromContainer(cpOptions) if err != nil { log.Println("copy failed") log.Panicln(err) } options := docker.DownloadFromContainerOptions{ OutputStream: fi, Path: "/data/test/", } err = client.DownloadFromContainer("omega-abc", options) if err != nil { log.Panicln(err) } }
// CreateClient creates a docker client based on the specified options. func CreateClient(c ClientOpts) (*dockerclient.Client, error) { if c.TLSOptions.CAFile == "" { c.TLSOptions.CAFile = filepath.Join(dockerCertPath, defaultCaFile) } if c.TLSOptions.CertFile == "" { c.TLSOptions.CertFile = filepath.Join(dockerCertPath, defaultCertFile) } if c.TLSOptions.KeyFile == "" { c.TLSOptions.KeyFile = filepath.Join(dockerCertPath, defaultKeyFile) } if c.Host == "" { defaultHost := os.Getenv("DOCKER_HOST") if defaultHost == "" { if runtime.GOOS != "windows" { // If we do not have a host, default to unix socket defaultHost = fmt.Sprintf("unix://%s", opts.DefaultUnixSocket) } else { // If we do not have a host, default to TCP socket on Windows defaultHost = fmt.Sprintf("tcp://%s:%d", opts.DefaultHTTPHost, opts.DefaultHTTPPort) } } defaultHost, err := opts.ValidateHost(defaultHost) if err != nil { return nil, err } c.Host = defaultHost } if c.TrustKey == "" { c.TrustKey = filepath.Join(homedir.Get(), ".docker", defaultTrustKeyFile) } if c.TLSVerify { c.TLS = true } if c.TLS { c.TLSOptions.InsecureSkipVerify = !c.TLSVerify } apiVersion := c.APIVersion if apiVersion == "" { apiVersion = DefaultAPIVersion } if c.TLS { client, err := dockerclient.NewVersionedTLSClient(c.Host, c.TLSOptions.CertFile, c.TLSOptions.KeyFile, c.TLSOptions.CAFile, apiVersion) if err != nil { return nil, err } if c.TLSOptions.InsecureSkipVerify { client.TLSConfig.InsecureSkipVerify = true } return client, nil } return dockerclient.NewVersionedClient(c.Host, apiVersion) }
func newDockerClient() (*_dockerclient, error) { client, err := godocker.NewVersionedClient(config.UnixSocketPrefix+config.DockerUnixSocket(), "1.15") if err != nil { return nil, err } err = client.Ping() return &_dockerclient{ docker: client, }, err }
func newDockerClient() (*_dockerclient, error) { client, err := godocker.NewVersionedClient("unix://"+defaultDockerEndpoint, "1.15") if err != nil { return nil, err } err = client.Ping() return &_dockerclient{ docker: client, }, err }
func getClient(c *Context) (*dockerClient.Client, error) { if c.Client != nil { return c.Client, nil } endpoint := os.Getenv("DOCKER_HOST") if len(endpoint) == 0 { endpoint = "unix:///var/run/docker.sock" } return dockerClient.NewVersionedClient(endpoint, "1.12") }
func NewVersionedClient(apiPath string, apiVersionString string) (*Client, error) { if !strings.Contains(apiPath, "://") { apiPath = "tcp://" + apiPath } dc, err := docker.NewVersionedClient(apiPath, apiVersionString) if err != nil { return nil, err } client := &Client{dc} return client, client.checkWorking() }
func main() { client, err := docker.NewVersionedClient("unix:///var/run/docker.sock", "1.20") // Start create .tar file // Create a buffer to write our archive to. buf := new(bytes.Buffer) // Create a new tar archive. tw := tar.NewWriter(buf) // Add some files to the archive. var files = []struct { Name, Body string }{ {"file1.txt", "This archive contains some text files."}, {"file2.txt", "Gopher names:\nGeorge\nGeoffrey\nGonzo"}, } for _, file := range files { hdr := &tar.Header{ Name: file.Name, Mode: 0600, Size: int64(len(file.Body)), } if err := tw.WriteHeader(hdr); err != nil { log.Fatalln(err) } if _, err := tw.Write([]byte(file.Body)); err != nil { log.Fatalln(err) } } // Make sure to check the error on Close. if err := tw.Close(); err != nil { log.Fatalln(err) } // End .tar file // Start upload .tar uploadOption := docker.UploadToContainerOptions{ InputStream: buf, Path: "/", NoOverwriteDirNonDir: true, } err = client.UploadToContainer("omega-slave", uploadOption) if err != nil { log.Panicln(err) } log.Println("Good") // End upload .tar }
func uploadTar() { client, err := docker.NewVersionedClient("unix:///var/run/docker.sock", "1.20") // Start create .tar file // Create a buffer to write our archive to. buf := new(bytes.Buffer) var tarFile string = "./docker.tar.gz" // Create a new tar archive. tw := tar.NewWriter(buf) fileInfo, err := os.Open(tarFile) if err != nil { log.Fatalln(err) } stat, _ := fileInfo.Stat() hdr := &tar.Header{ Name: tarFile, Mode: int64(stat.Mode()), Size: stat.Size(), } if err := tw.WriteHeader(hdr); err != nil { log.Fatalln(err) } // if _, err := tw.Write([]byte(file.Body)); err != nil { // log.Fatalln(err) // } _, err = io.Copy(tw, fileInfo) // Make sure to check the error on Close. if err := tw.Close(); err != nil { log.Fatalln(err) } // End .tar file // Start upload .tar uploadOption := docker.UploadToContainerOptions{ InputStream: buf, Path: "/etc/", NoOverwriteDirNonDir: true, } err = client.UploadToContainer("omega-slave", uploadOption) if err != nil { log.Panicln(err) } log.Println("Good") // End upload .tar }
func newDockerClient() (*_dockerclient, error) { dockerUnixSocketSourcePath, fromEnv := config.DockerUnixSocket() if !fromEnv { dockerUnixSocketSourcePath = "/var/run/docker.sock" } client, err := godocker.NewVersionedClient(config.UnixSocketPrefix+dockerUnixSocketSourcePath, "1.15") if err != nil { return nil, err } err = client.Ping() return &_dockerclient{ docker: client, }, err }
// Client returns a Docker client for the given Docker machine func Client(name string) (*docker.Client, error) { output, _, err := localcmd.New(dockerMachineBinary()).Args("env", name).Output() if err != nil { return nil, ErrDockerMachineExec("env", err) } scanner := bufio.NewScanner(bytes.NewBufferString(output)) var ( dockerHost, certPath string tlsVerify bool ) prefix := "export " if runtime.GOOS == "windows" { prefix = "SET " } for scanner.Scan() { line := scanner.Text() if strings.HasPrefix(line, prefix) { line = strings.TrimPrefix(line, prefix) parts := strings.SplitN(line, "=", 2) if len(parts) != 2 { continue } switch strings.ToUpper(parts[0]) { case "DOCKER_HOST": dockerHost = strings.Trim(parts[1], "\"") case "DOCKER_CERT_PATH": certPath = strings.Trim(parts[1], "\"") case "DOCKER_TLS_VERIFY": tlsVerify = len(parts[1]) > 0 } } } var client *docker.Client if tlsVerify { cert := filepath.Join(certPath, "cert.pem") key := filepath.Join(certPath, "key.pem") ca := filepath.Join(certPath, "ca.pem") client, err = docker.NewVersionedTLSClient(dockerHost, cert, key, ca, "") } else { client, err = docker.NewVersionedClient(dockerHost, "") } if err != nil { return nil, errors.NewError("could not get Docker client for machine %s", name).WithCause(err) } client.SkipServerVersionCheck = true return client, nil }
func main() { lient, err := docker.NewVersionedClient("unix:///var/run/docker.sock", "1.17") if err != nil { fmt.Println(err.Error()) return } /* Parameters: all – 1/True/true or 0/False/false, Show all containers. Only running containers are shown by default (i.e., this defaults to false) limit – Show limit last created containers, include non-running ones. since – Show only containers created since Id, include non-running ones. before – Show only containers created before Id, include non-running ones. size – 1/True/true or 0/False/false, Show the containers sizes filters - a JSON encoded value of the filters (a map[string][]string) to process on the containers list. Available filters: exited=<int>; – containers with exit code of <int> ; status=(created|restarting|running|paused|exited) label=key or label="key=value" of a container label */ /* type ListContainersOptions struct { All bool Size bool Limit int Since string Before string Filters map[string][]string } */ listOption := docker.ListContainersOptions{All: true, Filters: map[string][]string{"label": {"dataman"}}} containers, err := client.ListContainers(listOption) if err != nil { fmt.Println(err.Error()) return } fmt.Println(len(containers)) fmt.Println(containers[0].Names[0]) }
func NewDockerGoClient() (*DockerGoClient, error) { endpoint := utils.DefaultIfBlank(os.Getenv(DOCKER_ENDPOINT_ENV_VARIABLE), DOCKER_DEFAULT_ENDPOINT) client, err := docker.NewVersionedClient(endpoint, "1.17") if err != nil { log.Error("Unable to connect to docker daemon . Ensure docker is running", "endpoint", endpoint, "err", err) return nil, err } // Even if we have a dockerclient, the daemon might not be running. Ping it // to ensure it's up. err = client.Ping() if err != nil { log.Error("Unable to ping docker daemon. Ensure docker is running", "endpoint", endpoint, "err", err) return nil, err } return &DockerGoClient{ dockerClient: client, }, nil }
func main() { client, err := docker.NewVersionedClient("unix:///var/run/docker.sock", "1.17") if err != nil { fmt.Println(err.Error()) return } execOptions := docker.CreateExecOptions{ AttachStdout: true, AttachStdin: false, Cmd: []string{"date"}, Container: "omega-abc", } exec, err := client.CreateExec(execOptions) if err != nil { log.Fatalln("create exec has error: ", err) } var squidLogs bytes.Buffer err = client.StartExec(exec.ID, docker.StartExecOptions{ OutputStream: &squidLogs, }) if err != nil { log.Fatal(err) } for { tmp, _ := client.InspectExec(exec.ID) if !tmp.Running { break } time.Sleep(100 * time.Millisecond) } log.Println(squidLogs.String()) }
func main() { client, err := docker.NewVersionedClient("unix:///var/run/docker.sock", "1.17") if err != nil { fmt.Println(err) return } result, err := client.TopContainer("omega-cadvisor", "aux") if err != nil { fmt.Println(err) return } fmt.Println(result.Titles) for _, process := range result.Processes { for i, processInfo := range process { fmt.Println(result.Titles[i], ": ", processInfo) } } /* [USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND] USER : root PID : 13677 %CPU : 1.7 %MEM : 0.7 VSZ : 408232 RSS : 31728 TTY : ? STAT : Ssl START : Nov13 TIME : 64:25 COMMAND : /usr/bin/cadvisor -logtostderr -port=9007 */ }
// FindAvailableVersions tests each supported version and returns a slice // of available versions FindAvailableVersions() []DockerVersion } type factory struct { endpoint string lock sync.Mutex clients map[DockerVersion]dockeriface.Client } // newVersionedClient is a variable such that the implementation can be // swapped out for unit tests var newVersionedClient = func(endpoint, version string) (dockeriface.Client, error) { return docker.NewVersionedClient(endpoint, version) } func NewFactory(endpoint string) Factory { return &factory{ endpoint: endpoint, clients: make(map[DockerVersion]dockeriface.Client), } } func (f *factory) GetDefaultClient() (dockeriface.Client, error) { return f.GetClient(defaultVersion) } func (f *factory) GetClient(version DockerVersion) (dockeriface.Client, error) { client, ok := f.clients[version]
// Client returns a Docker client for the given Docker machine func Client(name string) (*docker.Client, *dockerclient.Client, error) { output, _, err := localcmd.New(dockerMachineBinary()).Args("env", name).Output() if err != nil { return nil, nil, ErrDockerMachineExec("env", err) } scanner := bufio.NewScanner(bytes.NewBufferString(output)) var ( dockerHost, certPath string tlsVerify bool ) prefix := "export " if runtime.GOOS == "windows" { prefix = "SET " } for scanner.Scan() { line := scanner.Text() if strings.HasPrefix(line, prefix) { line = strings.TrimPrefix(line, prefix) parts := strings.SplitN(line, "=", 2) if len(parts) != 2 { continue } switch strings.ToUpper(parts[0]) { case "DOCKER_HOST": dockerHost = strings.Trim(parts[1], "\"") case "DOCKER_CERT_PATH": certPath = strings.Trim(parts[1], "\"") case "DOCKER_TLS_VERIFY": tlsVerify = len(parts[1]) > 0 } } } var client *docker.Client if len(certPath) > 0 { cert := filepath.Join(certPath, "cert.pem") key := filepath.Join(certPath, "key.pem") ca := filepath.Join(certPath, "ca.pem") client, err = docker.NewVersionedTLSClient(dockerHost, cert, key, ca, "") } else { client, err = docker.NewVersionedClient(dockerHost, "") } if err != nil { return nil, nil, errors.NewError("could not get Docker client for machine %s", name).WithCause(err) } client.SkipServerVersionCheck = true var httpClient *http.Client if len(certPath) > 0 { tlscOptions := tlsconfig.Options{ CAFile: filepath.Join(certPath, "ca.pem"), CertFile: filepath.Join(certPath, "cert.pem"), KeyFile: filepath.Join(certPath, "key.pem"), InsecureSkipVerify: !tlsVerify, } tlsc, tlsErr := tlsconfig.Client(tlscOptions) if tlsErr != nil { return nil, nil, errors.NewError("could not create TLS config client for machine %s", name).WithCause(tlsErr) } httpClient = &http.Client{ Transport: net.SetTransportDefaults(&http.Transport{ TLSClientConfig: tlsc, }), } } engineAPIClient, err := dockerclient.NewClient(dockerHost, "", httpClient, nil) if err != nil { return nil, nil, errors.NewError("cannot create Docker engine API client").WithCause(err) } return client, engineAPIClient, nil }