forked from rqlite/rqlite
/
service.go
936 lines (802 loc) · 22.7 KB
/
service.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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
// Package http provides the HTTP server for accessing the distributed database.
// It also provides the endpoint for other nodes to join an existing cluster.
package http
import (
"bytes"
"crypto/tls"
"crypto/x509"
"encoding/json"
"errors"
"expvar"
"fmt"
"io/ioutil"
"log"
"net"
"net/http"
"net/http/pprof"
"os"
"runtime"
"strings"
"sync"
"time"
sql "github.com/rqlite/rqlite/db"
"github.com/rqlite/rqlite/store"
)
// Store is the interface the Raft-based database must implement.
type Store interface {
// Execute executes a slice of queries, each of which is not expected
// to return rows. If timings is true, then timing information will
// be return. If tx is true, then either all queries will be executed
// successfully or it will as though none executed.
Execute(er *store.ExecuteRequest) ([]*sql.Result, error)
// ExecuteOrAbort performs the same function as Execute(), but ensures
// any transactions are aborted in case of any error.
ExecuteOrAbort(er *store.ExecuteRequest) ([]*sql.Result, error)
// Query executes a slice of queries, each of which returns rows. If
// timings is true, then timing information will be returned. If tx
// is true, then all queries will take place while a read transaction
// is held on the database.
Query(qr *store.QueryRequest) ([]*sql.Rows, error)
// Join joins the node, reachable at addr, to this node.
Join(addr string) error
// Remove removes the node, specified by addr, from the cluster.
Remove(addr string) error
// Leader returns the Raft leader of the cluster.
Leader() string
// Peer returns the API peer for the given address
Peer(addr string) string
// Stats returns stats on the Store.
Stats() (map[string]interface{}, error)
// Backup returns a byte slice representing a backup of the node state.
Backup(leader bool, f store.BackupFormat) ([]byte, error)
}
// CredentialStore is the interface credential stores must support.
type CredentialStore interface {
// Check returns whether username and password are a valid combination.
Check(username, password string) bool
// HasPerm returns whether username has the given perm.
HasPerm(username string, perm string) bool
}
// Statuser is the interface status providers must implement.
type Statuser interface {
Stats() (interface{}, error)
}
// Response represents a response from the HTTP service.
type Response struct {
Results interface{} `json:"results,omitempty"`
Error string `json:"error,omitempty"`
Time float64 `json:"time,omitempty"`
start time.Time
end time.Time
}
// stats captures stats for the HTTP service.
var stats *expvar.Map
const (
numExecutions = "executions"
numQueries = "queries"
numBackups = "backups"
numLoad = "loads"
// PermAll means all actions permitted.
PermAll = "all"
// PermJoin means user is permitted to join cluster.
PermJoin = "join"
// PermRemove means user is permitted to remove a node.
PermRemove = "remove"
// PermExecute means user can access execute endpoint.
PermExecute = "execute"
// PermQuery means user can access query endpoint
PermQuery = "query"
// PermStatus means user can retrieve node status.
PermStatus = "status"
// PermBackup means user can backup node.
PermBackup = "backup"
// PermLoad means user can load a SQLite dump into a node.
PermLoad = "load"
// VersionHTTPHeader is the HTTP header key for the version.
VersionHTTPHeader = "X-RQLITE-VERSION"
)
func init() {
stats = expvar.NewMap("http")
stats.Add(numExecutions, 0)
stats.Add(numQueries, 0)
stats.Add(numBackups, 0)
}
// SetTime sets the Time attribute of the response. This way it will be present
// in the serialized JSON version.
func (r *Response) SetTime() {
r.Time = r.end.Sub(r.start).Seconds()
}
// NewResponse returns a new instance of response.
func NewResponse() *Response {
return &Response{
start: time.Now(),
}
}
// Service provides HTTP service.
type Service struct {
addr string // Bind address of the HTTP service.
ln net.Listener // Service listener
store Store // The Raft-backed database store.
start time.Time // Start up time.
lastBackup time.Time // Time of last successful backup.
statusMu sync.RWMutex
statuses map[string]Statuser
CACertFile string // Path to root X.509 certificate.
CertFile string // Path to SSL certificate.
KeyFile string // Path to SSL private key.
credentialStore CredentialStore
Expvar bool
Pprof bool
BuildInfo map[string]interface{}
logger *log.Logger
}
// New returns an uninitialized HTTP service. If credentials is nil, then
// the service performs no authentication and authorization checks.
func New(addr string, store Store, credentials CredentialStore) *Service {
return &Service{
addr: addr,
store: store,
start: time.Now(),
statuses: make(map[string]Statuser),
credentialStore: credentials,
logger: log.New(os.Stderr, "[http] ", log.LstdFlags),
}
}
// Start starts the service.
func (s *Service) Start() error {
server := http.Server{
Handler: s,
}
var ln net.Listener
var err error
if s.CertFile == "" || s.KeyFile == "" {
ln, err = net.Listen("tcp", s.addr)
if err != nil {
return err
}
} else {
config, err := createTLSConfig(s.CertFile, s.KeyFile, s.CACertFile)
if err != nil {
return err
}
ln, err = tls.Listen("tcp", s.addr, config)
if err != nil {
return err
}
s.logger.Printf("secure HTTPS server enabled with cert %s, key %s", s.CertFile, s.KeyFile)
}
s.ln = ln
go func() {
err := server.Serve(s.ln)
if err != nil {
s.logger.Println("HTTP service Serve() returned:", err.Error())
}
}()
s.logger.Println("service listening on", s.addr)
return nil
}
// Close closes the service.
func (s *Service) Close() {
s.ln.Close()
return
}
// ServeHTTP allows Service to serve HTTP requests.
func (s *Service) ServeHTTP(w http.ResponseWriter, r *http.Request) {
s.addBuildVersion(w)
if s.credentialStore != nil {
username, password, ok := r.BasicAuth()
if !ok || !s.credentialStore.Check(username, password) {
w.WriteHeader(http.StatusUnauthorized)
return
}
}
switch {
case strings.HasPrefix(r.URL.Path, "/db/execute"):
stats.Add(numExecutions, 1)
s.handleExecute(w, r)
case strings.HasPrefix(r.URL.Path, "/db/query"):
stats.Add(numQueries, 1)
s.handleQuery(w, r)
case strings.HasPrefix(r.URL.Path, "/db/backup"):
stats.Add(numBackups, 1)
s.handleBackup(w, r)
case strings.HasPrefix(r.URL.Path, "/db/load"):
stats.Add(numLoad, 1)
s.handleLoad(w, r)
case strings.HasPrefix(r.URL.Path, "/join"):
s.handleJoin(w, r)
case strings.HasPrefix(r.URL.Path, "/remove"):
s.handleRemove(w, r)
case strings.HasPrefix(r.URL.Path, "/status"):
s.handleStatus(w, r)
case r.URL.Path == "/debug/vars" && s.Expvar:
s.handleExpvar(w, r)
case strings.HasPrefix(r.URL.Path, "/debug/pprof") && s.Pprof:
s.handlePprof(w, r)
default:
w.WriteHeader(http.StatusNotFound)
}
}
// RegisterStatus allows other modules to register status for serving over HTTP.
func (s *Service) RegisterStatus(key string, stat Statuser) error {
s.statusMu.Lock()
defer s.statusMu.Unlock()
if _, ok := s.statuses[key]; ok {
return fmt.Errorf("status already registered with key %s", key)
}
s.statuses[key] = stat
return nil
}
// handleJoin handles cluster-join requests from other nodes.
func (s *Service) handleJoin(w http.ResponseWriter, r *http.Request) {
if !s.CheckRequestPerm(r, PermJoin) {
w.WriteHeader(http.StatusUnauthorized)
return
}
if r.Method != "POST" {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
b, err := ioutil.ReadAll(r.Body)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
m := map[string]string{}
if err := json.Unmarshal(b, &m); err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
if len(m) != 1 {
w.WriteHeader(http.StatusBadRequest)
return
}
remoteAddr, ok := m["addr"]
if !ok {
w.WriteHeader(http.StatusBadRequest)
return
}
if err := s.store.Join(remoteAddr); err != nil {
if err == store.ErrNotLeader {
leader := s.store.Peer(s.store.Leader())
if leader == "" {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return
}
redirect := s.FormRedirect(r, leader)
http.Redirect(w, r, redirect, http.StatusMovedPermanently)
return
}
b := bytes.NewBufferString(err.Error())
w.WriteHeader(http.StatusInternalServerError)
w.Write(b.Bytes())
return
}
}
// handleRemove handles cluster-remove requests.
func (s *Service) handleRemove(w http.ResponseWriter, r *http.Request) {
if !s.CheckRequestPerm(r, PermRemove) {
w.WriteHeader(http.StatusUnauthorized)
return
}
if r.Method != "DELETE" {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
b, err := ioutil.ReadAll(r.Body)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
m := map[string]string{}
if err := json.Unmarshal(b, &m); err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
if len(m) != 1 {
w.WriteHeader(http.StatusBadRequest)
return
}
remoteAddr, ok := m["addr"]
if !ok {
w.WriteHeader(http.StatusBadRequest)
return
}
if err := s.store.Remove(remoteAddr); err != nil {
if err == store.ErrNotLeader {
leader := s.store.Peer(s.store.Leader())
if leader == "" {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return
}
redirect := s.FormRedirect(r, leader)
http.Redirect(w, r, redirect, http.StatusMovedPermanently)
return
}
w.WriteHeader(http.StatusInternalServerError)
return
}
}
// handleBackup returns the consistent database snapshot.
func (s *Service) handleBackup(w http.ResponseWriter, r *http.Request) {
if !s.CheckRequestPerm(r, PermBackup) {
w.WriteHeader(http.StatusUnauthorized)
return
}
if r.Method != "GET" {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
noLeader, err := noLeader(r)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
bf, err := backupFormat(w, r)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
b, err := s.store.Backup(!noLeader, bf)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
_, err = w.Write(b)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
s.lastBackup = time.Now()
}
// handleLoad loads the state contained in a .dump output.
func (s *Service) handleLoad(w http.ResponseWriter, r *http.Request) {
if !s.CheckRequestPerm(r, PermLoad) {
w.WriteHeader(http.StatusUnauthorized)
return
}
if r.Method != "POST" {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
resp := NewResponse()
timings, err := timings(r)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
b, err := ioutil.ReadAll(r.Body)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
r.Body.Close()
queries := []string{string(b)}
results, err := s.store.ExecuteOrAbort(&store.ExecuteRequest{queries, timings, false})
if err != nil {
if err == store.ErrNotLeader {
leader := s.store.Peer(s.store.Leader())
if leader == "" {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return
}
redirect := s.FormRedirect(r, leader)
http.Redirect(w, r, redirect, http.StatusMovedPermanently)
return
}
resp.Error = err.Error()
} else {
resp.Results = results
}
resp.end = time.Now()
writeResponse(w, r, resp)
}
// handleStatus returns status on the system.
func (s *Service) handleStatus(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
if !s.CheckRequestPerm(r, PermStatus) {
w.WriteHeader(http.StatusUnauthorized)
return
}
if r.Method != "GET" {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
results, err := s.store.Stats()
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
rt := map[string]interface{}{
"GOARCH": runtime.GOARCH,
"GOOS": runtime.GOOS,
"GOMAXPROCS": runtime.GOMAXPROCS(0),
"numCPU": runtime.NumCPU(),
"numGoroutine": runtime.NumGoroutine(),
"version": runtime.Version(),
}
httpStatus := map[string]interface{}{
"addr": s.Addr().String(),
"auth": prettyEnabled(s.credentialStore != nil),
"redirect": s.store.Peer(s.store.Leader()),
}
nodeStatus := map[string]interface{}{
"start_time": s.start,
"uptime": time.Since(s.start).String(),
}
// Build the status response.
status := map[string]interface{}{
"runtime": rt,
"store": results,
"http": httpStatus,
"node": nodeStatus,
}
if !s.lastBackup.IsZero() {
status["last_backup"] = s.lastBackup
}
if s.BuildInfo != nil {
status["build"] = s.BuildInfo
}
// Add any registered statusers.
func() {
s.statusMu.RLock()
defer s.statusMu.RUnlock()
for k, v := range s.statuses {
stat, err := v.Stats()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
status[k] = stat
}
}()
pretty, _ := isPretty(r)
var b []byte
if pretty {
b, err = json.MarshalIndent(status, "", " ")
} else {
b, err = json.Marshal(status)
}
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
} else {
_, err = w.Write([]byte(b))
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
}
}
}
// handleExecute handles queries that modify the database.
func (s *Service) handleExecute(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
if !s.CheckRequestPerm(r, PermExecute) {
w.WriteHeader(http.StatusUnauthorized)
return
}
if r.Method != "POST" {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
resp := NewResponse()
isTx, err := isTx(r)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
timings, err := timings(r)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
b, err := ioutil.ReadAll(r.Body)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
r.Body.Close()
queries := []string{}
if err := json.Unmarshal(b, &queries); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
results, err := s.store.Execute(&store.ExecuteRequest{queries, timings, isTx})
if err != nil {
if err == store.ErrNotLeader {
leader := s.store.Peer(s.store.Leader())
if leader == "" {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return
}
redirect := s.FormRedirect(r, leader)
http.Redirect(w, r, redirect, http.StatusMovedPermanently)
return
}
resp.Error = err.Error()
} else {
resp.Results = results
}
resp.end = time.Now()
writeResponse(w, r, resp)
}
// handleQuery handles queries that do not modify the database.
func (s *Service) handleQuery(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
if !s.CheckRequestPerm(r, PermQuery) {
w.WriteHeader(http.StatusUnauthorized)
return
}
if r.Method != "GET" && r.Method != "POST" {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
resp := NewResponse()
isTx, err := isTx(r)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
timings, err := timings(r)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
lvl, err := level(r)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Get the query statement(s), and do tx if necessary.
queries, err := requestQueries(r)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
results, err := s.store.Query(&store.QueryRequest{queries, timings, isTx, lvl})
if err != nil {
if err == store.ErrNotLeader {
leader := s.store.Peer(s.store.Leader())
if leader == "" {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return
}
redirect := s.FormRedirect(r, leader)
http.Redirect(w, r, redirect, http.StatusMovedPermanently)
return
}
resp.Error = err.Error()
} else {
resp.Results = results
}
resp.end = time.Now()
writeResponse(w, r, resp)
}
// handleExpvar serves registered expvar information over HTTP.
func (s *Service) handleExpvar(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
if !s.CheckRequestPerm(r, PermStatus) {
w.WriteHeader(http.StatusUnauthorized)
return
}
fmt.Fprintf(w, "{\n")
first := true
expvar.Do(func(kv expvar.KeyValue) {
if !first {
fmt.Fprintf(w, ",\n")
}
first = false
fmt.Fprintf(w, "%q: %s", kv.Key, kv.Value)
})
fmt.Fprintf(w, "\n}\n")
}
// handlePprof serves pprof information over HTTP.
func (s *Service) handlePprof(w http.ResponseWriter, r *http.Request) {
if !s.CheckRequestPerm(r, PermStatus) {
w.WriteHeader(http.StatusUnauthorized)
return
}
switch r.URL.Path {
case "/debug/pprof/cmdline":
pprof.Cmdline(w, r)
case "/debug/pprof/profile":
pprof.Profile(w, r)
case "/debug/pprof/symbol":
pprof.Symbol(w, r)
default:
pprof.Index(w, r)
}
}
// Addr returns the address on which the Service is listening
func (s *Service) Addr() net.Addr {
return s.ln.Addr()
}
// FormRedirect returns the value for the "Location" header for a 301 response.
func (s *Service) FormRedirect(r *http.Request, host string) string {
protocol := "http"
if s.credentialStore != nil {
protocol = "https"
}
rq := r.URL.RawQuery
if rq != "" {
rq = fmt.Sprintf("?%s", rq)
}
return fmt.Sprintf("%s://%s%s%s", protocol, host, r.URL.Path, rq)
}
// CheckRequestPerm returns true if authentication is enabled and the user contained
// in the BasicAuth request has either PermAll, or the given perm.
func (s *Service) CheckRequestPerm(r *http.Request, perm string) bool {
if s.credentialStore == nil {
return true
}
username, _, ok := r.BasicAuth()
if !ok {
return false
}
return s.credentialStore.HasPerm(username, PermAll) || s.credentialStore.HasPerm(username, perm)
}
// addBuildVersion adds the build version to the HTTP response.
func (s *Service) addBuildVersion(w http.ResponseWriter) {
// Add version header to every response, if available.
version := "unknown"
if v, ok := s.BuildInfo["version"].(string); ok {
version = v
}
w.Header().Add(VersionHTTPHeader, version)
}
func requestQueries(r *http.Request) ([]string, error) {
if r.Method == "GET" {
query, err := stmtParam(r)
if err != nil || query == "" {
return nil, errors.New("bad query GET request")
}
return []string{query}, nil
}
qs := []string{}
b, err := ioutil.ReadAll(r.Body)
if err != nil {
return nil, errors.New("bad query POST request")
}
r.Body.Close()
if err := json.Unmarshal(b, &qs); err != nil {
return nil, errors.New("bad query POST request")
}
if len(qs) == 0 {
return nil, errors.New("bad query POST request")
}
return qs, nil
}
func writeResponse(w http.ResponseWriter, r *http.Request, j *Response) {
var b []byte
var err error
pretty, _ := isPretty(r)
timings, _ := timings(r)
if timings {
j.SetTime()
}
if pretty {
b, err = json.MarshalIndent(j, "", " ")
} else {
b, err = json.Marshal(j)
}
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
_, err = w.Write(b)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
// createTLSConfig returns a TLS config from the given cert and key.
func createTLSConfig(certFile, keyFile, caCertFile string) (*tls.Config, error) {
var err error
config := &tls.Config{}
config.Certificates = make([]tls.Certificate, 1)
config.Certificates[0], err = tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
return nil, err
}
if caCertFile != "" {
asn1Data, err := ioutil.ReadFile(caCertFile)
if err != nil {
return nil, err
}
config.RootCAs = x509.NewCertPool()
ok := config.RootCAs.AppendCertsFromPEM([]byte(asn1Data))
if !ok {
return nil, fmt.Errorf("failed to parse root certificate(s) in %q", caCertFile)
}
}
return config, nil
}
// queryParam returns whether the given query param is set to true.
func queryParam(req *http.Request, param string) (bool, error) {
err := req.ParseForm()
if err != nil {
return false, err
}
if _, ok := req.Form[param]; ok {
return true, nil
}
return false, nil
}
// stmtParam returns the value for URL param 'q', if present.
func stmtParam(req *http.Request) (string, error) {
q := req.URL.Query()
stmt := strings.TrimSpace(q.Get("q"))
return stmt, nil
}
// fmtParam returns the value for URL param 'fmt', if present.
func fmtParam(req *http.Request) (string, error) {
q := req.URL.Query()
return strings.TrimSpace(q.Get("fmt")), nil
}
// isPretty returns whether the HTTP response body should be pretty-printed.
func isPretty(req *http.Request) (bool, error) {
return queryParam(req, "pretty")
}
// isTx returns whether the HTTP request is requesting a transaction.
func isTx(req *http.Request) (bool, error) {
return queryParam(req, "transaction")
}
// noLeader returns whether processing should skip the leader check.
func noLeader(req *http.Request) (bool, error) {
return queryParam(req, "noleader")
}
// timings returns whether timings are requested.
func timings(req *http.Request) (bool, error) {
return queryParam(req, "timings")
}
// level returns the requested consistency level for a query
func level(req *http.Request) (store.ConsistencyLevel, error) {
q := req.URL.Query()
lvl := strings.TrimSpace(q.Get("level"))
switch strings.ToLower(lvl) {
case "none":
return store.None, nil
case "weak":
return store.Weak, nil
case "strong":
return store.Strong, nil
default:
return store.Weak, nil
}
}
// backupFormat returns the request backup format, setting the response header
// accordingly.
func backupFormat(w http.ResponseWriter, r *http.Request) (store.BackupFormat, error) {
fmt, err := fmtParam(r)
if err != nil {
return store.BackupBinary, err
}
if fmt == "sql" {
w.Header().Set("Content-Type", "application/sql")
return store.BackupSQL, nil
}
w.Header().Set("Content-Type", "application/octet-stream")
return store.BackupBinary, nil
}
func prettyEnabled(e bool) string {
if e {
return "enabled"
}
return "disabled"
}
// NormalizeAddr ensures that the given URL has a HTTP protocol prefix.
// If none is supplied, it prefixes the URL with "http://".
func NormalizeAddr(addr string) string {
if !strings.HasPrefix(addr, "http://") && !strings.HasPrefix(addr, "https://") {
return fmt.Sprintf("http://%s", addr)
}
return addr
}
// EnsureHTTPS modifies the given URL, so that is ensures it is using the HTTPS protocol.
func EnsureHTTPS(addr string) string {
if !strings.HasPrefix(addr, "http://") && !strings.HasPrefix(addr, "https://") {
return fmt.Sprintf("https://%s", addr)
}
return strings.Replace(addr, "http://", "https://", 1)
}
// CheckHTTPS returns true if the given URL uses HTTPS.
func CheckHTTPS(addr string) bool {
return strings.HasPrefix(addr, "https://")
}