Snippets

Jorge Araya Navarro Configuración reproducible de copias de seguridad del sistema operativo

Created by Jorge Araya Navarro
#+TITLE: Respaldo de configuración del sistema operativo
#+STARTUP: content

Para extraer todos los bloques de código a archivos use =C-c C-v t=. Para instalar y activar todo use =C-c C-v b=.

* Respaldo de configuración del sistema operativo
Para las copias de seguridad se usa [[http://rsnapshot.org/][Rsnapshot]]. Las copias son incrementales, las mas recientes son las copias diarias.
** Requisitos
Debemos instalar varias aplicaciones y comprobar que ciertas carpetas existen para que los scripts funcionan.
#+BEGIN_SRC shell :results silent :dir /sudo::
  mkdir -p /var/local/rsnapshot/
  pacman -Sy
  pacman --noconfirm --needed -S gnupg p7zip rsnapshot
#+END_SRC

** Configuración
Archivo de configuración de Rsnapshot.
#+BEGIN_SRC conf-unix :eval never :tangle "/sudo::/etc/rsnapshot.conf"
  config_version	1.2

  # All snapshots will be stored under this root directory.
  #
  snapshot_root	/respaldos

  #################################
  # EXTERNAL PROGRAM DEPENDENCIES #
  #################################

  cmd_cp		/usr/bin/cp
  cmd_rm		/usr/bin/rm
  cmd_rsync	/usr/bin/rsync
  cmd_logger	/usr/bin/logger
  cmd_du		/usr/bin/du
  cmd_rsnapshot_diff	/usr/bin/rsnapshot-diff

  # actualiza la lista de aplicaciones instaladas en la computadora
  # antes de arrancar con las actualizaciones
  cmd_preexec	/usr/bin/paclist.sh

  # Comprime todos los archivos sincronizados
  cmd_postexec	/usr/bin/backupcompress.sh

  # Intervalos de respaldos
  # 24 veces al día
  retain	hora	24
  # 7 veces a la semana
  retain	diario	7
  # 4 veces al mes
  retain	semanal	4
  # 12 veces al año
  retain	mensual	12
  # 4 veces cada lustro
  retain	anual	4

  # opciones globales
  # 2 es default. 1 es Quiet y 5 es debug mode
  verbose		2

  # Same as "verbose" above, but controls the amount of data sent to the
  # logfile, if one is being used. The default is 3.
  #
  loglevel	2

  # If you enable this, data will be written to the file you specify. The
  # amount of data written is controlled by the "loglevel" parameter.
  #
  #logfile	/var/log/rsnapshot

  # Previene que dos instancias de rsnapshot corran a la vez
  lockfile	/tmp/rsnapshot.pid

  # Default rsync args. All rsync commands have at least these options set.
  #
  #rsync_short_args	-a
  rsync_long_args	--delete --numeric-ids --relative --delete-excluded --no-specials --no-devices

  # Default arguments for the "du" program (for disk space reporting).
  # The GNU version of "du" is preferred. See the man page for more details.
  # If your version of "du" doesn't support the -h flag, try -k flag instead.
  #
  #du_args	-csh

  # If this is enabled, rsync won't span filesystem partitions within a
  # backup point. This essentially passes the -x option to rsync.
  # The default is 0 (off).
  #
  #one_fs		0

  # The include and exclude parameters, if enabled, simply get passed directly
  # to rsync. If you have multiple include/exclude patterns, put each one on a
  # separate line. Please look up the --include and --exclude options in the
  # rsync man page for more details on how to specify file name patterns.
  #
  #include	???
  #include	???
  exclude		*.pacnew
  exclude		tags
  exclude		TAGS
  exclude		.make.state
  exclude		.nse_depinfo
  exclude		*~
  exclude		#*
  exclude		.#*
  exclude		,*
  exclude		_$*
  exclude		*$
  exclude		*.old
  exclude		*.bak
  exclude		*.BAK
  exclude		*.orig
  exclude		*.rej
  exclude		.del-*
  exclude		*.a
  exclude		*.olb
  exclude		*.o
  exclude		*.obj
  exclude		*.so
  exclude		*.exe
  exclude		*.Z
  exclude		*.elc
  exclude		*.ln

  # If your version of rsync supports --link-dest, consider enabling this.
  # This is the best way to support special files (FIFOs, etc) cross-platform.
  # The default is 0 (off).
  #
  link_dest	1

  # When sync_first is enabled, it changes the default behaviour of rsnapshot.
  # Normally, when rsnapshot is called with its lowest interval
  # (i.e.: "rsnapshot alpha"), it will sync files AND rotate the lowest
  # intervals. With sync_first enabled, "rsnapshot sync" handles the file sync,
  # and all interval calls simply rotate files. See the man page for more
  # details. The default is 0 (off).
  #
  #sync_first	0

  # If enabled, rsnapshot will move the oldest directory for each interval
  # to [interval_name].delete, then it will remove the lockfile and delete
  # that directory just before it exits. The default is 0 (off).
  #
  #use_lazy_deletes	0

  ###############################
  ### BACKUP POINTS / SCRIPTS ###
  ###############################

  # respalda archivos locales en el sistema local
  backup	/etc/			localhost/
  backup	/home/jorge/.ssh/	localhost/
#+END_SRC
Script para listar paquetes instalados en el sistema.
#+BEGIN_SRC shell :eval never :tangle "/sudo::/usr/bin/paclist.sh" :shebang #!/usr/bin/sh
  #!/usr/bin/sh

  # Este script listara los paquetes instalados en el sistema, si existen algunos
  # provenientes de AUR, también son registrados.

  pacman -Qetq | sort > /tmp/a.txt
  pacman -Qmq | sort > /tmp/b.txt

  comm /tmp/a.txt /tmp/b.txt > /etc/lista_pacman.txt
  comm /tmp/b.txt /tmp/a.txt > /etc/lista_pacman_aur.txt

  rm /tmp/a.txt /tmp/b.txt
#+END_SRC
Script para comprimir los respaldos
#+BEGIN_SRC shell :eval never :tangle "/sudo::/usr/bin/backupcompress.sh" :shebang #!/usr/bin/sh
  #!/usr/bin/sh

  compress_and_encrypt() {
      # comprime
      tar cf - $SNAPSHOTDIR | 7z a -si /tmp/respaldos.tar.7z
      # cifra
      gpg -z 0 \
          --no-greeting \
          --encrypt \
          --yes \
          --batch \
          --no-tty \
          --trust-model always \
          -r A3CDCDE939A264EE \
          /tmp/respaldos.tar.7z
      # copia
      mv -f /tmp/respaldos.tar.7z.gpg /var/local/rsnapshot/
      # borra respaldo comprimido original
      rm /tmp/respaldos.tar.7z
      # recuerda la ultima comprobación
      mv -f /tmp/rsnapdiff.txt /var/local/respaldos.txt
  }

  SNAPSHOTDIR=`cat /etc/rsnapshot.conf | grep snapshot_root | cut -f2 -d$'\t' -`
  if [ -d "$SNAPSHOTDIR/hora.0/" -a -d "$SNAPSHOTDIR/hora.1/" ]; then
      SNAPSHOTDIFF=`rsnapshot-diff "$SNAPSHOTDIR/hora.0/" "$SNAPSHOTDIR/hora.1"`
  else
      # Aun no es hora
      echo "No existen copias de seguridad aun"
      exit 0
  fi


  # extrae los bytes añadidos/removidos y el consumo/ahorro en bytes para
  # comparar con la ultima vez que este script fue corrido.
  echo $SNAPSHOTDIFF > /tmp/rsnapdiff.txt

  # Existe la comprobación anterior?
  if [ -r /var/local/respaldos.txt ]; then

      # Si ambos archivos son diferentes, comprime los respaldos.
      if [ ! $(cmp --silent /var/local/respaldos.txt /tmp/rsnapdiff.txt) ]; then
          # comprime respaldos
          compress_and_encrypt
      fi
  else
      # la comprobación anterior no existe, comprime los respaldos.
      echo "Primera vez cifrando y comprimiendo respaldos"
      compress_and_encrypt
  fi
#+END_SRC
** Activación automática
Rsnapshot puede hacer su trabajo sin intervención humana, por razones de conveniencia se usa systemd
*** cada hora
#+BEGIN_SRC systemd :eval never :tangle "/sudo::/etc/systemd/system/rsnapshot-hora.service"
  [Unit]
  Description=rsnapshot respaldos cada hora

  [Service]
  Type=oneshot
  Nice=19
  IOSchedulingClass=3
  ExecStart=/usr/bin/rsnapshot hora
#+END_SRC
#+BEGIN_SRC systemd :eval never :tangle "/sudo::/etc/systemd/system/rsnapshot-hora.timer"
  [Unit]
  Description=rsnapshot respaldos cada hora

  [Timer]
  OnCalendar=hourly
  Persistent=false
  Unit=rsnapshot-hora.service

  [Install]
  WantedBy=timers.target
#+END_SRC
*** cada día
#+BEGIN_SRC systemd :eval never :tangle "/sudo::/etc/systemd/system/rsnapshot-dia.service"
  [Unit]
  Description=rsnapshot respaldos cada dia
  After=rsnapshot-hora.service

  [Service]
  Type=oneshot
  Nice=19
  IOSchedulingClass=3
  ExecStart=/usr/bin/rsnapshot diario
#+END_SRC
#+BEGIN_SRC systemd :eval never :tangle "/sudo::/etc/systemd/system/rsnapshot-dia.timer"
  [Unit]
  Description=rsnapshot respaldos cada dia

  [Timer]
  OnCalendar=daily
  Persistent=true
  Unit=rsnapshot-dia.service

  [Install]
  WantedBy=timers.target
#+END_SRC
*** cada semana
#+BEGIN_SRC systemd :eval never :tangle "/sudo::/etc/systemd/system/rsnapshot-semana.service"
  [Unit]
  Description=rsnapshot respaldos cada semana
  After=rsnapshot-dia.service

  [Service]
  Type=oneshot
  Nice=19
  IOSchedulingClass=3
  ExecStart=/usr/bin/rsnapshot semanal
#+END_SRC
#+BEGIN_SRC systemd :eval never :tangle "/sudo::/etc/systemd/system/rsnapshot-semana.timer"
  [Unit]
  Description=rsnapshot respaldos cada semana

  [Timer]
  OnCalendar=weekly
  Persistent=true
  Unit=rsnapshot-semana.service

  [Install]
  WantedBy=timers.target
#+END_SRC
*** cada mes
#+BEGIN_SRC systemd :eval never :tangle "/sudo::/etc/systemd/system/rsnapshot-mes.service"
  [Unit]
  Description=rsnapshot respaldos cada mes
  After=rsnapshot-semana.service

  [Service]
  Type=oneshot
  Nice=19
  IOSchedulingClass=3
  ExecStart=/usr/bin/rsnapshot mensual
#+END_SRC
#+BEGIN_SRC systemd :eval never :tangle "/sudo::/etc/systemd/system/rsnapshot-mes.timer"
  [Unit]
  Description=rsnapshot respaldos cada mes

  [Timer]
  OnCalendar=monthly
  Persistent=true
  Unit=rsnapshot-mes.service

  [Install]
  WantedBy=timers.target
#+END_SRC
*** cada año
#+BEGIN_SRC systemd :eval never :tangle "/sudo::/etc/systemd/system/rsnapshot-anual.service"
  [Unit]
  Description=rsnapshot respaldos cada año
  After=rsnapshot-mes.service

  [Service]
  Type=oneshot
  Nice=19
  IOSchedulingClass=3
  ExecStart=/usr/bin/rsnapshot anual
#+END_SRC
#+BEGIN_SRC systemd :eval never :tangle "/sudo::/etc/systemd/system/rsnapshot-anual.timer"
  [Unit]
  Description=rsnapshot respaldos cada año

  [Timer]
  OnCalendar=yearly
  Persistent=true
  Unit=rsnapshot-anual.service

  [Install]
  WantedBy=timers.target
#+END_SRC
*** Activación de los timers
#+BEGIN_SRC shell :results silent :dir /sudo::
  systemctl daemon-reload
  for tiempo in hora dia semana mes anual
  do
      systemctl enable rsnapshot-$tiempo.timer
      systemctl start rsnapshot-$tiempo.timer
  done
#+END_SRC

#+RESULTS:

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.