This repository has been archived by the owner on May 11, 2020. It is now read-only.
/
main.go
70 lines (56 loc) · 1.52 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package main
import (
"fmt"
"net/http"
"os"
"time"
"context"
"log"
compute "google.golang.org/api/compute/v1"
)
func main() {
http.HandleFunc("/", handler)
port := os.Getenv("PORT")
if port == "" {
port = "8080"
log.Printf("Defaulting to port %s", port)
}
log.Printf("Listening on port %s", port)
if err := http.ListenAndServe(":"+port, nil); err != nil {
log.Fatal(err)
}
}
func handler(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
// See https://stackoverflow.com/questions/46659607/how-to-allow-only-internal-cron-requests-in-my-app-engine/46662128
if r.Header.Get("X-Appengine-Cron") != "true" {
log.Println("Rejecting request since it does not originate from cron")
w.WriteHeader(http.StatusForbidden)
return
}
// Taking disk name from URL would be a bit more sophisticated
diskName := "mtb-lohja-forum-data"
selfLink, err := snapshot(ctx, diskName)
if err != nil {
log.Println("Snapshotting failed:", err)
fmt.Fprint(w, err)
w.WriteHeader(http.StatusInternalServerError)
return
}
fmt.Fprint(w, selfLink)
}
func snapshot(ctx context.Context, disk string) (string, error) {
computeService, err := compute.NewService(ctx)
if err != nil {
return "", err
}
snapshot := &compute.Snapshot{
Description: "Snapshot of MTB Lohja Forum data",
Name: fmt.Sprintf("%s-%d", disk, time.Now().Unix()),
}
resp, err := computeService.Disks.CreateSnapshot("mtb-lohja", "europe-west1-c", disk, snapshot).Do()
if err != nil {
return "", err
}
return resp.SelfLink, nil
}