/
docker.go
98 lines (85 loc) · 2.5 KB
/
docker.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package deployer
import (
"context"
"encoding/base64"
"encoding/json"
"errors"
"io"
"io/ioutil"
"time"
"github.com/docker/docker/api/types"
"github.com/docker/docker/client"
)
type DockerClient interface {
ImageBuild(context.Context, io.Reader, types.ImageBuildOptions) (types.ImageBuildResponse, error)
ImagePush(context.Context, string, types.ImagePushOptions) (io.ReadCloser, error)
}
// DockerDeployer uses the Docker SDK to build and push images to a remote registry
type DockerDeployer struct {
cli DockerClient
auth string
}
// NewDockerDeployer initializes a DockerDeployer with a Docker API version and credentials to access a Dockerhub registry
func NewDockerDeployer(registryUsername string, registryPassword string) (*DockerDeployer, error) {
cli, err := client.NewClientWithOpts(client.WithVersion("1.40"))
if err != nil {
return nil, err
}
auth, err := generateRegistryAuth(registryUsername, registryPassword)
if err != nil {
return nil, err
}
return &DockerDeployer{cli, auth}, nil
}
// generateRegistryAuth converts a Dockerhub username and password into an authentication string
// used by the Docker SDK
func generateRegistryAuth(username string, password string) (string, error) {
if username == "" || password == "" {
return "", errors.New("Missing Dockerhub username or password")
}
authConfig := types.AuthConfig{
Username: username,
Password: password,
}
encodedJSON, err := json.Marshal(authConfig)
if err != nil {
return "", err
}
authStr := base64.URLEncoding.EncodeToString(encodedJSON)
return authStr, nil
}
// BuildImage converts a directory to a tar file and uses the Docker SDK to build a Docker image
func (d DockerDeployer) BuildImage(dockerfileTarReader io.Reader, tag string) error {
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(300)*time.Second)
defer cancel()
resp, err := d.cli.ImageBuild(
ctx,
dockerfileTarReader,
types.ImageBuildOptions{
Dockerfile: "Dockerfile",
Tags: []string{tag},
NoCache: true,
Remove: true,
})
if err != nil {
return err
}
// block until the image is finished building
_, err = ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
return nil
}
// PushImage takes a local Docker image and pushes it to a Dockerhub registry
func (d DockerDeployer) PushImage(image string) error {
ctx := context.Background()
out, err := d.cli.ImagePush(ctx, image, types.ImagePushOptions{
RegistryAuth: d.auth,
})
if err != nil {
return err
}
defer out.Close()
return nil
}