本文整理汇总了Golang中github.com/docker/docker/api/client.NewDockerCli函数的典型用法代码示例。如果您正苦于以下问题:Golang NewDockerCli函数的具体用法?Golang NewDockerCli怎么用?Golang NewDockerCli使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NewDockerCli函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: NewClient
// NewClient returns a new docker test client.
func NewClient() (
cli *client.DockerCli, stdout *io.PipeReader, stdoutPipe *io.PipeWriter) {
proto, addr, _ := DockerHost()
stdout, stdoutPipe = io.Pipe()
dockerCertPath := os.Getenv("DOCKER_CERT_PATH")
// Boot2docker use TLS per default, Jenkins not
if dockerCertPath != "" {
var (
tlsConfig tls.Config
)
tlsConfig.InsecureSkipVerify = true
flCert := filepath.Join(dockerCertPath, defaultCertFile)
flKey := filepath.Join(dockerCertPath, defaultKeyFile)
_, errCert := os.Stat(flCert)
_, errKey := os.Stat(flKey)
if errCert == nil && errKey == nil {
cert, err := tls.LoadX509KeyPair(flCert, flKey)
if err != nil {
log.Fatalf("Couldn't load X509 key pair: %s. Key encrypted?", err)
}
tlsConfig.Certificates = []tls.Certificate{cert}
}
// Avoid fallback to SSL protocols < TLS1.0
tlsConfig.MinVersion = tls.VersionTLS10
cli = client.NewDockerCli(nil, stdoutPipe, nil, nil, proto, addr, &tlsConfig)
} else {
cli = client.NewDockerCli(nil, stdoutPipe, nil, nil, proto, addr, nil)
}
return
}
示例2: main
func main() {
if reexec.Init() {
return
}
// Set terminal emulation based on platform as required.
stdin, stdout, stderr := term.StdStreams()
logrus.SetOutput(stderr)
flag.Merge(flag.CommandLine, clientFlags.FlagSet, commonFlags.FlagSet)
flag.Usage = func() {
fmt.Fprint(os.Stdout, "Usage: docker [OPTIONS] COMMAND [arg...]\n"+daemonUsage+" docker [ -h | --help | -v | --version ]\n\n")
fmt.Fprint(os.Stdout, "A self-sufficient runtime for containers.\n\nOptions:\n")
flag.CommandLine.SetOutput(os.Stdout)
flag.PrintDefaults()
help := "\nCommands:\n"
for _, cmd := range dockerCommands {
help += fmt.Sprintf(" %-10.10s%s\n", cmd.name, cmd.description)
}
help += "\nRun 'docker COMMAND --help' for more information on a command."
fmt.Fprintf(os.Stdout, "%s\n", help)
}
flag.Parse()
if *flVersion {
showVersion()
return
}
clientCli := client.NewDockerCli(stdin, stdout, stderr, clientFlags)
// TODO: remove once `-d` is retired
handleGlobalDaemonFlag()
if *flHelp {
// if global flag --help is present, regardless of what other options and commands there are,
// just print the usage.
flag.Usage()
return
}
c := cli.New(clientCli, daemonCli)
if err := c.Run(flag.Args()...); err != nil {
if sterr, ok := err.(cli.StatusError); ok {
if sterr.Status != "" {
fmt.Fprintln(os.Stderr, sterr.Status)
os.Exit(1)
}
os.Exit(sterr.StatusCode)
}
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
示例3: TestRunCidFileCleanupIfEmpty
// Ensure that CIDFile gets deleted if it's empty
// Perform this test by making `docker run` fail
func TestRunCidFileCleanupIfEmpty(t *testing.T) {
tmpDir, err := ioutil.TempDir("", "TestRunCidFile")
if err != nil {
t.Fatal(err)
}
tmpCidFile := path.Join(tmpDir, "cid")
cli := client.NewDockerCli(nil, ioutil.Discard, ioutil.Discard, testDaemonProto, testDaemonAddr, nil)
defer cleanup(globalEngine, t)
c := make(chan struct{})
go func() {
defer close(c)
if err := cli.CmdRun("--cidfile", tmpCidFile, unitTestImageID); err == nil {
t.Fatal("running without a command should haveve failed")
}
if _, err := os.Stat(tmpCidFile); err == nil {
t.Fatalf("empty CIDFile '%s' should've been deleted", tmpCidFile)
}
}()
defer os.RemoveAll(tmpDir)
setTimeout(t, "CmdRun timed out", 5*time.Second, func() {
<-c
})
}
示例4: BuildImage
func BuildImage(dockerfile string, name string) (string, error) {
cli := dockerCli.NewDockerCli(os.Stdin, os.Stdout, os.Stderr, nil, "unix", "/var/run/docker.sock", nil)
err := cli.CmdBuild("-t", name, strings.TrimSuffix(dockerfile, "Dockerfile"))
if err != nil {
return "", err
}
return GetImageId(name, "")
}
示例5: TestHttpsInfo
// TestHttpsInfo connects via two-way authenticated HTTPS to the info endpoint
func TestHttpsInfo(t *testing.T) {
cli := client.NewDockerCli(nil, ioutil.Discard, ioutil.Discard, testDaemonProto,
testDaemonHttpsAddr, getTlsConfig("client-cert.pem", "client-key.pem", t))
setTimeout(t, "Reading command output time out", 10*time.Second, func() {
if err := cli.CmdInfo(); err != nil {
t.Fatal(err)
}
})
}
示例6: NewCobraAdaptor
// NewCobraAdaptor returns a new handler
func NewCobraAdaptor(clientFlags *cliflags.ClientFlags) CobraAdaptor {
stdin, stdout, stderr := term.StdStreams()
dockerCli := client.NewDockerCli(stdin, stdout, stderr, clientFlags)
var rootCmd = &cobra.Command{
Use: "docker",
SilenceUsage: true,
SilenceErrors: true,
}
rootCmd.SetUsageTemplate(usageTemplate)
rootCmd.SetHelpTemplate(helpTemplate)
rootCmd.SetFlagErrorFunc(cli.FlagErrorFunc)
rootCmd.SetOutput(stdout)
rootCmd.AddCommand(
container.NewAttachCommand(dockerCli),
container.NewCreateCommand(dockerCli),
container.NewDiffCommand(dockerCli),
container.NewExportCommand(dockerCli),
container.NewKillCommand(dockerCli),
container.NewLogsCommand(dockerCli),
container.NewPauseCommand(dockerCli),
container.NewPortCommand(dockerCli),
container.NewRenameCommand(dockerCli),
container.NewRestartCommand(dockerCli),
container.NewRmCommand(dockerCli),
container.NewRunCommand(dockerCli),
container.NewStartCommand(dockerCli),
container.NewStatsCommand(dockerCli),
container.NewStopCommand(dockerCli),
container.NewTopCommand(dockerCli),
container.NewUnpauseCommand(dockerCli),
container.NewWaitCommand(dockerCli),
image.NewBuildCommand(dockerCli),
image.NewHistoryCommand(dockerCli),
image.NewImagesCommand(dockerCli),
image.NewLoadCommand(dockerCli),
image.NewRemoveCommand(dockerCli),
image.NewSaveCommand(dockerCli),
image.NewSearchCommand(dockerCli),
image.NewImportCommand(dockerCli),
image.NewTagCommand(dockerCli),
network.NewNetworkCommand(dockerCli),
system.NewEventsCommand(dockerCli),
system.NewVersionCommand(dockerCli),
volume.NewVolumeCommand(dockerCli),
)
rootCmd.PersistentFlags().BoolP("help", "h", false, "Print usage")
rootCmd.PersistentFlags().MarkShorthandDeprecated("help", "please use --help")
return CobraAdaptor{
rootCmd: rootCmd,
dockerCli: dockerCli,
}
}
示例7: newDockerClient
func newDockerClient() *client.DockerCli {
// Set terminal emulation based on platform as required.
stdin, stdout, stderr := term.StdStreams()
setDefaultConfFlag(flTrustKey, defaultTrustKeyFile)
if len(flHosts) > 1 {
log.Fatal("Please specify only one -H")
}
protoAddrParts := strings.SplitN(flHosts[0], "://", 2)
var (
cli *client.DockerCli
tlsConfig tls.Config
)
tlsConfig.InsecureSkipVerify = true
// Regardless of whether the user sets it to true or false, if they
// specify --tlsverify at all then we need to turn on tls
if flag.IsSet("-tlsverify") {
*flTls = true
}
// If we should verify the server, we need to load a trusted ca
if *flTlsVerify {
certPool := x509.NewCertPool()
file, err := ioutil.ReadFile(*flCa)
if err != nil {
log.Fatalf("Couldn't read ca cert %s: %s", *flCa, err)
}
certPool.AppendCertsFromPEM(file)
tlsConfig.RootCAs = certPool
tlsConfig.InsecureSkipVerify = false
}
// If tls is enabled, try to load and send client certificates
if *flTls || *flTlsVerify {
_, errCert := os.Stat(*flCert)
_, errKey := os.Stat(*flKey)
if errCert == nil && errKey == nil {
*flTls = true
cert, err := tls.LoadX509KeyPair(*flCert, *flKey)
if err != nil {
log.Fatalf("Couldn't load X509 key pair: %q. Make sure the key is encrypted", err)
}
tlsConfig.Certificates = []tls.Certificate{cert}
}
// Avoid fallback to SSL protocols < TLS1.0
tlsConfig.MinVersion = tls.VersionTLS10
}
cli = client.NewDockerCli(stdin, stdout, stderr, *flTrustKey, protoAddrParts[0], protoAddrParts[1], &tlsConfig)
return cli
}
示例8: TestRunDetach
// TestRunDetach checks attaching and detaching with the escape sequence.
func TestRunDetach(t *testing.T) {
stdout, stdoutPipe := io.Pipe()
cpty, tty, err := pty.Open()
if err != nil {
t.Fatal(err)
}
key, err := libtrust.GenerateECP256PrivateKey()
if err != nil {
t.Fatal(err)
}
cli := client.NewDockerCli(tty, stdoutPipe, ioutil.Discard, key, testDaemonProto, testDaemonAddr, nil)
defer cleanup(globalEngine, t)
ch := make(chan struct{})
go func() {
defer close(ch)
cli.CmdRun("-i", "-t", unitTestImageID, "cat")
}()
container := waitContainerStart(t, 10*time.Second)
state := setRaw(t, container)
defer unsetRaw(t, container, state)
setTimeout(t, "First read/write assertion timed out", 2*time.Second, func() {
if err := assertPipe("hello\n", "hello", stdout, cpty, 150); err != nil {
t.Fatal(err)
}
})
setTimeout(t, "Escape sequence timeout", 5*time.Second, func() {
cpty.Write([]byte{16})
time.Sleep(100 * time.Millisecond)
cpty.Write([]byte{17})
})
// wait for CmdRun to return
setTimeout(t, "Waiting for CmdRun timed out", 15*time.Second, func() {
<-ch
})
closeWrap(cpty, stdout, stdoutPipe)
time.Sleep(500 * time.Millisecond)
if !container.IsRunning() {
t.Fatal("The detached container should be still running")
}
setTimeout(t, "Waiting for container to die timed out", 20*time.Second, func() {
container.Kill()
})
}
示例9: TestRunDisconnectTty
// Expected behaviour: the process stay alive when the client disconnects
// but the client detaches.
func TestRunDisconnectTty(t *testing.T) {
stdin, stdinPipe := io.Pipe()
stdout, stdoutPipe := io.Pipe()
key, err := libtrust.GenerateECP256PrivateKey()
if err != nil {
t.Fatal(err)
}
cli := client.NewDockerCli(stdin, stdoutPipe, ioutil.Discard, key, testDaemonProto, testDaemonAddr, nil)
defer cleanup(globalEngine, t)
c1 := make(chan struct{})
go func() {
defer close(c1)
// We're simulating a disconnect so the return value doesn't matter. What matters is the
// fact that CmdRun returns.
if err := cli.CmdRun("-i", "-t", unitTestImageID, "/bin/cat"); err != nil {
log.Debugf("Error CmdRun: %s", err)
}
}()
container := waitContainerStart(t, 10*time.Second)
state := setRaw(t, container)
defer unsetRaw(t, container, state)
// Client disconnect after run -i should keep stdin out in TTY mode
setTimeout(t, "Read/Write assertion timed out", 2*time.Second, func() {
if err := assertPipe("hello\n", "hello", stdout, stdinPipe, 150); err != nil {
t.Fatal(err)
}
})
// Close pipes (simulate disconnect)
if err := closeWrap(stdin, stdinPipe, stdout, stdoutPipe); err != nil {
t.Fatal(err)
}
// wait for CmdRun to return
setTimeout(t, "Waiting for CmdRun timed out", 5*time.Second, func() {
<-c1
})
// In tty mode, we expect the process to stay alive even after client's stdin closes.
// Give some time to monitor to do his thing
container.WaitStop(500 * time.Millisecond)
if !container.IsRunning() {
t.Fatalf("/bin/cat should still be running after closing stdin (tty mode)")
}
}
示例10: TestRunExit
func TestRunExit(t *testing.T) {
stdin, stdinPipe := io.Pipe()
stdout, stdoutPipe := io.Pipe()
cli := client.NewDockerCli(stdin, stdoutPipe, ioutil.Discard, testDaemonProto, testDaemonAddr, nil)
defer cleanup(globalEngine, t)
c1 := make(chan struct{})
go func() {
cli.CmdRun("-i", unitTestImageID, "/bin/cat")
close(c1)
}()
setTimeout(t, "Read/Write assertion timed out", 2*time.Second, func() {
if err := assertPipe("hello\n", "hello", stdout, stdinPipe, 150); err != nil {
t.Fatal(err)
}
})
container := globalDaemon.List()[0]
// Closing /bin/cat stdin, expect it to exit
if err := stdin.Close(); err != nil {
t.Fatal(err)
}
// as the process exited, CmdRun must finish and unblock. Wait for it
setTimeout(t, "Waiting for CmdRun timed out", 10*time.Second, func() {
<-c1
go func() {
cli.CmdWait(container.ID)
}()
if _, err := bufio.NewReader(stdout).ReadString('\n'); err != nil {
t.Fatal(err)
}
})
// Make sure that the client has been disconnected
setTimeout(t, "The client should have been disconnected once the remote process exited.", 2*time.Second, func() {
// Expecting pipe i/o error, just check that read does not block
stdin.Read([]byte{})
})
// Cleanup pipes
if err := closeWrap(stdin, stdinPipe, stdout, stdoutPipe); err != nil {
t.Fatal(err)
}
}
示例11: TestHttpsInfoRogueCert
// TestHttpsInfoRogueCert connects via two-way authenticated HTTPS to the info endpoint
// by using a rogue client certificate and checks that it fails with the expected error.
func TestHttpsInfoRogueCert(t *testing.T) {
cli := client.NewDockerCli(nil, ioutil.Discard, ioutil.Discard, testDaemonProto,
testDaemonHttpsAddr, getTlsConfig("client-rogue-cert.pem", "client-rogue-key.pem", t))
setTimeout(t, "Reading command output time out", 10*time.Second, func() {
err := cli.CmdInfo()
if err == nil {
t.Fatal("Expected error but got nil")
}
if !strings.Contains(err.Error(), errBadCertificate) {
t.Fatalf("Expected error: %s, got instead: %s", errBadCertificate, err)
}
})
}
示例12: TestRunCidFileCheckIDLength
// #2098 - Docker cidFiles only contain short version of the containerId
//sudo docker run --cidfile /tmp/docker_test.cid ubuntu echo "test"
// TestRunCidFile tests that run --cidfile returns the longid
func TestRunCidFileCheckIDLength(t *testing.T) {
stdout, stdoutPipe := io.Pipe()
tmpDir, err := ioutil.TempDir("", "TestRunCidFile")
if err != nil {
t.Fatal(err)
}
tmpCidFile := path.Join(tmpDir, "cid")
cli := client.NewDockerCli(nil, stdoutPipe, ioutil.Discard, testDaemonProto, testDaemonAddr, nil)
defer cleanup(globalEngine, t)
c := make(chan struct{})
go func() {
defer close(c)
if err := cli.CmdRun("--cidfile", tmpCidFile, unitTestImageID, "ls"); err != nil {
t.Fatal(err)
}
}()
defer os.RemoveAll(tmpDir)
setTimeout(t, "Reading command output time out", 2*time.Second, func() {
cmdOutput, err := bufio.NewReader(stdout).ReadString('\n')
if err != nil {
t.Fatal(err)
}
if len(cmdOutput) < 1 {
t.Fatalf("'ls' should return something , not '%s'", cmdOutput)
}
//read the tmpCidFile
buffer, err := ioutil.ReadFile(tmpCidFile)
if err != nil {
t.Fatal(err)
}
id := string(buffer)
if len(id) != len("2bf44ea18873287bd9ace8a4cb536a7cbe134bed67e805fdf2f58a57f69b320c") {
t.Fatalf("--cidfile should be a long id, not '%s'", id)
}
//test that its a valid cid? (though the container is gone..)
//remove the file and dir.
})
setTimeout(t, "CmdRun timed out", 5*time.Second, func() {
<-c
})
}
示例13: TestRunDisconnect
// Expected behaviour: the process dies when the client disconnects
func TestRunDisconnect(t *testing.T) {
stdin, stdinPipe := io.Pipe()
stdout, stdoutPipe := io.Pipe()
key, err := libtrust.GenerateECP256PrivateKey()
if err != nil {
t.Fatal(err)
}
cli := client.NewDockerCli(stdin, stdoutPipe, ioutil.Discard, key, testDaemonProto, testDaemonAddr, nil)
defer cleanup(globalEngine, t)
c1 := make(chan struct{})
go func() {
// We're simulating a disconnect so the return value doesn't matter. What matters is the
// fact that CmdRun returns.
cli.CmdRun("-i", unitTestImageID, "/bin/cat")
close(c1)
}()
setTimeout(t, "Read/Write assertion timed out", 2*time.Second, func() {
if err := assertPipe("hello\n", "hello", stdout, stdinPipe, 150); err != nil {
t.Fatal(err)
}
})
// Close pipes (simulate disconnect)
if err := closeWrap(stdin, stdinPipe, stdout, stdoutPipe); err != nil {
t.Fatal(err)
}
// as the pipes are close, we expect the process to die,
// therefore CmdRun to unblock. Wait for CmdRun
setTimeout(t, "Waiting for CmdRun timed out", 2*time.Second, func() {
<-c1
})
// Client disconnect after run -i should cause stdin to be closed, which should
// cause /bin/cat to exit.
setTimeout(t, "Waiting for /bin/cat to exit timed out", 2*time.Second, func() {
container := globalDaemon.List()[0]
container.WaitStop(-1 * time.Second)
if container.IsRunning() {
t.Fatalf("/bin/cat is still running after closing stdin")
}
})
}
示例14: TestRunWorkdirExistsAndIsFile
// TestRunWorkdirExistsAndIsFile checks that if 'docker run -w' with existing file can be detected
func TestRunWorkdirExistsAndIsFile(t *testing.T) {
cli := client.NewDockerCli(nil, nil, ioutil.Discard, testDaemonProto, testDaemonAddr, nil)
defer cleanup(globalEngine, t)
c := make(chan struct{})
go func() {
defer close(c)
if err := cli.CmdRun("-w", "/bin/cat", unitTestImageID, "pwd"); err == nil {
t.Fatal("should have failed to run when using /bin/cat as working dir.")
}
}()
setTimeout(t, "CmdRun timed out", 5*time.Second, func() {
<-c
})
}
示例15: Build
func (s *BPacker) Build(endpoint string, certpath string, imagename string) {
cert := fmt.Sprintf(certFileFormat, certpath)
key := fmt.Sprintf(keyFileFormat, certpath)
ca := fmt.Sprintf(caFileFormat, certpath)
client, err := docker.NewTLSClient(endpoint, cert, key, ca)
outputbuf, errbuf := bytes.NewBuffer(nil), bytes.NewBuffer(nil)
dockerfileString := s.CreateDockerFile()
fmt.Println(dockerfileString)
ioutil.WriteFile("./Dockerfile", []byte(dockerfileString), os.ModePerm)
defer os.Remove("Dockerfile")
reader := strings.NewReader("")
inputbuf := ioutil.NopCloser(reader)
endpoint = strings.TrimPrefix(endpoint, fmt.Sprintf("%s://", DefaultProto))
dcli := dkr.NewDockerCli(inputbuf, outputbuf, errbuf, key, DefaultProto, endpoint, client.TLSConfig)
err = dcli.CmdBuild("--force-rm=true", "--rm=true", fmt.Sprintf("--tag=\"%s\"", imagename), "./")
fmt.Println(err)
fmt.Println(outputbuf)
}