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 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825
|
package llb
import (
"context"
_ "crypto/sha256" // for opencontainers/go-digest
"os"
"path"
"strconv"
"strings"
"time"
"github.com/moby/buildkit/solver/pb"
digest "github.com/opencontainers/go-digest"
"github.com/pkg/errors"
)
// Examples:
// local := llb.Local(...)
// llb.Image().Dir("/abc").File(Mkdir("./foo").Mkfile("/abc/foo/bar", []byte("data")))
// llb.Image().File(Mkdir("/foo").Mkfile("/foo/bar", []byte("data")))
// llb.Image().File(Copy(local, "/foo", "/bar")).File(Copy(local, "/foo2", "/bar2"))
//
// a := Mkdir("./foo") // *FileAction /ced/foo
// b := Mkdir("./bar") // /abc/bar
// c := b.Copy(a.WithState(llb.Scratch().Dir("/ced")), "./foo", "./baz") // /abc/baz
// llb.Image().Dir("/abc").File(c)
//
// In future this can be extended to multiple outputs with:
// a := Mkdir("./foo")
// b, id := a.GetSelector()
// c := b.Mkdir("./bar")
// filestate = state.File(c)
// filestate.GetOutput(id).Exec()
func NewFileOp(s State, action *FileAction, c Constraints) *FileOp {
action = action.bind(s)
f := &FileOp{
action: action,
constraints: c,
}
f.output = &output{vertex: f, getIndex: func() (pb.OutputIndex, error) {
return pb.OutputIndex(0), nil
}}
return f
}
// CopyInput is either llb.State or *FileActionWithState
// It is used by [Copy] to to specify the source of the copy operation.
type CopyInput interface {
isFileOpCopyInput()
}
type subAction interface {
toProtoAction(context.Context, string, pb.InputIndex) (pb.IsFileAction, error)
}
type capAdder interface {
addCaps(*FileOp)
}
// FileAction is used to specify a file operation on a [State].
// It can be used to create a directory, create a file, or remove a file, etc.
// This is used by [State.File]
// Typically a FileAction is created by calling one of the helper functions such as [Mkdir], [Copy], [Rm], [Mkfile]
type FileAction struct {
state *State
prev *FileAction
action subAction
err error
}
func (fa *FileAction) Mkdir(p string, m os.FileMode, opt ...MkdirOption) *FileAction {
a := Mkdir(p, m, opt...)
a.prev = fa
return a
}
func (fa *FileAction) Mkfile(p string, m os.FileMode, dt []byte, opt ...MkfileOption) *FileAction {
a := Mkfile(p, m, dt, opt...)
a.prev = fa
return a
}
func (fa *FileAction) Rm(p string, opt ...RmOption) *FileAction {
a := Rm(p, opt...)
a.prev = fa
return a
}
func (fa *FileAction) Copy(input CopyInput, src, dest string, opt ...CopyOption) *FileAction {
a := Copy(input, src, dest, opt...)
a.prev = fa
return a
}
func (fa *FileAction) allOutputs(m map[Output]struct{}) {
if fa == nil {
return
}
if fa.state != nil && fa.state.Output() != nil {
m[fa.state.Output()] = struct{}{}
}
if a, ok := fa.action.(*fileActionCopy); ok {
if a.state != nil {
if out := a.state.Output(); out != nil {
m[out] = struct{}{}
}
} else if a.fas != nil {
a.fas.allOutputs(m)
}
}
fa.prev.allOutputs(m)
}
func (fa *FileAction) bind(s State) *FileAction {
if fa == nil {
return nil
}
fa2 := *fa
fa2.prev = fa.prev.bind(s)
fa2.state = &s
return &fa2
}
func (fa *FileAction) WithState(s State) CopyInput {
return &fileActionWithState{FileAction: fa.bind(s)}
}
type fileActionWithState struct {
*FileAction
}
func (fas *fileActionWithState) isFileOpCopyInput() {}
// Mkdir creates a FileAction which creates a directory at the given path.
// Example:
//
// llb.Scratch().File(llb.Mkdir("/foo", 0755))
func Mkdir(p string, m os.FileMode, opt ...MkdirOption) *FileAction {
var mi MkdirInfo
for _, o := range opt {
o.SetMkdirOption(&mi)
}
return &FileAction{
action: &fileActionMkdir{
file: p,
mode: m,
info: mi,
},
}
}
type fileActionMkdir struct {
file string
mode os.FileMode
info MkdirInfo
}
func (a *fileActionMkdir) toProtoAction(ctx context.Context, parent string, base pb.InputIndex) (pb.IsFileAction, error) {
return &pb.FileAction_Mkdir{
Mkdir: &pb.FileActionMkDir{
Path: normalizePath(parent, a.file, false),
Mode: int32(a.mode & 0777),
MakeParents: a.info.MakeParents,
Owner: a.info.ChownOpt.marshal(base),
Timestamp: marshalTime(a.info.CreatedTime),
},
}, nil
}
type MkdirOption interface {
SetMkdirOption(*MkdirInfo)
}
type ChownOption interface {
MkdirOption
MkfileOption
CopyOption
}
type mkdirOptionFunc func(*MkdirInfo)
func (fn mkdirOptionFunc) SetMkdirOption(mi *MkdirInfo) {
fn(mi)
}
var _ MkdirOption = &MkdirInfo{}
// WithParents is an option for Mkdir which creates parent directories if they do not exist.
func WithParents(b bool) MkdirOption {
return mkdirOptionFunc(func(mi *MkdirInfo) {
mi.MakeParents = b
})
}
type MkdirInfo struct {
MakeParents bool
ChownOpt *ChownOpt
CreatedTime *time.Time
}
func (mi *MkdirInfo) SetMkdirOption(mi2 *MkdirInfo) {
*mi2 = *mi
}
func WithUser(name string) ChownOption {
opt := ChownOpt{}
parts := strings.SplitN(name, ":", 2)
for i, v := range parts {
switch i {
case 0:
uid, err := parseUID(v)
if err != nil {
opt.User = &UserOpt{Name: v}
} else {
opt.User = &UserOpt{UID: uid}
}
case 1:
gid, err := parseUID(v)
if err != nil {
opt.Group = &UserOpt{Name: v}
} else {
opt.Group = &UserOpt{UID: gid}
}
}
}
return opt
}
func parseUID(str string) (int, error) {
if str == "root" {
return 0, nil
}
uid, err := strconv.ParseInt(str, 10, 32)
if err != nil {
return 0, err
}
return int(uid), nil
}
func WithUIDGID(uid, gid int) ChownOption {
return ChownOpt{
User: &UserOpt{UID: uid},
Group: &UserOpt{UID: gid},
}
}
type ChownOpt struct {
User *UserOpt
Group *UserOpt
}
func (co ChownOpt) SetMkdirOption(mi *MkdirInfo) {
mi.ChownOpt = &co
}
func (co ChownOpt) SetMkfileOption(mi *MkfileInfo) {
mi.ChownOpt = &co
}
func (co ChownOpt) SetCopyOption(mi *CopyInfo) {
mi.ChownOpt = &co
}
func (co *ChownOpt) marshal(base pb.InputIndex) *pb.ChownOpt {
if co == nil {
return nil
}
return &pb.ChownOpt{
User: co.User.marshal(base),
Group: co.Group.marshal(base),
}
}
type UserOpt struct {
UID int
Name string
}
func (up *UserOpt) marshal(base pb.InputIndex) *pb.UserOpt {
if up == nil {
return nil
}
if up.Name != "" {
return &pb.UserOpt{User: &pb.UserOpt_ByName{ByName: &pb.NamedUserOpt{
Name: up.Name, Input: base}}}
}
return &pb.UserOpt{User: &pb.UserOpt_ByID{ByID: uint32(up.UID)}}
}
// Mkfile creates a FileAction which creates a file at the given path with the provided contents.
// Example:
//
// llb.Scratch().File(llb.Mkfile("/foo", 0644, []byte("hello world!")))
func Mkfile(p string, m os.FileMode, dt []byte, opts ...MkfileOption) *FileAction {
var mi MkfileInfo
for _, o := range opts {
o.SetMkfileOption(&mi)
}
return &FileAction{
action: &fileActionMkfile{
file: p,
mode: m,
dt: dt,
info: mi,
},
}
}
type MkfileOption interface {
SetMkfileOption(*MkfileInfo)
}
type MkfileInfo struct {
ChownOpt *ChownOpt
CreatedTime *time.Time
}
func (mi *MkfileInfo) SetMkfileOption(mi2 *MkfileInfo) {
*mi2 = *mi
}
var _ MkfileOption = &MkfileInfo{}
type fileActionMkfile struct {
file string
mode os.FileMode
dt []byte
info MkfileInfo
}
func (a *fileActionMkfile) toProtoAction(ctx context.Context, parent string, base pb.InputIndex) (pb.IsFileAction, error) {
return &pb.FileAction_Mkfile{
Mkfile: &pb.FileActionMkFile{
Path: normalizePath(parent, a.file, false),
Mode: int32(a.mode & 0777),
Data: a.dt,
Owner: a.info.ChownOpt.marshal(base),
Timestamp: marshalTime(a.info.CreatedTime),
},
}, nil
}
// Rm creates a FileAction which removes a file or directory at the given path.
// Example:
//
// llb.Scratch().File(Mkfile("/foo", 0644, []byte("not around for long..."))).File(llb.Rm("/foo"))
func Rm(p string, opts ...RmOption) *FileAction {
var mi RmInfo
for _, o := range opts {
o.SetRmOption(&mi)
}
return &FileAction{
action: &fileActionRm{
file: p,
info: mi,
},
}
}
type RmOption interface {
SetRmOption(*RmInfo)
}
type rmOptionFunc func(*RmInfo)
func (fn rmOptionFunc) SetRmOption(mi *RmInfo) {
fn(mi)
}
type RmInfo struct {
AllowNotFound bool
AllowWildcard bool
}
func (mi *RmInfo) SetRmOption(mi2 *RmInfo) {
*mi2 = *mi
}
var _ RmOption = &RmInfo{}
func WithAllowNotFound(b bool) RmOption {
return rmOptionFunc(func(mi *RmInfo) {
mi.AllowNotFound = b
})
}
func WithAllowWildcard(b bool) RmOption {
return rmOptionFunc(func(mi *RmInfo) {
mi.AllowWildcard = b
})
}
type excludeOnCopyAction struct {
patterns []string
}
func (e *excludeOnCopyAction) SetCopyOption(i *CopyInfo) {
i.ExcludePatterns = append(i.ExcludePatterns, e.patterns...)
}
func WithExcludePatterns(patterns []string) CopyOption {
return &excludeOnCopyAction{patterns}
}
type fileActionRm struct {
file string
info RmInfo
}
func (a *fileActionRm) toProtoAction(ctx context.Context, parent string, base pb.InputIndex) (pb.IsFileAction, error) {
return &pb.FileAction_Rm{
Rm: &pb.FileActionRm{
Path: normalizePath(parent, a.file, false),
AllowNotFound: a.info.AllowNotFound,
AllowWildcard: a.info.AllowWildcard,
},
}, nil
}
// Copy produces a FileAction which copies a file or directory from the source to the destination.
// The "input" parameter is the contents to copy from.
// "src" is the path to copy from within the "input".
// "dest" is the path to copy to within the destination (the state being operated on).
// See [CopyInput] for the valid types of input.
//
// Example:
//
// st := llb.Local(".")
// llb.Scratch().File(llb.Copy(st, "/foo", "/bar"))
//
// The example copies the local (client) directory "./foo" to a new empty directory at /bar.
//
// Note: Copying directories can have different behavior based on if the destination exists or not.
// When the destination already exists, the contents of the source directory is copied underneath the destination, including the directory itself.
// You may need to supply a copy option to copy the dir contents only.
// You may also need to pass in a [CopyOption] which creates parent directories if they do not exist.
//
// See [CopyOption] for more details on what options are available.
func Copy(input CopyInput, src, dest string, opts ...CopyOption) *FileAction {
var state *State
var fas *fileActionWithState
var err error
if st, ok := input.(State); ok {
state = &st
} else if v, ok := input.(*fileActionWithState); ok {
fas = v
} else {
err = errors.Errorf("invalid input type %T for copy", input)
}
var mi CopyInfo
for _, o := range opts {
o.SetCopyOption(&mi)
}
return &FileAction{
action: &fileActionCopy{
state: state,
fas: fas,
src: src,
dest: dest,
info: mi,
},
err: err,
}
}
type CopyOption interface {
SetCopyOption(*CopyInfo)
}
type CopyInfo struct {
Mode *os.FileMode
FollowSymlinks bool
CopyDirContentsOnly bool
IncludePatterns []string
ExcludePatterns []string
AttemptUnpack bool
CreateDestPath bool
AllowWildcard bool
AllowEmptyWildcard bool
ChownOpt *ChownOpt
CreatedTime *time.Time
}
func (mi *CopyInfo) SetCopyOption(mi2 *CopyInfo) {
*mi2 = *mi
}
var _ CopyOption = &CopyInfo{}
type fileActionCopy struct {
state *State
fas *fileActionWithState
src string
dest string
info CopyInfo
}
func (a *fileActionCopy) toProtoAction(ctx context.Context, parent string, base pb.InputIndex) (pb.IsFileAction, error) {
src, err := a.sourcePath(ctx)
if err != nil {
return nil, err
}
c := &pb.FileActionCopy{
Src: src,
Dest: normalizePath(parent, a.dest, true),
Owner: a.info.ChownOpt.marshal(base),
IncludePatterns: a.info.IncludePatterns,
ExcludePatterns: a.info.ExcludePatterns,
AllowWildcard: a.info.AllowWildcard,
AllowEmptyWildcard: a.info.AllowEmptyWildcard,
FollowSymlink: a.info.FollowSymlinks,
DirCopyContents: a.info.CopyDirContentsOnly,
AttemptUnpackDockerCompatibility: a.info.AttemptUnpack,
CreateDestPath: a.info.CreateDestPath,
Timestamp: marshalTime(a.info.CreatedTime),
}
if a.info.Mode != nil {
c.Mode = int32(*a.info.Mode)
} else {
c.Mode = -1
}
return &pb.FileAction_Copy{
Copy: c,
}, nil
}
func (a *fileActionCopy) sourcePath(ctx context.Context) (string, error) {
p := path.Clean(a.src)
dir := "/"
var err error
if !path.IsAbs(p) {
if a.state != nil {
dir, err = a.state.GetDir(ctx)
} else if a.fas != nil {
dir, err = a.fas.state.GetDir(ctx)
}
if err != nil {
return "", err
}
}
return path.Join(dir, p), nil
}
func (a *fileActionCopy) addCaps(f *FileOp) {
if len(a.info.IncludePatterns) != 0 || len(a.info.ExcludePatterns) != 0 {
addCap(&f.constraints, pb.CapFileCopyIncludeExcludePatterns)
}
}
type CreatedTime time.Time
func WithCreatedTime(t time.Time) CreatedTime {
return CreatedTime(t)
}
func (c CreatedTime) SetMkdirOption(mi *MkdirInfo) {
mi.CreatedTime = (*time.Time)(&c)
}
func (c CreatedTime) SetMkfileOption(mi *MkfileInfo) {
mi.CreatedTime = (*time.Time)(&c)
}
func (c CreatedTime) SetCopyOption(mi *CopyInfo) {
mi.CreatedTime = (*time.Time)(&c)
}
func marshalTime(t *time.Time) int64 {
if t == nil {
return -1
}
return t.UnixNano()
}
type FileOp struct {
MarshalCache
action *FileAction
output Output
constraints Constraints
isValidated bool
}
func (f *FileOp) Validate(context.Context, *Constraints) error {
if f.isValidated {
return nil
}
if f.action == nil {
return errors.Errorf("action is required")
}
f.isValidated = true
return nil
}
type marshalState struct {
ctx context.Context
visited map[*FileAction]*fileActionState
inputs []*pb.Input
actions []*fileActionState
}
func newMarshalState(ctx context.Context) *marshalState {
return &marshalState{
visited: map[*FileAction]*fileActionState{},
ctx: ctx,
}
}
type fileActionState struct {
base pb.InputIndex
input pb.InputIndex
inputRelative *int
input2 pb.InputIndex
input2Relative *int
target int
action subAction
fa *FileAction
}
func (ms *marshalState) addInput(st *fileActionState, c *Constraints, o Output) (pb.InputIndex, error) {
inp, err := o.ToInput(ms.ctx, c)
if err != nil {
return 0, err
}
for i, inp2 := range ms.inputs {
if *inp == *inp2 {
return pb.InputIndex(i), nil
}
}
i := pb.InputIndex(len(ms.inputs))
ms.inputs = append(ms.inputs, inp)
return i, nil
}
func (ms *marshalState) add(fa *FileAction, c *Constraints) (*fileActionState, error) {
if st, ok := ms.visited[fa]; ok {
return st, nil
}
if fa.err != nil {
return nil, fa.err
}
var prevState *fileActionState
if parent := fa.prev; parent != nil {
var err error
prevState, err = ms.add(parent, c)
if err != nil {
return nil, err
}
}
st := &fileActionState{
action: fa.action,
input: -1,
input2: -1,
base: -1,
fa: fa,
}
if source := fa.state.Output(); source != nil {
inp, err := ms.addInput(st, c, source)
if err != nil {
return nil, err
}
st.base = inp
}
if fa.prev == nil {
st.input = st.base
} else {
st.inputRelative = &prevState.target
}
if a, ok := fa.action.(*fileActionCopy); ok {
if a.state != nil {
if out := a.state.Output(); out != nil {
inp, err := ms.addInput(st, c, out)
if err != nil {
return nil, err
}
st.input2 = inp
}
} else if a.fas != nil {
src, err := ms.add(a.fas.FileAction, c)
if err != nil {
return nil, err
}
st.input2Relative = &src.target
} else {
return nil, errors.Errorf("invalid empty source for copy")
}
}
st.target = len(ms.actions)
ms.visited[fa] = st
ms.actions = append(ms.actions, st)
return st, nil
}
func (f *FileOp) Marshal(ctx context.Context, c *Constraints) (digest.Digest, []byte, *pb.OpMetadata, []*SourceLocation, error) {
if f.Cached(c) {
return f.Load()
}
if err := f.Validate(ctx, c); err != nil {
return "", nil, nil, nil, err
}
addCap(&f.constraints, pb.CapFileBase)
pfo := &pb.FileOp{}
if f.constraints.Platform == nil {
p, err := getPlatform(*f.action.state)(ctx, c)
if err != nil {
return "", nil, nil, nil, err
}
f.constraints.Platform = p
}
state := newMarshalState(ctx)
for _, st := range state.actions {
if adder, isCapAdder := st.action.(capAdder); isCapAdder {
adder.addCaps(f)
}
}
pop, md := MarshalConstraints(c, &f.constraints)
pop.Platform = nil // file op is not platform specific
pop.Op = &pb.Op_File{
File: pfo,
}
_, err := state.add(f.action, c)
if err != nil {
return "", nil, nil, nil, err
}
pop.Inputs = state.inputs
for i, st := range state.actions {
output := pb.SkipOutput
if i+1 == len(state.actions) {
output = 0
}
var parent string
if st.fa.state != nil {
parent, err = st.fa.state.GetDir(ctx)
if err != nil {
return "", nil, nil, nil, err
}
}
action, err := st.action.toProtoAction(ctx, parent, st.base)
if err != nil {
return "", nil, nil, nil, err
}
pfo.Actions = append(pfo.Actions, &pb.FileAction{
Input: getIndex(st.input, len(state.inputs), st.inputRelative),
SecondaryInput: getIndex(st.input2, len(state.inputs), st.input2Relative),
Output: output,
Action: action,
})
}
dt, err := pop.Marshal()
if err != nil {
return "", nil, nil, nil, err
}
f.Store(dt, md, f.constraints.SourceLocations, c)
return f.Load()
}
func normalizePath(parent, p string, keepSlash bool) string {
origPath := p
p = path.Clean(p)
if !path.IsAbs(p) {
p = path.Join("/", parent, p)
}
if keepSlash {
if strings.HasSuffix(origPath, "/") && !strings.HasSuffix(p, "/") {
p += "/"
} else if strings.HasSuffix(origPath, "/.") {
if p != "/" {
p += "/"
}
p += "."
}
}
return p
}
func (f *FileOp) Output() Output {
return f.output
}
func (f *FileOp) Inputs() (inputs []Output) {
mm := map[Output]struct{}{}
f.action.allOutputs(mm)
for o := range mm {
inputs = append(inputs, o)
}
return inputs
}
func getIndex(input pb.InputIndex, len int, relative *int) pb.InputIndex {
if relative != nil {
return pb.InputIndex(len + *relative)
}
return input
}
|