Skip to content

karmadactl: set default 5s timeout for resource completion#7315

Open
manmathbh wants to merge 3 commits intokarmada-io:masterfrom
manmathbh:fix/completion-request-timeout
Open

karmadactl: set default 5s timeout for resource completion#7315
manmathbh wants to merge 3 commits intokarmada-io:masterfrom
manmathbh:fix/completion-request-timeout

Conversation

@manmathbh
Copy link
Copy Markdown
Contributor

@manmathbh manmathbh commented Mar 22, 2026

What type of PR is this?

/kind bug

What this PR does / why we need it:

This PR sets a default 5s timeout for resource discovery used by karmadactl shell completion, so completion requests do not block indefinitely when API discovery is slow or unreachable.

Implementation details:

  • Wraps the provided RESTClientGetter with timeoutRESTClientGetter.
  • In ToRESTConfig(), applies cfg.Timeout = 5s for completion requests.
  • Uses the wrapped getter in compGetResourceList(...) before calling apiresources discovery.

This avoids relying on *genericclioptions.ConfigFlags type assertions and ensures timeout behavior is applied consistently through the REST config path used by completion.

Which issue(s) this PR fixes:

Fixes #

Special notes for your reviewer:

- Scope is limited to completion-time resource list discovery.

- Added/updated unit tests in completion_test.go to cover:
- timeout applied to rest config by wrapper
- error propagation path
-
- Verification run locally:
- go test ./pkg/karmadactl/util/completion -count=1
- bash hack/verify-staticcheck.sh

Does this PR introduce a user-facing change?:

NONE

Copilot AI review requested due to automatic review settings March 22, 2026 18:00
@karmada-bot
Copy link
Copy Markdown
Contributor

Welcome @manmathbh! It looks like this is your first PR to karmada-io/karmada 🎉

@gemini-code-assist
Copy link
Copy Markdown

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request enhances the reliability and user experience of karmadactl commands by implementing a default 5-second timeout for resource completion. This change ensures that operations do not wait indefinitely, providing clearer feedback and preventing potential command stalls.

Highlights

  • Default Timeout for Resource Completion: A default 5-second timeout has been introduced for resource completion operations within karmadactl to prevent commands from hanging indefinitely.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@karmada-bot karmada-bot added the size/XS Denotes a PR that changes 0-9 lines, ignoring generated files. label Mar 22, 2026
Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

This PR aims to prevent karmadactl shell completion (resource discovery via apiresources) from hanging by applying a default 5s timeout when listing resources.

Changes:

  • Adds logic in compGetResourceList to default the REST client timeout to 5s when none is set.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +259 to +263
if configFlags, ok := restClientGetter.(*genericclioptions.ConfigFlags); ok {
if configFlags.Timeout == nil || len(*configFlags.Timeout) == 0 {
configFlags.Timeout = ptr.To("5s")
}
}
Copy link

Copilot AI Mar 22, 2026

Choose a reason for hiding this comment

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

restClientGetter is typically a util.Factory/cmdutil.Factory here (see callers passing f), so the type assertion to *genericclioptions.ConfigFlags will fail and the default timeout will never be applied. Consider wrapping the provided genericclioptions.RESTClientGetter with a small delegating implementation that overrides ToRESTConfig() to set rest.Config.Timeout to 5s when it is zero (or otherwise ensure you can access/mutate the underlying ConfigFlags used by the factory).

Copilot uses AI. Check for mistakes.
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Agree, how about:

	config, err := restClientGetter.ToRawKubeConfigLoader().ClientConfig()
	if err != nil {
		return nil
	}
	config.Timeout = 5 * time.Second

Copy link
Copy Markdown

@gemini-code-assist gemini-code-assist Bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request introduces a default 5-second timeout for resource completion lookups to prevent them from hanging. The implementation modifies the ConfigFlags to set the timeout. My review includes a suggestion to avoid side effects by restoring the original timeout value after the operation, improving the code's robustness.

// TODO: Should set --request-timeout=5s
if configFlags, ok := restClientGetter.(*genericclioptions.ConfigFlags); ok {
if configFlags.Timeout == nil || len(*configFlags.Timeout) == 0 {
configFlags.Timeout = ptr.To("5s")
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

While this change correctly sets a default timeout, it modifies the configFlags object in place. This creates a side effect that could potentially affect other parts of the code using the same restClientGetter instance within the same process execution. To avoid this, it's better to restore the original timeout value before the function returns. You can achieve this by using a defer statement.

            originalTimeout := configFlags.Timeout
            configFlags.Timeout = ptr.To("5s")
            defer func() { configFlags.Timeout = originalTimeout }()

Signed-off-by: manmathbh <manmathcode@gmail.com>
@manmathbh manmathbh force-pushed the fix/completion-request-timeout branch from 9444460 to 379e04e Compare March 22, 2026 18:06
@codecov-commenter
Copy link
Copy Markdown

codecov-commenter commented Mar 22, 2026

⚠️ Please install the 'codecov app svg image' to ensure uploads and comments are reliably processed by Codecov.

Codecov Report

❌ Patch coverage is 57.14286% with 3 lines in your changes missing coverage. Please review.
✅ Project coverage is 42.16%. Comparing base (3424bc7) to head (503eba6).
⚠️ Report is 104 commits behind head on master.

Files with missing lines Patch % Lines
pkg/karmadactl/util/completion/completion.go 57.14% 2 Missing and 1 partial ⚠️
❗ Your organization needs to install the Codecov GitHub app to enable full functionality.
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #7315      +/-   ##
==========================================
+ Coverage   42.03%   42.16%   +0.12%     
==========================================
  Files         874      875       +1     
  Lines       53551    53610      +59     
==========================================
+ Hits        22511    22603      +92     
+ Misses      29349    29307      -42     
- Partials     1691     1700       +9     
Flag Coverage Δ
unittests 42.16% <57.14%> (+0.12%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@XiShanYongYe-Chang
Copy link
Copy Markdown
Member

/cc @zhzhuang-zju

@zhzhuang-zju
Copy link
Copy Markdown
Contributor

Thanks
/assign

Copy link
Copy Markdown
Contributor

@zhzhuang-zju zhzhuang-zju left a comment

Choose a reason for hiding this comment

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

Others LGTM

Comment on lines +259 to +263
if configFlags, ok := restClientGetter.(*genericclioptions.ConfigFlags); ok {
if configFlags.Timeout == nil || len(*configFlags.Timeout) == 0 {
configFlags.Timeout = ptr.To("5s")
}
}
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Agree, how about:

	config, err := restClientGetter.ToRawKubeConfigLoader().ClientConfig()
	if err != nil {
		return nil
	}
	config.Timeout = 5 * time.Second

Signed-off-by: manmathbh <manmathcode@gmail.com>
@karmada-bot
Copy link
Copy Markdown
Contributor

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by:
Once this PR has been reviewed and has the lgtm label, please ask for approval from zhzhuang-zju. For more information see the Code Review Process.

The full list of commands accepted by this bot can be found here.

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

@karmada-bot karmada-bot added size/L Denotes a PR that changes 100-499 lines, ignoring generated files. and removed size/XS Denotes a PR that changes 0-9 lines, ignoring generated files. labels Apr 14, 2026
@manmathbh
Copy link
Copy Markdown
Contributor Author

Hi @zhzhuang-zju, thanks for the suggestion.
I updated the implementation to enforce a default 5s timeout through the REST client getter path used by completion discovery, so it applies reliably without relying on ConfigFlags type assertion.
I also added unit tests for default timeout, preserving existing timeout, and error propagation. PTAL.

Copy link
Copy Markdown
Contributor

@zhzhuang-zju zhzhuang-zju left a comment

Choose a reason for hiding this comment

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

@manmathbh Thanks, others LGTM

Comment on lines +58 to +60
if cfg.Timeout == 0 {
cfg.Timeout = g.timeout
}
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Suggested change
if cfg.Timeout == 0 {
cfg.Timeout = g.timeout
}
cfg.Timeout = g.timeout

I think if the caller creates a timeoutRESTClientGetter rather than a genericclioptions.RESTClientGetter, the purpose is to use the timeout defined by the timeoutRESTClientGette.timeout

@@ -0,0 +1,89 @@
/*
Copyright 2024 The Karmada Authors.
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Suggested change
Copyright 2024 The Karmada Authors.
Copyright 2026 The Karmada Authors.

How time flies!

"k8s.io/client-go/tools/clientcmd"
)

type fakeRESTClientGetter struct {
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

// TestFactory extends cmdutil.Factory
type TestFactory struct {
*cmdtesting.TestFactory
}

We can directly use the existing TestFactory object

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

@manmathbh Could you explain why you are not using TestFactory and instead creating a new fake object fakeRESTClientGetter?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Hi @zhzhuang-zju my apologies! I completely missed that part of your feedback in my last push and accidentally left the fake in there.

I just force-pushed an update that completely removes fakeRESTClientGetter and properly utilizes TestFactory from util/testing. Thanks for catching my oversight!

Comment on lines +54 to +89
func TestTimeoutRESTClientGetterToRESTConfigSetsDefaultTimeout(t *testing.T) {
base := &fakeRESTClientGetter{cfg: &rest.Config{}}
getter := &timeoutRESTClientGetter{RESTClientGetter: base, timeout: 5 * time.Second}

cfg, err := getter.ToRESTConfig()
if err != nil {
t.Fatalf("ToRESTConfig() unexpected error: %v", err)
}
if cfg.Timeout != 5*time.Second {
t.Fatalf("expected timeout %v, got %v", 5*time.Second, cfg.Timeout)
}
}

func TestTimeoutRESTClientGetterToRESTConfigPreservesExistingTimeout(t *testing.T) {
base := &fakeRESTClientGetter{cfg: &rest.Config{Timeout: 2 * time.Second}}
getter := &timeoutRESTClientGetter{RESTClientGetter: base, timeout: 5 * time.Second}

cfg, err := getter.ToRESTConfig()
if err != nil {
t.Fatalf("ToRESTConfig() unexpected error: %v", err)
}
if cfg.Timeout != 2*time.Second {
t.Fatalf("expected existing timeout %v to be preserved, got %v", 2*time.Second, cfg.Timeout)
}
}

func TestTimeoutRESTClientGetterToRESTConfigPropagatesError(t *testing.T) {
expectedErr := errors.New("boom")
base := &fakeRESTClientGetter{err: expectedErr}
getter := &timeoutRESTClientGetter{RESTClientGetter: base, timeout: 5 * time.Second}

_, err := getter.ToRESTConfig()
if !errors.Is(err, expectedErr) {
t.Fatalf("expected error %v, got %v", expectedErr, err)
}
}
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Unit tests are generally written at the function level. These three unit tests essentially test the ToRESTConfig() function so that we can consolidate them into a single unit test.

@manmathbh
Copy link
Copy Markdown
Contributor Author

Hi @zhzhuang-zju, thanks for the suggestions.

Updated accordingly:

  • timeoutRESTClientGetter.ToRESTConfig() now always applies cfg.Timeout = g.timeout.
  • Consolidated the 3 timeout wrapper unit tests into one function-level table-driven test.
  • Updated the new test file copyright year to 2026.

Verification:

  • go test ./pkg/karmadactl/util/completion -count=1
  • bash hack/verify-staticcheck.sh

PTAL.

Signed-off-by: manmathbh <manmathcode@gmail.com>
@manmathbh manmathbh force-pushed the fix/completion-request-timeout branch from c0054eb to 503eba6 Compare April 15, 2026 03:46
@karmada-bot karmada-bot added size/M Denotes a PR that changes 30-99 lines, ignoring generated files. and removed size/L Denotes a PR that changes 100-499 lines, ignoring generated files. labels Apr 15, 2026
@zhzhuang-zju
Copy link
Copy Markdown
Contributor

@manmathbh Thanks, generally LGTM. Can you squash the commits into one?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size/M Denotes a PR that changes 30-99 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants