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: data lost caused by Longhorn CSI plugin doing a wrong re-encryption of volume in rare race condition #3566

Merged
merged 1 commit into from
Feb 14, 2025

Conversation

PhanLe1010
Copy link
Contributor

@PhanLe1010 PhanLe1010 commented Feb 14, 2025

longhorn/longhorn#10416

RCA

This happens with encrypted volume only

While Longhorn CSI plugin is doing NodeStageVolume, if the Longhorn engine crash right before GetDiskFormat and recover quickly after that, the following race condition can happen:

  1. When engine is crash, the engine removes the Longhorn device at /dev/longhorn/volume-name
  2. Because the device path is gone, getDiskFormat returns empty value for diskFormat and nil error. Ref
    if exit.ExitStatus() == 2 {
    // Disk device is unformatted.
    // For `blkid`, if the specified token (TYPE/PTTYPE, etc) was
    // not found, or no (specified) devices could be identified, an
    // exit code of 2 is returned.
    return "", nil
    }
  3. Now engine is recovered, so it recreates the device at /dev/longhorn/volume-name
  4. However, due to diskFormat having empty value, Longhorn re-encrypts the volume which wipes out the all data. Ref
    if diskFormat == "" {
    if err := crypto.EncryptVolume(devicePath, passphrase, cryptoParams); err != nil {
    return nil, status.Error(codes.Internal, err.Error())
    }
    }
  5. Finally, Longhorn cannot detect a filesystem for the volume any more so it reformat the filesystem
  6. The root cause of the issue is that getDiskFormat is using blkid. The blkid command cannot differentiate 2 cases: the device doesn't exist VS the device doesn't have filesystem inside it

Proposal

Use cryptsetup isLuks instead. It can differentiate between:

  1. The device is already encrypted -> return exit code 0
  2. The device is not encrypted -> return exit code 1
  3. All other errors -> return exit code 4

Ref: https://gitlab.com/cryptsetup/cryptsetup/-/blob/main/FAQ.md?plain=1#L2848

With this proposal, we can safely make decision of only doing encryption in the 2nd case

Additional documentation or context

We were discussing of the below ideas with @derekbit and @shuo-wu but it seems cannot remove the race condition 100%

Idea 1: Check if the device path exist before doing GetDiskFormat

_, err := os.stat(devicePath)
if err != nil {
    return err
}

formatMounter.GetDiskFormat(devicePath)

-> Cannot avoid the race condition as the device can still disappear before GetDiskFormat and re-appear after GetDiskFormat

Idea 2: Check if the device path exist after doing GetDiskFormat

formatMounter.GetDiskFormat(devicePath)

_, err := os.stat(devicePath)
if err != nil {
    return err
}

-> Cannot avoid the race condition as the device can still disappear before GetDiskFormat and re-appear after GetDiskFormat

Copy link

coderabbitai bot commented Feb 14, 2025

Walkthrough

The changes modify the encryption process in the crypto.go file by introducing a new function, isDeviceEncrypted, which checks if a device is already encrypted using a namespace executor. The EncryptVolume function now calls this helper function; if an error occurs during this check, a warning is logged and the error is returned, and if the device is already encrypted, an informational log is output and the function exits early. Additionally, the import for github.com/longhorn/longhorn-manager/types has been reorganized.

Changes

File Summary
csi/crypto/crypto.go - Added isDeviceEncrypted function to check device encryption status.
- Modified EncryptVolume for error handling and early exit if already encrypted.
- Reorganized import for .../longhorn-manager/types.

Sequence Diagram(s)

sequenceDiagram
    participant Caller
    participant EncryptVolume
    participant isDeviceEncrypted
    participant Logger

    Caller->>EncryptVolume: Request encryption (devicePath)
    EncryptVolume->>isDeviceEncrypted: Check if device is encrypted
    isDeviceEncrypted-->>EncryptVolume: Returns (error or true/false)
    alt Error during check
        EncryptVolume->>Logger: Log warning
        EncryptVolume-->>Caller: Return error
    else Device already encrypted
        EncryptVolume->>Logger: Log info (skip encryption)
        EncryptVolume-->>Caller: Return nil
    else Device not encrypted
        EncryptVolume->>Logger: Proceed with encryption process
        EncryptVolume-->>Caller: Continue with encryption
    end
Loading

Possibly related PRs

  • feat(crypto): v2 volume encryption #3438: Updates related to volume encryption logic, specifically accommodating new parameters in encryption functions, which share context with the modifications introduced by the new isDeviceEncrypted function.

Suggested reviewers

  • derekbit
  • shuo-wu
✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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.

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.

derekbit
derekbit previously approved these changes Feb 14, 2025
Copy link
Member

@derekbit derekbit left a comment

Choose a reason for hiding this comment

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

LGTM

@PhanLe1010
Copy link
Contributor Author

Btw, please let me know if you have better idea than the cryptsetup isLuks solution @derekbit @shuo-wu @c3y1huang @mantissahz

c3y1huang
c3y1huang previously approved these changes Feb 14, 2025
@derekbit
Copy link
Member

@PhanLe1010 go fmt failed

PhanLe1010 added a commit to PhanLe1010/go-common-libs that referenced this pull request Feb 14, 2025
…ion of volume in rare race condition

see more details at
longhorn/longhorn-manager#3566

longhorn-10416

Signed-off-by: Phan Le <phan.le@suse.com>
@PhanLe1010 PhanLe1010 dismissed stale reviews from c3y1huang and derekbit via ea48851 February 14, 2025 05:36
…ion of volume in rare

race condition

This happens with encrypted volume only

While Longhorn CSI plugin is doing NodeStageVolume, if the Longhorn
engine crash right before GetDiskFormat
(https://github.com/longhorn/longhorn-manager/blob/
   5f9ec86/csi/node_server.go#L486)
and recover quickly after that, the following race condition can happen:
1. When engine is crash, the engine removes the Longhorn device at
   /dev/longhorn/volume-name
2. Because the device path is gone, getDiskFormat returns empty value for diskFormat
   and nil error. Ref https://github.com/longhorn/longhorn-manager/blob/
       5f9ec86/vendor/k8s.io/
           mount-utils/mount_linux.go#L687-L693
3. Now engine is recovered, so it recreate the device at
   /dev/longhorn/volume-name
4. However, due to diskFormat having empty value, Longhorn re-encrypts
   the volume which wipes out the all data. Ref https://github.com/longhorn/
       longhorn-manager/blob/5f9ec86d18612afaa9f97c78cee3e34f7b653ad6/
           csi/node_server.go#L513-L517
5. Finally, Longhorn cannot detect a filesystem for the volume any more
   so it reformat the filesystem

RCA

The root cause of the issue is that getDiskFormat is using blkid. The
blkid command cannot differentiate 2 cases: the device doesn't exist VS
the device doesn't have filesystem inside it

Proposal

Use cryptsetup isLuks instead. can differentiate between:
1. The device is already encrypted -> return exit code 0
2. The device is not encrypted -> return exit code 1
3. All other errors -> return exit code 4

Ref: https://gitlab.com/cryptsetup/cryptsetup/-/blob/main/FAQ.md?plain=1#L2848

Now we can safely make decision of only doing encryption in the 2nd case

longhorn-10416

Signed-off-by: Phan Le <phan.le@suse.com>
@PhanLe1010 PhanLe1010 marked this pull request as ready for review February 14, 2025 05:49
@PhanLe1010
Copy link
Contributor Author

@PhanLe1010 go fmt failed

Fixed

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

🧹 Nitpick comments (2)
csi/crypto/crypto.go (2)

194-201: LGTM! Critical fix for race condition.

The new function correctly uses cryptsetup isLuks to accurately determine the encryption status of a device, addressing the root cause of data loss during re-encryption. The implementation properly handles namespace isolation and error propagation.

This change is crucial as it:

  1. Prevents race conditions during engine crashes
  2. Provides reliable device encryption detection
  3. Avoids data loss from incorrect re-encryption

88-97: LGTM! Enhanced error handling and data protection.

The changes correctly prevent data loss by checking encryption status before proceeding. The error handling and logging provide good observability.

Consider enhancing the log message in line 90 to include more context:

-		logrus.WithError(err).Warnf("Failed to check IsDeviceEncrypted before encrypting volume %v", devicePath)
+		logrus.WithError(err).Warnf("Failed to check encryption status before encrypting volume %v. This might indicate issues with cryptsetup or device access", devicePath)
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5f9ec86 and e3d1e9f.

⛔ Files ignored due to path filters (1)
  • vendor/github.com/longhorn/go-common-libs/ns/crypto.go is excluded by !vendor/**
📒 Files selected for processing (1)
  • csi/crypto/crypto.go (3 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Build binaries
  • GitHub Check: Summary
🔇 Additional comments (1)
csi/crypto/crypto.go (1)

14-15: LGTM!

The import reorganization follows Go's standard grouping practices.

derekbit pushed a commit to longhorn/go-common-libs that referenced this pull request Feb 14, 2025
…ion of volume in rare race condition

see more details at
longhorn/longhorn-manager#3566

longhorn-10416

Signed-off-by: Phan Le <phan.le@suse.com>
@derekbit derekbit merged commit 72c9173 into longhorn:master Feb 14, 2025
9 checks passed
@derekbit
Copy link
Member

@mergify backport v1.8.x v1.7.x

Copy link

mergify bot commented Feb 14, 2025

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.

4 participants