/
image.go
310 lines (265 loc) · 7.55 KB
/
image.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
package provider
import (
"bufio"
"context"
"encoding/base64"
"encoding/json"
"fmt"
"github.com/docker/docker/api/types"
"github.com/docker/docker/client"
"github.com/docker/docker/pkg/archive"
"github.com/docker/docker/pkg/jsonmessage"
structpb "github.com/golang/protobuf/ptypes/struct"
"github.com/pkg/errors"
"github.com/pulumi/pulumi/sdk/v3/go/common/resource"
"github.com/pulumi/pulumi/sdk/v3/go/common/resource/plugin"
)
const defaultDockerfile = "Dockerfile"
type Image struct {
Name string
SkipPush bool
Registry Registry
Tag string
Build Build
}
type Registry struct {
Server string
Username string
Password string
}
type Build struct {
Context string
Dockerfile string
CachedImages []string
Env map[string]string
Args map[string]*string
ExtraOptions []string
Target string
}
func (p *dockerNativeProvider) dockerBuild(ctx context.Context,
urn resource.URN,
props *structpb.Struct) (string, *structpb.Struct, error) {
inputs, err := plugin.UnmarshalProperties(props, plugin.MarshalOptions{KeepUnknowns: true, SkipNulls: true})
if err != nil {
return "", nil, err
}
reg := setRegistry(inputs["registry"])
// read in values to Image
img := Image{
Name: inputs["imageName"].StringValue(),
SkipPush: inputs["skipPush"].BoolValue(),
Registry: reg,
}
build := marshalBuild(inputs["build"])
cache := getCachedImages(img, inputs["build"])
build.CachedImages = cache
img.Build = build
docker, err := client.NewClientWithOpts(client.FromEnv)
if err != nil {
return "", nil, err
}
err = p.host.Log(ctx, "info", urn, "Building the image")
if err != nil {
return "", nil, err
}
// make the build context
tar, err := archive.TarWithOptions(img.Build.Context, &archive.TarOptions{})
if err != nil {
return "", nil, err
}
// make the build options
opts := types.ImageBuildOptions{
Dockerfile: img.Build.Dockerfile,
Tags: []string{img.Name}, //this should build the image locally, sans registry info
Remove: true,
//CacheFrom: img.Build.CachedImages, // TODO: this needs a login, so needs to be handled differently.
BuildArgs: build.Args,
//Version: types.BuilderBuildKit, // TODO: parse this setting from the `env` input
}
imgBuildResp, err := docker.ImageBuild(ctx, tar, opts)
if err != nil {
return "", nil, err
}
defer imgBuildResp.Body.Close()
// Print build logs to terminal
scanner := bufio.NewScanner(imgBuildResp.Body)
for scanner.Scan() {
err := p.host.Log(ctx, "info", urn, scanner.Text())
if err != nil {
return "", nil, err
}
}
// if we are not pushing to the registry, we return after building the local image.
if img.SkipPush {
outputs := map[string]interface{}{
"dockerfile": img.Build.Dockerfile,
"context": img.Build.Context,
"registryServer": img.Registry.Server,
}
pbstruct, err := plugin.MarshalProperties(
resource.NewPropertyMapFromMap(outputs),
plugin.MarshalOptions{KeepUnknowns: true, SkipNulls: true},
)
return img.Name, pbstruct, err
}
err = p.host.Log(ctx, "info", urn, "Pushing Image to the registry")
if err != nil {
return "", nil, err
}
// Quick and dirty auth; we can also preconfigure the client itself I believe
var authConfig = types.AuthConfig{
Username: img.Registry.Username,
Password: img.Registry.Password,
ServerAddress: img.Registry.Server,
}
authConfigBytes, err := json.Marshal(authConfig)
if err != nil {
return "", nil, errors.Wrap(err, "Error parsing authConfig")
}
authConfigEncoded := base64.URLEncoding.EncodeToString(authConfigBytes)
pushOpts := types.ImagePushOptions{RegistryAuth: authConfigEncoded}
// By default, we push our image with the qualified image name from the input, without extra tagging.
pushOutput, err := docker.ImagePush(ctx, img.Name, pushOpts)
if err != nil {
return "", nil, err
}
defer pushOutput.Close()
// Print push logs to terminal
pushScanner := bufio.NewScanner(pushOutput)
for pushScanner.Scan() {
msg := pushScanner.Text()
var jsmsg jsonmessage.JSONMessage
err := json.Unmarshal([]byte(msg), &jsmsg)
if err != nil {
return "", nil, errors.Wrapf(err, "encountered error unmarshalling:")
}
if jsmsg.Status != "" {
if jsmsg.Status != "Pushing" {
var info string
if jsmsg.ID != "" {
info = fmt.Sprintf("%s: %s", jsmsg.ID, jsmsg.Status)
} else {
info = jsmsg.Status
}
err := p.host.Log(ctx, "info", urn, info)
if err != nil {
return "", nil, err
}
}
}
if jsmsg.Error != nil {
return "", nil, errors.Errorf(jsmsg.Error.Message)
}
}
outputs := map[string]interface{}{
"dockerfile": img.Build.Dockerfile,
"context": img.Build.Context,
"baseImageName": img.Name,
"registryServer": img.Registry.Server,
}
pbstruct, err := plugin.MarshalProperties(
resource.NewPropertyMapFromMap(outputs),
plugin.MarshalOptions{KeepUnknowns: true, SkipNulls: true},
)
return img.Name, pbstruct, err
}
func marshalBuild(b resource.PropertyValue) Build {
// build can be nil, a string or an object; we will also use reasonable defaults here.
var build Build
if b.IsNull() {
// use the default build context
build.Dockerfile = defaultDockerfile
build.Context = "."
return build
}
if b.IsString() {
// use the filepath as context
build.Context = b.StringValue()
build.Dockerfile = defaultDockerfile
return build
}
// read in the build type fields
buildObject := b.ObjectValue()
// Dockerfile
if buildObject["dockerfile"].IsNull() {
// set default
build.Dockerfile = defaultDockerfile
} else {
build.Dockerfile = buildObject["dockerfile"].StringValue()
}
// Context
if buildObject["context"].IsNull() {
// set default
build.Context = "."
} else {
build.Context = buildObject["context"].StringValue()
}
// Envs
envs := make(map[string]string)
if !buildObject["env"].IsNull() {
for k, v := range buildObject["env"].ObjectValue() {
key := fmt.Sprintf("%v", k)
envs[key] = v.StringValue()
}
}
build.Env = envs
// Args
args := make(map[string]*string)
if !buildObject["args"].IsNull() {
for k, v := range buildObject["args"].ObjectValue() {
key := fmt.Sprintf("%v", k)
vStr := v.StringValue()
args[key] = &vStr
}
}
build.Args = args
// ExtraOptions
if !buildObject["extraOptions"].IsNull() {
opts := buildObject["extraOptions"].ArrayValue()
for _, v := range opts {
build.ExtraOptions = append(build.ExtraOptions, v.StringValue())
}
}
// Target
if !buildObject["target"].IsNull() {
build.Target = buildObject["target"].StringValue()
}
return build
}
func getCachedImages(img Image, b resource.PropertyValue) []string {
var cacheImages []string
if b.IsNull() {
return cacheImages
}
c := b.ObjectValue()["cacheFrom"]
if c.IsNull() {
return cacheImages
}
latest := img.Registry.Username + "/" + img.Name
// if we specify cacheFrom as True, we pull the latest build+push of our image implicitly, i.e. registry/image
if c.IsBool() {
useCache := c.BoolValue()
if useCache {
cacheImages = append(cacheImages, latest)
}
return cacheImages
}
// if we specify a list of stages, then we only pull those
cacheFrom := c.ObjectValue()
stages := cacheFrom["stages"].ArrayValue()
for _, img := range stages {
stage := img.StringValue()
cacheImages = append(cacheImages, stage)
}
return cacheImages
}
func setRegistry(r resource.PropertyValue) Registry {
var reg Registry
if !r.IsNull() {
reg.Server = r.ObjectValue()["server"].StringValue()
reg.Username = r.ObjectValue()["username"].StringValue()
reg.Password = r.ObjectValue()["password"].StringValue()
return reg
}
return reg
}