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

feat(commands): add backup command #9

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

Conversation

steveiliop56
Copy link
Collaborator

@steveiliop56 steveiliop56 commented Jan 23, 2024

Summary by CodeRabbit

  • New Features
    • Introduced a backup command to create backups of specific directories and the "Tipi" service.
  • Enhancements
    • Implemented automatic creation of a "backups" directory to organize backup files.

Copy link
Contributor

coderabbitai bot commented Jan 23, 2024

Walkthrough

The codebase now includes a new backup feature. It introduces a command to back up a specified directory, halt the "Tipi" service, and ensure its data is preserved using Docker and tar. The changes integrate this functionality into the system, including updates to the command handling and system utilities to support backup creation and storage.

Changes

Files Change Summary
src/args.rs Added Backup variant to RuntipiMainCommand enum.
src/commands/backup.rs Created to handle backup creation and "Tipi" service.
src/commands/mod.rs Included backup module in public interface.
src/main.rs Implemented Backup command handling.
src/utils/system.rs Added "backups" directory creation in "media" directory.

Poem

🐇✨
In the burrow of the code, a backup's now in store,
A hop, a skip, a service stop, and tar does seal the lore.
Tipi's data safe and sound, in Docker's gentle keep,
CodeRabbit leaps with joy, as systems rest in sleep. 🌙💾

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>.
    • Generate unit-tests for this file.
  • 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 tests 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 generate interesting stats about this repository from git and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit tests.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

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 as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger a review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • The JSON schema for the configuration file is available here.
  • 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/coderabbit-overrides.v2.json

CodeRabbit Discord Community

Join our Discord Community to get help, request features, and share feedback.

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.

Review Status

Actionable comments generated: 2

Configuration used: CodeRabbit UI

Commits Files that changed from the base of the PR and between 5e063b1 and a07957f.
Files ignored due to path filters (2)
  • Cargo.lock is excluded by: !**/*.lock
  • Cargo.toml is excluded by: !**/*.toml
Files selected for processing (5)
  • src/args.rs (1 hunks)
  • src/commands/backup.rs (1 hunks)
  • src/commands/mod.rs (1 hunks)
  • src/main.rs (1 hunks)
  • src/utils/system.rs (1 hunks)
Files skipped from review due to trivial changes (2)
  • src/commands/mod.rs
  • src/utils/system.rs
Additional comments: 2
src/main.rs (1)
  • 34-36: The implementation for the Backup command in the main function is straightforward and follows the existing pattern for other commands. However, ensure that the commands::backup::run() function is designed to handle any required arguments or configurations that might be needed for the backup process.
Verification successful

The rg command has successfully located the run function within the backup.rs file, and the output indicates that the function does not take any arguments. This confirms that the run function is designed to be called without any parameters, as is done in the main.rs file.

Based on this information, the review comment suggesting to ensure that the commands::backup::run() function is designed to handle any required arguments or configurations is not applicable, as the function signature indicates that it does not accept any arguments.

Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Verify that the backup command does not require additional arguments.
ast-grep --lang rust --pattern $'fn run($_) { $$$ }' src/commands/backup.rs

Length of output: 76



Script:

#!/bin/bash
# Verify the signature of the `run` function in the `backup.rs` file.
ast-grep --lang rust --pattern $'fn run($$$) { $$$ }' src/commands/backup.rs

Length of output: 77



Script:

#!/bin/bash
# Use ripgrep to search for the `run` function within the `backup.rs` file.
rg "fn run" src/commands/backup.rs

Length of output: 51

src/args.rs (1)
  • 55-56: The addition of the Backup variant to the RuntipiMainCommand enum is consistent with the existing command structure. Ensure that the documentation for the Backup command is clear and provides enough information for users to understand its purpose and usage.

Comment on lines +6 to +42
pub fn run() {
let spin = spinner::new("");
let root_folder: PathBuf = env::current_dir().expect("Unable to get current directory");

spin.set_message("Creating backup directory...");

if let Err(e) = fs::create_dir_all(root_folder.join("backups")) {
spin.fail(e.to_string().as_str());
spin.finish();
process::exit(1);
}

spin.succeed("Created backup directory");

spin.set_message("Stopping Tipi...");

let args = vec!["down", "--remove-orphans", "--rmi", "local"];

process::Command::new("docker")
.arg("compose")
.args(&args)
.output()
.expect("Failed to stop containers. Cannot continue with backup");

spin.succeed("Tipi successfully stopped");

spin.set_message("Backing up tipi...");

if let Err(e) = backup(root_folder) {
spin.fail(e.to_string().as_str());
spin.finish();
return;
}

spin.succeed("Tipi Backed Up!");
spin.finish();
}
Copy link
Contributor

Choose a reason for hiding this comment

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

The run function in backup.rs is responsible for creating the backup directory, stopping the "Tipi" service, and performing the backup. The error handling within this function exits the process immediately upon encountering an error, which may not be the best approach. Consider returning a Result type and allowing the caller to decide how to handle the error.

- process::exit(1);
+ return Err(e);

Comment on lines +44 to +58
pub fn backup(root_folder: PathBuf) -> Result<(), Error> {
let datetime = chrono::Utc::now();
let parent_folder = root_folder.parent().unwrap();
let root_folder_string = root_folder.to_str().unwrap();
let filename = format!("runtipi-backup-{}.tar.gz", datetime.format("%d-%m-%Y"));
let tar_path = format!("{}/{}", parent_folder.to_str().unwrap(), filename);
let backups_folder = format!("{}/backups/{}", root_folder_string, filename);

env::set_current_dir(&parent_folder)?;

process::Command::new("tar").args(["-czvf", &filename, &root_folder_string]).output().expect("Failed to run tar command");
fs::rename(tar_path, backups_folder).expect("Failed to move the tar archive.");

Ok(())
}
Copy link
Contributor

Choose a reason for hiding this comment

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

The backup function creates a tarball of the current directory. Ensure that the backup includes all necessary files and that no sensitive information is inadvertently included in the backup. Additionally, the use of unwrap could cause a panic if the parent() or to_str() calls fail. Replace unwrap with proper error handling.

- let parent_folder = root_folder.parent().unwrap();
- let root_folder_string = root_folder.to_str().unwrap();
+ let parent_folder = root_folder.parent().ok_or_else(|| Error::new(ErrorKind::Other, "Failed to get parent directory"))?;
+ let root_folder_string = root_folder.to_str().ok_or_else(|| Error::new(ErrorKind::Other, "Failed to convert root folder to string"))?;

@steveiliop56 steveiliop56 marked this pull request as draft February 10, 2024 14:59
@meienberger meienberger changed the base branch from main to develop March 8, 2024 07:56
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant