netbox-db-backup 0.1.6__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,22 @@
1
+ from netbox.plugins import PluginConfig
2
+
3
+ MIN_FREE_BYTES = 5 * 1024 ** 3
4
+ DEFAULT_KEEP_BACKUPS = 5
5
+
6
+
7
+ class NetBoxDBBackupConfig(PluginConfig):
8
+ name = "netbox_db_backup"
9
+ verbose_name = "Database Backups"
10
+ description = "Create, list, download, and delete PostgreSQL backups."
11
+ version = "0.1.6"
12
+ author = "Najafzadeh Reza"
13
+ base_url = "db-backup"
14
+ min_version = "4.5.0"
15
+ default_settings = {
16
+ "backup_dir": "/opt/netbox/netbox/media/db_backups",
17
+ "min_free_bytes": MIN_FREE_BYTES,
18
+ "keep_backups": DEFAULT_KEEP_BACKUPS,
19
+ }
20
+
21
+
22
+ config = NetBoxDBBackupConfig
@@ -0,0 +1,363 @@
1
+ import hashlib
2
+ import os
3
+ import shutil
4
+ import subprocess
5
+ import threading
6
+
7
+ from django.conf import settings
8
+ from django.db import close_old_connections, connection
9
+ from django_rq import job
10
+ from netbox.plugins.utils import get_plugin_config
11
+
12
+ from . import DEFAULT_KEEP_BACKUPS, MIN_FREE_BYTES
13
+ from .models import BackupFile, format_bytes
14
+
15
+ JOB_TIMEOUT_SECONDS = 6 * 60 * 60
16
+ PG_DUMP_MISSING = (
17
+ "Backup was not started. pg_dump was not found. "
18
+ "Install the PostgreSQL client tools on the host that runs the RQ worker."
19
+ )
20
+
21
+
22
+ def pg_dump_available():
23
+ return shutil.which("pg_dump") is not None
24
+
25
+
26
+ def backup_directory():
27
+ path = get_plugin_config("netbox_db_backup", "backup_dir")
28
+ if not path:
29
+ raise RuntimeError("backup_dir is not configured.")
30
+ return os.path.realpath(path)
31
+
32
+
33
+ def backup_path(filename):
34
+ if not filename or os.path.basename(filename) != filename:
35
+ raise ValueError("Invalid backup filename.")
36
+ root = backup_directory()
37
+ path = os.path.realpath(os.path.join(root, filename))
38
+ if os.path.commonpath([root, path]) != root:
39
+ raise ValueError("Invalid backup path.")
40
+ return path
41
+
42
+
43
+ class StorageStatus:
44
+ def __init__(
45
+ self,
46
+ path,
47
+ total,
48
+ used,
49
+ free,
50
+ required,
51
+ enough,
52
+ warning,
53
+ status_label,
54
+ reserve=None,
55
+ reserve_note="",
56
+ ):
57
+ self.path = path
58
+ self.total = total
59
+ self.used = used
60
+ self.free = free
61
+ self.required = required
62
+ self.enough = enough
63
+ self.warning = warning
64
+ self.status_label = status_label
65
+ self.reserve = reserve
66
+ self.reserve_note = reserve_note
67
+
68
+ def _display(self, size):
69
+ if size is None:
70
+ return "Unavailable"
71
+ return format_bytes(size)
72
+
73
+ @property
74
+ def free_display(self):
75
+ return self._display(self.free)
76
+
77
+ @property
78
+ def total_display(self):
79
+ return self._display(self.total)
80
+
81
+ @property
82
+ def used_display(self):
83
+ return self._display(self.used)
84
+
85
+ @property
86
+ def required_display(self):
87
+ return self._display(self.required)
88
+
89
+ @property
90
+ def reserve_display(self):
91
+ return self._display(self.reserve)
92
+
93
+ @property
94
+ def needed_display(self):
95
+ if self.required is None or self.reserve is None:
96
+ return "Unavailable"
97
+ return format_bytes(self.required + self.reserve)
98
+
99
+
100
+ def _existing_storage_path(path):
101
+ current = path
102
+ while not os.path.exists(current):
103
+ parent = os.path.dirname(current)
104
+ if parent == current:
105
+ raise RuntimeError(f"Storage path does not exist: {path}")
106
+ current = parent
107
+ return current
108
+
109
+
110
+ def safety_reserve_bytes():
111
+ configured = get_plugin_config("netbox_db_backup", "min_free_bytes")
112
+ try:
113
+ configured = int(configured)
114
+ except (TypeError, ValueError):
115
+ return MIN_FREE_BYTES, "Configured reserve is invalid, so the 5 GB floor is used."
116
+ if configured < MIN_FREE_BYTES:
117
+ return MIN_FREE_BYTES, "Configured reserve is below the 5 GB floor, so 5 GB is used."
118
+ return configured, ""
119
+
120
+
121
+ def database_size_bytes():
122
+ with connection.cursor() as cursor:
123
+ cursor.execute("SELECT pg_database_size(current_database())")
124
+ row = cursor.fetchone()
125
+ if not row or row[0] is None:
126
+ raise RuntimeError("Could not read the database size.")
127
+ return int(row[0])
128
+
129
+
130
+ def storage_status():
131
+ path = ""
132
+ total = used = free = required = None
133
+ reserve, reserve_note = safety_reserve_bytes()
134
+ try:
135
+ path = backup_directory()
136
+ usage = shutil.disk_usage(_existing_storage_path(path))
137
+ total, used, free = usage.total, usage.used, usage.free
138
+ except Exception as error:
139
+ return StorageStatus(
140
+ path=path,
141
+ total=total,
142
+ used=used,
143
+ free=free,
144
+ required=required,
145
+ enough=False,
146
+ warning=f"Backup was not started. Host storage could not be checked: {error}",
147
+ status_label="Storage check failed",
148
+ reserve=reserve,
149
+ reserve_note=reserve_note,
150
+ )
151
+
152
+ database = settings.DATABASES["default"]
153
+ if "postgresql" not in database.get("ENGINE", ""):
154
+ return StorageStatus(
155
+ path=path,
156
+ total=total,
157
+ used=used,
158
+ free=free,
159
+ required=required,
160
+ enough=False,
161
+ warning="Backup was not started. Database backups require PostgreSQL.",
162
+ status_label="Storage check failed",
163
+ reserve=reserve,
164
+ reserve_note=reserve_note,
165
+ )
166
+
167
+ try:
168
+ required = database_size_bytes()
169
+ except Exception as error:
170
+ return StorageStatus(
171
+ path=path,
172
+ total=total,
173
+ used=used,
174
+ free=free,
175
+ required=required,
176
+ enough=False,
177
+ warning=f"Backup was not started. Database size could not be checked: {error}",
178
+ status_label="Storage check failed",
179
+ reserve=reserve,
180
+ reserve_note=reserve_note,
181
+ )
182
+
183
+ if free < required + reserve:
184
+ return StorageStatus(
185
+ path=path,
186
+ total=total,
187
+ used=used,
188
+ free=free,
189
+ required=required,
190
+ enough=False,
191
+ warning=(
192
+ f"Backup was not started. Host storage has {format_bytes(free)} free "
193
+ f"of {format_bytes(total)} at {path}. "
194
+ f"The database is {format_bytes(required)} and {format_bytes(reserve)} "
195
+ f"must stay free for NetBox and the host."
196
+ ),
197
+ status_label="Not enough free space",
198
+ reserve=reserve,
199
+ reserve_note=reserve_note,
200
+ )
201
+
202
+ return StorageStatus(
203
+ path=path,
204
+ total=total,
205
+ used=used,
206
+ free=free,
207
+ required=required,
208
+ enough=True,
209
+ warning="",
210
+ status_label="Enough free space",
211
+ reserve=reserve,
212
+ reserve_note=reserve_note,
213
+ )
214
+
215
+
216
+ def _pg_dump_command(database, destination):
217
+ command = ["pg_dump", "--no-password", "-Fc", "-f", destination, "-d", database["NAME"]]
218
+ if database.get("USER"):
219
+ command.extend(["-U", database["USER"]])
220
+ if database.get("HOST"):
221
+ command.extend(["-h", database["HOST"]])
222
+ if database.get("PORT"):
223
+ command.extend(["-p", str(database["PORT"])])
224
+ return command
225
+
226
+
227
+ def verify_dump(path):
228
+ if shutil.which("pg_restore") is None:
229
+ raise RuntimeError("pg_restore was not found, so the dump was not verified.")
230
+ result = subprocess.run(
231
+ ["pg_restore", "--list", path],
232
+ stdout=subprocess.PIPE,
233
+ stderr=subprocess.PIPE,
234
+ check=False,
235
+ )
236
+ if result.returncode != 0:
237
+ detail = result.stderr.decode(errors="replace").strip()
238
+ raise RuntimeError(detail or "pg_restore could not read the dump.")
239
+
240
+
241
+ def file_sha256(path):
242
+ digest = hashlib.sha256()
243
+ with open(path, "rb") as handle:
244
+ for chunk in iter(lambda: handle.read(1024 * 1024), b""):
245
+ digest.update(chunk)
246
+ return digest.hexdigest()
247
+
248
+
249
+ def _watch_file_size(backup_id, path, stop):
250
+ close_old_connections()
251
+ try:
252
+ while not stop.wait(2):
253
+ if os.path.isfile(path):
254
+ BackupFile.objects.filter(
255
+ pk=backup_id,
256
+ status=BackupFile.STATUS_RUNNING,
257
+ ).update(file_size=os.path.getsize(path))
258
+ finally:
259
+ close_old_connections()
260
+
261
+
262
+ def keep_backup_count():
263
+ configured = get_plugin_config("netbox_db_backup", "keep_backups")
264
+ try:
265
+ configured = int(configured)
266
+ except (TypeError, ValueError):
267
+ return DEFAULT_KEEP_BACKUPS
268
+ if configured < 1:
269
+ return 1
270
+ return configured
271
+
272
+
273
+ def prune_old_backups():
274
+ keep = keep_backup_count()
275
+ kept = (BackupFile.STATUS_COMPLETED, BackupFile.STATUS_VERIFIED)
276
+ extras = BackupFile.objects.filter(status__in=kept).order_by("-created_at")[keep:]
277
+ for old in extras:
278
+ try:
279
+ path = backup_path(old.filename)
280
+ except ValueError:
281
+ path = None
282
+ if path and os.path.isfile(path):
283
+ os.remove(path)
284
+ old.status = BackupFile.STATUS_DELETED
285
+ old.deleted_by = "retention"
286
+ old.save(update_fields=["status", "deleted_by"])
287
+
288
+
289
+ def _mark_failed(backup, message, destination=None):
290
+ backup.status = BackupFile.STATUS_FAILED
291
+ backup.error = (message or "Backup failed.")[:4000]
292
+ backup.save(update_fields=["status", "error"])
293
+ if destination and os.path.isfile(destination):
294
+ os.remove(destination)
295
+
296
+
297
+ @job("default", timeout=JOB_TIMEOUT_SECONDS)
298
+ def create_database_backup(backup_id):
299
+ backup = BackupFile.objects.get(pk=backup_id)
300
+ destination = None
301
+ started_dump = False
302
+ stop_watch = threading.Event()
303
+ watcher = None
304
+ try:
305
+ if not pg_dump_available():
306
+ raise RuntimeError(PG_DUMP_MISSING)
307
+
308
+ database = settings.DATABASES["default"]
309
+ if "postgresql" not in database.get("ENGINE", ""):
310
+ raise RuntimeError("Database backups require PostgreSQL.")
311
+
312
+ status = storage_status()
313
+ if not status.enough:
314
+ raise RuntimeError(status.warning)
315
+
316
+ directory = backup_directory()
317
+ os.makedirs(directory, mode=0o750, exist_ok=True)
318
+ destination = backup_path(backup.filename)
319
+ if os.path.exists(destination):
320
+ raise RuntimeError(f"Backup already exists: {backup.filename}")
321
+ started_dump = True
322
+ watcher = threading.Thread(
323
+ target=_watch_file_size,
324
+ args=(backup.pk, destination, stop_watch),
325
+ daemon=True,
326
+ )
327
+ watcher.start()
328
+
329
+ env = os.environ.copy()
330
+ password = database.get("PASSWORD")
331
+ if password:
332
+ env["PGPASSWORD"] = password
333
+ sslmode = (database.get("OPTIONS") or {}).get("sslmode")
334
+ if sslmode:
335
+ env["PGSSLMODE"] = sslmode
336
+
337
+ result = subprocess.run(
338
+ _pg_dump_command(database, destination),
339
+ stderr=subprocess.PIPE,
340
+ env=env,
341
+ check=False,
342
+ )
343
+ stop_watch.set()
344
+ watcher.join(timeout=5)
345
+ if result.returncode != 0:
346
+ detail = result.stderr.decode(errors="replace").strip()
347
+ raise RuntimeError(detail or f"pg_dump exited {result.returncode}")
348
+
349
+ os.chmod(destination, 0o640)
350
+ verify_dump(destination)
351
+ backup.file_size = os.path.getsize(destination)
352
+ backup.checksum = file_sha256(destination)
353
+ backup.status = BackupFile.STATUS_VERIFIED
354
+ backup.error = ""
355
+ backup.save(update_fields=["file_size", "checksum", "status", "error"])
356
+ except Exception as error:
357
+ stop_watch.set()
358
+ if watcher is not None:
359
+ watcher.join(timeout=5)
360
+ _mark_failed(backup, str(error), destination if started_dump else None)
361
+ raise
362
+ else:
363
+ prune_old_backups()
@@ -0,0 +1,32 @@
1
+ from django.db import migrations, models
2
+
3
+
4
+ class Migration(migrations.Migration):
5
+
6
+ initial = True
7
+
8
+ dependencies = []
9
+
10
+ operations = [
11
+ migrations.CreateModel(
12
+ name="BackupFile",
13
+ fields=[
14
+ (
15
+ "id",
16
+ models.BigAutoField(
17
+ auto_created=True,
18
+ primary_key=True,
19
+ serialize=False,
20
+ verbose_name="ID",
21
+ ),
22
+ ),
23
+ ("filename", models.CharField(max_length=255)),
24
+ ("file_size", models.BigIntegerField()),
25
+ ("created_at", models.DateTimeField(auto_now_add=True)),
26
+ ("netbox_version", models.CharField(max_length=64)),
27
+ ],
28
+ options={
29
+ "ordering": ["-created_at"],
30
+ },
31
+ ),
32
+ ]
@@ -0,0 +1,34 @@
1
+ from django.db import migrations, models
2
+
3
+
4
+ class Migration(migrations.Migration):
5
+
6
+ dependencies = [
7
+ ("netbox_db_backup", "0001_initial"),
8
+ ]
9
+
10
+ operations = [
11
+ migrations.AddField(
12
+ model_name="backupfile",
13
+ name="status",
14
+ field=models.CharField(default="completed", max_length=16),
15
+ ),
16
+ migrations.AddField(
17
+ model_name="backupfile",
18
+ name="error",
19
+ field=models.TextField(blank=True, default=""),
20
+ ),
21
+ migrations.AlterField(
22
+ model_name="backupfile",
23
+ name="file_size",
24
+ field=models.BigIntegerField(default=0),
25
+ ),
26
+ migrations.AddConstraint(
27
+ model_name="backupfile",
28
+ constraint=models.UniqueConstraint(
29
+ condition=models.Q(status="running"),
30
+ fields=("status",),
31
+ name="netbox_db_backup_one_running",
32
+ ),
33
+ ),
34
+ ]
@@ -0,0 +1,16 @@
1
+ from django.db import migrations, models
2
+
3
+
4
+ class Migration(migrations.Migration):
5
+
6
+ dependencies = [
7
+ ("netbox_db_backup", "0002_backup_status"),
8
+ ]
9
+
10
+ operations = [
11
+ migrations.AddField(
12
+ model_name="backupfile",
13
+ name="expected_size",
14
+ field=models.BigIntegerField(default=0),
15
+ ),
16
+ ]
@@ -0,0 +1,16 @@
1
+ from django.db import migrations, models
2
+
3
+
4
+ class Migration(migrations.Migration):
5
+
6
+ dependencies = [
7
+ ("netbox_db_backup", "0003_expected_size"),
8
+ ]
9
+
10
+ operations = [
11
+ migrations.AddField(
12
+ model_name="backupfile",
13
+ name="checksum",
14
+ field=models.CharField(blank=True, default="", max_length=64),
15
+ ),
16
+ ]
@@ -0,0 +1,21 @@
1
+ from django.db import migrations, models
2
+
3
+
4
+ class Migration(migrations.Migration):
5
+
6
+ dependencies = [
7
+ ("netbox_db_backup", "0004_checksum"),
8
+ ]
9
+
10
+ operations = [
11
+ migrations.AddField(
12
+ model_name="backupfile",
13
+ name="created_by",
14
+ field=models.CharField(blank=True, default="", max_length=150),
15
+ ),
16
+ migrations.AddField(
17
+ model_name="backupfile",
18
+ name="deleted_by",
19
+ field=models.CharField(blank=True, default="", max_length=150),
20
+ ),
21
+ ]
File without changes
@@ -0,0 +1,71 @@
1
+ from django.conf import settings
2
+ from django.db import models
3
+
4
+
5
+ def current_netbox_version():
6
+ version = getattr(settings, "VERSION", "")
7
+ if isinstance(version, (list, tuple)):
8
+ return ".".join(str(part) for part in version)
9
+ return str(version)
10
+
11
+
12
+ def format_bytes(size):
13
+ value = float(size or 0)
14
+ for unit in ("B", "KB", "MB", "GB"):
15
+ if value < 1024 or unit == "GB":
16
+ if unit == "B":
17
+ return f"{int(value)} B"
18
+ return f"{value:.1f} {unit}"
19
+ value /= 1024
20
+ return f"{int(size or 0)} B"
21
+
22
+
23
+ class BackupFile(models.Model):
24
+ STATUS_RUNNING = "running"
25
+ STATUS_COMPLETED = "completed"
26
+ STATUS_VERIFIED = "verified"
27
+ STATUS_FAILED = "failed"
28
+ STATUS_DELETED = "deleted"
29
+
30
+ filename = models.CharField(max_length=255)
31
+ file_size = models.BigIntegerField(default=0)
32
+ expected_size = models.BigIntegerField(default=0)
33
+ checksum = models.CharField(max_length=64, blank=True, default="")
34
+ created_by = models.CharField(max_length=150, blank=True, default="")
35
+ deleted_by = models.CharField(max_length=150, blank=True, default="")
36
+ created_at = models.DateTimeField(auto_now_add=True)
37
+ netbox_version = models.CharField(max_length=64)
38
+ status = models.CharField(max_length=16, default=STATUS_COMPLETED)
39
+ error = models.TextField(blank=True, default="")
40
+
41
+ class Meta:
42
+ ordering = ["-created_at"]
43
+ constraints = [
44
+ models.UniqueConstraint(
45
+ fields=["status"],
46
+ condition=models.Q(status="running"),
47
+ name="netbox_db_backup_one_running",
48
+ )
49
+ ]
50
+
51
+ def __str__(self):
52
+ return self.filename
53
+
54
+ @property
55
+ def size_display(self):
56
+ return format_bytes(self.file_size)
57
+
58
+ @property
59
+ def progress_display(self):
60
+ if self.status == self.STATUS_RUNNING and self.expected_size:
61
+ return f"{format_bytes(self.file_size)} / {format_bytes(self.expected_size)}"
62
+ if self.status in (self.STATUS_COMPLETED, self.STATUS_VERIFIED, self.STATUS_DELETED):
63
+ return format_bytes(self.file_size)
64
+ return "—"
65
+
66
+ def compatible_with(self, running_version):
67
+ return (self.netbox_version or "").strip() == (running_version or "").strip()
68
+
69
+ @classmethod
70
+ def in_progress(cls):
71
+ return cls.objects.filter(status=cls.STATUS_RUNNING).exists()
@@ -0,0 +1,9 @@
1
+ from netbox.plugins import PluginMenuItem
2
+
3
+ menu_items = (
4
+ PluginMenuItem(
5
+ link="plugins:netbox_db_backup:backup_list",
6
+ link_text="Database Backups",
7
+ staff_only=True,
8
+ ),
9
+ )
@@ -0,0 +1,182 @@
1
+ {% extends 'base/layout.html' %}
2
+
3
+ {% block title %}Database Backups{% endblock %}
4
+
5
+ {% block content %}
6
+ <div class="row align-items-center mb-3">
7
+ <div class="col">
8
+ <h1 class="page-title mb-0">Database Backups</h1>
9
+ </div>
10
+ <div class="col-auto">
11
+ <form method="post" action="{% url 'plugins:netbox_db_backup:backup_create' %}">
12
+ {% csrf_token %}
13
+ <button type="submit" class="btn btn-primary" {% if not storage.enough or backup_running or not pg_dump_ready %}disabled{% endif %}>Create Backup</button>
14
+ </form>
15
+ </div>
16
+ </div>
17
+
18
+ <div class="alert alert-info" role="status">
19
+ Current Running NetBox Version: <strong>{{ current_version }}</strong>
20
+ </div>
21
+
22
+ {% if backup_running %}
23
+ <div class="alert alert-info" role="status">A backup is running. This page refreshes every 5 seconds.</div>
24
+ {% endif %}
25
+ {% if not pg_dump_ready %}
26
+ <div class="alert alert-warning" role="status">pg_dump was not found. Install the PostgreSQL client tools on the host that runs the RQ worker.</div>
27
+ {% endif %}
28
+
29
+ <div class="row row-cards mb-3">
30
+ <div class="col-sm-6 col-xl d-flex">
31
+ <div class="card flex-fill">
32
+ <div class="card-body">
33
+ <div class="text-secondary">Free space</div>
34
+ <div class="h3 mb-0">{{ storage.free_display }}</div>
35
+ <div class="text-secondary">of {{ storage.total_display }}</div>
36
+ </div>
37
+ </div>
38
+ </div>
39
+ <div class="col-sm-6 col-xl d-flex">
40
+ <div class="card flex-fill">
41
+ <div class="card-body">
42
+ <div class="text-secondary">Database size</div>
43
+ <div class="h3 mb-0">{{ storage.required_display }}</div>
44
+ </div>
45
+ </div>
46
+ </div>
47
+ <div class="col-sm-6 col-xl d-flex">
48
+ <div class="card flex-fill">
49
+ <div class="card-body">
50
+ <div class="text-secondary">Reserve</div>
51
+ <div class="h3 mb-0">{{ storage.reserve_display }}</div>
52
+ <div class="text-secondary">stays free after the backup</div>
53
+ </div>
54
+ </div>
55
+ </div>
56
+ <div class="col-sm-6 col-xl d-flex">
57
+ <div class="card flex-fill">
58
+ <div class="card-body">
59
+ <div class="text-secondary">Space needed</div>
60
+ <div class="h3 mb-0">{{ storage.needed_display }}</div>
61
+ </div>
62
+ </div>
63
+ </div>
64
+ <div class="col-sm-6 col-xl d-flex">
65
+ <div class="card flex-fill {% if storage.enough %}border-success{% else %}border-warning{% endif %}">
66
+ <div class="card-body">
67
+ <div class="text-secondary">Status</div>
68
+ <div class="h3 mb-0">
69
+ {% if storage.enough %}
70
+ <span class="badge text-bg-success">{{ storage.status_label }}</span>
71
+ {% else %}
72
+ <span class="badge text-bg-warning">{{ storage.status_label }}</span>
73
+ {% endif %}
74
+ </div>
75
+ </div>
76
+ </div>
77
+ </div>
78
+ </div>
79
+
80
+ {% if storage.path %}
81
+ <div class="text-secondary mb-3">Backup directory: {{ storage.path }}</div>
82
+ {% endif %}
83
+ {% if storage.reserve_note %}
84
+ <div class="alert alert-warning" role="status">{{ storage.reserve_note }}</div>
85
+ {% endif %}
86
+ {% if not storage.enough %}
87
+ <div class="alert alert-warning" role="status">{{ storage.warning }}</div>
88
+ {% endif %}
89
+
90
+ <div class="card">
91
+ <div class="table-responsive">
92
+ <table class="table table-hover card-table mb-0">
93
+ <thead>
94
+ <tr>
95
+ <th>Filename</th>
96
+ <th>Backup Date &amp; Time</th>
97
+ <th>File Size</th>
98
+ <th>SHA-256</th>
99
+ <th>NetBox Version</th>
100
+ <th>Running Version</th>
101
+ <th>Compatibility Status</th>
102
+ <th>Job Status</th>
103
+ <th>Started by</th>
104
+ <th>Deleted by</th>
105
+ <th>Actions</th>
106
+ </tr>
107
+ </thead>
108
+ <tbody>
109
+ {% for backup in backups %}
110
+ <tr>
111
+ <td>{{ backup.record.filename }}</td>
112
+ <td>{{ backup.record.created_at }}</td>
113
+ <td>{{ backup.record.progress_display }}</td>
114
+ <td>
115
+ {% if backup.record.checksum %}
116
+ <code class="small user-select-all">{{ backup.record.checksum }}</code>
117
+ {% else %}
118
+ —
119
+ {% endif %}
120
+ </td>
121
+ <td>{{ backup.record.netbox_version }}</td>
122
+ <td>{{ current_version }}</td>
123
+ <td>
124
+ {% if backup.record.status == "completed" or backup.record.status == "verified" %}
125
+ {% if backup.compatible %}
126
+ <span class="badge text-bg-success">Compatible</span>
127
+ {% else %}
128
+ <span class="badge text-bg-warning">Version Mismatch</span>
129
+ {% endif %}
130
+ {% else %}
131
+ —
132
+ {% endif %}
133
+ </td>
134
+ <td>
135
+ {% if backup.record.status == "running" %}
136
+ <span class="badge text-bg-info">Running</span>
137
+ {% elif backup.record.status == "failed" %}
138
+ <span class="badge text-bg-danger">Failed</span>
139
+ {% if backup.record.error %}
140
+ <div class="small text-danger mt-1">{{ backup.record.error }}</div>
141
+ {% endif %}
142
+ {% elif backup.record.status == "deleted" %}
143
+ <span class="badge text-bg-secondary">Deleted</span>
144
+ {% elif backup.record.status == "verified" %}
145
+ <span class="badge text-bg-success">Verified</span>
146
+ {% else %}
147
+ <span class="badge text-bg-success">Completed</span>
148
+ {% endif %}
149
+ </td>
150
+ <td>{{ backup.record.created_by|default:"—" }}</td>
151
+ <td>{{ backup.record.deleted_by|default:"—" }}</td>
152
+ <td class="text-nowrap">
153
+ {% if backup.record.status == "completed" or backup.record.status == "verified" %}
154
+ <a class="btn btn-sm btn-primary" href="{% url 'plugins:netbox_db_backup:backup_download' pk=backup.record.pk %}">Download</a>
155
+ <form method="post" action="{% url 'plugins:netbox_db_backup:backup_delete' pk=backup.record.pk %}" class="d-inline" onsubmit="return confirm('Delete this backup?');">
156
+ {% csrf_token %}
157
+ <button type="submit" class="btn btn-sm btn-danger">Delete</button>
158
+ </form>
159
+ {% elif backup.record.status == "failed" %}
160
+ <form method="post" action="{% url 'plugins:netbox_db_backup:backup_delete' pk=backup.record.pk %}" class="d-inline" onsubmit="return confirm('Delete this backup record?');">
161
+ {% csrf_token %}
162
+ <button type="submit" class="btn btn-sm btn-danger">Delete</button>
163
+ </form>
164
+ {% else %}
165
+ —
166
+ {% endif %}
167
+ </td>
168
+ </tr>
169
+ {% empty %}
170
+ <tr>
171
+ <td colspan="11" class="text-muted">No backups yet.</td>
172
+ </tr>
173
+ {% endfor %}
174
+ </tbody>
175
+ </table>
176
+ </div>
177
+ </div>
178
+
179
+ {% if backup_running %}
180
+ <script>setTimeout(function () { window.location.reload(); }, 5000);</script>
181
+ {% endif %}
182
+ {% endblock %}
@@ -0,0 +1,10 @@
1
+ from django.urls import path
2
+
3
+ from . import views
4
+
5
+ urlpatterns = [
6
+ path("", views.BackupListView.as_view(), name="backup_list"),
7
+ path("create/", views.BackupCreateView.as_view(), name="backup_create"),
8
+ path("<int:pk>/download/", views.BackupDownloadView.as_view(), name="backup_download"),
9
+ path("<int:pk>/delete/", views.BackupDeleteView.as_view(), name="backup_delete"),
10
+ ]
@@ -0,0 +1,119 @@
1
+ import os
2
+
3
+ from django.contrib import messages
4
+ from django.contrib.auth.mixins import LoginRequiredMixin
5
+ from django.db import IntegrityError
6
+ from django.http import FileResponse, Http404, HttpResponseForbidden
7
+ from django.shortcuts import get_object_or_404, redirect, render
8
+ from django.utils import timezone
9
+ from django.views import View
10
+
11
+ from .jobs import PG_DUMP_MISSING, backup_path, create_database_backup, pg_dump_available, storage_status
12
+ from .models import BackupFile, current_netbox_version
13
+
14
+
15
+ class SuperuserRequiredMixin(LoginRequiredMixin):
16
+ def dispatch(self, request, *args, **kwargs):
17
+ if not request.user.is_authenticated:
18
+ return super().dispatch(request, *args, **kwargs)
19
+ if not request.user.is_superuser:
20
+ return HttpResponseForbidden("Superuser access is required.")
21
+ return super().dispatch(request, *args, **kwargs)
22
+
23
+
24
+ class BackupListView(SuperuserRequiredMixin, View):
25
+ def get(self, request):
26
+ running_version = current_netbox_version()
27
+ backups = [
28
+ {
29
+ "record": backup,
30
+ "compatible": backup.compatible_with(running_version),
31
+ }
32
+ for backup in BackupFile.objects.all()
33
+ ]
34
+ return render(
35
+ request,
36
+ "netbox_db_backup/backup_list.html",
37
+ {
38
+ "backups": backups,
39
+ "current_version": running_version,
40
+ "storage": storage_status(),
41
+ "backup_running": BackupFile.in_progress(),
42
+ "pg_dump_ready": pg_dump_available(),
43
+ },
44
+ )
45
+
46
+
47
+ class BackupCreateView(SuperuserRequiredMixin, View):
48
+ def post(self, request):
49
+ if BackupFile.in_progress():
50
+ messages.warning(request, "A backup is already running.")
51
+ return redirect("plugins:netbox_db_backup:backup_list")
52
+ if not pg_dump_available():
53
+ messages.warning(request, PG_DUMP_MISSING)
54
+ return redirect("plugins:netbox_db_backup:backup_list")
55
+ status = storage_status()
56
+ if not status.enough:
57
+ messages.warning(request, status.warning)
58
+ return redirect("plugins:netbox_db_backup:backup_list")
59
+ filename = f"netbox_{timezone.now().strftime('%Y%m%d_%H%M%S')}.dump"
60
+ try:
61
+ backup = BackupFile.objects.create(
62
+ filename=filename,
63
+ file_size=0,
64
+ expected_size=status.required or 0,
65
+ created_by=request.user.get_username(),
66
+ netbox_version=current_netbox_version(),
67
+ status=BackupFile.STATUS_RUNNING,
68
+ )
69
+ except IntegrityError:
70
+ messages.warning(request, "A backup is already running.")
71
+ return redirect("plugins:netbox_db_backup:backup_list")
72
+ try:
73
+ create_database_backup.delay(backup.pk)
74
+ except Exception:
75
+ backup.status = BackupFile.STATUS_FAILED
76
+ backup.error = "Could not queue the backup job."
77
+ backup.save(update_fields=["status", "error"])
78
+ messages.error(request, "Could not queue the backup job.")
79
+ else:
80
+ messages.info(request, "Backup started. This page refreshes until it finishes.")
81
+ return redirect("plugins:netbox_db_backup:backup_list")
82
+
83
+
84
+ class BackupDownloadView(SuperuserRequiredMixin, View):
85
+ def get(self, request, pk):
86
+ backup = get_object_or_404(BackupFile, pk=pk)
87
+ if backup.status not in (BackupFile.STATUS_COMPLETED, BackupFile.STATUS_VERIFIED):
88
+ messages.warning(request, "This backup is not ready to download.")
89
+ return redirect("plugins:netbox_db_backup:backup_list")
90
+ try:
91
+ path = backup_path(backup.filename)
92
+ except ValueError as error:
93
+ raise Http404("Backup file not found.") from error
94
+ if not os.path.isfile(path):
95
+ raise Http404("Backup file not found.")
96
+ handle = open(path, "rb")
97
+ return FileResponse(handle, as_attachment=True, filename=backup.filename)
98
+
99
+
100
+ class BackupDeleteView(SuperuserRequiredMixin, View):
101
+ def post(self, request, pk):
102
+ backup = get_object_or_404(BackupFile, pk=pk)
103
+ if backup.status == BackupFile.STATUS_RUNNING:
104
+ messages.warning(request, "This backup is still running.")
105
+ return redirect("plugins:netbox_db_backup:backup_list")
106
+ if backup.status == BackupFile.STATUS_DELETED:
107
+ messages.warning(request, "This backup is already deleted.")
108
+ return redirect("plugins:netbox_db_backup:backup_list")
109
+ try:
110
+ path = backup_path(backup.filename)
111
+ except ValueError:
112
+ path = None
113
+ if path and os.path.isfile(path):
114
+ os.remove(path)
115
+ backup.status = BackupFile.STATUS_DELETED
116
+ backup.deleted_by = request.user.get_username()
117
+ backup.save(update_fields=["status", "deleted_by"])
118
+ messages.success(request, "Backup deleted.")
119
+ return redirect("plugins:netbox_db_backup:backup_list")
@@ -0,0 +1,110 @@
1
+ Metadata-Version: 2.4
2
+ Name: netbox-db-backup
3
+ Version: 0.1.6
4
+ Summary: Minimal NetBox plugin for PostgreSQL database backups.
5
+ Author: Najafzadeh Reza
6
+ License: MIT
7
+ Requires-Python: >=3.10
8
+ Description-Content-Type: text/markdown
9
+ License-File: LICENSE
10
+ Dynamic: license-file
11
+
12
+ # netbox-db-backup
13
+
14
+ NetBox plugin that creates, lists, downloads, and deletes PostgreSQL backups from one page.
15
+
16
+ NetBox 4.5 or newer. PostgreSQL only. Actions are limited to superusers.
17
+
18
+ ## What you get
19
+
20
+ Open **Database Backups** at `/plugins/db-backup/`.
21
+
22
+ - **Create Backup** queues `pg_dump` on the default RQ worker. The row appears immediately as **Running**, and the page refreshes every 5 seconds until the job finishes. While it runs, the file size is shown against the database size, such as `200.0 MB / 964.5 MB`. The finished row shows the real file size.
23
+ - A second backup cannot start while one is running.
24
+ - `pg_dump` writes a compressed custom-format `.dump` file directly. The worker then runs `pg_restore --list`. A readable file is marked **Verified**. A file that cannot be read is marked **Failed** and removed. The worker job timeout is 6 hours.
25
+ - The table lists each file with its date, size, the NetBox version stored at backup time, the running version, a compatibility badge, and the job status.
26
+ - **Compatible** means those two versions match. **Version Mismatch** means they do not.
27
+ - **Failed** keeps the row and shows the error. The partial file is removed after the row is marked failed.
28
+ - **Download** returns a completed file. The row stores a SHA-256 checksum. Check a download with `sha256sum` and compare it with the value on the page. **Delete** removes the file and its record after confirmation.
29
+
30
+ Free space, database size, reserve, space needed, and status are shown in separate columns. The status is green when a backup can run, and yellow when it would leave less than the reserve free.
31
+
32
+ ## Requirements
33
+
34
+ - Unix. Linux and other Unix systems are supported. Windows is not supported.
35
+ - NetBox 4.5 or newer
36
+ - PostgreSQL
37
+ - `pg_dump` on the `PATH` of the host or container that runs the RQ worker
38
+ - The RQ worker must be able to reach the NetBox database
39
+ - `backup_dir` must be writable. In a container, mount that directory as a volume so backups survive a restart
40
+
41
+ The page checks for `pg_dump` before a backup starts. If it is missing, **Create Backup** stays disabled and the page shows a warning. The worker checks again before `pg_dump` runs.
42
+
43
+ ## Install
44
+
45
+ From the NetBox virtualenv:
46
+
47
+ ```bash
48
+ source /opt/netbox/venv/bin/activate
49
+ pip install /path/to/netbox_db_backup
50
+ ```
51
+
52
+ Add the plugin in `/opt/netbox/netbox/netbox/configuration.py`:
53
+
54
+ ```python
55
+ PLUGINS = [
56
+ 'netbox_db_backup',
57
+ ]
58
+
59
+ PLUGINS_CONFIG = {
60
+ 'netbox_db_backup': {
61
+ 'backup_dir': '/opt/netbox/netbox/media/db_backups',
62
+ 'min_free_bytes': 5 * 1024 ** 3,
63
+ 'keep_backups': 5,
64
+ },
65
+ }
66
+ ```
67
+
68
+ Apply the migration and restart NetBox and the worker:
69
+
70
+ ```bash
71
+ cd /opt/netbox/netbox
72
+ python manage.py migrate netbox_db_backup
73
+ sudo systemctl restart netbox netbox-rq
74
+ ```
75
+
76
+ In a container, restart the NetBox web process and the RQ worker for that image instead of `systemctl`. Install `pg_dump` in the worker image.
77
+
78
+ Sign in as a superuser and open **Database Backups**.
79
+
80
+ ## Settings
81
+
82
+ | Setting | Default | Purpose |
83
+ | --- | --- | --- |
84
+ | `backup_dir` | `/opt/netbox/netbox/media/db_backups` | Directory where `.dump` files are stored |
85
+ | `min_free_bytes` | `5 * 1024 ** 3` (5 GB) | Space that must remain free after a backup |
86
+ | `keep_backups` | `5` | How many verified backups to keep. Older ones are deleted |
87
+
88
+ `min_free_bytes` can be raised. A lower value is ignored and 5 GB is used. `keep_backups` can be raised. A value below 1 is treated as 1, so the newest backup is kept. Failed rows are left in place.
89
+
90
+ The backup row stores who started it. A delete removes the file and keeps the row, with the username in **Deleted by**. Automatic cleanup stores `retention` there.
91
+
92
+ ## Disk safety
93
+
94
+ A backup starts only when:
95
+
96
+ `free space − current database size ≥ reserve`
97
+
98
+ The database size comes from `pg_database_size`. The same check runs again in the worker before `pg_dump`. If it fails, the row is marked **Failed** and no backup file is kept.
99
+
100
+ When space is too low, or a backup is already running, **Create Backup** stays disabled and the page shows a warning.
101
+
102
+ ## Backup files
103
+
104
+ Files are named `netbox_YYYYMMDD_HHMMSS.dump`. Restore a completed file with `pg_restore`. Each record stores the file name, size, creation time, job status, and the NetBox version that was running when the backup was created.
105
+
106
+ After an upgrade, run `python manage.py migrate netbox_db_backup` and restart `netbox` and `netbox-rq`.
107
+
108
+ ## License
109
+
110
+ MIT. Copyright (c) 2026 Najafzadeh Reza. See [LICENSE](LICENSE).
@@ -0,0 +1,18 @@
1
+ netbox_db_backup/__init__.py,sha256=wLGV2R8SKmdIxptoytzpCw5Dysxe_1D_kHGINUuXpGI,602
2
+ netbox_db_backup/jobs.py,sha256=1Uw3HmLPJoNaSFH-4nG-uXj6HonNeYDIU0ED5lGG0QQ,11101
3
+ netbox_db_backup/models.py,sha256=yaEgsAZaTQ6zYHg9cSwTxdLxY6VFYdr9M5LKtzTMs-8,2402
4
+ netbox_db_backup/navigation.py,sha256=-AYMeMVENKCeDUXKMreqhRSuqD4a3Rxnna2KnbrDRtQ,203
5
+ netbox_db_backup/urls.py,sha256=VgWIscM8Os2BPEHi2n3VDOVEqIz2EQqtZThDL5onhUs,390
6
+ netbox_db_backup/views.py,sha256=lpZBdn21Bibd01I32KOUBa5IcvaVIw-gNiU1ldsnka4,5068
7
+ netbox_db_backup/migrations/0001_initial.py,sha256=TEMeomug7Du6iuH4Ke9XbrJzXzERc99suEhAndT2qEg,902
8
+ netbox_db_backup/migrations/0002_backup_status.py,sha256=JwLlmvjmJT7G-hedPWAjisbltY-gKEqA3AKbHPp_bqU,971
9
+ netbox_db_backup/migrations/0003_expected_size.py,sha256=wsgDP1XlBhqgk75DYKvxy03qpJTtICbcPQ20KaU9Y4g,352
10
+ netbox_db_backup/migrations/0004_checksum.py,sha256=krATQhTtuxS13S-8RYi4YVL7wFnseHzxg_kC5n1kj3g,369
11
+ netbox_db_backup/migrations/0005_backup_users.py,sha256=ViQGgrvJmbbHrFsyFAExLUQAJ-hBZ6id9AvAbqzttSo,551
12
+ netbox_db_backup/migrations/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
13
+ netbox_db_backup/templates/netbox_db_backup/backup_list.html,sha256=gHkQoQebONjP5fWdAewjveVTQNbf-gdhPm4k5T9JunQ,7343
14
+ netbox_db_backup-0.1.6.dist-info/licenses/LICENSE,sha256=2O3P_orq3eDRHDGFAaBcS1H912FWgyBv-AKbyuqdV_0,1072
15
+ netbox_db_backup-0.1.6.dist-info/METADATA,sha256=xe8KfxneBIqEw7lH1tlu7SOIf4rYTChO9lfN-Alwkms,4788
16
+ netbox_db_backup-0.1.6.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
17
+ netbox_db_backup-0.1.6.dist-info/top_level.txt,sha256=pqFMkwA_6MPDU_7swAouQEsmAvFmjOzO3QOcFuC3QWo,17
18
+ netbox_db_backup-0.1.6.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Najafzadeh Reza
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ netbox_db_backup