github.com/click2cloud/libcompose@v0.4.1-0.20170816121048-7c20f79ac6b9/docker/client/client.go (about) 1 package client 2 3 import ( 4 "fmt" 5 "net/http" 6 "os" 7 "path/filepath" 8 "runtime" 9 10 cliconfig "github.com/docker/cli/cli/config" 11 "github.com/docker/docker/client" 12 "github.com/docker/docker/pkg/homedir" 13 "github.com/docker/go-connections/sockets" 14 "github.com/docker/go-connections/tlsconfig" 15 "github.com/Click2Cloud/libcompose/version" 16 ) 17 18 const ( 19 // DefaultAPIVersion is the default docker API version set by libcompose 20 DefaultAPIVersion = "v1.20" 21 defaultTrustKeyFile = "key.json" 22 defaultCaFile = "ca.pem" 23 defaultKeyFile = "key.pem" 24 defaultCertFile = "cert.pem" 25 ) 26 27 var ( 28 dockerCertPath = os.Getenv("DOCKER_CERT_PATH") 29 ) 30 31 func init() { 32 if dockerCertPath == "" { 33 dockerCertPath = cliconfig.Dir() 34 } 35 } 36 37 // Options holds docker client options (host, tls, ..) 38 type Options struct { 39 TLS bool 40 TLSVerify bool 41 TLSCAFile string 42 TLSCertFile string 43 TLSKeyFile string 44 TrustKey string 45 Host string 46 APIVersion string 47 } 48 49 // Create creates a docker client based on the specified options. 50 func Create(c Options) (client.APIClient, error) { 51 if c.Host == "" { 52 if os.Getenv("DOCKER_API_VERSION") == "" { 53 os.Setenv("DOCKER_API_VERSION", DefaultAPIVersion) 54 } 55 client, err := client.NewEnvClient() 56 if err != nil { 57 return nil, err 58 } 59 return client, nil 60 } 61 62 apiVersion := c.APIVersion 63 if apiVersion == "" { 64 apiVersion = DefaultAPIVersion 65 } 66 67 if c.TLSCAFile == "" { 68 c.TLSCAFile = filepath.Join(dockerCertPath, defaultCaFile) 69 } 70 if c.TLSCertFile == "" { 71 c.TLSCertFile = filepath.Join(dockerCertPath, defaultCertFile) 72 } 73 if c.TLSKeyFile == "" { 74 c.TLSKeyFile = filepath.Join(dockerCertPath, defaultKeyFile) 75 } 76 if c.TrustKey == "" { 77 c.TrustKey = filepath.Join(homedir.Get(), ".docker", defaultTrustKeyFile) 78 } 79 if c.TLSVerify { 80 c.TLS = true 81 } 82 83 84 var httpClient *http.Client 85 if c.TLS { 86 tlsOptions := tlsconfig.Options{ 87 CAFile: c.TLSCAFile, 88 CertFile: c.TLSCertFile, 89 KeyFile: c.TLSKeyFile, 90 InsecureSkipVerify: !c.TLSVerify, 91 } 92 config, err := tlsconfig.Client(tlsOptions) 93 if err != nil { 94 return nil, err 95 } 96 tr := &http.Transport{ 97 TLSClientConfig: config, 98 } 99 proto, addr, _, err := client.ParseHost(c.Host) 100 if err != nil { 101 return nil, err 102 } 103 104 if err := sockets.ConfigureTransport(tr, proto, addr); err != nil { 105 return nil, err 106 } 107 108 httpClient = &http.Client{ 109 Transport: tr, 110 } 111 } 112 113 customHeaders := map[string]string{} 114 customHeaders["User-Agent"] = fmt.Sprintf("Libcompose-Client/%s (%s)", version.VERSION, runtime.GOOS) 115 116 client, err := client.NewClient(c.Host, apiVersion, httpClient, customHeaders) 117 if err != nil { 118 return nil, err 119 } 120 return client, nil 121 }