/
service.go
1762 lines (1535 loc) · 47.4 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
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Package http provides the HTTP server for accessing the distributed database.
package http
import (
"bufio"
"context"
"crypto/tls"
"encoding/json"
"errors"
"expvar"
"fmt"
"io"
"log"
"net"
"net/http"
"net/http/pprof"
"os"
"runtime"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/rqlite/rqlite/v8/auth"
clstrPB "github.com/rqlite/rqlite/v8/cluster/proto"
"github.com/rqlite/rqlite/v8/command/encoding"
"github.com/rqlite/rqlite/v8/command/proto"
command "github.com/rqlite/rqlite/v8/command/proto"
"github.com/rqlite/rqlite/v8/command/sql"
"github.com/rqlite/rqlite/v8/db"
"github.com/rqlite/rqlite/v8/queue"
"github.com/rqlite/rqlite/v8/rtls"
"github.com/rqlite/rqlite/v8/store"
)
var (
// ErrLeaderNotFound is returned when a node cannot locate a leader
ErrLeaderNotFound = errors.New("leader not found")
)
type ResultsError interface {
Error() string
IsAuthorized() bool
}
// Database is the interface any queryable system must implement
type Database 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 *proto.ExecuteRequest) ([]*proto.ExecuteQueryResponse, 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 *proto.QueryRequest) ([]*proto.QueryRows, error)
// Request processes a slice of requests, each of which can be either
// an Execute or Query request.
Request(eqr *proto.ExecuteQueryRequest) ([]*proto.ExecuteQueryResponse, error)
// Load loads a SQLite file into the system via Raft consensus.
Load(lr *proto.LoadRequest) error
}
// Store is the interface the Raft-based database must implement.
type Store interface {
Database
// Remove removes the node from the cluster.
Remove(rn *proto.RemoveNodeRequest) error
// LeaderAddr returns the Raft address of the leader of the cluster.
LeaderAddr() (string, error)
// Ready returns whether the Store is ready to service requests.
Ready() bool
// Committed blocks until the local commit index is greater than or
// equal to the Leader index, as checked when the function is called.
Committed(timeout time.Duration) (uint64, error)
// Stats returns stats on the Store.
Stats() (map[string]interface{}, error)
// Nodes returns the slice of store.Servers in the cluster
Nodes() ([]*store.Server, error)
// Backup writes backup of the node state to dst
Backup(br *proto.BackupRequest, dst io.Writer) error
// ReadFrom reads and loads a SQLite database into the node, initially bypassing
// the Raft system. It then triggers a Raft snapshot, which will then make
// Raft aware of the new data.
ReadFrom(r io.Reader) (int64, error)
}
// GetAddresser is the interface that wraps the GetNodeAPIAddr method.
// GetNodeAPIAddr returns the HTTP API URL for the node at the given Raft address.
type GetAddresser interface {
GetNodeAPIAddr(addr string, retries int, timeout time.Duration) (string, error)
}
// Cluster is the interface node API services must provide
type Cluster interface {
GetAddresser
// Execute performs an Execute Request on a remote node.
Execute(er *proto.ExecuteRequest, nodeAddr string, creds *clstrPB.Credentials, timeout time.Duration, retries int) ([]*proto.ExecuteQueryResponse, error)
// Query performs an Query Request on a remote node.
Query(qr *proto.QueryRequest, nodeAddr string, creds *clstrPB.Credentials, timeout time.Duration) ([]*proto.QueryRows, error)
// Request performs an ExecuteQuery Request on a remote node.
Request(eqr *proto.ExecuteQueryRequest, nodeAddr string, creds *clstrPB.Credentials, timeout time.Duration, retries int) ([]*proto.ExecuteQueryResponse, error)
// Backup retrieves a backup from a remote node and writes to the io.Writer.
Backup(br *proto.BackupRequest, nodeAddr string, creds *clstrPB.Credentials, timeout time.Duration, w io.Writer) error
// Load loads a SQLite database into the node.
Load(lr *proto.LoadRequest, nodeAddr string, creds *clstrPB.Credentials, timeout time.Duration, retries int) error
// RemoveNode removes a node from the cluster.
RemoveNode(rn *proto.RemoveNodeRequest, nodeAddr string, creds *clstrPB.Credentials, timeout time.Duration) error
// Stats returns stats on the Cluster.
Stats() (map[string]interface{}, error)
}
// CredentialStore is the interface credential stores must support.
type CredentialStore interface {
// AA authenticates and checks authorization for the given perm.
AA(username, password, perm string) bool
}
// StatusReporter is the interface status providers must implement.
type StatusReporter interface {
Stats() (map[string]interface{}, error)
}
// DBResults stores either an Execute result, a Query result, or
// an ExecuteQuery result.
type DBResults struct {
ExecuteQueryResponse []*proto.ExecuteQueryResponse
QueryRows []*proto.QueryRows
AssociativeJSON bool // Render in associative form
BlobsAsArrays bool // Render BLOB data as byte arrays
}
// Responser is the interface response objects must implement.
type Responser interface {
SetTime()
}
// MarshalJSON implements the JSON Marshaler interface.
func (d *DBResults) MarshalJSON() ([]byte, error) {
enc := encoding.Encoder{
Associative: d.AssociativeJSON,
BlobsAsByteArrays: d.BlobsAsArrays,
}
if d.QueryRows != nil {
return enc.JSONMarshal(d.QueryRows)
} else if d.ExecuteQueryResponse != nil {
return enc.JSONMarshal(d.ExecuteQueryResponse)
}
return json.Marshal(make([]interface{}, 0))
}
// Response represents a response from the HTTP service.
type Response struct {
Results *DBResults `json:"results,omitempty"`
Error string `json:"error,omitempty"`
Time float64 `json:"time,omitempty"`
SequenceNum int64 `json:"sequence_number,omitempty"`
start time.Time
end time.Time
}
// 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{
Results: &DBResults{},
start: time.Now(),
}
}
// stats captures stats for the HTTP service.
var stats *expvar.Map
const (
numLeaderNotFound = "leader_not_found"
numExecutions = "executions"
numExecuteStmtsRx = "execute_stmts_rx"
numQueuedExecutions = "queued_executions"
numQueuedExecutionsOK = "queued_executions_ok"
numQueuedExecutionsStmtsRx = "queued_executions_num_stmts_rx"
numQueuedExecutionsStmtsTx = "queued_executions_num_stmts_tx"
numQueuedExecutionsNoLeader = "queued_executions_no_leader"
numQueuedExecutionsNotLeader = "queued_executions_not_leader"
numQueuedExecutionsLeadershipLost = "queued_executions_leadership_lost"
numQueuedExecutionsUnknownError = "queued_executions_unknown_error"
numQueuedExecutionsFailed = "queued_executions_failed"
numQueuedExecutionsWait = "queued_executions_wait"
numQueries = "queries"
numQueryStmtsRx = "query_stmts_rx"
numRequests = "requests"
numRequestStmtsRx = "request_stmts_rx"
numRemoteExecutions = "remote_executions"
numRemoteExecutionsFailed = "remote_executions_failed"
numRemoteQueries = "remote_queries"
numRemoteQueriesFailed = "remote_queries_failed"
numRemoteRequests = "remote_requests"
numRemoteRequestsFailed = "remote_requests_failed"
numRemoteBackups = "remote_backups"
numRemoteLoads = "remote_loads"
numRemoteRemoveNode = "remote_remove_node"
numReadyz = "num_readyz"
numStatus = "num_status"
numBackups = "backups"
numLoad = "loads"
numLoadAborted = "loads_aborted"
numBoot = "boot"
numAuthOK = "authOK"
numAuthFail = "authFail"
// Default timeout for cluster communications.
defaultTimeout = 30 * time.Second
// VersionHTTPHeader is the HTTP header key for the version.
VersionHTTPHeader = "X-RQLITE-VERSION"
// ServedByHTTPHeader is the HTTP header used to report which
// node (by node Raft address) actually served the request if
// it wasn't served by this node.
ServedByHTTPHeader = "X-RQLITE-SERVED-BY"
// AllowOriginHeader is the HTTP header for allowing CORS compliant access from certain origins
AllowOriginHeader = "Access-Control-Allow-Origin"
// AllowMethodsHeader is the HTTP header for supporting the correct methods
AllowMethodsHeader = "Access-Control-Allow-Methods"
// AllowHeadersHeader is the HTTP header for supporting the correct request headers
AllowHeadersHeader = "Access-Control-Allow-Headers"
// AllowCredentialsHeader is the HTTP header for supporting specifying credentials
AllowCredentialsHeader = "Access-Control-Allow-Credentials"
)
func init() {
stats = expvar.NewMap("http")
ResetStats()
}
// ResetStats resets the expvar stats for this module. Mostly for test purposes.
func ResetStats() {
stats.Init()
stats.Add(numLeaderNotFound, 0)
stats.Add(numExecutions, 0)
stats.Add(numExecuteStmtsRx, 0)
stats.Add(numQueuedExecutions, 0)
stats.Add(numQueuedExecutionsOK, 0)
stats.Add(numQueuedExecutionsStmtsRx, 0)
stats.Add(numQueuedExecutionsStmtsTx, 0)
stats.Add(numQueuedExecutionsNoLeader, 0)
stats.Add(numQueuedExecutionsNotLeader, 0)
stats.Add(numQueuedExecutionsLeadershipLost, 0)
stats.Add(numQueuedExecutionsUnknownError, 0)
stats.Add(numQueuedExecutionsFailed, 0)
stats.Add(numQueuedExecutionsWait, 0)
stats.Add(numQueries, 0)
stats.Add(numQueryStmtsRx, 0)
stats.Add(numRequests, 0)
stats.Add(numRequestStmtsRx, 0)
stats.Add(numRemoteExecutions, 0)
stats.Add(numRemoteExecutionsFailed, 0)
stats.Add(numRemoteQueries, 0)
stats.Add(numRemoteQueriesFailed, 0)
stats.Add(numRemoteRequests, 0)
stats.Add(numRemoteRequestsFailed, 0)
stats.Add(numRemoteBackups, 0)
stats.Add(numRemoteLoads, 0)
stats.Add(numRemoteRemoveNode, 0)
stats.Add(numReadyz, 0)
stats.Add(numStatus, 0)
stats.Add(numBackups, 0)
stats.Add(numLoad, 0)
stats.Add(numLoadAborted, 0)
stats.Add(numBoot, 0)
stats.Add(numAuthOK, 0)
stats.Add(numAuthFail, 0)
}
// Service provides HTTP service.
type Service struct {
httpServer http.Server
closeCh chan struct{}
addr string // Bind address of the HTTP service.
ln net.Listener // Service listener
store Store // The Raft-backed database store.
queueDone chan struct{}
stmtQueue *queue.Queue[*command.Statement] // Queue for queued executes
cluster Cluster // The Cluster service.
start time.Time // Start up time.
lastBackup time.Time // Time of last successful backup.
statusMu sync.RWMutex
statuses map[string]StatusReporter
CACertFile string // Path to x509 CA certificate used to verify certificates.
CertFile string // Path to server's own x509 certificate.
KeyFile string // Path to server's own x509 private key.
ClientVerify bool // Whether client certificates should verified.
tlsConfig *tls.Config
aoMu sync.RWMutex
allowOrigin string // Value to set for Access-Control-Allow-Origin
DefaultQueueCap int
DefaultQueueBatchSz int
DefaultQueueTimeout time.Duration
DefaultQueueTx bool
seqNum int64 // Last sequence number written OK.
credentialStore CredentialStore
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, cluster Cluster, credentials CredentialStore) *Service {
return &Service{
addr: addr,
store: store,
DefaultQueueCap: 1024,
DefaultQueueBatchSz: 128,
DefaultQueueTimeout: 100 * time.Millisecond,
cluster: cluster,
start: time.Now(),
statuses: make(map[string]StatusReporter),
credentialStore: credentials,
logger: log.New(os.Stderr, "[http] ", log.LstdFlags),
}
}
// Start starts the service.
func (s *Service) Start() error {
s.httpServer = 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 {
mTLSState := rtls.MTLSStateDisabled
if s.ClientVerify {
mTLSState = rtls.MTLSStateEnabled
}
s.tlsConfig, err = rtls.CreateServerConfig(s.CertFile, s.KeyFile, s.CACertFile, mTLSState)
if err != nil {
return err
}
ln, err = tls.Listen("tcp", s.addr, s.tlsConfig)
if err != nil {
return err
}
var b strings.Builder
b.WriteString(fmt.Sprintf("secure HTTPS server enabled with cert %s, key %s", s.CertFile, s.KeyFile))
if s.CACertFile != "" {
b.WriteString(fmt.Sprintf(", CA cert %s", s.CACertFile))
}
if s.ClientVerify {
b.WriteString(", mutual TLS enabled")
} else {
b.WriteString(", mutual TLS disabled")
}
// print the message
s.logger.Println(b.String())
}
s.ln = ln
s.closeCh = make(chan struct{})
s.queueDone = make(chan struct{})
s.stmtQueue = queue.New[*command.Statement](s.DefaultQueueCap, s.DefaultQueueBatchSz, s.DefaultQueueTimeout)
go s.runQueue()
s.logger.Printf("execute queue processing started with capacity %d, batch size %d, timeout %s",
s.DefaultQueueCap, s.DefaultQueueBatchSz, s.DefaultQueueTimeout.String())
go func() {
err := s.httpServer.Serve(s.ln)
if err != nil {
s.logger.Printf("HTTP service on %s stopped: %s", s.ln.Addr().String(), err.Error())
}
}()
s.logger.Println("service listening on", s.Addr())
return nil
}
// Close closes the service.
func (s *Service) Close() {
s.logger.Println("closing HTTP service on", s.ln.Addr().String())
s.httpServer.Shutdown(context.Background())
s.stmtQueue.Close()
select {
case <-s.queueDone:
default:
close(s.closeCh)
}
<-s.queueDone
s.ln.Close()
}
// HTTPS returns whether this service is using HTTPS.
func (s *Service) HTTPS() bool {
return s.CertFile != "" && s.KeyFile != ""
}
// SetAllowOrigin sets the value for the Access-Control-Allow-Origin header.
func (s *Service) SetAllowOrigin(origin string) {
s.aoMu.Lock()
defer s.aoMu.Unlock()
s.allowOrigin = origin
}
// AllowOrigin returns the value for the Access-Control-Allow-Origin header.
func (s *Service) AllowOrigin() string {
s.aoMu.RLock()
defer s.aoMu.RUnlock()
return s.allowOrigin
}
// ServeHTTP allows Service to serve HTTP requests.
func (s *Service) ServeHTTP(w http.ResponseWriter, r *http.Request) {
s.addBuildVersion(w)
s.addAllowHeaders(w)
if r.Method == http.MethodOptions {
w.WriteHeader(http.StatusOK)
return
}
params, err := NewQueryParams(r)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
switch {
case r.URL.Path == "/" || r.URL.Path == "":
http.Redirect(w, r, "/status", http.StatusFound)
case strings.HasPrefix(r.URL.Path, "/db/execute"):
stats.Add(numExecutions, 1)
s.handleExecute(w, r, params)
case strings.HasPrefix(r.URL.Path, "/db/query"):
stats.Add(numQueries, 1)
s.handleQuery(w, r, params)
case strings.HasPrefix(r.URL.Path, "/db/request"):
stats.Add(numRequests, 1)
s.handleRequest(w, r, params)
case strings.HasPrefix(r.URL.Path, "/db/backup"):
stats.Add(numBackups, 1)
s.handleBackup(w, r, params)
case strings.HasPrefix(r.URL.Path, "/db/load"):
stats.Add(numLoad, 1)
s.handleLoad(w, r, params)
case r.URL.Path == "/boot":
stats.Add(numBoot, 1)
s.handleBoot(w, r)
case strings.HasPrefix(r.URL.Path, "/remove"):
s.handleRemove(w, r, params)
case strings.HasPrefix(r.URL.Path, "/status"):
stats.Add(numStatus, 1)
s.handleStatus(w, r, params)
case strings.HasPrefix(r.URL.Path, "/nodes"):
s.handleNodes(w, r, params)
case strings.HasPrefix(r.URL.Path, "/readyz"):
stats.Add(numReadyz, 1)
s.handleReadyz(w, r, params)
case r.URL.Path == "/debug/vars":
s.handleExpvar(w, r, params)
case strings.HasPrefix(r.URL.Path, "/debug/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 StatusReporter) 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
}
// handleRemove handles cluster-remove requests.
func (s *Service) handleRemove(w http.ResponseWriter, r *http.Request, qp QueryParams) {
if !s.CheckRequestPerm(r, auth.PermRemove) {
w.WriteHeader(http.StatusUnauthorized)
return
}
if r.Method != "DELETE" {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
b, err := io.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
}
remoteID, ok := m["id"]
if !ok {
w.WriteHeader(http.StatusBadRequest)
return
}
rn := &proto.RemoveNodeRequest{
Id: remoteID,
}
err = s.store.Remove(rn)
if err != nil {
if err == store.ErrNotLeader {
if s.DoRedirect(w, r, qp) {
return
}
addr, err := s.store.LeaderAddr()
if err != nil {
http.Error(w, fmt.Sprintf("leader address: %s", err.Error()),
http.StatusInternalServerError)
return
}
if addr == "" {
stats.Add(numLeaderNotFound, 1)
http.Error(w, ErrLeaderNotFound.Error(), http.StatusServiceUnavailable)
return
}
username, password, ok := r.BasicAuth()
if !ok {
username = ""
}
w.Header().Add(ServedByHTTPHeader, addr)
removeErr := s.cluster.RemoveNode(rn, addr, makeCredentials(username, password), qp.Timeout(defaultTimeout))
if removeErr != nil {
if removeErr.Error() == "unauthorized" {
http.Error(w, "remote remove node not authorized", http.StatusUnauthorized)
} else {
http.Error(w, removeErr.Error(), http.StatusInternalServerError)
}
return
}
stats.Add(numRemoteRemoveNode, 1)
return
}
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
// handleBackup returns the consistent database snapshot.
func (s *Service) handleBackup(w http.ResponseWriter, r *http.Request, qp QueryParams) {
if !s.CheckRequestPerm(r, auth.PermBackup) {
w.WriteHeader(http.StatusUnauthorized)
return
}
if r.Method != "GET" {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
br := &proto.BackupRequest{
Format: qp.BackupFormat(),
Leader: !qp.NoLeader(),
Vacuum: qp.Vacuum(),
Compress: qp.Compress(),
}
addBackupFormatHeader(w, qp)
err := s.store.Backup(br, w)
if err != nil {
if err == store.ErrNotLeader {
if s.DoRedirect(w, r, qp) {
return
}
addr, err := s.store.LeaderAddr()
if err != nil {
http.Error(w, fmt.Sprintf("leader address: %s", err.Error()),
http.StatusInternalServerError)
return
}
if addr == "" {
stats.Add(numLeaderNotFound, 1)
http.Error(w, ErrLeaderNotFound.Error(), http.StatusServiceUnavailable)
return
}
username, password, ok := r.BasicAuth()
if !ok {
username = ""
}
w.Header().Add(ServedByHTTPHeader, addr)
backupErr := s.cluster.Backup(br, addr, makeCredentials(username, password), qp.Timeout(defaultTimeout), w)
if backupErr != nil {
if backupErr.Error() == "unauthorized" {
http.Error(w, "remote backup not authorized", http.StatusUnauthorized)
} else {
http.Error(w, backupErr.Error(), http.StatusInternalServerError)
}
return
}
stats.Add(numRemoteBackups, 1)
return
} else if err == store.ErrInvalidVacuum {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
s.lastBackup = time.Now()
}
// handleLoad loads the database from the given SQLite database file or SQLite dump.
func (s *Service) handleLoad(w http.ResponseWriter, r *http.Request, qp QueryParams) {
if !s.CheckRequestPerm(r, auth.PermLoad) {
w.WriteHeader(http.StatusUnauthorized)
return
}
if r.Method != "POST" {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
resp := NewResponse()
b, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
r.Body.Close()
if db.IsValidSQLiteData(b) {
s.logger.Printf("SQLite database file detected as load data")
lr := &proto.LoadRequest{
Data: b,
}
err := s.store.Load(lr)
if err != nil && err != store.ErrNotLeader {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
} else if err != nil && err == store.ErrNotLeader {
if s.DoRedirect(w, r, qp) {
return
}
addr, err := s.store.LeaderAddr()
if err != nil {
http.Error(w, fmt.Sprintf("leader address: %s", err.Error()),
http.StatusInternalServerError)
return
}
if addr == "" {
stats.Add(numLeaderNotFound, 1)
http.Error(w, ErrLeaderNotFound.Error(), http.StatusServiceUnavailable)
return
}
username, password, ok := r.BasicAuth()
if !ok {
username = ""
}
w.Header().Add(ServedByHTTPHeader, addr)
loadErr := s.cluster.Load(lr, addr, makeCredentials(username, password),
qp.Timeout(defaultTimeout), qp.Retries(0))
if loadErr != nil {
if loadErr.Error() == "unauthorized" {
http.Error(w, "remote load not authorized", http.StatusUnauthorized)
} else {
http.Error(w, loadErr.Error(), http.StatusInternalServerError)
}
return
}
stats.Add(numRemoteLoads, 1)
// Allow this if block to exit, so response remains as before request
// forwarding was put in place.
}
} else {
// No JSON structure expected for this API.
queries := []string{string(b)}
er := executeRequestFromStrings(queries, qp.Timings(), false)
response, err := s.store.Execute(er)
if err != nil {
if err == store.ErrNotLeader {
if s.DoRedirect(w, r, qp) {
return
}
}
resp.Error = err.Error()
} else {
resp.Results.ExecuteQueryResponse = response
}
resp.end = time.Now()
}
s.writeResponse(w, qp, resp)
}
// handleBoot handles booting this node using a SQLite file.
func (s *Service) handleBoot(w http.ResponseWriter, r *http.Request) {
if !s.CheckRequestPerm(r, auth.PermLoad) {
w.WriteHeader(http.StatusUnauthorized)
return
}
if r.Method != "POST" {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
bufReader := bufio.NewReader(r.Body)
peek, err := bufReader.Peek(db.SQLiteHeaderSize)
if err != nil {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return
}
if !db.IsValidSQLiteData(peek) {
http.Error(w, "invalid SQLite data", http.StatusBadRequest)
return
}
s.logger.Printf("starting boot process")
_, err = s.store.ReadFrom(bufReader)
if err != nil {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return
}
}
// handleStatus returns status on the system.
func (s *Service) handleStatus(w http.ResponseWriter, r *http.Request, qp QueryParams) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
if !s.CheckRequestPerm(r, auth.PermStatus) {
w.WriteHeader(http.StatusUnauthorized)
return
}
if r.Method != "GET" {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
storeStatus, err := s.store.Stats()
if err != nil {
http.Error(w, fmt.Sprintf("store stats: %s", err.Error()),
http.StatusInternalServerError)
return
}
clusterStatus, err := s.cluster.Stats()
if err != nil {
http.Error(w, fmt.Sprintf("cluster stats: %s", err.Error()),
http.StatusInternalServerError)
return
}
rt := map[string]interface{}{
"GOARCH": runtime.GOARCH,
"GOOS": runtime.GOOS,
"GOMAXPROCS": runtime.GOMAXPROCS(0),
"num_cpu": runtime.NumCPU(),
"num_goroutine": runtime.NumGoroutine(),
"version": runtime.Version(),
}
oss := map[string]interface{}{
"pid": os.Getpid(),
"ppid": os.Getppid(),
"page_size": os.Getpagesize(),
}
executable, err := os.Executable()
if err == nil {
oss["executable"] = executable
}
hostname, err := os.Hostname()
if err == nil {
oss["hostname"] = hostname
}
qs, err := s.stmtQueue.Stats()
if err != nil {
http.Error(w, fmt.Sprintf("queue stats: %s", err.Error()),
http.StatusInternalServerError)
return
}
qs["sequence_number"] = atomic.LoadInt64(&s.seqNum)
queueStats := map[string]interface{}{
"_default": qs,
}
httpStatus := map[string]interface{}{
"bind_addr": s.Addr().String(),
"auth": prettyEnabled(s.credentialStore != nil),
"cluster": clusterStatus,
"queue": queueStats,
"tls": s.tlsStats(),
}
ao := s.AllowOrigin()
if ao != "" {
httpStatus["allow_origin"] = ao
}
nodeStatus := map[string]interface{}{
"start_time": s.start,
"current_time": time.Now(),
"uptime": time.Since(s.start).String(),
}
// Build the status response.
status := map[string]interface{}{
"os": oss,
"runtime": rt,
"store": storeStatus,
"http": httpStatus,
"node": nodeStatus,
}
if !s.lastBackup.IsZero() {
status["last_backup_time"] = s.lastBackup
}
if s.BuildInfo != nil {
status["build"] = s.BuildInfo
}
// Add any registered StatusReporters.
func() {
s.statusMu.RLock()
defer s.statusMu.RUnlock()
for k, v := range s.statuses {
stat, err := v.Stats()
if err != nil {
http.Error(w, fmt.Sprintf("registered stats: %s", err.Error()),
http.StatusInternalServerError)
return
}
status[k] = stat
}
}()
var b []byte
if qp.Pretty() {
b, err = json.MarshalIndent(status, "", " ")
} else {
b, err = json.Marshal(status)
}
if err != nil {
http.Error(w, fmt.Sprintf("JSON marshal: %s", err.Error()),
http.StatusInternalServerError)
return
}
b, err = getSubJSON(b, qp.Key())
if err != nil {
http.Error(w, fmt.Sprintf("JSON subkey: %s", err.Error()),
http.StatusInternalServerError)
return
}
_, err = w.Write(b)
if err != nil {
s.logger.Println("failed to write status to client", err.Error())
return
}
}
// handleNodes returns status on the other voting nodes in the system.
// This attempts to contact all the nodes in the cluster, so may take
// some time to return.
func (s *Service) handleNodes(w http.ResponseWriter, r *http.Request, qp QueryParams) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
if !s.CheckRequestPerm(r, auth.PermStatus) {
w.WriteHeader(http.StatusUnauthorized)
return
}
if r.Method != "GET" {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
// Get nodes in the cluster, and possibly filter out non-voters.
sNodes, err := s.store.Nodes()
if err != nil {
statusCode := http.StatusInternalServerError
if err == store.ErrNotOpen {
statusCode = http.StatusServiceUnavailable
}
http.Error(w, fmt.Sprintf("store nodes: %s", err.Error()), statusCode)
return
}
nodes := NewNodesFromServers(sNodes)
if !qp.NonVoters() {
nodes = nodes.Voters()
}
// Now test the nodes
lAddr, err := s.store.LeaderAddr()
if err != nil {
http.Error(w, fmt.Sprintf("leader address: %s", err.Error()),
http.StatusInternalServerError)
return
}
nodes.Test(s.cluster, lAddr, qp.Retries(0), qp.Timeout(defaultTimeout))
enc := NewNodesRespEncoder(w, qp.Version() != "2")
if qp.Pretty() {
enc.SetIndent("", " ")
}
err = enc.Encode(nodes)
if err != nil {
http.Error(w, fmt.Sprintf("JSON marshal: %s", err.Error()),
http.StatusInternalServerError)
}
}
// handleReadyz returns whether the node is ready.
func (s *Service) handleReadyz(w http.ResponseWriter, r *http.Request, qp QueryParams) {
if !s.CheckRequestPerm(r, auth.PermReady) {
w.WriteHeader(http.StatusUnauthorized)
return
}
if r.Method != "GET" {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
if qp.NoLeader() {
// Simply handling the HTTP request is enough.
w.WriteHeader(http.StatusOK)
w.Write([]byte("[+]node ok"))
return
}
lAddr, err := s.store.LeaderAddr()