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

Support SSH proxy command #493

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

zjgemi
Copy link
Contributor

@zjgemi zjgemi commented Sep 26, 2024

Summary by CodeRabbit

  • New Features

    • Introduced an optional proxy_command parameter for SSH connections, allowing users to specify a command for proxying.
  • Documentation

    • Updated documentation to include details about the new proxy_command argument, clarifying its purpose and usage.

Signed-off-by: zjgemi <[email protected]>
Copy link
Contributor

coderabbitai bot commented Sep 26, 2024

📝 Walkthrough

Walkthrough

The changes introduce an optional proxy_command parameter to the __init__ method of the SSHContext class in the dpdispatcher/contexts/ssh_context.py file. This parameter allows users to define a command for proxying SSH connections. The _setup_ssh method is modified to handle this new parameter, creating a paramiko.ProxyCommand object if provided. Additionally, documentation for the proxy_command argument is added to the arginfo function.

Changes

Files Change Summary
dpdispatcher/contexts/ssh_context.py Added proxy_command parameter to __init__ method and updated _setup_ssh method to use it. Documentation for proxy_command added to arginfo.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant SSHContext
    participant ProxyCommand

    User->>SSHContext: Initialize with proxy_command
    SSHContext->>SSHContext: Set proxy_command attribute
    SSHContext->>SSHContext: Call _setup_ssh()
    alt proxy_command provided
        SSHContext->>ProxyCommand: Create ProxyCommand object
        ProxyCommand->>SSHContext: Return ProxyCommand object
    else proxy_command not provided
        SSHContext->>SSHContext: Create standard socket connection
    end
Loading

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 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

codecov bot commented Sep 26, 2024

Codecov Report

Attention: Patch coverage is 75.00000% with 2 lines in your changes missing coverage. Please review.

Project coverage is 47.80%. Comparing base (819eddf) to head (e45e720).

Files with missing lines Patch % Lines
dpdispatcher/contexts/ssh_context.py 75.00% 2 Missing ⚠️

❗ There is a different number of reports uploaded between BASE (819eddf) and HEAD (e45e720). Click for more details.

HEAD has 1 upload less than BASE
Flag BASE (819eddf) HEAD (e45e720)
15 14
Additional details and impacted files
@@             Coverage Diff             @@
##           master     #493       +/-   ##
===========================================
- Coverage   60.19%   47.80%   -12.40%     
===========================================
  Files          39       39               
  Lines        3859     3864        +5     
===========================================
- Hits         2323     1847      -476     
- Misses       1536     2017      +481     

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

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: 2

🧹 Outside diff range and nitpick comments (1)
dpdispatcher/contexts/ssh_context.py (1)

352-352: Clarify the documentation for proxy_command

The current description "The command of proxy" may be ambiguous to users. Consider enhancing it to provide more clarity, such as:

-doc_proxy_command = "The command of proxy."
+doc_proxy_command = "The command used to establish a proxy for SSH connections (e.g., 'ssh -W %h:%p proxy.example.com')."
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 819eddf and e45e720.

📒 Files selected for processing (1)
  • dpdispatcher/contexts/ssh_context.py (5 hunks)
🧰 Additional context used
GitHub Check: codecov/patch
dpdispatcher/contexts/ssh_context.py

[warning] 147-148: dpdispatcher/contexts/ssh_context.py#L147-L148
Added lines #L147 - L148 were not covered by tests

Comment on lines +146 to +148
if self.proxy_command is not None:
sock = paramiko.ProxyCommand(self.proxy_command)
sock.settimeout(self.timeout)
Copy link
Contributor

@coderabbitai coderabbitai bot Sep 26, 2024

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add unit tests for the proxy_command functionality

The newly added code handling the proxy_command is not covered by existing tests. To ensure reliability and prevent future regressions, please add unit tests that verify the behavior when a proxy_command is provided.

🧰 Tools
GitHub Check: codecov/patch

[warning] 147-148: dpdispatcher/contexts/ssh_context.py#L147-L148
Added lines #L147 - L148 were not covered by tests

Copy link
Member

Choose a reason for hiding this comment

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

I agree with the AI. A unit test should be added.

Copy link
Contributor

Choose a reason for hiding this comment

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

@njzjz, I'll proceed to add unit tests for the proxy_command functionality as requested. Here's a test case that verifies the behavior when a proxy_command is provided:

import unittest
from unittest.mock import patch, MagicMock
from dpdispatcher.contexts.ssh_context import SSHSession

class TestSSHSessionProxyCommand(unittest.TestCase):
    
    @patch('paramiko.ProxyCommand')
    @patch('socket.socket')
    def test_setup_ssh_with_proxy_command(self, mock_socket, mock_proxy_command):
        # Mock the ProxyCommand and socket behavior
        mock_proxy = MagicMock()
        mock_proxy_command.return_value = mock_proxy
        
        # Create an SSHSession with a proxy command
        session = SSHSession(
            hostname="example.com",
            username="user",
            proxy_command="proxy_command_example"
        )
        
        # Ensure that ProxyCommand is used instead of socket
        mock_proxy_command.assert_called_once_with("proxy_command_example")
        mock_proxy.settimeout.assert_called_once_with(session.timeout)
        mock_socket.assert_not_called()  # Ensure socket is not used

    @patch('paramiko.ProxyCommand')
    @patch('socket.socket')
    def test_setup_ssh_without_proxy_command(self, mock_socket, mock_proxy_command):
        # Create an SSHSession without a proxy command
        session = SSHSession(
            hostname="example.com",
            username="user"
        )
        
        # Ensure that socket is used instead of ProxyCommand
        mock_socket.assert_called_once_with(socket.AF_INET, socket.SOCK_STREAM)
        mock_socket().settimeout.assert_called_once_with(session.timeout)
        mock_socket().connect.assert_called_once_with(("example.com", 22))
        mock_proxy_command.assert_not_called()  # Ensure ProxyCommand is not used

if __name__ == '__main__':
    unittest.main()

Explanation:

  • Test 1 (test_setup_ssh_with_proxy_command): Verifies that when a proxy_command is provided, paramiko.ProxyCommand is used, and the standard socket connection is not invoked.
  • Test 2 (test_setup_ssh_without_proxy_command): Verifies that when no proxy_command is provided, the standard socket connection is used.

This should ensure that the proxy_command functionality is properly tested and prevent future regressions.

Let me know if you'd like any further adjustments!

Comment on lines +401 to +407
Argument(
"proxy_command",
str,
optional=True,
default=None,
doc=doc_proxy_command,
),
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Ensure consistency in argument definitions

The Argument definition for proxy_command should align with the improved documentation string. Please update the doc parameter accordingly to reflect the clarified description.

else:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(self.timeout)
sock.connect((self.hostname, self.port))

# Make a Paramiko Transport object using the socket
ts = paramiko.Transport(sock)
Copy link
Member

Choose a reason for hiding this comment

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

Could you ignore this line before python/typeshed#12697 is accepted?

Comment on lines +146 to +148
if self.proxy_command is not None:
sock = paramiko.ProxyCommand(self.proxy_command)
sock.settimeout(self.timeout)
Copy link
Member

Choose a reason for hiding this comment

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

I agree with the AI. A unit test should be added.

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