Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Docker context build hash check #446

Merged
merged 15 commits into from
Jan 4, 2023
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions examples/dotnet/.dockerignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
bin/
obj/
1 change: 0 additions & 1 deletion examples/examples_dotnet_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@ func TestNginxCs(t *testing.T) {
}

func TestDotNet(t *testing.T) {
//t.Skip("Skipping test due to updates in Image resource")

test := getCsharpBaseOptions(t).
With(integration.ProgramTestOptions{
Expand Down
3 changes: 2 additions & 1 deletion provider/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,12 @@ go 1.19
require (
github.com/docker/docker v20.10.21+incompatible
github.com/golang/protobuf v1.5.2
github.com/moby/moby v20.10.18+incompatible
github.com/pkg/errors v0.9.1
github.com/pulumi/pulumi-terraform-bridge/v3 v3.33.0
github.com/pulumi/pulumi/pkg/v3 v3.44.2
github.com/pulumi/pulumi/sdk/v3 v3.44.2
github.com/stretchr/testify v1.8.0
github.com/terraform-providers/terraform-provider-docker/shim v0.0.0
google.golang.org/grpc v1.49.0
google.golang.org/protobuf v1.28.1
Expand Down Expand Up @@ -217,7 +219,6 @@ require (
github.com/spf13/cast v1.5.0 // indirect
github.com/spf13/cobra v1.5.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/stretchr/testify v1.8.0 // indirect
github.com/terraform-providers/terraform-provider-docker v0.0.0 // indirect
github.com/texttheater/golang-levenshtein v1.0.1 // indirect
github.com/tweekmonster/luser v0.0.0-20161003172636-3fa38070dbd7 // indirect
Expand Down
2 changes: 2 additions & 0 deletions provider/go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -1353,6 +1353,8 @@ github.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx
github.com/moby/buildkit v0.10.5 h1:d9krS/lG3dn6N7y+R8o9PTgIixlYAaDk35f3/B4jZOw=
github.com/moby/buildkit v0.10.5/go.mod h1:Yajz9vt1Zw5q9Pp4pdb3TCSUXJBIroIQGQ3TTs/sLug=
github.com/moby/locker v1.0.1/go.mod h1:S7SDdo5zpBK84bzzVlKr2V0hz+7x9hWbYC/kq7oQppc=
github.com/moby/moby v20.10.18+incompatible h1:aAQ5lDb+SDrhVDnoMbR3kSzswd+41X34pex8VRJXvHg=
github.com/moby/moby v20.10.18+incompatible/go.mod h1:fDXVQ6+S340veQPv35CzDahGBmHsiclFwfEygB/TWMc=
github.com/moby/spdystream v0.2.0/go.mod h1:f7i0iNDQJ059oMTcWxx8MA/zKFIuD/lY+0GqbN2Wy8c=
github.com/moby/sys/mount v0.3.0 h1:bXZYMmq7DBQPwHRxH/MG+u9+XF90ZOwoXpHTOznMGp0=
github.com/moby/sys/mount v0.3.0/go.mod h1:U2Z3ur2rXPFrFmy4q6WMwWrBOAQGYtYTRVM8BIvzbwk=
Expand Down
165 changes: 163 additions & 2 deletions provider/provider.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
package provider

import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"fmt"
pbempty "github.com/golang/protobuf/ptypes/empty"
"github.com/moby/buildkit/frontend/dockerfile/dockerignore"
"github.com/moby/moby/pkg/fileutils"
"github.com/pkg/errors"
"github.com/pulumi/pulumi/pkg/v3/resource/provider"
"github.com/pulumi/pulumi/sdk/v3/go/common/resource"
Expand All @@ -13,6 +18,10 @@ import (
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/types/known/emptypb"
"io"
"io/fs"
"os"
"path/filepath"
)

type dockerNativeProvider struct {
Expand Down Expand Up @@ -88,7 +97,44 @@ func (p *dockerNativeProvider) Check(ctx context.Context, req *rpc.CheckRequest)
label := fmt.Sprintf("%s.Create(%s)", p.name, urn)
logging.V(9).Infof("%s executing", label)

return &rpc.CheckResponse{Inputs: req.News, Failures: nil}, nil
inputs, err := plugin.UnmarshalProperties(req.GetNews(), plugin.MarshalOptions{
KeepUnknowns: true,
SkipNulls: true,
KeepSecrets: true,
})
if err != nil {
return nil, err
}

// Set defaults
build, err := marshalBuildAndApplyDefaults(inputs["build"])
if err != nil {
return nil, err
}

dockerContext := build.Context
dockerfile := build.Dockerfile

// Set docker build context
contextDigest, err := hashContext(dockerContext, dockerfile)
if err != nil {
return nil, err
}

// add implicit resource to provider
inputs["build"].ObjectValue()["contextDigest"] = resource.NewStringProperty(contextDigest)

inputStruct, err := plugin.MarshalProperties(inputs, plugin.MarshalOptions{
KeepUnknowns: true,
SkipNulls: true,
KeepSecrets: true,
})

if err != nil {
return nil, err
}

return &rpc.CheckResponse{Inputs: inputStruct, Failures: nil}, nil
}

// Diff checks what impacts a hypothetical update will have on the resource's properties.
Expand Down Expand Up @@ -126,8 +172,20 @@ func (p *dockerNativeProvider) Diff(ctx context.Context, req *rpc.DiffRequest) (
}, nil
}

diff := map[string]*rpc.PropertyDiff{}
for key := range d.Adds {
diff[string(key)] = &rpc.PropertyDiff{Kind: rpc.PropertyDiff_ADD}
}
for key := range d.Deletes {
diff[string(key)] = &rpc.PropertyDiff{Kind: rpc.PropertyDiff_DELETE}
}
for key := range d.Updates {
diff[string(key)] = &rpc.PropertyDiff{Kind: rpc.PropertyDiff_UPDATE}
}
return &rpc.DiffResponse{
Changes: rpc.DiffResponse_DIFF_UNKNOWN,
Changes: rpc.DiffResponse_DIFF_SOME,
AaronFriel marked this conversation as resolved.
Show resolved Hide resolved
DetailedDiff: diff,
HasDetailedDiff: true,
}, nil
}

Expand Down Expand Up @@ -299,3 +357,106 @@ func parseCheckpointObject(obj resource.PropertyMap) resource.PropertyMap {

return nil
}

type contextHash struct {
t0yv0 marked this conversation as resolved.
Show resolved Hide resolved
contextPath string
input bytes.Buffer
}

func newContextHash(contextPath string) *contextHash {
return &contextHash{contextPath: contextPath}
}

func (ch *contextHash) hashPath(path string, fileMode fs.FileMode) error {
f, err := os.Open(filepath.Join(ch.contextPath, path))
if err != nil {
return fmt.Errorf("open %s: %w", path, err)
}
defer f.Close()
h := sha256.New()
_, err = io.Copy(h, f)
if err != nil {
return fmt.Errorf("read %s: %w", path, err)
}
ch.input.Write([]byte(path))
ch.input.Write([]byte(fileMode.String()))
ch.input.Write(h.Sum(nil))
ch.input.WriteByte(0)
return nil
}

func (ch *contextHash) hexSum() string {
h := sha256.New()
_, err := ch.input.WriteTo(h)
if err != nil {
return ""
}
return hex.EncodeToString(h.Sum(nil))
}

func hashContext(contextPath string, dockerfile string) (string, error) {
dockerIgnorePath := dockerfile + ".dockerignore"
dockerIgnore, err := os.ReadFile(dockerIgnorePath)
if err != nil {
if os.IsNotExist(err) {
dockerIgnorePath = filepath.Join(contextPath, ".dockerignore")
dockerIgnore, err = os.ReadFile(dockerIgnorePath)
if err != nil && !os.IsNotExist(err) {
return "", fmt.Errorf("unable to read %s file: %w", dockerIgnorePath, err)
}
} else {
return "", fmt.Errorf("unable to read %s file: %w", dockerIgnorePath, err)
}
}
ignorePatterns, err := dockerignore.ReadAll(bytes.NewReader(dockerIgnore))
if err != nil {
return "", fmt.Errorf("unable to parse %s file: %w", dockerIgnorePath, err)
}
ignoreMatcher, err := fileutils.NewPatternMatcher(ignorePatterns)
if err != nil {
return "", fmt.Errorf("unable to load rules from %s: %w", dockerIgnorePath, err)
}
ch := newContextHash(contextPath)
err = ch.hashPath(dockerfile, 0)
if err != nil {
return "", fmt.Errorf("hashing dockerfile %q: %w", dockerfile, err)
}
err = filepath.WalkDir(contextPath, func(path string, d os.DirEntry, err error) error {
if err != nil {
return err
}
path, err = filepath.Rel(contextPath, path)
if err != nil {
return err
}
if path == "." {
return nil
}
ignore, err := ignoreMatcher.Matches(path)
if err != nil {
return fmt.Errorf("%s rule failed: %w", dockerIgnorePath, err)
}
if ignore {
if d.IsDir() {
return filepath.SkipDir
}
return nil

} else if d.IsDir() {
return nil
}
info, err := d.Info()
if err != nil {
return fmt.Errorf("determining mode for %q: %w", path, err)
}
err = ch.hashPath(path, info.Mode())
if err != nil {
return fmt.Errorf("hashing %q: %w", path, err)
}
return nil
})
if err != nil {
return "", fmt.Errorf("unable to hash build context: %w", err)
}
return ch.hexSum(), nil
}