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

Open
wants to merge 3 commits into
base: master
Choose a base branch
from

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 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
@@ -117,6 +130,19 @@ func (b *MultiFile) UpdateAndSwap(newBackup PackedMulti) error {
return fmt.Errorf("unable to close file: %w", err)
}

// We check if the main backup file exists, if it does we archive it
// before replacing it with the new backup.
if _, err := os.Stat(b.fileName); err == nil {
Copy link
Member

Choose a reason for hiding this comment

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

Q: should we return the error here instead?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

If we return an error here, LND will fail to start during the first run because channel.backup does not exist then. Should we add a log here instead?

I will also update the comment to capture this.

Copy link
Member

Choose a reason for hiding this comment

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

I would consider this a two-step process - during the initialization phase, we create all the necessary dirs, similar to how to handle other file creation or db init, which is done in the config. Then the second phase is when we actually make updates to it - this way we can always catch errors earlier if the creation of the folder fails. That being said, it def needs more refactoring so maybe a future PR.

As for now, I think a debug log can be nice - so at least we won't let the error passes silently.

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 added a debug log 👍

config.go Outdated
@@ -360,6 +366,8 @@ type Config struct {
MaxPendingChannels int `long:"maxpendingchannels" description:"The maximum number of incoming pending channels permitted per peer."`
BackupFilePath string `long:"backupfilepath" description:"The target location of the channel backup file"`

DisableBackupArchive bool `long:"disable-backup-archive" description:"If set to true, channel backups will be deleted or replaced rather than being archived to a separate location."`
Copy link
Member

Choose a reason for hiding this comment

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

think it'd be better if we could name it ArchiveBackup - then we don't need to use a double negative to decide whether we wanna create this archive or not.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

The problem with this approach is when you try to disable this feature (since its enabled by default) using a CLI arg. Running the command lnd --archivebackup=false results in an error although setting archivebackup=false in the lnd.conf file works fine.
imageedit_0_3450861008

I think the alternative is to disable this feature by default and then the user can then run lnd --archivebackup to enable it without getting any errors. In this case there won't be any need for lnd --archivebackup=false

Copy link
Member

Choose a reason for hiding this comment

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

hmm ok so this is on by default, then nvm.

Copy link
Collaborator

Choose a reason for hiding this comment

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

Alternative naming would be no-backup-archive, which is a bit shorter and fits in better with other no- flags we have.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

now using the no-backup-archive, and it looks much neater.

docs/release-notes/release-notes-0.19.0.md Outdated Show resolved Hide resolved
chanbackup/backupfile.go Outdated Show resolved Hide resolved
@@ -94,7 +94,7 @@ func TestUpdateAndSwap(t *testing.T) {
},
}
for i, testCase := range testCases {
backupFile := NewMultiFile(testCase.fileName)
backupFile := NewMultiFile(testCase.fileName, false)
Copy link
Member

Choose a reason for hiding this comment

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

think this test should also be updated to check the new behavior, maybe a new test TestUpdateAndSwapWithArchive.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

The test is in the next commit ade9d50, I will squash it into the first commit.

Copy link
Member

Choose a reason for hiding this comment

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

yeah that test focuses on createArchiveFile, which is great, but we should also test NewMultiFile(filename, true) to check that when the archive flag is on, we correctly create the archive and swap the file.

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 updated the TestUpdateAndSwap to evaluate the new behavior. I think adding a new test would lead to much duplication.

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

} else {
log.Infof("Archiving old backup file at %v", b.fileName)

if err := createArchiveFile(
Copy link
Member

Choose a reason for hiding this comment

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

nit: this is pre-existing so no need to change, but for future PRs we'd prefer

err := createArchiveFile(...)
if err != nil {
...

as it saves more indentation space and IMO a bit nicer to read.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Noted 👍

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 have updated this to use the suggested

err := createArchiveFile(...)
if err != nil {
...

It's more readable like you mentioned 👍

},

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

Comment on lines 133 to 156
// Archive the existing main backup file before creating a new one.
// Note that if no backup file exists yet (e.g. on the first startup
// of the node), os.Stat will return an error, which we just log
// and not error out.
_, err = os.Stat(b.fileName)
if err != nil {
log.Debugf("Unable to get backup file info: %v", err)
} else {
log.Infof("Archiving old backup file at %v", b.fileName)

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

Copy link
Collaborator

Choose a reason for hiding this comment

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

I think all of this logic should go into createArchiveFile().
Then you don't need the } else { case here either, because you can just do:

	_, err = os.Stat(b.fileName)
	if err != nil {
		log.Debugf("Unable to get backup file info: %v", err)
		return nil
	}

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Now that I use the lnrpc.FileFileExists, the } else { is not there anymore.

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

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

}
defer func() {
if cerr := oldBackupFile.Close(); cerr != nil && err == nil {
err = fmt.Errorf("unable to close old backup file: %w",
Copy link
Collaborator

Choose a reason for hiding this comment

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

I think this assignment doesn't do anything, since we don't have a named return variable. So perhaps just log the error? Same further below.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Now logging the error 👍

{
name: "invalid archive directory permissions",
setup: func() {
// Create dir with no write permissions
Copy link
Collaborator

Choose a reason for hiding this comment

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

nit: missing punctuation in comment, here and below.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Fixed

); 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)
			}
		}
	}

)
// The archived content should match the previous
// backup (newPackedMulti) that was just swapped out.
assertBackupMatches(t, archiveFile, newPackedMulti)
Copy link
Collaborator

Choose a reason for hiding this comment

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

Just add a continue here? Whenever I see an } else { that indicates to me that something can probably be optimized to make reading the code more easy.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Done.

Whenever I see an } else { that indicates to me that something can probably be optimized to make reading the code more easy.

great to have this information 👍

config.go Outdated
@@ -360,6 +366,8 @@ type Config struct {
MaxPendingChannels int `long:"maxpendingchannels" description:"The maximum number of incoming pending channels permitted per peer."`
BackupFilePath string `long:"backupfilepath" description:"The target location of the channel backup file"`

DisableBackupArchive bool `long:"disable-backup-archive" description:"If set to true, channel backups will be deleted or replaced rather than being archived to a separate location."`
Copy link
Collaborator

Choose a reason for hiding this comment

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

Alternative naming would be no-backup-archive, which is a bit shorter and fits in better with other no- flags we have.

config.go Outdated
// channel backups. When false (default), old backups are archived to a
// designated location. When true, old backups are simply deleted or
// replaced.
defaultDisableBackupArchive = false
Copy link
Collaborator

Choose a reason for hiding this comment

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

A boolean value always has false as the default. I don't think we need this constant or any assignment in DefaultConfig().

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Fixed

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.
@Abdulkbk Abdulkbk force-pushed the archive-channel-backups branch from 1051ab4 to 76a3b56 Compare January 20, 2025 20:54
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 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
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