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] Panic while accessing SleepyTicker methods Stop()/SetSleep() #1779

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

Conversation

stenya
Copy link
Contributor

@stenya stenya commented Dec 17, 2024

The time.Ticker object was stored as a value type, but it is expected to be a pointer according to its implementation:

func (t *Ticker) Stop()
func (t *Ticker) Reset(d Duration)

This was leading to an application crash.

STR 1:
Run portmaster-core without privileged rights. It will not be able to start the kernel driver (Windows). During unloading of already initialized modules, the process crashes because of stopping SleepyTicker instances in workers of the "network" module.

STR 2:
Run tests from service\mgr\sleepyticker_test.go

Summary by CodeRabbit

  • New Features

    • Introduced unit tests for the SleepyTicker functionality, validating its behavior in normal and sleep modes.
  • Bug Fixes

    • Ensured safe stopping of the ticker without causing panic.
  • Refactor

    • Updated the ticker field from a value type to a pointer type for improved memory management and performance.

The time.Ticker object was stored as a value type, but it is expected to be a pointer according to its implementation:
```
func (t *Ticker) Stop()
func (t *Ticker) Reset(d Duration)
```

This was leading to an application crash.

STR 1:
Run `portmaster-core` without privileged rights. It will not be able to start the kernel driver (Windows).
During unloading of already initialized modules, the process crashes because of stopping SleepyTicker instances in workers of the "network" module.

STR 2:
Run tests from `service\mgr\sleepyticker_test.go`
@stenya stenya requested review from vlabo and dhaavi December 17, 2024 13:52
Copy link
Contributor

coderabbitai bot commented Dec 17, 2024

Warning

There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure.

🔧 ast-grep (0.31.1)
service/mgr/sleepyticker.go

An unexpected error occurred while running ast-grep.

📝 Walkthrough

Walkthrough

The pull request introduces changes to the SleepyTicker implementation in the service/mgr package. The primary modification is changing the ticker field from a value type to a pointer type in the sleepyticker.go file. Simultaneously, a new test file sleepyticker_test.go is added to provide comprehensive unit tests for the SleepyTicker functionality, covering scenarios like normal ticking, sleep mode, and stopping the ticker.

Changes

File Change Summary
service/mgr/sleepyticker.go - Changed ticker field from time.Ticker to *time.Ticker
- Updated ticker initialization to use pointer semantics
service/mgr/sleepyticker_test.go - Added new test file with two test functions
- TestSleepyTickerStop: Verifies safe stopping of ticker
- TestSleepyTicker: Tests normal mode, sleep mode, and ticker stopping

Sequence Diagram

sequenceDiagram
    participant ST as SleepyTicker
    participant Ticker as time.Ticker
    
    ST->>Ticker: NewTicker(normalDuration)
    ST->>ST: Wait for tick
    alt Normal Mode
        Ticker-->>ST: Tick received
    else Sleep Mode
        ST->>Ticker: SetSleep(sleepDuration)
        Ticker-->>ST: No tick
    end
    
    ST->>Ticker: Stop()
    ST->>ST: No further ticks
Loading

Tip

CodeRabbit's docstrings feature is now available as part of our Early Access Program! Simply use the command @coderabbitai generate docstrings to have CodeRabbit automatically generate docstrings for your pull request. We would love to hear your feedback on Discord.


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

🧹 Nitpick comments (3)
service/mgr/sleepyticker_test.go (3)

8-14: Add t.Parallel() for concurrent test execution

The test effectively verifies that Stop() no longer panics. Consider adding t.Parallel() at the start of the test to enable concurrent execution with other tests.

 func TestSleepyTickerStop(t *testing.T) {
+    t.Parallel()
     normalDuration := 100 * time.Millisecond
🧰 Tools
🪛 golangci-lint (1.62.2)

8-8: Function TestSleepyTickerStop missing the call to method parallel

(paralleltest)


16-57: Consider using sub-tests and parallel execution

The test comprehensively covers the key scenarios. Consider these improvements:

  1. Add t.Parallel() for concurrent execution
  2. Use t.Run() to organize scenarios into sub-tests for better isolation and parallel execution
 func TestSleepyTicker(t *testing.T) {
+    t.Parallel()
     normalDuration := 100 * time.Millisecond
     sleepDuration := 200 * time.Millisecond

-    st := NewSleepyTicker(normalDuration, sleepDuration)
-
-    // Test normal mode
+    t.Run("normal mode", func(t *testing.T) {
+        t.Parallel()
+        st := NewSleepyTicker(normalDuration, sleepDuration)
+        defer st.Stop()
         select {

Continue this pattern for other test scenarios (sleep mode, zero sleep duration, and stop).

🧰 Tools
🪛 golangci-lint (1.62.2)

16-16: Function TestSleepyTicker missing the call to method parallel

(paralleltest)


1-57: Consider adding more test cases

While the current tests cover the main functionality, consider adding these scenarios:

  1. Calling SetSleep(true) multiple times
  2. Switching between sleep and normal modes rapidly
  3. Edge cases with very small or very large durations
  4. Concurrent access to Wait() from multiple goroutines

Would you like me to provide example implementations for these test cases?

🧰 Tools
🪛 golangci-lint (1.62.2)

8-8: Function TestSleepyTickerStop missing the call to method parallel

(paralleltest)


16-16: Function TestSleepyTicker missing the call to method parallel

(paralleltest)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 6e173e3 and 6c014d2.

📒 Files selected for processing (2)
  • service/mgr/sleepyticker.go (2 hunks)
  • service/mgr/sleepyticker_test.go (1 hunks)
🧰 Additional context used
🪛 golangci-lint (1.62.2)
service/mgr/sleepyticker_test.go

8-8: Function TestSleepyTickerStop missing the call to method parallel

(paralleltest)


16-16: Function TestSleepyTicker missing the call to method parallel

(paralleltest)

🔇 Additional comments (4)
service/mgr/sleepyticker.go (4)

7-7: Correct fix: Changed ticker to pointer type

The change from time.Ticker to *time.Ticker is the right fix. The time.Ticker type's methods like Stop() and Reset() are defined with pointer receivers, so storing it as a value type would create a copy, leading to method calls on the copy instead of the original ticker. This explains the panic in the original code.


19-19: LGTM: Correct initialization of ticker pointer

The initialization is properly updated to match the new pointer type field. time.NewTicker returns *time.Ticker which is now directly assigned without dereferencing.


Line range hint 35-37: Verified: Stop() now works correctly with pointer ticker

The Stop() method now correctly operates on the original ticker instance rather than a copy, preventing the panic that was occurring in the original code.

✅ Verification successful

Based on the results, I can now generate the final response:

Verified: Stop() implementation correctly handles ticker cleanup

The verification confirms that:

  • SleepyTicker struct holds a pointer to time.Ticker (ticker *time.Ticker)
  • The Stop() method correctly calls Stop() on the underlying ticker pointer (st.ticker.Stop())
  • Test files demonstrate the method is working as expected without panics
  • The implementation is used consistently across the codebase
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Verify that Stop() is only called on pointer receiver
ast-grep --pattern 'func ($r *time.Ticker) Stop()'

Length of output: 52


Script:

#!/bin/bash
# Let's check the implementation of SleepyTicker's Stop method and its usage
ast-grep --pattern 'type SleepyTicker struct {
  $$$
}'

# Also check for any Stop method implementations
ast-grep --pattern 'func ($r *SleepyTicker) Stop() {
  $$$
}'

# And check for any usages of Stop
rg "\.Stop\(\)" -A 2

Length of output: 8189


Line range hint 40-56: Verified: SetSleep() now works correctly with pointer ticker

The SetSleep() method now correctly calls Reset() on the original ticker instance. The channel management logic for sleep mode is well-implemented, properly handling both the sleep and wake scenarios.

✅ Verification successful

Verified: SetSleep() correctly uses pointer ticker for Reset() operations

The verification confirms that:

  • SleepyTicker.ticker is properly declared as *time.Ticker
  • The ticker is correctly initialized as a pointer in NewSleepyTicker() using time.NewTicker()
  • Reset() calls in SetSleep() are made on the pointer ticker, which is the correct way to use the time.Ticker API
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Verify that Reset() is only called on pointer receiver
ast-grep --pattern 'func ($r *time.Ticker) Reset($d time.Duration)'

Length of output: 69


Script:

#!/bin/bash
# Let's verify the implementation of SleepyTicker and its usage of Reset
ast-grep --pattern 'type SleepyTicker struct {
  $$$
}'

# Also check the initialization to ensure ticker is a pointer
ast-grep --pattern 'func NewSleepyTicker($$$) *SleepyTicker {
  $$$
}'

# And check all Reset calls within the codebase
rg "Reset\(" -A 2

Length of output: 3818

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