Skip to content

Commit

Permalink
Add Backup function to search
Browse files Browse the repository at this point in the history
  • Loading branch information
tom-f committed Jun 24, 2017
1 parent 30dea40 commit 0a1d7d9
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 0 deletions.
9 changes: 9 additions & 0 deletions system/admin/handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import (
"github.com/ponzu-cms/ponzu/system/api/analytics"
"github.com/ponzu-cms/ponzu/system/db"
"github.com/ponzu-cms/ponzu/system/item"
"github.com/ponzu-cms/ponzu/system/search"

"github.com/gorilla/schema"
emailer "github.com/nilslice/email"
Expand Down Expand Up @@ -224,6 +225,14 @@ func backupHandler(res http.ResponseWriter, req *http.Request) {
return
}

case "search":
err := search.Backup(ctx, res)
if err != nil {
log.Println("Failed to run backup on search:", err)
res.WriteHeader(http.StatusInternalServerError)
return
}

default:
res.WriteHeader(http.StatusBadRequest)
}
Expand Down
57 changes: 57 additions & 0 deletions system/search/backup.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
package search

import (
"context"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"time"

"github.com/ponzu-cms/ponzu/system/backup"
)

// Backup creates an archive of a project's search index and writes it
// to the response as a download
func Backup(ctx context.Context, res http.ResponseWriter) error {
ts := time.Now().Unix()
filename := fmt.Sprintf("search-%d.bak.tar.gz", ts)
tmp := os.TempDir()
bk := filepath.Join(tmp, filename)

// create search-{stamp}.bak.tar.gz
f, err := os.Create(bk)
if err != nil {
return err
}

backup.ArchiveFS(ctx, "search", f)

err = f.Close()
if err != nil {
return err
}

// write data to response
data, err := os.Open(bk)
if err != nil {
return err
}
defer data.Close()
defer os.Remove(bk)

disposition := `attachment; filename=%s`
info, err := data.Stat()
if err != nil {
return err
}

res.Header().Set("Content-Type", "application/octet-stream")
res.Header().Set("Content-Disposition", fmt.Sprintf(disposition, ts))
res.Header().Set("Content-Length", fmt.Sprintf("%d", info.Size()))

_, err = io.Copy(res, data)

return err
}

0 comments on commit 0a1d7d9

Please sign in to comment.