-
Notifications
You must be signed in to change notification settings - Fork 40
/
main.go
295 lines (257 loc) · 8.06 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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
// Copyright (C) 2022 Sneller, Inc.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package main
import (
"encoding/json"
"flag"
"fmt"
"log"
"net"
"net/http"
"os"
"path"
"reflect"
"sync"
"time"
"github.com/SnellerInc/sneller/elasticproxy/proxy_http"
"github.com/bradfitz/gomemcache/memcache"
"github.com/gorilla/mux"
"golang.org/x/crypto/acme/autocert"
)
type config struct {
proxy_http.Config
LogFolder string `json:"logFolder,omitempty"`
syncMutex sync.Mutex
lastTimestamp string
timestampCounter int
ReverseProxy http.HandlerFunc
}
func (c *config) baseName(t time.Time) string {
c.syncMutex.Lock()
defer c.syncMutex.Unlock()
timestamp := t.Format("20060102-1504")
if timestamp != c.lastTimestamp {
c.timestampCounter = 0
c.lastTimestamp = timestamp
}
name := fmt.Sprintf("%s-%03d", timestamp, c.timestampCounter)
c.timestampCounter++
return name
}
type tenantConfig map[string]*config
var (
verbose bool = false
verboseLog = func(format string, v ...any) {}
)
const (
memcacheItemTimeout = 60 * 60
)
func main() {
ver, ok := Version()
if ok {
proxy_http.Version = ver
}
useTLS := flag.Bool("tls", false, "Enable TLS (automatically gets TLS certificates)")
configFile := flag.String("config", "config.json", "Configuration file")
endpoint := flag.String("endpoint", "localhost:8888", "Default endpoint (only for non-TLS mode)")
memcacheEndpoint := flag.String("memcache", "", "Optional memcache address")
verboseFlag := flag.Bool("v", false, "Verbose logging")
flag.Parse()
if *verboseFlag {
verboseLog = log.Printf
verbose = true
}
tenants, err := loadTenantConfiguration(*configFile)
if err != nil {
log.Fatalf("can't load %q: %v", *configFile, err)
}
var memcacheClient *memcache.Client
if *memcacheEndpoint != "" {
memcacheClient = memcache.New(*memcacheEndpoint)
}
withTenantConfig := func(f func(t *config, c *proxy_http.HandlerContext) bool) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
tenantID := r.Host
t, ok := tenants[r.Host]
if !ok {
if t, ok = tenants["*"]; !ok {
tenantID = "*"
w.WriteHeader(http.StatusNotFound)
return
}
}
client := &http.Client{
Timeout: t.Config.Sneller.Timeout,
}
c := proxy_http.NewHandlerContext(&t.Config, client, w, r, verbose, verboseLog)
if memcacheClient != nil {
c.Memcache.Client = memcacheClient
c.Memcache.TenantID = tenantID
c.Memcache.Secret = tenantID
c.Memcache.ExpirationTime = memcacheItemTimeout
}
baseName := path.Join(t.LogFolder, t.baseName(c.Logging.Start))
handled := f(t, c)
if !handled {
if t.ReverseProxy == nil {
w.WriteHeader(http.StatusNotFound)
return
}
t.ReverseProxy(w, r)
} else if t.LogFolder != "" {
writeIndentedJSON(baseName+"-step1-request.json", c.Logging.Request)
writeText(baseName+"-step2.sql", c.Logging.SQL)
writeIndentedJSON(baseName+"-step3-sneller-result.json", c.Logging.SnellerResult)
writeIndentedJSON(baseName+"-step3-sneller-stats.json", c.Logging.Sneller)
writeIndentedJSON(baseName+"-step4-preprocessed.json", c.Logging.Preprocessed)
writeIndentedJSON(baseName+"-step5-result.json", c.Logging.Result)
writeIndentedJSON(baseName+"-step6-elastic-result.json", c.Logging.ElasticResult)
writeText(baseName+"-step7-elastic-diff.json", c.Logging.ElasticDiff)
}
}
}
withConfig := func(f func(c *proxy_http.HandlerContext) bool) http.HandlerFunc {
return withTenantConfig(func(t *config, c *proxy_http.HandlerContext) bool {
return f(c)
})
}
r := mux.NewRouter()
r.HandleFunc("/sneller/version", proxy_http.VersionHandler).Methods(http.MethodGet)
r.HandleFunc("/{index}/_count", withConfig(proxy_http.CountProxy)).Methods(http.MethodGet, http.MethodPost)
r.HandleFunc("/{index}/_search", withConfig(proxy_http.SearchProxy)).Methods(http.MethodGet, http.MethodPost)
r.HandleFunc("/{index}/_async_search", withConfig(proxy_http.AsyncSearchProxy)).Methods(http.MethodPost)
r.HandleFunc("/_bulk", withConfig(proxy_http.BulkProxy)).Methods(http.MethodPost)
r.HandleFunc("/{target}/_bulk", withConfig(proxy_http.BulkProxy)).Methods(http.MethodPost)
r.HandleFunc("/{index}/_mapping", withConfig(func(c *proxy_http.HandlerContext) bool {
if proxy_http.Forward(c.Config, c.Writer, c.Request) {
return true
}
return proxy_http.MappingProxy(c)
})).Methods(http.MethodGet)
r.HandleFunc("/sneller/mapping/{index}", withConfig(proxy_http.MappingProxy)).Methods(http.MethodGet)
r.HandleFunc("/", withTenantConfig(func(t *config, c *proxy_http.HandlerContext) bool {
// always forward "ping" to the underlying Elastic instance (if set)
if t.ReverseProxy != nil {
return false
}
return proxy_http.Ping(&t.Config, c.Writer, c.Request)
})).Methods(http.MethodGet)
r.PathPrefix("/").Handler(http.HandlerFunc(withConfig(func(c *proxy_http.HandlerContext) bool {
return false
})))
var l net.Listener
if *useTLS {
var hosts []string
for host := range tenants {
if host == "*" {
log.Fatal("cannot use host '*' in TLS mode")
}
hosts = append(hosts, host)
verboseLog("listening on https://%s", host)
}
certManager := autocert.Manager{
Prompt: autocert.AcceptTOS,
HostPolicy: autocert.HostWhitelist(hosts...),
Cache: autocert.DirCache("certs"),
}
l = certManager.Listener()
} else {
verboseLog("listening on http://%s", *endpoint)
l, err = net.Listen("tcp", *endpoint)
if err != nil {
log.Fatalf("can't listen on %q: %v", *endpoint, err)
}
}
err = http.Serve(l, &handler{r})
if err != nil {
log.Fatal(err)
}
}
type handler struct {
http.Handler
}
func (h *handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if verbose {
start := time.Now()
ww := loggingResponseWriter{ResponseWriter: w}
defer func() {
duration := time.Since(start).Milliseconds()
log.Printf("%s %s (remote: %s, result: %d, forwarded: %v, took: %dms)", r.Method, r.Host+r.URL.Path, r.RemoteAddr, ww.statusCode, ww.forwarded, duration)
}()
w = &ww
}
h.Handler.ServeHTTP(w, r)
}
func loadTenantConfiguration(path string) (tenantConfig, error) {
configReader, err := os.Open(path)
if err != nil {
return nil, err
}
defer configReader.Close()
var tenants tenantConfig
err = json.NewDecoder(configReader).Decode(&tenants)
if err != nil {
return nil, err
}
// create a reverse-proxy for the underlying Elastic endpoint
for _, t := range tenants {
if t.LogFolder != "" {
err := os.MkdirAll(t.LogFolder, 0755)
if err != nil {
log.Printf("Unable to create folder %q (logs may be missing)", t.LogFolder)
}
}
if t.Config.Elastic.EndPoint != "" {
rp, err := proxy_http.ReverseProxyForConfig(&t.Config)
if err != nil {
return nil, err
}
t.ReverseProxy = func(w http.ResponseWriter, r *http.Request) {
if lrw, ok := w.(*loggingResponseWriter); ok {
lrw.forwarded = true
}
rp(w, r)
}
}
}
return tenants, nil
}
type loggingResponseWriter struct {
http.ResponseWriter
statusCode int
forwarded bool
}
func (lrw *loggingResponseWriter) WriteHeader(code int) {
lrw.statusCode = code
lrw.ResponseWriter.WriteHeader(code)
}
func writeText(fileName, text string) {
if text == "" {
return
}
os.WriteFile(fileName, []byte(text), 0644)
}
func writeIndentedJSON(fileName string, v any) {
if reflect.ValueOf(v).IsZero() {
return
}
w, err := os.OpenFile(fileName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
if err != nil {
return
}
defer w.Close()
e := json.NewEncoder(w)
e.SetIndent("", " ")
e.Encode(v)
}