-
Notifications
You must be signed in to change notification settings - Fork 8
/
binary.go
219 lines (179 loc) · 6.59 KB
/
binary.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
// Copyright 2022 Namespace Labs Inc; All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
package binary
import (
"context"
"fmt"
"io/fs"
"os"
"path/filepath"
"strings"
"github.com/moby/buildkit/client/llb"
specs "github.com/opencontainers/image-spec/specs-go/v1"
"namespacelabs.dev/foundation/internal/build"
"namespacelabs.dev/foundation/internal/build/buildkit"
"namespacelabs.dev/foundation/internal/bytestream"
"namespacelabs.dev/foundation/internal/compute"
"namespacelabs.dev/foundation/internal/dependencies/pins"
"namespacelabs.dev/foundation/internal/fnerrors"
"namespacelabs.dev/foundation/internal/fnfs"
"namespacelabs.dev/foundation/internal/fnfs/memfs"
"namespacelabs.dev/foundation/internal/integrations/opaque"
"namespacelabs.dev/foundation/internal/llbutil"
"namespacelabs.dev/foundation/internal/parsing/platform"
"namespacelabs.dev/foundation/internal/workspace/dirs"
"namespacelabs.dev/foundation/schema"
"namespacelabs.dev/foundation/std/cfg"
)
const (
AppRootPath = "/app"
backendsConfigFn = "src/config/backends.ns.js"
)
var (
NodejsExclude = []string{"**/.yarn/cache", "**/.pnp.*"}
)
type nodeJsBinary struct {
nodejsEnv string
}
func (n nodeJsBinary) LLB(ctx context.Context, cfg cfg.Configuration, bnj buildNodeJS, conf build.Configuration) (llb.State, []buildkit.LocalContents, error) {
packageManagerState, err := LookupPackageManager(bnj.config.NodePkgMgr)
if err != nil {
return llb.State{}, nil, err
}
local := buildkit.LocalContents{
Module: conf.Workspace(),
Path: bnj.loc.Rel(),
ExcludePatterns: NodejsExclude,
}
src := buildkit.MakeLocalState(local)
var platform specs.Platform
if conf.TargetPlatform() != nil {
platform = *conf.TargetPlatform()
} else {
cli, err := compute.GetValue(ctx, buildkit.MakeClient(cfg, nil))
if err != nil {
return llb.State{}, nil, err
}
// Happens for Web builds where the output is platform-independent.
platform = cli.BuildkitOpts().HostPlatform
}
sub := conf.Workspace().ReadOnlyFS(bnj.loc.Rel())
devImage, err := createBaseImage(ctx, platform, src, sub, "development", packageManagerState)
if err != nil {
return llb.State{}, nil, err
}
devImage = devImage.With(llbutil.CopyFrom(src, ".", AppRootPath))
devImage, err = maybeGenerateBackendsJs(ctx, devImage, bnj)
if err != nil {
return llb.State{}, nil, err
}
var out llb.State
if opaque.UseDevBuild(bnj.env) {
out = devImage
} else {
config := bnj.config.Prod
var prodImage llb.State
if config.InstallDeps {
prodImage, err = createBaseImage(ctx, platform, src, sub, "production", packageManagerState)
if err != nil {
return llb.State{}, nil, err
}
} else {
prodImage = llb.Scratch()
}
if config.BuildScript != "" {
devImage = devImage.
// Important to build in the prod mode.
AddEnv("NODE_ENV", "production").
Run(
llb.Shlexf("%s run %s", packageManagerState.CLI, config.BuildScript),
llb.Dir(AppRootPath),
).Root()
}
pathToCopy := filepath.Join(AppRootPath, config.BuildOutDir)
destPath := pathToCopy
if config.BuildOutDir == "" {
destPath = "."
}
prodImage = prodImage.With(llbutil.CopyFromExcluding(devImage, pathToCopy, destPath,
append(packageManagerState.ExcludePatterns, dirs.BasePatternsToExclude...)))
out = prodImage
}
return out, []buildkit.LocalContents{local}, nil
}
func maybeGenerateBackendsJs(ctx context.Context, base llb.State, bnj buildNodeJS) (llb.State, error) {
if len(bnj.config.InternalDoNotUseBackend) == 0 {
return base, nil
}
// XXX replace with general purpose `genrule` layer.
if _, err := fs.Stat(bnj.loc.Module.ReadOnlyFS(), bnj.loc.Rel(backendsConfigFn)); os.IsNotExist(err) {
bytes, err := generateBackendsConfig(ctx, bnj.loc, bnj.config.InternalDoNotUseBackend, bnj.assets.IngressFragments,
&BackendsOpts{Placeholder: true})
if err != nil {
return llb.State{}, err
}
return base, fnerrors.NewWithLocation(bnj.loc, `%q must be present in the source tree when Web backends are used. Example content:
%s
`, backendsConfigFn, bytes)
}
bytes, err := generateBackendsConfig(ctx, bnj.loc, bnj.config.InternalDoNotUseBackend, bnj.assets.IngressFragments,
&BackendsOpts{Placeholder: false, UseInClusterAddresses: bnj.env.Purpose == schema.Environment_TESTING})
if err != nil {
return llb.State{}, err
}
var fsys memfs.FS
fsys.Add(backendsConfigFn, bytes)
return llbutil.Reforge(ctx, &fsys, base, AppRootPath)
}
// Copies package.json and other files from "src" that are needed for the "install" call.
func copySrcForInstall(ctx context.Context, base llb.State, src llb.State, fsys fs.FS, packageManagerState *PackageManager) (llb.State, error) {
opts := fnfs.MatcherOpts{
IncludeFiles: append([]string{"package.json"}, packageManagerState.RequiredFiles...),
ExcludeFilesGlobs: packageManagerState.ExcludePatterns,
}
for _, wc := range packageManagerState.WildcardDirectories {
opts.IncludeFilesGlobs = append(opts.IncludeFilesGlobs, wc+"/**/*")
}
m, err := fnfs.NewMatcher(opts)
if err != nil {
return llb.State{}, err
}
if err := fnfs.VisitFiles(ctx, fsys, func(path string, bs bytestream.ByteStream, _ fs.DirEntry) error {
if !m.Excludes(path) && m.Includes(path) {
base = base.With(llbutil.CopyFrom(src, path, filepath.Join(AppRootPath, path)))
}
return nil
}); err != nil {
return llb.State{}, err
}
return base, nil
}
func createBaseImage(ctx context.Context, p specs.Platform, src llb.State, fsys fs.FS, nodeEnv string, packageManagerState *PackageManager) (llb.State, error) {
nodeImage, err := pins.CheckDefault("node")
if err != nil {
return llb.State{}, err
}
baseImage := llbutil.Image(nodeImage, p).
AddEnv("NODE_ENV", nodeEnv).
File(llb.Mkdir(AppRootPath, 0644))
if packageManagerState.MakeState != nil {
baseImage = baseImage.With(packageManagerState.MakeState)
}
baseImage, err = copySrcForInstall(ctx, baseImage, src, fsys, packageManagerState)
if err != nil {
return llb.State{}, err
}
plfrm := strings.ReplaceAll(platform.FormatPlatform(p), "/", "-")
pkgMgrInstall := baseImage.
Run(
llb.Shlexf(packageManagerState.InstallCmd),
llb.Dir(AppRootPath),
)
pkgMgrInstall.AddMount(filepath.Join(containerCacheDir, packageManagerState.CacheKey), llb.Scratch(),
llb.AsPersistentCacheDir(fmt.Sprintf("%s-cache-%s-%s", packageManagerState.CacheKey, nodeEnv, plfrm),
// Not using a shared cache: it causes transient failures when the same files
// are accessed by multiple package manager instances.
llb.CacheMountPrivate))
return pkgMgrInstall.Root(), nil
}