-
Notifications
You must be signed in to change notification settings - Fork 18
/
buildpack.go
605 lines (475 loc) · 15.5 KB
/
buildpack.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
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
/*
* 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 libpak
import (
"fmt"
"net/url"
"os"
"reflect"
"runtime"
"sort"
"strconv"
"strings"
"time"
"github.com/Masterminds/semver/v3"
"github.com/buildpacks/libcnb"
"github.com/heroku/color"
"github.com/paketo-buildpacks/libpak/bard"
"github.com/paketo-buildpacks/libpak/sbom"
)
// BuildpackConfiguration represents a build or launch configuration parameter.
type BuildpackConfiguration struct {
// Build indicates whether the configuration is for build-time. Optional.
Build bool `toml:"build"`
// Default is the default value of the configuration parameter. Optional.
Default string `toml:"default"`
// Description is the description of the configuration parameter.
Description string `toml:"description"`
// Launch indicates whether the configuration is for launch-time. Optional.
Launch bool `toml:"launch"`
// Name is the environment variable name of the configuration parameter.
Name string `toml:"name"`
}
// BuildpackDependencyLicense represents a license that a BuildpackDependency is distributed under. At least one of
// Name or URI MUST be specified.
type BuildpackDependencyLicense struct {
// Type is the type of the license. This is typically the SPDX short identifier.
Type string `toml:"type"`
// URI is the location where the license can be found.
URI string `toml:"uri"`
}
// BuildpackDependency describes a dependency known to the buildpack.
type BuildpackDependency struct {
// ID is the dependency ID.
ID string `toml:"id"`
// Name is the dependency name.
Name string `toml:"name"`
// Version is the dependency version.
Version string `toml:"version"`
// URI is the dependency URI.
URI string `toml:"uri"`
// SHA256 is the hash of the dependency.
SHA256 string `toml:"sha256"`
// Stacks are the stacks the dependency is compatible with.
Stacks []string `toml:"stacks"`
// Licenses are the licenses the dependency is distributed under.
Licenses []BuildpackDependencyLicense `toml:"licenses"`
// CPEs are the Common Platform Enumeration identifiers for the dependency
CPEs []string `toml:"cpes"`
// PURL is the package URL that identifies the dependency
PURL string `toml:"purl"`
// DeprecationDate is the time when the dependency is deprecated
DeprecationDate time.Time `toml:"deprecation_date"`
}
// Equals compares the 2 structs if they are equal. This is very simiar to reflect.DeepEqual
// except that properties that will not work (e.g. DeprecationDate) are ignored.
func (b1 BuildpackDependency) Equals(b2 BuildpackDependency) bool {
b1.DeprecationDate = b1.DeprecationDate.Truncate(time.Second).In(time.UTC)
b2.DeprecationDate = b2.DeprecationDate.Truncate(time.Second).In(time.UTC)
if len(b1.CPEs) == 0 {
b1.CPEs = nil
}
if len(b2.CPEs) == 0 {
b2.CPEs = nil
}
return reflect.DeepEqual(b1, b2)
}
// AsBOMEntry renders a bill of materials entry describing the dependency.
//
// Deprecated: as of Buildpacks RFC 95, use `BuildpackDependency.AsSyftArtifact` instead
func (b BuildpackDependency) AsBOMEntry() libcnb.BOMEntry {
return libcnb.BOMEntry{
Name: b.ID,
Metadata: map[string]interface{}{
"name": b.Name,
"version": b.Version,
"uri": b.URI,
"sha256": b.SHA256,
"stacks": b.Stacks,
"licenses": b.Licenses,
},
}
}
// AsSyftArtifact renders a bill of materials entry describing the dependency as Syft.
func (b BuildpackDependency) AsSyftArtifact() (sbom.SyftArtifact, error) {
licenses := []string{}
for _, license := range b.Licenses {
licenses = append(licenses, license.Type)
}
sbomArtifact := sbom.SyftArtifact{
Name: b.Name,
Version: b.Version,
Type: "UnknownPackage",
FoundBy: "libpak",
Licenses: licenses,
Locations: []sbom.SyftLocation{{Path: "buildpack.toml"}},
CPEs: b.CPEs,
PURL: b.PURL,
}
var err error
sbomArtifact.ID, err = sbomArtifact.Hash()
if err != nil {
return sbom.SyftArtifact{}, fmt.Errorf("unable to generate hash\n%w", err)
}
return sbomArtifact, nil
}
func (b BuildpackDependency) IsDeprecated() bool {
deprecationDate := b.DeprecationDate.UTC()
now := time.Now().UTC()
return deprecationDate.Equal(now) || deprecationDate.Before(now)
}
func (b BuildpackDependency) IsSoonDeprecated() bool {
deprecationDate := b.DeprecationDate.UTC()
now := time.Now().UTC()
return deprecationDate.Add(-30*24*time.Hour).Before(now) && deprecationDate.After(now)
}
// BuildpackMetadata is an extension to libcnb.Buildpack's metadata with opinions.
type BuildpackMetadata struct {
// Configurations are environment variables that can be used at build time to configure the buildpack and launch
// time to configure the application.
Configurations []BuildpackConfiguration
// Dependencies are the dependencies known to the buildpack.
Dependencies []BuildpackDependency
// IncludeFiles describes the files to include in the package.
IncludeFiles []string
// PrePackage describes a command to invoke before packaging.
PrePackage string
}
// NewBuildpackMetadata creates a new instance of BuildpackMetadata from the contents of libcnb.Buildpack.Metadata
func NewBuildpackMetadata(metadata map[string]interface{}) (BuildpackMetadata, error) {
m := BuildpackMetadata{}
if v, ok := metadata["configurations"]; ok {
for _, v := range v.([]map[string]interface{}) {
var c BuildpackConfiguration
if v, ok := v["build"].(bool); ok {
c.Build = v
}
if v, ok := v["default"].(string); ok {
c.Default = v
}
if v, ok := v["description"].(string); ok {
c.Description = v
}
if v, ok := v["launch"].(bool); ok {
c.Launch = v
}
if v, ok := v["name"].(string); ok {
c.Name = v
}
m.Configurations = append(m.Configurations, c)
}
}
if v, ok := metadata["dependencies"]; ok {
for _, v := range v.([]map[string]interface{}) {
var d BuildpackDependency
if v, ok := v["id"].(string); ok {
d.ID = v
}
if v, ok := v["name"].(string); ok {
d.Name = v
}
if v, ok := v["version"].(string); ok {
d.Version = v
}
if v, ok := v["uri"].(string); ok {
d.URI = v
}
if v, ok := v["sha256"].(string); ok {
d.SHA256 = v
}
if v, ok := v["stacks"].([]interface{}); ok {
for _, v := range v {
d.Stacks = append(d.Stacks, v.(string))
}
}
if v, ok := v["licenses"].([]map[string]interface{}); ok {
for _, v := range v {
var l BuildpackDependencyLicense
if v, ok := v["type"].(string); ok {
l.Type = v
}
if v, ok := v["uri"].(string); ok {
l.URI = v
}
d.Licenses = append(d.Licenses, l)
}
}
if v, ok := v["cpes"].([]interface{}); ok {
for _, v := range v {
d.CPEs = append(d.CPEs, v.(string))
}
}
if v, ok := v["purl"].(string); ok {
d.PURL = v
}
if v, ok := v["deprecation_date"].(string); ok {
deprecationDate, err := time.Parse(time.RFC3339, v)
if err != nil {
return BuildpackMetadata{}, fmt.Errorf("unable to parse deprecation date\n%w", err)
}
d.DeprecationDate = deprecationDate
}
m.Dependencies = append(m.Dependencies, d)
}
}
if v, ok := metadata["include-files"].([]interface{}); ok {
for _, v := range v {
m.IncludeFiles = append(m.IncludeFiles, v.(string))
}
}
if v, ok := metadata["pre-package"].(string); ok {
m.PrePackage = v
}
return m, nil
}
// ConfigurationResolver provides functionality for resolving a configuration value.
type ConfigurationResolver struct {
// Configurations are the configurations to resolve against
Configurations []BuildpackConfiguration
}
type configurationEntry struct {
Name string
Description string
Value string
}
func (c configurationEntry) String(nameLength int, valueLength int) string {
sb := strings.Builder{}
sb.WriteString("$")
sb.WriteString(c.Name)
for i := 0; i < nameLength-len(c.Name); i++ {
sb.WriteString(" ")
}
sb.WriteString(" ")
sb.WriteString(c.Value)
for i := 0; i < valueLength-len(c.Value); i++ {
sb.WriteString(" ")
}
if valueLength > 0 {
sb.WriteString(" ")
}
sb.WriteString(c.Description)
return sb.String()
}
// NewConfigurationResolver creates a new instance from buildpack metadata. Logs configuration options to the body
// level int the form 'Set $Name to configure $Description[. Default <i>$Default</i>.]'.
func NewConfigurationResolver(buildpack libcnb.Buildpack, logger *bard.Logger) (ConfigurationResolver, error) {
md, err := NewBuildpackMetadata(buildpack.Metadata)
if err != nil {
return ConfigurationResolver{}, fmt.Errorf("unable to unmarshal buildpack metadata\n%w", err)
}
cr := ConfigurationResolver{Configurations: md.Configurations}
if logger == nil {
return cr, nil
}
var (
build []configurationEntry
launch []configurationEntry
unknown []configurationEntry
nameLength int
valueLength int
)
sort.Slice(md.Configurations, func(i, j int) bool {
return md.Configurations[i].Name < md.Configurations[j].Name
})
for _, c := range md.Configurations {
s, _ := cr.Resolve(c.Name)
e := configurationEntry{
Name: c.Name,
Description: c.Description,
Value: s,
}
if l := len(e.Name); l > nameLength {
nameLength = l
}
if l := len(e.Value); l > valueLength {
valueLength = l
}
if c.Build {
build = append(build, e)
}
if c.Launch {
launch = append(launch, e)
}
if !c.Build && !c.Launch {
unknown = append(unknown, e)
}
}
f := color.New(color.Faint)
if len(build) > 0 {
logger.Header(f.Sprint("Build Configuration:"))
for _, e := range build {
logger.Body(e.String(nameLength, valueLength))
}
}
if len(launch) > 0 {
logger.Header(f.Sprint("Launch Configuration:"))
for _, e := range launch {
logger.Body(e.String(nameLength, valueLength))
}
}
if len(unknown) > 0 {
logger.Header(f.Sprint("Unknown Configuration:"))
for _, e := range unknown {
logger.Body(e.String(nameLength, valueLength))
}
}
return cr, nil
}
// Resolve resolves the value for a configuration option, returning the default value and false if it was not set.
func (c *ConfigurationResolver) Resolve(name string) (string, bool) {
if v, ok := os.LookupEnv(name); ok {
return v, ok
}
for _, c := range c.Configurations {
if c.Name == name {
return c.Default, false
}
}
return "", false
}
// ResolveBool resolves a boolean value for a configuration option. Returns true for 1, t, T, TRUE, true, True. Returns
// false for all other values or unset.
func (c *ConfigurationResolver) ResolveBool(name string) bool {
s, _ := c.Resolve(name)
t, err := strconv.ParseBool(s)
if err != nil {
return false
}
return t
}
// DependencyResolver provides functionality for resolving a dependency given a collection of constraints.
type DependencyResolver struct {
// Dependencies are the dependencies to resolve against.
Dependencies []BuildpackDependency
// StackID is the stack id of the build.
StackID string
// Logger is the logger used to write to the console.
Logger *bard.Logger
}
// NewDependencyResolver creates a new instance from the buildpack metadata and stack id.
func NewDependencyResolver(context libcnb.BuildContext) (DependencyResolver, error) {
md, err := NewBuildpackMetadata(context.Buildpack.Metadata)
if err != nil {
return DependencyResolver{}, fmt.Errorf("unable to unmarshal buildpack metadata\n%w", err)
}
return DependencyResolver{Dependencies: md.Dependencies, StackID: context.StackID}, nil
}
// NoValidDependenciesError is returned when the resolver cannot find any valid dependencies given the constraints.
type NoValidDependenciesError struct {
// Message is the error message
Message string
}
func (n NoValidDependenciesError) Error() string {
return n.Message
}
// IsNoValidDependencies indicates whether an error is a NoValidDependenciesError.
func IsNoValidDependencies(err error) bool {
_, ok := err.(NoValidDependenciesError)
return ok
}
// Resolve returns the latest version of a dependency within the collection of Dependencies. The candidate set is first
// filtered by the constraints, then the remaining candidates are sorted for the latest result by semver semantics.
// Version can contain wildcards and defaults to "*" if not specified.
func (d *DependencyResolver) Resolve(id string, version string) (BuildpackDependency, error) {
if version == "" {
version = "*"
}
vc, err := semver.NewConstraint(version)
if err != nil {
return BuildpackDependency{}, fmt.Errorf("invalid constraint %s\n%w", vc, err)
}
var candidates []BuildpackDependency
for _, c := range d.Dependencies {
v, err := semver.NewVersion(c.Version)
if err != nil {
return BuildpackDependency{}, fmt.Errorf("unable to parse version %s\n%w", c.Version, err)
}
// filter out deps that do not match the current running architecture
arch, err := archFromPURL(c.PURL)
if err != nil {
return BuildpackDependency{}, fmt.Errorf("unable to compare arch\n%w", err)
}
if arch != archFromSystem() {
continue
}
if c.ID == id && vc.Check(v) && d.contains(c.Stacks, d.StackID) {
candidates = append(candidates, c)
}
}
if len(candidates) == 0 {
return BuildpackDependency{}, NoValidDependenciesError{
Message: fmt.Sprintf("no valid dependencies for %s, %s, and %s in %s",
id, version, d.StackID, DependenciesFormatter(d.Dependencies)),
}
}
sort.Slice(candidates, func(i int, j int) bool {
a, _ := semver.NewVersion(candidates[i].Version)
b, _ := semver.NewVersion(candidates[j].Version)
return a.GreaterThan(b)
})
candidate := candidates[0]
if (candidate.DeprecationDate != time.Time{}) {
d.printDependencyDeprecation(candidate)
}
return candidate, nil
}
func archFromPURL(rawPURL string) (string, error) {
if len(strings.TrimSpace(rawPURL)) == 0 {
return "amd64", nil
}
purl, err := url.Parse(rawPURL)
if err != nil {
return "", fmt.Errorf("unable to parse PURL\n%w", err)
}
queryParams := purl.Query()
if arch, ok := queryParams["arch"]; ok {
return arch[0], nil
}
return archFromSystem(), nil
}
func archFromSystem() string {
archFromEnv, ok := os.LookupEnv("BP_ARCH")
if !ok {
archFromEnv = runtime.GOARCH
}
return archFromEnv
}
func (DependencyResolver) contains(candidates []string, value string) bool {
if len(candidates) == 0 {
return true
}
for _, c := range candidates {
if c == value || c == "*" {
return true
}
}
return false
}
func (d *DependencyResolver) printDependencyDeprecation(dependency BuildpackDependency) {
if d.Logger == nil {
return
}
f := color.New(color.FgYellow)
if dependency.IsDeprecated() {
d.Logger.Header(f.Sprint("Deprecation Notice:"))
d.Logger.Body(f.Sprintf("Version %s of %s is deprecated.", dependency.Version, dependency.Name))
d.Logger.Body(f.Sprintf("Migrate your application to a supported version of %s.", dependency.Name))
} else if dependency.IsSoonDeprecated() {
d.Logger.Header(f.Sprint("Deprecation Notice:"))
d.Logger.Body(f.Sprintf("Version %s of %s will be deprecated after %s.", dependency.Version, dependency.Name, dependency.DeprecationDate.Format("2006-01-02")))
d.Logger.Body(f.Sprintf("Migrate your application to a supported version of %s before this time.", dependency.Name))
}
}