forked from MarshallWace/cachenator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
143 lines (124 loc) · 4.61 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
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
// Copyright 2021 Adrian Chifor, Marshall Wace
// SPDX-FileCopyrightText: 2021 Marshall Wace <[email protected]>
// SPDX-License-Identifier: GPL-3.0-only
package main
import (
"flag"
"fmt"
"net/http"
"os"
"os/signal"
"strings"
"syscall"
"github.com/gin-gonic/gin"
log "github.com/sirupsen/logrus"
)
const version string = "0.13.1"
var (
host string
port int
maxMultipartMemory int64
peersFlag string
verbose bool
versionFlag bool
)
func init() {
flag.StringVar(&host, "host", "localhost", "Host/IP to identify self in peers list")
flag.IntVar(&port, "port", 8080, "Server port")
flag.IntVar(&metricsPort, "metrics-port", 9095, "Prometheus metrics port")
flag.StringVar(&s3Endpoint, "s3-endpoint", "", "Custom S3 endpoint URL (defaults to AWS)")
flag.BoolVar(&s3ForcePathStyle, "s3-force-path-style", false,
"Force S3 path bucket addressing (endpoint/bucket/key vs. bucket.endpoint/key) (default false)")
flag.Int64Var(&uploadPartSize, "s3-upload-part-size", 5,
"Buffer size in megabytes when uploading blob chunks to S3 (minimum 5)")
flag.IntVar(&uploadConcurrency, "s3-upload-concurrency", 10,
"Number of goroutines to spin up when uploading blob chunks to S3")
flag.Int64Var(&downloadPartSize, "s3-download-part-size", 5,
"Size in megabytes to request from S3 for each blob chunk (minimum 5)")
flag.IntVar(&downloadConcurrency, "s3-download-concurrency", 10,
"Number of goroutines to spin up when downloading blob chunks from S3")
flag.Int64Var(&maxMultipartMemory, "max-multipart-memory", 128,
"Max memory in megabytes for /upload multipart form parsing")
flag.Int64Var(&maxCacheSize, "max-cache-size", 512,
"Max cache size in megabytes. If size goes above, oldest keys will be evicted")
flag.IntVar(&ttl, "ttl", 60, "Blob time-to-live in cache in minutes")
flag.IntVar(&timeout, "timeout", 5000, "Get blob timeout in milliseconds")
flag.StringVar(&peersFlag, "peers", "",
"Peers (default '', e.g. 'http://peer1:8080,http://peer2:8080')")
flag.BoolVar(&verbose, "verbose", false, "Verbose logs")
flag.BoolVar(&versionFlag, "version", false, "Version")
flag.Parse()
}
func main() {
checkFlags()
initS3()
initCachePool()
initMetrics()
go collectMetrics()
runServer()
}
func checkFlags() {
if verbose {
log.SetLevel(log.DebugLevel)
} else {
log.SetLevel(log.InfoLevel)
}
if versionFlag {
log.Infof("Cachenator version %s", version)
os.Exit(0)
}
peers = []string{}
if peersFlag != "" {
peers = strings.Split(peersFlag, ",")
peers = cleanupPeers(peers)
}
}
func runServer() {
done := make(chan bool, 1)
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
router := gin.Default()
listenAddr := fmt.Sprintf("127.0.0.1:%d", port)
if os.Getenv("GIN_MODE") == "release" {
listenAddr = fmt.Sprintf("0.0.0.0:%d", port)
log.SetFormatter(&log.JSONFormatter{})
router.Use(jsonLogMiddleware())
} else {
log.SetFormatter(&log.TextFormatter{
FullTimestamp: true,
})
}
router.Use(httpMetricsMiddleware())
router.MaxMultipartMemory = maxMultipartMemory << 20
router.POST("/upload", s3Upload)
router.DELETE("/delete", s3Delete)
router.GET("/list", s3List)
router.GET("/get", cacheGet)
router.POST("/prewarm", cachePrewarm)
router.POST("/invalidate", cacheInvalidate)
router.GET("/_groupcache/s3/*blob", gin.WrapF(cachePool.ServeHTTP))
router.DELETE("/_groupcache/s3/*blob", gin.WrapF(cachePool.ServeHTTP))
router.GET("/healthz", func(c *gin.Context) {
c.String(200, "UP")
})
server := &http.Server{
Addr: listenAddr,
Handler: router,
}
fmt.Println(`
┌────────────────────────────────────────┐
│░█▀▀░█▀█░█▀▀░█░█░█▀▀░█▀█░█▀█░▀█▀░█▀█░█▀▄│
│░█░░░█▀█░█░░░█▀█░█▀▀░█░█░█▀█░░█░░█░█░█▀▄│
│░▀▀▀░▀░▀░▀▀▀░▀░▀░▀▀▀░▀░▀░▀░▀░░▀░░▀▀▀░▀░▀│
└────────────────────────────────────────┘
`)
log.Infof("Running (v%s): %s", version, strings.Join(os.Args, " "))
go runMetricsServer()
go serverGracefulShutdown(server, quit, done)
log.Infof("HTTP server is ready to handle requests at %s", listenAddr)
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatalf("HTTP server could not listen on %s: %v\n", listenAddr, err)
}
<-done
log.Info("HTTP server stopped")
}