diff --git a/cmd/kosli/snapshotECS.go b/cmd/kosli/snapshotECS.go index baa8c6e0f..747600c7f 100644 --- a/cmd/kosli/snapshotECS.go +++ b/cmd/kosli/snapshotECS.go @@ -98,6 +98,7 @@ type snapshotECSOptions struct { serviceFilter *filters.ResourceFilterOptions serviceName string awsStaticCreds *aws.AWSStaticCreds + generic bool } func newSnapshotECSCmd(out io.Writer) *cobra.Command { @@ -181,6 +182,7 @@ func newSnapshotECSCmd(out io.Writer) *cobra.Command { cmd.Flags().StringVarP(&o.serviceName, "service-name", "s", "", ecsServiceFlag) addAWSAuthFlags(cmd, o.awsStaticCreds) addDryRunFlag(cmd) + addGenericFlag(cmd, &o.generic) err := DeprecateFlags(cmd, map[string]string{ "cluster": "use --clusters instead", @@ -194,6 +196,9 @@ func newSnapshotECSCmd(out io.Writer) *cobra.Command { } func (o *snapshotECSOptions) run(args []string) error { + if o.generic { + return o.runGeneric(args) + } envName := args[0] return newSnapshotReporter().report(envName, "ECS", func() (any, string, error) { tasksData, err := o.awsStaticCreds.GetEcsTasksData(o.clustersFilter, o.serviceFilter, logger) diff --git a/cmd/kosli/snapshotECSGeneric.go b/cmd/kosli/snapshotECSGeneric.go new file mode 100644 index 000000000..b73e93133 --- /dev/null +++ b/cmd/kosli/snapshotECSGeneric.go @@ -0,0 +1,33 @@ +package main + +import ( + "fmt" + + "github.com/kosli-dev/cli/internal/envreport" + "github.com/spf13/cobra" +) + +const genericFlag = "[optional] Report a version 1 environment report, with every workload the command sees, to the route every environment type shares." + +// addGenericFlag adds the hidden --generic flag, which a snapshot command +// reads to send a version 1 report instead of its typed one. +func addGenericFlag(cmd *cobra.Command, generic *bool) { + cmd.Flags().BoolVar(generic, "generic", false, genericFlag) + if err := cmd.Flags().MarkHidden("generic"); err != nil { + logger.Error("failed to hide the generic flag: %v", err) + } +} + +// runGeneric reports the ECS clusters and services the filters keep as a +// version 1 report: a workload per service, an instance per task. +func (o *snapshotECSOptions) runGeneric(args []string) error { + envName := args[0] + return newSnapshotReporter().reportGeneric(envName, "ECS", func() (any, string, error) { + workloads, err := o.awsStaticCreds.GetEcsWorkloads(o.clustersFilter, o.serviceFilter, logger) + if err != nil { + return nil, "", err + } + reported := fmt.Sprintf("[%d] workloads were reported to environment %s", len(workloads), envName) + return envreport.FullReport(workloads), reported, nil + }) +} diff --git a/cmd/kosli/snapshotECSGeneric_test.go b/cmd/kosli/snapshotECSGeneric_test.go new file mode 100644 index 000000000..9998bc1d9 --- /dev/null +++ b/cmd/kosli/snapshotECSGeneric_test.go @@ -0,0 +1,21 @@ +package main + +import ( + "io" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestSnapshotECSHasAHiddenGenericFlag(t *testing.T) { + previous := global + global = &GlobalOpts{} + t.Cleanup(func() { global = previous }) + cmd := newSnapshotECSCmd(io.Discard) + + flag := cmd.Flags().Lookup("generic") + + require.NotNil(t, flag) + require.True(t, flag.Hidden) + require.Equal(t, "false", flag.DefValue) +} diff --git a/cmd/kosli/snapshotReportGeneric.go b/cmd/kosli/snapshotReportGeneric.go new file mode 100644 index 000000000..a6163320a --- /dev/null +++ b/cmd/kosli/snapshotReportGeneric.go @@ -0,0 +1,40 @@ +package main + +import ( + "net/http" + "net/url" + + "github.com/kosli-dev/cli/internal/requests" +) + +// reportGeneric reports a version 1 environment report, sent by a snapshot +// command's hidden --generic flag, to the route every environment type +// shares. It prepares the Environment as report does, but leaves report and +// the typed routes untouched. +func (r *snapshotReporter) reportGeneric(envName, envType string, collect snapshotCollector) error { + if err := r.ensureOnce(envName, envType); err != nil { + return err + } + + endpoint, err := url.JoinPath(r.host, "api/v2/environments", r.org, envName, "report") + if err != nil { + return err + } + + payload, reported, err := collect() + if err != nil { + return err + } + + _, err = r.client.Do(&requests.RequestParams{ + Method: http.MethodPut, + URL: endpoint, + Payload: payload, + DryRun: r.dryRun, + Token: r.token, + }) + if err == nil && !r.dryRun { + r.logger.Info("%s", reported) + } + return err +} diff --git a/cmd/kosli/snapshotReportGeneric_test.go b/cmd/kosli/snapshotReportGeneric_test.go new file mode 100644 index 000000000..d1c74b3b2 --- /dev/null +++ b/cmd/kosli/snapshotReportGeneric_test.go @@ -0,0 +1,67 @@ +package main + +import ( + "net/http" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestSnapshotReporterPutsAGenericReportToTheEnvironmentURL(t *testing.T) { + server, fake := newFakeSnapshotServer(t) + reporter, _, _ := newTestSnapshotReporter(t, server.URL, false) + + err := reporter.reportGeneric("prod", "ECS", oneWorkload) + + require.NoError(t, err) + require.Len(t, fake.recorded, 1) + require.Equal(t, http.MethodPut, fake.recorded[0].method) + require.Equal(t, "/api/v2/environments/acme/prod/report", fake.recorded[0].path) + require.Equal(t, "1", fake.recorded[0].body["schema_version"]) +} + +func TestSnapshotReporterEnsuresTheEnvironmentBeforeAGenericReport(t *testing.T) { + server, _ := newFakeSnapshotServer(t) + reporter, ensured, _ := newTestSnapshotReporter(t, server.URL, false) + var ensuredWhenCollecting []string + + err := reporter.reportGeneric("prod", "ECS", func() (any, string, error) { + ensuredWhenCollecting = append([]string{}, ensured.calls...) + return oneWorkload() + }) + + require.NoError(t, err) + require.Equal(t, []string{"prod/ECS"}, ensuredWhenCollecting) +} + +func TestSnapshotReporterLogsTheGenericReportedLine(t *testing.T) { + server, _ := newFakeSnapshotServer(t) + reporter, _, out := newTestSnapshotReporter(t, server.URL, false) + + err := reporter.reportGeneric("prod", "ECS", oneWorkload) + + require.NoError(t, err) + require.Equal(t, "[1] workloads were reported to environment prod\n", out.String()) +} + +func TestSnapshotReporterSendsNoGenericReportInDryRun(t *testing.T) { + server, fake := newFakeSnapshotServer(t) + reporter, _, out := newTestSnapshotReporter(t, server.URL, true) + + err := reporter.reportGeneric("prod", "ECS", oneWorkload) + + require.NoError(t, err) + require.Empty(t, fake.recorded) + require.Contains(t, out.String(), "THIS IS A DRY-RUN") + require.NotContains(t, out.String(), "workloads were reported") +} + +// oneWorkload collects a version 1 report of one workload. +func oneWorkload() (any, string, error) { + payload := map[string]any{ + "schema_version": "1", + "scope": map[string]any{"all": true}, + "claims": []map[string]any{{"type": "workload.observed"}}, + } + return payload, "[1] workloads were reported to environment prod", nil +} diff --git a/cmd/kosli/testdata/empty-flag-audit-coverage.json b/cmd/kosli/testdata/empty-flag-audit-coverage.json index ce30451e8..1b0b66000 100644 --- a/cmd/kosli/testdata/empty-flag-audit-coverage.json +++ b/cmd/kosli/testdata/empty-flag-audit-coverage.json @@ -972,6 +972,7 @@ "exclude-regex": "stringSlice", "exclude-services": "stringSlice", "exclude-services-regex": "stringSlice", + "generic": "bool", "service-name": "string", "services": "stringSlice", "services-regex": "stringSlice" diff --git a/internal/aws/ecs_generic.go b/internal/aws/ecs_generic.go new file mode 100644 index 000000000..9631bb59b --- /dev/null +++ b/internal/aws/ecs_generic.go @@ -0,0 +1,191 @@ +package aws + +import ( + "context" + "fmt" + "reflect" + "strings" + + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/ecs" + ecsTypes "github.com/aws/aws-sdk-go-v2/service/ecs/types" + "github.com/kosli-dev/cli/internal/envreport" + "github.com/kosli-dev/cli/internal/filters" + "github.com/kosli-dev/cli/internal/logger" +) + +// This file is the snapshot ecs --generic path only. Nothing here is called +// by the legacy path, so the report today's command sends cannot change. + +// ECSTasksAPI is the subset of AWS ECS operations used when listing and +// describing a service's tasks. The real *ecs.Client satisfies this +// implicitly. +type ECSTasksAPI interface { + ListTasks(ctx context.Context, params *ecs.ListTasksInput, optFns ...func(*ecs.Options)) (*ecs.ListTasksOutput, error) + DescribeTasks(ctx context.Context, params *ecs.DescribeTasksInput, optFns ...func(*ecs.Options)) (*ecs.DescribeTasksOutput, error) +} + +// ECSWorkloadsAPI is the subset of AWS ECS operations used to gather the +// workloads of a snapshot ecs --generic run. +type ECSWorkloadsAPI interface { + ECSClustersAPI + ECSServicesAPI + ECSTasksAPI +} + +// GetEcsWorkloads is the version 1 workload of every service in the +// clusters and services the filters keep, for snapshot ecs --generic. +func (staticCreds *AWSStaticCreds) GetEcsWorkloads(clusterFilter, serviceFilter *filters.ResourceFilterOptions, logger *logger.Logger) ([]envreport.Workload, error) { + client, err := staticCreds.NewECSClient() + if err != nil { + return nil, fmt.Errorf("failed to create ECS client: %w", err) + } + return ecsWorkloads(client, clusterFilter.Compile(), serviceFilter.Compile(), logger) +} + +// ecsWorkloads is the version 1 workload of every service in the clusters +// and services the filters keep, warning, as the legacy path does, when a +// filter leaves out every cluster or service it was given. +func ecsWorkloads(client ECSWorkloadsAPI, clusterFilter, serviceFilter *filters.CompiledResourceFilter, logger *logger.Logger) ([]envreport.Workload, error) { + workloads := []envreport.Workload{} + clusters, listedClusters, err := getFilteredECSClusters(client, &[]ecsTypes.Cluster{}, clusterFilter, nil, logger) + if err != nil { + return nil, fmt.Errorf("failed to filter ECS clusters: %w", err) + } + clusterFilter.WarnIfLeftOutAll(listedClusters, len(*clusters), "ECS clusters", logger) + listedServices, keptServices := 0, 0 + for _, cluster := range *clusters { + clusterName := *cluster.ClusterName + services, listed, err := getFilteredECSServicesInCluster(client, clusterName, &[]ecsTypes.Service{}, serviceFilter, nil, logger) + if err != nil { + return nil, fmt.Errorf("failed to filter ECS services in cluster %s: %w", clusterName, err) + } + listedServices += listed + keptServices += len(*services) + for _, service := range *services { + tasks, err := ecsServiceTasks(client, clusterName, service) + if err != nil { + return nil, fmt.Errorf("failed to get tasks data in cluster %s: %w", clusterName, err) + } + workloads = append(workloads, ecsWorkload(clusterName, service, tasks)) + } + } + serviceFilter.WarnIfLeftOutAll(listedServices, keptServices, "ECS services in the scanned clusters", logger) + return workloads, nil +} + +// ecsServiceTasks is every task of the service, gathered from each page +// ListTasks returns (100 at a time), so one service is one set of tasks. +func ecsServiceTasks(client ECSTasksAPI, clusterName string, service ecsTypes.Service) ([]ecsTypes.Task, error) { + tasks := []ecsTypes.Task{} + listInput := &ecs.ListTasksInput{ + Cluster: aws.String(clusterName), + ServiceName: service.ServiceName, + } + for { + listTasksOutput, err := client.ListTasks(context.Background(), listInput) + if err != nil { + return tasks, err + } + if len(listTasksOutput.TaskArns) > 0 { + result, err := client.DescribeTasks(context.Background(), &ecs.DescribeTasksInput{ + Cluster: aws.String(clusterName), + Tasks: listTasksOutput.TaskArns, + }) + if err != nil { + return tasks, err + } + tasks = append(tasks, result.Tasks...) + } + if listTasksOutput.NextToken == nil { + return tasks, nil + } + listInput.NextToken = listTasksOutput.NextToken + } +} + +// ecsWorkload is the version 1 workload of a service: a component per +// container of its first running task, and an instance per running task. A +// task not running is left out, as the typed report leaves it out; a service +// with no running task has neither. +func ecsWorkload(clusterName string, service ecsTypes.Service, tasks []ecsTypes.Task) envreport.Workload { + running := []ecsTypes.Task{} + for _, task := range tasks { + if aws.ToString(task.LastStatus) == "RUNNING" { + running = append(running, task) + } + } + components := []envreport.Component{} + if len(running) > 0 { + components = ecsComponents(running[0]) + } + instances := []envreport.Instance{} + for _, task := range running { + instances = append(instances, ecsInstance(task, components)) + } + return envreport.Workload{ + ID: *service.ServiceArn, + Name: *service.ServiceName, + Kind: "service", + Metadata: map[string]any{"aws.ecs.cluster.name": clusterName}, + Components: components, + Instances: instances, + } +} + +// ecsComponents is a version 1 component per container the task runs. +func ecsComponents(task ecsTypes.Task) []envreport.Component { + components := []envreport.Component{} + for _, container := range task.Containers { + components = append(components, envreport.Component{ + Name: *container.Name, + Artifact: ecsArtifact(container), + }) + } + return components +} + +// ecsInstance is the running task as a version 1 instance, with components +// of its own only when it runs other artifacts than its workload's components. +func ecsInstance(task ecsTypes.Task, workloadComponents []envreport.Component) envreport.Instance { + instance := envreport.Instance{ + ID: *task.TaskArn, + StartedAt: task.StartedAt.UTC().Format("2006-01-02T15:04:05Z"), + } + components := ecsComponents(task) + if !reflect.DeepEqual(components, workloadComponents) { + instance.Components = &components + } + return instance +} + +// ecsArtifact is the version 1 artifact a container runs; one with no +// digest is unidentified, as the legacy report's empty digest says. +func ecsArtifact(container ecsTypes.Container) envreport.Artifact { + imageName, digest := ecsImageDigest(container) + if digest == "" { + return envreport.Artifact{Name: imageName, Unidentified: "image pulled by tag; ECS resolved no digest"} + } else { + return envreport.Artifact{Name: imageName, Fingerprint: &digest} + } +} + +// ecsImageDigest is the name a container's image is reported under and its +// digest: the one ECS resolved, else the one the image is pinned by, else "". +// It keeps the legacy path's rule in getTasksDataInClusterService, which the +// server's oracle checks: the same image name and digest in both reports. +func ecsImageDigest(container ecsTypes.Container) (string, string) { + imageName := container.Image + if imageName == nil { + // some images like AWS Guard Duty don't get an image name from AWS + // so we default to the container name + imageName = container.Name + } + if container.ImageDigest != nil { + return *imageName, strings.TrimPrefix(*container.ImageDigest, "sha256:") + } else if strings.Contains(*imageName, "@sha256:") { + return *imageName, strings.Split(*imageName, "@sha256:")[1] + } else { + return *imageName, "" + } +} diff --git a/internal/aws/ecs_generic_test.go b/internal/aws/ecs_generic_test.go new file mode 100644 index 000000000..bf3f76e0f --- /dev/null +++ b/internal/aws/ecs_generic_test.go @@ -0,0 +1,221 @@ +package aws + +import ( + "encoding/json" + "testing" + "time" + + "github.com/aws/aws-sdk-go-v2/aws" + ecsTypes "github.com/aws/aws-sdk-go-v2/service/ecs/types" + "github.com/kosli-dev/cli/internal/envreport" + "github.com/kosli-dev/cli/internal/filters" + "github.com/kosli-dev/cli/internal/logger" + "github.com/stretchr/testify/require" +) + +const ( + billingTaskArn = "arn:aws:ecs:eu-west-1:123456789012:task/prod/4b1e9c7d2a6f4e0b8c3d" + billingServiceArn = "arn:aws:ecs:eu-west-1:123456789012:service/prod/billing" + billingImage = "123456789012.dkr.ecr.eu-west-1.amazonaws.com/billing:2.0.7" + billingSha = "8e4c1e13057c13e36dc878e29f014fae9957731a554f8694b682a6d57b35acd4" + billingNextTaskArn = "arn:aws:ecs:eu-west-1:123456789012:task/prod/c7a2e5f9d1b34e8a6f0c" + billingNextImage = "123456789012.dkr.ecr.eu-west-1.amazonaws.com/billing:2.0.8" + billingNextSha = "68d7c04782c5ef157f6941124c8d323f0a392539c659bee71dcf62fc3517fc5d" + guarddutySha = "010cf1c0be57a10e2974f22e55974815570c84343b5a3907053ede8ba1be8d5b" + datadogSha = "2fcb308a64586fff2b097ebea019409693711853a2c41c9c501b542c8ddeec92" + datadogImage = "public.ecr.aws/datadog/agent@sha256:" + datadogSha + logRouterImage = "public.ecr.aws/aws-observability/aws-for-fluent-bit:stable" +) + +// 2025-11-24T16:00:00Z +var billingStartedAt = time.Unix(1764000000, 0).UTC() + +// TestEcsArtifact pins the legacy path's image name and digest rule, which +// the --generic path keeps as its own copy. +func TestEcsArtifact(t *testing.T) { + t.Run("an image is named as reported, with the digest ECS resolved", func(t *testing.T) { + actual := ecsArtifact(billingContainer(billingImage, billingSha)) + + require.Equal(t, identified(billingImage, billingSha), actual) + }) + + t.Run("an image with no name is named after its container", func(t *testing.T) { + actual := ecsArtifact(ecsTypes.Container{ + Name: aws.String("aws-guardduty-agent-nm40l"), + ImageDigest: aws.String("sha256:" + guarddutySha), + }) + + require.Equal(t, identified("aws-guardduty-agent-nm40l", guarddutySha), actual) + }) + + t.Run("an image pinned by digest, which ECS did not resolve, has the pinned digest", func(t *testing.T) { + actual := ecsArtifact(ecsTypes.Container{ + Name: aws.String("datadog-agent"), + Image: aws.String(datadogImage), + }) + + require.Equal(t, identified(datadogImage, datadogSha), actual) + }) + + t.Run("an image pulled by tag, which ECS did not resolve, is unidentified", func(t *testing.T) { + artifact := ecsArtifact(ecsTypes.Container{ + Name: aws.String("log-router"), + Image: aws.String(logRouterImage), + }) + actual, err := json.Marshal(artifact) + + require.NoError(t, err) + require.JSONEq(t, `{ + "name": "`+logRouterImage+`", + "fingerprint": null, + "unidentified": "image pulled by tag; ECS resolved no digest" + }`, string(actual)) + }) +} + +func TestEcsWorkload(t *testing.T) { + t.Run("a service is a workload; its tasks are instances running its first task's containers", func(t *testing.T) { + task := billingTask(billingContainer(billingImage, billingSha)) + + actual, err := json.Marshal(ecsWorkload("prod", billingService(), []ecsTypes.Task{task})) + + require.NoError(t, err) + require.JSONEq(t, `{ + "id": "`+billingServiceArn+`", + "name": "billing", + "kind": "service", + "metadata": {"aws.ecs.cluster.name": "prod"}, + "components": [{ + "name": "billing", + "artifact": {"name": "`+billingImage+`", "fingerprint": "`+billingSha+`"} + }], + "instances": [{ + "id": "`+billingTaskArn+`", + "started_at": "2025-11-24T16:00:00Z" + }] + }`, string(actual)) + }) +} + +func TestEcsWorkloadRollout(t *testing.T) { + t.Run("a task running other images than the first task has components of its own", func(t *testing.T) { + old := billingTask(billingContainer(billingImage, billingSha)) + next := billingTask(billingContainer(billingNextImage, billingNextSha)) + next.TaskArn = aws.String(billingNextTaskArn) + + workload := ecsWorkload("prod", billingService(), []ecsTypes.Task{old, next}) + actual, err := json.Marshal(workload.Instances) + + require.NoError(t, err) + require.JSONEq(t, `[ + {"id": "`+billingTaskArn+`", "started_at": "2025-11-24T16:00:00Z"}, + {"id": "`+billingNextTaskArn+`", "started_at": "2025-11-24T16:00:00Z", + "components": [{ + "name": "billing", + "artifact": {"name": "`+billingNextImage+`", "fingerprint": "`+billingNextSha+`"} + }]} + ]`, string(actual)) + }) +} + +func TestEcsWorkloadTaskNotRunning(t *testing.T) { + t.Run("a task not running yet is left out, as the typed report leaves it out", func(t *testing.T) { + pending := billingTask(billingContainer(billingNextImage, billingNextSha)) + pending.TaskArn = aws.String(billingNextTaskArn) + pending.LastStatus = aws.String("PENDING") + pending.StartedAt = nil + running := billingTask(billingContainer(billingImage, billingSha)) + + workload := ecsWorkload("prod", billingService(), []ecsTypes.Task{pending, running}) + actual, err := json.Marshal(workload) + + require.NoError(t, err) + require.JSONEq(t, `{ + "id": "`+billingServiceArn+`", + "name": "billing", + "kind": "service", + "metadata": {"aws.ecs.cluster.name": "prod"}, + "components": [{ + "name": "billing", + "artifact": {"name": "`+billingImage+`", "fingerprint": "`+billingSha+`"} + }], + "instances": [{"id": "`+billingTaskArn+`", "started_at": "2025-11-24T16:00:00Z"}] + }`, string(actual)) + }) +} + +func TestEcsWorkloadScaledToZero(t *testing.T) { + t.Run("a service with no tasks is a workload with no components and no instances", func(t *testing.T) { + workload := ecsWorkload("prod", billingService(), []ecsTypes.Task{}) + + require.Equal(t, []envreport.Component{}, workload.Components) + require.Equal(t, []envreport.Instance{}, workload.Instances) + require.Equal(t, "billing", workload.Name) + }) +} + +func TestEcsServiceTasks(t *testing.T) { + t.Run("a service's tasks are gathered from every page ListTasks returns", func(t *testing.T) { + first := billingTask(billingContainer(billingImage, billingSha)) + second := billingTask(billingContainer(billingNextImage, billingNextSha)) + second.TaskArn = aws.String(billingNextTaskArn) + client := &FakeECSClient{TaskPages: [][]ecsTypes.Task{{first}, {second}}} + + actual, err := ecsServiceTasks(client, "prod", billingService()) + + require.NoError(t, err) + require.Equal(t, []ecsTypes.Task{first, second}, actual) + }) +} + +func TestEcsWorkloads(t *testing.T) { + t.Run("each filtered service of each filtered cluster is a workload", func(t *testing.T) { + task := billingTask(billingContainer(billingImage, billingSha)) + client := &FakeECSClient{ + Clusters: []ecsTypes.Cluster{{ClusterName: aws.String("prod")}}, + ServiceArns: []string{billingServiceArn}, + Services: []ecsTypes.Service{billingService()}, + TaskPages: [][]ecsTypes.Task{{task}}, + } + everything := (&filters.ResourceFilterOptions{}).Compile() + + actual, err := ecsWorkloads(client, everything, everything, logger.NewStandardLogger()) + + require.NoError(t, err) + require.Equal(t, []envreport.Workload{ + ecsWorkload("prod", billingService(), []ecsTypes.Task{task}), + }, actual) + }) +} + +// identified is the artifact named name, with the fingerprint sha. +func identified(name, sha string) envreport.Artifact { + return envreport.Artifact{Name: name, Fingerprint: &sha} +} + +// billingContainer is the billing container running image, with the digest ECS resolved. +func billingContainer(image, sha string) ecsTypes.Container { + return ecsTypes.Container{ + Name: aws.String("billing"), + Image: aws.String(image), + ImageDigest: aws.String("sha256:" + sha), + } +} + +// billingService is the prod cluster's billing service. +func billingService() ecsTypes.Service { + return ecsTypes.Service{ + ServiceName: aws.String("billing"), + ServiceArn: aws.String(billingServiceArn), + } +} + +// billingTask is a running billing task, started at billingStartedAt, with containers. +func billingTask(containers ...ecsTypes.Container) ecsTypes.Task { + return ecsTypes.Task{ + TaskArn: aws.String(billingTaskArn), + LastStatus: aws.String("RUNNING"), + StartedAt: aws.Time(billingStartedAt), + Containers: containers, + } +} diff --git a/internal/aws/fake_ecs.go b/internal/aws/fake_ecs.go index ad59c9ec5..a3b64398a 100644 --- a/internal/aws/fake_ecs.go +++ b/internal/aws/fake_ecs.go @@ -3,6 +3,7 @@ package aws import ( "context" "fmt" + "slices" "github.com/aws/aws-sdk-go-v2/service/ecs" ecsTypes "github.com/aws/aws-sdk-go-v2/service/ecs/types" @@ -18,6 +19,42 @@ type FakeECSClient struct { ServiceArns []string // Services is the list of services returned by DescribeServices. Services []ecsTypes.Service + // TaskPages are the tasks ListTasks returns, one page at a time, and + // DescribeTasks describes by ARN. + TaskPages [][]ecsTypes.Task +} + +func (f *FakeECSClient) ListTasks(_ context.Context, params *ecs.ListTasksInput, _ ...func(*ecs.Options)) (*ecs.ListTasksOutput, error) { + page := 0 + if params.NextToken != nil { + _, err := fmt.Sscanf(*params.NextToken, "page-%d", &page) + if err != nil { + return nil, err + } + } + output := &ecs.ListTasksOutput{TaskArns: []string{}} + if page < len(f.TaskPages) { + for _, task := range f.TaskPages[page] { + output.TaskArns = append(output.TaskArns, *task.TaskArn) + } + } + if page+1 < len(f.TaskPages) { + next := fmt.Sprintf("page-%d", page+1) + output.NextToken = &next + } + return output, nil +} + +func (f *FakeECSClient) DescribeTasks(_ context.Context, params *ecs.DescribeTasksInput, _ ...func(*ecs.Options)) (*ecs.DescribeTasksOutput, error) { + output := &ecs.DescribeTasksOutput{} + for _, page := range f.TaskPages { + for _, task := range page { + if slices.Contains(params.Tasks, *task.TaskArn) { + output.Tasks = append(output.Tasks, task) + } + } + } + return output, nil } func (f *FakeECSClient) ListClusters(_ context.Context, _ *ecs.ListClustersInput, _ ...func(*ecs.Options)) (*ecs.ListClustersOutput, error) { diff --git a/internal/envreport/envreport.go b/internal/envreport/envreport.go new file mode 100644 index 000000000..0397f64e1 --- /dev/null +++ b/internal/envreport/envreport.go @@ -0,0 +1,64 @@ +// Package envreport holds the version 1 environment report a snapshot +// command sends with --generic: workloads, their components and instances. +package envreport + +// Report is one version 1 report: claims about workloads, complete for its scope. +type Report struct { + SchemaVersion string `json:"schema_version"` + Scope Scope `json:"scope"` + Claims []Claim `json:"claims"` +} + +// Scope is what a report is complete for; a workload inside it that the +// report does not claim is gone. +type Scope struct { + All bool `json:"all"` +} + +// Claim is one thing a report tells Kosli: that a workload was observed. +type Claim struct { + Type string `json:"type"` + Workload Workload `json:"workload"` +} + +// FullReport is the report that workloads are everything the snapshot +// command looked at, as each run of a snapshot command reports. +func FullReport(workloads []Workload) Report { + claims := []Claim{} + for _, workload := range workloads { + claims = append(claims, Claim{Type: "workload.observed", Workload: workload}) + } + return Report{SchemaVersion: "1", Scope: Scope{All: true}, Claims: claims} +} + +// Workload is what a person deploys and recognises, never a pod or a task. +type Workload struct { + ID string `json:"id,omitempty"` + Name string `json:"name,omitempty"` + Kind string `json:"kind,omitempty"` + Metadata map[string]any `json:"metadata,omitempty"` + Components []Component `json:"components"` + Instances []Instance `json:"instances"` +} + +// Component is a named slot in a workload, running one artifact. +type Component struct { + Name string `json:"name"` + Artifact Artifact `json:"artifact"` +} + +// Artifact is what a component runs, identified by its fingerprint, or +// unidentified, with a nil fingerprint and the reason why. +type Artifact struct { + Name string `json:"name"` + Fingerprint *string `json:"fingerprint"` + Unidentified string `json:"unidentified,omitempty"` +} + +// Instance is one copy of a whole workload. Components is set only when the +// copy runs other artifacts than its workload, as during a rollout. +type Instance struct { + ID string `json:"id,omitempty"` + StartedAt string `json:"started_at,omitempty"` + Components *[]Component `json:"components,omitempty"` +} diff --git a/internal/envreport/envreport_test.go b/internal/envreport/envreport_test.go new file mode 100644 index 000000000..2baccd8a2 --- /dev/null +++ b/internal/envreport/envreport_test.go @@ -0,0 +1,26 @@ +package envreport + +import ( + "encoding/json" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestFullReport(t *testing.T) { + t.Run("a full report claims each workload observed, complete for the whole source", func(t *testing.T) { + billing := Workload{Name: "billing", Components: []Component{}, Instances: []Instance{}} + + actual, err := json.Marshal(FullReport([]Workload{billing})) + + require.NoError(t, err) + require.JSONEq(t, `{ + "schema_version": "1", + "scope": {"all": true}, + "claims": [{ + "type": "workload.observed", + "workload": {"name": "billing", "components": [], "instances": []} + }] + }`, string(actual)) + }) +}