-
Notifications
You must be signed in to change notification settings - Fork 26
/
build.go
388 lines (334 loc) · 11.2 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
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
package packit
import (
"errors"
"fmt"
"math"
"os"
"path/filepath"
"sort"
"strings"
"github.com/paketo-buildpacks/packit/v2/fs"
"github.com/BurntSushi/toml"
"github.com/Masterminds/semver/v3"
"github.com/paketo-buildpacks/packit/v2/internal"
)
// BuildFunc is the definition of a callback that can be invoked when the Build
// function is executed. Buildpack authors should implement a BuildFunc that
// performs the specific build phase operations for a buildpack.
type BuildFunc func(BuildContext) (BuildResult, error)
// BuildContext provides the contextual details that are made available by the
// buildpack lifecycle during the build phase. This context is populated by the
// Build function and passed to BuildFunc during execution.
type BuildContext struct {
// BuildpackInfo includes the details of the buildpack parsed from the
// buildpack.toml included in the buildpack contents.
BuildpackInfo BuildpackInfo
// CNBPath is the absolute path location of the buildpack contents.
// This path is useful for finding the buildpack.toml or any other
// files included in the buildpack.
CNBPath string
// Platform includes the platform context according to the specification:
// https://github.com/buildpacks/spec/blob/main/buildpack.md#build
Platform Platform
// Layers provides access to layers managed by the buildpack. It can be used
// to create new layers or retrieve cached layers from previous builds.
Layers Layers
// Plan includes the BuildpackPlan provided by the lifecycle as specified in
// the specification:
// https://github.com/buildpacks/spec/blob/main/buildpack.md#buildpack-plan-toml.
Plan BuildpackPlan
// Stack is the value of the chosen stack. This value is populated from the
// $CNB_STACK_ID environment variable.
Stack string
// WorkingDir is the location of the application source code as provided by
// the lifecycle.
WorkingDir string
}
// BuildResult allows buildpack authors to indicate the result of the build
// phase for a given buildpack. This result, returned in a BuildFunc callback,
// will be parsed and persisted by the Build function and returned to the
// lifecycle at the end of the build phase execution.
type BuildResult struct {
// Plan is the set of refinements to the Buildpack Plan that were performed
// during the build phase.
Plan BuildpackPlan
// Layers is a list of layers that will be persisted by the lifecycle at the
// end of the build phase. Layers not included in this list will not be made
// available to the lifecycle.
Layers []Layer
// Launch is the metadata that will be persisted as launch.toml according to
// the buildpack lifecycle specification:
// https://github.com/buildpacks/spec/blob/main/buildpack.md#launchtoml-toml
Launch LaunchMetadata
// Build is the metadata that will be persisted as build.toml according to
// the buildpack lifecycle specification:
// https://github.com/buildpacks/spec/blob/main/buildpack.md#buildtoml-toml
Build BuildMetadata
}
// Build is an implementation of the build phase according to the Cloud Native
// Buildpacks specification. Calling this function with a BuildFunc will
// perform the build phase process.
func Build(f BuildFunc, options ...Option) {
config := OptionConfig{
exitHandler: internal.NewExitHandler(),
args: os.Args,
tomlWriter: internal.NewTOMLWriter(),
envWriter: internal.NewEnvironmentWriter(),
fileWriter: internal.NewFileWriter(),
}
for _, option := range options {
config = option(config)
}
pwd, err := os.Getwd()
if err != nil {
config.exitHandler.Error(err)
return
}
planPath, ok := os.LookupEnv("CNB_BP_PLAN_PATH")
if !ok {
planPath = config.args[3]
}
var plan BuildpackPlan
_, err = toml.DecodeFile(planPath, &plan)
if err != nil {
config.exitHandler.Error(err)
return
}
cnbPath, ok := os.LookupEnv("CNB_BUILDPACK_DIR")
if !ok {
cnbPath = filepath.Clean(strings.TrimSuffix(config.args[0], filepath.Join("bin", "build")))
}
layersPath, ok := os.LookupEnv("CNB_LAYERS_DIR")
if !ok {
layersPath = config.args[1]
}
platformPath, ok := os.LookupEnv("CNB_PLATFORM_DIR")
if !ok {
platformPath = config.args[2]
}
var buildpackInfo struct {
APIVersion string `toml:"api"`
Buildpack BuildpackInfo `toml:"buildpack"`
}
_, err = toml.DecodeFile(filepath.Join(cnbPath, "buildpack.toml"), &buildpackInfo)
if err != nil {
config.exitHandler.Error(err)
return
}
apiV05, _ := semver.NewVersion("0.5")
apiV06, _ := semver.NewVersion("0.6")
apiV08, _ := semver.NewVersion("0.8")
apiV09, _ := semver.NewVersion("0.9")
apiVersion, err := semver.NewVersion(buildpackInfo.APIVersion)
if err != nil {
config.exitHandler.Error(err)
return
}
result, err := f(BuildContext{
CNBPath: cnbPath,
Platform: Platform{
Path: platformPath,
},
Stack: os.Getenv("CNB_STACK_ID"),
WorkingDir: pwd,
Plan: plan,
Layers: Layers{
Path: layersPath,
},
BuildpackInfo: buildpackInfo.Buildpack,
})
if err != nil {
config.exitHandler.Error(err)
return
}
if len(result.Plan.Entries) > 0 {
if apiVersion.GreaterThan(apiV05) || apiVersion.Equal(apiV05) {
config.exitHandler.Error(errors.New("buildpack plan is read only since Buildpack API v0.5"))
return
}
err = config.tomlWriter.Write(planPath, result.Plan)
if err != nil {
config.exitHandler.Error(err)
return
}
}
layerTomls, err := filepath.Glob(filepath.Join(layersPath, "*.toml"))
if err != nil {
config.exitHandler.Error(err)
return
}
if apiVersion.LessThan(apiV06) {
for _, file := range layerTomls {
if filepath.Base(file) != "launch.toml" && filepath.Base(file) != "store.toml" && filepath.Base(file) != "build.toml" {
err = os.Remove(file)
if err != nil {
config.exitHandler.Error(fmt.Errorf("failed to remove layer toml: %w", err))
return
}
}
}
}
for _, layer := range result.Layers {
err = config.tomlWriter.Write(filepath.Join(layersPath, fmt.Sprintf("%s.toml", layer.Name)), formattedLayer{layer, apiVersion})
if err != nil {
config.exitHandler.Error(err)
return
}
err = config.envWriter.Write(filepath.Join(layer.Path, "env"), layer.SharedEnv)
if err != nil {
config.exitHandler.Error(err)
return
}
err = config.envWriter.Write(filepath.Join(layer.Path, "env.launch"), layer.LaunchEnv)
if err != nil {
config.exitHandler.Error(err)
return
}
err = config.envWriter.Write(filepath.Join(layer.Path, "env.build"), layer.BuildEnv)
if err != nil {
config.exitHandler.Error(err)
return
}
for process, processEnv := range layer.ProcessLaunchEnv {
err = config.envWriter.Write(filepath.Join(layer.Path, "env.launch", process), processEnv)
if err != nil {
config.exitHandler.Error(err)
return
}
}
if layer.SBOM != nil {
if apiVersion.GreaterThan(apiV06) {
for _, format := range layer.SBOM.Formats() {
err = config.fileWriter.Write(filepath.Join(layersPath, fmt.Sprintf("%s.sbom.%s", layer.Name, format.Extension)), format.Content)
if err != nil {
config.exitHandler.Error(err)
return
}
}
} else {
config.exitHandler.Error(fmt.Errorf("%s.sbom.* output is only supported with Buildpack API v0.7 or higher", layer.Name))
return
}
}
if (apiVersion.GreaterThan(apiV05) || apiVersion.Equal(apiV05)) && len(layer.ExecD) > 0 {
execdDir := filepath.Join(layer.Path, "exec.d")
err = os.MkdirAll(execdDir, os.ModePerm)
if err != nil {
config.exitHandler.Error(err)
return
}
lexicalWidth := 1 + int(math.Log10(float64(len(layer.ExecD))))
for i, exe := range layer.ExecD {
err = fs.Copy(exe, filepath.Join(execdDir, fmt.Sprintf("%0*d-%s", lexicalWidth, i, filepath.Base(exe))))
if err != nil {
if errors.Is(err, os.ErrNotExist) {
err = fmt.Errorf("file %s does not exist. Be sure to include it in the buildpack.toml", exe)
}
config.exitHandler.Error(err)
return
}
}
}
}
if !result.Launch.isEmpty() {
if apiVersion.LessThan(apiV05) && len(result.Launch.BOM) > 0 {
config.exitHandler.Error(errors.New("BOM entries in launch.toml is only supported with Buildpack API v0.5 or higher"))
return
}
type label struct {
Key string `toml:"key"`
Value string `toml:"value"`
}
var launch struct {
Processes []Process `toml:"processes,omitempty"`
DirectProcesses []DirectProcess `toml:"processes,omitempty"`
Slices []Slice `toml:"slices"`
Labels []label `toml:"labels"`
BOM []BOMEntry `toml:"bom"`
}
if apiVersion.LessThan(apiV09) {
if result.Launch.DirectProcesses != nil {
config.exitHandler.Error(errors.New("direct processes can only be used with Buildpack API v0.9 or higher"))
return
}
launch.Processes = result.Launch.Processes
} else {
if result.Launch.Processes != nil {
config.exitHandler.Error(errors.New("non direct processes can only be used with Buildpack API v0.8 or lower"))
return
}
launch.DirectProcesses = result.Launch.DirectProcesses
}
if apiVersion.LessThan(apiV06) {
for _, process := range launch.Processes {
if process.Default {
config.exitHandler.Error(errors.New("processes can only be marked as default with Buildpack API v0.6 or higher"))
return
}
}
}
if apiVersion.LessThan(apiV08) {
for _, process := range launch.Processes {
if process.WorkingDirectory != "" {
config.exitHandler.Error(errors.New("processes can only have a specific working directory with Buildpack API v0.8 or higher"))
return
}
}
}
launch.Slices = result.Launch.Slices
launch.BOM = result.Launch.BOM
if len(result.Launch.Labels) > 0 {
launch.Labels = []label{}
for k, v := range result.Launch.Labels {
launch.Labels = append(launch.Labels, label{Key: k, Value: v})
}
sort.Slice(launch.Labels, func(i, j int) bool {
return launch.Labels[i].Key < launch.Labels[j].Key
})
}
err = config.tomlWriter.Write(filepath.Join(layersPath, "launch.toml"), launch)
if err != nil {
config.exitHandler.Error(err)
return
}
if result.Launch.SBOM != nil {
if apiVersion.GreaterThan(apiV06) {
for _, format := range result.Launch.SBOM.Formats() {
err = config.fileWriter.Write(filepath.Join(layersPath, fmt.Sprintf("launch.sbom.%s", format.Extension)), format.Content)
if err != nil {
config.exitHandler.Error(err)
return
}
}
} else {
config.exitHandler.Error(fmt.Errorf("launch.sbom.* output is only supported with Buildpack API v0.7 or higher"))
return
}
}
}
if !result.Build.isEmpty() {
if apiVersion.LessThan(apiV05) {
config.exitHandler.Error(fmt.Errorf("build.toml is only supported with Buildpack API v0.5 or higher"))
return
}
if result.Build.SBOM != nil {
if apiVersion.GreaterThan(apiV06) {
for _, format := range result.Build.SBOM.Formats() {
err = config.fileWriter.Write(filepath.Join(layersPath, fmt.Sprintf("build.sbom.%s", format.Extension)), format.Content)
if err != nil {
config.exitHandler.Error(err)
return
}
}
} else {
config.exitHandler.Error(fmt.Errorf("build.sbom.* output is only supported with Buildpack API v0.7 or higher"))
return
}
}
err = config.tomlWriter.Write(filepath.Join(layersPath, "build.toml"), result.Build)
if err != nil {
config.exitHandler.Error(err)
return
}
}
}