forked from project-dalec/dalec
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcache.go
More file actions
598 lines (506 loc) · 18.1 KB
/
cache.go
File metadata and controls
598 lines (506 loc) · 18.1 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
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
package dalec
import (
"errors"
"fmt"
"path/filepath"
"github.com/containerd/platforms"
"github.com/moby/buildkit/client/llb"
"github.com/opencontainers/go-digest"
ocispecs "github.com/opencontainers/image-spec/specs-go/v1"
)
const (
cacheMountShared = "shared" // llb.CacheMountShared
cacheMountLocked = "locked" // llb.CacheMountLocked
cacheMountPrivate = "private" // llb.CacheMountPrivate
cacheMountUnset = ""
BazelDefaultSocketID = "bazel-default" // Default ID for bazel socket
)
// getSccacheSource returns a Source for downloading and verifying sccache using SourceHTTP
func getSccacheSource(p *ocispecs.Platform) Source {
// sccache version and download configuration
const (
sccacheVersion = "v0.10.0"
sccacheDownloadURL = "https://github.com/mozilla/sccache/releases/download"
)
// Determine architecture string and checksum based on platform
var arch, checksum string
switch {
case p.Architecture == "amd64":
arch = "x86_64-unknown-linux-musl"
checksum = "1fbb35e135660d04a2d5e42b59c7874d39b3deb17de56330b25b713ec59f849b"
case p.Architecture == "arm64":
arch = "aarch64-unknown-linux-musl"
checksum = "d6a1ce4acd02b937cd61bc675a8be029a60f7bc167594c33d75732bbc0a07400"
case p.Architecture == "arm" && p.Variant == "v7":
arch = "armv7-unknown-linux-musleabi"
checksum = "ab7af4e5c78aa71f38145e7bed41dd944d99ce5a00339424d927f8bbd8b61b78"
default:
// Fallback to linux x64 for unsupported platforms
arch = "x86_64-unknown-linux-musl"
checksum = "1fbb35e135660d04a2d5e42b59c7874d39b3deb17de56330b25b713ec59f849b"
}
// Build download URL
url := fmt.Sprintf("%s/%s/sccache-%s-%s.tar.gz", sccacheDownloadURL, sccacheVersion, sccacheVersion, arch)
return Source{
HTTP: &SourceHTTP{
URL: url,
Digest: digest.Digest("sha256:" + checksum),
},
}
}
// CacheConfig configures a cache to use for a build.
type CacheConfig struct {
// Dir specifies a generic cache directory configuration.
Dir *CacheDir `json:"dir,omitempty" yaml:"dir,omitempty" jsonschema:"oneof_required=dir"`
// GoBuild specifies a cache for Go's incremental build artifacts.
// This should speed up repeated builds of Go projects.
GoBuild *GoBuildCache `json:"gobuild,omitempty" yaml:"gobuild,omitempty" jsonschema:"oneof_required=gobuild"`
// RustSCCache specifies a cache for Rust build artifacts.
// This uses sccache to cache Rust compilation artifacts.
RustSCCache *SCCache `json:"rustsccache,omitempty" yaml:"rustsccache,omitempty" jsonschema:"oneof_required=rustsccache"`
// Bazel specifies a cache for bazel builds.
Bazel *BazelCache `json:"bazel,omitempty" yaml:"bazel,omitempty" jsonschema:"oneof_required=bazel-local"`
}
type CacheInfo struct {
DirInfo CacheDirInfo
GoBuild GoBuildCacheInfo
RustSCCache SCCacheInfo
Bazel BazelCacheInfo
}
type CacheDirInfo struct {
// Platform sets the platform used to generate part of the cache key when
// CacheDir.NoAutoNamespace is set to false.
Platform *ocispecs.Platform
}
type CacheConfigOption interface {
SetCacheConfigOption(*CacheInfo)
}
type CacheConfigOptionFunc func(*CacheInfo)
func (f CacheConfigOptionFunc) SetCacheConfigOption(info *CacheInfo) {
f(info)
}
type CacheDirOption interface {
SetCacheDirOption(*CacheDirInfo)
}
type CacheDirOptionFunc func(*CacheDirInfo)
func (f CacheDirOptionFunc) SetCacheDirOption(info *CacheDirInfo) {
f(info)
}
func WithCacheDirConstraints(opts ...llb.ConstraintsOpt) CacheConfigOption {
return CacheConfigOptionFunc(func(info *CacheInfo) {
var c llb.Constraints
for _, opt := range opts {
opt.SetConstraintsOption(&c)
}
info.DirInfo.Platform = c.Platform
})
}
func (c *CacheConfig) ToRunOption(worker llb.State, distroKey string, opts ...CacheConfigOption) llb.RunOption {
if c.Dir != nil {
return c.Dir.ToRunOption(distroKey, CacheDirOptionFunc(func(info *CacheDirInfo) {
var cacheInfo CacheInfo
for _, opt := range opts {
opt.SetCacheConfigOption(&cacheInfo)
}
*info = cacheInfo.DirInfo
}))
}
if c.GoBuild != nil {
return c.GoBuild.ToRunOption(distroKey, GoBuildCacheOptionFunc(func(info *GoBuildCacheInfo) {
var cacheInfo CacheInfo
for _, opt := range opts {
opt.SetCacheConfigOption(&cacheInfo)
}
*info = cacheInfo.GoBuild
}))
}
if c.RustSCCache != nil {
return c.RustSCCache.ToRunOption(distroKey, SCCacheOptionFunc(func(info *SCCacheInfo) {
var cacheInfo CacheInfo
for _, opt := range opts {
opt.SetCacheConfigOption(&cacheInfo)
}
*info = cacheInfo.RustSCCache
}))
}
if c.Bazel != nil {
return c.Bazel.ToRunOption(worker, distroKey, BazelCacheOptionFunc(func(info *BazelCacheInfo) {
var cacheInfo CacheInfo
for _, opt := range opts {
opt.SetCacheConfigOption(&cacheInfo)
}
*info = cacheInfo.Bazel
}))
}
// Should not reach this point
panic("invalid cache config")
}
func (c *CacheConfig) validate() error {
if c == nil {
return nil
}
var count int
if c.Dir != nil {
count++
}
if c.GoBuild != nil {
count++
}
if c.RustSCCache != nil {
count++
}
if c.Bazel != nil {
count++
}
if count != 1 {
return fmt.Errorf("invalid cache config: exactly one of (dir, gobuild, rustsccache, bazel) must be set")
}
var errs []error
if c.Dir != nil {
if err := c.Dir.validate(); err != nil {
errs = append(errs, fmt.Errorf("invalid cache dir config: %w", err))
}
}
if c.GoBuild != nil {
if err := c.GoBuild.validate(); err != nil {
errs = append(errs, fmt.Errorf("invalid go build cache config: %w", err))
}
}
if c.RustSCCache != nil {
if err := c.RustSCCache.validate(); err != nil {
errs = append(errs, fmt.Errorf("invalid rust sccache config: %w", err))
}
}
if c.Bazel != nil {
if err := c.Bazel.validate(); err != nil {
errs = append(errs, fmt.Errorf("invalid bazel cache config: %w", err))
}
}
if len(errs) > 0 {
return errors.Join(errs...)
}
return nil
}
// CacheDir is a generic cache directory configuration.
type CacheDir struct {
// Key is the cache key to use.
// If not set then the dest will be used.
Key string `json:"key" yaml:"key"`
// Dest is the directory to mount the cache to.
Dest string `json:"dest" yaml:"dest" jsonschema:"required"`
// Sharing is the sharing mode of the cache.
// It can be one of the following:
// - shared: multiple jobs can use the cache at the same time.
// - locked: exclusive access to the cache is required.
// - private: changes to the cache are not shared with other jobs and are discarded
// after the job is finished.
Sharing string `json:"sharing" yaml:"sharing" jsonschema:"enum=shared,enum=locked,enum=private"`
// NoAutoNamespace disables the automatic prefixing of the cache key with the
// target specific information such as distro and CPU architecture, which may
// be auto-injected to prevent common issues that would cause an invalid cache.
NoAutoNamespace bool `json:"no_auto_namespace" yaml:"no_auto_namespace"`
}
func (c *CacheDir) ToRunOption(distroKey string, opts ...CacheDirOption) llb.RunOption {
return RunOptFunc(func(ei *llb.ExecInfo) {
var sharing llb.CacheMountSharingMode
switch c.Sharing {
case cacheMountShared, cacheMountUnset:
sharing = llb.CacheMountShared
case cacheMountLocked:
sharing = llb.CacheMountLocked
case cacheMountPrivate:
sharing = llb.CacheMountPrivate
default:
// validation needs to happen before this point
// if we got here then this is a bug
panic("invalid cache sharing mode")
}
key := c.Key
if key == "" {
// No key is set, so use the destination as the key.
key = c.Dest
}
var info CacheDirInfo
for _, opt := range opts {
opt.SetCacheDirOption(&info)
}
if !c.NoAutoNamespace {
platform := ei.Platform
if platform == nil {
platform = info.Platform
}
if platform == nil {
p := platforms.DefaultSpec()
platform = &p
}
key = fmt.Sprintf("%s-%s-%s", distroKey, platforms.Format(*platform), key)
}
llb.AddMount(c.Dest, llb.Scratch(), llb.AsPersistentCacheDir(key, sharing)).SetRunOption(ei)
})
}
func (c *CacheDir) validate() error {
var errs []error
if c.Dest == "" {
errs = append(errs, fmt.Errorf("cache dir dest is required"))
}
if !filepath.IsAbs(c.Dest) {
errs = append(errs, fmt.Errorf("cache dir dest must be an absolute path: %s", c.Dest))
}
switch c.Sharing {
case cacheMountShared, cacheMountLocked, cacheMountPrivate, cacheMountUnset:
default:
errs = append(errs, fmt.Errorf("invalid cache dir sharing mode: %s, valid values: %v", c.Sharing, []string{cacheMountShared, cacheMountLocked, cacheMountPrivate}))
}
if len(errs) > 0 {
return errors.Join(errs...)
}
return nil
}
// GoBuildCache is a cache for Go build artifacts.
// It is used to speed up Go builds by caching the incremental builds.
type GoBuildCache struct {
// Scope adds extra information to the cache key.
// This is useful to differentiate between different build contexts if required.
//
// This is mainly intended for internal testing purposes.
Scope string `json:"scope,omitempty" yaml:"scope,omitempty"`
// The gobuild cache may be automatically injected into a build if
// go is detected.
// Disabled explicitly turns this off.
Disabled bool `json:"disabled,omitempty" yaml:"disabled,omitempty"`
}
func (c *GoBuildCache) validate() error {
return nil
}
type GoBuildCacheInfo struct {
Platform *ocispecs.Platform
}
type GoBuildCacheOption interface {
SetGoBuildCacheOption(*GoBuildCacheInfo)
}
type GoBuildCacheOptionFunc func(*GoBuildCacheInfo)
func (f GoBuildCacheOptionFunc) SetGoBuildCacheOption(info *GoBuildCacheInfo) {
f(info)
}
func WithGoCacheConstraints(opts ...llb.ConstraintsOpt) CacheConfigOption {
return CacheConfigOptionFunc(func(info *CacheInfo) {
var c llb.Constraints
for _, opt := range opts {
opt.SetConstraintsOption(&c)
}
info.GoBuild.Platform = c.Platform
})
}
const goBuildCacheDir = "/tmp/dalec/gobuild-cache"
func (c *GoBuildCache) ToRunOption(distroKey string, opts ...GoBuildCacheOption) llb.RunOption {
return RunOptFunc(func(ei *llb.ExecInfo) {
if c.Disabled {
return
}
var info GoBuildCacheInfo
for _, opt := range opts {
opt.SetGoBuildCacheOption(&info)
}
platform := ei.Platform
if platform == nil {
platform = info.Platform
}
if platform == nil {
p := platforms.DefaultSpec()
platform = &p
}
key := fmt.Sprintf("%s-%s-dalec-gobuildcache", distroKey, platforms.Format(*platform))
if c.Scope != "" {
key = fmt.Sprintf("%s-%s", key, c.Scope)
}
llb.AddMount(goBuildCacheDir, llb.Scratch(), llb.AsPersistentCacheDir(key, llb.CacheMountShared)).SetRunOption(ei)
llb.AddEnv("GOCACHE", goBuildCacheDir).SetRunOption(ei)
})
}
// SCCache is a cache for Rust build artifacts.
// It uses sccache to speed up Rust compilation by caching build artifacts.
//
// NOTE: This cache downloads a pre-compiled binary from GitHub. Users must
// explicitly include this cache in their configuration to use it, which serves
// as acknowledgment of the external dependency.
//
// Future enhancement: Add support for providing sccache via build context instead of
// downloading from GitHub. This would add Source and BinaryPath fields to allow users
// to include their own verified sccache binary in the build context.
type SCCache struct {
// Scope adds extra information to the cache key.
// This is useful to differentiate between different build contexts if required.
//
// This is mainly intended for internal testing purposes.
Scope string `json:"scope,omitempty" yaml:"scope,omitempty"`
}
func (c *SCCache) validate() error {
return nil
}
type SCCacheInfo struct {
Platform *ocispecs.Platform
}
type SCCacheOption interface {
SetSCCacheOption(*SCCacheInfo)
}
type SCCacheOptionFunc func(*SCCacheInfo)
func (f SCCacheOptionFunc) SetSCCacheOption(info *SCCacheInfo) {
f(info)
}
const (
sccacheCacheDir = "/tmp/dalec/sccache-cache"
sccacheBinary = "/tmp/internal/dalec/sccache/sccache"
)
func (c *SCCache) ToRunOption(distroKey string, opts ...SCCacheOption) llb.RunOption {
// TODO: Future improvement - allow pulling sccache from build context instead of GitHub
// This would provide better security and flexibility by allowing users to:
// 1. Bring their own verified sccache binary
// 2. Use different versions than the hardcoded v0.10.0
// 3. Work in offline environments
// 4. Avoid external downloads during build time
//
// Implementation would add Source and BinaryPath fields to SCCache struct
// to allow specifying a context source like: { "context": { "name": "." }, "path": "tools/sccache" }
return RunOptFunc(func(ei *llb.ExecInfo) {
var info SCCacheInfo
for _, opt := range opts {
opt.SetSCCacheOption(&info)
}
// Ensure platform is set
var platform *ocispecs.Platform
if ei.Platform != nil {
platform = ei.Platform
} else if info.Platform != nil {
platform = info.Platform
} else {
p := platforms.DefaultSpec()
platform = &p
}
key := fmt.Sprintf("%s-%s-dalec-rustsccache", distroKey, platforms.Format(*platform))
if c.Scope != "" {
key = fmt.Sprintf("%s-%s", key, c.Scope)
}
// Set up cache mount for sccache compilation cache
llb.AddMount(sccacheCacheDir, llb.Scratch(), llb.AsPersistentCacheDir(key, llb.CacheMountShared)).SetRunOption(ei)
// Set up environment variables
llb.AddEnv("SCCACHE_DIR", sccacheCacheDir).SetRunOption(ei)
// Always download and set up precompiled sccache for consistent behavior
sccacheSource := getSccacheSource(platform)
// Use HTTP download directly since we're in a RunOption context without SourceOpts
sccacheDownload := llb.HTTP(sccacheSource.HTTP.URL, llb.Filename("sccache.tar.gz"))
// Extract sccache binary using LLB state operations
extractedSccache := ei.State.Run(
llb.AddMount("/tmp/internal/dalec/sccache-download", sccacheDownload, llb.Readonly),
ShArgs(`set -e
# Create temporary extraction directory
mkdir -p /tmp/internal/dalec/sccache-extract
# Extract sccache from tar.gz - the archive contains a versioned directory like sccache-v0.10.0-x86_64-unknown-linux-musl/
tar -xzf /tmp/internal/dalec/sccache-download/sccache.tar.gz -C /tmp/internal/dalec/sccache-extract/
# Find the sccache binary and copy it to output
sccache_bin=$(find /tmp/internal/dalec/sccache-extract/ -name "sccache" -type f | head -1)
if [ -n "$sccache_bin" ]; then
cp "$sccache_bin" /output/sccache && chmod +x /output/sccache
echo "sccache binary extracted successfully"
else
echo "Warning: sccache binary not found in archive" >&2
exit 1
fi`),
).AddMount("/output", llb.Scratch())
// Mount the extracted sccache binary to a temp directory
llb.AddMount(sccacheBinary, extractedSccache, llb.SourcePath("sccache")).SetRunOption(ei)
// Set up RUSTC_WRAPPER to point at the absolute sccache binary path (no PATH update needed)
llb.AddEnv("RUSTC_WRAPPER", sccacheBinary).SetRunOption(ei)
})
} // BazelCache sets up a cache for bazel builds.
// Currently this only supports setting up a *local* bazel cache.
//
// BazelCache relies on the *system* bazelrc file to configure the default cache location.
// If the project being built includes its own bazelrc it may override the one configured by BazelCache.
//
// An alternative to BazelCache would be a [CacheDir] and use `--disk_cache` to set the cache location
// when executing bazel commands.
type BazelCache struct {
// Scope adds extra information to the cache key.
// This is useful to differentiate between different build contexts if required.
//
// This is mainly intended for internal testing purposes.
Scope string `json:"scope,omitempty" yaml:"scope,omitepty"`
}
func (c *BazelCache) validate() error {
return nil
}
type BazelCacheInfo struct {
Platform *ocispecs.Platform
constraints *llb.Constraints
}
func WithBazelCacheConstraints(opts ...llb.ConstraintsOpt) CacheConfigOption {
return CacheConfigOptionFunc(func(info *CacheInfo) {
var c llb.Constraints
for _, opt := range opts {
opt.SetConstraintsOption(&c)
}
info.Bazel.Platform = c.Platform
info.Bazel.constraints = &c
})
}
type BazelCacheOptionFunc func(*BazelCacheInfo)
func (f BazelCacheOptionFunc) SetBazelCacheOption(info *BazelCacheInfo) {
f(info)
}
type BazelCacheOption interface {
SetBazelCacheOption(*BazelCacheInfo)
}
func (c *BazelCache) ToRunOption(worker llb.State, distroKey string, opts ...BazelCacheOption) llb.RunOption {
return RunOptFunc(func(ei *llb.ExecInfo) {
var info BazelCacheInfo
for _, opt := range opts {
opt.SetBazelCacheOption(&info)
}
platform := ei.Platform
if platform == nil {
platform = info.Platform
}
if platform == nil {
p := platforms.DefaultSpec()
platform = &p
}
key := fmt.Sprintf("%s-%s-dalec-bazelcache", distroKey, platforms.Format(*platform))
if c.Scope != "" {
key = fmt.Sprintf("%s-%s", key, c.Scope)
}
// See bazelrc https://bazel.build/run/bazelrc for more information on the bazelrc file
const (
cacheDir = "/tmp/dalec/bazel-local-cache"
sockPath = "/tmp/dalec/bazel-remote.sock"
)
rcFileContent := `
build --disk_cache=` + cacheDir + `
fetch --disk_cache=` + cacheDir + `
`
rcFile := llb.Scratch().File(
llb.Mkfile("bazelrc", 0o644, []byte(rcFileContent)),
WithConstraint(info.constraints),
)
checkSockPath := filepath.Join(filepath.Dir(sockPath), c.Scope, filepath.Base(sockPath))
checkScript := fmt.Sprintf(`#!/usr/bin/env sh
if [ -S %q ]; then
echo "build --remote_cache=unix:%s" >> /tmp/dalec/bazelrc
echo "fetch --remote_cache=unix:%s" >> /tmp/dalec/bazelrc
fi
`, checkSockPath, sockPath, sockPath)
checkScriptSt := llb.Scratch().File(
llb.Mkfile("script.sh", 0o755, []byte(checkScript)),
WithConstraint(info.constraints),
)
scriptPath := "/tmp/dalec/internal/bazel/check-socket.sh"
rcFile = worker.Run(
llb.AddSSHSocket(llb.SSHID(BazelDefaultSocketID), llb.SSHSocketTarget(checkSockPath), llb.SSHOptional),
ShArgs(scriptPath),
llb.AddMount(scriptPath, checkScriptSt, llb.SourcePath("script.sh")),
WithConstraint(info.constraints),
).AddMount("/tmp/dalec/bazelrc", rcFile, llb.SourcePath("bazelrc"))
llb.AddMount("/etc/bazel.bazelrc", rcFile, llb.SourcePath("bazelrc")).SetRunOption(ei)
llb.AddMount(cacheDir, llb.Scratch(), llb.AsPersistentCacheDir(key, llb.CacheMountShared)).SetRunOption(ei)
llb.AddSSHSocket(llb.SSHID(BazelDefaultSocketID), llb.SSHSocketTarget(sockPath), llb.SSHOptional).SetRunOption(ei)
})
}