-
Notifications
You must be signed in to change notification settings - Fork 40
/
builder.go
538 lines (456 loc) · 14.5 KB
/
builder.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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
package builder
import (
"context"
"fmt"
"io"
"os"
"os/signal"
"path/filepath"
"strconv"
"strings"
"sync"
"syscall"
"time"
"github.com/go-git/go-billy/v5/memfs"
"github.com/go-git/go-git/v5"
"github.com/go-git/go-git/v5/plumbing"
"github.com/go-git/go-git/v5/storage/memory"
"golang.org/x/mod/modfile"
"github.com/strangelove-ventures/heighliner/docker"
"github.com/strangelove-ventures/heighliner/dockerfile"
)
type HeighlinerBuilder struct {
buildConfig HeighlinerDockerBuildConfig
queue []HeighlinerQueuedChainBuilds
parallel int16
local bool
race bool
buildIndex int
buildIndexMu sync.Mutex
errors []error
errorsLock sync.Mutex
tmpDirsToRemove map[string]bool
tmpDirMapMu sync.Mutex
}
func NewHeighlinerBuilder(
buildConfig HeighlinerDockerBuildConfig,
parallel int16,
local bool,
race bool,
) *HeighlinerBuilder {
return &HeighlinerBuilder{
buildConfig: buildConfig,
parallel: parallel,
local: local,
race: race,
tmpDirsToRemove: make(map[string]bool),
}
}
func (h *HeighlinerBuilder) AddToQueue(chainBuilds ...HeighlinerQueuedChainBuilds) {
h.queue = append(h.queue, chainBuilds...)
}
func (h *HeighlinerBuilder) QueueLen() int {
return len(h.queue)
}
// imageTag determines which docker image tag to use based on inputs.
func imageTag(ref string, tag string, local bool) string {
if tag != "" {
return tag
}
tag = deriveTagFromRef(ref)
if local && tag == "" {
return "local"
}
return tag
}
// deriveTagFromRef returns a sanitized docker image tag from a git ref (branch/tag).
func deriveTagFromRef(version string) string {
return strings.ReplaceAll(version, "/", "-")
}
// dockerfileEmbeddedOrLocal attempts to find Dockerfile within current working directory.
// Returns embedded Dockerfile if local file is not found or cannot be read.
func dockerfileEmbeddedOrLocal(dockerfile string, embedded []byte) []byte {
cwd, err := os.Getwd()
if err != nil {
fmt.Printf("Using embedded %s due to working directory not found\n", dockerfile)
return embedded
}
absDockerfile := filepath.Join(cwd, "dockerfile", dockerfile)
if _, err := os.Stat(absDockerfile); err != nil {
fmt.Printf("Using embedded %s due to local dockerfile not found\n", dockerfile)
return embedded
}
df, err := os.ReadFile(absDockerfile)
if err != nil {
fmt.Printf("Using embedded %s due to failure to read local dockerfile\n", dockerfile)
return embedded
}
fmt.Printf("Using local %s\n", dockerfile)
return df
}
// dockerfileAndTag returns the appropriate dockerfile as bytes and the docker image tag
// based on the input configuration.
func rawDockerfile(
dockerfileType DockerfileType,
useBuildKit bool,
local bool,
) []byte {
switch dockerfileType {
case DockerfileTypeImported:
return dockerfileEmbeddedOrLocal("imported/Dockerfile", dockerfile.Imported)
case DockerfileTypeCargo:
if useBuildKit {
return dockerfileEmbeddedOrLocal("cargo/Dockerfile", dockerfile.Cargo)
}
return dockerfileEmbeddedOrLocal("cargo/native.Dockerfile", dockerfile.CargoNative)
case DockerfileTypeCosmos:
if local {
if useBuildKit {
return dockerfileEmbeddedOrLocal("cosmos/localcross.Dockerfile", dockerfile.CosmosLocalCross)
}
return dockerfile.CosmosLocal
}
if useBuildKit {
return dockerfileEmbeddedOrLocal("cosmos/Dockerfile", dockerfile.Cosmos)
}
return dockerfileEmbeddedOrLocal("cosmos/native.Dockerfile", dockerfile.CosmosNative)
case DockerfileTypeAvalanche:
if useBuildKit {
return dockerfileEmbeddedOrLocal("avalanche/Dockerfile", dockerfile.Avalanche)
}
return dockerfileEmbeddedOrLocal("avalanche/native.Dockerfile", dockerfile.AvalancheNative)
default:
return dockerfileEmbeddedOrLocal("none/Dockerfile", dockerfile.None)
}
}
func getModFile(
repoHost string,
organization string,
repoName string,
ref string,
buildDir string,
local bool,
) (*modfile.File, error) {
var goModBz []byte
var err error
goModPath := "go.mod"
if buildDir != "" {
goModPath = filepath.Join(buildDir, goModPath)
}
if local {
goModBz, err = os.ReadFile(goModPath)
if err != nil {
return nil, fmt.Errorf("failed to read %s for local build: %w", goModPath, err)
}
} else {
// single branch depth 1 clone to only fetch most recent state of files
cloneOpts := &git.CloneOptions{
URL: fmt.Sprintf("https://%s/%s/%s", repoHost, organization, repoName),
SingleBranch: true,
Depth: 1,
}
// Try as tag ref first
cloneOpts.ReferenceName = plumbing.NewTagReferenceName(ref)
// Clone into memory
fs := memfs.New()
_, err = git.Clone(memory.NewStorage(), fs, cloneOpts)
if err != nil {
// In error case, try as branch ref
cloneOpts.ReferenceName = plumbing.NewBranchReferenceName(ref)
_, err := git.Clone(memory.NewStorage(), fs, cloneOpts)
if err != nil {
return nil, fmt.Errorf("failed to clone go.mod file to determine go version: %w", err)
}
}
goModFile, err := fs.Open(goModPath)
if err != nil {
return nil, fmt.Errorf("failed to open go.mod file: %w", err)
}
goModBz, err = io.ReadAll(goModFile)
if err != nil {
return nil, fmt.Errorf("failed to read go.mod file: %w", err)
}
}
goMod, err := modfile.Parse("go.mod", goModBz, nil)
if err != nil {
return nil, fmt.Errorf("failed to parse go.mod file: %w", err)
}
return goMod, nil
}
// getWasmvmVersion will get the wasmvm version from the mod file
func getWasmvmVersion(modFile *modfile.File) string {
const defaultWasmvmRepo = "github.com/CosmWasm/wasmvm"
wasmvmRepo := defaultWasmvmRepo
wasmvmVersion := ""
// First check all the "requires"
for _, item := range modFile.Require {
// Must have 2 tokens, repo & version
if (len(item.Syntax.Token) == 2) && (strings.Contains(item.Syntax.Token[0], wasmvmRepo)) {
wasmvmRepo = item.Syntax.Token[0]
wasmvmVersion = item.Syntax.Token[1]
}
}
// Then, check all the "replaces"
for _, item := range modFile.Replace {
// Must have 3 or more tokens
if (len(item.Syntax.Token) > 2) && (strings.Contains(item.Syntax.Token[0], wasmvmRepo)) {
wasmvmRepo = item.Syntax.Token[len(item.Syntax.Token)-2]
wasmvmVersion = item.Syntax.Token[len(item.Syntax.Token)-1]
}
}
fmt.Printf("WasmVM from go.mod: repo: %s, version: %s\n", wasmvmRepo, wasmvmVersion)
if wasmvmVersion == "" {
return ""
}
return wasmvmRepo + " " + wasmvmVersion
}
// buildChainNodeDockerImage builds the requested chain node docker image
// based on the input configuration.
func (h *HeighlinerBuilder) buildChainNodeDockerImage(
chainConfig *ChainNodeDockerBuildConfig,
) error {
buildCfg := h.buildConfig
dockerfile := chainConfig.Build.Dockerfile
// DEPRECATION HANDLING
if chainConfig.Build.Language != "" {
fmt.Printf("'language' chain config property is deprecated, please use 'dockerfile' instead\n")
if dockerfile == "" {
dockerfile = chainConfig.Build.Language
}
}
for _, rep := range deprecationReplacements {
if dockerfile == rep[0] {
fmt.Printf("'dockerfile' value of '%s' is deprecated, please use '%s' instead\n", rep[0], rep[1])
dockerfile = rep[1]
}
}
// END DEPRECATION HANDLING
df := rawDockerfile(dockerfile, buildCfg.UseBuildKit, h.local)
tag := imageTag(chainConfig.Ref, chainConfig.Tag, h.local)
cwd, err := os.Getwd()
if err != nil {
return fmt.Errorf("error getting working directory: %w", err)
}
dir, err := os.MkdirTemp(cwd, "heighliner")
if err != nil {
return fmt.Errorf("error making temporary directory for dockerfile: %w", err)
}
// queue removal on ctrl+c
h.queueTmpDirRemoval(dir, true)
defer func() {
// this build is done, so don't need removal on ctrl+c anymore since we are removing now.
h.queueTmpDirRemoval(dir, false)
_ = os.RemoveAll(dir)
}()
reldir, err := filepath.Rel(cwd, dir)
if err != nil {
return fmt.Errorf("error finding relative path for dockerfile working directory: %w", err)
}
dfilepath := filepath.Join(reldir, "Dockerfile")
if err := os.WriteFile(dfilepath, df, 0644); err != nil {
return fmt.Errorf("error writing temporary dockerfile: %w", err)
}
var imageName string
if buildCfg.ContainerRegistry == "" {
imageName = chainConfig.Build.Name
} else {
imageName = fmt.Sprintf("%s/%s", buildCfg.ContainerRegistry, chainConfig.Build.Name)
}
imageTags := []string{fmt.Sprintf("%s:%s", imageName, tag)}
if chainConfig.Latest {
imageTags = append(imageTags, fmt.Sprintf("%s:latest", imageName))
}
buildFrom := "ref: " + chainConfig.Ref
if h.local {
buildFrom = "current working directory source"
}
buildEnv := ""
buildTagsEnvVar := ""
for _, envVar := range chainConfig.Build.BuildEnv {
envVarSplit := strings.Split(envVar, "=")
if envVarSplit[0] == "BUILD_TAGS" {
buildTagsEnvVar = envVar
} else {
buildEnv += envVar + " "
}
}
binaries := strings.Join(chainConfig.Build.Binaries, ",")
libraries := strings.Join(chainConfig.Build.Libraries, " ")
targetLibraries := strings.Join(chainConfig.Build.TargetLibraries, " ")
directories := strings.Join(chainConfig.Build.Directories, " ")
repoHost := chainConfig.Build.RepoHost
if repoHost == "" {
repoHost = "github.com"
}
buildTimestamp := ""
if buildCfg.NoBuildCache {
buildTimestamp = strconv.FormatInt(time.Now().Unix(), 10)
}
var gv GoVersion
var wasmvmVersion string
race := ""
modFile, err := getModFile(
repoHost, chainConfig.Build.GithubOrganization, chainConfig.Build.GithubRepo,
chainConfig.Ref, chainConfig.Build.BuildDir, h.local,
)
goVersion := buildCfg.GoVersion
if goVersion == "" && err == nil {
goVersion = modFile.Go.Version
}
if goVersion != "" {
gv = GetImageAndVersionForGoVersion(goVersion, buildCfg.AlpineVersion)
}
if dockerfile == DockerfileTypeCosmos || dockerfile == DockerfileTypeAvalanche {
if err != nil {
return fmt.Errorf("error getting mod file: %w", err)
}
wasmvmVersion = getWasmvmVersion(modFile)
if h.race {
race = "true"
buildEnv += " GOFLAGS=-race"
for i, imageTag := range imageTags {
imageTags[i] = imageTag + "-race"
}
}
fmt.Printf("Go version from go.mod: %s, will build with version: %s image: %s\n", modFile.Go.Version, gv.Version, gv.Image)
}
fmt.Printf("Building image from %s, resulting docker image tags: +%v\n", buildFrom, imageTags)
// If build dir is empty, add a "." for dockerfile compatibility
if chainConfig.Build.BuildDir == "" {
chainConfig.Build.BuildDir = "."
}
buildArgs := map[string]string{
"VERSION": chainConfig.Ref,
"BASE_VERSION": gv.Image,
"NAME": chainConfig.Build.Name,
"BASE_IMAGE": chainConfig.Build.BaseImage,
"REPO_HOST": repoHost,
"GITHUB_ORGANIZATION": chainConfig.Build.GithubOrganization,
"GITHUB_REPO": chainConfig.Build.GithubRepo,
"BUILD_TARGET": chainConfig.Build.BuildTarget,
"BINARIES": binaries,
"LIBRARIES": libraries,
"TARGET_LIBRARIES": targetLibraries,
"DIRECTORIES": directories,
"PRE_BUILD": chainConfig.Build.PreBuild,
"FINAL_IMAGE": chainConfig.Build.FinalImage,
"BUILD_ENV": buildEnv,
"BUILD_TAGS": buildTagsEnvVar,
"BUILD_DIR": chainConfig.Build.BuildDir,
"BUILD_TIMESTAMP": buildTimestamp,
"GO_VERSION": gv.Version,
"WASMVM_VERSION": wasmvmVersion,
"RACE": race,
}
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(time.Minute*180))
defer cancel()
push := buildCfg.ContainerRegistry != "" && !buildCfg.SkipPush
if buildCfg.UseBuildKit {
buildKitOptions := docker.GetDefaultBuildKitOptions()
buildKitOptions.Address = buildCfg.BuildKitAddr
supportedPlatforms := chainConfig.Build.Platforms
if len(supportedPlatforms) > 0 {
platforms := []string{}
requestedPlatforms := strings.Split(buildCfg.Platform, ",")
for _, supportedPlatform := range supportedPlatforms {
for _, requestedPlatform := range requestedPlatforms {
if supportedPlatform == requestedPlatform {
platforms = append(platforms, requestedPlatform)
}
}
}
if len(platforms) == 0 {
return fmt.Errorf("no requested platforms are supported for this chain: %s. requested: %s, supported: %s", chainConfig.Build.Name, buildCfg.Platform, strings.Join(supportedPlatforms, ","))
}
buildKitOptions.Platform = strings.Join(platforms, ",")
} else {
buildKitOptions.Platform = buildCfg.Platform
}
buildKitOptions.NoCache = buildCfg.NoCache
if err := docker.BuildDockerImageWithBuildKit(ctx, reldir, imageTags, push, buildCfg.TarExportPath, buildArgs, buildKitOptions); err != nil {
return err
}
} else {
if err := docker.BuildDockerImage(ctx, dfilepath, imageTags, push, buildArgs, buildCfg.NoCache); err != nil {
return err
}
}
return nil
}
// returns queue items, starting with latest for each chain
func (h *HeighlinerBuilder) getNextQueueItem() *ChainNodeDockerBuildConfig {
h.buildIndexMu.Lock()
defer h.buildIndexMu.Unlock()
j := 0
for i := 0; true; i++ {
foundForThisIndex := false
for _, queuedChainBuilds := range h.queue {
if i < len(queuedChainBuilds.ChainConfigs) {
if j == h.buildIndex {
h.buildIndex++
return &queuedChainBuilds.ChainConfigs[i]
}
j++
foundForThisIndex = true
}
}
if !foundForThisIndex {
// all done
return nil
}
}
return nil
}
func (h *HeighlinerBuilder) buildNextImage(wg *sync.WaitGroup) {
chainConfig := h.getNextQueueItem()
if chainConfig == nil {
wg.Done()
return
}
go func() {
if err := h.buildChainNodeDockerImage(chainConfig); err != nil {
h.errorsLock.Lock()
h.errors = append(h.errors, fmt.Errorf("error building docker image for %s from ref: %s - %v\n", chainConfig.Build.Name, chainConfig.Ref, err))
h.errorsLock.Unlock()
}
h.buildNextImage(wg)
}()
}
func (h *HeighlinerBuilder) queueTmpDirRemoval(tmpDir string, start bool) {
h.tmpDirMapMu.Lock()
defer h.tmpDirMapMu.Unlock()
if start {
h.tmpDirsToRemove[tmpDir] = true
} else {
delete(h.tmpDirsToRemove, tmpDir)
}
}
// registerSigIntHandler will delete tmp dirs on ctrl+c
func (h *HeighlinerBuilder) registerSigIntHandler() {
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
go func() {
<-c
h.tmpDirMapMu.Lock()
defer h.tmpDirMapMu.Unlock()
for dir := range h.tmpDirsToRemove {
_ = os.RemoveAll(dir)
}
os.Exit(1)
}()
}
func (h *HeighlinerBuilder) BuildImages() {
h.registerSigIntHandler()
wg := new(sync.WaitGroup)
for i := int16(0); i < h.parallel; i++ {
wg.Add(1)
h.buildNextImage(wg)
}
wg.Wait()
if len(h.errors) > 0 {
for _, err := range h.errors {
fmt.Println(err)
}
panic("Some images failed to build")
}
}