2021-05-17 00:39:33 +08:00
// Package bisync implements bisync
// Copyright (c) 2017-2020 Chris Nelson
package bisync
import (
"context"
"crypto/md5"
"encoding/hex"
2021-11-04 18:12:57 +08:00
"errors"
"fmt"
2021-05-17 00:39:33 +08:00
"io"
"os"
"path/filepath"
"strings"
"time"
"github.com/rclone/rclone/cmd"
"github.com/rclone/rclone/cmd/bisync/bilib"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/fs/config"
"github.com/rclone/rclone/fs/config/flags"
"github.com/rclone/rclone/fs/filter"
"github.com/rclone/rclone/fs/hash"
"github.com/spf13/cobra"
)
2023-10-07 04:38:47 +08:00
// TestFunc allows mocking errors during tests
type TestFunc func ( )
2021-05-17 00:39:33 +08:00
// Options keep bisync options
type Options struct {
2023-07-11 18:40:01 +08:00
Resync bool
CheckAccess bool
CheckFilename string
CheckSync CheckSyncMode
2023-07-11 19:09:06 +08:00
CreateEmptySrcDirs bool
2023-07-11 18:40:01 +08:00
RemoveEmptyDirs bool
MaxDelete int // percentage from 0 to 100
Force bool
FiltersFile string
Workdir string
2023-11-12 23:34:38 +08:00
OrigBackupDir string
BackupDir1 string
BackupDir2 string
2023-07-11 18:40:01 +08:00
DryRun bool
NoCleanup bool
SaveQueues bool // save extra debugging files (test only flag)
IgnoreListingChecksum bool
2023-07-11 18:57:49 +08:00
Resilient bool
bisync: Graceful Shutdown, --recover from interruptions without --resync - fixes #7470
Before this change, bisync had no mechanism to gracefully cancel a sync early
and exit in a clean state. Additionally, there was no way to recover on the
next run -- any interruption at all would cause bisync to require a --resync,
which made bisync more difficult to use as a scheduled background process.
This change introduces a "Graceful Shutdown" mode and --recover flag to
robustly recover from even un-graceful shutdowns.
If --recover is set, in the event of a sudden interruption or other un-graceful
shutdown, bisync will attempt to automatically recover on the next run, instead
of requiring --resync. Bisync is able to recover robustly by keeping one
"backup" listing at all times, representing the state of both paths after the
last known successful sync. Bisync can then compare the current state with this
snapshot to determine which changes it needs to retry. Changes that were synced
after this snapshot (during the run that was later interrupted) will appear to
bisync as if they are "new or changed on both sides", but in most cases this is
not a problem, as bisync will simply do its usual "equality check" and learn
that no action needs to be taken on these files, since they are already
identical on both sides.
In the rare event that a file is synced successfully during a run that later
aborts, and then that same file changes AGAIN before the next run, bisync will
think it is a sync conflict, and handle it accordingly. (From bisync's
perspective, the file has changed on both sides since the last trusted sync,
and the files on either side are not currently identical.) Therefore, --recover
carries with it a slightly increased chance of having conflicts -- though in
practice this is pretty rare, as the conditions required to cause it are quite
specific. This risk can be reduced by using bisync's "Graceful Shutdown" mode
(triggered by sending SIGINT or Ctrl+C), when you have the choice, instead of
forcing a sudden termination.
--recover and --resilient are similar, but distinct -- the main difference is
that --resilient is about _retrying_, while --recover is about _recovering_.
Most users will probably want both. --resilient allows retrying when bisync has
chosen to abort itself due to safety features such as failing --check-access or
detecting a filter change. --resilient does not cover external interruptions
such as a user shutting down their computer in the middle of a sync -- that is
what --recover is for.
"Graceful Shutdown" mode is activated by sending SIGINT or pressing Ctrl+C
during a run. Once triggered, bisync will use best efforts to exit cleanly
before the timer runs out. If bisync is in the middle of transferring files, it
will attempt to cleanly empty its queue by finishing what it has started but
not taking more. If it cannot do so within 30 seconds, it will cancel the
in-progress transfers at that point and then give itself a maximum of 60
seconds to wrap up, save its state for next time, and exit. With the -vP flags
you will see constant status updates and a final confirmation of whether or not
the graceful shutdown was successful.
At any point during the "Graceful Shutdown" sequence, a second SIGINT or Ctrl+C
will trigger an immediate, un-graceful exit, which will leave things in a
messier state. Usually a robust recovery will still be possible if using
--recover mode, otherwise you will need to do a --resync.
If you plan to use Graceful Shutdown mode, it is recommended to use --resilient
and --recover, and it is important to NOT use --inplace, otherwise you risk
leaving partially-written files on one side, which may be confused for real
files on the next run. Note also that in the event of an abrupt interruption, a
lock file will be left behind to block concurrent runs. You will need to delete
it before you can proceed with the next run (or wait for it to expire on its
own, if using --max-lock.)
2023-12-03 13:38:18 +08:00
Recover bool
2023-10-07 04:38:47 +08:00
TestFn TestFunc // test-only option, for mocking errors
bisync: high-level retries if --resilient
Before this change, bisync had no ability to retry in the event of sync errors.
After this change, bisync will retry if --resilient is passed, but only in one
direction at a time. We can safely retry in one direction because the source is
still intact, even if the dest was left in a messy state. If the first
direction still fails after our final retry, we abort and do NOT continue in
the other direction, to prevent the messy dest from polluting the source. If
the first direction succeeds, we do then allow retries in the other direction.
The number of retries is controllable by --retries (default 3)
bisync: high-level retries if --resilient
Before this change, bisync had no ability to retry in the event of sync errors.
After this change, bisync will retry if --resilient is passed, but only in one
direction at a time. We can safely retry in one direction because the source is
still intact, even if the dest was left in a messy state. If the first
direction still fails after our final retry, we abort and do NOT continue in
the other direction, to prevent the messy dest from polluting the source. If
the first direction succeeds, we do then allow retries in the other direction.
The number of retries is controllable by --retries (default 3)
2023-11-11 11:56:28 +08:00
Retries int
bisync: full support for comparing checksum, size, modtime - fixes #5679 fixes #5683 fixes #5684 fixes #5675
Before this change, bisync could only detect changes based on modtime, and
would refuse to run if either path lacked modtime support. This made bisync
unavailable for many of rclone's backends. Additionally, bisync did not account
for the Fs's precision when comparing modtimes, meaning that they could only be
reliably compared within the same side -- not against the opposite side. Size
and checksum (even when available) were ignored completely for deltas.
After this change, bisync now fully supports comparing based on any combination
of size, modtime, and checksum, lifting the prior restriction on backends
without modtime support. The comparison logic considers the backend's
precision, hash types, and other features as appropriate.
The comparison features optionally use a new --compare flag (which takes any
combination of size,modtime,checksum) and even supports some combinations not
otherwise supported in `sync` (like comparing all three at the same time.) By
default (without the --compare flag), bisync inherits the same comparison
options as `sync` (that is: size and modtime by default, unless modified with
flags such as --checksum or --size-only.) If the --compare flag is set, it will
override these defaults.
If --compare includes checksum and both remotes support checksums but have no
hash types in common with each other, checksums will be considered only for
comparisons within the same side (to determine what has changed since the prior
sync), but not for comparisons against the opposite side. If one side supports
checksums and the other does not, checksums will only be considered on the side
that supports them. When comparing with checksum and/or size without modtime,
bisync cannot determine whether a file is newer or older -- only whether it is
changed or unchanged. (If it is changed on both sides, bisync still does the
standard equality-check to avoid declaring a sync conflict unless it absolutely
has to.)
Also included are some new flags to customize the checksum comparison behavior
on backends where hashes are slow or unavailable. --no-slow-hash and
--slow-hash-sync-only allow selectively ignoring checksums on backends such as
local where they are slow. --download-hash allows computing them by downloading
when (and only when) they're otherwise not available. Of course, this option
probably won't be practical with large files, but may be a good option for
syncing small-but-important files with maximum accuracy (for example, a source
code repo on a crypt remote.) An additional advantage over methods like
cryptcheck is that the original file is not required for comparison (for
example, --download-hash can be used to bisync two different crypt remotes with
different passwords.)
Additionally, all of the above are now considered during the final --check-sync
for much-improved accuracy (before this change, it only compared filenames!)
Many other details are explained in the included docs.
2023-12-01 08:44:38 +08:00
Compare CompareOpt
CompareFlag string
bisync: Graceful Shutdown, --recover from interruptions without --resync - fixes #7470
Before this change, bisync had no mechanism to gracefully cancel a sync early
and exit in a clean state. Additionally, there was no way to recover on the
next run -- any interruption at all would cause bisync to require a --resync,
which made bisync more difficult to use as a scheduled background process.
This change introduces a "Graceful Shutdown" mode and --recover flag to
robustly recover from even un-graceful shutdowns.
If --recover is set, in the event of a sudden interruption or other un-graceful
shutdown, bisync will attempt to automatically recover on the next run, instead
of requiring --resync. Bisync is able to recover robustly by keeping one
"backup" listing at all times, representing the state of both paths after the
last known successful sync. Bisync can then compare the current state with this
snapshot to determine which changes it needs to retry. Changes that were synced
after this snapshot (during the run that was later interrupted) will appear to
bisync as if they are "new or changed on both sides", but in most cases this is
not a problem, as bisync will simply do its usual "equality check" and learn
that no action needs to be taken on these files, since they are already
identical on both sides.
In the rare event that a file is synced successfully during a run that later
aborts, and then that same file changes AGAIN before the next run, bisync will
think it is a sync conflict, and handle it accordingly. (From bisync's
perspective, the file has changed on both sides since the last trusted sync,
and the files on either side are not currently identical.) Therefore, --recover
carries with it a slightly increased chance of having conflicts -- though in
practice this is pretty rare, as the conditions required to cause it are quite
specific. This risk can be reduced by using bisync's "Graceful Shutdown" mode
(triggered by sending SIGINT or Ctrl+C), when you have the choice, instead of
forcing a sudden termination.
--recover and --resilient are similar, but distinct -- the main difference is
that --resilient is about _retrying_, while --recover is about _recovering_.
Most users will probably want both. --resilient allows retrying when bisync has
chosen to abort itself due to safety features such as failing --check-access or
detecting a filter change. --resilient does not cover external interruptions
such as a user shutting down their computer in the middle of a sync -- that is
what --recover is for.
"Graceful Shutdown" mode is activated by sending SIGINT or pressing Ctrl+C
during a run. Once triggered, bisync will use best efforts to exit cleanly
before the timer runs out. If bisync is in the middle of transferring files, it
will attempt to cleanly empty its queue by finishing what it has started but
not taking more. If it cannot do so within 30 seconds, it will cancel the
in-progress transfers at that point and then give itself a maximum of 60
seconds to wrap up, save its state for next time, and exit. With the -vP flags
you will see constant status updates and a final confirmation of whether or not
the graceful shutdown was successful.
At any point during the "Graceful Shutdown" sequence, a second SIGINT or Ctrl+C
will trigger an immediate, un-graceful exit, which will leave things in a
messier state. Usually a robust recovery will still be possible if using
--recover mode, otherwise you will need to do a --resync.
If you plan to use Graceful Shutdown mode, it is recommended to use --resilient
and --recover, and it is important to NOT use --inplace, otherwise you risk
leaving partially-written files on one side, which may be confused for real
files on the next run. Note also that in the event of an abrupt interruption, a
lock file will be left behind to block concurrent runs. You will need to delete
it before you can proceed with the next run (or wait for it to expire on its
own, if using --max-lock.)
2023-12-03 13:38:18 +08:00
DebugName string
2021-05-17 00:39:33 +08:00
}
// Default values
const (
DefaultMaxDelete int = 50
DefaultCheckFilename string = "RCLONE_TEST"
)
// DefaultWorkdir is default working directory
var DefaultWorkdir = filepath . Join ( config . GetCacheDir ( ) , "bisync" )
// CheckSyncMode controls when to compare final listings
type CheckSyncMode int
// CheckSync modes
const (
CheckSyncTrue CheckSyncMode = iota // Compare final listings (default)
CheckSyncFalse // Disable comparison of final listings
CheckSyncOnly // Only compare listings from the last run, do not sync
)
func ( x CheckSyncMode ) String ( ) string {
switch x {
case CheckSyncTrue :
return "true"
case CheckSyncFalse :
return "false"
case CheckSyncOnly :
return "only"
}
return "unknown"
}
// Set a CheckSync mode from a string
func ( x * CheckSyncMode ) Set ( s string ) error {
switch strings . ToLower ( s ) {
case "true" :
* x = CheckSyncTrue
case "false" :
* x = CheckSyncFalse
case "only" :
* x = CheckSyncOnly
default :
2021-11-04 18:12:57 +08:00
return fmt . Errorf ( "unknown check-sync mode for bisync: %q" , s )
2021-05-17 00:39:33 +08:00
}
return nil
}
// Type of the CheckSync value
func ( x * CheckSyncMode ) Type ( ) string {
return "string"
}
// Opt keeps command line options
var Opt Options
func init ( ) {
bisync: high-level retries if --resilient
Before this change, bisync had no ability to retry in the event of sync errors.
After this change, bisync will retry if --resilient is passed, but only in one
direction at a time. We can safely retry in one direction because the source is
still intact, even if the dest was left in a messy state. If the first
direction still fails after our final retry, we abort and do NOT continue in
the other direction, to prevent the messy dest from polluting the source. If
the first direction succeeds, we do then allow retries in the other direction.
The number of retries is controllable by --retries (default 3)
bisync: high-level retries if --resilient
Before this change, bisync had no ability to retry in the event of sync errors.
After this change, bisync will retry if --resilient is passed, but only in one
direction at a time. We can safely retry in one direction because the source is
still intact, even if the dest was left in a messy state. If the first
direction still fails after our final retry, we abort and do NOT continue in
the other direction, to prevent the messy dest from polluting the source. If
the first direction succeeds, we do then allow retries in the other direction.
The number of retries is controllable by --retries (default 3)
2023-11-11 11:56:28 +08:00
Opt . Retries = 3
2021-05-17 00:39:33 +08:00
cmd . Root . AddCommand ( commandDefinition )
cmdFlags := commandDefinition . Flags ( )
2023-11-12 23:34:38 +08:00
// when adding new flags, remember to also update the rc params:
// cmd/bisync/rc.go cmd/bisync/help.go (not docs/content/rc.md)
2023-07-11 01:34:10 +08:00
flags . BoolVarP ( cmdFlags , & Opt . Resync , "resync" , "1" , Opt . Resync , "Performs the resync run. Path1 files may overwrite Path2 versions. Consider using --verbose or --dry-run first." , "" )
flags . BoolVarP ( cmdFlags , & Opt . CheckAccess , "check-access" , "" , Opt . CheckAccess , makeHelp ( "Ensure expected {CHECKFILE} files are found on both Path1 and Path2 filesystems, else abort." ) , "" )
flags . StringVarP ( cmdFlags , & Opt . CheckFilename , "check-filename" , "" , Opt . CheckFilename , makeHelp ( "Filename for --check-access (default: {CHECKFILE})" ) , "" )
flags . BoolVarP ( cmdFlags , & Opt . Force , "force" , "" , Opt . Force , "Bypass --max-delete safety check and run the sync. Consider using with --verbose" , "" )
flags . FVarP ( cmdFlags , & Opt . CheckSync , "check-sync" , "" , "Controls comparison of final listings: true|false|only (default: true)" , "" )
2023-07-11 19:09:06 +08:00
flags . BoolVarP ( cmdFlags , & Opt . CreateEmptySrcDirs , "create-empty-src-dirs" , "" , Opt . CreateEmptySrcDirs , "Sync creation and deletion of empty directories. (Not compatible with --remove-empty-dirs)" , "" )
flags . BoolVarP ( cmdFlags , & Opt . RemoveEmptyDirs , "remove-empty-dirs" , "" , Opt . RemoveEmptyDirs , "Remove ALL empty directories at the final cleanup step." , "" )
2023-07-11 01:34:10 +08:00
flags . StringVarP ( cmdFlags , & Opt . FiltersFile , "filters-file" , "" , Opt . FiltersFile , "Read filtering patterns from a file" , "" )
flags . StringVarP ( cmdFlags , & Opt . Workdir , "workdir" , "" , Opt . Workdir , makeHelp ( "Use custom working dir - useful for testing. (default: {WORKDIR})" ) , "" )
2023-11-12 23:34:38 +08:00
flags . StringVarP ( cmdFlags , & Opt . BackupDir1 , "backup-dir1" , "" , Opt . BackupDir1 , "--backup-dir for Path1. Must be a non-overlapping path on the same remote." , "" )
flags . StringVarP ( cmdFlags , & Opt . BackupDir2 , "backup-dir2" , "" , Opt . BackupDir2 , "--backup-dir for Path2. Must be a non-overlapping path on the same remote." , "" )
bisync: Graceful Shutdown, --recover from interruptions without --resync - fixes #7470
Before this change, bisync had no mechanism to gracefully cancel a sync early
and exit in a clean state. Additionally, there was no way to recover on the
next run -- any interruption at all would cause bisync to require a --resync,
which made bisync more difficult to use as a scheduled background process.
This change introduces a "Graceful Shutdown" mode and --recover flag to
robustly recover from even un-graceful shutdowns.
If --recover is set, in the event of a sudden interruption or other un-graceful
shutdown, bisync will attempt to automatically recover on the next run, instead
of requiring --resync. Bisync is able to recover robustly by keeping one
"backup" listing at all times, representing the state of both paths after the
last known successful sync. Bisync can then compare the current state with this
snapshot to determine which changes it needs to retry. Changes that were synced
after this snapshot (during the run that was later interrupted) will appear to
bisync as if they are "new or changed on both sides", but in most cases this is
not a problem, as bisync will simply do its usual "equality check" and learn
that no action needs to be taken on these files, since they are already
identical on both sides.
In the rare event that a file is synced successfully during a run that later
aborts, and then that same file changes AGAIN before the next run, bisync will
think it is a sync conflict, and handle it accordingly. (From bisync's
perspective, the file has changed on both sides since the last trusted sync,
and the files on either side are not currently identical.) Therefore, --recover
carries with it a slightly increased chance of having conflicts -- though in
practice this is pretty rare, as the conditions required to cause it are quite
specific. This risk can be reduced by using bisync's "Graceful Shutdown" mode
(triggered by sending SIGINT or Ctrl+C), when you have the choice, instead of
forcing a sudden termination.
--recover and --resilient are similar, but distinct -- the main difference is
that --resilient is about _retrying_, while --recover is about _recovering_.
Most users will probably want both. --resilient allows retrying when bisync has
chosen to abort itself due to safety features such as failing --check-access or
detecting a filter change. --resilient does not cover external interruptions
such as a user shutting down their computer in the middle of a sync -- that is
what --recover is for.
"Graceful Shutdown" mode is activated by sending SIGINT or pressing Ctrl+C
during a run. Once triggered, bisync will use best efforts to exit cleanly
before the timer runs out. If bisync is in the middle of transferring files, it
will attempt to cleanly empty its queue by finishing what it has started but
not taking more. If it cannot do so within 30 seconds, it will cancel the
in-progress transfers at that point and then give itself a maximum of 60
seconds to wrap up, save its state for next time, and exit. With the -vP flags
you will see constant status updates and a final confirmation of whether or not
the graceful shutdown was successful.
At any point during the "Graceful Shutdown" sequence, a second SIGINT or Ctrl+C
will trigger an immediate, un-graceful exit, which will leave things in a
messier state. Usually a robust recovery will still be possible if using
--recover mode, otherwise you will need to do a --resync.
If you plan to use Graceful Shutdown mode, it is recommended to use --resilient
and --recover, and it is important to NOT use --inplace, otherwise you risk
leaving partially-written files on one side, which may be confused for real
files on the next run. Note also that in the event of an abrupt interruption, a
lock file will be left behind to block concurrent runs. You will need to delete
it before you can proceed with the next run (or wait for it to expire on its
own, if using --max-lock.)
2023-12-03 13:38:18 +08:00
flags . StringVarP ( cmdFlags , & Opt . DebugName , "debugname" , "" , Opt . DebugName , "Debug by tracking one file at various points throughout a bisync run (when -v or -vv)" , "" )
2023-07-11 01:34:10 +08:00
flags . BoolVarP ( cmdFlags , & tzLocal , "localtime" , "" , tzLocal , "Use local time in listings (default: UTC)" , "" )
flags . BoolVarP ( cmdFlags , & Opt . NoCleanup , "no-cleanup" , "" , Opt . NoCleanup , "Retain working files (useful for troubleshooting and testing)." , "" )
2023-07-11 18:40:01 +08:00
flags . BoolVarP ( cmdFlags , & Opt . IgnoreListingChecksum , "ignore-listing-checksum" , "" , Opt . IgnoreListingChecksum , "Do not use checksums for listings (add --ignore-checksum to additionally skip post-copy checksum checks)" , "" )
2023-07-11 18:57:49 +08:00
flags . BoolVarP ( cmdFlags , & Opt . Resilient , "resilient" , "" , Opt . Resilient , "Allow future runs to retry after certain less-serious errors, instead of requiring --resync. Use at your own risk!" , "" )
bisync: Graceful Shutdown, --recover from interruptions without --resync - fixes #7470
Before this change, bisync had no mechanism to gracefully cancel a sync early
and exit in a clean state. Additionally, there was no way to recover on the
next run -- any interruption at all would cause bisync to require a --resync,
which made bisync more difficult to use as a scheduled background process.
This change introduces a "Graceful Shutdown" mode and --recover flag to
robustly recover from even un-graceful shutdowns.
If --recover is set, in the event of a sudden interruption or other un-graceful
shutdown, bisync will attempt to automatically recover on the next run, instead
of requiring --resync. Bisync is able to recover robustly by keeping one
"backup" listing at all times, representing the state of both paths after the
last known successful sync. Bisync can then compare the current state with this
snapshot to determine which changes it needs to retry. Changes that were synced
after this snapshot (during the run that was later interrupted) will appear to
bisync as if they are "new or changed on both sides", but in most cases this is
not a problem, as bisync will simply do its usual "equality check" and learn
that no action needs to be taken on these files, since they are already
identical on both sides.
In the rare event that a file is synced successfully during a run that later
aborts, and then that same file changes AGAIN before the next run, bisync will
think it is a sync conflict, and handle it accordingly. (From bisync's
perspective, the file has changed on both sides since the last trusted sync,
and the files on either side are not currently identical.) Therefore, --recover
carries with it a slightly increased chance of having conflicts -- though in
practice this is pretty rare, as the conditions required to cause it are quite
specific. This risk can be reduced by using bisync's "Graceful Shutdown" mode
(triggered by sending SIGINT or Ctrl+C), when you have the choice, instead of
forcing a sudden termination.
--recover and --resilient are similar, but distinct -- the main difference is
that --resilient is about _retrying_, while --recover is about _recovering_.
Most users will probably want both. --resilient allows retrying when bisync has
chosen to abort itself due to safety features such as failing --check-access or
detecting a filter change. --resilient does not cover external interruptions
such as a user shutting down their computer in the middle of a sync -- that is
what --recover is for.
"Graceful Shutdown" mode is activated by sending SIGINT or pressing Ctrl+C
during a run. Once triggered, bisync will use best efforts to exit cleanly
before the timer runs out. If bisync is in the middle of transferring files, it
will attempt to cleanly empty its queue by finishing what it has started but
not taking more. If it cannot do so within 30 seconds, it will cancel the
in-progress transfers at that point and then give itself a maximum of 60
seconds to wrap up, save its state for next time, and exit. With the -vP flags
you will see constant status updates and a final confirmation of whether or not
the graceful shutdown was successful.
At any point during the "Graceful Shutdown" sequence, a second SIGINT or Ctrl+C
will trigger an immediate, un-graceful exit, which will leave things in a
messier state. Usually a robust recovery will still be possible if using
--recover mode, otherwise you will need to do a --resync.
If you plan to use Graceful Shutdown mode, it is recommended to use --resilient
and --recover, and it is important to NOT use --inplace, otherwise you risk
leaving partially-written files on one side, which may be confused for real
files on the next run. Note also that in the event of an abrupt interruption, a
lock file will be left behind to block concurrent runs. You will need to delete
it before you can proceed with the next run (or wait for it to expire on its
own, if using --max-lock.)
2023-12-03 13:38:18 +08:00
flags . BoolVarP ( cmdFlags , & Opt . Recover , "recover" , "" , Opt . Recover , "Automatically recover from interruptions without requiring --resync." , "" )
bisync: high-level retries if --resilient
Before this change, bisync had no ability to retry in the event of sync errors.
After this change, bisync will retry if --resilient is passed, but only in one
direction at a time. We can safely retry in one direction because the source is
still intact, even if the dest was left in a messy state. If the first
direction still fails after our final retry, we abort and do NOT continue in
the other direction, to prevent the messy dest from polluting the source. If
the first direction succeeds, we do then allow retries in the other direction.
The number of retries is controllable by --retries (default 3)
bisync: high-level retries if --resilient
Before this change, bisync had no ability to retry in the event of sync errors.
After this change, bisync will retry if --resilient is passed, but only in one
direction at a time. We can safely retry in one direction because the source is
still intact, even if the dest was left in a messy state. If the first
direction still fails after our final retry, we abort and do NOT continue in
the other direction, to prevent the messy dest from polluting the source. If
the first direction succeeds, we do then allow retries in the other direction.
The number of retries is controllable by --retries (default 3)
2023-11-11 11:56:28 +08:00
flags . IntVarP ( cmdFlags , & Opt . Retries , "retries" , "" , Opt . Retries , "Retry operations this many times if they fail" , "" )
bisync: full support for comparing checksum, size, modtime - fixes #5679 fixes #5683 fixes #5684 fixes #5675
Before this change, bisync could only detect changes based on modtime, and
would refuse to run if either path lacked modtime support. This made bisync
unavailable for many of rclone's backends. Additionally, bisync did not account
for the Fs's precision when comparing modtimes, meaning that they could only be
reliably compared within the same side -- not against the opposite side. Size
and checksum (even when available) were ignored completely for deltas.
After this change, bisync now fully supports comparing based on any combination
of size, modtime, and checksum, lifting the prior restriction on backends
without modtime support. The comparison logic considers the backend's
precision, hash types, and other features as appropriate.
The comparison features optionally use a new --compare flag (which takes any
combination of size,modtime,checksum) and even supports some combinations not
otherwise supported in `sync` (like comparing all three at the same time.) By
default (without the --compare flag), bisync inherits the same comparison
options as `sync` (that is: size and modtime by default, unless modified with
flags such as --checksum or --size-only.) If the --compare flag is set, it will
override these defaults.
If --compare includes checksum and both remotes support checksums but have no
hash types in common with each other, checksums will be considered only for
comparisons within the same side (to determine what has changed since the prior
sync), but not for comparisons against the opposite side. If one side supports
checksums and the other does not, checksums will only be considered on the side
that supports them. When comparing with checksum and/or size without modtime,
bisync cannot determine whether a file is newer or older -- only whether it is
changed or unchanged. (If it is changed on both sides, bisync still does the
standard equality-check to avoid declaring a sync conflict unless it absolutely
has to.)
Also included are some new flags to customize the checksum comparison behavior
on backends where hashes are slow or unavailable. --no-slow-hash and
--slow-hash-sync-only allow selectively ignoring checksums on backends such as
local where they are slow. --download-hash allows computing them by downloading
when (and only when) they're otherwise not available. Of course, this option
probably won't be practical with large files, but may be a good option for
syncing small-but-important files with maximum accuracy (for example, a source
code repo on a crypt remote.) An additional advantage over methods like
cryptcheck is that the original file is not required for comparison (for
example, --download-hash can be used to bisync two different crypt remotes with
different passwords.)
Additionally, all of the above are now considered during the final --check-sync
for much-improved accuracy (before this change, it only compared filenames!)
Many other details are explained in the included docs.
2023-12-01 08:44:38 +08:00
flags . StringVarP ( cmdFlags , & Opt . CompareFlag , "compare" , "" , Opt . CompareFlag , "Comma-separated list of bisync-specific compare options ex. 'size,modtime,checksum' (default: 'size,modtime')" , "" )
flags . BoolVarP ( cmdFlags , & Opt . Compare . NoSlowHash , "no-slow-hash" , "" , Opt . Compare . NoSlowHash , "Ignore listing checksums only on backends where they are slow" , "" )
flags . BoolVarP ( cmdFlags , & Opt . Compare . SlowHashSyncOnly , "slow-hash-sync-only" , "" , Opt . Compare . SlowHashSyncOnly , "Ignore slow checksums for listings and deltas, but still consider them during sync calls." , "" )
flags . BoolVarP ( cmdFlags , & Opt . Compare . DownloadHash , "download-hash" , "" , Opt . Compare . DownloadHash , "Compute hash by downloading when otherwise unavailable. (warning: may be slow and use lots of data!)" , "" )
2021-05-17 00:39:33 +08:00
}
// bisync command definition
var commandDefinition = & cobra . Command {
Use : "bisync remote1:path1 remote2:path2" ,
Short : shortHelp ,
Long : longHelp ,
2022-11-27 06:40:49 +08:00
Annotations : map [ string ] string {
"versionIntroduced" : "v1.58" ,
2023-07-11 01:34:10 +08:00
"groups" : "Filter,Copy,Important" ,
2023-12-04 20:37:05 +08:00
"status" : "Beta" ,
2022-11-27 06:40:49 +08:00
} ,
2021-05-17 00:39:33 +08:00
RunE : func ( command * cobra . Command , args [ ] string ) error {
cmd . CheckArgs ( 2 , 2 , command , args )
fs1 , file1 , fs2 , file2 := cmd . NewFsSrcDstFiles ( args )
if file1 != "" || file2 != "" {
return errors . New ( "paths must be existing directories" )
}
ctx := context . Background ( )
opt := Opt
opt . applyContext ( ctx )
if tzLocal {
TZ = time . Local
}
commonHashes := fs1 . Hashes ( ) . Overlap ( fs2 . Hashes ( ) )
isDropbox1 := strings . HasPrefix ( fs1 . String ( ) , "Dropbox" )
isDropbox2 := strings . HasPrefix ( fs2 . String ( ) , "Dropbox" )
if commonHashes == hash . Set ( 0 ) && ( isDropbox1 || isDropbox2 ) {
ci := fs . GetConfig ( ctx )
if ! ci . DryRun && ! ci . RefreshTimes {
fs . Debugf ( nil , "Using flag --refresh-times is recommended" )
}
}
2023-12-04 20:37:05 +08:00
fs . Logf ( nil , "bisync is IN BETA. Don't use in production!" )
2021-05-17 00:39:33 +08:00
cmd . Run ( false , true , command , func ( ) error {
err := Bisync ( ctx , fs1 , fs2 , & opt )
if err == ErrBisyncAborted {
os . Exit ( 2 )
}
return err
} )
return nil
} ,
}
func ( opt * Options ) applyContext ( ctx context . Context ) {
maxDelete := DefaultMaxDelete
ci := fs . GetConfig ( ctx )
if ci . MaxDelete >= 0 {
maxDelete = int ( ci . MaxDelete )
}
if maxDelete < 0 {
maxDelete = 0
}
if maxDelete > 100 {
maxDelete = 100
}
opt . MaxDelete = maxDelete
// reset MaxDelete for fs/operations, bisync handles this parameter specially
ci . MaxDelete = - 1
opt . DryRun = ci . DryRun
}
func ( opt * Options ) setDryRun ( ctx context . Context ) context . Context {
ctxNew , ci := fs . AddConfig ( ctx )
ci . DryRun = opt . DryRun
return ctxNew
}
func ( opt * Options ) applyFilters ( ctx context . Context ) ( context . Context , error ) {
filtersFile := opt . FiltersFile
if filtersFile == "" {
return ctx , nil
}
f , err := os . Open ( filtersFile )
if err != nil {
2021-11-04 18:12:57 +08:00
return ctx , fmt . Errorf ( "specified filters file does not exist: %s" , filtersFile )
2021-05-17 00:39:33 +08:00
}
fs . Infof ( nil , "Using filters file %s" , filtersFile )
hasher := md5 . New ( )
if _ , err := io . Copy ( hasher , f ) ; err != nil {
_ = f . Close ( )
return ctx , err
}
gotHash := hex . EncodeToString ( hasher . Sum ( nil ) )
_ = f . Close ( )
hashFile := filtersFile + ".md5"
2022-08-20 22:38:02 +08:00
wantHash , err := os . ReadFile ( hashFile )
2021-05-17 00:39:33 +08:00
if err != nil && ! opt . Resync {
2021-11-04 18:12:57 +08:00
return ctx , fmt . Errorf ( "filters file md5 hash not found (must run --resync): %s" , filtersFile )
2021-05-17 00:39:33 +08:00
}
if gotHash != string ( wantHash ) && ! opt . Resync {
2021-11-04 18:12:57 +08:00
return ctx , fmt . Errorf ( "filters file has changed (must run --resync): %s" , filtersFile )
2021-05-17 00:39:33 +08:00
}
if opt . Resync {
2023-07-11 16:35:01 +08:00
if opt . DryRun {
fs . Infof ( nil , "Skipped storing filters file hash to %s as --dry-run is set" , hashFile )
} else {
2023-07-11 18:40:01 +08:00
fs . Infof ( nil , "Storing filters file hash to %s" , hashFile )
if err := os . WriteFile ( hashFile , [ ] byte ( gotHash ) , bilib . PermSecure ) ; err != nil {
return ctx , err
2023-07-11 16:35:01 +08:00
}
2021-05-17 00:39:33 +08:00
}
}
// Prepend our filter file first in the list
filterOpt := filter . GetConfig ( ctx ) . Opt
filterOpt . FilterFrom = append ( [ ] string { filtersFile } , filterOpt . FilterFrom ... )
newFilter , err := filter . NewFilter ( & filterOpt )
if err != nil {
2021-11-04 18:12:57 +08:00
return ctx , fmt . Errorf ( "invalid filters file: %s: %w" , filtersFile , err )
2021-05-17 00:39:33 +08:00
}
return filter . ReplaceConfig ( ctx , newFilter ) , nil
}