A modern, self-hosted backup solution for secure, encrypted backups across local and cloud storage.
fix: resolve replication frozen issue on stale lock
towfiqi5931b8579a15
diff --git a/backend/__tests__/managers/handlers/ReplicationHandler.test.ts b/backend/__tests__/managers/handlers/ReplicationHandler.test.tsindex 7f39381..aad169e 100644--- a/backend/__tests__/managers/handlers/ReplicationHandler.test.ts+++ b/backend/__tests__/managers/handlers/ReplicationHandler.test.ts@@ -334,9 +334,9 @@ describe('ReplicationHandler', () => {// Check that relevant progress actions were calledconst actionCalls = mockUpdateReplicationAction.mock.calls.map((c: any) => c[3]);+ expect(actionCalls).toContain('REPLICATION_START');+ expect(actionCalls).toContain('REPLICATION_UNLOCK_START');expect(actionCalls).toContain('REPLICATION_COPY_START');- expect(actionCalls).toContain('REPLICATION_INIT_START');- expect(actionCalls).toContain('REPLICATION_INIT_COMPLETE');expect(actionCalls).toContain('REPLICATION_COPY_COMPLETE');expect(actionCalls).toContain('REPLICATION_COMPLETE');});@@ -425,10 +425,11 @@ describe('ReplicationHandler', () => {});it('should report REPLICATION_INIT_FAILED when repo init fails', async () => {- // First call is snapshots check (fails = repo doesn't exist)+ // First call is repo config check (code 10 = repo doesn't exist)// Second call is init (also fails)+ const repoMissingError = Object.assign(new Error('repo not found'), { code: 10 });mockRunResticCommand- .mockRejectedValueOnce(new Error('repo not found'))+ .mockRejectedValueOnce(repoMissingError).mockRejectedValueOnce(new Error('Init permission denied'));const results = await handler.replicateSnapshot(@@ -452,12 +453,17 @@ describe('ReplicationHandler', () => {describe('cancelReplications', () => {it('should kill all active replication processes for a backup', async () => {// Start a replication that we can check tracking for+ let copyStartedResolve: Function;+ const copyStartedPromise = new Promise(resolve => {+ copyStartedResolve = resolve;+ });let copyResolve: Function;const copyPromise = new Promise(resolve => {copyResolve = resolve;});mockRunResticCommand.mockImplementation(async (args: string[]) => {if (args.includes('copy')) {+ copyStartedResolve!('started');// Simulate a long-running copyawait copyPromise;}@@ -476,8 +482,8 @@ describe('ReplicationHandler', () => {retryInfo);- // Give it a tick to start- await new Promise(resolve => setTimeout(resolve, 10));+ // Wait until copy starts so the replication is definitely active+ await copyStartedPromise;// Cancelawait handler.cancelReplications(backupId);diff --git a/backend/src/managers/handlers/ReplicationHandler.ts b/backend/src/managers/handlers/ReplicationHandler.tsindex a4c4b6f..1632f81 100644--- a/backend/src/managers/handlers/ReplicationHandler.ts+++ b/backend/src/managers/handlers/ReplicationHandler.ts@@ -147,27 +147,20 @@ export class ReplicationHandler {planId,backupId,replicationId,- 'REPLICATION_COPY_START',+ 'REPLICATION_START',false);const destRepoPath = generateResticRepoPath(storageName, storagePath);// Step 1: Ensure replication repo is initialized (with chunker params from source)- await this.progressManager.updateReplicationAction(- planId,- backupId,- replicationId,- 'REPLICATION_INIT_START',- false- );-try {await this.ensureRepoInitialized(destRepoPath,sourceRepoPath,password,encryption,+ planId,backupId,replicationId);@@ -184,20 +177,19 @@ export class ReplicationHandler {throw initError;}- await this.progressManager.updateReplicationAction(- planId,- backupId,- replicationId,- 'REPLICATION_INIT_COMPLETE',- true- );-// Check for cancellationif (this.cancelledBackups.has(planId)) {throw new Error('Cancelled by user');}// Step 2: Unlock stale locks (non-fatal)+ await this.progressManager.updateReplicationAction(+ planId,+ backupId,+ replicationId,+ 'REPLICATION_UNLOCK_START',+ true+ );try {const unlockArgs = ['unlock', '-r', destRepoPath];if (!encryption) unlockArgs.push('--insecure-no-password');@@ -215,6 +207,15 @@ export class ReplicationHandler {// Non-fatal - swallow errors}+ // Step 2: Unlock stale locks (non-fatal)+ await this.progressManager.updateReplicationAction(+ planId,+ backupId,+ replicationId,+ 'REPLICATION_COPY_START',+ true+ );+// Step 3: Run restic copyconst copyArgs = ['-r',@@ -449,8 +450,9 @@ export class ReplicationHandler {sourceRepoPath: string,password: string,encryption: boolean,- backupId?: string,- replicationId?: string+ planId: string,+ backupId: string,+ replicationId: string): Promise<void> {if (this.initializedRepos.has(repoPath)) {return;@@ -463,8 +465,8 @@ export class ReplicationHandler {};try {- // Try to list snapshots to check if repo exists- const checkArgs = ['snapshots', '-r', repoPath, '--json'];+ // Check if the repo exists in replication storage+ const checkArgs = ['cat', 'config', '--no-lock', '-r', repoPath];if (!encryption) checkArgs.push('--insecure-no-password');await runResticCommand(checkArgs,@@ -475,34 +477,61 @@ export class ReplicationHandler {trackProcess);this.initializedRepos.add(repoPath);- } catch (error) {- // Repo doesn't exist, initialize it with chunker params from source for deduplication- try {- const initArgs = [- '-r',- repoPath,- 'init',- '--from-repo',- sourceRepoPath,- '--copy-chunker-params',- ];- if (!encryption) {- initArgs.push('--insecure-no-password');- initArgs.push('--from-insecure-no-password');- }- const initEnv: Record<string, string> = {- RESTIC_PASSWORD: password,- RESTIC_FROM_PASSWORD: password,- };- await runResticCommand(initArgs, initEnv, undefined, undefined, undefined, trackProcess);- this.initializedRepos.add(repoPath);- } catch (initError: any) {- // If init also fails with "already initialized", that's OK- if (initError.message?.includes('already initialized')) {+ } catch (error: any) {+ if (error.code === 10) {+ // Repo doesn't exist+ await this.progressManager.updateReplicationAction(+ planId,+ backupId,+ replicationId,+ 'REPLICATION_INIT_START',+ false+ );++ //initialize it with chunker params from source for deduplication+ try {+ const initArgs = [+ '-r',+ repoPath,+ 'init',+ '--from-repo',+ sourceRepoPath,+ '--copy-chunker-params',+ ];+ if (!encryption) {+ initArgs.push('--insecure-no-password');+ initArgs.push('--from-insecure-no-password');+ }+ const initEnv: Record<string, string> = {+ RESTIC_PASSWORD: password,+ RESTIC_FROM_PASSWORD: password,+ };+ await runResticCommand(initArgs, initEnv, undefined, undefined, undefined, trackProcess);this.initializedRepos.add(repoPath);- } else {- throw initError;+ await this.progressManager.updateReplicationAction(+ planId,+ backupId,+ replicationId,+ 'REPLICATION_INIT_COMPLETE',+ true+ );+ } catch (initError: any) {+ // If init also fails with "already initialized", that's OK+ if (initError.message?.includes('already initialized')) {+ this.initializedRepos.add(repoPath);+ } else {+ throw initError;+ }}+ } else if (error.code === 11) {+ // failed to lock repo - likely due to stale lock from previous replication attempt.+ // do not throw we want to attempt to unlock and continue - the copy command will handle any remaining lock issues.+ console.log(+ 'Repo is locked, likely from a previous failed replication attempt. Will attempt to unlock and continue.',+ repoPath+ );+ } else {+ throw error;}}}diff --git a/backend/src/types/restic.ts b/backend/src/types/restic.tsindex ebe36a6..48a0bf2 100644--- a/backend/src/types/restic.ts+++ b/backend/src/types/restic.ts@@ -65,3 +65,8 @@ export interface ResticRestoredFile {action: string;isDirectory?: boolean;}++export type ResticCommandError = Error & {+ code?: number;+ stderr?: string;+};diff --git a/backend/src/utils/restic/restic.ts b/backend/src/utils/restic/restic.tsindex 3a5c38d..b65c8d5 100644--- a/backend/src/utils/restic/restic.ts+++ b/backend/src/utils/restic/restic.ts@@ -10,6 +10,11 @@ import { configService } from '../../services/ConfigService';import { buildResticEnvFromSettings, buildRcloneEnvFromSettings } from '../globalSettings';import { BackupVerifiedResult } from '../../types/plans';+export type ResticCommandError = Error & {+ code?: number;+ stderr?: string;+};+export function runResticCommand(args: string[],env?: Record<string, string>,@@ -56,6 +61,8 @@ export function runResticCommand(path.join(appPaths.getTempDir(), 'restic-cache'),];+ // console.log('🎷', 'restic ', finalArgs.join(' '));+// if an empty password is passed, it means encryption is disabled, so we avoid restic prompting for a passwordif ((envVars as Record<string, string>)?.RESTIC_PASSWORD === '') {finalArgs.push('--insecure-no-password');@@ -136,8 +143,13 @@ export function runResticCommand(if (code === 0) {resolve(output.trim());} else {- console.log('Restic Error :', errorOutput.trim() || 'Restic command failed');- const error = new Error(errorOutput.trim() || 'Restic command failed');+ const stderr = errorOutput.trim();+ console.log('Restic Error :', stderr || 'Restic command failed');+ const error: ResticCommandError = new Error(+ stderr || 'Restic command failed with code ' + code+ );+ error.code = code;+ error.stderr = stderr;onError?.(Buffer.from(error.message));reject(error);}