📑

virshのdomainのバックアップを取得するスクリプト

2024/12/18に公開

スクリプト本体

#!/bin/bash

# 引数チェック
if [ $# -ne 1 ]; then
    echo "Usage: $0 <domain_name>"
    exit 1
fi

DOMAIN_NAME=$1
BACKUP_DIR="/var/lib/libvirt/backup"
DATE=$(date +%Y%m%d_%H%M%S)

# バックアップディレクトリの作成
mkdir -p "$BACKUP_DIR"

# domainが存在するか確認
if ! virsh dominfo "$DOMAIN_NAME" >/dev/null 2>&1; then
    echo "Error: Domain $DOMAIN_NAME does not exist"
    exit 1
fi

# domainの状態を確認
DOMAIN_STATE=$(virsh domstate "$DOMAIN_NAME")
if [ "$DOMAIN_STATE" != "shut off" ]; then
    echo "Warning: Domain $DOMAIN_NAME is running. Shutting down..."
    virsh shutdown "$DOMAIN_NAME"
    
    # シャットダウンを待つ
    for i in {1..60}; do
        if [ "$(virsh domstate "$DOMAIN_NAME")" == "shut off" ]; then
            break
        fi
        echo "Waiting for shutdown... ($i/60)"
        sleep 5
    done
    
    if [ "$(virsh domstate "$DOMAIN_NAME")" != "shut off" ]; then
        echo "Error: Failed to shutdown domain"
        exit 1
    fi
fi

# ボリュームの一覧を取得
echo "Getting volume list for $DOMAIN_NAME..."
VOLUMES=$(virsh domblklist "$DOMAIN_NAME" | grep -v "^$\|Source$\|Target$\|^-" | awk '{print $2}')

# 各ボリュームをバックアップ
for VOLUME in $VOLUMES; do
    if [ -n "$VOLUME" ] && [ "$VOLUME" != "-" ]; then
        VOLUME_NAME=$(basename "$VOLUME")
        BACKUP_PATH="$BACKUP_DIR/${DOMAIN_NAME}_${VOLUME_NAME}_${DATE}.qcow2"
        
        echo "Backing up volume: $VOLUME to $BACKUP_PATH"
        if ! cp "$VOLUME" "$BACKUP_PATH"; then
            echo "Error: Failed to backup volume $VOLUME"
            exit 1
        fi
    fi
done

echo "Backup completed successfully!"
echo "Backup location: $BACKUP_DIR"

# バックアップの一覧を表示
echo "Backup files:"
ls -lh "$BACKUP_DIR" | grep "$DOMAIN_NAME"

使いかた

まずドメイン一覧を取得する。

virsh list --all
 Id   Name           State
-------------------------------
 -    hoge-default   shut off

バックアップを実行する。

./virsh-backup.sh hoge-default

Discussion