Как поместить ограничения времени выполнения на процессы rsync?

Я хочу установить ограничение по времени на своих rsync процессах резервного копирования. Как я лучше всего иду о?

Согласно этому сообщению, существует опция сделать точно что:

--time-limit
When this option is used rsync will stop after T minutes and exit.

Мне не реализовали ту опцию на моей Ubuntu 12.04, как бы то ни было. В комментариях сообщения существует возможное решение, на которое намекают, но я не достаточно быстр, чтобы сметь начинать это сам, точно так же, как это.

Также, кажется, существует команда/программа timelimit, но у меня нет этого также. Это было бы решением, возможно?

1
задан 13 April 2017 в 15:14

3 ответа

Старый вопрос, но команда coreutils timeout может сделать это (хотя это не закончится корректно).

timeout 60 rsync source destination

, Где 60 ограничение по времени в секундах

1
ответ дан 7 December 2019 в 16:28

Вот то, как я исправил его:

wget http://mirrors.ibiblio.org/rsync/src/rsync-patches-3.0.9.tar.gz
wget http://mirrors.ibiblio.org/rsync/src/rsync-3.0.9.tar.gz
tar xvf rsync-3.0.9.tar.gz
tar xvf rsync-patches-3.0.9.tar.gz
cd rsync-3.0.9
patch -p1 <patches/time-limit.diff
./configure
make
cp ./rsync /usr/local/bin

ПРИМЕЧАНИЕ: я должен был исправить rsync с обеих сторон моей резервной связи.

0
ответ дан 7 December 2019 в 16:28

Shellscript

Я сделал bash shellscript, который повторяется до тех пор, пока все не будет скопировано. Когда есть большие файлы, важно использовать то, что уже было скопировано в предыдущей итерации, и приятно «видеть» ход процесса копирования.

#!/bin/bash

########################################################################

function usage {

 echo "
Usage:   $0 source-dir/ target-dir  # copies content of source-dir
         $0 source-dir  target-dir  # copies source-dir (with subdirs)
"
 exit
}
########################################################################

# main

########################################################################

if [ $# -ne 2 ]
then
 usage
fi
if ! test -d "$1"
then
 echo "$1 is not a directory"
 if test -f "$1"
 then
  echo "but $1 is a file :-)"
 else
  echo "and $1 is not a file :-("
  usage
 fi
fi
if ! test -d "${2##*:}"  # allowing network directories
then
 echo "$2 is not a directory :-("
 usage
else
 echo "$2 is a directory :-)"
fi

cont=true
while $cont
do
 echo "copying ..."
 timeout --foreground 25 rsync --info=progress2 --partial -Ha "$1" "$2"  
 if [ "$?" != "0" ]
 then
  cont=true
  echo "flushing the buffers ..."
  sync
  echo "sleeping for 5 seconds ..."
  sleep 5
 else
  cont=false
 fi
done
echo "final flushing of buffers ..."
sync
echo "Dome :-)"

Usage

Когда вы делаете исполняемый файл shellscript и запускаете его без каких-либо параметров, вы получаете следующее сообщение справки,

Usage:   ./rsyncer-w-pause source-dir/ target-dir  # copies content of source-dir
         ./rsyncer-w-pause source-dir  target-dir  # copies source-dir (with subdirs)

Я протестировал shellscript, скопировав некоторые ISO-файлы с дистрибутивами Linux с медленного USB-накопителя на мой жесткий диск. Таким образом, было несколько итераций, и копирование прерывалось в середине iso-файлов, но скопированная часть могла быть использована следующей итерацией. Поэтому я проверил, что он также работает для копирования больших файлов.

Для использования для реального копирования, Я думаю, что вы должны увеличить время копирования (с 25 секунд), а также вы должны увеличить время сна (с 5 секунд). Используйте временные интервалы, которые лучше всего подходят для вашей конкретной задачи.

Комментарии к параметрам и параметрам командной строки

Команда timeout останавливает выполнение команды, которой она управляет, даже в середине копирования файла.

   --foreground

          when not running timeout directly from a shell prompt,

          allow COMMAND to read from the TTY and get TTY signals; in  this
          mode, children of COMMAND will not be timed out

Команда rsync является мощной командой копирования. См. man rsync, чтобы получить полное описание возможных вариантов.

   --info=FLAGS
          This option lets you have fine-grained control over the informa‐
          tion output you want to see.  An individual  flag  name  may  be
          followed  by a level number, with 0 meaning to silence that out‐
          put, 1 being  the  default  output  level,  and  higher  numbers
          increasing  the  output  of  that  flag  (for those that support
          higher levels).  Use --info=help to see all the  available  flag
          names,  what they output, and what flag names are added for each
          increase in the verbose level.  Some examples:

              rsync -a --info=progress2 src/ dest/
              rsync -avv --info=stats2,misc1,flist0 src/ dest/

   --partial
          By default, rsync will delete any partially transferred file  if
          the  transfer  is  interrupted. In some circumstances it is more
          desirable to keep partially transferred files. Using the  --par‐
          tial  option  tells  rsync to keep the partial file which should
          make a subsequent transfer of the rest of the file much faster.

Вам может понравиться или не понравиться опция -hard-links,

   -H, --hard-links
          This tells rsync to look for hard-linked files in the source and
          link together the corresponding files on the destination.  With‐
          out  this option, hard-linked files in the source are treated as
          though they were separate files.

   -a, --archive
          This  is equivalent to -rlptgoD. It is a quick way of saying you
          want recursion and want to preserve almost everything  (with  -H
          being  a  notable  omission).   The  only exception to the above
          equivalence is when --files-from is specified, in which case  -r
          is not implied.

          Note that -a does not preserve hardlinks, because finding multi‐
          ply-linked files is expensive.  You must separately specify -H.

Наконец, прочитайте это объяснение о параметрах (источник и цель),

          rsync -avz foo:src/bar /data/tmp

   This would recursively transfer all files from the directory src/bar on
   the  machine foo into the /data/tmp/bar directory on the local machine.
   The files are transferred in "archive" mode, which  ensures  that  sym‐
   bolic  links,  devices,  attributes,  permissions, ownerships, etc. are
   preserved in the transfer.  Additionally, compression will be  used  to
   reduce the size of data portions of the transfer.

          rsync -avz foo:src/bar/ /data/tmp

   A  trailing slash on the source changes this behavior to avoid creating
   an additional directory level at the destination.  You can think  of  a
   trailing / on a source as meaning "copy the contents of this directory"
   as opposed to "copy the directory by  name",  but  in  both  cases  the
   attributes  of the containing directory are transferred to the contain‐
   ing directory on the destination.  In other words, each of the  follow‐
   ing  commands copies the files in the same way, including their setting
   of the attributes of /dest/foo:

          rsync -av /src/foo /dest
          rsync -av /src/foo/ /dest/foo
0
ответ дан 1 June 2020 в 17:38

Другие вопросы по тегам:

Похожие вопросы: