-
Notifications
You must be signed in to change notification settings - Fork 4
/
server.go
109 lines (90 loc) · 2.36 KB
/
server.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
// Package healthcheck runs a server that responds with the status of the IPFS
// node.
package healthcheck
import (
"context"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"github.com/ipfs/go-cid"
coreiface "github.com/ipfs/interface-go-ipfs-core"
)
type ServerContext struct {
ipfs coreiface.CoreAPI
}
type ipfsServerContextKey struct {
key string
}
type status struct {
Message string
}
func StartServer(port string, ipfs coreiface.CoreAPI) {
server := http.Server{
Addr: ":" + port,
}
ctx := ServerContext{ipfs}
http.HandleFunc("/", createHandler(ctx, healthcheckHandler))
// Shutdown gracefully
idleConnsClosed := make(chan struct{})
go func() {
sigint := make(chan os.Signal, 1)
signal.Notify(sigint, os.Interrupt)
signal.Notify(sigint, syscall.SIGTERM)
<-sigint
fmt.Println("Healthcheck server shutting down...")
close(idleConnsClosed)
if err := server.Shutdown(context.Background()); err != nil {
log.Printf("Healthcheck server error on Shutdown: %+v", err)
}
}()
fmt.Println("Healthcheck server listening on port", port)
if err := server.ListenAndServe(); err != http.ErrServerClosed {
log.Printf("Healthcheck server error on ListenAndServe: %+v", err)
}
<-idleConnsClosed
}
func createHandler(
ctx ServerContext,
fn func(http.ResponseWriter, *http.Request),
) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
updatedCtx := context.WithValue(
r.Context(),
ipfsServerContextKey{"ipfs"},
ctx.ipfs,
)
updatedRequest := r.Clone(updatedCtx)
fn(w, updatedRequest)
}
}
func healthcheckHandler(w http.ResponseWriter, r *http.Request) {
// Use CID of empty directory which is pinned on all nodes by default
// https://github.com/ipfs/go-ipfs/issues/8404#issuecomment-917426813
c, err := cid.Decode("QmUNLLsPACCz1vLxQVkXqqLX5R1X345qqfHbsf67hvA3Nn")
if err != nil {
log.Panic(err)
}
var failed = false
var healthCheck *status
ctx := r.Context()
ipfs, _ := ctx.Value(ipfsServerContextKey{"ipfs"}).(coreiface.CoreAPI)
nd, err := ipfs.Dag().Get(ctx, c)
if err != nil {
failed = true
} else {
_, err = nd.Stat()
if err != nil {
failed = true
}
}
if failed {
w.WriteHeader(http.StatusInternalServerError)
healthCheck = &status{Message: "Health check failed"}
} else {
healthCheck = &status{Message: "Health check succeeded"}
}
_, _ = fmt.Fprintf(w, healthCheck.Message)
}