aboutsummaryrefslogtreecommitdiffstats
path: root/molecule/default/tests/test_manual_backup.py
blob: ea48655e0eaeeec3495d4ef6fe4092fd8e430aae (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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
import pytest
from datetime import datetime

testinfra_hosts = ["borg-client", "borg-client-2"]


def get_server_info(hostname):
    if hostname == "borg-client-2":
        return ("backupserver", "borg-server-2", "/var/backups")
    return ("borg", "borg-server", "/opt/borg")


compression_types = [
    "none",
    "lz4",
    "zstd",
    "zstd,10",
    "zlib",
    "zlib,6",
]


"""Creates backups with all possible combinations of compression to the backup
host"""


@pytest.mark.parametrize("compression", compression_types)
def test_backup_push(host, compression):
    hostname = host.backend.get_hostname()
    server_user, server_host, server_path = get_server_info(hostname)

    c = host.run(
        f'borg create -C "{compression}" {server_user}@{server_host}:{server_path}/{hostname}::testinfra-{{now:%S.%f}} /etc'
    )
    assert c.rc == 0
    assert c.stdout == ""
    assert c.stderr == ""


@pytest.mark.parametrize("compression", compression_types)
def test_backup_restore(host, compression):
    hostname = host.backend.get_hostname()
    server_user, server_host, server_path = get_server_info(hostname)
    timestamp = datetime.now().strftime("%Y%m%d-%H%M%S-%f")
    archive_name = f"testinfra-backup-restore-{compression}-{timestamp}"

    # Create backup
    c = host.run(
        f'borg create -C "{compression}" {server_user}@{server_host}:{server_path}/{hostname}::{archive_name} /etc'
    )
    assert c.rc == 0
    assert c.stdout == ""
    assert c.stderr == ""

    # Restore Backup
    c = host.run(
        f"cd /mnt && borg extract {server_user}@{server_host}:{server_path}/{hostname}::{archive_name}"
    )
    assert c.rc == 0
    assert c.stdout == ""
    assert c.stderr == ""

    # Check if every file exists, content has, and permissions / metadata
    c1 = host.run(
        'cd /etc && find /etc -type f -printf "%P\\n" | sort | xargs -i sh -c "echo {}; sha512sum {} | cut -d \' \' -f 1; ls -l {}; echo"'
    )
    c2 = host.run(
        'cd /mnt/etc && find /etc -type f -printf "%P\\n" | sort | xargs -i sh -c "echo {}; sha512sum {} | cut -d \' \' -f 1; ls -l {}; echo"'
    )
    assert c1.rc == 0 and c2.rc == 0
    assert c1.stderr == "" and c2.stderr == ""
    assert c1.stdout == c2.stdout

    # Delete directory extract directory again for future tests
    c = host.run("rm -rf /mnt/etc")
    assert c.rc == 0
    assert c.stdout == ""
    assert c.stderr == ""

    # Delete backup
    c = host.run(
        f"borg delete {server_user}@{server_host}:{server_path}/{hostname}::{archive_name}"
    )
    assert c.rc == 0
    assert c.stdout == ""
    assert c.stderr == ""


def test_after_backup_scripts_prune_old_archives(host):
    hostname = host.backend.get_hostname()
    if hostname != "borg-client":
        return

    server_user, server_host, server_path = get_server_info(hostname)
    backup_script_path = "/usr/local/bin/run_borg_backup@borg-server"
    prune_script_path = "/usr/local/bin/run_borg_prune@borg-server"

    original_backup_script = host.file(backup_script_path).content_string
    original_prune_script = host.file(prune_script_path).content_string
    prefix = f"testprune-{datetime.now().strftime('%Y%m%d%H%M%S%f')}"

    modified_backup_script = original_backup_script.replace(
        "::{hostname}-{now:%Y-%m-%dT%H:%M:%S}",
        f"::{prefix}-${{BORG_TEST_ITERATION}}-{{now:%Y-%m-%dT%H:%M:%S}}",
    )
    modified_prune_script = original_prune_script.replace(
        "{hostname}-*",
        f"{prefix}-*",
    )

    rewrite = host.run(
        "python3 - <<'PY'\n"
        "from pathlib import Path\n"
        f"Path({backup_script_path!r}).write_text({modified_backup_script!r})\n"
        f"Path({prune_script_path!r}).write_text({modified_prune_script!r})\n"
        "PY"
    )
    assert rewrite.rc == 0
    assert host.run(f"bash -n {backup_script_path}").rc == 0
    assert host.run(f"bash -n {prune_script_path}").rc == 0

    try:
        for iteration in range(4):
            backup = host.run(f"BORG_TEST_ITERATION={iteration} {backup_script_path}")
            assert backup.rc == 0
            prune = host.run(prune_script_path)
            assert prune.rc == 0

        archives = host.run(
            f"borg list {server_user}@{server_host}:{server_path}/{hostname} --glob-archives '{prefix}-*'"
        )
        assert archives.rc == 0

        archive_lines = [line for line in archives.stdout.splitlines() if line.strip()]
        assert len(archive_lines) == 2
    finally:
        restore = host.run(
            "python3 - <<'PY'\n"
            "from pathlib import Path\n"
            f"Path({backup_script_path!r}).write_text({original_backup_script!r})\n"
            f"Path({prune_script_path!r}).write_text({original_prune_script!r})\n"
            "PY"
        )
        assert restore.rc == 0


def test_manual_prune_script_prunes_old_archives(host):
    hostname = host.backend.get_hostname()
    if hostname != "borg-client-2":
        return

    server_user, server_host, server_path = get_server_info(hostname)
    prefix = f"testprune-timer-{datetime.now().strftime('%Y%m%d%H%M%S%f')}"
    script_path = "/usr/local/bin/run_borg_prune@borg-server-2"

    for iteration in range(4):
        create = host.run(
            f"borg create -C lz4 {server_user}@{server_host}:{server_path}/{hostname}::{prefix}-{iteration}-{{now:%Y-%m-%dT%H:%M:%S}} /etc"
        )
        assert create.rc == 0

    original_script = host.file(script_path).content_string
    assert "--keep-daily 7" in original_script
    assert "--keep-weekly 4" in original_script

    modified_script = (
        original_script.replace("{hostname}-*", f"{prefix}-*")
        .replace("--keep-daily 7", "--keep-last 2")
        .replace("--keep-weekly 4", "")
    )
    assert "--keep-last 2" in modified_script
    assert "--keep-daily 7" not in modified_script
    assert "--keep-weekly 4" not in modified_script

    rewrite = host.run(
        "python3 - <<'PY'\n"
        "from pathlib import Path\n"
        f"Path({script_path!r}).write_text({modified_script!r})\n"
        "PY"
    )
    assert rewrite.rc == 0
    syntax_check = host.run(f"bash -n {script_path}")
    assert syntax_check.rc == 0

    try:
        result = host.run(script_path)
        assert result.rc == 0

        archives = host.run(
            f"borg list {server_user}@{server_host}:{server_path}/{hostname} --glob-archives '{prefix}-*'"
        )
        assert archives.rc == 0

        archive_lines = [line for line in archives.stdout.splitlines() if line.strip()]
        assert len(archive_lines) == 2
    finally:
        restore = host.run(
            "python3 - <<'PY'\n"
            "from pathlib import Path\n"
            f"Path({script_path!r}).write_text({original_script!r})\n"
            "PY"
        )
        assert restore.rc == 0

        cleanup = host.run(
            f"borg delete --glob-archives '{prefix}-*' {server_user}@{server_host}:{server_path}/{hostname}"
        )
        assert cleanup.rc == 0