|
- <%
- ' Backup, verification and restore of the SQLite database (spec NFR-005, AC-17).
- ' Run through scripts\backup.cmd, which sets BACKUP_ACTION and BACKUP_FILE:
- '
- ' backup [file] consistent online copy with VACUUM INTO (default db/backups/app-YYYYMMDD-HHMMSS.sqlite),
- ' then verifies the copy and compares its row counts with the live database
- ' verify <file> PRAGMA integrity_check, foreign_key_check, latest migration and row counts per table
- ' restore <file> verifies <file>, keeps the current database as db/backups/pre-restore-<ts>.sqlite, then copies
- ' <file> over the live database. Only with the HTTP server and embed worker STOPPED
- ' (scripts\restore.cmd does that); afterwards run scripts\embed.cmd reindex.
- ' repair [apply] lists foreign key violations in the live database and what would fix them; with BACKUP_FILE=apply
- ' it creates placeholder principals for author ids from another installation (imported data) and
- ' deletes verifications whose memory no longer exists. Take a backup first.
- '
- ' File names are relative to the framework folder (for example db/backups/app-20261205-120000.sqlite) or absolute
- ' under /opt/axonasp/site. The framework folder must be the web root: -e SERVER_WEB_ROOT=/opt/axonasp/site
- ' Prints "RESULT: ok" or "RESULT: failed" as the last line (the CLI exit code is not reliable, see AGENTS.md).
- %>
- <!--#include file="../core/autoload_core.asp" -->
- <%
- Const BK_DIR = "/db/backups"
- Const BK_LIVE = "/db/app.sqlite"
- Const BK_SITE = "/opt/axonasp/site"
-
- Dim sh : Set sh = CreateObject("WScript.Shell")
- Dim fso : Set fso = Server.CreateObject("Scripting.FileSystemObject")
-
- Function Arg(name)
- Dim v
- v = sh.ExpandEnvironmentStrings("%" & name & "%")
- If v = "%" & name & "%" Then v = ""
- Arg = Trim(v)
- End Function
-
- Sub Say(msg)
- Response.Write msg & vbCrLf
- End Sub
-
- Function Stamp()
- Dim n
- n = Now()
- Stamp = Year(n) & Right("0" & Month(n), 2) & Right("0" & Day(n), 2) & "-" & _
- Right("0" & Hour(n), 2) & Right("0" & Minute(n), 2) & Right("0" & Second(n), 2)
- End Function
-
- ' Physical path for a file name given relative to the framework folder (or absolute under it). "" if invalid.
- Function PhysPath(name)
- Dim p
- PhysPath = ""
- p = Replace(name, "\", "/")
- If InStr(p, "..") > 0 Then Exit Function
- If Left(p, Len(BK_SITE) + 1) = BK_SITE & "/" Then
- p = Mid(p, Len(BK_SITE) + 1)
- End If
- If Left(p, 1) <> "/" Then
- p = "/" & p
- End If
- PhysPath = Server.MapPath(p)
- End Function
-
- Function SqlText(s)
- SqlText = "'" & Replace(s, "'", "''") & "'"
- End Function
-
- ' Opens a SQLite file with G3DB; Nothing if it cannot be opened.
- Function OpenDb(path)
- Dim db
- Set OpenDb = Nothing
- Set db = Server.CreateObject("G3DB")
- If Not db.Open("sqlite", path) Then
- Say "ERROR: cannot open " & path & ": " & db.LastError
- Exit Function
- End If
- Set OpenDb = db
- End Function
-
- ' Checks a database file and prints its report; returns True when it is sound. counts receives "table=n;..." text.
- Function CheckDb(path, ByRef counts)
- Dim db, rs, names, i, n, v, ok, fk, latest
- CheckDb = False
- counts = ""
- If Not fso.FileExists(path) Then
- Say "ERROR: no such file: " & path
- Exit Function
- End If
- Set db = OpenDb(path)
- If db Is Nothing Then
- Exit Function
- End If
- ok = True
-
- Set rs = db.Query("PRAGMA integrity_check")
- If IsEmpty(rs) Then
- Say "ERROR: integrity_check failed: " & db.LastError
- db.Close
- Exit Function
- End If
- v = ""
- Do While Not rs.EOF
- v = v & rs(0) & " "
- rs.MoveNext
- Loop
- rs.Close
- v = Trim(v)
- Say "integrity_check: " & v
- If v <> "ok" Then
- ok = False
- End If
-
- Set rs = db.Query("PRAGMA foreign_key_check")
- fk = 0
- If Not IsEmpty(rs) Then
- Do While Not rs.EOF
- fk = fk + 1
- rs.MoveNext
- Loop
- rs.Close
- End If
- Say "foreign_key_violations: " & fk
- If fk > 0 Then
- ok = False
- End If
-
- Set rs = db.Query("SELECT MAX(version) FROM schema_migrations")
- latest = ""
- If Not IsEmpty(rs) Then
- If Not rs.EOF Then
- latest = "" & rs(0)
- End If
- rs.Close
- End If
- Say "latest_migration: " & latest
- If latest = "" Then
- ok = False
- End If
-
- ' Table names first (close the result set before counting).
- names = ""
- Set rs = db.Query("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name")
- If Not IsEmpty(rs) Then
- Do While Not rs.EOF
- names = names & rs(0) & vbLf
- rs.MoveNext
- Loop
- rs.Close
- End If
- names = Split(names, vbLf)
- For i = 0 To UBound(names) - 1
- Set rs = db.Query("SELECT COUNT(*) FROM """ & Replace(names(i), """", """""") & """")
- n = "?"
- If Not IsEmpty(rs) Then
- If Not rs.EOF Then
- n = "" & rs(0)
- End If
- rs.Close
- End If
- counts = counts & names(i) & "=" & n & ";"
- Next
- db.Close
- Say "tables: " & (UBound(names))
- CheckDb = ok
- End Function
-
- Function DoBackup()
- Dim target, db, res, counts, liveCounts, sz, t0
- DoBackup = False
- If Arg("BACKUP_FILE") = "" Then
- If Not fso.FolderExists(Server.MapPath(BK_DIR)) Then
- fso.CreateFolder Server.MapPath(BK_DIR)
- End If
- target = Server.MapPath(BK_DIR & "/app-" & Stamp() & ".sqlite")
- Else
- target = PhysPath(Arg("BACKUP_FILE"))
- End If
- If target = "" Then
- Say "ERROR: invalid file name"
- Exit Function
- End If
- If fso.FileExists(target) Then
- Say "ERROR: file exists: " & target
- Exit Function
- End If
- Set db = OpenDb(Server.MapPath(BK_LIVE))
- If db Is Nothing Then
- Exit Function
- End If
- t0 = Timer
- ' VACUUM INTO writes a consistent, compacted copy while the server keeps running (readers and writers wait).
- Set res = db.Exec("VACUUM INTO " & SqlText(target))
- If IsEmpty(res) Then
- Say "ERROR: VACUUM INTO failed: " & db.LastError
- db.Close
- Exit Function
- End If
- db.Close
- sz = fso.GetFile(target).Size
- Say "backup: " & target
- Say "bytes: " & sz
- Say "seconds: " & FormatNumber(Timer - t0, 2, -1, 0, 0)
- If Not CheckDb(target, counts) Then
- Exit Function
- End If
- Say "-- live database"
- If Not CheckDb(Server.MapPath(BK_LIVE), liveCounts) Then
- Exit Function
- End If
- If counts = liveCounts Then
- Say "row_counts: match"
- Else
- ' A write between the copy and the comparison also gives a difference; rerun verify if the server is busy.
- Say "row_counts: differ (backup " & counts & " live " & liveCounts & ")"
- End If
- DoBackup = True
- End Function
-
- Function DoVerify()
- Dim path, counts
- DoVerify = False
- path = PhysPath(Arg("BACKUP_FILE"))
- If path = "" Then
- Say "ERROR: give the backup file (BACKUP_FILE)"
- Exit Function
- End If
- If Not CheckDb(path, counts) Then
- Exit Function
- End If
- Say "row_counts: " & counts
- DoVerify = True
- End Function
-
- Function DoRestore()
- Dim src, live, safety, counts, f
- DoRestore = False
- src = PhysPath(Arg("BACKUP_FILE"))
- live = Server.MapPath(BK_LIVE)
- If src = "" Then
- Say "ERROR: give the backup file (BACKUP_FILE)"
- Exit Function
- End If
- If LCase(src) = LCase(live) Then
- Say "ERROR: the backup is the live database"
- Exit Function
- End If
- If Not CheckDb(src, counts) Then
- Say "ERROR: the backup did not verify; nothing was changed"
- Exit Function
- End If
- If fso.FileExists(live) Then
- If Not fso.FolderExists(Server.MapPath(BK_DIR)) Then
- fso.CreateFolder Server.MapPath(BK_DIR)
- End If
- safety = Server.MapPath(BK_DIR & "/pre-restore-" & Stamp() & ".sqlite")
- fso.CopyFile live, safety, False
- Say "previous database kept as: " & safety
- End If
- For Each f In Array(live & "-wal", live & "-shm", live & "-journal")
- If fso.FileExists(f) Then
- fso.DeleteFile f, True
- End If
- Next
- fso.CopyFile src, live, True
- Say "restored: " & src & " -> " & live
- Say "-- restored database"
- If Not CheckDb(live, counts) Then
- Exit Function
- End If
- Say "row_counts: " & counts
- DoRestore = True
- End Function
-
- ' Foreign key violations of the live database grouped as "table->parent", one line each; returns the total.
- Function ReportFk()
- Dim rs, keys, total, k, d
- Set d = Server.CreateObject("Scripting.Dictionary")
- total = 0
- Set rs = DAL().Query("PRAGMA foreign_key_check", Empty)
- Do While Not rs.EOF
- k = rs(0) & "->" & rs(2)
- If d.Exists(k) Then
- d(k) = d(k) + 1
- Else
- d.Add k, 1
- End If
- total = total + 1
- rs.MoveNext
- Loop
- rs.Close
- keys = d.Keys
- For Each k In keys
- Say " " & k & ": " & d(k)
- Next
- Say "foreign_key_violations: " & total
- ReportFk = total
- End Function
-
- Function ScalarOf(sql)
- Dim rs
- Set rs = DAL().Query(sql, Empty)
- ScalarOf = CLng(rs(0))
- rs.Close
- End Function
-
- Function DoRepair()
- Dim apply, orphans, made, left
- DoRepair = False
- apply = (LCase(Arg("BACKUP_FILE")) = "apply")
- Say "-- before"
- ReportFk
- orphans = ScalarOf("SELECT COUNT(*) FROM verifications v WHERE NOT EXISTS (SELECT 1 FROM memories m WHERE m.id = v.memory_id)")
- Say "orphaned_verifications: " & orphans
- If Not apply Then
- Say "dry run: nothing changed. Placeholder principals are created for the missing author ids and the orphaned"
- Say "verifications are deleted with BACKUP_FILE=apply (scripts\backup.cmd repair apply, ops.sh repair apply)."
- DoRepair = True
- Exit Function
- End If
- On Error Resume Next
- DAL().BeginTransaction
- made = Api_EnsureReferencedPrincipals("")
- If Err.Number = 0 Then
- DAL().Execute "DELETE FROM verifications WHERE NOT EXISTS (SELECT 1 FROM memories m WHERE m.id = verifications.memory_id)", Empty
- End If
- If Err.Number <> 0 Then
- Say "ERROR: " & Err.Description
- Err.Clear
- DAL().RollbackTransaction
- On Error GoTo 0
- Exit Function
- End If
- DAL().CommitTransaction
- If Err.Number <> 0 Then
- Say "ERROR: " & Err.Description
- On Error GoTo 0
- Exit Function
- End If
- On Error GoTo 0
- Say "placeholder_principals_created: " & made
- Say "orphaned_verifications_deleted: " & orphans
- Say "-- after"
- left = ReportFk()
- DoRepair = (left = 0)
- End Function
-
- Dim action, ok
- action = LCase(Arg("BACKUP_ACTION"))
- ok = False
- Select Case action
- Case "backup"
- ok = DoBackup()
- Case "verify"
- ok = DoVerify()
- Case "restore"
- ok = DoRestore()
- Case "repair"
- ok = DoRepair()
- Case Else
- Say "Usage: BACKUP_ACTION=backup|verify|restore|repair [BACKUP_FILE=db/backups/<file>.sqlite]"
- End Select
- If ok Then
- Say "RESULT: ok"
- Else
- Say "RESULT: failed"
- End If
- %>
|