Skip to content
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

fix: remove context from wsl connection struct #1663

Merged
merged 6 commits into from
Jan 2, 2025
Merged

Conversation

oneirocosm
Copy link
Member

This fixes a WSL bug where disconnecting the controller does not allow the controller to restart until the app reboots.

This fixes a bug where disconnecting the controller does not allow the
controller to restart until the app reboots.
Copy link
Contributor

coderabbitai bot commented Jan 1, 2025

Warning

Rate limit exceeded

@oneirocosm has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 1 minutes and 36 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 01bcd39 and edf2ae6.

📒 Files selected for processing (1)
  • pkg/wsl/wsl.go (5 hunks)

Walkthrough

The pull request introduces modifications to context management in the pkg/shellexec/shellexec.go and pkg/wsl/wsl.go files. The primary changes involve the introduction of a new context variable utilCtx in the StartWslShellProc function, which replaces the previous usage of conn.Context for several operations, including wsl.DetectShell, wsl.InstallClientRcFiles, and wsl.GetHomeDir. Additionally, the WslConn struct has had its Context field removed, leading to the StartConnServer method creating a new context using context.WithTimeout. This new context is used for various operations, ensuring that context is managed locally within methods rather than globally. These changes streamline context handling and enhance the lifecycle management of shell processes and connections.


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (2)
pkg/wsl/wsl.go (1)

190-196: Ensure proper context cancellation.

This block properly creates and assigns a new cancelFn while also ensuring any previous cancelFn is canceled first. However, consider wrapping the function body in a single lock acquisition to reduce the overhead of repeated conn.WithLock calls.

190     ctx, cancelFn := context.WithCancel(context.Background())
      conn.WithLock(func() {
-       if conn.cancelFn != nil {
-         conn.cancelFn()
-       }
-       conn.cancelFn = cancelFn
+       if conn.cancelFn != nil { conn.cancelFn() }
+       conn.cancelFn = cancelFn
      })
pkg/shellexec/shellexec.go (1)

156-156: Graceful error handling.

Verifying that DetectShell handles potential errors (e.g., no shell detected) is vital. The returned error is correctly propagated, but consider adding logs for debugging or user-friendly messages.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 035e0b9 and 83dbbf6.

📒 Files selected for processing (2)
  • pkg/shellexec/shellexec.go (2 hunks)
  • pkg/wsl/wsl.go (5 hunks)
🔇 Additional comments (5)
pkg/wsl/wsl.go (3)

230-230: Validate concurrency around ConnController.

By assigning cmd := client.WslCommand(ctx, cmdStr) under this local context, you ensure that the command respects cancellations. Make sure references to cmd in other goroutines (e.g., the goroutine handling I/O) do not introduce race conditions.


482-482: Confirm initialization of new connection fields.

Initializing cancelFn to nil here is valid, but ensure other WslConn methods can handle a nil cancelFn gracefully.


Line range hint 209-219: Validate usage of context in downstream function calls.

GetWshPath and DetectShell rely on the passed context. Ensure they handle cancellation gracefully to prevent leaks and guarantee quick termination of any blocking I/O operations if cancellation is triggered.

Run the following script to confirm that GetWshPath and DetectShell have proper cancellation checks:

✅ Verification successful

Based on the code analysis, I can now provide a final response:

Context handling in GetWshPath and DetectShell is properly implemented

Both functions properly propagate the context through their command execution chains:

  1. GetWshPath uses the context in WslCommand calls to execute which wsh and where.exe wsh
  2. DetectShell uses the context in both GetWshPath and subsequent WslCommand call
  3. The underlying WslCommand implementation in wsl-win.go has proper context validation:
    • Panics on nil context
    • Propagates context to inner command execution
    • Uses sync.WaitGroup for proper cleanup

The context is properly passed through the entire chain of command execution, ensuring that cancellation signals will be propagated to any running processes.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Recursively search for context usage in GetWshPath and DetectShell

ast-grep --pattern $'function GetWshPath($_, $_) {\n  $$$\n}' 
ast-grep --pattern $'function DetectShell($_, $_) {\n  $$$\n}'

Length of output: 122


Script:

#!/bin/bash
# Search for GetWshPath and DetectShell function definitions using ripgrep
echo "=== Searching for GetWshPath ==="
rg "func GetWshPath" -A 10

echo -e "\n=== Searching for DetectShell ==="
rg "func DetectShell" -A 10

Length of output: 2557


Script:

#!/bin/bash
# Search for WslCommand implementation to check context handling
echo "=== Searching for WslCommand method ==="
rg "func.*WslCommand" -A 10

# Search for any context cancellation patterns in the same files
echo -e "\n=== Checking context usage patterns ==="
rg "ctx\." pkg/wsl/wsl-util.go

Length of output: 1214


Script:

#!/bin/bash
# Search for Command implementation and context usage
echo "=== Searching for Command method ==="
rg "func.*Command.*Context" -A 10

# Search for exec.Command usage to see how commands are created
echo -e "\n=== Checking exec.Command usage ==="
rg "exec\.Command" pkg/wsl/

Length of output: 47433

pkg/shellexec/shellexec.go (2)

165-165: Ensure idempotent installation.

InstallClientRcFiles might partially install or update RC files. Ensure the function can gracefully handle repeated calls without corrupting the installation or leaving incomplete states if interrupted.


171-171: Context usage is consistent.

Using shellProcCtx here for GetHomeDir is consistent with the new local context approach. Confirm you don’t need the home directory beyond this method’s scope once canceled.

Comment on lines 151 to 152
shellProcCtx, cancelFn := context.WithCancel(ctx)
defer cancelFn()
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Consider controlling the lifetime beyond the function scope.

Creating a new context with its own cancel function and immediately deferring its cancellation will cancel the shell context as soon as this function returns, which limits the lifetime of the shell. If you intend for the shell to remain active after returning, remove or modify the defer cancelFn().

- shellProcCtx, cancelFn := context.WithCancel(ctx)
- defer cancelFn()
+ shellProcCtx, cancelFn := context.WithCancel(ctx)
// Possibly remove defer or invoke cancelFn() at a different time

Committable suggestion skipped: line range outside the PR's diff.

@sawka
Copy link
Member

sawka commented Jan 2, 2025

might be able to add an actual timeout to some of these... not the connserver, but for the other utilities -- like shell detection or wsh path, etc. they could just have like a 5s timeout.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (2)
pkg/wsl/wsl.go (2)

190-191: Consider increasing or externalizing the 2-second timeout.

While a 2-second timeout may suffice in many scenarios, user feedback suggests that some WSL-related utilities (e.g., shell detection, path resolution) may benefit from a 5-second timeout. Extending or making this timeout configurable can help avoid premature timeouts under slow system conditions.


214-214: Ensure robust handling for DetectShell timeouts.

Similar to GetWshPath, DetectShell invokes potentially time-consuming operations. If it exceeds the 2-second timeout, consider logging detailed context or offering a fallback shell path to avoid functionality blocks.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 83dbbf6 and c8d1157.

📒 Files selected for processing (2)
  • pkg/shellexec/shellexec.go (2 hunks)
  • pkg/wsl/wsl.go (5 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • pkg/shellexec/shellexec.go
🔇 Additional comments (3)
pkg/wsl/wsl.go (3)

204-204: Validate potential context deadline errors from GetWshPath.

Using utilCtx with a 2-second timeout might cause undesired failures if GetWshPath occasionally takes longer. Consider more extensive logging or a graceful fallback when a timeout occurs.


225-231: Confirm proper cleanup of old contexts.

Overwriting the existing cancelFn cleans up previously running contexts, but ensure no running goroutines rely on the old context’s lifecycle. If tasks using the old context are still active, they may throw cancellation or incomplete operation errors. Otherwise, this is a good approach to prevent stale contexts.


484-484: Initialize cancelFn carefully to avoid nil calls.

Currently, cancelFn defaults to nil and is later set by StartConnServer. This is fine as long as every usage site checks for nil first. Otherwise, consider assigning a no-op function to reduce branching.

@oneirocosm oneirocosm merged commit 6c53eb8 into main Jan 2, 2025
7 of 8 checks passed
@oneirocosm oneirocosm deleted the sylvie/wsl-cancelfn branch January 2, 2025 21:05
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants