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(recurring-job): support system backup task #3476

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

Conversation

c3y1huang
Copy link
Contributor

Which issue(s) this PR fixes:

Issue longhorn/longhorn#6534

What this PR does / why we need it:

Support system backup task in the recurring job.

Special notes for your reviewer:

None

Additional documentation or context

None

longhorn/longhorn-6534

Signed-off-by: Chin-Ya Huang <[email protected]>
longhorn/longhorn-6534

Signed-off-by: Chin-Ya Huang <[email protected]>
@c3y1huang c3y1huang self-assigned this Jan 14, 2025
Copy link

coderabbitai bot commented Jan 14, 2025

Walkthrough

This pull request introduces a comprehensive implementation of recurring system backups for Longhorn, a Kubernetes storage system. The changes involve creating a new package recurringjob with modular functions for managing system backup jobs, updating type definitions, and extending existing infrastructure to support a new recurring job type. The implementation allows users to configure system backups with retention policies and automatic scheduling, addressing the need for systematic and predictable system backup management.

Changes

File Change Summary
app/post_upgrade.go, app/pre_upgrade.go Replaced local createEventBroadcaster with imported apputil.CreateEventBroadcaster
app/recurring_job.go Refactored job management, removed Job struct, delegated logic to recurringjob package
app/recurringjob/* New package with comprehensive system backup and volume job management utilities
datastore/longhorn.go Updated recurring job parameter validation, added system backup validation
k8s/crds.yaml Updated CRD descriptions and added system backup task type
types/types.go Renamed and added constants for recurring job parameters

Assessment against linked issues

Objective Addressed Explanation
Implement recurring system backup
Support volume backup policy
Provide retention mechanism

Possibly related PRs

Suggested reviewers

  • innobead
  • derekbit
  • ChanYiLin

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.

longhorn/longhorn-6534

Signed-off-by: Chin-Ya Huang <[email protected]>
@c3y1huang c3y1huang force-pushed the 6534-recurring-system-backup branch from cab0f1c to 33cc9a5 Compare January 14, 2025 07:44
@c3y1huang
Copy link
Contributor Author

@coderabbitai review

Copy link

coderabbitai bot commented Jan 14, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

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

🧹 Nitpick comments (11)
app/post_upgrade.go (1)

Line range hint 144-149: Consider improving error handling in pod list retrieval.

The error handling in the pod list retrieval could be more informative. Consider including more context in the warning message.

-			logrus.Warnf("failed to list pods: %v", err)
+			logrus.Warnf("failed to list manager pods in namespace %s: %v", u.namespace, err)
app/recurring_job.go (3)

14-14: Ensure imported packages are necessary and used.

The newly added import for "github.com/longhorn/longhorn-manager/types" should be verified for usage within the file. If the types from this package are not used in the current code, consider removing the import to keep the code clean.


55-59: Handle potential error when getting Longhorn clientset.

The function recurringjob.GetLonghornClientset() may return an error that should be handled appropriately. Ensure that the error logging provides enough context for debugging.

Consider enhancing the error message to include additional context:

	lhClient, err := recurringjob.GetLonghornClientset()
	if err != nil {
-		return errors.Wrap(err, "failed to get clientset")
+		return errors.Wrap(err, "failed to get Longhorn clientset in recurringJob")
	}

76-80: Validate the handling of different recurring job types in the switch statement.

The switch statement introduces support for longhorn.RecurringJobTypeSystemBackup. Ensure that all desired recurring job types are properly handled and that the default case correctly starts volume jobs.

Also, consider adding a default case to handle unexpected job types, possibly logging an error or warning.

Example:

	default:
		return recurringjob.StartVolumeJobs(job, recurringJob)
+	default:
+		job.logger.Errorf("Unknown recurring job type: %v", recurringJob.Spec.Task)
+		return fmt.Errorf("unknown recurring job type: %v", recurringJob.Spec.Task)
app/recurringjob/type.go (3)

17-29: Consider encapsulating client interfaces for better testability.

The Job struct contains concrete clients like *longhornclient.RancherClient and *lhclientset.Clientset. To improve testability and reduce coupling, consider injecting interfaces instead of concrete types.

Define interfaces that encapsulate the required methods and update the Job struct to use these interfaces. This approach facilitates mocking dependencies during testing.

Example:

type RancherClientInterface interface {
	// Define required methods
}

type ClientsetInterface interface {
	// Define required methods
}

type Job struct {
	api      RancherClientInterface
	lhClient ClientsetInterface
	// ...
}

31-43: Ensure consistency in logging fields.

The VolumeJob struct includes a logger field, which might duplicate the logger in the embedded Job struct. Verify if this duplication is necessary or if the Job's logger can be reused to maintain consistency.

If a separate logger is required, ensure that it includes context from both the Job and VolumeJob structs. Otherwise, consider removing the redundant logger field.

Example:

type VolumeJob struct {
	*Job
-	logger logrus.FieldLogger
	// ...
}

45-54: Clarify the purpose of SystemBackupJob fields.

Ensure that the fields systemBackupName and volumeBackupPolicy in the SystemBackupJob struct are correctly initialized and used. Provide comments to explain their roles in the system backup process.

Consider adding comments to explain these fields:

type SystemBackupJob struct {
	*Job

	// systemBackupName is the name assigned to the system backup job instance.
	systemBackupName string

	// volumeBackupPolicy defines the backup policy for volumes during system backup.
	volumeBackupPolicy longhorn.SystemBackupCreateVolumeBackupPolicy
}
app/recurringjob/systembackup.go (2)

55-60: Avoid redundant logger fields in SystemBackupJob.

Similar to VolumeJob, SystemBackupJob includes a logger field that may duplicate the logger from the embedded Job struct. Evaluate if it's necessary to have a separate logger or if the existing one can be utilized with added context.

If additional context is needed, consider extending the existing logger rather than introducing a new field.

Example:

job.logger = job.logger.WithFields(logrus.Fields{
	// additional fields
})

104-122: Optimize cleanup of expired system backups.

In the cleanup method, the deletion of expired backups happens sequentially. For a large number of backups, this might be inefficient. Consider parallelizing deletions or implementing batching to improve performance.

Example:

var wg sync.WaitGroup
for _, systemBackupName := range expiredSystemBackups {
	wg.Add(1)
	go func(name string) {
		defer wg.Done()
		job.logger.Infof("Deleting system backup %v", name)
		err := job.DeleteSystemBackup(name)
		if err != nil {
			job.logger.WithError(err).Warnf("Failed to delete system backup %v", name)
		}
	}(systemBackupName)
}
wg.Wait()

Ensure that concurrency is handled safely, especially if the underlying client is not thread-safe.

app/recurringjob/volume.go (1)

260-274: Fix typo in function name waitForSnaphotReady

The function name waitForSnaphotReady contains a typo. It should be waitForSnapshotReady.

Apply this diff to correct the typo and update references:

-func (job *VolumeJob) waitForSnaphotReady(volume *longhornclient.Volume, timeout int) error {
+func (job *VolumeJob) waitForSnapshotReady(volume *longhornclient.Volume, timeout int) error {

Also, update the function call:

-    if err := job.waitForSnaphotReady(volume, SnapshotReadyTimeout); err != nil {
+    if err := job.waitForSnapshotReady(volume, SnapshotReadyTimeout); err != nil {
app/recurringjob/constant.go (1)

6-6: Fix typo in constant name HTTPClientTimout

The constant HTTPClientTimout has a typo in its name. It should be HTTPClientTimeout.

Apply this diff to correct the typo:

-	HTTPClientTimout = 1 * time.Minute
+	HTTPClientTimeout = 1 * time.Minute

Also, update any references to this constant in the codebase.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7c50e4f and 33cc9a5.

📒 Files selected for processing (14)
  • app/post_upgrade.go (2 hunks)
  • app/pre_upgrade.go (2 hunks)
  • app/recurring_job.go (2 hunks)
  • app/recurringjob/constant.go (1 hunks)
  • app/recurringjob/job.go (1 hunks)
  • app/recurringjob/systembackup.go (1 hunks)
  • app/recurringjob/type.go (1 hunks)
  • app/recurringjob/util.go (1 hunks)
  • app/recurringjob/volume.go (1 hunks)
  • app/util/util.go (2 hunks)
  • datastore/longhorn.go (3 hunks)
  • k8s/crds.yaml (73 hunks)
  • k8s/pkg/apis/longhorn/v1beta2/recurringjob.go (5 hunks)
  • types/types.go (1 hunks)
🧰 Additional context used
🪛 GitHub Check: CodeFactor
app/recurringjob/volume.go

[notice] 427-542: app/recurringjob/volume.go#L427-L542
Complex Method

⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Build binaries
  • GitHub Check: Summary
🔇 Additional comments (21)
app/util/util.go (2)

1-1: LGTM! Good package organization.

Moving this utility function to a dedicated util package improves code organization and reusability.


Line range hint 21-22: Consider addressing the TODO comment about client wrapper.

The comment indicates temporary code that should be removed when clients move to use the clientset. This technical debt should be tracked.

Would you like me to create a GitHub issue to track the removal of this wrapper once all clients have moved to use the clientset?

app/pre_upgrade.go (1)

19-19: LGTM! Clean integration with util package.

The changes correctly integrate the moved CreateEventBroadcaster function from the util package while maintaining existing error handling.

Also applies to: 63-63

app/post_upgrade.go (1)

25-25: LGTM! Clean integration with util package.

The changes correctly integrate the moved CreateEventBroadcaster function from the util package while maintaining existing error handling.

Also applies to: 70-70

app/recurringjob/type.go (1)

56-60: Ensure thread safety when handling time-related data.

The NameWithTimestamp struct might be used in concurrent operations. Verify that any usage of this struct in concurrent contexts handles synchronization appropriately to prevent race conditions.

If the struct is accessed concurrently, consider using synchronization mechanisms or immutable data patterns.

app/recurringjob/systembackup.go (1)

41-42: Ensure uniqueness and validity of generated system backup names.

The systemBackupName generation truncates and concatenates strings, which may lead to non-unique names if not carefully handled. Confirm that the generated names are unique and conform to Kubernetes naming conventions.

Consider including a timestamp or a UUID to ensure uniqueness:

systemBackupName := fmt.Sprintf("%s-%s", sliceStringSafely(types.GetCronJobNameForRecurringJob(job.name), 0, 8), util.UUID())
app/recurringjob/job.go (1)

1-131: The implementation in job.go is well-structured and clear

The code defines the Job struct and associated methods effectively. Initialization, error handling, and client configurations are appropriately managed.

k8s/pkg/apis/longhorn/v1beta2/recurringjob.go (4)

5-5: LGTM: Validation enum updated to include system backup task

The validation enum is properly updated to include system-backup as a valid recurring job type.

Also applies to: 16-16


42-44: LGTM: Task field documentation updated

The Task field documentation is properly updated to include the new system-backup option.


58-60: LGTM: Parameters field documentation updated

The Parameters field documentation is properly updated to include the new volume-backup-policy parameter.


79-79: LGTM: Print column description updated

The print column description is properly updated to include the new system-backup option.

app/recurringjob/util.go (1)

1-168: LGTM: Well-structured utility package for recurring jobs

The new utility package provides a clean implementation of recurring job management functions with proper error handling and logging.

types/types.go (1)

238-239: LGTM: New recurring job parameter constants

The new constants for recurring job parameters follow the project's naming conventions.

datastore/longhorn.go (2)

5016-5030: LGTM: Validation logic for recurring job parameters

The validation logic for recurring job parameters is properly implemented with appropriate error handling.


5045-5046: LGTM: System backup added to valid recurring job tasks

The system backup task is properly added to the list of valid recurring job tasks.

k8s/crds.yaml (6)

2753-2756: LGTM: Description for groups field is clear and accurate.

The description for the groups field in the RecurringJob CRD accurately explains that when set to "default", the group will be added to the volume label when no other job label exists in the volume.


2757-2760: LGTM: Task field description is comprehensive and includes the new system-backup type.

The description for the task field in the RecurringJob CRD has been updated to include all valid task types, including the newly added "system-backup" task.


2829-2829: LGTM: Parameters field description is accurate.

The description for the parameters field in the RecurringJob CRD spec clearly lists the supported parameters: "full-backup-interval" and "volume-backup-policy".


Line range hint 2837-2846: LGTM: Task field enumeration is complete and includes system-backup.

The task field enumeration in the RecurringJob CRD spec has been updated to include all valid task types:

  • Existing tasks: snapshot, snapshot-force-create, snapshot-cleanup, snapshot-delete, backup, backup-force-create, filesystem-trim
  • New task: system-backup

2850-2856: LGTM: Status fields are well documented.

The RecurringJobStatus fields are well documented:

  • executionCount: Tracks the number of jobs triggered
  • ownerID: Identifies the controller responsible for reconciliation

Line range hint 2694-2757: Verify system-backup task integration in printer columns.

The printer columns configuration should be reviewed to ensure it properly displays system backup information.

Run this script to verify the printer columns configuration:

✅ Verification successful

System-backup task integration is properly configured

The system-backup task is correctly integrated in the CRD configuration with proper printer columns and documentation.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if printer columns configuration needs updating for system backup task

# Search for printer column definitions that might need updating for system backup
rg -A 5 'additionalPrinterColumns:.*task' k8s/crds.yaml

# Search for any potential missing system backup related columns
rg -i 'system.?backup' k8s/crds.yaml

Length of output: 1633

app/recurring_job.go Show resolved Hide resolved
app/recurringjob/systembackup.go Show resolved Hide resolved
app/recurringjob/systembackup.go Show resolved Hide resolved
app/recurringjob/systembackup.go Show resolved Hide resolved
app/recurringjob/volume.go Show resolved Hide resolved
app/recurringjob/volume.go Show resolved Hide resolved
@c3y1huang
Copy link
Contributor Author

@c3y1huang c3y1huang marked this pull request as ready for review January 14, 2025 12:48
@c3y1huang c3y1huang requested review from derekbit and a team January 14, 2025 12:49
Copy link
Contributor

@james-munson james-munson left a comment

Choose a reason for hiding this comment

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

Still reviewing, but I wanted to ask this question about crds.yaml.

@@ -19,8 +19,7 @@ spec:
scope: Namespaced
versions:
- additionalPrinterColumns:
- description: The current state of the pod used to provision the backing image
file from source
- description: The current state of the pod used to provision the backing image file from source
jsonPath: .status.currentState
Copy link
Contributor

Choose a reason for hiding this comment

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

Is there a war between yaml formatters on this file? Two days ago, commit a6cb36e split this and other long descriptions from a single line into multiple lines. Now they are being reverted into a single line again. IIRC, I've seen it go back and forth more than once.

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 am not sure, but this is the output I got after running k8s/generate_code.sh. Could you try running the script on your end and let me know if it comes out differently?

Copy link
Contributor

Choose a reason for hiding this comment

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

Interesting. I get this output:

jmunson@JMunson:~/repos/Longhorn/longhorn-manager$ ./k8s/generate_code.sh 
controller-gen is missing
Prepare to install controller-gen
go: sigs.k8s.io/[email protected] requires go >= 1.22.0; switching to go1.22.10
kustomize is missing
Prepare to install kustomize
~/go/src/github.com/kubernetes-sigs ~/repos/Longhorn/longhorn-manager
~/repos/Longhorn/longhorn-manager
Generating deepcopy funcs
Generating clientset for longhorn:v1beta1,v1beta2 at github.com/longhorn/longhorn-manager/k8s/pkg/client/clientset
Generating listers for longhorn:v1beta1,v1beta2 at github.com/longhorn/longhorn-manager/k8s/pkg/client/listers
Generating informers for longhorn:v1beta1,v1beta2 at github.com/longhorn/longhorn-manager/k8s/pkg/client/informers
Generating CRD
./k8s/generate_code.sh: line 68: controller-gen: command not found

And it doesn't touch crds.yaml

Copy link
Contributor

Choose a reason for hiding this comment

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

jmunson@JMunson:~/repos/Longhorn/longhorn-manager$ go version
go version go1.23.4 linux/amd64

Copy link
Contributor

Choose a reason for hiding this comment

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

My gopath was not in my PATH.

When I run it, I get the multi-line descriptions

Copy link
Contributor

Choose a reason for hiding this comment

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

Seems like this whole question will be resolved by longhorn/longhorn#10193.

Copy link
Contributor

@james-munson james-munson left a comment

Choose a reason for hiding this comment

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

LGTM. A clean refactoring. One other small nit.

}

job.logger.Infof("Waiting for system backup to reach state %v, current state is %v", expectedStates, systemBackup.Status.State)
time.Sleep(5 * time.Second)
Copy link
Contributor

Choose a reason for hiding this comment

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

Would it be reasonable to use the named constant WaitInterval here?

@derekbit derekbit requested a review from mantissahz January 18, 2025 03:18
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.

2 participants