Archives pour la catégorie ‘Sauvegarde’

BackupPC : script de génération d’un rapport d’audit

Le script a pour but de générer un rapport quotidien listant l’ensemble des fichiers ajoutés et modifiés suite au précédent job de sauvegarde d’un client BackupPC. L’exécution de ce script est évidemment à planifier quotidiennement.

# more BackupPC_auditReport
#!/bin/bash
#
# Boris HUISGEN
#
# This script will send a audit report log of the last client backup
#

BACKUPPC_CLIENT="server.my.domain"         # client hostname/IP address
BACKUPPC_LOGDIR=/home/backuppc/pc/server   # BackupPC log directory
BACKUPPC_BINDIR=/usr/local/BackupPC/bin    # BackupPC bin directory
MAIL=1                                     # enable/disable mail report
MAIL_TO="admin@my.domain"                  # mail to address
MAIL_CC="toto@my.domain"                   # mail cc addresses (comma list)

#
# script
#

XFER_PID="$1"                        # custom XFER PID

if [ ! -d $BACKUPPC_LOGDIR ]; then
   exit;
fi

CURRENT_DIR=$(pwd)

cd $BACKUPPC_LOGDIR

if [ -z "$XFER_PID" ]; then
   XFER_PID=$(find . -mindepth 1  -maxdepth 1 -type d | sort -nr | head -1 | cut -d'/' -f2)
fi

XFERLOG="$BACKUPPC_LOGDIR/XferLOG.$XFER_PID.z"

echo "Checking $XFERLOG..." > /tmp/report_$BACKUPPC_CLIENT
echo "" >> /tmp/report_$BACKUPPC_CLIENT

$BACKUPPC_BINDIR/BackupPC_zcat $XFERLOG | \
grep -e 'create  ' | grep -e '.*\.php' -e '.*\.html' | \
grep -v -i -e '.*/cache/.*' -e '.*templates_c/.*' \
>> /tmp/report_$BACKUPPC_CLIENT

if [ $MAIL -eq "1" ] ; then
   if [ -z $MAIL_CC ]; then
      cat /tmp/report_$BACKUPPC_CLIENT | mail -s '[backuppc] Audit report for '$BACKUPPC_CLIENT $MAIL_TO
   else
      cat /tmp/report_$BACKUPPC_CLIENT | mail -s '[backuppc] Audit report for '$BACKUPPC_CLIENT -c $MAIL_CC $MAIL_TO
   fi
else
   cat /tmp/report_$BACKUPPC_CLIENT
fi

rm /tmp/report_$BACKUPPC_CLIENT
cd $CURRENT_DIR

OpenVZ : script de sauvegarde des CT

Voici le script que j’utilise pour dumper quotidiennement l’ensemble de mes CT OpenVZ. Outre les options de dump habituelles, il  est possible de préciser le nombre de dumps à conserver localement sur le HN et d’activer une copie des dumps par rsync sur un serveur distant, en vue de constituer un historique plus conséquent. Il est possible de limiter le débit I/O de génération des dumps (I/O disque) tout comme pour la copie (I/O réseau) afin d’éviter une perturbation conséquente de votre serveur.

Bref, c’est simple et efficace, donc à placer en cron très rapidement !

#!/bin/bash
#
# vzbackup.sh
#
# Boris HUISGEN <bhuisgen@hbis.fr>
#

PATH=$PATH:/usr/sbin

# backup settings

VZDUMP_DIR="/home/backup/vz"    # backup directory
VZDUMP_MODE="snapshot"          # dump mode (stop/suspend/snapshot)
VZDUMP_COMPRESS="yes"           # compress dump files (yes/no)
VZDUMP_MAXFILES="3"             # maximum backups per CT to keep in local
VZDUMP_BWLIMIT="0"              # limit I/O bandwith (unit kbytes/s, 0 to disable)
VZDUMP_EXTRA_OPTIONS=""         # extra options (man vzdump)

# remote copy settings

RSYNC_ENABLE="yes"              # copy backup directory to remote server (yes/no)
RSYNC_HOST="backup.my.domain"   # remote server host
RSYNC_USER="root"               # remote server user
RSYNC_DIR="/home/backup/mcbain" # remote server directory
RSYNC_DELETE="no"               # delete old backups on remote server (set to no to keep a remote historic)
RSYNC_BWLIMIT="0"               # limit I/O bandwith (unit kbytes/s, 0 to disable)
RSYNC_EXTRA_OPTIONS=""          # extra options (man rsync)

#
# DO NOT MODIFY AFTER THIS LINE !!!
#

VZLIST="$(which vzlist)"
VZDUMP="$(which vzdump)"
VZDUMP_OPTIONS="--stdexcludes"

RSYNC="$(which rsync)"
RSYNC_OPTIONS="-avz"

function log {
 echo "[" `date "+%Y-%m-%d %H:%M:%S"` "] $1"
}

# create backup directory
if [ ! -d $VZDUMP_DIR ]
then
 mkdir -p $VZDUMP_DIR;
fi

# set vzdump options
VZDUMP_OPTIONS="$VZDUMP_OPTIONS --$VZDUMP_MODE"

if [ $VZDUMP_COMPRESS = "yes" ]
then
 VZDUMP_OPTIONS="$VZDUMP_OPTIONS --compress"
fi

VZDUMP_OPTIONS="$VZDUMP_OPTIONS --maxfiles $VZDUMP_MAXFILES"

if [ $VZDUMP_BWLIMIT -gt "0" ]
then
 VZDUMP_OPTIONS="$VZDUMP_OPTIONS --bwlimit $VZDUMP_BWLIMIT"
fi

if [ -z $VZDUMP_EXTRA_OPTIONS ]
then
 VZDUMP_OPTIONS="$VZDUMP_OPTIONS $VZDUMP_EXTRA_OPTIONS"
fi

# set rsync options
if [ $RSYNC_DELETE = "yes" ]
then
 RSYNC_OPTIONS="$RSYNC_OPTIONS --delete"
fi

if [ $RSYNC_BWLIMIT -gt "0" ]
then
 RSYNC_OPTIONS="$RSYNC_OPTIONS --bwlimit=$RSYNC_BWLIMIT"fi
fi

if [ -z $RSYNC_EXTRA_OPTIONS ]
then
 RSYNC_OPTIONS="$RSYNC_OPTIONS $RSYNC_EXTRA_OPTIONS"
fi

# dump all CT
for CT in `$VZLIST -Ho veid`; do
 log "Starting backup of CT $CT..."

 # create CT directory
 VZDUMP_SUBDIR="$VZDUMP_DIR/$CT"
 if [ ! -d $VZDUMP_SUBDIR ]
 then
  mkdir $VZDUMP_SUBDIR
 fi

 # start vzdump
 $VZDUMP $VZDUMP_OPTIONS --dumpdir=$VZDUMP_SUBDIR $CT

 log "Backup done."
done

# copy backup directory to remote server
if [ $RSYNC_ENABLE = "yes" ]
then
 log "Synchronizing to remote server..."

 # start rsync
 $RSYNC $RSYNC_OPTIONS $VZDUMP_DIR/ $RSYNC_USER@$RSYNC_HOST:$RSYNC_DIR/

 log "Synchronization done."
fi

# end of script

Voici un exemple de sortie :

# ./vzbackup.sh
Starting backup of CT 101...
INFO: starting new backup job: vzdump --stdexcludes --snapshot --compress --maxfiles 4 --dumpdir=/home/backup/vz/101 101
INFO: Starting Backup of VM 101 (openvz)
INFO: CTID 101 exist mounted running
INFO: status = CTID 101 exist mounted running
INFO: backup mode: snapshot
INFO: ionice priority: 7
INFO: creating lvm snapshot of /dev/mapper/openvz-vz ('/dev/openvz/vzsnap-mcbain-0')
INFO:   Logical volume "vzsnap-mcbain-0" created
INFO: creating archive '/home/backup/vz/101/vzdump-openvz-101-2011_02_16-17_42_01.tgz'
INFO: Total bytes written: 2044569600 (2.0GiB, 8.9MiB/s)
INFO: archive file size: 1016MB
INFO:   Logical volume "vzsnap-mcbain-0" successfully removed
INFO: Finished Backup of VM 101 (00:05:24)
INFO: Backup job finished successfuly
Backup done.
Synchronizing to remote server...
sending incremental file list
101/
101/vzdump-openvz-101-2011_02_16-17_42_01.log
101/vzdump-openvz-101-2011_02_16-17_42_01.tgz
Synchronization done.

BackupPC : sauvegarder le serveur localhost

Si vous souhaitez sauvegarder les données locales de votre serveur BackupPC (localhost), il faut effectuer une configuration spécifique afin d’éviter le chiffrement inutile par SSH. Je vous fais part des paramètres que j’ai spécifié sur mon serveur BackupPC (qui est également mon poste de travail) :

$Conf{ClientNameAlias} = '127.0.0.1';
$Conf{XferMethod} = 'rsync';
$Conf{RsyncClientCmd} = '$rsyncPath $argList+';
$Conf{RsyncClientRestoreCmd} = '$rsyncPath $argList+';
$Conf{RsyncShareName} = [
  '/Users/bhuisgen/'
];

Les temps de sauvegarde/restauration devraient d’ailleurs être améliorés.

BackupPC : installation sous Mac OS X

backuppc-macosxJ’ai installé le système de backup BackupPC sur mon Mac Mini, afin de sauvegarder facilement des serveurs distants. Voici donc la procédure complète d’installation de BackupPC sous Mac OS X, avec un serveur Web Nginx et support CGI / Perl. En fin d’article, je vous fais part d’une idée de configuration possible pour le stockage sur un disque dur externe / clé USB.

Je vous renvoie en premier lieu à mes articles précédents :

Les modules Perl Compress::zlib et File::RsyncP sont à installer, comme toujours par MacPorts :

sudo port install p5-compress-zlib
sudo port install p5-file-rsyncp

Au niveau des scripts de démarrage de BackupPC, pkill et cie sera nécessaire :

sudo port install proctools

Je vais effectuer l’installation de BackupPC dans /opt/local pour rester dans l’esprit MacPorts :

cd /opt/local/src
tar xzf BackupPC.tar.gz
sudo perl configure.pl
--> Full path to existing main config.pl []?
--> Are these paths correct? [y]?
--> BackupPC will run on host [bhuisgen.local]?
--> Install directory (full path) [/usr/local/BackupPC]? /opt/local/share/backuppc
--> Data directory (full path) [/data/BackupPC]? /Volumes/WORK/backup/backuppc
--> Compression level [3]?
--> Apache image directory (full path) []? /opt/local/www/backuppc/images
--> URL for image directory (omit http://host; starts with '/') []? /backuppc/images
--> CGI bin directory (full path) []? /opt/local/www/backuppc

L’installation effectue la copie des fichiers de configuration dans /etc. Cà ne me va pas du tout et les majuscules dans les répertoires je déteste ; donc fix direct :

sudo mv BackupPC/ /opt/local/etc/backuppc
sudo mv /var/log/BackupPC/ /opt/local/var/log/backuppc
sudo chown root:admin /opt/local/etc/backuppc
sudo chown root:admin /opt/local/var/log/backuppc/

Il faut ensuite modifier le fichier /opt/local/share/backuppc/lib/BackupPC/Lib.pm pour lui préciser les répertoires /opt/local/etc/backuppc et /opt/local/var/log/backuppc car les répertoires sont codés en dur (pas bien bouh) :

--- Lib.pm.old  2009-04-10 00:56:46.000000000 +0200
+++ Lib.pm      2009-04-10 00:57:33.000000000 +0200
@@ -128,8 +128,8 @@
             useFHS     => $useFHS,
             TopDir     => $topDir,
             InstallDir => $installDir,
-            ConfDir    => $confDir eq "" ? '/etc/BackupPC' : $confDir,
-            LogDir     => '/var/log/BackupPC',
+            ConfDir    => $confDir eq "" ? '/opt/local/etc/backuppc' : $confDir,
+            LogDir     => '/opt/local/var/log/backuppc',

Dans le fichier principal de configuration /opt/local/etc/backuppc/config.pl, il faut également modifier les répertoires :

$Conf{TopDir}      = '/Volumes/WORK/backup/backuppc';
$Conf{ConfDir}     = '/opt/local/etc/backuppc';
$Conf{LogDir}      = '/opt/local/var/log/backuppc';
$Conf{InstallDir}  = '/opt/local/share/backuppc';
$Conf{CgiDir}      = '/opt/local/www/backuppc';

Vérifiez également que root est bien l’utilisateur exécutant le démon BackupPC :

$Conf{BackupPCUser} = 'root';

Remarque : vous pouvez autrement laisser l’utilisateur backuppc, mais il faut le créer et modifier en conséquence le script de démarrage du démon (sans compter la partie CGI).

Ensuite, j’autorise par défaut tous les droits d’administration :

$Conf{CgiAdminUserGroup} = '';
$Conf{CgiAdminUsers}     = '*';

La configuration est à présent terminée. A présent un petit lien symbolique qui simplifie l’accès web :

$ cd /opt/local/www/backuppc
$ sudo ln -s ./BackupPC_Admin index.cgi

Il reste à créer le script de démarrage de BackupPC. J’ai donc fait un wrapper et un script launchd s’appuyant sur daemondo de MacPorts :

$ cd /opt/local/etc/LaunchDaemons/fr.hbis.backuppc
$ more backuppc.wrapper
#!/bin/sh
#
# daemondo support script for BackupPC
#
# Boris HUISGEN <bhuisgen@hbis.fr>
#

# backuppc directory, needed to pkill
BACKUPPC_DIR="/opt/local/share/backuppc/"
# command to start daemon
CMD="/opt/local/bin/perl /opt/local/share/backuppc/bin/BackupPC"

#
# Init
#
prefix=/opt/local

#
# Start
#

Start()
{
 $CMD
}

#
# Stop
#

Stop()
{
 pkill -f $BACKUPPC_DIR
}

#
# Restart
#

Restart()
{
 Stop
 Start
}

#
# Run
#

Run()
{
 case $1 in
 start  ) Start   ;;
 stop   ) Stop    ;;
 restart) Restart ;;
 *      ) echo "$0: unknown argument: $1";;
 esac
}

#
# Run a phase based on the selector
#
Run $1
$ more fr.hbis.backuppc.plist
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
   <key>Debug</key>
   <false/>
   <key>Label</key>
   <string>fr.hbis.backuppc</string>
   <key>OnDemand</key>
   <false/>
   <key>ProgramArguments</key>
   <array>
      <string>/opt/local/bin/daemondo</string>
      <string>--label=backuppc</string>
      <string>--start-cmd</string>
      <string>/opt/local/etc/LaunchDaemons/org.macports.backuppc/backuppc.wrapper</string>
      <string>start</string>
      <string>;</string>
      <string>--stop-cmd</string>
      <string>/opt/local/etc/LaunchDaemons/org.macports.backuppc/backuppc.wrapper</string>
      <string>stop</string>
      <string>;</string>
      <string>--restart-cmd</string>
      <string>/opt/local/etc/LaunchDaemons/orgs.macports.backuppc/backuppc.wrapper</string>
      <string>restart</string>
      <string>;</string>
      <string>--pid=none</string>
   </array>
   <key>RunAtLoad</key>
   <false/>
</dict>
</plist>

On référence le script pour démarrer BackupPC :

$ sudo launchctl load -w fr.hbis.backuppc.plist

Si tout est OK, http://localhost/backuppc/ doit vous afficher l’interface de gestion de BackupPC. Il vous reste à configurer les serveurs à sauvegarder, partie hosts. Le reste peut se faire avec la documentation accessible depuis l’interface.

Dans le cas de sauvegardes manuelles sur un volume externe, launchd peut détecter le montage de périphérique et lancer un script particulier. Cette fonctionnalité peut être utilisée pour détecter la présence effective de votre volume externe (pour ma part /Volumes/WORK) et lancer un job manuel de backup de vos serveurs gràce à /opt/local/share/backuppc/bin/BackupPC_serverMesg. Je pense que je vous ferai un article d’ici peu avec les scripts adéquats…

Haut de page