Repository navigation
feat(snapshot ecs): add a hidden --generic flag #1433
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
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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 | ||
| }) | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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) | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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 | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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 | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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{ | ||
|
JonJagger marked this conversation as resolved.
Resolved
|
||
| 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 == "" { | ||
|
JonJagger marked this conversation as resolved.
Resolved
|
||
| 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, "" | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.