├── .gitignore ├── LICENSE ├── README.md ├── auth.go ├── auth_test.go ├── dockerclient.go ├── dockerclient_test.go ├── engine_mock_test.go ├── example_responses.go ├── examples ├── events.go └── stats │ └── stats.go ├── interface.go ├── mockclient ├── mock.go └── mock_test.go ├── nopclient └── nop.go ├── tls.go ├── types.go └── utils.go /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled Object files, Static and Dynamic libs (Shared Objects) 2 | *.o 3 | *.a 4 | *.so 5 | 6 | # Folders 7 | _obj 8 | _test 9 | 10 | # Architecture specific extensions/prefixes 11 | *.[568vq] 12 | [568vq].out 13 | 14 | *.cgo1.go 15 | *.cgo2.c 16 | _cgo_defun.c 17 | _cgo_gotypes.go 18 | _cgo_export.* 19 | 20 | _testmain.go 21 | 22 | *.exe 23 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2014 Sam Alba 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Docker client library in Go 2 | =========================== 3 | [![GoDoc](http://godoc.org/github.com/samalba/dockerclient?status.png)](http://godoc.org/github.com/samalba/dockerclient) 4 | 5 | No longer well-maintained docker client library. Docker's supported engine 6 | API client for go is [docker/engine-api](http://github.com/docker/engine-api). 7 | 8 | # How to use it? 9 | 10 | Here is an example showing how to use it: 11 | 12 | ```go 13 | package main 14 | 15 | import ( 16 | "github.com/samalba/dockerclient" 17 | "log" 18 | "time" 19 | "os" 20 | ) 21 | 22 | // Callback used to listen to Docker's events 23 | func eventCallback(event *dockerclient.Event, ec chan error, args ...interface{}) { 24 | log.Printf("Received event: %#v\n", *event) 25 | } 26 | 27 | func main() { 28 | // Init the client 29 | docker, _ := dockerclient.NewDockerClient("unix:///var/run/docker.sock", nil) 30 | 31 | // Get only running containers 32 | containers, err := docker.ListContainers(false, false, "") 33 | if err != nil { 34 | log.Fatal(err) 35 | } 36 | for _, c := range containers { 37 | log.Println(c.Id, c.Names) 38 | } 39 | 40 | // Inspect the first container returned 41 | if len(containers) > 0 { 42 | id := containers[0].Id 43 | info, _ := docker.InspectContainer(id) 44 | log.Println(info) 45 | } 46 | 47 | // Build a docker image 48 | // some.tar contains the build context (Dockerfile any any files it needs to add/copy) 49 | dockerBuildContext, err := os.Open("some.tar") 50 | defer dockerBuildContext.Close() 51 | buildImageConfig := &dockerclient.BuildImage{ 52 | Context: dockerBuildContext, 53 | RepoName: "your_image_name", 54 | SuppressOutput: false, 55 | } 56 | reader, err := docker.BuildImage(buildImageConfig) 57 | if err != nil { 58 | log.Fatal(err) 59 | } 60 | 61 | // Create a container 62 | containerConfig := &dockerclient.ContainerConfig{ 63 | Image: "ubuntu:14.04", 64 | Cmd: []string{"bash"}, 65 | AttachStdin: true, 66 | Tty: true} 67 | containerId, err := docker.CreateContainer(containerConfig, "foobar", nil) 68 | if err != nil { 69 | log.Fatal(err) 70 | } 71 | 72 | // Start the container 73 | hostConfig := &dockerclient.HostConfig{} 74 | err = docker.StartContainer(containerId, hostConfig) 75 | if err != nil { 76 | log.Fatal(err) 77 | } 78 | 79 | // Stop the container (with 5 seconds timeout) 80 | docker.StopContainer(containerId, 5) 81 | 82 | // Listen to events 83 | docker.StartMonitorEvents(eventCallback, nil) 84 | 85 | // Hold the execution to look at the events coming 86 | time.Sleep(3600 * time.Second) 87 | } 88 | ``` 89 | 90 | # Maintainers 91 | 92 | List of people you can ping for feedback on Pull Requests or any questions. 93 | 94 | - [Sam Alba](https://github.com/samalba) 95 | - [Michael Crosby](https://github.com/crosbymichael) 96 | - [Andrea Luzzardi](https://github.com/aluzzardi) 97 | - [Victor Vieux](https://github.com/vieux) 98 | - [Evan Hazlett](https://github.com/ehazlett) 99 | - [Donald Huang](https://github.com/donhcd) 100 | -------------------------------------------------------------------------------- /auth.go: -------------------------------------------------------------------------------- 1 | package dockerclient 2 | 3 | import ( 4 | "bytes" 5 | "encoding/base64" 6 | "encoding/json" 7 | ) 8 | 9 | // AuthConfig hold parameters for authenticating with the docker registry 10 | type AuthConfig struct { 11 | Username string `json:"username,omitempty"` 12 | Password string `json:"password,omitempty"` 13 | Email string `json:"email,omitempty"` 14 | RegistryToken string `json:"registrytoken,omitempty"` 15 | } 16 | 17 | // encode the auth configuration struct into base64 for the X-Registry-Auth header 18 | func (c *AuthConfig) encode() (string, error) { 19 | var buf bytes.Buffer 20 | if err := json.NewEncoder(&buf).Encode(c); err != nil { 21 | return "", err 22 | } 23 | return base64.URLEncoding.EncodeToString(buf.Bytes()), nil 24 | } 25 | 26 | // ConfigFile holds parameters for authenticating during a BuildImage request 27 | type ConfigFile struct { 28 | Configs map[string]AuthConfig `json:"configs,omitempty"` 29 | rootPath string 30 | } 31 | 32 | // encode the configuration struct into base64 for the X-Registry-Config header 33 | func (c *ConfigFile) encode() (string, error) { 34 | var buf bytes.Buffer 35 | if err := json.NewEncoder(&buf).Encode(c); err != nil { 36 | return "", err 37 | } 38 | return base64.URLEncoding.EncodeToString(buf.Bytes()), nil 39 | } 40 | -------------------------------------------------------------------------------- /auth_test.go: -------------------------------------------------------------------------------- 1 | package dockerclient 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func TestAuthEncode(t *testing.T) { 8 | a := AuthConfig{Username: "foo", Password: "password", Email: "bar@baz.com"} 9 | expected := "eyJ1c2VybmFtZSI6ImZvbyIsInBhc3N3b3JkIjoicGFzc3dvcmQiLCJlbWFpbCI6ImJhckBiYXouY29tIn0K" 10 | got, _ := a.encode() 11 | 12 | if expected != got { 13 | t.Errorf("testAuthEncode failed. Expected [%s] got [%s]", expected, got) 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /dockerclient.go: -------------------------------------------------------------------------------- 1 | package dockerclient 2 | 3 | import ( 4 | "bytes" 5 | "crypto/tls" 6 | "encoding/json" 7 | "errors" 8 | "fmt" 9 | "io" 10 | "io/ioutil" 11 | "net/http" 12 | "net/url" 13 | "strconv" 14 | "strings" 15 | "sync/atomic" 16 | "time" 17 | ) 18 | 19 | var _ Client = (*DockerClient)(nil) 20 | 21 | const ( 22 | // APIVersion is currently hardcoded to v1.15 23 | // TODO: bump the API version or allow users to choose which API version to 24 | // use the client with. The current value does not make sense for many 25 | // methods, such as ContainerStats, StartMonitorStats, and StopAllMonitorStats 26 | // (v1.17) and 27 | // ListVolumes, {Remove,Create}Volume, ListNetworks, 28 | // {Inspect,Create,Connect,Disconnect,Remove}Network (v1.21) 29 | APIVersion = "v1.15" 30 | ) 31 | 32 | var ( 33 | ErrImageNotFound = errors.New("Image not found") 34 | ErrNotFound = errors.New("Not found") 35 | ErrConnectionRefused = errors.New("Cannot connect to the docker engine endpoint") 36 | 37 | defaultTimeout = 30 * time.Second 38 | ) 39 | 40 | type DockerClient struct { 41 | URL *url.URL 42 | HTTPClient *http.Client 43 | TLSConfig *tls.Config 44 | monitorStats int32 45 | eventStopChan chan (struct{}) 46 | } 47 | 48 | type Error struct { 49 | StatusCode int 50 | Status string 51 | msg string 52 | } 53 | 54 | func (e Error) Error() string { 55 | return fmt.Sprintf("%s: %s", e.Status, e.msg) 56 | } 57 | 58 | func NewDockerClient(daemonUrl string, tlsConfig *tls.Config) (*DockerClient, error) { 59 | return NewDockerClientTimeout(daemonUrl, tlsConfig, time.Duration(defaultTimeout), nil) 60 | } 61 | 62 | func NewDockerClientTimeout(daemonUrl string, tlsConfig *tls.Config, timeout time.Duration, setUserTimeout tcpFunc) (*DockerClient, error) { 63 | u, err := url.Parse(daemonUrl) 64 | if err != nil { 65 | return nil, err 66 | } 67 | if u.Scheme == "" || u.Scheme == "tcp" { 68 | if tlsConfig == nil { 69 | u.Scheme = "http" 70 | } else { 71 | u.Scheme = "https" 72 | } 73 | } 74 | httpClient := newHTTPClient(u, tlsConfig, timeout, setUserTimeout) 75 | return &DockerClient{u, httpClient, tlsConfig, 0, nil}, nil 76 | } 77 | 78 | func (client *DockerClient) doRequest(method string, path string, body []byte, headers map[string]string) ([]byte, error) { 79 | b := bytes.NewBuffer(body) 80 | 81 | reader, err := client.doStreamRequest(method, path, b, headers) 82 | if err != nil { 83 | return nil, err 84 | } 85 | 86 | defer reader.Close() 87 | data, err := ioutil.ReadAll(reader) 88 | if err != nil { 89 | return nil, err 90 | } 91 | return data, nil 92 | } 93 | 94 | func (client *DockerClient) doStreamRequest(method string, path string, in io.Reader, headers map[string]string) (io.ReadCloser, error) { 95 | if (method == "POST" || method == "PUT") && in == nil { 96 | in = bytes.NewReader(nil) 97 | } 98 | req, err := http.NewRequest(method, client.URL.String()+path, in) 99 | if err != nil { 100 | return nil, err 101 | } 102 | req.Header.Add("Content-Type", "application/json") 103 | if headers != nil { 104 | for header, value := range headers { 105 | req.Header.Add(header, value) 106 | } 107 | } 108 | resp, err := client.HTTPClient.Do(req) 109 | if err != nil { 110 | if !strings.Contains(err.Error(), "connection refused") && client.TLSConfig == nil { 111 | return nil, fmt.Errorf("%v. Are you trying to connect to a TLS-enabled daemon without TLS?", err) 112 | } 113 | if strings.Contains(err.Error(), "connection refused") { 114 | return nil, ErrConnectionRefused 115 | } 116 | return nil, err 117 | } 118 | if resp.StatusCode == 404 { 119 | defer resp.Body.Close() 120 | data, err := ioutil.ReadAll(resp.Body) 121 | if err != nil { 122 | return nil, ErrNotFound 123 | } 124 | if len(data) > 0 { 125 | // check if is image not found error 126 | if strings.Index(string(data), "No such image") != -1 { 127 | return nil, ErrImageNotFound 128 | } 129 | return nil, errors.New(string(data)) 130 | } 131 | return nil, ErrNotFound 132 | } 133 | if resp.StatusCode >= 400 { 134 | defer resp.Body.Close() 135 | data, err := ioutil.ReadAll(resp.Body) 136 | if err != nil { 137 | return nil, err 138 | } 139 | return nil, Error{StatusCode: resp.StatusCode, Status: resp.Status, msg: string(data)} 140 | } 141 | 142 | return resp.Body, nil 143 | } 144 | 145 | func (client *DockerClient) Info() (*Info, error) { 146 | uri := fmt.Sprintf("/%s/info", APIVersion) 147 | data, err := client.doRequest("GET", uri, nil, nil) 148 | if err != nil { 149 | return nil, err 150 | } 151 | ret := &Info{} 152 | err = json.Unmarshal(data, &ret) 153 | if err != nil { 154 | return nil, err 155 | } 156 | return ret, nil 157 | } 158 | 159 | func (client *DockerClient) ListContainers(all bool, size bool, filters string) ([]Container, error) { 160 | argAll := 0 161 | if all == true { 162 | argAll = 1 163 | } 164 | showSize := 0 165 | if size == true { 166 | showSize = 1 167 | } 168 | uri := fmt.Sprintf("/%s/containers/json?all=%d&size=%d", APIVersion, argAll, showSize) 169 | 170 | if filters != "" { 171 | uri += "&filters=" + filters 172 | } 173 | 174 | data, err := client.doRequest("GET", uri, nil, nil) 175 | if err != nil { 176 | return nil, err 177 | } 178 | ret := []Container{} 179 | err = json.Unmarshal(data, &ret) 180 | if err != nil { 181 | return nil, err 182 | } 183 | return ret, nil 184 | } 185 | 186 | func (client *DockerClient) InspectContainer(id string) (*ContainerInfo, error) { 187 | uri := fmt.Sprintf("/%s/containers/%s/json", APIVersion, id) 188 | data, err := client.doRequest("GET", uri, nil, nil) 189 | if err != nil { 190 | return nil, err 191 | } 192 | info := &ContainerInfo{} 193 | err = json.Unmarshal(data, info) 194 | if err != nil { 195 | return nil, err 196 | } 197 | return info, nil 198 | } 199 | 200 | func (client *DockerClient) CreateContainer(config *ContainerConfig, name string, auth *AuthConfig) (string, error) { 201 | data, err := json.Marshal(config) 202 | if err != nil { 203 | return "", err 204 | } 205 | uri := fmt.Sprintf("/%s/containers/create", APIVersion) 206 | if name != "" { 207 | v := url.Values{} 208 | v.Set("name", name) 209 | uri = fmt.Sprintf("%s?%s", uri, v.Encode()) 210 | } 211 | headers := map[string]string{} 212 | if auth != nil { 213 | encoded_auth, err := auth.encode() 214 | if err != nil { 215 | return "", err 216 | } 217 | headers["X-Registry-Auth"] = encoded_auth 218 | } 219 | data, err = client.doRequest("POST", uri, data, headers) 220 | if err != nil { 221 | return "", err 222 | } 223 | result := &RespContainersCreate{} 224 | err = json.Unmarshal(data, result) 225 | if err != nil { 226 | return "", fmt.Errorf(string(data)) 227 | } 228 | return result.Id, nil 229 | } 230 | 231 | func (client *DockerClient) ContainerLogs(id string, options *LogOptions) (io.ReadCloser, error) { 232 | v := url.Values{} 233 | v.Add("follow", strconv.FormatBool(options.Follow)) 234 | v.Add("stdout", strconv.FormatBool(options.Stdout)) 235 | v.Add("stderr", strconv.FormatBool(options.Stderr)) 236 | v.Add("timestamps", strconv.FormatBool(options.Timestamps)) 237 | if options.Tail > 0 { 238 | v.Add("tail", strconv.FormatInt(options.Tail, 10)) 239 | } 240 | 241 | uri := fmt.Sprintf("/%s/containers/%s/logs?%s", APIVersion, id, v.Encode()) 242 | req, err := http.NewRequest("GET", client.URL.String()+uri, nil) 243 | if err != nil { 244 | return nil, err 245 | } 246 | req.Header.Add("Content-Type", "application/json") 247 | resp, err := client.HTTPClient.Do(req) 248 | if err != nil { 249 | return nil, err 250 | } 251 | return resp.Body, nil 252 | } 253 | 254 | func (client *DockerClient) ContainerChanges(id string) ([]*ContainerChanges, error) { 255 | uri := fmt.Sprintf("/%s/containers/%s/changes", APIVersion, id) 256 | data, err := client.doRequest("GET", uri, nil, nil) 257 | if err != nil { 258 | return nil, err 259 | } 260 | changes := []*ContainerChanges{} 261 | err = json.Unmarshal(data, &changes) 262 | if err != nil { 263 | return nil, err 264 | } 265 | return changes, nil 266 | } 267 | 268 | func (client *DockerClient) ContainerStats(id string, stopChan <-chan struct{}) (<-chan StatsOrError, error) { 269 | uri := fmt.Sprintf("/%s/containers/%s/stats", APIVersion, id) 270 | resp, err := client.HTTPClient.Get(client.URL.String() + uri) 271 | if err != nil { 272 | return nil, err 273 | } 274 | 275 | decode := func(decoder *json.Decoder) decodingResult { 276 | var containerStats Stats 277 | if err := decoder.Decode(&containerStats); err != nil { 278 | return decodingResult{err: err} 279 | } else { 280 | return decodingResult{result: containerStats} 281 | } 282 | } 283 | decodingResultChan := client.readJSONStream(resp.Body, decode, stopChan) 284 | statsOrErrorChan := make(chan StatsOrError) 285 | go func() { 286 | for decodingResult := range decodingResultChan { 287 | stats, _ := decodingResult.result.(Stats) 288 | statsOrErrorChan <- StatsOrError{ 289 | Stats: stats, 290 | Error: decodingResult.err, 291 | } 292 | } 293 | close(statsOrErrorChan) 294 | }() 295 | return statsOrErrorChan, nil 296 | } 297 | 298 | func (client *DockerClient) readJSONStream(stream io.ReadCloser, decode func(*json.Decoder) decodingResult, stopChan <-chan struct{}) <-chan decodingResult { 299 | resultChan := make(chan decodingResult) 300 | 301 | go func() { 302 | decodeChan := make(chan decodingResult) 303 | 304 | go func() { 305 | decoder := json.NewDecoder(stream) 306 | for { 307 | decodeResult := decode(decoder) 308 | decodeChan <- decodeResult 309 | if decodeResult.err != nil { 310 | close(decodeChan) 311 | return 312 | } 313 | } 314 | }() 315 | 316 | defer close(resultChan) 317 | 318 | for { 319 | select { 320 | case <-stopChan: 321 | stream.Close() 322 | for range decodeChan { 323 | } 324 | return 325 | case decodeResult := <-decodeChan: 326 | resultChan <- decodeResult 327 | if decodeResult.err != nil { 328 | stream.Close() 329 | return 330 | } 331 | } 332 | } 333 | 334 | }() 335 | 336 | return resultChan 337 | } 338 | 339 | func (client *DockerClient) ExecCreate(config *ExecConfig) (string, error) { 340 | data, err := json.Marshal(config) 341 | if err != nil { 342 | return "", err 343 | } 344 | uri := fmt.Sprintf("/%s/containers/%s/exec", APIVersion, config.Container) 345 | resp, err := client.doRequest("POST", uri, data, nil) 346 | if err != nil { 347 | return "", err 348 | } 349 | var createExecResp struct { 350 | Id string 351 | } 352 | if err = json.Unmarshal(resp, &createExecResp); err != nil { 353 | return "", err 354 | } 355 | return createExecResp.Id, nil 356 | } 357 | 358 | func (client *DockerClient) ExecStart(id string, config *ExecConfig) error { 359 | data, err := json.Marshal(config) 360 | if err != nil { 361 | return err 362 | } 363 | 364 | uri := fmt.Sprintf("/%s/exec/%s/start", APIVersion, id) 365 | if _, err := client.doRequest("POST", uri, data, nil); err != nil { 366 | return err 367 | } 368 | 369 | return nil 370 | } 371 | 372 | func (client *DockerClient) ExecResize(id string, width, height int) error { 373 | v := url.Values{} 374 | 375 | w := strconv.Itoa(width) 376 | h := strconv.Itoa(height) 377 | 378 | v.Set("w", w) 379 | v.Set("h", h) 380 | 381 | uri := fmt.Sprintf("/%s/exec/%s/resize?%s", APIVersion, id, v.Encode()) 382 | if _, err := client.doRequest("POST", client.URL.String()+uri, nil, nil); err != nil { 383 | return err 384 | } 385 | 386 | return nil 387 | } 388 | 389 | func (client *DockerClient) AttachContainer(id string, options *AttachOptions) (io.ReadCloser, error) { 390 | v := url.Values{} 391 | if options != nil { 392 | if options.Logs { 393 | v.Set("logs", "1") 394 | } 395 | if options.Stream { 396 | v.Set("stream", "1") 397 | } 398 | if options.Stdin { 399 | v.Set("stdin", "1") 400 | } 401 | if options.Stdout { 402 | v.Set("stdout", "1") 403 | } 404 | if options.Stderr { 405 | v.Set("stderr", "1") 406 | } 407 | } 408 | uri := fmt.Sprintf("/%s/containers/%s/attach?%s", APIVersion, id, v.Encode()) 409 | return client.doStreamRequest("POST", uri, nil, nil) 410 | } 411 | 412 | func (client *DockerClient) StartContainer(id string, config *HostConfig) error { 413 | data, err := json.Marshal(config) 414 | if err != nil { 415 | return err 416 | } 417 | uri := fmt.Sprintf("/%s/containers/%s/start", APIVersion, id) 418 | _, err = client.doRequest("POST", uri, data, nil) 419 | if err != nil { 420 | return err 421 | } 422 | return nil 423 | } 424 | 425 | func (client *DockerClient) StopContainer(id string, timeout int) error { 426 | uri := fmt.Sprintf("/%s/containers/%s/stop?t=%d", APIVersion, id, timeout) 427 | _, err := client.doRequest("POST", uri, nil, nil) 428 | if err != nil { 429 | return err 430 | } 431 | return nil 432 | } 433 | 434 | func (client *DockerClient) RestartContainer(id string, timeout int) error { 435 | uri := fmt.Sprintf("/%s/containers/%s/restart?t=%d", APIVersion, id, timeout) 436 | _, err := client.doRequest("POST", uri, nil, nil) 437 | if err != nil { 438 | return err 439 | } 440 | return nil 441 | } 442 | 443 | func (client *DockerClient) KillContainer(id, signal string) error { 444 | uri := fmt.Sprintf("/%s/containers/%s/kill?signal=%s", APIVersion, id, signal) 445 | _, err := client.doRequest("POST", uri, nil, nil) 446 | if err != nil { 447 | return err 448 | } 449 | return nil 450 | } 451 | 452 | func (client *DockerClient) Wait(id string) <-chan WaitResult { 453 | ch := make(chan WaitResult) 454 | uri := fmt.Sprintf("/%s/containers/%s/wait", APIVersion, id) 455 | 456 | go func() { 457 | data, err := client.doRequest("POST", uri, nil, nil) 458 | if err != nil { 459 | ch <- WaitResult{ExitCode: -1, Error: err} 460 | return 461 | } 462 | 463 | var result struct { 464 | StatusCode int `json:"StatusCode"` 465 | } 466 | err = json.Unmarshal(data, &result) 467 | ch <- WaitResult{ExitCode: result.StatusCode, Error: err} 468 | }() 469 | return ch 470 | } 471 | 472 | func (client *DockerClient) MonitorEvents(options *MonitorEventsOptions, stopChan <-chan struct{}) (<-chan EventOrError, error) { 473 | v := url.Values{} 474 | if options != nil { 475 | if options.Since != 0 { 476 | v.Add("since", strconv.Itoa(options.Since)) 477 | } 478 | if options.Until != 0 { 479 | v.Add("until", strconv.Itoa(options.Until)) 480 | } 481 | if options.Filters != nil { 482 | filterMap := make(map[string][]string) 483 | events := []string{} 484 | if options.Filters.Event != "" { 485 | events = append(events, options.Filters.Event) 486 | } 487 | if len(options.Filters.Events) > 0 { 488 | events = append(events, options.Filters.Events...) 489 | } 490 | if len(events) > 0 { 491 | filterMap["event"] = events 492 | } 493 | 494 | images := []string{} 495 | if options.Filters.Image != "" { 496 | images = append(images, options.Filters.Image) 497 | } 498 | if len(options.Filters.Images) > 0 { 499 | images = append(images, options.Filters.Images...) 500 | } 501 | if len(images) > 0 { 502 | filterMap["image"] = images 503 | } 504 | 505 | containers := []string{} 506 | if options.Filters.Container != "" { 507 | containers = append(containers, options.Filters.Container) 508 | } 509 | if len(options.Filters.Containers) > 0 { 510 | containers = append(containers, options.Filters.Containers...) 511 | } 512 | if len(containers) > 0 { 513 | filterMap["container"] = containers 514 | } 515 | 516 | if len(filterMap) > 0 { 517 | filterJSONBytes, err := json.Marshal(filterMap) 518 | if err != nil { 519 | return nil, err 520 | } 521 | v.Add("filters", string(filterJSONBytes)) 522 | } 523 | } 524 | } 525 | uri := fmt.Sprintf("%s/%s/events?%s", client.URL.String(), APIVersion, v.Encode()) 526 | resp, err := client.HTTPClient.Get(uri) 527 | if err != nil { 528 | return nil, err 529 | } 530 | 531 | decode := func(decoder *json.Decoder) decodingResult { 532 | var event Event 533 | if err := decoder.Decode(&event); err != nil { 534 | return decodingResult{err: err} 535 | } else { 536 | return decodingResult{result: event} 537 | } 538 | } 539 | decodingResultChan := client.readJSONStream(resp.Body, decode, stopChan) 540 | eventOrErrorChan := make(chan EventOrError) 541 | go func() { 542 | for decodingResult := range decodingResultChan { 543 | event, _ := decodingResult.result.(Event) 544 | eventOrErrorChan <- EventOrError{ 545 | Event: event, 546 | Error: decodingResult.err, 547 | } 548 | } 549 | close(eventOrErrorChan) 550 | }() 551 | return eventOrErrorChan, nil 552 | } 553 | 554 | func (client *DockerClient) StartMonitorEvents(cb Callback, ec chan error, args ...interface{}) { 555 | client.eventStopChan = make(chan struct{}) 556 | 557 | go func() { 558 | eventErrChan, err := client.MonitorEvents(nil, client.eventStopChan) 559 | if err != nil { 560 | if ec != nil { 561 | ec <- err 562 | } 563 | return 564 | } 565 | 566 | for e := range eventErrChan { 567 | if e.Error != nil { 568 | if ec != nil { 569 | ec <- e.Error 570 | } 571 | return 572 | } 573 | cb(&e.Event, ec, args...) 574 | } 575 | }() 576 | } 577 | 578 | func (client *DockerClient) StopAllMonitorEvents() { 579 | if client.eventStopChan == nil { 580 | return 581 | } 582 | close(client.eventStopChan) 583 | } 584 | 585 | func (client *DockerClient) StartMonitorStats(id string, cb StatCallback, ec chan error, args ...interface{}) { 586 | atomic.StoreInt32(&client.monitorStats, 1) 587 | go client.getStats(id, cb, ec, args...) 588 | } 589 | 590 | func (client *DockerClient) getStats(id string, cb StatCallback, ec chan error, args ...interface{}) { 591 | uri := fmt.Sprintf("%s/%s/containers/%s/stats", client.URL.String(), APIVersion, id) 592 | resp, err := client.HTTPClient.Get(uri) 593 | if err != nil { 594 | ec <- err 595 | return 596 | } 597 | defer resp.Body.Close() 598 | 599 | dec := json.NewDecoder(resp.Body) 600 | for atomic.LoadInt32(&client.monitorStats) > 0 { 601 | var stats *Stats 602 | if err := dec.Decode(&stats); err != nil { 603 | ec <- err 604 | return 605 | } 606 | cb(id, stats, ec, args...) 607 | } 608 | } 609 | 610 | func (client *DockerClient) StopAllMonitorStats() { 611 | atomic.StoreInt32(&client.monitorStats, 0) 612 | } 613 | 614 | func (client *DockerClient) TagImage(nameOrID string, repo string, tag string, force bool) error { 615 | v := url.Values{} 616 | v.Set("repo", repo) 617 | v.Set("tag", tag) 618 | if force { 619 | v.Set("force", "1") 620 | } 621 | uri := fmt.Sprintf("/%s/images/%s/tag?%s", APIVersion, nameOrID, v.Encode()) 622 | if _, err := client.doRequest("POST", uri, nil, nil); err != nil { 623 | return err 624 | } 625 | return nil 626 | } 627 | 628 | func (client *DockerClient) Version() (*Version, error) { 629 | uri := fmt.Sprintf("/%s/version", APIVersion) 630 | data, err := client.doRequest("GET", uri, nil, nil) 631 | if err != nil { 632 | return nil, err 633 | } 634 | version := &Version{} 635 | err = json.Unmarshal(data, version) 636 | if err != nil { 637 | return nil, err 638 | } 639 | return version, nil 640 | } 641 | 642 | func (client *DockerClient) PushImage(name string, tag string, auth *AuthConfig) error { 643 | v := url.Values{} 644 | if tag != "" { 645 | v.Set("tag", tag) 646 | } 647 | uri := fmt.Sprintf("/%s/images/%s/push?%s", APIVersion, url.QueryEscape(name), v.Encode()) 648 | req, err := http.NewRequest("POST", client.URL.String()+uri, nil) 649 | if auth != nil { 650 | if encodedAuth, err := auth.encode(); err != nil { 651 | return err 652 | } else { 653 | req.Header.Add("X-Registry-Auth", encodedAuth) 654 | } 655 | } 656 | resp, err := client.HTTPClient.Do(req) 657 | if err != nil { 658 | return err 659 | } 660 | defer resp.Body.Close() 661 | var finalObj map[string]interface{} 662 | for decoder := json.NewDecoder(resp.Body); err == nil; err = decoder.Decode(&finalObj) { 663 | } 664 | if err != io.EOF { 665 | return err 666 | } 667 | if err, ok := finalObj["error"]; ok { 668 | return fmt.Errorf("%v", err) 669 | } 670 | return nil 671 | } 672 | 673 | func (client *DockerClient) PullImage(name string, auth *AuthConfig) error { 674 | v := url.Values{} 675 | v.Set("fromImage", name) 676 | uri := fmt.Sprintf("/%s/images/create?%s", APIVersion, v.Encode()) 677 | req, err := http.NewRequest("POST", client.URL.String()+uri, nil) 678 | if auth != nil { 679 | encoded_auth, err := auth.encode() 680 | if err != nil { 681 | return err 682 | } 683 | req.Header.Add("X-Registry-Auth", encoded_auth) 684 | } 685 | resp, err := client.HTTPClient.Do(req) 686 | if err != nil { 687 | return err 688 | } 689 | 690 | defer resp.Body.Close() 691 | if resp.StatusCode == 404 { 692 | return ErrNotFound 693 | } 694 | if resp.StatusCode >= 400 { 695 | data, err := ioutil.ReadAll(resp.Body) 696 | if err != nil { 697 | return err 698 | } 699 | return fmt.Errorf("%s", string(data)) 700 | } 701 | 702 | var finalObj map[string]interface{} 703 | for decoder := json.NewDecoder(resp.Body); err == nil; err = decoder.Decode(&finalObj) { 704 | } 705 | if err != io.EOF { 706 | return err 707 | } 708 | if err, ok := finalObj["error"]; ok { 709 | return fmt.Errorf("%v", err) 710 | } 711 | return nil 712 | } 713 | 714 | func (client *DockerClient) InspectImage(id string) (*ImageInfo, error) { 715 | uri := fmt.Sprintf("/%s/images/%s/json", APIVersion, id) 716 | data, err := client.doRequest("GET", uri, nil, nil) 717 | if err != nil { 718 | return nil, err 719 | } 720 | info := &ImageInfo{} 721 | err = json.Unmarshal(data, info) 722 | if err != nil { 723 | return nil, err 724 | } 725 | return info, nil 726 | } 727 | 728 | func (client *DockerClient) LoadImage(reader io.Reader) error { 729 | uri := fmt.Sprintf("/%s/images/load", APIVersion) 730 | _, err := client.doStreamRequest("POST", uri, reader, nil) 731 | return err 732 | } 733 | 734 | func (client *DockerClient) RemoveContainer(id string, force, volumes bool) error { 735 | argForce := 0 736 | argVolumes := 0 737 | if force == true { 738 | argForce = 1 739 | } 740 | if volumes == true { 741 | argVolumes = 1 742 | } 743 | args := fmt.Sprintf("force=%d&v=%d", argForce, argVolumes) 744 | uri := fmt.Sprintf("/%s/containers/%s?%s", APIVersion, id, args) 745 | _, err := client.doRequest("DELETE", uri, nil, nil) 746 | return err 747 | } 748 | 749 | func (client *DockerClient) ListImages(all bool) ([]*Image, error) { 750 | argAll := 0 751 | if all { 752 | argAll = 1 753 | } 754 | uri := fmt.Sprintf("/%s/images/json?all=%d", APIVersion, argAll) 755 | data, err := client.doRequest("GET", uri, nil, nil) 756 | if err != nil { 757 | return nil, err 758 | } 759 | var images []*Image 760 | if err := json.Unmarshal(data, &images); err != nil { 761 | return nil, err 762 | } 763 | return images, nil 764 | } 765 | 766 | func (client *DockerClient) RemoveImage(name string, force bool) ([]*ImageDelete, error) { 767 | argForce := 0 768 | if force { 769 | argForce = 1 770 | } 771 | 772 | args := fmt.Sprintf("force=%d", argForce) 773 | uri := fmt.Sprintf("/%s/images/%s?%s", APIVersion, name, args) 774 | data, err := client.doRequest("DELETE", uri, nil, nil) 775 | if err != nil { 776 | return nil, err 777 | } 778 | var imageDelete []*ImageDelete 779 | if err := json.Unmarshal(data, &imageDelete); err != nil { 780 | return nil, err 781 | } 782 | return imageDelete, nil 783 | } 784 | 785 | func (client *DockerClient) SearchImages(query, registry string, auth *AuthConfig) ([]ImageSearch, error) { 786 | term := query 787 | if registry != "" { 788 | term = registry + "/" + term 789 | } 790 | uri := fmt.Sprintf("/%s/images/search?term=%s", APIVersion, term) 791 | headers := map[string]string{} 792 | if auth != nil { 793 | if encodedAuth, err := auth.encode(); err != nil { 794 | return nil, err 795 | } else { 796 | headers["X-Registry-Auth"] = encodedAuth 797 | } 798 | } 799 | data, err := client.doRequest("GET", uri, nil, headers) 800 | if err != nil { 801 | return nil, err 802 | } 803 | var imageSearches []ImageSearch 804 | if err := json.Unmarshal(data, &imageSearches); err != nil { 805 | return nil, err 806 | } 807 | return imageSearches, nil 808 | } 809 | 810 | func (client *DockerClient) PauseContainer(id string) error { 811 | uri := fmt.Sprintf("/%s/containers/%s/pause", APIVersion, id) 812 | _, err := client.doRequest("POST", uri, nil, nil) 813 | if err != nil { 814 | return err 815 | } 816 | return nil 817 | } 818 | func (client *DockerClient) UnpauseContainer(id string) error { 819 | uri := fmt.Sprintf("/%s/containers/%s/unpause", APIVersion, id) 820 | _, err := client.doRequest("POST", uri, nil, nil) 821 | if err != nil { 822 | return err 823 | } 824 | return nil 825 | } 826 | 827 | func (client *DockerClient) RenameContainer(oldName string, newName string) error { 828 | uri := fmt.Sprintf("/containers/%s/rename?name=%s", oldName, newName) 829 | _, err := client.doRequest("POST", uri, nil, nil) 830 | return err 831 | } 832 | 833 | func (client *DockerClient) ImportImage(source string, repository string, tag string, tar io.Reader) (io.ReadCloser, error) { 834 | var fromSrc string 835 | v := &url.Values{} 836 | if source == "" { 837 | fromSrc = "-" 838 | } else { 839 | fromSrc = source 840 | } 841 | 842 | v.Set("fromSrc", fromSrc) 843 | v.Set("repo", repository) 844 | if tag != "" { 845 | v.Set("tag", tag) 846 | } 847 | 848 | var in io.Reader 849 | if fromSrc == "-" { 850 | in = tar 851 | } 852 | return client.doStreamRequest("POST", "/images/create?"+v.Encode(), in, nil) 853 | } 854 | 855 | func (client *DockerClient) BuildImage(image *BuildImage) (io.ReadCloser, error) { 856 | v := url.Values{} 857 | 858 | if image.DockerfileName != "" { 859 | v.Set("dockerfile", image.DockerfileName) 860 | } 861 | if image.RepoName != "" { 862 | v.Set("t", image.RepoName) 863 | } 864 | if image.RemoteURL != "" { 865 | v.Set("remote", image.RemoteURL) 866 | } 867 | if image.NoCache { 868 | v.Set("nocache", "1") 869 | } 870 | if image.Pull { 871 | v.Set("pull", "1") 872 | } 873 | if image.Remove { 874 | v.Set("rm", "1") 875 | } else { 876 | v.Set("rm", "0") 877 | } 878 | if image.ForceRemove { 879 | v.Set("forcerm", "1") 880 | } 881 | if image.SuppressOutput { 882 | v.Set("q", "1") 883 | } 884 | 885 | v.Set("memory", strconv.FormatInt(image.Memory, 10)) 886 | v.Set("memswap", strconv.FormatInt(image.MemorySwap, 10)) 887 | v.Set("cpushares", strconv.FormatInt(image.CpuShares, 10)) 888 | v.Set("cpuperiod", strconv.FormatInt(image.CpuPeriod, 10)) 889 | v.Set("cpuquota", strconv.FormatInt(image.CpuQuota, 10)) 890 | v.Set("cpusetcpus", image.CpuSetCpus) 891 | v.Set("cpusetmems", image.CpuSetMems) 892 | v.Set("cgroupparent", image.CgroupParent) 893 | if image.BuildArgs != nil { 894 | buildArgsJSON, err := json.Marshal(image.BuildArgs) 895 | if err != nil { 896 | return nil, err 897 | } 898 | v.Set("buildargs", string(buildArgsJSON)) 899 | } 900 | 901 | headers := make(map[string]string) 902 | if image.Config != nil { 903 | encoded_config, err := image.Config.encode() 904 | if err != nil { 905 | return nil, err 906 | } 907 | headers["X-Registry-Config"] = encoded_config 908 | } 909 | if image.Context != nil { 910 | headers["Content-Type"] = "application/tar" 911 | } 912 | 913 | uri := fmt.Sprintf("/%s/build?%s", APIVersion, v.Encode()) 914 | return client.doStreamRequest("POST", uri, image.Context, headers) 915 | } 916 | 917 | func (client *DockerClient) ListVolumes() ([]*Volume, error) { 918 | uri := fmt.Sprintf("/%s/volumes", APIVersion) 919 | data, err := client.doRequest("GET", uri, nil, nil) 920 | if err != nil { 921 | return nil, err 922 | } 923 | var volumesList VolumesListResponse 924 | if err := json.Unmarshal(data, &volumesList); err != nil { 925 | return nil, err 926 | } 927 | return volumesList.Volumes, nil 928 | } 929 | 930 | func (client *DockerClient) RemoveVolume(name string) error { 931 | uri := fmt.Sprintf("/%s/volumes/%s", APIVersion, name) 932 | _, err := client.doRequest("DELETE", uri, nil, nil) 933 | return err 934 | } 935 | 936 | func (client *DockerClient) CreateVolume(request *VolumeCreateRequest) (*Volume, error) { 937 | data, err := json.Marshal(request) 938 | if err != nil { 939 | return nil, err 940 | } 941 | uri := fmt.Sprintf("/%s/volumes/create", APIVersion) 942 | data, err = client.doRequest("POST", uri, data, nil) 943 | if err != nil { 944 | return nil, err 945 | } 946 | volume := &Volume{} 947 | err = json.Unmarshal(data, volume) 948 | return volume, err 949 | } 950 | 951 | func (client *DockerClient) ListNetworks(filters string) ([]*NetworkResource, error) { 952 | uri := fmt.Sprintf("/%s/networks", APIVersion) 953 | 954 | if filters != "" { 955 | uri += "&filters=" + filters 956 | } 957 | 958 | data, err := client.doRequest("GET", uri, nil, nil) 959 | if err != nil { 960 | return nil, err 961 | } 962 | ret := []*NetworkResource{} 963 | err = json.Unmarshal(data, &ret) 964 | if err != nil { 965 | return nil, err 966 | } 967 | return ret, nil 968 | } 969 | 970 | func (client *DockerClient) InspectNetwork(id string) (*NetworkResource, error) { 971 | uri := fmt.Sprintf("/%s/networks/%s", APIVersion, id) 972 | 973 | data, err := client.doRequest("GET", uri, nil, nil) 974 | if err != nil { 975 | return nil, err 976 | } 977 | ret := &NetworkResource{} 978 | err = json.Unmarshal(data, ret) 979 | if err != nil { 980 | return nil, err 981 | } 982 | 983 | return ret, nil 984 | } 985 | 986 | func (client *DockerClient) CreateNetwork(config *NetworkCreate) (*NetworkCreateResponse, error) { 987 | data, err := json.Marshal(config) 988 | if err != nil { 989 | return nil, err 990 | } 991 | uri := fmt.Sprintf("/%s/networks/create", APIVersion) 992 | data, err = client.doRequest("POST", uri, data, nil) 993 | if err != nil { 994 | return nil, err 995 | } 996 | ret := &NetworkCreateResponse{} 997 | err = json.Unmarshal(data, ret) 998 | return ret, nil 999 | } 1000 | 1001 | func (client *DockerClient) ConnectNetwork(id, container string) error { 1002 | data, err := json.Marshal(NetworkConnect{Container: container}) 1003 | if err != nil { 1004 | return err 1005 | } 1006 | uri := fmt.Sprintf("/%s/networks/%s/connect", APIVersion, id) 1007 | _, err = client.doRequest("POST", uri, data, nil) 1008 | return err 1009 | } 1010 | 1011 | func (client *DockerClient) DisconnectNetwork(id, container string, force bool) error { 1012 | data, err := json.Marshal(NetworkDisconnect{Container: container, Force: force}) 1013 | if err != nil { 1014 | return err 1015 | } 1016 | uri := fmt.Sprintf("/%s/networks/%s/disconnect", APIVersion, id) 1017 | _, err = client.doRequest("POST", uri, data, nil) 1018 | return err 1019 | } 1020 | 1021 | func (client *DockerClient) RemoveNetwork(id string) error { 1022 | uri := fmt.Sprintf("/%s/networks/%s", APIVersion, id) 1023 | _, err := client.doRequest("DELETE", uri, nil, nil) 1024 | return err 1025 | } 1026 | -------------------------------------------------------------------------------- /dockerclient_test.go: -------------------------------------------------------------------------------- 1 | package dockerclient 2 | 3 | import ( 4 | "bytes" 5 | "encoding/json" 6 | "fmt" 7 | "io" 8 | "os" 9 | "reflect" 10 | "strings" 11 | "testing" 12 | "time" 13 | 14 | "github.com/docker/docker/pkg/stdcopy" 15 | ) 16 | 17 | func assertEqual(t *testing.T, a interface{}, b interface{}, message string) { 18 | if a == b { 19 | return 20 | } 21 | if len(message) == 0 { 22 | message = fmt.Sprintf("%v != %v", a, b) 23 | } 24 | t.Fatal(message) 25 | } 26 | 27 | func testDockerClient(t *testing.T) *DockerClient { 28 | client, err := NewDockerClient(testHTTPServer.URL, nil) 29 | if err != nil { 30 | t.Fatal("Cannot init the docker client") 31 | } 32 | return client 33 | } 34 | 35 | func ExampleDockerClient_AttachContainer() { 36 | docker, err := NewDockerClient("unix:///var/run/docker.sock", nil) 37 | if err != nil { 38 | panic(err) 39 | } 40 | cID, err := docker.CreateContainer(&ContainerConfig{ 41 | Cmd: []string{"echo", "hi"}, 42 | Image: "busybox", 43 | }, "", nil) 44 | if err != nil { 45 | panic(err) 46 | } 47 | done := make(chan struct{}) 48 | if body, err := docker.AttachContainer(cID, &AttachOptions{ 49 | Stream: true, 50 | Stdout: true, 51 | }); err != nil { 52 | panic(err) 53 | } else { 54 | go func() { 55 | defer body.Close() 56 | if _, err := stdcopy.StdCopy(os.Stdout, os.Stderr, body); err != nil { 57 | panic(err) 58 | } 59 | close(done) 60 | }() 61 | } 62 | 63 | if err := docker.StartContainer(cID, nil); err != nil { 64 | panic(err) 65 | } 66 | <-done 67 | } 68 | 69 | func TestInfo(t *testing.T) { 70 | client := testDockerClient(t) 71 | info, err := client.Info() 72 | if err != nil { 73 | t.Fatal("Cannot get server info") 74 | } 75 | assertEqual(t, info.Images, int64(1), "") 76 | assertEqual(t, info.Containers, int64(2), "") 77 | } 78 | 79 | func TestKillContainer(t *testing.T) { 80 | client := testDockerClient(t) 81 | if err := client.KillContainer("23132acf2ac", "5"); err != nil { 82 | t.Fatal("cannot kill container: %s", err) 83 | } 84 | } 85 | 86 | func TestWait(t *testing.T) { 87 | client := testDockerClient(t) 88 | 89 | // This provokes an error on the server. 90 | select { 91 | case wr := <-client.Wait("1234"): 92 | assertEqual(t, wr.ExitCode, int(-1), "") 93 | case <-time.After(2 * time.Second): 94 | t.Fatal("Timed out!") 95 | } 96 | 97 | // Valid case. 98 | select { 99 | case wr := <-client.Wait("valid-id"): 100 | assertEqual(t, wr.ExitCode, int(0), "") 101 | case <-time.After(2 * time.Second): 102 | t.Fatal("Timed out!") 103 | } 104 | } 105 | 106 | func TestPullImage(t *testing.T) { 107 | client := testDockerClient(t) 108 | err := client.PullImage("busybox", nil) 109 | if err != nil { 110 | t.Fatal("unable to pull busybox") 111 | } 112 | 113 | err = client.PullImage("haproxy", nil) 114 | if err != nil { 115 | t.Fatal("unable to pull haproxy") 116 | } 117 | 118 | err = client.PullImage("wrongimg", nil) 119 | if err == nil { 120 | t.Fatal("should return error when it fails to pull wrongimg") 121 | } 122 | } 123 | 124 | func TestListContainers(t *testing.T) { 125 | client := testDockerClient(t) 126 | containers, err := client.ListContainers(true, false, "") 127 | if err != nil { 128 | t.Fatal("cannot get containers: %s", err) 129 | } 130 | assertEqual(t, len(containers), 1, "") 131 | cnt := containers[0] 132 | assertEqual(t, cnt.SizeRw, int64(0), "") 133 | } 134 | 135 | func TestContainerChanges(t *testing.T) { 136 | client := testDockerClient(t) 137 | changes, err := client.ContainerChanges("foobar") 138 | if err != nil { 139 | t.Fatal("cannot get container changes: %s", err) 140 | } 141 | assertEqual(t, len(changes), 3, "unexpected number of changes") 142 | c := changes[0] 143 | assertEqual(t, c.Path, "/dev", "unexpected") 144 | assertEqual(t, c.Kind, 0, "unexpected") 145 | } 146 | 147 | func TestListContainersWithSize(t *testing.T) { 148 | client := testDockerClient(t) 149 | containers, err := client.ListContainers(true, true, "") 150 | if err != nil { 151 | t.Fatal("cannot get containers: %s", err) 152 | } 153 | assertEqual(t, len(containers), 1, "") 154 | cnt := containers[0] 155 | assertEqual(t, cnt.SizeRw, int64(123), "") 156 | } 157 | 158 | func TestListContainersWithFilters(t *testing.T) { 159 | client := testDockerClient(t) 160 | containers, err := client.ListContainers(true, true, "{'id':['332375cfbc23edb921a21026314c3497674ba8bdcb2c85e0e65ebf2017f688ce']}") 161 | if err != nil { 162 | t.Fatal("cannot get containers: %s", err) 163 | } 164 | assertEqual(t, len(containers), 1, "") 165 | 166 | containers, err = client.ListContainers(true, true, "{'id':['332375cfbc23edb921a21026314c3497674ba8bdcb2c85e0e65ebf2017f688cf']}") 167 | if err != nil { 168 | t.Fatal("cannot get containers: %s", err) 169 | } 170 | assertEqual(t, len(containers), 0, "") 171 | } 172 | 173 | func TestContainerLogs(t *testing.T) { 174 | client := testDockerClient(t) 175 | containerId := "foobar" 176 | logOptions := &LogOptions{ 177 | Follow: true, 178 | Stdout: true, 179 | Stderr: true, 180 | Timestamps: true, 181 | Tail: 10, 182 | } 183 | logsReader, err := client.ContainerLogs(containerId, logOptions) 184 | if err != nil { 185 | t.Fatal("cannot read logs from server") 186 | } 187 | 188 | stdoutBuffer := new(bytes.Buffer) 189 | stderrBuffer := new(bytes.Buffer) 190 | if _, err = stdcopy.StdCopy(stdoutBuffer, stderrBuffer, logsReader); err != nil { 191 | t.Fatal("cannot read logs from logs reader") 192 | } 193 | stdoutLogs := strings.TrimSpace(stdoutBuffer.String()) 194 | stderrLogs := strings.TrimSpace(stderrBuffer.String()) 195 | stdoutLogLines := strings.Split(stdoutLogs, "\n") 196 | stderrLogLines := strings.Split(stderrLogs, "\n") 197 | if len(stdoutLogLines) != 5 { 198 | t.Fatalf("wrong number of stdout logs: len=%d", len(stdoutLogLines)) 199 | } 200 | if len(stderrLogLines) != 5 { 201 | t.Fatalf("wrong number of stderr logs: len=%d", len(stdoutLogLines)) 202 | } 203 | for i, line := range stdoutLogLines { 204 | expectedSuffix := fmt.Sprintf("Z line %d", 41+2*i) 205 | if !strings.HasSuffix(line, expectedSuffix) { 206 | t.Fatalf("expected stdout log line \"%s\" to end with \"%s\"", line, expectedSuffix) 207 | } 208 | } 209 | for i, line := range stderrLogLines { 210 | expectedSuffix := fmt.Sprintf("Z line %d", 40+2*i) 211 | if !strings.HasSuffix(line, expectedSuffix) { 212 | t.Fatalf("expected stderr log line \"%s\" to end with \"%s\"", line, expectedSuffix) 213 | } 214 | } 215 | } 216 | 217 | func TestContainerStats(t *testing.T) { 218 | client := testDockerClient(t) 219 | var expectedContainerStats Stats 220 | if err := json.Unmarshal([]byte(statsResp), &expectedContainerStats); err != nil { 221 | t.Fatalf("cannot parse expected resp: %s", err.Error()) 222 | } 223 | containerIds := []string{"foobar", "foo"} 224 | expectedResults := [][]StatsOrError{ 225 | {{Stats: expectedContainerStats}, {Error: fmt.Errorf("invalid character 'i' looking for beginning of value")}}, 226 | {{Stats: expectedContainerStats}, {Stats: expectedContainerStats}}, 227 | } 228 | 229 | for i := range containerIds { 230 | t.Logf("on outer iter %d\n", i) 231 | stopChan := make(chan struct{}) 232 | statsOrErrorChan, err := client.ContainerStats(containerIds[i], stopChan) 233 | if err != nil { 234 | t.Fatalf("cannot get stats from server: %s", err.Error()) 235 | } 236 | 237 | for j, expectedResult := range expectedResults[i] { 238 | t.Logf("on iter %d\n", j) 239 | containerStatsOrError := <-statsOrErrorChan 240 | if containerStatsOrError.Error != nil { 241 | if expectedResult.Error == nil { 242 | t.Fatalf("index %d, got unexpected error %v", j, containerStatsOrError.Error) 243 | } else if containerStatsOrError.Error.Error() == expectedResult.Error.Error() { 244 | // continue so that we don't try to 245 | // compare error values directly 246 | continue 247 | } else { 248 | t.Fatalf("index %d, expected error %q but got %q", j, expectedResult.Error, containerStatsOrError.Error) 249 | } 250 | } 251 | if !reflect.DeepEqual(containerStatsOrError, expectedResult) { 252 | t.Fatalf("index %d, got:\n%#v\nexpected:\n%#v", j, containerStatsOrError, expectedResult) 253 | } 254 | t.Logf("done with iter %d\n", j) 255 | } 256 | close(stopChan) 257 | t.Logf("done with outer iter %d\n", i) 258 | } 259 | } 260 | 261 | func TestMonitorEvents(t *testing.T) { 262 | client := testDockerClient(t) 263 | decoder := json.NewDecoder(bytes.NewBufferString(eventsResp)) 264 | var expectedEvents []Event 265 | for { 266 | var event Event 267 | if err := decoder.Decode(&event); err != nil { 268 | if err == io.EOF { 269 | break 270 | } else { 271 | t.Fatalf("cannot parse expected resp: %s", err.Error()) 272 | } 273 | } else { 274 | expectedEvents = append(expectedEvents, event) 275 | } 276 | } 277 | 278 | // test passing stop chan 279 | stopChan := make(chan struct{}) 280 | eventInfoChan, err := client.MonitorEvents(nil, stopChan) 281 | if err != nil { 282 | t.Fatalf("cannot get events from server: %s", err.Error()) 283 | } 284 | 285 | eventInfo := <-eventInfoChan 286 | if eventInfo.Error != nil || eventInfo.Event != expectedEvents[0] { 287 | t.Fatalf("got:\n%#v\nexpected:\n%#v", eventInfo, expectedEvents[0]) 288 | } 289 | close(stopChan) 290 | for i := 0; i < 3; i++ { 291 | _, ok := <-eventInfoChan 292 | if i == 2 && ok { 293 | t.Fatalf("read more than 2 events successfully after closing stopChan") 294 | } 295 | } 296 | 297 | // test when you don't pass stop chan 298 | eventInfoChan, err = client.MonitorEvents(nil, nil) 299 | if err != nil { 300 | t.Fatalf("cannot get events from server: %s", err.Error()) 301 | } 302 | 303 | for i, expectedEvent := range expectedEvents { 304 | t.Logf("on iter %d\n", i) 305 | eventInfo := <-eventInfoChan 306 | if eventInfo.Error != nil || eventInfo.Event != expectedEvent { 307 | t.Fatalf("index %d, got:\n%#v\nexpected:\n%#v", i, eventInfo, expectedEvent) 308 | } 309 | t.Logf("done with iter %d\n", i) 310 | } 311 | } 312 | 313 | func TestDockerClientInterface(t *testing.T) { 314 | iface := reflect.TypeOf((*Client)(nil)).Elem() 315 | test := testDockerClient(t) 316 | 317 | if !reflect.TypeOf(test).Implements(iface) { 318 | t.Fatalf("DockerClient does not implement the Client interface") 319 | } 320 | } 321 | -------------------------------------------------------------------------------- /engine_mock_test.go: -------------------------------------------------------------------------------- 1 | package dockerclient 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "io" 7 | "log" 8 | "net/http" 9 | "net/http/httptest" 10 | "strconv" 11 | "time" 12 | 13 | "github.com/docker/docker/pkg/ioutils" 14 | "github.com/docker/docker/pkg/jsonlog" 15 | "github.com/docker/docker/pkg/stdcopy" 16 | "github.com/gorilla/mux" 17 | ) 18 | 19 | var ( 20 | testHTTPServer *httptest.Server 21 | ) 22 | 23 | func init() { 24 | r := mux.NewRouter() 25 | baseURL := "/" + APIVersion 26 | r.HandleFunc(baseURL+"/info", handlerGetInfo).Methods("GET") 27 | r.HandleFunc(baseURL+"/containers/json", handlerGetContainers).Methods("GET") 28 | r.HandleFunc(baseURL+"/containers/{id}/logs", handleContainerLogs).Methods("GET") 29 | r.HandleFunc(baseURL+"/containers/{id}/changes", handleContainerChanges).Methods("GET") 30 | r.HandleFunc(baseURL+"/containers/{id}/stats", handleContainerStats).Methods("GET") 31 | r.HandleFunc(baseURL+"/containers/{id}/kill", handleContainerKill).Methods("POST") 32 | r.HandleFunc(baseURL+"/containers/{id}/wait", handleWait).Methods("POST") 33 | r.HandleFunc(baseURL+"/images/create", handleImagePull).Methods("POST") 34 | r.HandleFunc(baseURL+"/events", handleEvents).Methods("GET") 35 | testHTTPServer = httptest.NewServer(handlerAccessLog(r)) 36 | } 37 | 38 | func handlerAccessLog(handler http.Handler) http.Handler { 39 | logHandler := func(w http.ResponseWriter, r *http.Request) { 40 | log.Printf("%s \"%s %s\"", r.RemoteAddr, r.Method, r.URL) 41 | handler.ServeHTTP(w, r) 42 | } 43 | return http.HandlerFunc(logHandler) 44 | } 45 | 46 | func handleContainerKill(w http.ResponseWriter, r *http.Request) { 47 | fmt.Fprintf(w, "{%q:%q", "Id", "421373210afd132") 48 | } 49 | 50 | func handleWait(w http.ResponseWriter, r *http.Request) { 51 | vars := mux.Vars(r) 52 | if vars["id"] == "valid-id" { 53 | fmt.Fprintf(w, `{"StatusCode":0}`) 54 | } else { 55 | http.Error(w, "failed", 500) 56 | } 57 | } 58 | 59 | func handleImagePull(w http.ResponseWriter, r *http.Request) { 60 | imageName := r.URL.Query()["fromImage"][0] 61 | responses := []map[string]interface{}{{ 62 | "status": fmt.Sprintf("Pulling repository mydockerregistry/%s", imageName), 63 | }} 64 | switch imageName { 65 | case "busybox": 66 | responses = append(responses, map[string]interface{}{ 67 | "status": "Status: Image is up to date for mydockerregistry/busybox", 68 | }) 69 | case "haproxy": 70 | fmt.Fprintf(w, haproxyPullOutput) 71 | return 72 | default: 73 | errorMsg := fmt.Sprintf("Error: image %s not found", imageName) 74 | responses = append(responses, map[string]interface{}{ 75 | "errorDetail": map[string]interface{}{ 76 | "message": errorMsg, 77 | }, 78 | "error": errorMsg, 79 | }) 80 | } 81 | for _, response := range responses { 82 | json.NewEncoder(w).Encode(response) 83 | } 84 | } 85 | 86 | func handleContainerLogs(w http.ResponseWriter, r *http.Request) { 87 | var outStream, errStream io.Writer 88 | outStream = ioutils.NewWriteFlusher(w) 89 | 90 | // not sure how to test follow 91 | if err := r.ParseForm(); err != nil { 92 | http.Error(w, err.Error(), 500) 93 | } 94 | stdout, stderr := getBoolValue(r.Form.Get("stdout")), getBoolValue(r.Form.Get("stderr")) 95 | if stderr { 96 | errStream = stdcopy.NewStdWriter(outStream, stdcopy.Stderr) 97 | } 98 | if stdout { 99 | outStream = stdcopy.NewStdWriter(outStream, stdcopy.Stdout) 100 | } 101 | var i int 102 | if tail, err := strconv.Atoi(r.Form.Get("tail")); err == nil && tail > 0 { 103 | i = 50 - tail 104 | if i < 0 { 105 | i = 0 106 | } 107 | } 108 | for ; i < 50; i++ { 109 | line := fmt.Sprintf("line %d", i) 110 | if getBoolValue(r.Form.Get("timestamps")) { 111 | l := &jsonlog.JSONLog{Log: line, Created: time.Now().UTC()} 112 | line = fmt.Sprintf("%s %s", l.Created.Format(jsonlog.RFC3339NanoFixed), line) 113 | } 114 | if i%2 == 0 && stderr { 115 | fmt.Fprintln(errStream, line) 116 | } else if i%2 == 1 && stdout { 117 | fmt.Fprintln(outStream, line) 118 | } 119 | } 120 | } 121 | 122 | func handleContainerChanges(w http.ResponseWriter, r *http.Request) { 123 | writeHeaders(w, 200, "changes") 124 | body := `[ 125 | { 126 | "Path": "/dev", 127 | "Kind": 0 128 | }, 129 | { 130 | "Path": "/dev/kmsg", 131 | "Kind": 1 132 | }, 133 | { 134 | "Path": "/test", 135 | "Kind": 1 136 | } 137 | ]` 138 | w.Write([]byte(body)) 139 | } 140 | 141 | func handleContainerStats(w http.ResponseWriter, r *http.Request) { 142 | switch mux.Vars(r)["id"] { 143 | case "foobar": 144 | fmt.Fprintf(w, "%s invalidresp", statsResp) 145 | default: 146 | fmt.Fprintf(w, "%s %s", statsResp, statsResp) 147 | } 148 | } 149 | 150 | func getBoolValue(boolString string) bool { 151 | switch boolString { 152 | case "1": 153 | return true 154 | case "True": 155 | return true 156 | case "true": 157 | return true 158 | default: 159 | return false 160 | } 161 | } 162 | 163 | func writeHeaders(w http.ResponseWriter, code int, jobName string) { 164 | h := w.Header() 165 | h.Add("Content-Type", "application/json") 166 | if jobName != "" { 167 | h.Add("Job-Name", jobName) 168 | } 169 | w.WriteHeader(code) 170 | } 171 | 172 | func handlerGetInfo(w http.ResponseWriter, r *http.Request) { 173 | writeHeaders(w, 200, "info") 174 | body := `{ 175 | "Containers": 2, 176 | "Debug": 1, 177 | "Driver": "aufs", 178 | "DriverStatus": [["Root Dir", "/mnt/sda1/var/lib/docker/aufs"], 179 | ["Dirs", "0"]], 180 | "ExecutionDriver": "native-0.2", 181 | "IPv4Forwarding": 1, 182 | "Images": 1, 183 | "IndexServerAddress": "https://index.docker.io/v1/", 184 | "InitPath": "/usr/local/bin/docker", 185 | "InitSha1": "", 186 | "KernelVersion": "3.16.4-tinycore64", 187 | "MemoryLimit": 1, 188 | "NEventsListener": 0, 189 | "NFd": 10, 190 | "NGoroutines": 11, 191 | "OperatingSystem": "Boot2Docker 1.3.1 (TCL 5.4); master : a083df4 - Thu Jan 01 00:00:00 UTC 1970", 192 | "SwapLimit": 1}` 193 | w.Write([]byte(body)) 194 | } 195 | 196 | func handlerGetContainers(w http.ResponseWriter, r *http.Request) { 197 | writeHeaders(w, 200, "containers") 198 | body := `[ 199 | { 200 | "Status": "Up 39 seconds", 201 | "Ports": [ 202 | { 203 | "Type": "tcp", 204 | "PublicPort": 49163, 205 | "PrivatePort": 8080, 206 | "IP": "0.0.0.0" 207 | } 208 | ], 209 | "Names": [ 210 | "/trusting_heisenberg" 211 | ], 212 | "Image": "foo:latest", 213 | "Id": "332375cfbc23edb921a21026314c3497674ba8bdcb2c85e0e65ebf2017f688ce", 214 | "Created": 1415720105, 215 | "Command": "/bin/go-run" 216 | } 217 | ]` 218 | if v, ok := r.URL.Query()["size"]; ok { 219 | if v[0] == "1" { 220 | body = `[ 221 | { 222 | "Status": "Up 39 seconds", 223 | "Ports": [ 224 | { 225 | "Type": "tcp", 226 | "PublicPort": 49163, 227 | "PrivatePort": 8080, 228 | "IP": "0.0.0.0" 229 | } 230 | ], 231 | "Names": [ 232 | "/trusting_heisenberg" 233 | ], 234 | "Image": "foo:latest", 235 | "Id": "332375cfbc23edb921a21026314c3497674ba8bdcb2c85e0e65ebf2017f688ce", 236 | "Created": 1415720105, 237 | "SizeRootFs": 12345, 238 | "SizeRW": 123, 239 | "Command": "/bin/go-run" 240 | } 241 | ]` 242 | } 243 | } 244 | if v, ok := r.URL.Query()["filters"]; ok { 245 | if v[0] != "{'id':['332375cfbc23edb921a21026314c3497674ba8bdcb2c85e0e65ebf2017f688ce']}" { 246 | body = "[]" 247 | } 248 | } 249 | w.Write([]byte(body)) 250 | } 251 | 252 | func handleEvents(w http.ResponseWriter, r *http.Request) { 253 | w.Write([]byte(eventsResp)) 254 | } 255 | -------------------------------------------------------------------------------- /example_responses.go: -------------------------------------------------------------------------------- 1 | package dockerclient 2 | 3 | var haproxyPullOutput = `{"status":"The image you are pulling has been verified","id":"haproxy:1"} 4 | {"status":"Already exists","progressDetail":{},"id":"511136ea3c5a"}{"status":"Already exists","progressDetail":{},"id":"1aeada447715"}{"status":"Already exists","progressDetail":{},"id":"479215127fa7"}{"status":"Already exists","progressDetail":{},"id":"66301eb54a7d"}{"status":"Already exists","progressDetail":{},"id":"e3990b07573f"}{"status":"Already exists","progressDetail":{},"id":"ecb4b23ca7ce"}{"status":"Already exists","progressDetail":{},"id":"f453e940c177"}{"status":"Already exists","progressDetail":{},"id":"fc5ea1bc05ab"}{"status":"Already exists","progressDetail":{},"id":"380557f8f7b3"}{"status":"The image you are pulling has been verified","id":"haproxy:1.4"} 5 | {"status":"Already exists","progressDetail":{},"id":"511136ea3c5a"}{"status":"Already exists","progressDetail":{},"id":"1aeada447715"}{"status":"Already exists","progressDetail":{},"id":"479215127fa7"}{"status":"Already exists","progressDetail":{},"id":"63a1b9929e14"}{"status":"Already exists","progressDetail":{},"id":"af43bf7d176e"}{"status":"Already exists","progressDetail":{},"id":"851aac2d69aa"}{"status":"Already exists","progressDetail":{},"id":"345053a92c95"}{"status":"Already exists","progressDetail":{},"id":"b41231d429c9"}{"status":"The image you are pulling has been verified","id":"haproxy:1.4.25"} 6 | {"status":"Already exists","progressDetail":{},"id":"511136ea3c5a"}{"status":"Already exists","progressDetail":{},"id":"1aeada447715"}{"status":"Already exists","progressDetail":{},"id":"479215127fa7"}{"status":"Already exists","progressDetail":{},"id":"63a1b9929e14"}{"status":"Already exists","progressDetail":{},"id":"af43bf7d176e"}{"status":"Already exists","progressDetail":{},"id":"851aac2d69aa"}{"status":"Already exists","progressDetail":{},"id":"345053a92c95"}{"status":"Already exists","progressDetail":{},"id":"b41231d429c9"}{"status":"The image you are pulling has been verified","id":"haproxy:1.5"} 7 | {"status":"Already exists","progressDetail":{},"id":"511136ea3c5a"}{"status":"Already exists","progressDetail":{},"id":"1aeada447715"}{"status":"Already exists","progressDetail":{},"id":"479215127fa7"}{"status":"Already exists","progressDetail":{},"id":"66301eb54a7d"}{"status":"Already exists","progressDetail":{},"id":"e3990b07573f"}{"status":"Already exists","progressDetail":{},"id":"ecb4b23ca7ce"}{"status":"Already exists","progressDetail":{},"id":"f453e940c177"}{"status":"Already exists","progressDetail":{},"id":"fc5ea1bc05ab"}{"status":"Already exists","progressDetail":{},"id":"380557f8f7b3"}{"status":"The image you are pulling has been verified","id":"haproxy:1.5.10"} 8 | {"status":"Already exists","progressDetail":{},"id":"511136ea3c5a"}{"status":"Already exists","progressDetail":{},"id":"1aeada447715"}{"status":"Already exists","progressDetail":{},"id":"479215127fa7"}{"status":"Already exists","progressDetail":{},"id":"66301eb54a7d"}{"status":"Already exists","progressDetail":{},"id":"e3990b07573f"}{"status":"Already exists","progressDetail":{},"id":"ecb4b23ca7ce"}{"status":"Already exists","progressDetail":{},"id":"f453e940c177"}{"status":"Already exists","progressDetail":{},"id":"fc5ea1bc05ab"}{"status":"Already exists","progressDetail":{},"id":"380557f8f7b3"}{"status":"The image you are pulling has been verified","id":"haproxy:1.5.9"} 9 | {"status":"Already exists","progressDetail":{},"id":"511136ea3c5a"}{"status":"Already exists","progressDetail":{},"id":"1aeada447715"}{"status":"Already exists","progressDetail":{},"id":"479215127fa7"}{"status":"Already exists","progressDetail":{},"id":"66301eb54a7d"}{"status":"Already exists","progressDetail":{},"id":"e3990b07573f"}{"status":"Already exists","progressDetail":{},"id":"3d894e6f7e63"}{"status":"Already exists","progressDetail":{},"id":"4d949c40bc77"}{"status":"Already exists","progressDetail":{},"id":"55e031889365"}{"status":"Already exists","progressDetail":{},"id":"c7aa675e1876"}{"status":"The image you are pulling has been verified","id":"haproxy:latest"} 10 | {"status":"Already exists","progressDetail":{},"id":"511136ea3c5a"}{"status":"Already exists","progressDetail":{},"id":"1aeada447715"}{"status":"Already exists","progressDetail":{},"id":"479215127fa7"}{"status":"Already exists","progressDetail":{},"id":"66301eb54a7d"}{"status":"Already exists","progressDetail":{},"id":"e3990b07573f"}{"status":"Already exists","progressDetail":{},"id":"ecb4b23ca7ce"}{"status":"Already exists","progressDetail":{},"id":"f453e940c177"}{"status":"Already exists","progressDetail":{},"id":"fc5ea1bc05ab"}{"status":"Already exists","progressDetail":{},"id":"380557f8f7b3"}{"status":"Status: Image is up to date for haproxy"} 11 | ` 12 | 13 | var statsResp = `{"read":"2015-02-02T17:06:08.187833376-05:00","network":{"rx_bytes":99988,"rx_packets":928,"rx_errors":0,"rx_dropped":0,"tx_bytes":1786548,"tx_packets":877,"tx_errors":0,"tx_dropped":0},"cpu_stats":{"cpu_usage":{"total_usage":170018598,"percpu_usage":[170018598],"usage_in_kernelmode":30000000,"usage_in_usermode":70000000},"system_cpu_usage":9020930000000,"throttling_data":{"periods":0,"throttled_periods":0,"throttled_time":0}},"memory_stats":{"usage":18022400,"max_usage":20541440,"stats":{"active_anon":6213632,"active_file":176128,"cache":11808768,"hierarchical_memory_limit":9223372036854775807,"hierarchical_memsw_limit":9223372036854775807,"inactive_anon":0,"inactive_file":11632640,"mapped_file":5165056,"pgfault":2535,"pgmajfault":13,"pgpgin":4293,"pgpgout":1937,"rss":6213632,"rss_huge":2097152,"swap":0,"total_active_anon":6213632,"total_active_file":176128,"total_cache":11808768,"total_inactive_anon":0,"total_inactive_file":11632640,"total_mapped_file":5165056,"total_pgfault":2535,"total_pgmajfault":13,"total_pgpgin":4293,"total_pgpgout":1937,"total_rss":6213632,"total_rss_huge":2097152,"total_swap":0,"total_unevictable":0,"unevictable":0},"failcnt":0,"limit":1041051648},"blkio_stats":{"io_service_bytes_recursive":[{"major":7,"minor":0,"op":"Read","value":28672},{"major":7,"minor":0,"op":"Write","value":0},{"major":7,"minor":0,"op":"Sync","value":0},{"major":7,"minor":0,"op":"Async","value":28672},{"major":7,"minor":0,"op":"Total","value":28672},{"major":253,"minor":0,"op":"Read","value":28672},{"major":253,"minor":0,"op":"Write","value":0},{"major":253,"minor":0,"op":"Sync","value":0},{"major":253,"minor":0,"op":"Async","value":28672},{"major":253,"minor":0,"op":"Total","value":28672},{"major":253,"minor":7,"op":"Read","value":11718656},{"major":253,"minor":7,"op":"Write","value":0},{"major":253,"minor":7,"op":"Sync","value":0},{"major":253,"minor":7,"op":"Async","value":11718656},{"major":253,"minor":7,"op":"Total","value":11718656},{"major":202,"minor":0,"op":"Read","value":0},{"major":202,"minor":0,"op":"Write","value":0},{"major":202,"minor":0,"op":"Sync","value":0},{"major":202,"minor":0,"op":"Async","value":0},{"major":202,"minor":0,"op":"Total","value":0}],"io_serviced_recursive":[{"major":7,"minor":0,"op":"Read","value":7},{"major":7,"minor":0,"op":"Write","value":0},{"major":7,"minor":0,"op":"Sync","value":0},{"major":7,"minor":0,"op":"Async","value":7},{"major":7,"minor":0,"op":"Total","value":7},{"major":253,"minor":0,"op":"Read","value":7},{"major":253,"minor":0,"op":"Write","value":0},{"major":253,"minor":0,"op":"Sync","value":0},{"major":253,"minor":0,"op":"Async","value":7},{"major":253,"minor":0,"op":"Total","value":7},{"major":253,"minor":7,"op":"Read","value":312},{"major":253,"minor":7,"op":"Write","value":0},{"major":253,"minor":7,"op":"Sync","value":0},{"major":253,"minor":7,"op":"Async","value":312},{"major":253,"minor":7,"op":"Total","value":312},{"major":202,"minor":0,"op":"Read","value":0},{"major":202,"minor":0,"op":"Write","value":0},{"major":202,"minor":0,"op":"Sync","value":0},{"major":202,"minor":0,"op":"Async","value":0},{"major":202,"minor":0,"op":"Total","value":0}],"io_queue_recursive":[],"io_service_time_recursive":[],"io_wait_time_recursive":[],"io_merged_recursive":[],"io_time_recursive":[],"sectors_recursive":[]}}` 14 | 15 | var eventsResp = `{"status":"pull","id":"nginx:latest","time":1428620433}{"status":"create","id":"9b818c3b8291708fdcecd7c4086b75c222cb503be10a93d9c11040886032a48b","from":"nginx:latest","time":1428620433}{"status":"start","id":"9b818c3b8291708fdcecd7c4086b75c222cb503be10a93d9c11040886032a48b","from":"nginx:latest","time":1428620433}{"status":"die","id":"9b818c3b8291708fdcecd7c4086b75c222cb503be10a93d9c11040886032a48b","from":"nginx:latest","time":1428620442}{"status":"create","id":"352d0b412aae5a5d2b14ae9d88be59dc276602d9edb9dcc33e138e475b3e4720","from":"52.11.96.81/foobar/ubuntu:latest","time":1428620444}{"status":"start","id":"352d0b412aae5a5d2b14ae9d88be59dc276602d9edb9dcc33e138e475b3e4720","from":"52.11.96.81/foobar/ubuntu:latest","time":1428620444}{"status":"die","id":"352d0b412aae5a5d2b14ae9d88be59dc276602d9edb9dcc33e138e475b3e4720","from":"52.11.96.81/foobar/ubuntu:latest","time":1428620444}{"status":"pull","id":"debian:latest","time":1428620453}{"status":"create","id":"668887b5729946546b3072655dc6da08f0e3210111b68b704eb842adfce53f6c","from":"debian:latest","time":1428620453}{"status":"start","id":"668887b5729946546b3072655dc6da08f0e3210111b68b704eb842adfce53f6c","from":"debian:latest","time":1428620453}{"status":"die","id":"668887b5729946546b3072655dc6da08f0e3210111b68b704eb842adfce53f6c","from":"debian:latest","time":1428620453}{"status":"create","id":"eb4a19ec21ab29bbbffbf3ee2e2df9d99cb749780e1eff06a591cee5ba505180","from":"nginx:latest","time":1428620458}{"status":"start","id":"eb4a19ec21ab29bbbffbf3ee2e2df9d99cb749780e1eff06a591cee5ba505180","from":"nginx:latest","time":1428620458}{"status":"pause","id":"eb4a19ec21ab29bbbffbf3ee2e2df9d99cb749780e1eff06a591cee5ba505180","from":"nginx:latest","time":1428620462}{"status":"unpause","id":"eb4a19ec21ab29bbbffbf3ee2e2df9d99cb749780e1eff06a591cee5ba505180","from":"nginx:latest","time":1428620466}{"status":"die","id":"eb4a19ec21ab29bbbffbf3ee2e2df9d99cb749780e1eff06a591cee5ba505180","from":"nginx:latest","time":1428620469}` 16 | -------------------------------------------------------------------------------- /examples/events.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "github.com/samalba/dockerclient" 5 | "log" 6 | "os" 7 | "os/signal" 8 | "syscall" 9 | ) 10 | 11 | func eventCallback(e *dockerclient.Event, ec chan error, args ...interface{}) { 12 | log.Println(e) 13 | } 14 | 15 | var ( 16 | client *dockerclient.DockerClient 17 | ) 18 | 19 | func waitForInterrupt() { 20 | sigChan := make(chan os.Signal, 1) 21 | signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM, syscall.SIGQUIT) 22 | for _ = range sigChan { 23 | client.StopAllMonitorEvents() 24 | os.Exit(0) 25 | } 26 | } 27 | 28 | func main() { 29 | docker, err := dockerclient.NewDockerClient(os.Getenv("DOCKER_HOST"), nil) 30 | if err != nil { 31 | log.Fatal(err) 32 | } 33 | 34 | client = docker 35 | 36 | client.StartMonitorEvents(eventCallback, nil) 37 | 38 | waitForInterrupt() 39 | } 40 | -------------------------------------------------------------------------------- /examples/stats/stats.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "github.com/samalba/dockerclient" 5 | "log" 6 | "os" 7 | "os/signal" 8 | "syscall" 9 | ) 10 | 11 | func statCallback(id string, stat *dockerclient.Stats, ec chan error, args ...interface{}) { 12 | log.Println(stat) 13 | } 14 | 15 | func waitForInterrupt() { 16 | sigChan := make(chan os.Signal, 1) 17 | signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM, syscall.SIGQUIT) 18 | for _ = range sigChan { 19 | os.Exit(0) 20 | } 21 | } 22 | 23 | func main() { 24 | docker, err := dockerclient.NewDockerClient(os.Getenv("DOCKER_HOST"), nil) 25 | if err != nil { 26 | log.Fatal(err) 27 | } 28 | 29 | containerConfig := &dockerclient.ContainerConfig{Image: "busybox", Cmd: []string{"sh"}} 30 | containerId, err := docker.CreateContainer(containerConfig, "", nil) 31 | if err != nil { 32 | log.Fatal(err) 33 | } 34 | 35 | // Start the container 36 | err = docker.StartContainer(containerId, nil) 37 | if err != nil { 38 | log.Fatal(err) 39 | } 40 | docker.StartMonitorStats(containerId, statCallback, nil) 41 | 42 | waitForInterrupt() 43 | } 44 | -------------------------------------------------------------------------------- /interface.go: -------------------------------------------------------------------------------- 1 | package dockerclient 2 | 3 | import ( 4 | "io" 5 | ) 6 | 7 | type Callback func(*Event, chan error, ...interface{}) 8 | 9 | type StatCallback func(string, *Stats, chan error, ...interface{}) 10 | 11 | type Client interface { 12 | Info() (*Info, error) 13 | ListContainers(all, size bool, filters string) ([]Container, error) 14 | InspectContainer(id string) (*ContainerInfo, error) 15 | InspectImage(id string) (*ImageInfo, error) 16 | CreateContainer(config *ContainerConfig, name string, authConfig *AuthConfig) (string, error) 17 | ContainerLogs(id string, options *LogOptions) (io.ReadCloser, error) 18 | ContainerChanges(id string) ([]*ContainerChanges, error) 19 | // ContainerStats takes a container ID and an optional stop channel and 20 | // returns a StatsOrError channel. If an error is ever sent, then no 21 | // more stats will be sent on that channel. If a stop channel is 22 | // provided, events will stop being monitored after the stop channel is 23 | // closed. 24 | ContainerStats(id string, stopChan <-chan struct{}) (<-chan StatsOrError, error) 25 | ExecCreate(config *ExecConfig) (string, error) 26 | ExecStart(id string, config *ExecConfig) error 27 | ExecResize(id string, width, height int) error 28 | StartContainer(id string, config *HostConfig) error 29 | AttachContainer(id string, options *AttachOptions) (io.ReadCloser, error) 30 | StopContainer(id string, timeout int) error 31 | RestartContainer(id string, timeout int) error 32 | KillContainer(id, signal string) error 33 | Wait(id string) <-chan WaitResult 34 | // MonitorEvents takes options and an optional stop channel, and returns 35 | // an EventOrError channel. If an error is ever sent, then no more 36 | // events will be sent. If a stop channel is provided, events will stop 37 | // being monitored after the stop channel is closed. 38 | MonitorEvents(options *MonitorEventsOptions, stopChan <-chan struct{}) (<-chan EventOrError, error) 39 | StartMonitorEvents(cb Callback, ec chan error, args ...interface{}) 40 | StopAllMonitorEvents() 41 | StartMonitorStats(id string, cb StatCallback, ec chan error, args ...interface{}) 42 | StopAllMonitorStats() 43 | TagImage(nameOrID string, repo string, tag string, force bool) error 44 | Version() (*Version, error) 45 | PullImage(name string, auth *AuthConfig) error 46 | PushImage(name string, tag string, auth *AuthConfig) error 47 | LoadImage(reader io.Reader) error 48 | RemoveContainer(id string, force, volumes bool) error 49 | ListImages(all bool) ([]*Image, error) 50 | RemoveImage(name string, force bool) ([]*ImageDelete, error) 51 | SearchImages(query, registry string, auth *AuthConfig) ([]ImageSearch, error) 52 | PauseContainer(name string) error 53 | UnpauseContainer(name string) error 54 | RenameContainer(oldName string, newName string) error 55 | ImportImage(source string, repository string, tag string, tar io.Reader) (io.ReadCloser, error) 56 | BuildImage(image *BuildImage) (io.ReadCloser, error) 57 | ListVolumes() ([]*Volume, error) 58 | RemoveVolume(name string) error 59 | CreateVolume(request *VolumeCreateRequest) (*Volume, error) 60 | ListNetworks(filters string) ([]*NetworkResource, error) 61 | InspectNetwork(id string) (*NetworkResource, error) 62 | CreateNetwork(config *NetworkCreate) (*NetworkCreateResponse, error) 63 | ConnectNetwork(id, container string) error 64 | DisconnectNetwork(id, container string, force bool) error 65 | RemoveNetwork(id string) error 66 | } 67 | -------------------------------------------------------------------------------- /mockclient/mock.go: -------------------------------------------------------------------------------- 1 | package mockclient 2 | 3 | import ( 4 | "io" 5 | 6 | "github.com/samalba/dockerclient" 7 | "github.com/stretchr/testify/mock" 8 | ) 9 | 10 | type MockClient struct { 11 | mock.Mock 12 | } 13 | 14 | func NewMockClient() *MockClient { 15 | return &MockClient{} 16 | } 17 | 18 | func (client *MockClient) Info() (*dockerclient.Info, error) { 19 | args := client.Mock.Called() 20 | return args.Get(0).(*dockerclient.Info), args.Error(1) 21 | } 22 | 23 | func (client *MockClient) ListContainers(all bool, size bool, filters string) ([]dockerclient.Container, error) { 24 | args := client.Mock.Called(all, size, filters) 25 | return args.Get(0).([]dockerclient.Container), args.Error(1) 26 | } 27 | 28 | func (client *MockClient) InspectContainer(id string) (*dockerclient.ContainerInfo, error) { 29 | args := client.Mock.Called(id) 30 | return args.Get(0).(*dockerclient.ContainerInfo), args.Error(1) 31 | } 32 | 33 | func (client *MockClient) InspectImage(id string) (*dockerclient.ImageInfo, error) { 34 | args := client.Mock.Called(id) 35 | return args.Get(0).(*dockerclient.ImageInfo), args.Error(1) 36 | } 37 | 38 | func (client *MockClient) CreateContainer(config *dockerclient.ContainerConfig, name string, authConfig *dockerclient.AuthConfig) (string, error) { 39 | args := client.Mock.Called(config, name, authConfig) 40 | return args.String(0), args.Error(1) 41 | } 42 | 43 | func (client *MockClient) ContainerLogs(id string, options *dockerclient.LogOptions) (io.ReadCloser, error) { 44 | args := client.Mock.Called(id, options) 45 | return args.Get(0).(io.ReadCloser), args.Error(1) 46 | } 47 | 48 | func (client *MockClient) ContainerChanges(id string) ([]*dockerclient.ContainerChanges, error) { 49 | args := client.Mock.Called(id) 50 | return args.Get(0).([]*dockerclient.ContainerChanges), args.Error(1) 51 | } 52 | 53 | func (client *MockClient) ContainerStats(id string, stopChan <-chan struct{}) (<-chan dockerclient.StatsOrError, error) { 54 | args := client.Mock.Called(id, stopChan) 55 | return args.Get(0).(<-chan dockerclient.StatsOrError), args.Error(1) 56 | } 57 | 58 | func (client *MockClient) AttachContainer(id string, options *dockerclient.AttachOptions) (io.ReadCloser, error) { 59 | args := client.Mock.Called(id, options) 60 | return args.Get(0).(io.ReadCloser), args.Error(1) 61 | } 62 | 63 | func (client *MockClient) StartContainer(id string, config *dockerclient.HostConfig) error { 64 | args := client.Mock.Called(id, config) 65 | return args.Error(0) 66 | } 67 | 68 | func (client *MockClient) StopContainer(id string, timeout int) error { 69 | args := client.Mock.Called(id, timeout) 70 | return args.Error(0) 71 | } 72 | 73 | func (client *MockClient) RestartContainer(id string, timeout int) error { 74 | args := client.Mock.Called(id, timeout) 75 | return args.Error(0) 76 | } 77 | 78 | func (client *MockClient) KillContainer(id, signal string) error { 79 | args := client.Mock.Called(id, signal) 80 | return args.Error(0) 81 | } 82 | 83 | func (client *MockClient) Wait(id string) <-chan dockerclient.WaitResult { 84 | args := client.Mock.Called(id) 85 | return args.Get(0).(<-chan dockerclient.WaitResult) 86 | } 87 | 88 | func (client *MockClient) MonitorEvents(options *dockerclient.MonitorEventsOptions, stopChan <-chan struct{}) (<-chan dockerclient.EventOrError, error) { 89 | args := client.Mock.Called(options, stopChan) 90 | return args.Get(0).(<-chan dockerclient.EventOrError), args.Error(1) 91 | } 92 | 93 | func (client *MockClient) StartMonitorEvents(cb dockerclient.Callback, ec chan error, args ...interface{}) { 94 | client.Mock.Called(cb, ec, args) 95 | } 96 | 97 | func (client *MockClient) StopAllMonitorEvents() { 98 | client.Mock.Called() 99 | } 100 | 101 | func (client *MockClient) TagImage(nameOrID string, repo string, tag string, force bool) error { 102 | args := client.Mock.Called(nameOrID, repo, tag, force) 103 | return args.Error(0) 104 | } 105 | 106 | func (client *MockClient) StartMonitorStats(id string, cb dockerclient.StatCallback, ec chan error, args ...interface{}) { 107 | client.Mock.Called(id, cb, ec, args) 108 | } 109 | 110 | func (client *MockClient) StopAllMonitorStats() { 111 | client.Mock.Called() 112 | } 113 | 114 | func (client *MockClient) Version() (*dockerclient.Version, error) { 115 | args := client.Mock.Called() 116 | return args.Get(0).(*dockerclient.Version), args.Error(1) 117 | } 118 | 119 | func (client *MockClient) PullImage(name string, auth *dockerclient.AuthConfig) error { 120 | args := client.Mock.Called(name, auth) 121 | return args.Error(0) 122 | } 123 | 124 | func (client *MockClient) PushImage(name string, tag string, auth *dockerclient.AuthConfig) error { 125 | args := client.Mock.Called(name, tag, auth) 126 | return args.Error(0) 127 | } 128 | 129 | func (client *MockClient) LoadImage(reader io.Reader) error { 130 | args := client.Mock.Called(reader) 131 | return args.Error(0) 132 | } 133 | 134 | func (client *MockClient) RemoveContainer(id string, force, volumes bool) error { 135 | args := client.Mock.Called(id, force, volumes) 136 | return args.Error(0) 137 | } 138 | 139 | func (client *MockClient) ListImages(all bool) ([]*dockerclient.Image, error) { 140 | args := client.Mock.Called(all) 141 | return args.Get(0).([]*dockerclient.Image), args.Error(1) 142 | } 143 | 144 | func (client *MockClient) RemoveImage(name string, force bool) ([]*dockerclient.ImageDelete, error) { 145 | args := client.Mock.Called(name, force) 146 | return args.Get(0).([]*dockerclient.ImageDelete), args.Error(1) 147 | } 148 | 149 | func (client *MockClient) SearchImages(query, registry string, authConfig *dockerclient.AuthConfig) ([]dockerclient.ImageSearch, error) { 150 | args := client.Mock.Called(query, registry, authConfig) 151 | return args.Get(0).([]dockerclient.ImageSearch), args.Error(1) 152 | } 153 | 154 | func (client *MockClient) PauseContainer(name string) error { 155 | args := client.Mock.Called(name) 156 | return args.Error(0) 157 | } 158 | 159 | func (client *MockClient) UnpauseContainer(name string) error { 160 | args := client.Mock.Called(name) 161 | return args.Error(0) 162 | } 163 | 164 | func (client *MockClient) ExecCreate(config *dockerclient.ExecConfig) (string, error) { 165 | args := client.Mock.Called(config) 166 | return args.String(0), args.Error(1) 167 | } 168 | 169 | func (client *MockClient) ExecStart(id string, config *dockerclient.ExecConfig) error { 170 | args := client.Mock.Called(id, config) 171 | return args.Error(0) 172 | } 173 | 174 | func (client *MockClient) ExecResize(id string, width, height int) error { 175 | args := client.Mock.Called(id, width, height) 176 | return args.Error(0) 177 | } 178 | 179 | func (client *MockClient) RenameContainer(oldName string, newName string) error { 180 | args := client.Mock.Called(oldName, newName) 181 | return args.Error(0) 182 | } 183 | 184 | func (client *MockClient) ImportImage(source string, repository string, tag string, tar io.Reader) (io.ReadCloser, error) { 185 | args := client.Mock.Called(source, repository, tag, tar) 186 | return args.Get(0).(io.ReadCloser), args.Error(1) 187 | } 188 | 189 | func (client *MockClient) BuildImage(image *dockerclient.BuildImage) (io.ReadCloser, error) { 190 | args := client.Mock.Called(image) 191 | return args.Get(0).(io.ReadCloser), args.Error(1) 192 | } 193 | 194 | func (client *MockClient) ListVolumes() ([]*dockerclient.Volume, error) { 195 | args := client.Mock.Called() 196 | return args.Get(0).([]*dockerclient.Volume), args.Error(1) 197 | } 198 | 199 | func (client *MockClient) RemoveVolume(name string) error { 200 | args := client.Mock.Called(name) 201 | return args.Error(0) 202 | } 203 | 204 | func (client *MockClient) CreateVolume(request *dockerclient.VolumeCreateRequest) (*dockerclient.Volume, error) { 205 | args := client.Mock.Called(request) 206 | return args.Get(0).(*dockerclient.Volume), args.Error(1) 207 | } 208 | 209 | func (client *MockClient) ListNetworks(filters string) ([]*dockerclient.NetworkResource, error) { 210 | args := client.Mock.Called(filters) 211 | return args.Get(0).([]*dockerclient.NetworkResource), args.Error(1) 212 | } 213 | 214 | func (client *MockClient) InspectNetwork(id string) (*dockerclient.NetworkResource, error) { 215 | args := client.Mock.Called(id) 216 | return args.Get(0).(*dockerclient.NetworkResource), args.Error(1) 217 | } 218 | 219 | func (client *MockClient) CreateNetwork(config *dockerclient.NetworkCreate) (*dockerclient.NetworkCreateResponse, error) { 220 | args := client.Mock.Called(config) 221 | return args.Get(0).(*dockerclient.NetworkCreateResponse), args.Error(1) 222 | } 223 | 224 | func (client *MockClient) ConnectNetwork(id, container string) error { 225 | args := client.Mock.Called(id, container) 226 | return args.Error(0) 227 | } 228 | 229 | func (client *MockClient) DisconnectNetwork(id, container string, force bool) error { 230 | args := client.Mock.Called(id, container, force) 231 | return args.Error(0) 232 | } 233 | 234 | func (client *MockClient) RemoveNetwork(id string) error { 235 | args := client.Mock.Called(id) 236 | return args.Error(0) 237 | } 238 | -------------------------------------------------------------------------------- /mockclient/mock_test.go: -------------------------------------------------------------------------------- 1 | package mockclient 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | 7 | "github.com/samalba/dockerclient" 8 | ) 9 | 10 | func TestMock(t *testing.T) { 11 | mock := NewMockClient() 12 | mock.On("Version").Return(&dockerclient.Version{Version: "foo"}, nil).Once() 13 | 14 | v, err := mock.Version() 15 | if err != nil { 16 | t.Fatal(err) 17 | } 18 | if v.Version != "foo" { 19 | t.Fatal(v) 20 | } 21 | 22 | mock.Mock.AssertExpectations(t) 23 | } 24 | 25 | func TestMockInterface(t *testing.T) { 26 | iface := reflect.TypeOf((*dockerclient.Client)(nil)).Elem() 27 | mock := NewMockClient() 28 | 29 | if !reflect.TypeOf(mock).Implements(iface) { 30 | t.Fatalf("Mock does not implement the Client interface") 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /nopclient/nop.go: -------------------------------------------------------------------------------- 1 | package nopclient 2 | 3 | import ( 4 | "errors" 5 | "io" 6 | 7 | "github.com/samalba/dockerclient" 8 | ) 9 | 10 | var ( 11 | ErrNoEngine = errors.New("Engine no longer exists") 12 | ) 13 | 14 | type NopClient struct { 15 | } 16 | 17 | func NewNopClient() *NopClient { 18 | return &NopClient{} 19 | } 20 | 21 | func (client *NopClient) Info() (*dockerclient.Info, error) { 22 | return nil, ErrNoEngine 23 | } 24 | 25 | func (client *NopClient) ListContainers(all bool, size bool, filters string) ([]dockerclient.Container, error) { 26 | return nil, ErrNoEngine 27 | } 28 | 29 | func (client *NopClient) InspectContainer(id string) (*dockerclient.ContainerInfo, error) { 30 | return nil, ErrNoEngine 31 | } 32 | 33 | func (client *NopClient) InspectImage(id string) (*dockerclient.ImageInfo, error) { 34 | return nil, ErrNoEngine 35 | } 36 | 37 | func (client *NopClient) CreateContainer(config *dockerclient.ContainerConfig, name string, authConfig *dockerclient.AuthConfig) (string, error) { 38 | return "", ErrNoEngine 39 | } 40 | 41 | func (client *NopClient) ContainerLogs(id string, options *dockerclient.LogOptions) (io.ReadCloser, error) { 42 | return nil, ErrNoEngine 43 | } 44 | 45 | func (client *NopClient) ContainerChanges(id string) ([]*dockerclient.ContainerChanges, error) { 46 | return nil, ErrNoEngine 47 | } 48 | 49 | func (client *NopClient) ContainerStats(id string, stopChan <-chan struct{}) (<-chan dockerclient.StatsOrError, error) { 50 | return nil, ErrNoEngine 51 | } 52 | 53 | func (client *NopClient) AttachContainer(id string, options *dockerclient.AttachOptions) (io.ReadCloser, error) { 54 | return nil, ErrNoEngine 55 | } 56 | 57 | func (client *NopClient) StartContainer(id string, config *dockerclient.HostConfig) error { 58 | return ErrNoEngine 59 | } 60 | 61 | func (client *NopClient) StopContainer(id string, timeout int) error { 62 | return ErrNoEngine 63 | } 64 | 65 | func (client *NopClient) RestartContainer(id string, timeout int) error { 66 | return ErrNoEngine 67 | } 68 | 69 | func (client *NopClient) KillContainer(id, signal string) error { 70 | return ErrNoEngine 71 | } 72 | 73 | func (client *NopClient) Wait(id string) <-chan dockerclient.WaitResult { 74 | return nil 75 | } 76 | 77 | func (client *NopClient) MonitorEvents(options *dockerclient.MonitorEventsOptions, stopChan <-chan struct{}) (<-chan dockerclient.EventOrError, error) { 78 | return nil, ErrNoEngine 79 | } 80 | 81 | func (client *NopClient) StartMonitorEvents(cb dockerclient.Callback, ec chan error, args ...interface{}) { 82 | return 83 | } 84 | 85 | func (client *NopClient) StopAllMonitorEvents() { 86 | return 87 | } 88 | 89 | func (client *NopClient) TagImage(nameOrID string, repo string, tag string, force bool) error { 90 | return ErrNoEngine 91 | } 92 | 93 | func (client *NopClient) StartMonitorStats(id string, cb dockerclient.StatCallback, ec chan error, args ...interface{}) { 94 | return 95 | } 96 | 97 | func (client *NopClient) StopAllMonitorStats() { 98 | return 99 | } 100 | 101 | func (client *NopClient) Version() (*dockerclient.Version, error) { 102 | return nil, ErrNoEngine 103 | } 104 | 105 | func (client *NopClient) PullImage(name string, auth *dockerclient.AuthConfig) error { 106 | return ErrNoEngine 107 | } 108 | 109 | func (client *NopClient) PushImage(name, tag string, auth *dockerclient.AuthConfig) error { 110 | return ErrNoEngine 111 | } 112 | 113 | func (client *NopClient) LoadImage(reader io.Reader) error { 114 | return ErrNoEngine 115 | } 116 | 117 | func (client *NopClient) RemoveContainer(id string, force, volumes bool) error { 118 | return ErrNoEngine 119 | } 120 | 121 | func (client *NopClient) ListImages(all bool) ([]*dockerclient.Image, error) { 122 | return nil, ErrNoEngine 123 | } 124 | 125 | func (client *NopClient) RemoveImage(name string, force bool) ([]*dockerclient.ImageDelete, error) { 126 | return nil, ErrNoEngine 127 | } 128 | 129 | func (client *NopClient) SearchImages(query, registry string, authConfig *dockerclient.AuthConfig) ([]dockerclient.ImageSearch, error) { 130 | return nil, ErrNoEngine 131 | } 132 | 133 | func (client *NopClient) PauseContainer(name string) error { 134 | return ErrNoEngine 135 | } 136 | 137 | func (client *NopClient) UnpauseContainer(name string) error { 138 | return ErrNoEngine 139 | } 140 | 141 | func (client *NopClient) ExecCreate(config *dockerclient.ExecConfig) (string, error) { 142 | return "", ErrNoEngine 143 | } 144 | 145 | func (client *NopClient) ExecStart(id string, config *dockerclient.ExecConfig) error { 146 | return ErrNoEngine 147 | } 148 | 149 | func (client *NopClient) ExecResize(id string, width, height int) error { 150 | return ErrNoEngine 151 | } 152 | 153 | func (client *NopClient) RenameContainer(oldName string, newName string) error { 154 | return ErrNoEngine 155 | } 156 | 157 | func (client *NopClient) ImportImage(source string, repository string, tag string, tar io.Reader) (io.ReadCloser, error) { 158 | return nil, ErrNoEngine 159 | } 160 | 161 | func (client *NopClient) BuildImage(image *dockerclient.BuildImage) (io.ReadCloser, error) { 162 | return nil, ErrNoEngine 163 | } 164 | 165 | func (client *NopClient) ListVolumes() ([]*dockerclient.Volume, error) { 166 | return nil, ErrNoEngine 167 | } 168 | 169 | func (client *NopClient) RemoveVolume(name string) error { 170 | return ErrNoEngine 171 | } 172 | 173 | func (client *NopClient) CreateVolume(request *dockerclient.VolumeCreateRequest) (*dockerclient.Volume, error) { 174 | return nil, ErrNoEngine 175 | } 176 | 177 | func (client *NopClient) ListNetworks(filters string) ([]*dockerclient.NetworkResource, error) { 178 | return nil, ErrNoEngine 179 | } 180 | 181 | func (client *NopClient) InspectNetwork(id string) (*dockerclient.NetworkResource, error) { 182 | return nil, ErrNoEngine 183 | } 184 | 185 | func (client *NopClient) CreateNetwork(config *dockerclient.NetworkCreate) (*dockerclient.NetworkCreateResponse, error) { 186 | return nil, ErrNoEngine 187 | } 188 | 189 | func (client *NopClient) ConnectNetwork(id, container string) error { 190 | return ErrNoEngine 191 | } 192 | 193 | func (client *NopClient) DisconnectNetwork(id, container string, force bool) error { 194 | return ErrNoEngine 195 | } 196 | 197 | func (client *NopClient) RemoveNetwork(id string) error { 198 | return ErrNoEngine 199 | } 200 | -------------------------------------------------------------------------------- /tls.go: -------------------------------------------------------------------------------- 1 | package dockerclient 2 | 3 | import ( 4 | "crypto/tls" 5 | "crypto/x509" 6 | "errors" 7 | "io/ioutil" 8 | "path/filepath" 9 | ) 10 | 11 | // TLSConfigFromCertPath returns a configuration based on PEM files in the directory 12 | // 13 | // path is usually what is set by the environment variable `DOCKER_CERT_PATH`, 14 | // or `$HOME/.docker`. 15 | func TLSConfigFromCertPath(path string) (*tls.Config, error) { 16 | cert, err := ioutil.ReadFile(filepath.Join(path, "cert.pem")) 17 | if err != nil { 18 | return nil, err 19 | } 20 | key, err := ioutil.ReadFile(filepath.Join(path, "key.pem")) 21 | if err != nil { 22 | return nil, err 23 | } 24 | ca, err := ioutil.ReadFile(filepath.Join(path, "ca.pem")) 25 | if err != nil { 26 | return nil, err 27 | } 28 | tlsCert, err := tls.X509KeyPair(cert, key) 29 | if err != nil { 30 | return nil, err 31 | } 32 | tlsConfig := &tls.Config{Certificates: []tls.Certificate{tlsCert}} 33 | tlsConfig.RootCAs = x509.NewCertPool() 34 | if !tlsConfig.RootCAs.AppendCertsFromPEM(ca) { 35 | return nil, errors.New("Could not add RootCA pem") 36 | } 37 | return tlsConfig, nil 38 | } 39 | -------------------------------------------------------------------------------- /types.go: -------------------------------------------------------------------------------- 1 | package dockerclient 2 | 3 | import ( 4 | "fmt" 5 | "io" 6 | "time" 7 | 8 | "github.com/docker/go-units" 9 | ) 10 | 11 | type ContainerConfig struct { 12 | Hostname string 13 | Domainname string 14 | User string 15 | AttachStdin bool 16 | AttachStdout bool 17 | AttachStderr bool 18 | ExposedPorts map[string]struct{} 19 | Tty bool 20 | OpenStdin bool 21 | StdinOnce bool 22 | Env []string 23 | Cmd []string 24 | Image string 25 | Volumes map[string]struct{} 26 | WorkingDir string 27 | Entrypoint []string 28 | NetworkDisabled bool 29 | MacAddress string 30 | OnBuild []string 31 | Labels map[string]string 32 | StopSignal string 33 | 34 | // FIXME: VolumeDriver have been removed since docker 1.9 35 | VolumeDriver string 36 | 37 | // FIXME: The following fields have been removed since API v1.18 38 | Memory int64 39 | MemorySwap int64 40 | CpuShares int64 41 | Cpuset string 42 | PortSpecs []string 43 | 44 | // This is used only by the create command 45 | HostConfig HostConfig 46 | 47 | // Network configuration support 48 | NetworkingConfig NetworkingConfig 49 | } 50 | 51 | type HostConfig struct { 52 | Binds []string 53 | ContainerIDFile string 54 | LxcConf []map[string]string 55 | Memory int64 56 | MemoryReservation int64 57 | MemorySwap int64 58 | KernelMemory int64 59 | CpuShares int64 60 | CpuPeriod int64 61 | CpusetCpus string 62 | CpusetMems string 63 | CpuQuota int64 64 | BlkioWeight int64 65 | OomKillDisable bool 66 | MemorySwappiness int64 67 | Privileged bool 68 | PortBindings map[string][]PortBinding 69 | Links []string 70 | PublishAllPorts bool 71 | Dns []string 72 | DNSOptions []string 73 | DnsSearch []string 74 | ExtraHosts []string 75 | VolumesFrom []string 76 | Devices []DeviceMapping 77 | NetworkMode string 78 | IpcMode string 79 | PidMode string 80 | UTSMode string 81 | CapAdd []string 82 | CapDrop []string 83 | GroupAdd []string 84 | RestartPolicy RestartPolicy 85 | SecurityOpt []string 86 | ReadonlyRootfs bool 87 | Ulimits []Ulimit 88 | LogConfig LogConfig 89 | CgroupParent string 90 | ConsoleSize [2]int 91 | VolumeDriver string 92 | OomScoreAdj int 93 | Tmpfs map[string]string 94 | ShmSize int64 `json:"omitempty"` 95 | BlkioWeightDevice []WeightDevice 96 | BlkioDeviceReadBps []ThrottleDevice 97 | BlkioDeviceWriteBps []ThrottleDevice 98 | BlkioDeviceReadIOps []ThrottleDevice 99 | BlkioDeviceWriteIOps []ThrottleDevice 100 | } 101 | 102 | type WeightDevice struct { 103 | Path string 104 | Weight uint16 105 | } 106 | 107 | type ThrottleDevice struct { 108 | Path string 109 | Rate uint64 110 | } 111 | 112 | type DeviceMapping struct { 113 | PathOnHost string `json:"PathOnHost"` 114 | PathInContainer string `json:"PathInContainer"` 115 | CgroupPermissions string `json:"CgroupPermissions"` 116 | } 117 | 118 | type ExecConfig struct { 119 | AttachStdin bool 120 | AttachStdout bool 121 | AttachStderr bool 122 | Tty bool 123 | Cmd []string 124 | Container string 125 | Detach bool 126 | } 127 | 128 | type LogOptions struct { 129 | Follow bool 130 | Stdout bool 131 | Stderr bool 132 | Timestamps bool 133 | Tail int64 134 | } 135 | 136 | type AttachOptions struct { 137 | Logs bool 138 | Stream bool 139 | Stdin bool 140 | Stdout bool 141 | Stderr bool 142 | } 143 | 144 | type MonitorEventsFilters struct { 145 | Event string `json:",omitempty"` 146 | Events []string `json:",omitempty"` 147 | Image string `json:",omitempty"` 148 | Images []string `json:",omitempty"` 149 | Container string `json:",omitempty"` 150 | Containers []string `json:",omitempty"` 151 | } 152 | 153 | type MonitorEventsOptions struct { 154 | Since int 155 | Until int 156 | Filters *MonitorEventsFilters `json:",omitempty"` 157 | } 158 | 159 | type RestartPolicy struct { 160 | Name string 161 | MaximumRetryCount int64 162 | } 163 | 164 | type PortBinding struct { 165 | HostIp string 166 | HostPort string 167 | } 168 | 169 | type State struct { 170 | Running bool 171 | Paused bool 172 | Restarting bool 173 | OOMKilled bool 174 | Dead bool 175 | Pid int 176 | ExitCode int 177 | Error string // contains last known error when starting the container 178 | StartedAt time.Time 179 | FinishedAt time.Time 180 | Ghost bool 181 | } 182 | 183 | // String returns a human-readable description of the state 184 | // Stoken from docker/docker/daemon/state.go 185 | func (s *State) String() string { 186 | if s.Running { 187 | if s.Paused { 188 | return fmt.Sprintf("Up %s (Paused)", units.HumanDuration(time.Now().UTC().Sub(s.StartedAt))) 189 | } 190 | if s.Restarting { 191 | return fmt.Sprintf("Restarting (%d) %s ago", s.ExitCode, units.HumanDuration(time.Now().UTC().Sub(s.FinishedAt))) 192 | } 193 | 194 | return fmt.Sprintf("Up %s", units.HumanDuration(time.Now().UTC().Sub(s.StartedAt))) 195 | } 196 | 197 | if s.Dead { 198 | return "Dead" 199 | } 200 | 201 | if s.StartedAt.IsZero() { 202 | return "Created" 203 | } 204 | 205 | if s.FinishedAt.IsZero() { 206 | return "" 207 | } 208 | 209 | return fmt.Sprintf("Exited (%d) %s ago", s.ExitCode, units.HumanDuration(time.Now().UTC().Sub(s.FinishedAt))) 210 | } 211 | 212 | // StateString returns a single string to describe state 213 | // Stoken from docker/docker/daemon/state.go 214 | func (s *State) StateString() string { 215 | if s.Running { 216 | if s.Paused { 217 | return "paused" 218 | } 219 | if s.Restarting { 220 | return "restarting" 221 | } 222 | return "running" 223 | } 224 | 225 | if s.Dead { 226 | return "dead" 227 | } 228 | 229 | if s.StartedAt.IsZero() { 230 | return "created" 231 | } 232 | 233 | return "exited" 234 | } 235 | 236 | type ImageInfo struct { 237 | Architecture string 238 | Author string 239 | Comment string 240 | Config *ContainerConfig 241 | Container string 242 | ContainerConfig *ContainerConfig 243 | Created time.Time 244 | DockerVersion string 245 | Id string 246 | Os string 247 | Parent string 248 | Size int64 249 | VirtualSize int64 250 | } 251 | 252 | type ImageSearch struct { 253 | Description string `json:"description,omitempty" yaml:"description,omitempty"` 254 | IsOfficial bool `json:"is_official,omitempty" yaml:"is_official,omitempty"` 255 | IsAutomated bool `json:"is_automated,omitempty" yaml:"is_automated,omitempty"` 256 | Name string `json:"name,omitempty" yaml:"name,omitempty"` 257 | StarCount int `json:"star_count,omitempty" yaml:"star_count,omitempty"` 258 | } 259 | 260 | type ContainerInfo struct { 261 | Id string 262 | Created string 263 | Path string 264 | Name string 265 | Args []string 266 | ExecIDs []string 267 | Config *ContainerConfig 268 | State *State 269 | Image string 270 | NetworkSettings struct { 271 | IPAddress string `json:"IpAddress"` 272 | IPPrefixLen int `json:"IpPrefixLen"` 273 | Gateway string 274 | Bridge string 275 | Ports map[string][]PortBinding 276 | Networks map[string]*EndpointSettings 277 | } 278 | SysInitPath string 279 | ResolvConfPath string 280 | Volumes map[string]string 281 | HostConfig *HostConfig 282 | } 283 | 284 | type ContainerChanges struct { 285 | Path string 286 | Kind int 287 | } 288 | 289 | type Port struct { 290 | IP string 291 | PrivatePort int 292 | PublicPort int 293 | Type string 294 | } 295 | 296 | // EndpointSettings stores the network endpoint details 297 | type EndpointSettings struct { 298 | // Configurations 299 | IPAMConfig *EndpointIPAMConfig 300 | Links []string 301 | Aliases []string 302 | // Operational data 303 | NetworkID string 304 | EndpointID string 305 | Gateway string 306 | IPAddress string 307 | IPPrefixLen int 308 | IPv6Gateway string 309 | GlobalIPv6Address string 310 | GlobalIPv6PrefixLen int 311 | MacAddress string 312 | } 313 | 314 | // NetworkingConfig represents the container's networking configuration for each of its interfaces 315 | // Carries the networink configs specified in the `docker run` and `docker network connect` commands 316 | type NetworkingConfig struct { 317 | EndpointsConfig map[string]*EndpointSettings // Endpoint configs for each conencting network 318 | } 319 | 320 | type Container struct { 321 | Id string 322 | Names []string 323 | Image string 324 | Command string 325 | Created int64 326 | Status string 327 | Ports []Port 328 | SizeRw int64 329 | SizeRootFs int64 330 | Labels map[string]string 331 | NetworkSettings struct { 332 | Networks map[string]EndpointSettings 333 | } 334 | } 335 | 336 | type Actor struct { 337 | ID string 338 | Attributes map[string]string 339 | } 340 | 341 | type Event struct { 342 | Status string `json:"status,omitempty"` 343 | ID string `json:"id,omitempty"` 344 | From string `json:"from,omitempty"` 345 | 346 | Type string 347 | Action string 348 | Actor Actor 349 | 350 | Time int64 `json:"time,omitempty"` 351 | TimeNano int64 `json:"timeNano,omitempty"` 352 | } 353 | 354 | type Version struct { 355 | ApiVersion string 356 | Arch string 357 | GitCommit string 358 | GoVersion string 359 | KernelVersion string 360 | Os string 361 | Version string 362 | } 363 | 364 | type RespContainersCreate struct { 365 | Id string 366 | Warnings []string 367 | } 368 | 369 | type Image struct { 370 | Created int64 371 | Id string 372 | Labels map[string]string 373 | ParentId string 374 | RepoDigests []string 375 | RepoTags []string 376 | Size int64 377 | VirtualSize int64 378 | } 379 | 380 | // Info is the struct returned by /info 381 | // The API is currently in flux, so Debug, MemoryLimit, SwapLimit, and 382 | // IPv4Forwarding are interfaces because in docker 1.6.1 they are 0 or 1 but in 383 | // master they are bools. 384 | type Info struct { 385 | ID string 386 | Containers int64 387 | Driver string 388 | DriverStatus [][]string 389 | ExecutionDriver string 390 | Images int64 391 | KernelVersion string 392 | OperatingSystem string 393 | NCPU int64 394 | MemTotal int64 395 | Name string 396 | Labels []string 397 | Debug interface{} 398 | NFd int64 399 | NGoroutines int64 400 | SystemTime string 401 | NEventsListener int64 402 | InitPath string 403 | InitSha1 string 404 | IndexServerAddress string 405 | MemoryLimit interface{} 406 | SwapLimit interface{} 407 | IPv4Forwarding interface{} 408 | BridgeNfIptables bool 409 | BridgeNfIp6tables bool 410 | DockerRootDir string 411 | HttpProxy string 412 | HttpsProxy string 413 | NoProxy string 414 | } 415 | 416 | type ImageDelete struct { 417 | Deleted string 418 | Untagged string 419 | } 420 | 421 | type StatsOrError struct { 422 | Stats 423 | Error error 424 | } 425 | 426 | type EventOrError struct { 427 | Event 428 | Error error 429 | } 430 | 431 | type WaitResult struct { 432 | ExitCode int 433 | Error error 434 | } 435 | 436 | type decodingResult struct { 437 | result interface{} 438 | err error 439 | } 440 | 441 | // The following are types for the API stats endpoint 442 | type ThrottlingData struct { 443 | // Number of periods with throttling active 444 | Periods uint64 `json:"periods"` 445 | // Number of periods when the container hit its throttling limit. 446 | ThrottledPeriods uint64 `json:"throttled_periods"` 447 | // Aggregate time the container was throttled for in nanoseconds. 448 | ThrottledTime uint64 `json:"throttled_time"` 449 | } 450 | 451 | // All CPU stats are aggregated since container inception. 452 | type CpuUsage struct { 453 | // Total CPU time consumed. 454 | // Units: nanoseconds. 455 | TotalUsage uint64 `json:"total_usage"` 456 | // Total CPU time consumed per core. 457 | // Units: nanoseconds. 458 | PercpuUsage []uint64 `json:"percpu_usage"` 459 | // Time spent by tasks of the cgroup in kernel mode. 460 | // Units: nanoseconds. 461 | UsageInKernelmode uint64 `json:"usage_in_kernelmode"` 462 | // Time spent by tasks of the cgroup in user mode. 463 | // Units: nanoseconds. 464 | UsageInUsermode uint64 `json:"usage_in_usermode"` 465 | } 466 | 467 | type CpuStats struct { 468 | CpuUsage CpuUsage `json:"cpu_usage"` 469 | SystemUsage uint64 `json:"system_cpu_usage"` 470 | ThrottlingData ThrottlingData `json:"throttling_data,omitempty"` 471 | } 472 | 473 | type NetworkStats struct { 474 | RxBytes uint64 `json:"rx_bytes"` 475 | RxPackets uint64 `json:"rx_packets"` 476 | RxErrors uint64 `json:"rx_errors"` 477 | RxDropped uint64 `json:"rx_dropped"` 478 | TxBytes uint64 `json:"tx_bytes"` 479 | TxPackets uint64 `json:"tx_packets"` 480 | TxErrors uint64 `json:"tx_errors"` 481 | TxDropped uint64 `json:"tx_dropped"` 482 | } 483 | 484 | type MemoryStats struct { 485 | Usage uint64 `json:"usage"` 486 | MaxUsage uint64 `json:"max_usage"` 487 | Stats map[string]uint64 `json:"stats"` 488 | Failcnt uint64 `json:"failcnt"` 489 | Limit uint64 `json:"limit"` 490 | } 491 | 492 | type BlkioStatEntry struct { 493 | Major uint64 `json:"major"` 494 | Minor uint64 `json:"minor"` 495 | Op string `json:"op"` 496 | Value uint64 `json:"value"` 497 | } 498 | 499 | type BlkioStats struct { 500 | // number of bytes tranferred to and from the block device 501 | IoServiceBytesRecursive []BlkioStatEntry `json:"io_service_bytes_recursive"` 502 | IoServicedRecursive []BlkioStatEntry `json:"io_serviced_recursive"` 503 | IoQueuedRecursive []BlkioStatEntry `json:"io_queue_recursive"` 504 | IoServiceTimeRecursive []BlkioStatEntry `json:"io_service_time_recursive"` 505 | IoWaitTimeRecursive []BlkioStatEntry `json:"io_wait_time_recursive"` 506 | IoMergedRecursive []BlkioStatEntry `json:"io_merged_recursive"` 507 | IoTimeRecursive []BlkioStatEntry `json:"io_time_recursive"` 508 | SectorsRecursive []BlkioStatEntry `json:"sectors_recursive"` 509 | } 510 | 511 | type Stats struct { 512 | Read time.Time `json:"read"` 513 | NetworkStats NetworkStats `json:"network,omitempty"` 514 | CpuStats CpuStats `json:"cpu_stats,omitempty"` 515 | MemoryStats MemoryStats `json:"memory_stats,omitempty"` 516 | BlkioStats BlkioStats `json:"blkio_stats,omitempty"` 517 | } 518 | 519 | type Ulimit struct { 520 | Name string `json:"name"` 521 | Soft uint64 `json:"soft"` 522 | Hard uint64 `json:"hard"` 523 | } 524 | 525 | type LogConfig struct { 526 | Type string `json:"type"` 527 | Config map[string]string `json:"config"` 528 | } 529 | 530 | type BuildImage struct { 531 | Config *ConfigFile 532 | DockerfileName string 533 | Context io.Reader 534 | RemoteURL string 535 | RepoName string 536 | SuppressOutput bool 537 | NoCache bool 538 | Remove bool 539 | ForceRemove bool 540 | Pull bool 541 | Memory int64 542 | MemorySwap int64 543 | CpuShares int64 544 | CpuPeriod int64 545 | CpuQuota int64 546 | CpuSetCpus string 547 | CpuSetMems string 548 | CgroupParent string 549 | BuildArgs map[string]string 550 | Labels map[string]string // Labels hold metadata about the image 551 | } 552 | 553 | type Volume struct { 554 | Name string // Name is the name of the volume 555 | Driver string // Driver is the Driver name used to create the volume 556 | Mountpoint string // Mountpoint is the location on disk of the volume 557 | Labels map[string]string // Labels hold metadata about the volume 558 | } 559 | 560 | type VolumesListResponse struct { 561 | Volumes []*Volume // Volumes is the list of volumes being returned 562 | } 563 | 564 | type VolumeCreateRequest struct { 565 | Name string // Name is the requested name of the volume 566 | Driver string // Driver is the name of the driver that should be used to create the volume 567 | DriverOpts map[string]string // DriverOpts holds the driver specific options to use for when creating the volume. 568 | Labels map[string]string // Labels hold metadata about the volume 569 | } 570 | 571 | // IPAM represents IP Address Management 572 | type IPAM struct { 573 | Driver string 574 | Options map[string]string //Per network IPAM driver options 575 | Config []IPAMConfig 576 | } 577 | 578 | // IPAMConfig represents IPAM configurations 579 | type IPAMConfig struct { 580 | Subnet string `json:",omitempty"` 581 | IPRange string `json:",omitempty"` 582 | Gateway string `json:",omitempty"` 583 | AuxAddress map[string]string `json:"AuxiliaryAddresses,omitempty"` 584 | } 585 | 586 | // EndpointIPAMConfig represents IPAM configurations for the endpoint 587 | type EndpointIPAMConfig struct { 588 | IPv4Address string `json:",omitempty"` 589 | IPv6Address string `json:",omitempty"` 590 | } 591 | 592 | // NetworkResource is the body of the "get network" http response message 593 | type NetworkResource struct { 594 | Name string 595 | ID string `json:"Id"` 596 | Scope string 597 | Driver string 598 | IPAM IPAM 599 | //Internal bool 600 | Containers map[string]EndpointResource 601 | Options map[string]string 602 | Labels map[string]string // Labels hold metadata about the network 603 | } 604 | 605 | // EndpointResource contains network resources allocated and used for a container in a network 606 | type EndpointResource struct { 607 | Name string 608 | EndpointID string 609 | MacAddress string 610 | IPv4Address string 611 | IPv6Address string 612 | } 613 | 614 | // NetworkCreate is the expected body of the "create network" http request message 615 | type NetworkCreate struct { 616 | Name string 617 | CheckDuplicate bool 618 | Driver string 619 | IPAM IPAM 620 | Internal bool 621 | Options map[string]string 622 | Labels map[string]string // Labels hold metadata about the network 623 | } 624 | 625 | // NetworkCreateResponse is the response message sent by the server for network create call 626 | type NetworkCreateResponse struct { 627 | ID string `json:"Id"` 628 | Warning string 629 | } 630 | 631 | // NetworkConnect represents the data to be used to connect a container to the network 632 | type NetworkConnect struct { 633 | Container string 634 | } 635 | 636 | // NetworkDisconnect represents the data to be used to disconnect a container from the network 637 | type NetworkDisconnect struct { 638 | Container string 639 | Force bool 640 | } 641 | -------------------------------------------------------------------------------- /utils.go: -------------------------------------------------------------------------------- 1 | package dockerclient 2 | 3 | import ( 4 | "crypto/tls" 5 | "net" 6 | "net/http" 7 | "net/url" 8 | "time" 9 | ) 10 | 11 | type tcpFunc func(*net.TCPConn, time.Duration) error 12 | 13 | func newHTTPClient(u *url.URL, tlsConfig *tls.Config, timeout time.Duration, setUserTimeout tcpFunc) *http.Client { 14 | httpTransport := &http.Transport{ 15 | TLSClientConfig: tlsConfig, 16 | } 17 | 18 | switch u.Scheme { 19 | default: 20 | httpTransport.Dial = func(proto, addr string) (net.Conn, error) { 21 | conn, err := net.DialTimeout(proto, addr, timeout) 22 | if tcpConn, ok := conn.(*net.TCPConn); ok && setUserTimeout != nil { 23 | // Sender can break TCP connection if the remote side doesn't 24 | // acknowledge packets within timeout 25 | setUserTimeout(tcpConn, timeout) 26 | } 27 | return conn, err 28 | } 29 | case "unix": 30 | socketPath := u.Path 31 | unixDial := func(proto, addr string) (net.Conn, error) { 32 | return net.DialTimeout("unix", socketPath, timeout) 33 | } 34 | httpTransport.Dial = unixDial 35 | // Override the main URL object so the HTTP lib won't complain 36 | u.Scheme = "http" 37 | u.Host = "unix.sock" 38 | u.Path = "" 39 | } 40 | return &http.Client{Transport: httpTransport} 41 | } 42 | --------------------------------------------------------------------------------