| 1 |
package gha |
| 2 |
|
| 3 |
import ( |
| 4 |
"bytes" |
| 5 |
"context" |
| 6 |
"encoding/json" |
| 7 |
"fmt" |
| 8 |
"io" |
| 9 |
"os" |
| 10 |
"strconv" |
| 11 |
"strings" |
| 12 |
"sync" |
| 13 |
"time" |
| 14 |
|
| 15 |
"github.com/containerd/containerd/v2/core/content" |
| 16 |
"github.com/containerd/containerd/v2/pkg/labels" |
| 17 |
cerrdefs "github.com/containerd/errdefs" |
| 18 |
"github.com/moby/buildkit/cache/remotecache" |
| 19 |
v1 "github.com/moby/buildkit/cache/remotecache/v1" |
| 20 |
"github.com/moby/buildkit/session" |
| 21 |
"github.com/moby/buildkit/solver" |
| 22 |
"github.com/moby/buildkit/util/bklog" |
| 23 |
"github.com/moby/buildkit/util/compression" |
| 24 |
"github.com/moby/buildkit/util/progress" |
| 25 |
"github.com/moby/buildkit/util/tracing" |
| 26 |
bkversion "github.com/moby/buildkit/version" |
| 27 |
"github.com/moby/buildkit/worker" |
| 28 |
digest "github.com/opencontainers/go-digest" |
| 29 |
ocispecs "github.com/opencontainers/image-spec/specs-go/v1" |
| 30 |
"github.com/pkg/errors" |
| 31 |
actionscache "github.com/tonistiigi/go-actions-cache" |
| 32 |
"golang.org/x/sync/errgroup" |
| 33 |
) |
| 34 |
|
| 35 |
func init() { |
| 36 |
actionscache.Log = bklog.L.Debugf |
| 37 |
} |
| 38 |
|
| 39 |
const ( |
| 40 |
attrScope = "scope" |
| 41 |
attrTimeout = "timeout" |
| 42 |
attrToken = "token" |
| 43 |
attrURL = "url" |
| 44 |
attrURLV2 = "url_v2" |
| 45 |
attrRepository = "repository" |
| 46 |
attrGHToken = "ghtoken" |
| 47 |
attrAPIVersion = "version" |
| 48 |
version = "1" |
| 49 |
|
| 50 |
defaultTimeout = 10 * time.Minute |
| 51 |
) |
| 52 |
|
| 53 |
type Config struct { |
| 54 |
Scope string |
| 55 |
URL string |
| 56 |
Token string // token for the Github Cache runtime API |
| 57 |
GHToken string // token for the Github REST API |
| 58 |
Repository string |
| 59 |
Version int |
| 60 |
Timeout time.Duration |
| 61 |
} |
| 62 |
|
| 63 |
func getConfig(attrs map[string]string) (*Config, error) { |
| 64 |
scope, ok := attrs[attrScope] |
| 65 |
if !ok { |
| 66 |
scope = "buildkit" |
| 67 |
} |
| 68 |
token, ok := attrs[attrToken] |
| 69 |
if !ok { |
| 70 |
return nil, errors.Errorf("token not set for github actions cache") |
| 71 |
} |
| 72 |
var apiVersionInt int |
| 73 |
apiVersion, ok := attrs[attrAPIVersion] |
| 74 |
if ok { |
| 75 |
i, err := strconv.ParseInt(apiVersion, 10, 64) |
| 76 |
if err != nil { |
| 77 |
return nil, errors.Wrapf(err, "failed to parse api version %q, expected positive integer", apiVersion) |
| 78 |
} |
| 79 |
apiVersionInt = int(i) |
| 80 |
} |
| 81 |
var url string |
| 82 |
if apiVersionInt != 1 { |
| 83 |
if v, ok := attrs[attrURLV2]; ok { |
| 84 |
url = v |
| 85 |
apiVersionInt = 2 |
| 86 |
} |
| 87 |
} |
| 88 |
if v, ok := attrs[attrURL]; ok && url == "" { |
| 89 |
url = v |
| 90 |
} |
| 91 |
if url == "" { |
| 92 |
return nil, errors.Errorf("url not set for github actions cache") |
| 93 |
} |
| 94 |
// best effort on old clients |
| 95 |
if apiVersionInt == 0 { |
| 96 |
if strings.Contains(url, "results-receiver.actions.githubusercontent.com") { |
| 97 |
apiVersionInt = 2 |
| 98 |
} else { |
| 99 |
apiVersionInt = 1 |
| 100 |
} |
| 101 |
} |
| 102 |
|
| 103 |
timeout := defaultTimeout |
| 104 |
if v, ok := attrs[attrTimeout]; ok { |
| 105 |
var err error |
| 106 |
timeout, err = time.ParseDuration(v) |
| 107 |
if err != nil { |
| 108 |
return nil, errors.Wrap(err, "failed to parse timeout for github actions cache") |
| 109 |
} |
| 110 |
} |
| 111 |
return &Config{ |
| 112 |
Scope: scope, |
| 113 |
URL: url, |
| 114 |
Token: token, |
| 115 |
Timeout: timeout, |
| 116 |
GHToken: attrs[attrGHToken], |
| 117 |
Repository: attrs[attrRepository], |
| 118 |
Version: apiVersionInt, |
| 119 |
}, nil |
| 120 |
} |
| 121 |
|
| 122 |
// ResolveCacheExporterFunc for Github actions cache exporter. |
| 123 |
func ResolveCacheExporterFunc() remotecache.ResolveCacheExporterFunc { |
| 124 |
return func(ctx context.Context, g session.Group, attrs map[string]string) (remotecache.Exporter, error) { |
| 125 |
cfg, err := getConfig(attrs) |
| 126 |
if err != nil { |
| 127 |
return nil, err |
| 128 |
} |
| 129 |
return NewExporter(cfg) |
| 130 |
} |
| 131 |
} |
| 132 |
|
| 133 |
type exporter struct { |
| 134 |
solver.CacheExporterTarget |
| 135 |
chains *v1.CacheChains |
| 136 |
cache *actionscache.Cache |
| 137 |
config *Config |
| 138 |
keyMapOnce sync.Once |
| 139 |
keyMap map[string]struct{} |
| 140 |
} |
| 141 |
|
| 142 |
func NewExporter(c *Config) (remotecache.Exporter, error) { |
| 143 |
cc := v1.NewCacheChains() |
| 144 |
cache, err := actionscache.New(c.Token, c.URL, c.Version > 1, actionscache.Opt{ |
| 145 |
Client: tracing.DefaultClient, |
| 146 |
Timeout: c.Timeout, |
| 147 |
UserAgent: bkversion.UserAgent(), |
| 148 |
}) |
| 149 |
if err != nil { |
| 150 |
return nil, err |
| 151 |
} |
| 152 |
return &exporter{CacheExporterTarget: cc, chains: cc, cache: cache, config: c}, nil |
| 153 |
} |
| 154 |
|
| 155 |
func (*exporter) Name() string { |
| 156 |
return "exporting to GitHub Actions Cache" |
| 157 |
} |
| 158 |
|
| 159 |
func (ce *exporter) Config() remotecache.Config { |
| 160 |
return remotecache.Config{ |
| 161 |
Compression: compression.New(compression.Default), |
| 162 |
} |
| 163 |
} |
| 164 |
|
| 165 |
func (ce *exporter) blobKeyPrefix() string { |
| 166 |
return "buildkit-blob-" + version + "-" |
| 167 |
} |
| 168 |
|
| 169 |
func (ce *exporter) blobKey(dgst digest.Digest) string { |
| 170 |
return ce.blobKeyPrefix() + dgst.String() |
| 171 |
} |
| 172 |
|
| 173 |
func (ce *exporter) indexKey() string { |
| 174 |
scope := "" |
| 175 |
for _, s := range ce.cache.Scopes() { |
| 176 |
if s.Permission&actionscache.PermissionWrite != 0 { |
| 177 |
scope = s.Scope |
| 178 |
} |
| 179 |
} |
| 180 |
scope = digest.FromBytes([]byte(scope)).Hex()[:8] |
| 181 |
return "index-" + ce.config.Scope + "-" + version + "-" + scope |
| 182 |
} |
| 183 |
|
| 184 |
func (ce *exporter) initActiveKeyMap(ctx context.Context) { |
| 185 |
ce.keyMapOnce.Do(func() { |
| 186 |
if ce.config.Repository == "" || ce.config.GHToken == "" { |
| 187 |
return |
| 188 |
} |
| 189 |
m, err := ce.initActiveKeyMapOnce(ctx) |
| 190 |
if err != nil { |
| 191 |
bklog.G(ctx).Errorf("error initializing active key map: %v", err) |
| 192 |
return |
| 193 |
} |
| 194 |
ce.keyMap = m |
| 195 |
}) |
| 196 |
} |
| 197 |
|
| 198 |
func (ce *exporter) initActiveKeyMapOnce(ctx context.Context) (map[string]struct{}, error) { |
| 199 |
api, err := actionscache.NewRestAPI(ce.config.Repository, ce.config.GHToken, actionscache.Opt{ |
| 200 |
Client: tracing.DefaultClient, |
| 201 |
Timeout: ce.config.Timeout, |
| 202 |
}) |
| 203 |
if err != nil { |
| 204 |
return nil, err |
| 205 |
} |
| 206 |
keys, err := ce.cache.AllKeys(ctx, api, ce.blobKeyPrefix()) |
| 207 |
if err != nil { |
| 208 |
return nil, err |
| 209 |
} |
| 210 |
return keys, nil |
| 211 |
} |
| 212 |
|
| 213 |
func (ce *exporter) Finalize(ctx context.Context) (map[string]string, error) { |
| 214 |
// res := make(map[string]string) |
| 215 |
config, descs, err := ce.chains.Marshal(ctx) |
| 216 |
if err != nil { |
| 217 |
return nil, err |
| 218 |
} |
| 219 |
|
| 220 |
// TODO: push parallel |
| 221 |
for i, l := range config.Layers { |
| 222 |
dgstPair, ok := descs[l.Blob] |
| 223 |
if !ok { |
| 224 |
return nil, errors.Errorf("missing blob %s", l.Blob) |
| 225 |
} |
| 226 |
if dgstPair.Descriptor.Annotations == nil { |
| 227 |
return nil, errors.Errorf("invalid descriptor without annotations") |
| 228 |
} |
| 229 |
var diffID digest.Digest |
| 230 |
v, ok := dgstPair.Descriptor.Annotations[labels.LabelUncompressed] |
| 231 |
if !ok { |
| 232 |
return nil, errors.Errorf("invalid descriptor without uncompressed annotation") |
| 233 |
} |
| 234 |
dgst, err := digest.Parse(v) |
| 235 |
if err != nil { |
| 236 |
return nil, errors.Wrapf(err, "failed to parse uncompressed annotation") |
| 237 |
} |
| 238 |
diffID = dgst |
| 239 |
ce.initActiveKeyMap(ctx) |
| 240 |
|
| 241 |
key := ce.blobKey(dgstPair.Descriptor.Digest) |
| 242 |
|
| 243 |
exists := false |
| 244 |
if ce.keyMap != nil { |
| 245 |
if _, ok := ce.keyMap[key]; ok { |
| 246 |
exists = true |
| 247 |
} |
| 248 |
} else { |
| 249 |
b, err := ce.cache.Load(ctx, key) |
| 250 |
if err != nil { |
| 251 |
return nil, err |
| 252 |
} |
| 253 |
if b != nil { |
| 254 |
exists = true |
| 255 |
} |
| 256 |
} |
| 257 |
if !exists { |
| 258 |
layerDone := progress.OneOff(ctx, fmt.Sprintf("writing layer %s", l.Blob)) |
| 259 |
ra, err := dgstPair.Provider.ReaderAt(ctx, dgstPair.Descriptor) |
| 260 |
if err != nil { |
| 261 |
return nil, layerDone(err) |
| 262 |
} |
| 263 |
if err := ce.cache.Save(ctx, key, ra); err != nil { |
| 264 |
if !errors.Is(err, os.ErrExist) { |
| 265 |
return nil, layerDone(errors.Wrap(err, "error writing layer blob")) |
| 266 |
} |
| 267 |
} |
| 268 |
layerDone(nil) |
| 269 |
} |
| 270 |
la := &v1.LayerAnnotations{ |
| 271 |
DiffID: diffID, |
| 272 |
Size: dgstPair.Descriptor.Size, |
| 273 |
MediaType: dgstPair.Descriptor.MediaType, |
| 274 |
} |
| 275 |
if v, ok := dgstPair.Descriptor.Annotations["buildkit/createdat"]; ok { |
| 276 |
var t time.Time |
| 277 |
if err := (&t).UnmarshalText([]byte(v)); err != nil { |
| 278 |
return nil, err |
| 279 |
} |
| 280 |
la.CreatedAt = t.UTC() |
| 281 |
} |
| 282 |
config.Layers[i].Annotations = la |
| 283 |
} |
| 284 |
|
| 285 |
dt, err := json.Marshal(config) |
| 286 |
if err != nil { |
| 287 |
return nil, err |
| 288 |
} |
| 289 |
|
| 290 |
if err := ce.cache.SaveMutable(ctx, ce.indexKey(), 15*time.Second, func(old *actionscache.Entry) (actionscache.Blob, error) { |
| 291 |
return actionscache.NewBlob(dt), nil |
| 292 |
}); err != nil { |
| 293 |
return nil, err |
| 294 |
} |
| 295 |
|
| 296 |
return nil, nil |
| 297 |
} |
| 298 |
|
| 299 |
// ResolveCacheImporterFunc for Github actions cache importer. |
| 300 |
func ResolveCacheImporterFunc() remotecache.ResolveCacheImporterFunc { |
| 301 |
return func(ctx context.Context, g session.Group, attrs map[string]string) (remotecache.Importer, ocispecs.Descriptor, error) { |
| 302 |
cfg, err := getConfig(attrs) |
| 303 |
if err != nil { |
| 304 |
return nil, ocispecs.Descriptor{}, err |
| 305 |
} |
| 306 |
i, err := NewImporter(cfg) |
| 307 |
if err != nil { |
| 308 |
return nil, ocispecs.Descriptor{}, err |
| 309 |
} |
| 310 |
return i, ocispecs.Descriptor{}, nil |
| 311 |
} |
| 312 |
} |
| 313 |
|
| 314 |
type importer struct { |
| 315 |
cache *actionscache.Cache |
| 316 |
config *Config |
| 317 |
} |
| 318 |
|
| 319 |
func NewImporter(c *Config) (remotecache.Importer, error) { |
| 320 |
cache, err := actionscache.New(c.Token, c.URL, c.Version > 1, actionscache.Opt{ |
| 321 |
Client: tracing.DefaultClient, |
| 322 |
Timeout: c.Timeout, |
| 323 |
UserAgent: bkversion.UserAgent(), |
| 324 |
}) |
| 325 |
if err != nil { |
| 326 |
return nil, err |
| 327 |
} |
| 328 |
return &importer{cache: cache, config: c}, nil |
| 329 |
} |
| 330 |
|
| 331 |
func (ci *importer) makeDescriptorProviderPair(l v1.CacheLayer) (*v1.DescriptorProviderPair, error) { |
| 332 |
if l.Annotations == nil { |
| 333 |
return nil, errors.Errorf("cache layer with missing annotations") |
| 334 |
} |
| 335 |
annotations := map[string]string{} |
| 336 |
if l.Annotations.DiffID == "" { |
| 337 |
return nil, errors.Errorf("cache layer with missing diffid") |
| 338 |
} |
| 339 |
annotations[labels.LabelUncompressed] = l.Annotations.DiffID.String() |
| 340 |
if !l.Annotations.CreatedAt.IsZero() { |
| 341 |
txt, err := l.Annotations.CreatedAt.MarshalText() |
| 342 |
if err != nil { |
| 343 |
return nil, err |
| 344 |
} |
| 345 |
annotations["buildkit/createdat"] = string(txt) |
| 346 |
} |
| 347 |
desc := ocispecs.Descriptor{ |
| 348 |
MediaType: l.Annotations.MediaType, |
| 349 |
Digest: l.Blob, |
| 350 |
Size: l.Annotations.Size, |
| 351 |
Annotations: annotations, |
| 352 |
} |
| 353 |
p := &ciProvider{desc: desc, ci: ci} |
| 354 |
return &v1.DescriptorProviderPair{ |
| 355 |
Descriptor: desc, |
| 356 |
Provider: p, |
| 357 |
InfoProvider: p, |
| 358 |
}, nil |
| 359 |
} |
| 360 |
|
| 361 |
func (ci *importer) loadScope(ctx context.Context, scope string) (*v1.CacheChains, error) { |
| 362 |
scope = digest.FromBytes([]byte(scope)).Hex()[:8] |
| 363 |
key := "index-" + ci.config.Scope + "-" + version + "-" + scope |
| 364 |
|
| 365 |
entry, err := ci.cache.Load(ctx, key) |
| 366 |
if err != nil { |
| 367 |
return nil, err |
| 368 |
} |
| 369 |
if entry == nil { |
| 370 |
return v1.NewCacheChains(), nil |
| 371 |
} |
| 372 |
|
| 373 |
// TODO: this buffer can be removed |
| 374 |
buf := &bytes.Buffer{} |
| 375 |
if err := entry.WriteTo(ctx, buf); err != nil { |
| 376 |
return nil, err |
| 377 |
} |
| 378 |
|
| 379 |
var config v1.CacheConfig |
| 380 |
if err := json.Unmarshal(buf.Bytes(), &config); err != nil { |
| 381 |
return nil, errors.WithStack(err) |
| 382 |
} |
| 383 |
|
| 384 |
allLayers := v1.DescriptorProvider{} |
| 385 |
|
| 386 |
for _, l := range config.Layers { |
| 387 |
dpp, err := ci.makeDescriptorProviderPair(l) |
| 388 |
if err != nil { |
| 389 |
return nil, err |
| 390 |
} |
| 391 |
allLayers[l.Blob] = *dpp |
| 392 |
} |
| 393 |
|
| 394 |
cc := v1.NewCacheChains() |
| 395 |
if err := v1.ParseConfig(config, allLayers, cc); err != nil { |
| 396 |
return nil, err |
| 397 |
} |
| 398 |
return cc, nil |
| 399 |
} |
| 400 |
|
| 401 |
func (ci *importer) Resolve(ctx context.Context, _ ocispecs.Descriptor, id string, w worker.Worker) (solver.CacheManager, error) { |
| 402 |
eg, ctx := errgroup.WithContext(ctx) |
| 403 |
ccs := make([]*v1.CacheChains, len(ci.cache.Scopes())) |
| 404 |
|
| 405 |
for i, s := range ci.cache.Scopes() { |
| 406 |
func(i int, scope string) { |
| 407 |
eg.Go(func() error { |
| 408 |
cc, err := ci.loadScope(ctx, scope) |
| 409 |
if err != nil { |
| 410 |
return err |
| 411 |
} |
| 412 |
ccs[i] = cc |
| 413 |
return nil |
| 414 |
}) |
| 415 |
}(i, s.Scope) |
| 416 |
} |
| 417 |
|
| 418 |
if err := eg.Wait(); err != nil { |
| 419 |
return nil, err |
| 420 |
} |
| 421 |
|
| 422 |
cms := make([]solver.CacheManager, 0, len(ccs)) |
| 423 |
|
| 424 |
for _, cc := range ccs { |
| 425 |
keysStorage, resultStorage, err := v1.NewCacheKeyStorage(cc, w) |
| 426 |
if err != nil { |
| 427 |
return nil, err |
| 428 |
} |
| 429 |
cms = append(cms, solver.NewCacheManager(ctx, id, keysStorage, resultStorage)) |
| 430 |
} |
| 431 |
|
| 432 |
return solver.NewCombinedCacheManager(cms, nil), nil |
| 433 |
} |
| 434 |
|
| 435 |
type ciProvider struct { |
| 436 |
ci *importer |
| 437 |
desc ocispecs.Descriptor |
| 438 |
mu sync.Mutex |
| 439 |
entries map[digest.Digest]*actionscache.Entry |
| 440 |
} |
| 441 |
|
| 442 |
func (p *ciProvider) Info(ctx context.Context, dgst digest.Digest) (content.Info, error) { |
| 443 |
if dgst != p.desc.Digest { |
| 444 |
return content.Info{}, errors.Wrapf(cerrdefs.ErrNotFound, "blob %s", dgst) |
| 445 |
} |
| 446 |
|
| 447 |
if _, err := p.loadEntry(ctx, p.desc); err != nil { |
| 448 |
return content.Info{}, err |
| 449 |
} |
| 450 |
return content.Info{ |
| 451 |
Digest: p.desc.Digest, |
| 452 |
Size: p.desc.Size, |
| 453 |
}, nil |
| 454 |
} |
| 455 |
|
| 456 |
func (p *ciProvider) loadEntry(ctx context.Context, desc ocispecs.Descriptor) (*actionscache.Entry, error) { |
| 457 |
p.mu.Lock() |
| 458 |
defer p.mu.Unlock() |
| 459 |
|
| 460 |
if ce, ok := p.entries[desc.Digest]; ok { |
| 461 |
return ce, nil |
| 462 |
} |
| 463 |
key := "buildkit-blob-" + version + "-" + desc.Digest.String() |
| 464 |
ce, err := p.ci.cache.Load(ctx, key) |
| 465 |
if err != nil { |
| 466 |
return nil, err |
| 467 |
} |
| 468 |
if ce == nil { |
| 469 |
return nil, errors.Wrapf(cerrdefs.ErrNotFound, "blob %s", desc.Digest) |
| 470 |
} |
| 471 |
if p.entries == nil { |
| 472 |
p.entries = make(map[digest.Digest]*actionscache.Entry) |
| 473 |
} |
| 474 |
p.entries[desc.Digest] = ce |
| 475 |
return ce, nil |
| 476 |
} |
| 477 |
|
| 478 |
func (p *ciProvider) ReaderAt(ctx context.Context, desc ocispecs.Descriptor) (content.ReaderAt, error) { |
| 479 |
ce, err := p.loadEntry(ctx, desc) |
| 480 |
if err != nil { |
| 481 |
return nil, err |
| 482 |
} |
| 483 |
rac := ce.Download(context.TODO()) |
| 484 |
return &readerAt{ReaderAtCloser: rac, desc: desc}, nil |
| 485 |
} |
| 486 |
|
| 487 |
type readerAt struct { |
| 488 |
actionscache.ReaderAtCloser |
| 489 |
desc ocispecs.Descriptor |
| 490 |
} |
| 491 |
|
| 492 |
func (r *readerAt) ReadAt(p []byte, off int64) (int, error) { |
| 493 |
if off >= r.desc.Size { |
| 494 |
return 0, io.EOF |
| 495 |
} |
| 496 |
return r.ReaderAtCloser.ReadAt(p, off) |
| 497 |
} |
| 498 |
|
| 499 |
func (r *readerAt) Size() int64 { |
| 500 |
return r.desc.Size |
| 501 |
} |