Skip to content
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
44 changes: 41 additions & 3 deletions internal/cli/plan.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,13 @@ import (
"encoding/json"
"fmt"
"io"
"strings"

"github.com/spf13/cobra"

"github.com/meigma/imgcli/internal/providers"
incusosprovider "github.com/meigma/imgcli/internal/providers/incusos"
"github.com/meigma/imgcli/internal/providers/incusos/cdn"
imgschemas "github.com/meigma/imgcli/schemas"
"github.com/meigma/imgcli/schemas/core"
)
Expand All @@ -25,7 +27,7 @@ func newPlanCommand(rt *runtime) *cobra.Command {
return err
}

plan, err := runIncusOSPlan(cmd.Context(), config)
plan, err := rt.runIncusOSPlan(cmd.Context(), config)
if err != nil {
return err
}
Expand All @@ -35,18 +37,33 @@ func newPlanCommand(rt *runtime) *cobra.Command {
}
}

func runIncusOSPlan(
func (rt *runtime) runIncusOSPlan(
ctx context.Context,
config imgschemas.Config,
) (providers.Plan, error) {
provider := incusosprovider.New(*config.Incusos, incusosprovider.Options{})
provider := incusosprovider.New(*config.Incusos, incusosprovider.Options{
Catalog: rt.incusOSPlanCatalog(),
})

return provider.Plan(ctx, providers.PlanRequest{
Image: config.Image,
OutputDir: buildOutputDir(config.Output),
})
}

func (rt *runtime) incusOSPlanCatalog() incusosprovider.Catalog {
if rt.opts.IncusOSCatalog != nil {
return rt.opts.IncusOSCatalog
}

options := []cdn.Option{}
if strings.TrimSpace(rt.opts.IncusOSCDNBaseURL) != "" {
options = append(options, cdn.WithBaseURL(rt.opts.IncusOSCDNBaseURL))
}

return cdn.NewClient(options...)
}

func printResolvedPlan(output io.Writer, plan providers.Plan) error {
encoder := json.NewEncoder(output)
encoder.SetIndent("", " ")
Expand Down Expand Up @@ -86,5 +103,26 @@ func resolvedArtifactForOutput(plan providers.Plan, artifact providers.ArtifactP
Path: artifact.OutputPath,
Labels: artifact.Labels,
Annotations: artifact.Annotations,
Source: resolvedArtifactSourceForOutput(artifact),
}
}

func resolvedArtifactSourceForOutput(artifact providers.ArtifactPlan) *core.ResolvedArtifactSource {
if artifact.Source == nil {
return nil
}

return &core.ResolvedArtifactSource{
Version: artifact.Source.Version,
URL: artifact.Source.URL,
Digest: qualifiedSHA256(artifact.Source.SHA256),
Size: artifact.Source.Size,
}
}

func qualifiedSHA256(sha256Digest string) string {
if strings.HasPrefix(sha256Digest, "sha256:") {
return sha256Digest
}
return "sha256:" + sha256Digest
}
101 changes: 93 additions & 8 deletions internal/cli/root_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"bytes"
"context"
"encoding/json"
"errors"
"os"
"path/filepath"
"strings"
Expand Down Expand Up @@ -178,13 +179,42 @@ incusos: {
}
`)

result := executeCommand(t, Options{}, "--cache-dir", cacheDir, "plan", configPath)
catalog := &testCatalog{
asset: incusos.ImageAsset{
Version: incusos.Version("202604261712"),
Architecture: core.Architecture("amd64"),
Type: incusos.ImageTypeRaw,
URL: "https://example.invalid/os/202604261712/x86_64/IncusOS_202604261712.img.gz",
SHA256: "source-sha",
Size: 42,
},
}

result := executeCommand(t, Options{IncusOSCatalog: catalog}, "--cache-dir", cacheDir, "plan", configPath)

require.NoError(t, result.err)
assert.Empty(t, result.stderr)
assert.NoDirExists(t, cacheDir)
assert.Equal(t, []incusos.ImageQuery{
{
Channel: incusos.ChannelTesting,
Architecture: core.Architecture("amd64"),
Type: incusos.ImageTypeRaw,
},
{
Channel: incusos.ChannelTesting,
Architecture: core.Architecture("amd64"),
Type: incusos.ImageTypeRaw,
},
}, catalog.queries)
var plan core.ResolvedPlan
require.NoError(t, json.Unmarshal([]byte(result.stdout), &plan))
source := &core.ResolvedArtifactSource{
Version: "202604261712",
URL: "https://example.invalid/os/202604261712/x86_64/IncusOS_202604261712.img.gz",
Digest: "sha256:source-sha",
Size: 42,
}
assert.Equal(t, core.ResolvedPlan{
Image: core.Image{
Name: core.Name("test-image"),
Expand All @@ -204,6 +234,7 @@ incusos: {
Path: filepath.Join(outputDir, "test-image-default-amd64.raw.gz"),
Labels: map[string]string{"tier": "smoke"},
Annotations: map[string]string{"note": "planned"},
Source: source,
},
"secureboot": {
ArtifactKey: core.ArtifactKey("secureboot"),
Expand All @@ -215,6 +246,7 @@ incusos: {
Format: core.ArtifactFormat("raw.gz"),
MediaType: "application/gzip",
Path: filepath.Join(outputDir, "custom", "secureboot.img.gz"),
Source: source,
},
},
}, plan)
Expand All @@ -233,13 +265,44 @@ incusos: variants: default: artifact: {
}
`)

result := executeCommand(t, Options{}, "plan", configPath)
result := executeCommand(t, Options{
IncusOSCatalog: &testCatalog{asset: incusos.ImageAsset{
Version: incusos.Version("202604261712"),
Architecture: core.Architecture("amd64"),
Type: incusos.ImageTypeRaw,
URL: "https://example.invalid/incusos.img.gz",
SHA256: "source-sha",
Size: 42,
}},
}, "plan", configPath)

require.NoError(t, result.err)
assert.Empty(t, result.stderr)
assert.NotEmpty(t, result.stdout)
})

t.Run("catalog errors fail without stdout", func(t *testing.T) {
clearIMGCLIEnv(t)
catalogErr := errors.New("catalog failed")
configPath := writeImageConfig(t, `
apiVersion: "imgcli.meigma.io/v0alpha1"
kind: "ImagePlan"
image: name: "test-image"
incusos: variants: default: artifact: {
architecture: "amd64"
format: "raw.gz"
}
`)

result := executeCommand(t, Options{
IncusOSCatalog: &testCatalog{err: catalogErr},
}, "plan", configPath)

require.ErrorIs(t, result.err, catalogErr)
assert.Empty(t, result.stdout)
assert.Empty(t, result.stderr)
})

t.Run("missing provider fails explicitly", func(t *testing.T) {
clearIMGCLIEnv(t)
configPath := writeImageConfig(t, `
Expand Down Expand Up @@ -380,6 +443,7 @@ talos: {}
Path: run.defaultPath,
Labels: map[string]string{"tier": "smoke"},
Annotations: map[string]string{"note": "built"},
Source: testResolvedSource(),
Digest: "sha256:" + run.sha256,
Size: int64(len(run.artifactBody)),
})
Expand All @@ -393,6 +457,7 @@ talos: {}
Format: core.ArtifactFormat("raw.gz"),
MediaType: "application/gzip",
Path: run.secureBootPath,
Source: testResolvedSource(),
Digest: "sha256:" + run.sha256,
Size: int64(len(run.artifactBody)),
})
Expand Down Expand Up @@ -561,9 +626,12 @@ incusos: {
wantOutputPath := filepath.Join(outputDir, "test-image-default-amd64.raw.gz")
catalog := &testCatalog{
asset: incusos.ImageAsset{
URL: "https://example.invalid/os/202604261712/x86_64/IncusOS_202604261712.img.gz",
SHA256: "source-sha",
Size: 42,
Version: incusos.Version("202604261712"),
Architecture: core.Architecture("amd64"),
Type: incusos.ImageTypeRaw,
URL: "https://example.invalid/os/202604261712/x86_64/IncusOS_202604261712.img.gz",
SHA256: "source-sha",
Size: 42,
},
}
downloader := &testDownloader{
Expand Down Expand Up @@ -843,9 +911,12 @@ incusos: {
secureBootPath := filepath.Join(outputDir, "test-image-secureboot-amd64.raw.gz")
catalog := &testCatalog{
asset: incusos.ImageAsset{
URL: "https://example.invalid/os/202604261712/x86_64/IncusOS_202604261712.img.gz",
SHA256: "source-sha",
Size: 42,
Version: incusos.Version("202604261712"),
Architecture: core.Architecture("amd64"),
Type: incusos.ImageTypeRaw,
URL: "https://example.invalid/os/202604261712/x86_64/IncusOS_202604261712.img.gz",
SHA256: "source-sha",
Size: 42,
},
}
downloader := &testDownloader{
Expand Down Expand Up @@ -907,6 +978,15 @@ func assertBuildMetadata(t *testing.T, path string, want core.ResolvedArtifact)
assert.Equal(t, os.FileMode(artifactMetadataFileMode), info.Mode().Perm())
}

func testResolvedSource() *core.ResolvedArtifactSource {
return &core.ResolvedArtifactSource{
Version: "202604261712",
URL: "https://example.invalid/os/202604261712/x86_64/IncusOS_202604261712.img.gz",
Digest: "sha256:source-sha",
Size: 42,
}
}

func assertSuccessfulBuildAdapters(t *testing.T, run buildCommandRun) {
t.Helper()

Expand Down Expand Up @@ -989,11 +1069,16 @@ func writeImageConfig(t *testing.T, content string) string {

type testCatalog struct {
asset incusos.ImageAsset
err error
queries []incusos.ImageQuery
}

func (c *testCatalog) ResolveImage(_ context.Context, query incusos.ImageQuery) (incusos.ImageAsset, error) {
c.queries = append(c.queries, query)
if c.err != nil {
return incusos.ImageAsset{}, c.err
}

return c.asset, nil
}

Expand Down
72 changes: 59 additions & 13 deletions internal/providers/incusos/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,11 +60,17 @@ func (p *Provider) Name() core.ProviderName {
}

// Plan resolves IncusOS configuration into concrete artifact work.
func (p *Provider) Plan(_ context.Context, req providers.PlanRequest) (providers.Plan, error) {
func (p *Provider) Plan(ctx context.Context, req providers.PlanRequest) (providers.Plan, error) {
artifacts, err := planArtifacts(req, p.config)
if err != nil {
return providers.Plan{}, err
}
if p.options.Catalog == nil {
return providers.Plan{}, errors.New("incusos catalog is required")
}
if err := p.resolveArtifactSources(ctx, artifacts); err != nil {
return providers.Plan{}, err
}

return providerPlan(req, artifacts), nil
}
Expand Down Expand Up @@ -105,18 +111,7 @@ func (p *Provider) Build(ctx context.Context, req providers.BuildRequest) (provi
builtArtifacts := make([]providers.BuiltArtifact, 0, len(artifacts))
cleanupOutputs := make([]string, 0, len(artifacts))
for _, artifact := range artifacts {
source := resolveSource(p.config.Defaults, artifact.variant.Source)
asset, err := p.options.Catalog.ResolveImage(ctx, ImageQuery{
Channel: source.Channel,
Version: source.Version,
Architecture: artifact.plan.Architecture,
Type: artifact.imageType,
})
if err != nil {
return providers.BuildResult{}, cleanupBuiltOutputs(err, cleanupOutputs)
}

downloaded, err := p.options.Downloader.DownloadImage(ctx, asset)
downloaded, err := p.options.Downloader.DownloadImage(ctx, artifact.source)
if err != nil {
return providers.BuildResult{}, cleanupBuiltOutputs(err, cleanupOutputs)
}
Expand Down Expand Up @@ -144,9 +139,31 @@ func (p *Provider) Build(ctx context.Context, req providers.BuildRequest) (provi
type plannedArtifact struct {
variant incusosschema.Variant
imageType ImageType
source ImageAsset
plan providers.ArtifactPlan
}

func (p *Provider) resolveArtifactSources(ctx context.Context, artifacts []plannedArtifact) error {
for index := range artifacts {
artifact := &artifacts[index]
source := resolveSource(p.config.Defaults, artifact.variant.Source)
asset, err := p.options.Catalog.ResolveImage(ctx, ImageQuery{
Channel: source.Channel,
Version: source.Version,
Architecture: artifact.plan.Architecture,
Type: artifact.imageType,
})
if err != nil {
return err
}

artifact.source = asset
artifact.plan.Source = sourceMetadataForAsset(asset)
}

return nil
}

func planArtifacts(req providers.PlanRequest, config Config) ([]plannedArtifact, error) {
if len(config.Variants) == 0 {
return nil, errors.New("incusos build requires at least one variant")
Expand Down Expand Up @@ -237,17 +254,46 @@ func plannedArtifactsForExecution(plan providers.Plan, config Config) ([]planned
if err != nil {
return nil, err
}
sourceAsset, err := sourceAssetFromPlan(artifactPlan, imageType)
if err != nil {
return nil, err
}

artifacts = append(artifacts, plannedArtifact{
variant: variant,
imageType: imageType,
source: sourceAsset,
plan: artifactPlan,
})
}

return artifacts, nil
}

func sourceMetadataForAsset(asset ImageAsset) *providers.SourceMetadata {
return &providers.SourceMetadata{
Version: string(asset.Version),
URL: asset.URL,
SHA256: asset.SHA256,
Size: asset.Size,
}
}

func sourceAssetFromPlan(artifact providers.ArtifactPlan, imageType ImageType) (ImageAsset, error) {
if artifact.Source == nil {
return ImageAsset{}, fmt.Errorf("incusos planned artifact %q is missing source metadata", artifact.Key)
}

return ImageAsset{
Version: Version(artifact.Source.Version),
Architecture: artifact.Architecture,
Type: imageType,
URL: artifact.Source.URL,
SHA256: artifact.Source.SHA256,
Size: artifact.Source.Size,
}, nil
}

func rejectExistingOutputPaths(artifacts []plannedArtifact) error {
for _, artifact := range artifacts {
path := artifact.plan.OutputPath
Expand Down
Loading