aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/%HOME%/.local/bin/virsh-cleanup.sh
blob: b0653f90c93cf0e00867f226ed7167700cb5e8a5 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#!/usr/bin/env bash

# Copyright (c) 2022 Egor Tensin <egor@tensin.name>
# This file is part of the "linux-home" project.
# For details, see https://github.com/egor-tensin/linux-home.
# Distributed under the MIT License.

# This script destroys all libvirt resources.

set -o errexit -o nounset -o pipefail
shopt -s inherit_errexit lastpipe

CONNECT="${CONNECT:=qemu:///system}"
POOL="${POOL:=default}"

dump() {
    local prefix="${FUNCNAME[0]}"
    [ "${#FUNCNAME[@]}" -gt 1 ] && prefix="${FUNCNAME[1]}"

    local msg
    for msg; do
        echo "$prefix: $msg"
    done
}

run_virsh() {
    virsh -q -c "$CONNECT" "$@"
}

list_domains() {
    run_virsh list --all --name
}

list_networks() {
    local name
    run_virsh net-list --all --name | while IFS= read -r name; do
        [ "$name" = default ] && continue
        echo "$name"
    done
}

list_volumes() {
    local name
    run_virsh vol-list "$POOL" | tr -s ' ' | while IFS=' ' read -r name _; do
        echo "$name"
    done
}

remove_domain() {
    local domain
    for domain; do
        dump "$domain"
        run_virsh destroy "$domain"
        run_virsh undefine "$domain"
    done
}

remove_network() {
    local network
    for network; do
        dump "$network"
        run_virsh net-destroy "$network"
        run_virsh net-undefine "$network"
    done
}

remove_volume() {
    local volume
    for volume; do
        dump "$volume"
        run_virsh vol-delete --pool "$POOL" "$volume"
    done
}

main() {
    local item

    list_domains  | while IFS= read -r item; do remove_domain  "$item"; done
    list_volumes  | while IFS= read -r item; do remove_volume  "$item"; done
    list_networks | while IFS= read -r item; do remove_network "$item"; done
}

main