This repository has been archived by the owner on Oct 18, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 39
/
main.go
325 lines (286 loc) · 9.7 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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
package main
import (
"flag"
"fmt"
"log"
"log/syslog"
"net"
"net/http"
"os"
"os/signal"
"regexp"
"runtime"
"runtime/pprof"
"strings"
"syscall"
"time"
"github.com/dustin/gojson"
"github.com/dustin/yellow"
)
var dbRoot = flag.String("root", "db", "Root directory for database files.")
var flushTime = flag.Duration("flushDelay", time.Second*5,
"Maximum amount of time to wait before flushing")
var liveTime = flag.Duration("liveTime", time.Minute*5,
"How long to keep an idle DB open")
var maxOpQueue = flag.Int("maxOpQueue", 1000,
"Maximum number of queued items before flushing")
var staticPath = flag.String("static", "static", "Path to static data")
var queryTimeout = flag.Duration("maxQueryTime", time.Minute*5,
"Maximum amount of time a query is allowed to process.")
var queryBacklog = flag.Int("queryBacklog", 0, "Query scan/group backlog size")
var docBacklog = flag.Int("docBacklog", 0, "MR group request backlog size")
var cacheAddr = flag.String("memcache", "", "Memcached server to connect to")
var cacheBacklog = flag.Int("cacheBacklog", 1000, "Cache backlog size")
var cacheWorkers = flag.Int("cacheWorkers", 4, "Number of cache workers")
var verbose = flag.Bool("v", false, "Verbose logging")
var logAccess = flag.Bool("logAccess", false, "Log HTTP Requests")
var useSyslog = flag.Bool("syslog", false, "Log to syslog")
var minQueryLogDuration = flag.Duration("minQueryLogDuration",
time.Millisecond*100, "minimum query duration to log")
// Profiling
var pprofFile = flag.String("proFile", "", "File to write profiling info into")
var pprofStart = flag.Duration("proStart", 5*time.Second,
"How long after startup to start profiling")
var pprofDuration = flag.Duration("proDuration", 5*time.Minute,
"How long to run the profiler before shutting it down")
type routeHandler func(parts []string, w http.ResponseWriter, req *http.Request)
type routingEntry struct {
Method string
Path *regexp.Regexp
Handler routeHandler
Deadline time.Duration
}
const dbMatch = "[-%+()$_a-zA-Z0-9]+"
var defaultDeadline = time.Millisecond * 50
var routingTable []routingEntry
func init() {
routingTable = []routingEntry{
routingEntry{"GET", regexp.MustCompile("^/$"),
serverInfo, defaultDeadline},
routingEntry{"GET", regexp.MustCompile("^/_static/(.*)"),
staticHandler, defaultDeadline},
routingEntry{"GET", regexp.MustCompile("^/_debug/open$"),
debugListOpenDBs, defaultDeadline},
routingEntry{"GET", regexp.MustCompile("^/_debug/vars"),
debugVars, defaultDeadline},
// Database stuff
routingEntry{"GET", regexp.MustCompile("^/_all_dbs$"),
listDatabases, defaultDeadline},
routingEntry{"GET", regexp.MustCompile("^/_(.*)"),
reservedHandler, defaultDeadline},
routingEntry{"GET", regexp.MustCompile("^/(" + dbMatch + ")/?$"),
dbInfo, defaultDeadline},
routingEntry{"HEAD", regexp.MustCompile("^/(" + dbMatch + ")/?$"),
checkDB, defaultDeadline},
routingEntry{"GET", regexp.MustCompile("^/(" + dbMatch + ")/_changes$"),
dbChanges, defaultDeadline},
routingEntry{"GET", regexp.MustCompile("^/(" + dbMatch + ")/_query$"),
query, *queryTimeout},
routingEntry{"DELETE", regexp.MustCompile("^/(" + dbMatch + ")/_bulk$"),
deleteBulk, *queryTimeout},
routingEntry{"GET", regexp.MustCompile("^/(" + dbMatch + ")/_all"),
allDocs, *queryTimeout},
routingEntry{"GET", regexp.MustCompile("^/(" + dbMatch + ")/_dump"),
dumpDocs, *queryTimeout},
routingEntry{"POST", regexp.MustCompile("^/(" + dbMatch + ")/_compact"),
compact, time.Second * 30},
routingEntry{"PUT", regexp.MustCompile("^/(" + dbMatch + ")/?$"),
createDB, defaultDeadline},
routingEntry{"DELETE", regexp.MustCompile("^/(" + dbMatch + ")/?$"),
deleteDB, defaultDeadline},
routingEntry{"POST", regexp.MustCompile("^/(" + dbMatch + ")/?$"),
newDocument, defaultDeadline},
// Document stuff
routingEntry{"PUT", regexp.MustCompile("^/(" + dbMatch + ")/([^/]+)$"),
putDocument, defaultDeadline},
routingEntry{"GET", regexp.MustCompile("^/(" + dbMatch + ")/([^/]+)$"),
getDocument, defaultDeadline},
routingEntry{"DELETE", regexp.MustCompile("^/(" + dbMatch + ")/([^/]+)$"),
rmDocument, defaultDeadline},
// Pre-flight goodness
routingEntry{"OPTIONS", regexp.MustCompile(".*"),
handleOptions, defaultDeadline},
}
}
func mustEncode(status int, w http.ResponseWriter, ob interface{}) {
b, err := json.Marshal(ob)
if err != nil {
log.Fatalf("Error encoding %v.", ob)
}
w.Header().Set("Content-Length", fmt.Sprintf("%d", len(b)))
w.WriteHeader(status)
w.Write(b)
}
func emitError(status int, w http.ResponseWriter, e, reason string) {
m := map[string]string{"error": e, "reason": reason}
mustEncode(status, w, m)
}
func staticHandler(parts []string, w http.ResponseWriter, req *http.Request) {
w.Header().Del("Content-type")
http.StripPrefix("/_static/",
http.FileServer(http.Dir(*staticPath))).ServeHTTP(w, req)
}
func reservedHandler(parts []string, w http.ResponseWriter, req *http.Request) {
emitError(400,
w, "illegal_database_name",
"Only lowercase characters (a-z), digits (0-9), "+
"and any of the characters _, $, (, ), +, -, and / are allowed. "+
"Must begin with a letter.")
}
func defaultHandler(parts []string, w http.ResponseWriter, req *http.Request) {
emitError(400, w, "no_handler",
fmt.Sprintf("Can't handle %v to %v\n", req.Method, req.URL.Path))
}
func handleOptions(parts []string, w http.ResponseWriter, req *http.Request) {
methods := []string{}
for _, r := range routingTable {
if len(r.Path.FindAllStringSubmatch(req.URL.Path, 1)) > 0 {
methods = append(methods, r.Method)
}
}
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", strings.Join(methods, ", "))
w.WriteHeader(204)
}
func findHandler(method, path string) (routingEntry, []string) {
for _, r := range routingTable {
if r.Method == method {
matches := r.Path.FindAllStringSubmatch(path, 1)
if len(matches) > 0 {
return r, matches[0][1:]
}
}
}
return routingEntry{"DEFAULT", nil, defaultHandler, defaultDeadline},
[]string{}
}
func handler(w http.ResponseWriter, req *http.Request) {
if *logAccess {
log.Printf("%s %s %s", req.RemoteAddr, req.Method, req.URL)
}
route, hparts := findHandler(req.Method, req.URL.Path)
defer yellow.DeadlineLog(route.Deadline, "%v:%v deadlined at %v",
req.Method, req.URL.Path, route.Deadline).Done()
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Content-type", "application/json")
route.Handler(hparts, w, req)
}
func startProfiler() {
time.Sleep(*pprofStart)
log.Printf("Starting profiler")
f, err := os.OpenFile(*pprofFile, os.O_WRONLY|os.O_CREATE, 0666)
if err == nil {
err = pprof.StartCPUProfile(f)
if err != nil {
log.Fatalf("Can't start profiler")
}
time.AfterFunc(*pprofDuration, func() {
log.Printf("Shutting down profiler")
pprof.StopCPUProfile()
f.Close()
})
} else {
log.Printf("Can't open profilefile")
}
}
// globalShutdownChan is closed when it's time to shut down.
var globalShutdownChan = make(chan bool)
func listener(addr string) net.Listener {
if addr == "" {
addr = ":http"
}
l, err := net.Listen("tcp", addr)
if err != nil {
log.Fatalf("Error setting up listener: %v", err)
}
return l
}
func shutdownHandler(ls []net.Listener, ch <-chan os.Signal) {
s := <-ch
log.Printf("Shutting down on sig %v", s)
for _, l := range ls {
l.Close()
}
dbCloseAll()
time.AfterFunc(time.Minute, func() {
log.Fatalf("Timed out waiting for connections to close.")
})
}
func main() {
halfProcs := runtime.GOMAXPROCS(0) / 2
if halfProcs < 1 {
halfProcs = 1
}
queryWorkers := flag.Int("queryWorkers", halfProcs,
"Number of query tree walkers.")
docWorkers := flag.Int("docWorkers", halfProcs,
"Number of document mapreduce workers.")
addr := flag.String("addr", ":3133", "Address to bind to")
mcaddr := flag.String("memcbind", "", "Memcached server bind address")
flag.Parse()
if *useSyslog {
sl, err := syslog.New(syslog.LOG_INFO, "seriesly")
if err != nil {
log.Fatalf("Can't initialize syslog: %v", err)
}
log.SetOutput(sl)
log.SetFlags(0)
}
if err := os.MkdirAll(*dbRoot, 0777); err != nil {
log.Fatalf("Could not create %v: %v", *dbRoot, err)
}
// Update the query handler deadline to the query timeout
found := false
for i := range routingTable {
matches := routingTable[i].Path.FindAllStringSubmatch("/x/_query", 1)
if len(matches) > 0 {
routingTable[i].Deadline = *queryTimeout
found = true
break
}
}
if !found {
log.Fatalf("Programming error: Could not find query handler")
}
processorInput = make(chan *processIn, *docBacklog)
for i := 0; i < *docWorkers; i++ {
go docProcessor(processorInput)
}
if *cacheAddr == "" {
cacheInput = processorInput
// Note: cacheInputSet will be null here, there should be no caching
} else {
cacheInput = make(chan *processIn, *cacheBacklog)
cacheInputSet = make(chan *processOut, *cacheBacklog)
for i := 0; i < *cacheWorkers; i++ {
go cacheProcessor(cacheInput, cacheInputSet)
}
}
queryInput = make(chan *queryIn, *queryBacklog)
for i := 0; i < *queryWorkers; i++ {
go queryExecutor()
}
if *pprofFile != "" {
go startProfiler()
}
listeners := []net.Listener{}
if *mcaddr != "" {
listeners = append(listeners, listenMC(*mcaddr))
}
s := &http.Server{
Addr: *addr,
Handler: http.HandlerFunc(handler),
ReadTimeout: 5 * time.Second,
}
log.Printf("Listening to web requests on %s", *addr)
l := listener(*addr)
listeners = append(listeners, l)
// Need signal handler to shut down listeners
sigch := make(chan os.Signal, 1)
signal.Notify(sigch, syscall.SIGINT, syscall.SIGTERM)
go shutdownHandler(listeners, sigch)
err := s.Serve(l)
log.Printf("Web server finished with %v", err)
log.Printf("Waiting for databases to finish")
dbWg.Wait()
}