-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathcli.go
More file actions
366 lines (320 loc) · 11.9 KB
/
cli.go
File metadata and controls
366 lines (320 loc) · 11.9 KB
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
package cli
import (
"archive/tar"
"compress/gzip"
"context"
"encoding/json"
"os"
"path/filepath"
"runtime"
"time"
"code.cloudfoundry.org/cnbapplifecycle/pkg/archive"
"code.cloudfoundry.org/cnbapplifecycle/pkg/buildpacks"
"code.cloudfoundry.org/cnbapplifecycle/pkg/credhub"
"code.cloudfoundry.org/cnbapplifecycle/pkg/databaseuri"
"code.cloudfoundry.org/cnbapplifecycle/pkg/errors"
"code.cloudfoundry.org/cnbapplifecycle/pkg/keychain"
"code.cloudfoundry.org/cnbapplifecycle/pkg/log"
"code.cloudfoundry.org/cnbapplifecycle/pkg/staging"
"github.com/spf13/cobra"
"github.com/buildpacks/pack/pkg/blob"
"github.com/buildpacks/pack/pkg/image"
"github.com/buildpacks/lifecycle/api"
"github.com/buildpacks/lifecycle/buildpack"
"github.com/buildpacks/lifecycle/cache"
"github.com/buildpacks/lifecycle/cmd"
"github.com/buildpacks/lifecycle/launch"
"github.com/buildpacks/lifecycle/layers"
"github.com/buildpacks/lifecycle/phase"
"github.com/buildpacks/lifecycle/platform"
"github.com/buildpacks/lifecycle/platform/files"
)
const (
PlatformAPI = "0.14"
DefaultLayersPath = "/home/vcap/layers"
DefaultWorkspacePath = "/home/vcap/workspace"
)
var (
layersDir string
workspaceDir string
cacheDir string
cacheOutputFile string
result string
dropletFile string
buildpackList []string
envVarNames []string
autoDetect bool
platformDir string
buildpacksDir string
systemBuildpacksDir string
extensionsDir string
downloadCacheDir string
credhubConnectionAttempts int
credhubRetryDelay time.Duration
)
func Execute() error {
return builderCmd.Execute()
}
func init() {
builderCmd.Flags().StringSliceVarP(&buildpackList, "buildpack", "b", nil, "buildpack(s) to use")
builderCmd.Flags().StringVarP(&systemBuildpacksDir, "system-buildpacks-dir", "", "/tmp/buildpacks", "system buildpacks dir")
builderCmd.Flags().StringVarP(&dropletFile, "droplet", "d", "/tmp/droplet", "output droplet file")
builderCmd.Flags().StringVarP(&result, "result", "r", "/tmp/result.json", "result file")
builderCmd.Flags().StringVarP(&workspaceDir, "workspace-dir", "w", DefaultWorkspacePath, "app workspace dir")
builderCmd.Flags().StringVarP(&layersDir, "layers", "l", DefaultLayersPath, "layers dir")
builderCmd.Flags().StringSliceVarP(&envVarNames, "pass-env-var", "", nil, "environment variable(s) to pass to buildpacks")
builderCmd.Flags().StringVarP(&cacheDir, "cache-dir", "c", "/tmp/cache", "cache dir")
builderCmd.Flags().StringVarP(&cacheOutputFile, "cache-output", "", "/tmp/cache-output.tgz", "cache output")
builderCmd.Flags().BoolVar(&autoDetect, "auto-detect", false, "run auto-detection with the provided buildpacks")
builderCmd.Flags().IntVar(&credhubConnectionAttempts, "credhub-connection-attempts", 3, "number of times that the credhub client will attempt to connect to credhub")
builderCmd.Flags().DurationVar(&credhubRetryDelay, "credhub-retry-delay", 1*time.Second, "delay duration that credhub client will wait before retries (ex. 1s, 2m, etc.)")
_ = builderCmd.MarkFlagRequired("buildpack")
}
var builderCmd = &cobra.Command{
Use: "builder",
SilenceUsage: true,
RunE: func(cobraCmd *cobra.Command, cmdArgs []string) error {
platformAPI := api.MustParse(PlatformAPI)
inputs := platform.NewLifecycleInputs(platformAPI)
cmd.DisableColor(inputs.NoColor)
logger := log.NewLogger()
if err := logger.SetLevel(inputs.LogLevel); err != nil {
logger.Errorf("failed to set log level to %q, error: %s\n", inputs.LogLevel, err.Error())
return errors.ErrGenericBuild
}
if err := credhub.InterpolateServiceRefs(credhubConnectionAttempts, credhubRetryDelay); err != nil {
logger.Error(err.Error())
return errors.ErrGenericBuild
}
databaseUrl, err := databaseuri.ParseDatabaseURI(os.Getenv("VCAP_SERVICES"))
if err != nil {
logger.Errorf("failed to parse database URI, error: %s\n", err.Error())
return errors.ErrGenericBuild
}
if databaseUrl != "" {
err = os.Setenv("DATABASE_URL", databaseUrl)
if err != nil {
logger.Errorf("Unable to set DATABASE_URL envirionment variable: %v", err)
return errors.ErrGenericBuild
}
}
tempDirs := map[string]*string{
"platform": &platformDir,
"buildpacks": &buildpacksDir,
"extensions": &extensionsDir,
"download-cache": &downloadCacheDir,
}
for name, dir := range tempDirs {
if *dir, err = os.MkdirTemp("", name); err != nil {
logger.Errorf("failed to create folder %q, error: %s\n", name, err.Error())
return errors.ErrGenericBuild
}
}
for _, dir := range []string{layersDir, cacheDir} {
if err := os.MkdirAll(dir, 0o755); err != nil {
logger.Errorf("failed to create %q, error: %s\n", dir, err.Error())
return errors.ErrGenericBuild
}
}
if err := staging.CreateEnvFiles(platformDir, envVarNames); err != nil {
logger.Errorf("failed to write env var files, error: %s\n", err.Error())
return errors.ErrGenericBuild
}
orderFile, err := os.CreateTemp("", "order.toml")
if err != nil {
logger.Errorf("failed to create 'order.toml', error: %s\n", err.Error())
return errors.ErrGenericBuild
}
analyzePath := filepath.Join(layersDir, "analyzed.toml")
analyzeMD, err := writeAnalyzed(analyzePath, logger)
if err != nil {
logger.Errorf("failed to create 'analyzed.toml', error: %s\n", err.Error())
return errors.ErrGenericBuild
}
creds, err := keychain.FromEnv()
if err != nil {
logger.Errorf("failed to parse %s environment variable, error: %s\n", keychain.CnbCredentialsEnv, err.Error())
return errors.ErrGenericBuild
}
buildpackList, err = buildpacks.Translate(buildpackList, systemBuildpacksDir, logger)
if err != nil {
logger.Errorf("failed to translate buildpack locations %#v, error: %s\n", buildpackList, err.Error())
return errors.ErrDownloadingBuildpack
}
err = buildpacks.DownloadBuildpacks(
buildpackList,
buildpacksDir,
image.NewFetcher(logger, nil, image.WithKeychain(creds)),
blob.NewDownloader(logger, downloadCacheDir, blob.WithClient(keychain.NewHTTPClient(creds))),
orderFile,
autoDetect,
logger,
)
if err != nil {
logger.Errorf("failed to download buildpacks, error: %s\n", err.Error())
return errors.ErrDownloadingBuildpack
}
dirStore := platform.NewDirStore(buildpacksDir, extensionsDir)
detectorFactory := phase.NewHermeticFactory(
platformAPI,
&cmd.BuildpackAPIVerifier{},
files.Handler,
dirStore,
)
detector, err := detectorFactory.NewDetector(platform.LifecycleInputs{
AnalyzedPath: analyzePath,
PlatformAPI: platformAPI,
AppDir: workspaceDir,
BuildpacksDir: buildpacksDir,
LayersDir: layersDir,
OrderPath: orderFile.Name(),
PlatformDir: platformDir,
CacheDir: cacheDir,
UseDaemon: false,
}, logger)
if err != nil {
logger.Errorf("failed creating detector, error: %s\n", err.Error())
return errors.ErrGenericBuild
}
logger.Phase("DETECTING")
bGroup, plan, err := detector.Detect()
if err != nil {
logger.Errorf("failed 'detect' phase, error: %s\n", err.Error())
return errors.ErrDetecting
}
logger.Phase("RESTORING")
cache, err := cache.NewVolumeCache(cacheDir, logger)
if err != nil {
logger.Errorf("failed to initialise cache, error: %s\n", err.Error())
return errors.ErrRestoring
}
restorer := phase.Restorer{
LayersDir: layersDir,
Logger: logger,
Buildpacks: bGroup.Group,
PlatformAPI: platformAPI,
}
if err := restorer.Restore(cache); err != nil {
logger.Errorf("failed to restore cached layers, error: %s\n", err.Error())
return errors.ErrRestoring
}
bldr := phase.Builder{
AppDir: workspaceDir,
LayersDir: layersDir,
PlatformDir: platformDir,
BuildExecutor: &buildpack.DefaultBuildExecutor{},
DirStore: dirStore,
Group: bGroup,
Logger: logger,
Out: os.Stdout,
Err: os.Stderr,
Plan: plan,
PlatformAPI: platformAPI,
AnalyzeMD: analyzeMD,
}
logger.Phase("BUILDING")
buildMeta, err := bldr.Build()
if err != nil {
logger.Errorf("failed 'build' phase, error: %s\n", err.Error())
return errors.ErrBuilding
}
ensureWebProcessType(buildMeta)
if err := files.Handler.WriteBuildMetadata(launch.GetMetadataFilePath(layersDir), buildMeta); err != nil {
logger.Errorf("failed writing build metadata, error: %s\n", err.Error())
return errors.ErrGenericBuild
}
artifactsDir, err := os.MkdirTemp("", "lifecycle.exporter.layer")
if err != nil {
logger.Errorf("create temp directory for artifacts, error: %s\n", err.Error())
return errors.ErrGenericBuild
}
exporter := phase.Exporter{
Buildpacks: bGroup.Group,
Logger: logger,
PlatformAPI: platformAPI,
LayerFactory: &layers.Factory{
ArtifactsDir: artifactsDir,
UID: inputs.UID,
GID: inputs.GID,
Logger: logger,
Ctx: context.Background(),
},
}
logger.Phase("EXPORTING")
if err := exporter.Cache(layersDir, cache); err != nil {
logger.Errorf("failed to save cached layers, error: %s\n", err.Error())
return errors.ErrExporting
}
cacheOutFile, err := os.OpenFile(cacheOutputFile, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o644)
if err != nil {
logger.Errorf("Failed to open %q, error: %s\n", cacheOutputFile, err.Error())
return errors.ErrGenericBuild
}
defer cacheOutFile.Close()
cgw := gzip.NewWriter(cacheOutFile)
defer cgw.Close()
if err := archive.FromDirectory(cacheDir, tar.NewWriter(cgw)); err != nil {
logger.Errorf("failed to save archive cache folder, error: %s\n", err.Error())
return errors.ErrExporting
}
resultData := staging.StagingResultFromMetadata(buildMeta)
resultBytes, err := json.Marshal(resultData)
if err != nil {
logger.Errorf("failed to marshal '/tmp/result.json', error: %s\n", err.Error())
return errors.ErrGenericBuild
}
if err := os.WriteFile(result, resultBytes, 0o644); err != nil {
logger.Errorf("failed to write '/tmp/result.json', error: %s\n", err.Error())
return errors.ErrGenericBuild
}
logger.Infof("result file saved to %q", result)
dropletOutFile, err := os.OpenFile(dropletFile, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o644)
if err != nil {
logger.Errorf("failed to open %q, error: %s\n", dropletFile, err.Error())
return errors.ErrGenericBuild
}
defer dropletOutFile.Close()
dgw := gzip.NewWriter(dropletOutFile)
defer dgw.Close()
if err := staging.RemoveBuildOnlyLayers(layersDir, bGroup.Group, logger); err != nil {
logger.Errorf("failed to remove build-only layers, error: %s\n", err.Error())
return errors.ErrExporting
}
if err := archive.FromDirectory(filepath.Dir(workspaceDir), tar.NewWriter(dgw)); err != nil {
logger.Errorf("failed 'export' phase, error: %s\n", err.Error())
return errors.ErrExporting
}
logger.Infof("droplet archive saved to %q", dropletFile)
return nil
},
}
func writeAnalyzed(path string, logger *log.Logger) (files.Analyzed, error) {
analyzed := files.Analyzed{
RunImage: &files.RunImage{
TargetMetadata: &files.TargetMetadata{
OS: "linux",
Arch: runtime.GOARCH,
},
},
}
return analyzed, files.Handler.WriteAnalyzed(path, &analyzed, logger)
}
// cloudfoundry expects a web process type to exist
// this will create a web process type identical to the default process type set by the buildpack if one does not exist
func ensureWebProcessType(buildMeta *files.BuildMetadata) {
var defaultProcess launch.Process
hasWebProcessType := false
for _, process := range buildMeta.Processes {
if process.Type == "web" {
hasWebProcessType = true
break
}
if process.Type == buildMeta.BuildpackDefaultProcessType || len(buildMeta.Processes) == 1 {
defaultProcess = process
}
}
if !hasWebProcessType && defaultProcess.Type != "" {
defaultProcess.Type = "web"
buildMeta.Processes = append(buildMeta.Processes, defaultProcess)
}
}