-
Notifications
You must be signed in to change notification settings - Fork 26
/
build.go
228 lines (186 loc) · 7.45 KB
/
build.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
package nodeengine
import (
"fmt"
"os"
"path/filepath"
"strconv"
"time"
"github.com/paketo-buildpacks/libnodejs"
"github.com/paketo-buildpacks/packit/v2"
"github.com/paketo-buildpacks/packit/v2/cargo"
"github.com/paketo-buildpacks/packit/v2/chronos"
"github.com/paketo-buildpacks/packit/v2/postal"
"github.com/paketo-buildpacks/packit/v2/sbom"
"github.com/paketo-buildpacks/packit/v2/scribe"
)
//go:generate faux --interface EntryResolver --output fakes/entry_resolver.go
type EntryResolver interface {
Resolve(name string, entries []packit.BuildpackPlanEntry, priorities []interface{}) (packit.BuildpackPlanEntry, []packit.BuildpackPlanEntry)
MergeLayerTypes(name string, entries []packit.BuildpackPlanEntry) (launch bool, build bool)
}
//go:generate faux --interface DependencyManager --output fakes/dependency_manager.go
type DependencyManager interface {
Resolve(path, id, version, stack string) (postal.Dependency, error)
Deliver(dependency postal.Dependency, cnbPath, layerPath, platformPath string) error
GenerateBillOfMaterials(dependencies ...postal.Dependency) []packit.BOMEntry
}
//go:generate faux --interface SBOMGenerator --output fakes/sbom_generator.go
type SBOMGenerator interface {
GenerateFromDependency(dependency postal.Dependency, dir string) (sbom.SBOM, error)
}
func IsLayerReusable(nodeLayer packit.Layer, depChecksum string, build bool, launch bool, logger scribe.Emitter) bool {
logger.Debug.Process("Checking if layer %s can be reused", nodeLayer.Path)
metadata := nodeLayer.Metadata
cachedChecksum, _ := metadata[DepKey].(string)
logger.Debug.Subprocess("Checksum of dependency: %s", depChecksum)
logger.Debug.Subprocess("Checksum of layer: %s", cachedChecksum)
cachedBuild, found := metadata[BuildKey].(bool)
buildOK := found && (build == cachedBuild)
logger.Debug.Subprocess("Build requirements match: %v", buildOK)
cachedLaunch, found := metadata[LaunchKey].(bool)
launchOK := found && (launch == cachedLaunch)
logger.Debug.Subprocess("Launch requirements match: %v", launchOK)
logger.Debug.Break()
return cargo.Checksum(depChecksum).MatchString(cachedChecksum) && buildOK && launchOK
}
func Build(entryResolver EntryResolver, dependencyManager DependencyManager, sbomGenerator SBOMGenerator, logger scribe.Emitter, clock chronos.Clock) packit.BuildFunc {
return func(context packit.BuildContext) (packit.BuildResult, error) {
logger.Title("%s %s", context.BuildpackInfo.Name, context.BuildpackInfo.Version)
var buildMetadata = packit.BuildMetadata{}
var launchMetadata = packit.LaunchMetadata{}
nodeLayer, err := context.Layers.Get(Node)
if err != nil {
return packit.BuildResult{}, err
}
logger.Process("Resolving Node Engine version")
entry, allEntries := libnodejs.ResolveNodeVersion(entryResolver.Resolve, context.Plan)
if entry.Name == "" && len(allEntries) == 0 {
logger.Process("Node no longer requested by plan, satisfied by extension")
logger.Process("Setting up launch layer for environment variables")
nodeLayer, err = nodeLayer.Reset()
if err != nil {
return packit.BuildResult{}, err
}
nodeLayer.Launch, nodeLayer.Build, nodeLayer.Cache = true, true, false
nodeLayer.Metadata = map[string]interface{}{
BuildKey: true,
LaunchKey: true,
}
nodeLayer.SharedEnv.Default("NODE_HOME", "")
} else {
logger.Candidates(allEntries)
version, _ := entry.Metadata["version"].(string)
dependency, err := dependencyManager.Resolve(filepath.Join(context.CNBPath, "buildpack.toml"), entry.Name, version, context.Stack)
if err != nil {
return packit.BuildResult{}, err
}
logger.SelectedDependency(entry, dependency, clock.Now())
sbomDisabled, err := checkSbomDisabled()
if err != nil {
return packit.BuildResult{}, err
}
var legacySBOM []packit.BOMEntry
if !sbomDisabled {
legacySBOM = dependencyManager.GenerateBillOfMaterials(dependency)
}
launch, build := entryResolver.MergeLayerTypes("node", context.Plan.Entries)
if build {
buildMetadata = packit.BuildMetadata{BOM: legacySBOM}
}
if launch {
launchMetadata = packit.LaunchMetadata{BOM: legacySBOM}
}
if IsLayerReusable(nodeLayer, dependency.Checksum, build, launch, logger) {
logger.Process("Reusing cached layer %s", nodeLayer.Path)
logger.Break()
nodeLayer.Launch, nodeLayer.Build, nodeLayer.Cache = launch, build, build
return packit.BuildResult{
Layers: []packit.Layer{nodeLayer},
Build: buildMetadata,
Launch: launchMetadata,
}, nil
}
logger.Process("Executing build process")
nodeLayer, err = nodeLayer.Reset()
if err != nil {
return packit.BuildResult{}, err
}
nodeLayer.Launch, nodeLayer.Build, nodeLayer.Cache = launch, build, build
nodeLayer.Metadata = map[string]interface{}{
DepKey: dependency.Checksum,
BuildKey: build,
LaunchKey: launch,
}
logger.Subprocess("Installing Node Engine %s", dependency.Version)
duration, err := clock.Measure(func() error {
return dependencyManager.Deliver(dependency, context.CNBPath, nodeLayer.Path, context.Platform.Path)
})
if err != nil {
return packit.BuildResult{}, err
}
logger.Action("Completed in %s", duration.Round(time.Millisecond))
logger.Break()
if sbomDisabled {
logger.Subprocess("Skipping SBOM generation for Node Engine")
logger.Break()
} else {
logger.GeneratingSBOM(nodeLayer.Path)
var sbomContent sbom.SBOM
duration, err = clock.Measure(func() error {
sbomContent, err = sbomGenerator.GenerateFromDependency(dependency, nodeLayer.Path)
return err
})
if err != nil {
return packit.BuildResult{}, err
}
logger.Action("Completed in %s", duration.Round(time.Millisecond))
logger.Break()
logger.FormattingSBOM(context.BuildpackInfo.SBOMFormats...)
nodeLayer.SBOM, err = sbomContent.InFormats(context.BuildpackInfo.SBOMFormats...)
if err != nil {
return packit.BuildResult{}, err
}
}
nodeLayer.SharedEnv.Default("NODE_HOME", nodeLayer.Path)
}
var optimizedMemory bool
if os.Getenv("BP_NODE_OPTIMIZE_MEMORY") == "true" {
optimizedMemory = true
}
nodeLayer.SharedEnv.Default("NODE_ENV", "production")
nodeLayer.SharedEnv.Default("NODE_VERBOSE", "false")
nodeLayer.SharedEnv.Default("NODE_OPTIONS", "--use-openssl-ca")
if optimizedMemory {
nodeLayer.LaunchEnv.Default("OPTIMIZE_MEMORY", "true")
}
logger.EnvironmentVariables(nodeLayer)
nodeLayer.ExecD = []string{
filepath.Join(context.CNBPath, "bin", "optimize-memory"),
filepath.Join(context.CNBPath, "bin", "inspector"),
}
logger.Subprocess("Writing exec.d/0-optimize-memory")
logger.Action("Calculates available memory based on container limits at launch time.")
logger.Action("Made available in the MEMORY_AVAILABLE environment variable.")
if optimizedMemory {
logger.Action("Assigns the NODE_OPTIONS environment variable with flag setting to optimize memory.")
logger.Action("Limits the total size of all objects on the heap to 75%% of the MEMORY_AVAILABLE.")
}
logger.Subprocess("Writing exec.d/1-inspector")
logger.Break()
return packit.BuildResult{
Layers: []packit.Layer{nodeLayer},
Build: buildMetadata,
Launch: launchMetadata,
}, nil
}
}
func checkSbomDisabled() (bool, error) {
if disableStr, ok := os.LookupEnv("BP_DISABLE_SBOM"); ok {
disable, err := strconv.ParseBool(disableStr)
if err != nil {
return false, fmt.Errorf("failed to parse BP_DISABLE_SBOM value %s: %w", disableStr, err)
}
return disable, nil
}
return false, nil
}