-
Notifications
You must be signed in to change notification settings - Fork 6
Added initial implementation of kosli snapshot cloud-run server/#4986 #833
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
Open
ToreMerkely
wants to merge
11
commits into
main
Choose a base branch
from
4986-google-cloud-run-1
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
e63822c
feat(snapshot): add hidden cloud-run skeleton command (#4986)
ToreMerkely d98c40c
feat(cloudrun): add internal/cloudrun package wrapping the Cloud Run …
ToreMerkely 1c08187
feat(snapshot): wire cloud-run command end-to-end via internal/cloudr…
ToreMerkely 2542614
feat(snapshot): add service filtering flags to cloud-run command (#4986)
ToreMerkely 176df4e
feat(cloudrun): friendly auth and not-found error messages (#4986)
ToreMerkely fa367b3
fix(cloudrun): align snapshot payload with server's snapshot-examples…
ToreMerkely cdb2429
chore(cloudrun): use service_name (snake_case) and number test cases …
ToreMerkely 88c8202
fix(cloudrun): close gRPC clients and clarify slice filtering (#4986)
ToreMerkely 9d40f4a
Merge branch 'main' of github.com:kosli-dev/cli into 4986-google-clou…
ToreMerkely eb064b2
feat(snapshot): integrate cloud-run with the Kosli server (#4986)
ToreMerkely 41808e6
Merge branch 'main' of github.com:kosli-dev/cli into 4986-google-clou…
ToreMerkely 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
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,125 @@ | ||
| package main | ||
|
|
||
| import ( | ||
| "context" | ||
| "io" | ||
| "net/http" | ||
| "net/url" | ||
|
|
||
| "github.com/kosli-dev/cli/internal/cloudrun" | ||
| "github.com/kosli-dev/cli/internal/filters" | ||
| "github.com/kosli-dev/cli/internal/requests" | ||
| "github.com/spf13/cobra" | ||
| ) | ||
|
|
||
| const snapshotCloudRunShortDesc = `Report a snapshot of running services in a Google Cloud Run project and region to Kosli. ` | ||
| const snapshotCloudRunLongDesc = snapshotCloudRunShortDesc + ` | ||
| Currently a hidden, in-development command. Use --dry-run to inspect the payload without sending it to Kosli.` | ||
|
|
||
| // cloudRunLister is the seam between the command and the GCP client. Tests | ||
| // override newCloudRunClient with a stub that returns canned services. | ||
| type cloudRunLister interface { | ||
| ListServices(ctx context.Context, project, region string) ([]cloudrun.Service, error) | ||
| } | ||
|
|
||
| var newCloudRunClient = func(ctx context.Context) (cloudRunLister, error) { | ||
| return cloudrun.New(ctx) | ||
| } | ||
|
|
||
| type snapshotCloudRunOptions struct { | ||
| project string | ||
| region string | ||
| serviceFilter *filters.ResourceFilterOptions | ||
| } | ||
|
|
||
| func newSnapshotCloudRunCmd(out io.Writer) *cobra.Command { | ||
| o := new(snapshotCloudRunOptions) | ||
| o.serviceFilter = new(filters.ResourceFilterOptions) | ||
| cmd := &cobra.Command{ | ||
| Use: "cloud-run ENVIRONMENT-NAME", | ||
| Short: snapshotCloudRunShortDesc, | ||
| Long: snapshotCloudRunLongDesc, | ||
| Hidden: true, | ||
| Args: cobra.ExactArgs(1), | ||
| PreRunE: func(cmd *cobra.Command, args []string) error { | ||
| if err := RequireGlobalFlags(global, []string{"Org", "ApiToken"}); err != nil { | ||
| return ErrorBeforePrintingUsage(cmd, err.Error()) | ||
| } | ||
| for _, pair := range [][]string{ | ||
| {"services", "exclude"}, | ||
| {"services", "exclude-regex"}, | ||
| {"services-regex", "exclude"}, | ||
| {"services-regex", "exclude-regex"}, | ||
| } { | ||
| if err := MuXRequiredFlags(cmd, pair, false); err != nil { | ||
| return err | ||
| } | ||
| } | ||
| return nil | ||
| }, | ||
| RunE: func(cmd *cobra.Command, args []string) error { | ||
| return o.run(args) | ||
| }, | ||
| } | ||
|
|
||
| cmd.Flags().StringVar(&o.project, "project", "", "[required] GCP project ID.") | ||
| cmd.Flags().StringVar(&o.region, "region", "", "[required] GCP region (e.g. europe-west1).") | ||
| cmd.Flags().StringSliceVar(&o.serviceFilter.IncludeNames, "services", []string{}, cloudRunServicesFlag) | ||
| cmd.Flags().StringSliceVar(&o.serviceFilter.IncludeNamesRegex, "services-regex", []string{}, cloudRunServicesRegexFlag) | ||
| cmd.Flags().StringSliceVar(&o.serviceFilter.ExcludeNames, "exclude", []string{}, cloudRunExcludeFlag) | ||
| cmd.Flags().StringSliceVar(&o.serviceFilter.ExcludeNamesRegex, "exclude-regex", []string{}, cloudRunExcludeRegexFlag) | ||
| addDryRunFlag(cmd) | ||
|
|
||
| if err := RequireFlags(cmd, []string{"project", "region"}); err != nil { | ||
| logger.Error("failed to configure required flags: %v", err) | ||
| } | ||
|
|
||
| return cmd | ||
| } | ||
|
|
||
| func (o *snapshotCloudRunOptions) run(args []string) error { | ||
| envName := args[0] | ||
| reportURL, err := url.JoinPath(global.Host, "api/v2/environments", global.Org, envName, "report/cloud-run") | ||
| if err != nil { | ||
| return err | ||
| } | ||
|
|
||
| ctx := context.Background() | ||
| client, err := newCloudRunClient(ctx) | ||
| if err != nil { | ||
| return err | ||
| } | ||
| if closer, ok := client.(io.Closer); ok { | ||
| defer func() { _ = closer.Close() }() | ||
| } | ||
| services, err := client.ListServices(ctx, o.project, o.region) | ||
| if err != nil { | ||
| return cloudrun.Classify(err, o.project, o.region) | ||
| } | ||
|
ToreMerkely marked this conversation as resolved.
|
||
|
|
||
| filtered := make([]cloudrun.Service, 0, len(services)) | ||
| for _, svc := range services { | ||
| include, err := o.serviceFilter.ShouldInclude(svc.Name) | ||
| if err != nil { | ||
| return err | ||
| } | ||
| if include { | ||
| filtered = append(filtered, svc) | ||
| } | ||
| } | ||
|
|
||
| payload := cloudrun.ToEnvRequest(filtered) | ||
|
|
||
| reqParams := &requests.RequestParams{ | ||
| Method: http.MethodPut, | ||
| URL: reportURL, | ||
| Payload: payload, | ||
| DryRun: global.DryRun, | ||
| Token: global.ApiToken, | ||
| } | ||
| _, err = kosliClient.Do(reqParams) | ||
| if err == nil && !global.DryRun { | ||
| logger.Info("[%d] revisions were reported to environment %s", len(payload.Artifacts), envName) | ||
| } | ||
| 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,213 @@ | ||
| package main | ||
|
|
||
| import ( | ||
| "context" | ||
| "fmt" | ||
| "testing" | ||
| "time" | ||
|
|
||
| "github.com/kosli-dev/cli/internal/cloudrun" | ||
| "github.com/stretchr/testify/require" | ||
| "github.com/stretchr/testify/suite" | ||
| "google.golang.org/grpc/codes" | ||
| "google.golang.org/grpc/status" | ||
| ) | ||
|
|
||
| type stubCloudRunLister struct { | ||
| services []cloudrun.Service | ||
| err error | ||
| } | ||
|
|
||
| func (s stubCloudRunLister) ListServices(_ context.Context, _, _ string) ([]cloudrun.Service, error) { | ||
| return s.services, s.err | ||
| } | ||
|
|
||
| var origNewCloudRunClient = newCloudRunClient | ||
|
|
||
| type SnapshotCloudRunTestSuite struct { | ||
| suite.Suite | ||
| defaultKosliArguments string | ||
| envName string | ||
| } | ||
|
|
||
| // stubServices returns two Cloud Run services so filter tests can verify | ||
| // inclusion and exclusion in a single run. Digests are full 64-char hex | ||
| // because the server's CloudRunReport model rejects anything else. | ||
| func stubServices() []cloudrun.Service { | ||
| const ( | ||
| alphaDigest = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" | ||
| betaDigest = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" | ||
| ) | ||
| return []cloudrun.Service{ | ||
| { | ||
| Name: "alpha", | ||
| URI: "https://alpha.run.app", | ||
| Revisions: []cloudrun.Revision{ | ||
| { | ||
| Name: "alpha-rev1", | ||
| Digests: map[string]string{"gcr.io/x/alpha@sha256:" + alphaDigest: alphaDigest}, | ||
| CreatedAt: time.Date(2026, 4, 28, 12, 0, 0, 0, time.UTC), | ||
| }, | ||
| }, | ||
| }, | ||
| { | ||
| Name: "beta", | ||
| URI: "https://beta.run.app", | ||
| Revisions: []cloudrun.Revision{ | ||
| { | ||
| Name: "beta-rev1", | ||
| Digests: map[string]string{"gcr.io/x/beta@sha256:" + betaDigest: betaDigest}, | ||
| CreatedAt: time.Date(2026, 4, 28, 12, 0, 0, 0, time.UTC), | ||
| }, | ||
| }, | ||
| }, | ||
| } | ||
| } | ||
|
|
||
| func (suite *SnapshotCloudRunTestSuite) SetupTest() { | ||
| suite.envName = "snapshot-cloud-run-env" | ||
| global = &GlobalOpts{ | ||
| ApiToken: "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6ImNkNzg4OTg5In0.e8i_lA_QrEhFncb05Xw6E_tkCHU9QfcY4OLTVUCHffY", | ||
| Org: "docs-cmd-test-user", | ||
| Host: "http://localhost:8001", | ||
| } | ||
| suite.defaultKosliArguments = fmt.Sprintf(" --host %s --org %s --api-token %s", global.Host, global.Org, global.ApiToken) | ||
|
|
||
| newCloudRunClient = func(_ context.Context) (cloudRunLister, error) { | ||
| return stubCloudRunLister{services: stubServices()}, nil | ||
| } | ||
|
|
||
| CreateEnv(global.Org, suite.envName, "cloud-run", suite.T()) | ||
| } | ||
|
|
||
| func (suite *SnapshotCloudRunTestSuite) TearDownTest() { | ||
| newCloudRunClient = origNewCloudRunClient | ||
| } | ||
|
|
||
| func (suite *SnapshotCloudRunTestSuite) TestSnapshotCloudRunCmd() { | ||
| tests := []cmdTestCase{ | ||
| { | ||
| wantError: true, | ||
| name: "01 snapshot cloud-run fails if no args are provided", | ||
| cmd: fmt.Sprintf(`snapshot cloud-run --project p --region r %s`, suite.defaultKosliArguments), | ||
| golden: "Error: accepts 1 arg(s), received 0\n", | ||
| }, | ||
| { | ||
| wantError: true, | ||
| name: "02 snapshot cloud-run fails if 2 args are provided", | ||
| cmd: fmt.Sprintf(`snapshot cloud-run %s xxx --project p --region r %s`, suite.envName, suite.defaultKosliArguments), | ||
| golden: "Error: accepts 1 arg(s), received 2\n", | ||
| }, | ||
| { | ||
| wantError: true, | ||
| name: "03 snapshot cloud-run fails if --project is missing", | ||
| cmd: fmt.Sprintf(`snapshot cloud-run %s --region r %s`, suite.envName, suite.defaultKosliArguments), | ||
| golden: "Error: required flag(s) \"project\" not set\n", | ||
| }, | ||
| { | ||
| wantError: true, | ||
| name: "04 snapshot cloud-run fails if --region is missing", | ||
| cmd: fmt.Sprintf(`snapshot cloud-run %s --project p %s`, suite.envName, suite.defaultKosliArguments), | ||
| golden: "Error: required flag(s) \"region\" not set\n", | ||
| }, | ||
| { | ||
| name: "05 snapshot cloud-run dry-runs the report URL and payload built from the GCP client", | ||
| cmd: fmt.Sprintf(`snapshot cloud-run %s --project proj-x --region europe-west1 --dry-run %s`, suite.envName, suite.defaultKosliArguments), | ||
| goldenRegex: `(?s)THIS IS A DRY-RUN.*report/cloud-run.*"type": "cloud-run".*"service_name": "alpha".*"service_name": "beta"`, | ||
| }, | ||
| { | ||
| wantError: true, | ||
| name: "06 snapshot cloud-run fails if --services and --exclude are set", | ||
| cmd: fmt.Sprintf(`snapshot cloud-run %s --project p --region r --services alpha --exclude beta %s`, suite.envName, suite.defaultKosliArguments), | ||
| golden: "Error: only one of --services, --exclude is allowed\n", | ||
| }, | ||
| { | ||
| wantError: true, | ||
| name: "07 snapshot cloud-run fails if --services and --exclude-regex are set", | ||
| cmd: fmt.Sprintf(`snapshot cloud-run %s --project p --region r --services alpha --exclude-regex "^b" %s`, suite.envName, suite.defaultKosliArguments), | ||
| golden: "Error: only one of --services, --exclude-regex is allowed\n", | ||
| }, | ||
| { | ||
| wantError: true, | ||
| name: "08 snapshot cloud-run fails if --services-regex and --exclude are set", | ||
| cmd: fmt.Sprintf(`snapshot cloud-run %s --project p --region r --services-regex "^a" --exclude beta %s`, suite.envName, suite.defaultKosliArguments), | ||
| golden: "Error: only one of --services-regex, --exclude is allowed\n", | ||
| }, | ||
| { | ||
| wantError: true, | ||
| name: "09 snapshot cloud-run fails if --services-regex and --exclude-regex are set", | ||
| cmd: fmt.Sprintf(`snapshot cloud-run %s --project p --region r --services-regex "^a" --exclude-regex "^b" %s`, suite.envName, suite.defaultKosliArguments), | ||
| golden: "Error: only one of --services-regex, --exclude-regex is allowed\n", | ||
| }, | ||
| } | ||
|
|
||
| runTestCmd(suite.T(), tests) | ||
| } | ||
|
|
||
| // runFilteredCmd executes the command and returns the combined output for | ||
| // substring assertions. Filter tests need to assert both presence (kept | ||
| // service appears) and absence (excluded service does not appear), so they | ||
| // cannot use the single-assertion cmdTestCase table. | ||
| func (suite *SnapshotCloudRunTestSuite) runFilteredCmd(filterArgs string) string { | ||
| cmd := fmt.Sprintf(`snapshot cloud-run %s --project p --region r --dry-run %s %s`, suite.envName, filterArgs, suite.defaultKosliArguments) | ||
| _, combined, _, _, err := executeCommandC(cmd) | ||
| require.NoError(suite.T(), err, "command failed: %s", combined) | ||
| return combined | ||
| } | ||
|
|
||
| func (suite *SnapshotCloudRunTestSuite) TestSnapshotCloudRunFilter_Services() { | ||
| out := suite.runFilteredCmd("--services alpha") | ||
| require.Contains(suite.T(), out, `"service_name": "alpha"`) | ||
| require.NotContains(suite.T(), out, `"service_name": "beta"`) | ||
| } | ||
|
|
||
| func (suite *SnapshotCloudRunTestSuite) TestSnapshotCloudRunFilter_ServicesRegex() { | ||
| out := suite.runFilteredCmd(`--services-regex "^al"`) | ||
| require.Contains(suite.T(), out, `"service_name": "alpha"`) | ||
| require.NotContains(suite.T(), out, `"service_name": "beta"`) | ||
| } | ||
|
|
||
| func (suite *SnapshotCloudRunTestSuite) TestSnapshotCloudRunFilter_Exclude() { | ||
| out := suite.runFilteredCmd("--exclude alpha") | ||
| require.NotContains(suite.T(), out, `"service_name": "alpha"`) | ||
| require.Contains(suite.T(), out, `"service_name": "beta"`) | ||
| } | ||
|
|
||
| func (suite *SnapshotCloudRunTestSuite) TestSnapshotCloudRunFilter_ExcludeRegex() { | ||
| out := suite.runFilteredCmd(`--exclude-regex "^al"`) | ||
| require.NotContains(suite.T(), out, `"service_name": "alpha"`) | ||
| require.Contains(suite.T(), out, `"service_name": "beta"`) | ||
| } | ||
|
|
||
| // TestSnapshotCloudRunCmd_HappyPathReportsToServer exercises the full | ||
| // CLI → local Kosli server roundtrip with the GCP client stubbed: the env is | ||
| // already created in SetupTest with type "cloud-run", and the command is | ||
| // expected to PUT the snapshot and emit the "[N] revisions were reported" | ||
| // success log mirroring ECS. | ||
| func (suite *SnapshotCloudRunTestSuite) TestSnapshotCloudRunCmd_HappyPathReportsToServer() { | ||
| cmd := fmt.Sprintf(`snapshot cloud-run %s --project p --region r %s`, suite.envName, suite.defaultKosliArguments) | ||
| _, combined, _, _, err := executeCommandC(cmd) | ||
|
|
||
| require.NoError(suite.T(), err, "command failed: %s", combined) | ||
| require.Contains(suite.T(), combined, fmt.Sprintf("[2] revisions were reported to environment %s", suite.envName)) | ||
| } | ||
|
|
||
| // TestSnapshotCloudRunCmd_UnauthenticatedReturnsFriendlyError verifies that a | ||
| // gRPC Unauthenticated error from GCP surfaces as the actionable ADC message | ||
| // rather than a raw SDK string. | ||
| func (suite *SnapshotCloudRunTestSuite) TestSnapshotCloudRunCmd_UnauthenticatedReturnsFriendlyError() { | ||
| newCloudRunClient = func(_ context.Context) (cloudRunLister, error) { | ||
| return stubCloudRunLister{err: status.Error(codes.Unauthenticated, "token expired")}, nil | ||
| } | ||
|
|
||
| cmd := fmt.Sprintf(`snapshot cloud-run %s --project p --region r %s`, suite.envName, suite.defaultKosliArguments) | ||
| _, combined, _, _, err := executeCommandC(cmd) | ||
|
|
||
| require.Error(suite.T(), err) | ||
| require.Contains(suite.T(), combined, "GCP authentication failed") | ||
| require.Contains(suite.T(), combined, "metadata server") | ||
| } | ||
|
|
||
| func TestSnapshotCloudRunCommandTestSuite(t *testing.T) { | ||
| suite.Run(t, new(SnapshotCloudRunTestSuite)) | ||
| } |
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.