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

chanbackup: archive old channel backup files #9232

Merged
merged 3 commits into from
Jan 24, 2025

Conversation

Abdulkbk
Copy link
Contributor

@Abdulkbk Abdulkbk commented Oct 29, 2024

Closes #8906

Change Description

From the feature description:

To ensure that certain classes of recovery are always possible, we should considering adding a mode to never delete channel backups, and only rename or move them to a special folder that stores archived channels. They're relatively small (~300 bytes or so), so it shouldn't take up a significant amount of disk space.

This PR allows for the archiving of channel backups, enabling users to choose whether to permanently delete previous backup files or archive them by moving them to a designated archives folder.

Problem:
LND currently overwrites old channel backup files when creating new ones. This means:

  • If a user accidentally deletes a channel backup file, the backup is irretrievably lost.
  • If a newly created backup file becomes corrupted and no older backups are preserved, recovering the channel through the file becomes impossible.
  • In certain cases, users may want to compare older and newer backups to verify that the evolution of the channel states was valid.

Solution:
We modify the current flow of creating channel.backup. We start by creating a folder in the same directory where we store the channel.backup file (chan-backup-archives). We ensure that the channel.backup file is copied to the archive directory and timestamped before finally replacing it with the new file.

We set the LND's default behavior to archive old channel backups, but we provide a configuration option that can be passed as an argument or specified in lnd.conf to disable this behavior. This option allows LND to delete channel.backup files instead of archiving them. This can be achieved by setting no-backup-archive=true in lnd.conf or passed as argument:

lnd --no-backup-archive

Steps to Test

  1. Start LND (make sure no-backup-archive=true is not set in lnd.conf):
lnd
  1. Trigger the channel backup process. This can be achieved by generating some blocks. If you're using BTCD backend:
btcctl generate 6
  1. Stop LND and check the directory where the channel.backup file is stored. You will find a new folder called chan-backup-archives, where the backup files are archived.

To test disabling this feature

  • Start LND
lnd # if no-backup-archive=true is set in lnd.conf

# or

lnd --no-backup-archive # pass as arg
  • Repeat 2 & 3. This time the chan-backup-archives directory will not be created (if it does not already exist). If it already exists a new archive will not be created.

Pull Request Checklist

Testing

  • Your PR passes all CI checks.
  • Tests covering the positive and negative (error paths) are included.
  • Bug fixes contain tests triggering the bug to prevent regressions.

Code Style and Documentation

📝 Please see our Contribution Guidelines for further guidance.

Copy link
Contributor

coderabbitai bot commented Oct 29, 2024

Important

Review skipped

Auto reviews are limited to specific labels.

🏷️ Labels to auto review (1)
  • llm-review

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.


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.

@Abdulkbk Abdulkbk marked this pull request as ready for review November 1, 2024 11:49
@Abdulkbk Abdulkbk force-pushed the archive-channel-backups branch from bd7fb87 to 71ee590 Compare November 24, 2024 15:38
chanbackup/backupfile_test.go Outdated Show resolved Hide resolved
@Abdulkbk Abdulkbk force-pushed the archive-channel-backups branch from 71ee590 to 375e0fb Compare December 22, 2024 16:46
@lightninglabs-deploy
Copy link

@Abdulkbk, remember to re-request review from reviewers when ready

@MPins
Copy link
Contributor

MPins commented Jan 6, 2025

LGTM 👌

chanbackup/backupfile_test.go Outdated Show resolved Hide resolved
@Abdulkbk Abdulkbk changed the title chanbackup: archive old channel backups chanbackup: archive old channel backup files Jan 7, 2025
@yyforyongyu
Copy link
Member

Could you do a rebase and push so the CI can run again, wanna check what's going in the logs but they are expired.

@Abdulkbk Abdulkbk force-pushed the archive-channel-backups branch from 375e0fb to ade9d50 Compare January 7, 2025 04:13
@Abdulkbk
Copy link
Contributor Author

Abdulkbk commented Jan 7, 2025

I've rebased and pushed
@yyforyongyu

@yyforyongyu yyforyongyu added this to the v0.19.0 milestone Jan 8, 2025
@yyforyongyu yyforyongyu added enhancement Improvements to existing features / behaviour SCB Related to static channel backup size/kilo medium, proper context needed, less than 1000 lines labels Jan 8, 2025
chanbackup/backupfile.go Outdated Show resolved Hide resolved
chanbackup/backupfile.go Show resolved Hide resolved
chanbackup/backupfile.go Outdated Show resolved Hide resolved
chanbackup/backupfile_test.go Outdated Show resolved Hide resolved
chanbackup/backupfile_test.go Outdated Show resolved Hide resolved
chanbackup/backupfile.go Outdated Show resolved Hide resolved
config.go Outdated Show resolved Hide resolved
docs/release-notes/release-notes-0.19.0.md Outdated Show resolved Hide resolved
chanbackup/backupfile.go Outdated Show resolved Hide resolved
chanbackup/backupfile_test.go Outdated Show resolved Hide resolved
@Abdulkbk Abdulkbk force-pushed the archive-channel-backups branch 3 times, most recently from bdcf713 to 8cf0088 Compare January 13, 2025 20:29
@Abdulkbk
Copy link
Contributor Author

Hi @yyforyongyu , thank you for the review. I've addressed your feedback and left some comments/questions.

@Abdulkbk Abdulkbk force-pushed the archive-channel-backups branch from 8cf0088 to 1051ab4 Compare January 16, 2025 11:18
@Abdulkbk
Copy link
Contributor Author

I think this PR is ready for another look :)

Copy link
Member

@yyforyongyu yyforyongyu left a comment

Choose a reason for hiding this comment

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

LGTM🚢 Thanks for the PR!

chanbackup/backupfile.go Outdated Show resolved Hide resolved
},

// Test with deleteOldBackup set to false - should create
// archive.
Copy link
Member

Choose a reason for hiding this comment

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

👍

@yyforyongyu yyforyongyu requested a review from guggero January 16, 2025 15:15
Copy link
Collaborator

@guggero guggero left a comment

Choose a reason for hiding this comment

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

Thanks for the feature. Have a couple of improvement proposals, but we're quite close.

chanbackup/backupfile.go Outdated Show resolved Hide resolved
// and not error out.
_, err = os.Stat(b.fileName)
if err != nil {
log.Debugf("Unable to get backup file info: %v", err)
Copy link
Collaborator

Choose a reason for hiding this comment

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

If you saw this error message as a user, would you be able to:

  1. Know what's going on?
  2. Tell if you need to react to it or not?

I think we should either:

  1. Test if the error is a "file not found error" (see
    func FileExists(name string) bool {
    ) and if it is not log anything.
  2. Directly use lnrpc.FileExists before even trying to do anything.
  3. Update the error message to be more informative, perhaps something like "Cannot archive channel backup file, unable to get file info: %v".

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I go with 2, called the lnrpc.FileExists directly and if it returns true we proceed with creating the archive.

chanbackup/backupfile.go Outdated Show resolved Hide resolved
chanbackup/backupfile_test.go Outdated Show resolved Hide resolved
); err != nil {
return fmt.Errorf("unable to archive old backup file:"+
" %w", err)
if !b.deleteOldBackup {
Copy link
Collaborator

Choose a reason for hiding this comment

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

One more flag to pass into createArchiveFile, then this can just be an early return.
No need to create that many levels of nesting.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

One more flag to pass into createArchiveFile,

I didn't quite understand this part, but now that we're using lnrpc.FileExists and the previous nesting is gone, does this solve the issue?

if !b.noBackupArchive {
		// Archive the main backup file if it exists before replacing
		// it with a new one.
		backupExists := lnrpc.FileExists(b.fileName)
		if backupExists {
			log.Infof("Archiving old channel backup to %v",
				b.archiveDir)

			err := createArchiveFile(
				b.archiveDir, b.fileName,
			)
			if err != nil {
				return fmt.Errorf("unable to archive old "+
					"channel backup file: %w", err)
			}
		}
	}

chanbackup/backupfile_test.go Show resolved Hide resolved
config.go Outdated Show resolved Hide resolved
config.go Outdated Show resolved Hide resolved
@Abdulkbk Abdulkbk force-pushed the archive-channel-backups branch 2 times, most recently from 76a3b56 to 55f328c Compare January 20, 2025 21:11
@Abdulkbk
Copy link
Contributor Author

Thanks for the feature. Have a couple of improvement proposals, but we're quite close.

Thank you for taking a look @guggero. I have addressed your feedback and added some comments as well.

@guggero guggero self-requested a review January 21, 2025 08:43
Copy link
Collaborator

@guggero guggero left a comment

Choose a reason for hiding this comment

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

Very clean and LGTM 🎉

Have two more nits. Do you want to address those, @Abdulkbk? Or should I merge?
IMO they're not blocking, just nice to have.

@@ -117,6 +131,21 @@ func (b *MultiFile) UpdateAndSwap(newBackup PackedMulti) error {
return fmt.Errorf("unable to close file: %w", err)
}

// Archive the main backup file if it exists before replacing it with a
// new one.
backupExists := lnrpc.FileExists(b.fileName)
Copy link
Collaborator

Choose a reason for hiding this comment

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

nit: the word "backup" is a bit overloaded in this context (does it mean the old channel.backup file? or the archival copy we're going to create)? My suggestion: oldFileExists.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Updated the comment and now using oldFileExists

if err != nil {
return fmt.Errorf("unable to archive old channel "+
"backup file: %w", err)
if !b.noBackupArchive {
Copy link
Collaborator

Choose a reason for hiding this comment

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

This is what I had in mind concerning reducing indentation (and having the "happy path" on the un-indented path whenever possible, which helps with readability):

diff --git a/chanbackup/backupfile.go b/chanbackup/backupfile.go
index e44a2005e..b5564b73e 100644
--- a/chanbackup/backupfile.go
+++ b/chanbackup/backupfile.go
@@ -136,22 +136,10 @@ func (b *MultiFile) UpdateAndSwap(newBackup PackedMulti) error {
                return fmt.Errorf("unable to close file: %w", err)
        }
 
-       if !b.noBackupArchive {
-               // Archive the main backup file if it exists before replacing
-               // it with a new one.
-               backupExists := lnrpc.FileExists(b.fileName)
-               if backupExists {
-                       log.Infof("Archiving old channel backup to %v",
-                               b.archiveDir)
-
-                       err := createArchiveFile(
-                               b.archiveDir, b.fileName,
-                       )
-                       if err != nil {
-                               return fmt.Errorf("unable to archive old "+
-                                       "channel backup file: %w", err)
-                       }
-               }
+       // Make a backup copy of the old backup file before replacing it (if the
+       // user didn't opt out of that).
+       if err := b.maybeCreateArchiveFile(); err != nil {
+               return fmt.Errorf("unable to archive old backup file: %w", err)
        }
 
        // Finally, we'll attempt to atomically rename the temporary file to
@@ -185,10 +173,31 @@ func (b *MultiFile) ExtractMulti(keyChain keychain.KeyRing) (*Multi, error) {
        return packedMulti.Unpack(keyChain)
 }
 
-// createArchiveFile creates an archive file with a timestamped name in the
+// maybeCreateArchiveFile creates an archive file with a timestamped name in the
 // specified archive directory, and copies the contents of the main backup file
-// to the new archive file.
-func createArchiveFile(archiveDir string, fileName string) error {
+// to the new archive file. Unless the user opted out of archiving old backups,
+// or the old backup file doesn't exist.
+func (b *MultiFile) maybeCreateArchiveFile(archiveDir string,
+       fileName string) error {
+
+       // User can skip archiving of old backup files to save disk space.
+       if b.noBackupArchive {
+               log.Debug("Skipping archive of old backup file as configured")
+
+               return nil
+       }
+
+       // Archive the main backup file if it exists before replacing it with a
+       // new one.
+       oldFileExists := lnrpc.FileExists(b.fileName)
+       if !oldFileExists {
+               log.Debug("No old backup file to archive")
+
+               return nil
+       }
+
+       log.Infof("Archiving old channel backup to %v", b.archiveDir)
+
        // Generate archive file path with timestamped name.
        baseFileName := filepath.Base(fileName)
        timestamp := time.Now().Format("2006-01-02-15-04-05")

@Abdulkbk
Copy link
Contributor Author

Very clean and LGTM 🎉

Have two more nits. Do you want to address those, @Abdulkbk? Or should I merge? IMO they're not blocking, just nice to have.

I will address them. It will be a learning experience for me 👍

@Abdulkbk Abdulkbk force-pushed the archive-channel-backups branch from 55f328c to c415d84 Compare January 23, 2025 14:38
@guggero guggero self-requested a review January 23, 2025 18:09
@Abdulkbk Abdulkbk force-pushed the archive-channel-backups branch from c415d84 to c27c16a Compare January 24, 2025 09:38
@Abdulkbk
Copy link
Contributor Author

Ready for another look @guggero

In this commit, we first check if a previous backup file exists,
if it does we copy it to archive folder before replacing it with
a new backup file. We also added a test for archiving chan backups.
In this commit, we add the --no-backup-archive with a default
as false. When set to true then previous channel backup file will
not be archived but replaced. We also modify TestUpdateAndSwap
test to make sure the new behaviour works as expected.
@Abdulkbk Abdulkbk force-pushed the archive-channel-backups branch from c27c16a to 3bf1548 Compare January 24, 2025 09:59
Copy link
Collaborator

@guggero guggero left a comment

Choose a reason for hiding this comment

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

Very nice, tACK, LGTM 🎉

@guggero guggero merged commit baa34b0 into lightningnetwork:master Jan 24, 2025
30 of 34 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement Improvements to existing features / behaviour SCB Related to static channel backup size/kilo medium, proper context needed, less than 1000 lines
Projects
None yet
Development

Successfully merging this pull request may close these issues.

chanbackup/[feature]: add archive mode for channel back ups
5 participants