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

feat(daemon): generate config file from Docker Engine API #1130

Merged
merged 3 commits into from
Apr 20, 2023
Merged
Show file tree
Hide file tree
Changes from all 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
151 changes: 149 additions & 2 deletions pkg/v1/daemon/image.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@ import (
"io"
"io/ioutil"
"sync"
"time"

api "github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/container"

"github.com/google/go-containerregistry/pkg/name"
v1 "github.com/google/go-containerregistry/pkg/v1"
Expand All @@ -31,7 +35,9 @@ type image struct {
ref name.Reference
opener *imageOpener
tarballImage v1.Image
computed bool
id *v1.Hash
configFile *v1.ConfigFile

once sync.Once
err error
Expand Down Expand Up @@ -122,6 +128,28 @@ func (i *image) initialize() error {
return i.err
}

func (i *image) compute() error {
// Don't re-compute if already computed.
if i.computed {
return nil
}

inspect, _, err := i.opener.client.ImageInspectWithRaw(i.opener.ctx, i.ref.String())
if err != nil {
return err
}

configFile, err := i.computeConfigFile(inspect)
if err != nil {
return err
}

i.configFile = configFile
i.computed = true

return nil
}

func (i *image) Layers() ([]v1.Layer, error) {
if err := i.initialize(); err != nil {
return nil, err
Expand Down Expand Up @@ -155,16 +183,19 @@ func (i *image) ConfigName() (v1.Hash, error) {
}

func (i *image) ConfigFile() (*v1.ConfigFile, error) {
if err := i.initialize(); err != nil {
if err := i.compute(); err != nil {
return nil, err
}
return i.tarballImage.ConfigFile()
return i.configFile.DeepCopy(), nil
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Interesting... so this lets you get the semantic image config cheaply, but if you want to actual config file docker would generate, we have to actually save the image and have docker do this serialization?

Somewhat confusing but it's nice that it's possible. What's the use case you have where you need quick access to the config file?

Copy link
Contributor Author

@knqyf263 knqyf263 Oct 11, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

but if you want to actual config file docker would generate, we have to actually save the image and have docker do this serialization?

As far as I know, it is the case. I didn't find Docker Engine API returning the actual config.

What's the use case you have where you need quick access to the config file?

Strictly speaking, we just need to get diff_id quickly so that we can check if the layer is already cached or not. Image ID doesn't meet our requirements. Let's say Image B is based on Image A like the following:

  • Image B
    • Layer 2
    • Layer 1
  • Image A
    • Layer 1

If we scan Image B, our cache should have image_id of Image B and diff_ids of Layer 1 and 2. Then, when we scan Image A, the image_id of Image A will be missed, while the diff_id of Layer 1 exists in the cache. In this case, we don't have to save Image A as we're actually interested in the layer content only.

Currently, we cannot skip saving Image A even though Layer 1 exists in our cache.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you add a test that compares the result of ConfigFile() with calling RawConfigFile() and parsing it?

I'm ok if they're not identical, but I'd like to see which fields are missing or different.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If I understand correctly, ConfigFile() and RawConfigFile() are already compared here.

if diff := cmp.Diff(pcf, cf); diff != "" {
errs = append(errs, fmt.Sprintf("mismatched config content: (-ParseConfigFile(RawConfigFile()) +ConfigFile()) %s", diff))
}

}

func (i *image) RawConfigFile() ([]byte, error) {
if err := i.initialize(); err != nil {
return nil, err
}

// RawConfigFile cannot be generated from "docker inspect" because Docker Engine API returns serialized data,
// and formatting information of the raw config such as indent and prefix will be lost.
return i.tarballImage.RawConfigFile()
}

Expand Down Expand Up @@ -202,3 +233,119 @@ func (i *image) LayerByDiffID(h v1.Hash) (v1.Layer, error) {
}
return i.tarballImage.LayerByDiffID(h)
}

func (i *image) configHistory(author string) ([]v1.History, error) {
historyItems, err := i.opener.client.ImageHistory(i.opener.ctx, i.ref.String())
if err != nil {
return nil, err
}

history := make([]v1.History, len(historyItems))
for j, h := range historyItems {
history[j] = v1.History{
Author: author,
Created: v1.Time{
Time: time.Unix(h.Created, 0).UTC(),
},
CreatedBy: h.CreatedBy,
Comment: h.Comment,
EmptyLayer: h.Size == 0,
}
}
return history, nil
}

func (i *image) diffIDs(rootFS api.RootFS) ([]v1.Hash, error) {
diffIDs := make([]v1.Hash, len(rootFS.Layers))
for j, l := range rootFS.Layers {
h, err := v1.NewHash(l)
if err != nil {
return nil, err
}
diffIDs[j] = h
}
return diffIDs, nil
}

func (i *image) computeConfigFile(inspect api.ImageInspect) (*v1.ConfigFile, error) {
diffIDs, err := i.diffIDs(inspect.RootFS)
if err != nil {
return nil, err
}

history, err := i.configHistory(inspect.Author)
if err != nil {
return nil, err
}

created, err := time.Parse(time.RFC3339Nano, inspect.Created)
if err != nil {
return nil, err
}

return &v1.ConfigFile{
Architecture: inspect.Architecture,
Author: inspect.Author,
Container: inspect.Container,
Created: v1.Time{Time: created},
DockerVersion: inspect.DockerVersion,
History: history,
OS: inspect.Os,
RootFS: v1.RootFS{
Type: inspect.RootFS.Type,
DiffIDs: diffIDs,
},
Config: i.computeImageConfig(inspect.Config),
OSVersion: inspect.OsVersion,
}, nil
}

func (i *image) computeImageConfig(config *container.Config) v1.Config {
if config == nil {
return v1.Config{}
}

c := v1.Config{
AttachStderr: config.AttachStderr,
AttachStdin: config.AttachStdin,
AttachStdout: config.AttachStdout,
Cmd: config.Cmd,
Domainname: config.Domainname,
Entrypoint: config.Entrypoint,
Env: config.Env,
Hostname: config.Hostname,
Image: config.Image,
Labels: config.Labels,
OnBuild: config.OnBuild,
OpenStdin: config.OpenStdin,
StdinOnce: config.StdinOnce,
Tty: config.Tty,
User: config.User,
Volumes: config.Volumes,
WorkingDir: config.WorkingDir,
ArgsEscaped: config.ArgsEscaped,
NetworkDisabled: config.NetworkDisabled,
MacAddress: config.MacAddress,
StopSignal: config.StopSignal,
Shell: config.Shell,
}

if config.Healthcheck != nil {
c.Healthcheck = &v1.HealthConfig{
Test: config.Healthcheck.Test,
Interval: config.Healthcheck.Interval,
Timeout: config.Healthcheck.Timeout,
StartPeriod: config.Healthcheck.StartPeriod,
Retries: config.Healthcheck.Retries,
}
}

if len(config.ExposedPorts) > 0 {
c.ExposedPorts = map[string]struct{}{}
for port := range c.ExposedPorts {
c.ExposedPorts[port] = struct{}{}
}
}

return c
}
43 changes: 42 additions & 1 deletion pkg/v1/daemon/image_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@ import (
"strings"
"testing"

"github.com/docker/docker/api/types/container"
api "github.com/docker/docker/api/types/image"

"github.com/docker/docker/api/types"
"github.com/google/go-containerregistry/internal/compare"
"github.com/google/go-containerregistry/pkg/name"
Expand Down Expand Up @@ -63,12 +66,49 @@ func (m *MockClient) ImageSave(_ context.Context, _ []string) (io.ReadCloser, er
return m.saveBody, m.saveErr
}

func (m *MockClient) ImageInspectWithRaw(context.Context, string) (types.ImageInspect, []byte, error) {
func (m *MockClient) ImageInspectWithRaw(_ context.Context, _ string) (types.ImageInspect, []byte, error) {
return types.ImageInspect{
ID: "sha256:6e0b05049ed9c17d02e1a55e80d6599dbfcce7f4f4b022e3c673e685789c470e",
RepoTags: []string{
"bazel/v1/tarball:test_image_1",
},
Created: "1970-01-01T00:00:00Z",
Author: "Bazel",
Architecture: "amd64",
Os: "linux",
Size: 8,
VirtualSize: 8,
Config: &container.Config{},
GraphDriver: types.GraphDriverData{
Data: map[string]string{
"MergedDir": "/var/lib/docker/overlay2/988ecd005d048fd47b241dd57687231859563ba65a1dfd01ae1771ebfc4cb7c5/merged",
"UpperDir": "/var/lib/docker/overlay2/988ecd005d048fd47b241dd57687231859563ba65a1dfd01ae1771ebfc4cb7c5/diff",
"WorkDir": "/var/lib/docker/overlay2/988ecd005d048fd47b241dd57687231859563ba65a1dfd01ae1771ebfc4cb7c5/work",
},
Name: "overlay2",
},
RootFS: types.RootFS{
Type: "layers",
Layers: []string{
"sha256:8897395fd26dc44ad0e2a834335b33198cb41ac4d98dfddf58eced3853fa7b17",
},
},
}, nil, nil
}

func (m *MockClient) ImageHistory(_ context.Context, _ string) ([]api.HistoryResponseItem, error) {
return []api.HistoryResponseItem{
{
CreatedBy: "bazel build ...",
ID: "sha256:6e0b05049ed9c17d02e1a55e80d6599dbfcce7f4f4b022e3c673e685789c470e",
Size: 8,
Tags: []string{
"bazel/v1/tarball:test_image_1",
},
},
}, nil
}

func TestImage(t *testing.T) {
for _, tc := range []struct {
name string
Expand Down Expand Up @@ -121,6 +161,7 @@ func TestImage(t *testing.T) {
}
return
}

err = compare.Images(img, dmn)
if err != nil {
if tc.wantErr == "" {
Expand Down
2 changes: 2 additions & 0 deletions pkg/v1/daemon/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import (
"io"

"github.com/docker/docker/api/types"
api "github.com/docker/docker/api/types/image"
"github.com/docker/docker/client"
)

Expand Down Expand Up @@ -100,4 +101,5 @@ type Client interface {
ImageLoad(context.Context, io.Reader, bool) (types.ImageLoadResponse, error)
ImageTag(context.Context, string, string) error
ImageInspectWithRaw(context.Context, string) (types.ImageInspect, []byte, error)
ImageHistory(context.Context, string) ([]api.HistoryResponseItem, error)
}