25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

365 lines
11KB

  1. <%
  2. ' Backup, verification and restore of the SQLite database (spec NFR-005, AC-17).
  3. ' Run through scripts\backup.cmd, which sets BACKUP_ACTION and BACKUP_FILE:
  4. '
  5. ' backup [file] consistent online copy with VACUUM INTO (default db/backups/app-YYYYMMDD-HHMMSS.sqlite),
  6. ' then verifies the copy and compares its row counts with the live database
  7. ' verify <file> PRAGMA integrity_check, foreign_key_check, latest migration and row counts per table
  8. ' restore <file> verifies <file>, keeps the current database as db/backups/pre-restore-<ts>.sqlite, then copies
  9. ' <file> over the live database. Only with the HTTP server and embed worker STOPPED
  10. ' (scripts\restore.cmd does that); afterwards run scripts\embed.cmd reindex.
  11. ' repair [apply] lists foreign key violations in the live database and what would fix them; with BACKUP_FILE=apply
  12. ' it creates placeholder principals for author ids from another installation (imported data) and
  13. ' deletes verifications whose memory no longer exists. Take a backup first.
  14. '
  15. ' File names are relative to the framework folder (for example db/backups/app-20261205-120000.sqlite) or absolute
  16. ' under /opt/axonasp/site. The framework folder must be the web root: -e SERVER_WEB_ROOT=/opt/axonasp/site
  17. ' Prints "RESULT: ok" or "RESULT: failed" as the last line (the CLI exit code is not reliable, see AGENTS.md).
  18. %>
  19. <!--#include file="../core/autoload_core.asp" -->
  20. <%
  21. Const BK_DIR = "/db/backups"
  22. Const BK_LIVE = "/db/app.sqlite"
  23. Const BK_SITE = "/opt/axonasp/site"
  24. Dim sh : Set sh = CreateObject("WScript.Shell")
  25. Dim fso : Set fso = Server.CreateObject("Scripting.FileSystemObject")
  26. Function Arg(name)
  27. Dim v
  28. v = sh.ExpandEnvironmentStrings("%" & name & "%")
  29. If v = "%" & name & "%" Then v = ""
  30. Arg = Trim(v)
  31. End Function
  32. Sub Say(msg)
  33. Response.Write msg & vbCrLf
  34. End Sub
  35. Function Stamp()
  36. Dim n
  37. n = Now()
  38. Stamp = Year(n) & Right("0" & Month(n), 2) & Right("0" & Day(n), 2) & "-" & _
  39. Right("0" & Hour(n), 2) & Right("0" & Minute(n), 2) & Right("0" & Second(n), 2)
  40. End Function
  41. ' Physical path for a file name given relative to the framework folder (or absolute under it). "" if invalid.
  42. Function PhysPath(name)
  43. Dim p
  44. PhysPath = ""
  45. p = Replace(name, "\", "/")
  46. If InStr(p, "..") > 0 Then Exit Function
  47. If Left(p, Len(BK_SITE) + 1) = BK_SITE & "/" Then
  48. p = Mid(p, Len(BK_SITE) + 1)
  49. End If
  50. If Left(p, 1) <> "/" Then
  51. p = "/" & p
  52. End If
  53. PhysPath = Server.MapPath(p)
  54. End Function
  55. Function SqlText(s)
  56. SqlText = "'" & Replace(s, "'", "''") & "'"
  57. End Function
  58. ' Opens a SQLite file with G3DB; Nothing if it cannot be opened.
  59. Function OpenDb(path)
  60. Dim db
  61. Set OpenDb = Nothing
  62. Set db = Server.CreateObject("G3DB")
  63. If Not db.Open("sqlite", path) Then
  64. Say "ERROR: cannot open " & path & ": " & db.LastError
  65. Exit Function
  66. End If
  67. Set OpenDb = db
  68. End Function
  69. ' Checks a database file and prints its report; returns True when it is sound. counts receives "table=n;..." text.
  70. Function CheckDb(path, ByRef counts)
  71. Dim db, rs, names, i, n, v, ok, fk, latest
  72. CheckDb = False
  73. counts = ""
  74. If Not fso.FileExists(path) Then
  75. Say "ERROR: no such file: " & path
  76. Exit Function
  77. End If
  78. Set db = OpenDb(path)
  79. If db Is Nothing Then
  80. Exit Function
  81. End If
  82. ok = True
  83. Set rs = db.Query("PRAGMA integrity_check")
  84. If IsEmpty(rs) Then
  85. Say "ERROR: integrity_check failed: " & db.LastError
  86. db.Close
  87. Exit Function
  88. End If
  89. v = ""
  90. Do While Not rs.EOF
  91. v = v & rs(0) & " "
  92. rs.MoveNext
  93. Loop
  94. rs.Close
  95. v = Trim(v)
  96. Say "integrity_check: " & v
  97. If v <> "ok" Then
  98. ok = False
  99. End If
  100. Set rs = db.Query("PRAGMA foreign_key_check")
  101. fk = 0
  102. If Not IsEmpty(rs) Then
  103. Do While Not rs.EOF
  104. fk = fk + 1
  105. rs.MoveNext
  106. Loop
  107. rs.Close
  108. End If
  109. Say "foreign_key_violations: " & fk
  110. If fk > 0 Then
  111. ok = False
  112. End If
  113. Set rs = db.Query("SELECT MAX(version) FROM schema_migrations")
  114. latest = ""
  115. If Not IsEmpty(rs) Then
  116. If Not rs.EOF Then
  117. latest = "" & rs(0)
  118. End If
  119. rs.Close
  120. End If
  121. Say "latest_migration: " & latest
  122. If latest = "" Then
  123. ok = False
  124. End If
  125. ' Table names first (close the result set before counting).
  126. names = ""
  127. Set rs = db.Query("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name")
  128. If Not IsEmpty(rs) Then
  129. Do While Not rs.EOF
  130. names = names & rs(0) & vbLf
  131. rs.MoveNext
  132. Loop
  133. rs.Close
  134. End If
  135. names = Split(names, vbLf)
  136. For i = 0 To UBound(names) - 1
  137. Set rs = db.Query("SELECT COUNT(*) FROM """ & Replace(names(i), """", """""") & """")
  138. n = "?"
  139. If Not IsEmpty(rs) Then
  140. If Not rs.EOF Then
  141. n = "" & rs(0)
  142. End If
  143. rs.Close
  144. End If
  145. counts = counts & names(i) & "=" & n & ";"
  146. Next
  147. db.Close
  148. Say "tables: " & (UBound(names))
  149. CheckDb = ok
  150. End Function
  151. Function DoBackup()
  152. Dim target, db, res, counts, liveCounts, sz, t0
  153. DoBackup = False
  154. If Arg("BACKUP_FILE") = "" Then
  155. If Not fso.FolderExists(Server.MapPath(BK_DIR)) Then
  156. fso.CreateFolder Server.MapPath(BK_DIR)
  157. End If
  158. target = Server.MapPath(BK_DIR & "/app-" & Stamp() & ".sqlite")
  159. Else
  160. target = PhysPath(Arg("BACKUP_FILE"))
  161. End If
  162. If target = "" Then
  163. Say "ERROR: invalid file name"
  164. Exit Function
  165. End If
  166. If fso.FileExists(target) Then
  167. Say "ERROR: file exists: " & target
  168. Exit Function
  169. End If
  170. Set db = OpenDb(Server.MapPath(BK_LIVE))
  171. If db Is Nothing Then
  172. Exit Function
  173. End If
  174. t0 = Timer
  175. ' VACUUM INTO writes a consistent, compacted copy while the server keeps running (readers and writers wait).
  176. Set res = db.Exec("VACUUM INTO " & SqlText(target))
  177. If IsEmpty(res) Then
  178. Say "ERROR: VACUUM INTO failed: " & db.LastError
  179. db.Close
  180. Exit Function
  181. End If
  182. db.Close
  183. sz = fso.GetFile(target).Size
  184. Say "backup: " & target
  185. Say "bytes: " & sz
  186. Say "seconds: " & FormatNumber(Timer - t0, 2, -1, 0, 0)
  187. If Not CheckDb(target, counts) Then
  188. Exit Function
  189. End If
  190. Say "-- live database"
  191. If Not CheckDb(Server.MapPath(BK_LIVE), liveCounts) Then
  192. Exit Function
  193. End If
  194. If counts = liveCounts Then
  195. Say "row_counts: match"
  196. Else
  197. ' A write between the copy and the comparison also gives a difference; rerun verify if the server is busy.
  198. Say "row_counts: differ (backup " & counts & " live " & liveCounts & ")"
  199. End If
  200. DoBackup = True
  201. End Function
  202. Function DoVerify()
  203. Dim path, counts
  204. DoVerify = False
  205. path = PhysPath(Arg("BACKUP_FILE"))
  206. If path = "" Then
  207. Say "ERROR: give the backup file (BACKUP_FILE)"
  208. Exit Function
  209. End If
  210. If Not CheckDb(path, counts) Then
  211. Exit Function
  212. End If
  213. Say "row_counts: " & counts
  214. DoVerify = True
  215. End Function
  216. Function DoRestore()
  217. Dim src, live, safety, counts, f
  218. DoRestore = False
  219. src = PhysPath(Arg("BACKUP_FILE"))
  220. live = Server.MapPath(BK_LIVE)
  221. If src = "" Then
  222. Say "ERROR: give the backup file (BACKUP_FILE)"
  223. Exit Function
  224. End If
  225. If LCase(src) = LCase(live) Then
  226. Say "ERROR: the backup is the live database"
  227. Exit Function
  228. End If
  229. If Not CheckDb(src, counts) Then
  230. Say "ERROR: the backup did not verify; nothing was changed"
  231. Exit Function
  232. End If
  233. If fso.FileExists(live) Then
  234. If Not fso.FolderExists(Server.MapPath(BK_DIR)) Then
  235. fso.CreateFolder Server.MapPath(BK_DIR)
  236. End If
  237. safety = Server.MapPath(BK_DIR & "/pre-restore-" & Stamp() & ".sqlite")
  238. fso.CopyFile live, safety, False
  239. Say "previous database kept as: " & safety
  240. End If
  241. For Each f In Array(live & "-wal", live & "-shm", live & "-journal")
  242. If fso.FileExists(f) Then
  243. fso.DeleteFile f, True
  244. End If
  245. Next
  246. fso.CopyFile src, live, True
  247. Say "restored: " & src & " -> " & live
  248. Say "-- restored database"
  249. If Not CheckDb(live, counts) Then
  250. Exit Function
  251. End If
  252. Say "row_counts: " & counts
  253. DoRestore = True
  254. End Function
  255. ' Foreign key violations of the live database grouped as "table->parent", one line each; returns the total.
  256. Function ReportFk()
  257. Dim rs, keys, total, k, d
  258. Set d = Server.CreateObject("Scripting.Dictionary")
  259. total = 0
  260. Set rs = DAL().Query("PRAGMA foreign_key_check", Empty)
  261. Do While Not rs.EOF
  262. k = rs(0) & "->" & rs(2)
  263. If d.Exists(k) Then
  264. d(k) = d(k) + 1
  265. Else
  266. d.Add k, 1
  267. End If
  268. total = total + 1
  269. rs.MoveNext
  270. Loop
  271. rs.Close
  272. keys = d.Keys
  273. For Each k In keys
  274. Say " " & k & ": " & d(k)
  275. Next
  276. Say "foreign_key_violations: " & total
  277. ReportFk = total
  278. End Function
  279. Function ScalarOf(sql)
  280. Dim rs
  281. Set rs = DAL().Query(sql, Empty)
  282. ScalarOf = CLng(rs(0))
  283. rs.Close
  284. End Function
  285. Function DoRepair()
  286. Dim apply, orphans, made, left
  287. DoRepair = False
  288. apply = (LCase(Arg("BACKUP_FILE")) = "apply")
  289. Say "-- before"
  290. ReportFk
  291. orphans = ScalarOf("SELECT COUNT(*) FROM verifications v WHERE NOT EXISTS (SELECT 1 FROM memories m WHERE m.id = v.memory_id)")
  292. Say "orphaned_verifications: " & orphans
  293. If Not apply Then
  294. Say "dry run: nothing changed. Placeholder principals are created for the missing author ids and the orphaned"
  295. Say "verifications are deleted with BACKUP_FILE=apply (scripts\backup.cmd repair apply, ops.sh repair apply)."
  296. DoRepair = True
  297. Exit Function
  298. End If
  299. On Error Resume Next
  300. DAL().BeginTransaction
  301. made = Api_EnsureReferencedPrincipals("")
  302. If Err.Number = 0 Then
  303. DAL().Execute "DELETE FROM verifications WHERE NOT EXISTS (SELECT 1 FROM memories m WHERE m.id = verifications.memory_id)", Empty
  304. End If
  305. If Err.Number <> 0 Then
  306. Say "ERROR: " & Err.Description
  307. Err.Clear
  308. DAL().RollbackTransaction
  309. On Error GoTo 0
  310. Exit Function
  311. End If
  312. DAL().CommitTransaction
  313. If Err.Number <> 0 Then
  314. Say "ERROR: " & Err.Description
  315. On Error GoTo 0
  316. Exit Function
  317. End If
  318. On Error GoTo 0
  319. Say "placeholder_principals_created: " & made
  320. Say "orphaned_verifications_deleted: " & orphans
  321. Say "-- after"
  322. left = ReportFk()
  323. DoRepair = (left = 0)
  324. End Function
  325. Dim action, ok
  326. action = LCase(Arg("BACKUP_ACTION"))
  327. ok = False
  328. Select Case action
  329. Case "backup"
  330. ok = DoBackup()
  331. Case "verify"
  332. ok = DoVerify()
  333. Case "restore"
  334. ok = DoRestore()
  335. Case "repair"
  336. ok = DoRepair()
  337. Case Else
  338. Say "Usage: BACKUP_ACTION=backup|verify|restore|repair [BACKUP_FILE=db/backups/<file>.sqlite]"
  339. End Select
  340. If ok Then
  341. Say "RESULT: ok"
  342. Else
  343. Say "RESULT: failed"
  344. End If
  345. %>

Powered by TurnKey Linux.