package web import ( "context" "errors" "io" "net/http" "os" "path/filepath" "strings" "time" "supermarket/internal/backup" "supermarket/internal/db" ) func (s *Server) backupDir() string { return backup.Dir(s.DataDir) } // RunBackups makes the daily backup, and prunes old dailies, while the app // runs. func (s *Server) RunBackups(ctx context.Context) { tick := time.NewTicker(time.Hour) defer tick.Stop() for { s.dailyBackup(time.Now()) select { case <-ctx.Done(): return case <-tick.C: } } } func (s *Server) dailyBackup(now time.Time) { due, err := backup.DueDaily(s.backupDir(), now) if err != nil { s.Log.Warn("backups: listing", "err", err) return } if !due { return } if _, err := backup.Make(s.DB.DB, s.backupDir(), backup.Daily, "", now); err != nil { s.Log.Error("backups: the daily backup failed", "err", err) return } if n, err := backup.Prune(s.backupDir()); err != nil { s.Log.Warn("backups: pruning", "err", err) } else if n > 0 { s.Log.Info("backups: removed old daily backups", "count", n) } } func (s *Server) backupsPage(w http.ResponseWriter, r *http.Request) { s.renderBackups(w, r, "", "") } func (s *Server) renderBackups(w http.ResponseWriter, r *http.Request, errMsg, flash string) { bs, err := backup.List(s.backupDir()) if err != nil { s.serverError(w, err) return } var total int64 for _, b := range bs { total += b.Size } keep := backup.Keep(bs) hostDir := s.backupDir() if s.MCPSocket != "" { // the data folder's path on the host hostDir = filepath.Join(filepath.Dir(s.MCPSocket), "backups") } data := map[string]any{"Backups": bs, "Total": total, "Keep": keep, "Schema": db.Schema(), "Dir": hostDir, "Pending": backup.Pending(s.DataDir), "CanRestart": s.Restart != nil} if last := backup.LastRestore(s.DataDir); last != nil && time.Since(last.At) < 24*time.Hour { data["Restored"] = last } s.render(w, r, "backups", page{Title: "Backups", Nav: "settings/backups", Error: errMsg, Flash: flash, Data: data}) } func (s *Server) backupsAction(w http.ResponseWriter, r *http.Request) { if err := r.ParseForm(); err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } switch r.PathValue("action") { case "now": b, err := backup.Make(s.DB.DB, s.backupDir(), backup.Manual, r.PostFormValue("note"), time.Now()) if err != nil { s.renderBackups(w, r, err.Error(), "") return } s.renderBackups(w, r, "", "Backed up to "+b.Name+".") case "restore": b, err := backup.Find(s.backupDir(), r.PostFormValue("name")) if err != nil { s.renderBackups(w, r, "There's no backup called "+r.PostFormValue("name")+".", "") return } s.restore(w, r, b.Path) case "cancel": backup.Cancel(s.DataDir) s.renderBackups(w, r, "", "The restore is cancelled.") case "delete": name := r.PostFormValue("name") if err := backup.Delete(s.backupDir(), name); err != nil { if errors.Is(err, os.ErrNotExist) { s.renderBackups(w, r, "There's no backup called "+name+".", "") return } s.serverError(w, err) return } s.renderBackups(w, r, "", "Deleted "+name+".") default: http.NotFound(w, r) } } // backupDownload sends a backup file. It holds contacts and the app's // data (not its secrets), so it's served to this machine only, like // everything else here. func (s *Server) backupDownload(w http.ResponseWriter, r *http.Request) { b, err := backup.Find(s.backupDir(), r.PathValue("name")) if err != nil { http.NotFound(w, r) return } w.Header().Set("Content-Type", "application/vnd.sqlite3") w.Header().Set("Content-Disposition", `attachment; filename="`+b.Name+`"`) w.Header().Set("Cache-Control", "no-store") http.ServeFile(w, r, b.Path) } // restore stages a restore from a backup file, then restarts the app to // apply it. Without a way to restart (tests, or not under Docker) it's // left staged for the next start. func (s *Server) restore(w http.ResponseWriter, r *http.Request, path string) { res, err := backup.Stage(s.DB.DB, s.DataDir, path, db.Schema(), time.Now()) if err != nil { s.renderBackups(w, r, "Not restored: "+err.Error(), "") return } msg := "Restoring " + res.From + ". The current database is backed up as " + res.Backup + "." if s.Restart == nil { s.renderBackups(w, r, "", msg+" It's applied when Supermarket next starts.") return } s.Log.Info("backups: restoring; restarting", "from", res.From) // Reload once the app is back: Docker starts it again in a few seconds. w.Header().Set("Refresh", "8; url=/settings/backups") s.renderBackups(w, r, "", msg+" Supermarket is restarting to apply it; this page reloads by itself.") go func() { time.Sleep(500 * time.Millisecond) s.Restart() }() } // maxUpload is the biggest backup that can be uploaded. const maxUpload = 4 << 30 // backupUpload takes a backup file from the browser (one downloaded from // here, perhaps on another machine) and adds it to the list, checked; // restoring it is a second step. func (s *Server) backupUpload(w http.ResponseWriter, r *http.Request) { r.Body = http.MaxBytesReader(w, r.Body, maxUpload) f, hdr, err := r.FormFile("file") if err != nil { s.renderBackups(w, r, "Choose a backup file to upload.", "") return } defer f.Close() if err := os.MkdirAll(s.backupDir(), 0o700); err != nil { s.serverError(w, err) return } tmp, err := os.CreateTemp(s.backupDir(), ".upload-*.db") if err != nil { s.serverError(w, err) return } defer os.Remove(tmp.Name()) if _, err := io.Copy(tmp, f); err != nil { tmp.Close() s.renderBackups(w, r, "The upload didn't finish: "+err.Error(), "") return } tmp.Close() if err := backup.Check(tmp.Name()); err != nil { s.renderBackups(w, r, hdr.Filename+" isn't a Supermarket backup: "+err.Error()+".", "") return } // A backup downloaded from here keeps its note, not its whole name. note := "uploaded " + strings.TrimSuffix(filepath.Base(hdr.Filename), ".db") if b, ok := backup.Parse(filepath.Base(hdr.Filename)); ok { note = "uploaded " + b.Kind if b.Note != "" { note = "uploaded " + b.Note } } b, err := backup.Adopt(tmp.Name(), s.backupDir(), note, time.Now()) if err != nil { s.serverError(w, err) return } s.renderBackups(w, r, "", "Uploaded as "+b.Name+". Restore it from the list when you're ready.") }