-
Notifications
You must be signed in to change notification settings - Fork 13
/
build.go
392 lines (322 loc) · 12.3 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
389
390
391
392
/*
* Copyright 2018-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package libcnb
import (
"errors"
"fmt"
"os"
"path/filepath"
"reflect"
"strings"
"github.com/BurntSushi/toml"
"github.com/Masterminds/semver"
"github.com/buildpacks/libcnb/v2/internal"
"github.com/buildpacks/libcnb/v2/log"
)
// BuildContext contains the inputs to build.
type BuildContext struct {
// ApplicationPath is the location of the application source code as provided by
// the lifecycle.
ApplicationPath string
// Buildpack is metadata about the buildpack, from buildpack.toml.
Buildpack Buildpack
// Layers is the layers available to the buildpack.
Layers Layers
// Logger is the way to write messages to the end user
Logger log.Logger
// PersistentMetadata is metadata that is persisted even across cache cleaning.
PersistentMetadata map[string]interface{}
// Plan is the buildpack plan provided to the buildpack.
Plan BuildpackPlan
// Platform is the contents of the platform.
Platform Platform
// Deprecated: StackID is the ID of the stack.
StackID string
// TargetInfo contains info of the target (os, arch, ...).
TargetInfo TargetInfo
// TargetDistro is the target distribution (name, version).
TargetDistro TargetDistro
}
// BuildResult contains the results of detection.
type BuildResult struct {
// Labels are the image labels contributed by the buildpack.
Labels []Label
// Layers is the collection of LayerCreators contributed by the buildpack.
Layers []Layer
// PersistentMetadata is metadata that is persisted even across cache cleaning.
PersistentMetadata map[string]interface{}
// Processes are the process types contributed by the buildpack.
Processes []Process
// Slices are the application slices contributed by the buildpack.
Slices []Slice
// Unmet contains buildpack plan entries that were not satisfied by the buildpack and therefore should be
// passed to subsequent providers.
Unmet []UnmetPlanEntry
}
// Constants to track minimum and maximum supported Buildpack API versions
const (
// MinSupportedBPVersion indicates the minium supported version of the Buildpacks API
MinSupportedBPVersion = "0.8"
// MaxSupportedBPVersion indicates the maximum supported version of the Buildpacks API
MaxSupportedBPVersion = "0.10"
)
// NewBuildResult creates a new BuildResult instance, initializing empty fields.
func NewBuildResult() BuildResult {
return BuildResult{
PersistentMetadata: make(map[string]interface{}),
}
}
func (b BuildResult) String() string {
var l []string
for _, c := range b.Layers {
l = append(l, reflect.TypeOf(c).Name())
}
return fmt.Sprintf(
"{Labels:%+v Layers:%s PersistentMetadata:%+v Processes:%+v Slices:%+v, Unmet:%+v}",
b.Labels, l, b.PersistentMetadata, b.PersistentMetadata, b.Slices, b.Unmet,
)
}
// BuildFunc takes a context and returns a result, performing buildpack build behaviors.
type BuildFunc func(context BuildContext) (BuildResult, error)
// Build is called by the main function of a buildpack, for build.
func Build(build BuildFunc, config Config) {
var (
err error
file string
ok bool
)
ctx := BuildContext{Logger: config.logger}
ctx.ApplicationPath, err = os.Getwd()
if err != nil {
config.exitHandler.Error(fmt.Errorf("unable to get working directory\n%w", err))
return
}
if config.logger.IsDebugEnabled() {
if err := config.contentWriter.Write("Application contents", ctx.ApplicationPath); err != nil {
config.logger.Debugf("unable to write application contents\n%w", err)
}
}
if s, ok := os.LookupEnv(EnvBuildpackDirectory); ok {
ctx.Buildpack.Path = filepath.Clean(s)
} else {
config.exitHandler.Error(fmt.Errorf("unable to get CNB_BUILDPACK_DIR, not found"))
return
}
if config.logger.IsDebugEnabled() {
if err := config.contentWriter.Write("Buildpack contents", ctx.Buildpack.Path); err != nil {
config.logger.Debugf("unable to write buildpack contents\n%w", err)
}
}
file = filepath.Join(ctx.Buildpack.Path, "buildpack.toml")
if _, err = toml.DecodeFile(file, &ctx.Buildpack); err != nil && !os.IsNotExist(err) {
config.exitHandler.Error(fmt.Errorf("unable to decode buildpack %s\n%w", file, err))
return
}
config.logger.Debugf("Buildpack: %+v", ctx.Buildpack)
API, err := semver.NewVersion(ctx.Buildpack.API)
if err != nil {
config.exitHandler.Error(errors.New("version cannot be parsed"))
return
}
compatVersionCheck, _ := semver.NewConstraint(fmt.Sprintf(">= %s, <= %s", MinSupportedBPVersion, MaxSupportedBPVersion))
if !compatVersionCheck.Check(API) {
if MinSupportedBPVersion == MaxSupportedBPVersion {
config.exitHandler.Error(fmt.Errorf("this version of libcnb is only compatible with buildpack API == %s", MinSupportedBPVersion))
return
}
config.exitHandler.Error(fmt.Errorf("this version of libcnb is only compatible with buildpack APIs >= %s, <= %s", MinSupportedBPVersion, MaxSupportedBPVersion))
return
}
layersDir, ok := os.LookupEnv(EnvLayersDirectory)
if !ok {
config.exitHandler.Error(fmt.Errorf("expected CNB_LAYERS_DIR to be set"))
return
}
ctx.Layers = Layers{layersDir}
ctx.Platform.Path, ok = os.LookupEnv(EnvPlatformDirectory)
if !ok {
config.exitHandler.Error(fmt.Errorf("expected CNB_PLATFORM_DIR to be set"))
return
}
buildpackPlanPath, ok := os.LookupEnv(EnvBuildPlanPath)
if !ok {
config.exitHandler.Error(fmt.Errorf("expected CNB_BP_PLAN_PATH to be set"))
return
}
config.logger.Debugf("Layers: %+v", ctx.Layers)
if config.logger.IsDebugEnabled() {
if err := config.contentWriter.Write("Platform contents", ctx.Platform.Path); err != nil {
config.logger.Debugf("unable to write platform contents\n%w", err)
}
}
if ctx.Platform.Bindings, err = NewBindings(ctx.Platform.Path); err != nil {
config.exitHandler.Error(fmt.Errorf("unable to read platform bindings %s\n%w", ctx.Platform.Path, err))
return
}
config.logger.Debugf("Platform Bindings: %+v", ctx.Platform.Bindings)
file = filepath.Join(ctx.Platform.Path, "env")
if ctx.Platform.Environment, err = internal.NewConfigMapFromPath(file); err != nil {
config.exitHandler.Error(fmt.Errorf("unable to read platform environment %s\n%w", file, err))
return
}
config.logger.Debugf("Platform Environment: %s", ctx.Platform.Environment)
var store Store
file = filepath.Join(ctx.Layers.Path, "store.toml")
if _, err = toml.DecodeFile(file, &store); err != nil && !os.IsNotExist(err) {
config.exitHandler.Error(fmt.Errorf("unable to decode persistent metadata %s\n%w", file, err))
return
}
ctx.PersistentMetadata = store.Metadata
config.logger.Debugf("Persistent Metadata: %+v", ctx.PersistentMetadata)
if _, err = toml.DecodeFile(buildpackPlanPath, &ctx.Plan); err != nil && !os.IsNotExist(err) {
config.exitHandler.Error(fmt.Errorf("unable to decode buildpack plan %s\n%w", buildpackPlanPath, err))
return
}
config.logger.Debugf("Buildpack Plan: %+v", ctx.Plan)
if ctx.StackID, ok = os.LookupEnv(EnvStackID); !ok {
config.logger.Debug("CNB_STACK_ID not set")
} else {
config.logger.Debugf("Stack: %s", ctx.StackID)
}
if API.GreaterThan(semver.MustParse("0.9")) {
ctx.TargetInfo = TargetInfo{}
ctx.TargetInfo.OS, _ = os.LookupEnv(EnvTargetOS)
ctx.TargetInfo.Arch, _ = os.LookupEnv(EnvTargetArch)
ctx.TargetInfo.Variant, _ = os.LookupEnv(EnvTargetArchVariant)
config.logger.Debugf("System: %+v", ctx.TargetInfo)
ctx.TargetDistro = TargetDistro{}
ctx.TargetDistro.Name, _ = os.LookupEnv(EnvTargetDistroName)
ctx.TargetDistro.Version, _ = os.LookupEnv(EnvTargetDistroVersion)
config.logger.Debugf("Distro: %+v", ctx.TargetDistro)
}
result, err := build(ctx)
if err != nil {
config.exitHandler.Error(err)
return
}
config.logger.Debugf("Result: %+v", result)
file = filepath.Join(ctx.Layers.Path, "*.toml")
existing, err := filepath.Glob(file)
if err != nil {
config.exitHandler.Error(fmt.Errorf("unable to list files in %s\n%w", file, err))
return
}
var contributed []string
for _, layer := range result.Layers {
file = filepath.Join(layer.Path, "env.build")
config.logger.Debugf("Writing layer env.build: %s <= %+v", file, layer.BuildEnvironment)
if err = config.environmentWriter.Write(file, layer.BuildEnvironment); err != nil {
config.exitHandler.Error(fmt.Errorf("unable to write layer env.build %s\n%w", file, err))
return
}
file = filepath.Join(layer.Path, "env.launch")
config.logger.Debugf("Writing layer env.launch: %s <= %+v", file, layer.LaunchEnvironment)
if err = config.environmentWriter.Write(file, layer.LaunchEnvironment); err != nil {
config.exitHandler.Error(fmt.Errorf("unable to write layer env.launch %s\n%w", file, err))
return
}
file = filepath.Join(layer.Path, "env")
config.logger.Debugf("Writing layer env: %s <= %+v", file, layer.SharedEnvironment)
if err = config.environmentWriter.Write(file, layer.SharedEnvironment); err != nil {
config.exitHandler.Error(fmt.Errorf("unable to write layer env %s\n%w", file, err))
return
}
file = filepath.Join(ctx.Layers.Path, fmt.Sprintf("%s.toml", layer.Name))
config.logger.Debugf("Writing layer metadata: %s <= %+v", file, layer)
if err = config.tomlWriter.Write(file, layer); err != nil {
config.exitHandler.Error(fmt.Errorf("unable to write layer metadata %s\n%w", file, err))
return
}
contributed = append(contributed, file)
}
for _, e := range existing {
if strings.HasSuffix(e, "store.toml") || contains(contributed, e) {
continue
}
config.logger.Debugf("Removing %s", e)
if err := os.RemoveAll(e); err != nil {
config.exitHandler.Error(fmt.Errorf("unable to remove %s\n%w", e, err))
return
}
}
if err := validateSBOMFormats(ctx.Layers.Path, ctx.Buildpack.Info.SBOMFormats); err != nil {
config.exitHandler.Error(fmt.Errorf("unable to validate SBOM\n%w", err))
return
}
launch := LaunchTOML{
Labels: result.Labels,
Processes: result.Processes,
Slices: result.Slices,
}
if !launch.isEmpty() {
file = filepath.Join(ctx.Layers.Path, "launch.toml")
config.logger.Debugf("Writing application metadata: %s <= %+v", file, launch)
if err = config.tomlWriter.Write(file, launch); err != nil {
config.exitHandler.Error(fmt.Errorf("unable to write application metadata %s\n%w", file, err))
return
}
}
buildTOML := BuildTOML{
Unmet: result.Unmet,
}
if !buildTOML.isEmpty() {
file = filepath.Join(ctx.Layers.Path, "build.toml")
config.logger.Debugf("Writing build metadata: %s <= %+v", file, build)
if err = config.tomlWriter.Write(file, buildTOML); err != nil {
config.exitHandler.Error(fmt.Errorf("unable to write build metadata %s\n%w", file, err))
return
}
}
if len(result.PersistentMetadata) > 0 {
store = Store{
Metadata: result.PersistentMetadata,
}
file = filepath.Join(ctx.Layers.Path, "store.toml")
config.logger.Debugf("Writing persistent metadata: %s <= %+v", file, store)
if err = config.tomlWriter.Write(file, store); err != nil {
config.exitHandler.Error(fmt.Errorf("unable to write persistent metadata %s\n%w", file, err))
return
}
}
}
func contains(candidates []string, s string) bool {
for _, c := range candidates {
if s == c {
return true
}
}
return false
}
func validateSBOMFormats(layersPath string, acceptedSBOMFormats []string) error {
sbomFiles, err := filepath.Glob(filepath.Join(layersPath, "*.sbom.*"))
if err != nil {
return fmt.Errorf("unable find SBOM files\n%w", err)
}
for _, sbomFile := range sbomFiles {
parts := strings.Split(filepath.Base(sbomFile), ".")
if len(parts) <= 2 {
return fmt.Errorf("invalid format %s", filepath.Base(sbomFile))
}
sbomFormat, err := SBOMFormatFromString(strings.Join(parts[len(parts)-2:], "."))
if err != nil {
return fmt.Errorf("unable to parse SBOM %s\n%w", sbomFormat, err)
}
if !contains(acceptedSBOMFormats, sbomFormat.MediaType()) {
return fmt.Errorf("unable to find actual SBOM Type %s in list of supported SBOM types %s", sbomFormat.MediaType(), acceptedSBOMFormats)
}
}
return nil
}