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(preflight): check APT package installation by status flag #132

Merged

Conversation

COLDTURNIP
Copy link
Contributor

Which issue(s) this PR fixes:

Issue longhorn/longhorn#9495

What this PR does / why we need it:

While checking the installation status with APT package system, we should read the actual package status instead of the exit code of dpkg-query -l or dpkg -l.

Special notes for your reviewer:

Additional documentation or context

Copy link

coderabbitai bot commented Dec 3, 2024

Walkthrough

The changes in this pull request enhance the CheckPackageInstalled method of the AptPackageManager class by updating its signature and improving its error handling. The method now returns a detailed output and processes the results of the dpkg-query command to check for installed packages. Additionally, a new error variable, packageNotInstalledError, is introduced for better error reporting. These modifications aim to provide clearer feedback regarding package installation status.

Changes

File Path Change Summary
pkg/local/preflight/packagemanager/apt.go Updated CheckPackageInstalled method signature and enhanced functionality to include package status checking.
pkg/local/preflight/packagemanager/apt.go Added detailed comment block for CheckPackageInstalled method.
pkg/local/preflight/packagemanager/apt.go Introduced several new constants related to package management actions and statuses.
pkg/local/preflight/packagemanager/packagemanager.go Introduced packageNotInstalledError for improved error handling related to package management.
pkg/local/preflight/packagemanager/packagemanager.go Imported errors package to support the new error variable.

Assessment against linked issues

Objective Addressed Explanation
The CLI should indicate that nfs-common is missing during the preflight check. (Issue #9495) The changes do not specifically address the nfs-common check.
The CLI should align its checks with environment_check.sh. (Issue #9495) It is unclear if the changes will affect the CLI's preflight checks for nfs-common.
Improve error reporting for package installation status. (Issue #9495) The introduction of packageNotInstalledError enhances error reporting.

Possibly related PRs


📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 513edfa and d9c83f8.

📒 Files selected for processing (2)
  • pkg/local/preflight/packagemanager/apt.go (2 hunks)
  • pkg/local/preflight/packagemanager/packagemanager.go (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • pkg/local/preflight/packagemanager/packagemanager.go
  • pkg/local/preflight/packagemanager/apt.go

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.

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

@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

🧹 Outside diff range and nitpick comments (1)
pkg/local/preflight/packagemanager/apt.go (1)

78-81: Consider adding context to execution error.

When the command execution fails, it would be helpful to wrap the error with additional context.

 output, err = c.executor.Execute([]string{}, "dpkg-query", []string{"-l", name}, commontypes.ExecuteNoTimeout)
 if err != nil {
-    return
+    return output, fmt.Errorf("failed to query package %s: %w", name, err)
 }
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between cd47aee and 5b3b5c2.

📒 Files selected for processing (2)
  • pkg/local/preflight/packagemanager/apt.go (2 hunks)
  • pkg/local/preflight/packagemanager/packagemanager.go (2 hunks)
🔇 Additional comments (3)
pkg/local/preflight/packagemanager/packagemanager.go (1)

4-4: LGTM! Well-structured error handling addition.

The new error variable is appropriately defined at the package level and follows Go conventions. The error message is clear and concise, which will help improve error reporting for package installation checks.

Also applies to: 23-24

pkg/local/preflight/packagemanager/apt.go (2)

70-77: LGTM! Clear and helpful documentation.

The added comment block with example output format is excellent. It clearly documents the expected format and helps understand the parsing logic.


82-92: Verify the fix addresses the nfs-common detection issue.

The implementation looks correct for detecting package installation status. Let's verify it specifically addresses the nfs-common package detection issue mentioned in the PR objectives.

@COLDTURNIP COLDTURNIP force-pushed the 9495-dpkg_check_package_status branch from 5b3b5c2 to 513edfa Compare December 3, 2024 09:25
@COLDTURNIP COLDTURNIP requested a review from c3y1huang December 3, 2024 09:26
Copy link

@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

🧹 Outside diff range and nitpick comments (2)
pkg/local/preflight/packagemanager/apt.go (2)

11-28: LGTM: Well-documented constants improve code clarity.

The new constants accurately represent dpkg package states and desired actions, making the code more maintainable.

Consider adding brief descriptions for each constant group to improve documentation:

 const (
     // Ref: man 1 dpkg-query
+    // Package desired actions
     dpkgDesiredActionUnknown = "u"
     dpkgDesiredActionInstall = "i"
     dpkgDesiredActionHold    = "h"
     dpkgDesiredActionRemove  = "r"
     dpkgDesiredActionPurge   = "p"

+    // Package status flags
     dpkgStatusNotInstalled     = "n"
     dpkgStatusConfigFiles      = "c"

89-90: Document the format string interpretation.

The dpkg-query format string is crucial for correct operation but lacks documentation about the expected output format.

Add a comment explaining the format string components:

 // example for an installed package:
 // $ dpkg-query -f='${binary:Package} ${db:Status-Abbrev}' -W nfs-common
 // nfs-common ii
+// where:
+// - ${binary:Package}: package name
+// - ${db:Status-Abbrev}: two-character status (e.g., 'ii' means installed)
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 5b3b5c2 and 513edfa.

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

4-4: LGTM: Import required for string manipulation.

The addition of the strings package is necessary and properly used for parsing the dpkg-query output.


95-101: ⚠️ Potential issue

Enhance the parsing logic robustness.

The current parsing logic could be more robust to handle various edge cases and provide better error reporting.

-    fields := strings.Fields(strings.TrimSpace(output))
-    if len(fields) == 2 {
-        if fields[0] == name && fields[1] == dpkgDesiredActionInstall+dpkgStatusInstalled {
-            return output, nil
-        }
-    }
-    return output, packageNotInstalledError
+    fields := strings.Fields(strings.TrimSpace(output))
+    if len(fields) != 2 {
+        return output, fmt.Errorf("unexpected dpkg-query output format: %q", output)
+    }
+    
+    if fields[0] != name {
+        return output, fmt.Errorf("package name mismatch: expected %q, got %q", name, fields[0])
+    }
+    
+    status := fields[1]
+    if len(status) != 2 {
+        return output, fmt.Errorf("invalid status format: %q", status)
+    }
+    
+    desiredAction := string(status[0])
+    pkgStatus := string(status[1])
+    
+    if desiredAction == dpkgDesiredActionInstall && pkgStatus == dpkgStatusInstalled {
+        return output, nil
+    }
+    
+    return output, fmt.Errorf("%w: status=%q", packageNotInstalledError, status)

This enhancement:

  1. Provides detailed error messages for debugging
  2. Validates the status string format
  3. Separates the status components for clarity
  4. Includes the actual status in the error message

Likely invalid or redundant comment.


87-101: Verify package status handling aligns with PR objectives.

The PR aims to improve package status checking accuracy, but the implementation only checks for "ii" status. Consider if other status combinations should be considered as "installed".

Let's verify the package status handling in the environment check script:

Consider:

  1. Documenting which package statuses are considered "installed"
  2. Adding unit tests for different package status combinations
  3. Ensuring consistency with environment_check.sh behavior
✅ Verification successful

Let me gather more information about the package status handling by searching for related constants and tests.


Let me search specifically for dpkg status codes and their documentation.


Based on the search results, I can now generate the final response as we have found the complete set of dpkg status codes and their implementation.

Package status handling is correctly implemented for the use case

The current implementation checking for "ii" status (dpkgDesiredActionInstall + dpkgStatusInstalled) is the correct approach because:

  • The "i" status in the first position indicates the package is desired to be installed
  • The "i" status in the second position confirms the package is fully installed
  • Other status combinations like "Hi" (half-installed), "Wi" (triggers awaiting), or "Fi" (half-configured) would indicate incomplete or problematic installations that shouldn't be considered as properly installed
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find how environment_check.sh handles package status checks
rg -A 5 "dpkg" | grep -C 5 "nfs-common"

Length of output: 896


Script:

#!/bin/bash
# Search for dpkg status-related constants and their usage
ast-grep --pattern 'const dpkg$_'

# Search for test cases related to package status checking
rg -l "TestCheckPackageInstalled" 

# Look for any documentation about package status
rg -i "package.*status" -A 3 -B 3

Length of output: 12194


Script:

#!/bin/bash
# Search for dpkg status code constants
rg -l "dpkg.*status"

# Look for any dpkg-related constants
ast-grep --pattern 'const $_ = "ii"'

# Search for any dpkg documentation or comments
rg -i "dpkg.*status.*" -A 5 -B 5

Length of output: 25232

@innobead innobead merged commit dcf886e into longhorn:master Dec 3, 2024
7 checks passed
@COLDTURNIP COLDTURNIP deleted the 9495-dpkg_check_package_status branch December 3, 2024 13:18
@COLDTURNIP
Copy link
Contributor Author

COLDTURNIP commented Dec 4, 2024

@mergify backport v1.7.x

Copy link

mergify bot commented Dec 4, 2024

backport v1.7.x

❌ Command disallowed due to command restrictions in the Mergify configuration.

  • sender-permission >= write

@derekbit
Copy link
Member

derekbit commented Dec 4, 2024

@mergify backport v1.7.x

Copy link

mergify bot commented Dec 4, 2024

backport v1.7.x

✅ Backports have been created

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.

3 participants