-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
infrastructure.go
1722 lines (1499 loc) · 50.6 KB
/
infrastructure.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
// Copyright (c) 2014-2017 The btcsuite developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package rpcclient
import (
"bytes"
"container/list"
"crypto/tls"
"crypto/x509"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"math"
"net"
"net/http"
"net/url"
"os"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/btcsuite/btcd/btcjson"
"github.com/btcsuite/btcd/chaincfg"
"github.com/btcsuite/go-socks/socks"
"github.com/btcsuite/websocket"
)
var (
// ErrInvalidAuth is an error to describe the condition where the client
// is either unable to authenticate or the specified endpoint is
// incorrect.
ErrInvalidAuth = errors.New("authentication failure")
// ErrInvalidEndpoint is an error to describe the condition where the
// websocket handshake failed with the specified endpoint.
ErrInvalidEndpoint = errors.New("the endpoint either does not support " +
"websockets or does not exist")
// ErrClientNotConnected is an error to describe the condition where a
// websocket client has been created, but the connection was never
// established. This condition differs from ErrClientDisconnect, which
// represents an established connection that was lost.
ErrClientNotConnected = errors.New("the client was never connected")
// ErrClientDisconnect is an error to describe the condition where the
// client has been disconnected from the RPC server. When the
// DisableAutoReconnect option is not set, any outstanding futures
// when a client disconnect occurs will return this error as will
// any new requests.
ErrClientDisconnect = errors.New("the client has been disconnected")
// ErrClientShutdown is an error to describe the condition where the
// client is either already shutdown, or in the process of shutting
// down. Any outstanding futures when a client shutdown occurs will
// return this error as will any new requests.
ErrClientShutdown = errors.New("the client has been shutdown")
// ErrNotWebsocketClient is an error to describe the condition of
// calling a Client method intended for a websocket client when the
// client has been configured to run in HTTP POST mode instead.
ErrNotWebsocketClient = errors.New("client is not configured for " +
"websockets")
// ErrClientAlreadyConnected is an error to describe the condition where
// a new client connection cannot be established due to a websocket
// client having already connected to the RPC server.
ErrClientAlreadyConnected = errors.New("websocket client has already " +
"connected")
)
const (
// sendBufferSize is the number of elements the websocket send channel
// can queue before blocking.
sendBufferSize = 50
// sendPostBufferSize is the number of elements the HTTP POST send
// channel can queue before blocking.
sendPostBufferSize = 100
// connectionRetryInterval is the amount of time to wait in between
// retries when automatically reconnecting to an RPC server.
connectionRetryInterval = time.Second * 5
// requestRetryInterval is the initial amount of time to wait in between
// retries when sending HTTP POST requests.
requestRetryInterval = time.Millisecond * 500
)
// jsonRequest holds information about a json request that is used to properly
// detect, interpret, and deliver a reply to it.
type jsonRequest struct {
id uint64
method string
cmd interface{}
marshalledJSON []byte
responseChan chan *Response
}
// BackendVersion represents the version of the backend the client is currently
// connected to.
type BackendVersion uint8
const (
// BitcoindPre19 represents a bitcoind version before 0.19.0.
BitcoindPre19 BackendVersion = iota
// BitcoindPost19 represents a bitcoind version equal to or greater than
// 0.19.0.
BitcoindPost19
// Btcd represents a catch-all btcd version.
Btcd
)
// Client represents a Bitcoin RPC client which allows easy access to the
// various RPC methods available on a Bitcoin RPC server. Each of the wrapper
// functions handle the details of converting the passed and return types to and
// from the underlying JSON types which are required for the JSON-RPC
// invocations
//
// The client provides each RPC in both synchronous (blocking) and asynchronous
// (non-blocking) forms. The asynchronous forms are based on the concept of
// futures where they return an instance of a type that promises to deliver the
// result of the invocation at some future time. Invoking the Receive method on
// the returned future will block until the result is available if it's not
// already.
type Client struct {
id uint64 // atomic, so must stay 64-bit aligned
// config holds the connection configuration assoiated with this client.
config *ConnConfig
// chainParams holds the params for the chain that this client is using,
// and is used for many wallet methods.
chainParams *chaincfg.Params
// wsConn is the underlying websocket connection when not in HTTP POST
// mode.
wsConn *websocket.Conn
// httpClient is the underlying HTTP client to use when running in HTTP
// POST mode.
httpClient *http.Client
// backendVersion is the version of the backend the client is currently
// connected to. This should be retrieved through GetVersion.
backendVersionMu sync.Mutex
backendVersion *BackendVersion
// mtx is a mutex to protect access to connection related fields.
mtx sync.Mutex
// disconnected indicated whether or not the server is disconnected.
disconnected bool
// whether or not to batch requests, false unless changed by Batch()
batch bool
batchList *list.List
// retryCount holds the number of times the client has tried to
// reconnect to the RPC server.
retryCount int64
// Track command and their response channels by ID.
requestLock sync.Mutex
requestMap map[uint64]*list.Element
requestList *list.List
// Notifications.
ntfnHandlers *NotificationHandlers
ntfnStateLock sync.Mutex
ntfnState *notificationState
// Networking infrastructure.
sendChan chan []byte
sendPostChan chan *jsonRequest
connEstablished chan struct{}
disconnect chan struct{}
shutdown chan struct{}
wg sync.WaitGroup
}
// NextID returns the next id to be used when sending a JSON-RPC message. This
// ID allows responses to be associated with particular requests per the
// JSON-RPC specification. Typically the consumer of the client does not need
// to call this function, however, if a custom request is being created and used
// this function should be used to ensure the ID is unique amongst all requests
// being made.
func (c *Client) NextID() uint64 {
return atomic.AddUint64(&c.id, 1)
}
// addRequest associates the passed jsonRequest with its id. This allows the
// response from the remote server to be unmarshalled to the appropriate type
// and sent to the specified channel when it is received.
//
// If the client has already begun shutting down, ErrClientShutdown is returned
// and the request is not added.
//
// This function is safe for concurrent access.
func (c *Client) addRequest(jReq *jsonRequest) error {
c.requestLock.Lock()
defer c.requestLock.Unlock()
// A non-blocking read of the shutdown channel with the request lock
// held avoids adding the request to the client's internal data
// structures if the client is in the process of shutting down (and
// has not yet grabbed the request lock), or has finished shutdown
// already (responding to each outstanding request with
// ErrClientShutdown).
select {
case <-c.shutdown:
return ErrClientShutdown
default:
}
if !c.batch {
element := c.requestList.PushBack(jReq)
c.requestMap[jReq.id] = element
} else {
element := c.batchList.PushBack(jReq)
c.requestMap[jReq.id] = element
}
return nil
}
// removeRequest returns and removes the jsonRequest which contains the response
// channel and original method associated with the passed id or nil if there is
// no association.
//
// This function is safe for concurrent access.
func (c *Client) removeRequest(id uint64) *jsonRequest {
c.requestLock.Lock()
defer c.requestLock.Unlock()
element := c.requestMap[id]
if element != nil {
delete(c.requestMap, id)
request := c.requestList.Remove(element).(*jsonRequest)
return request
}
return nil
}
// removeAllRequests removes all the jsonRequests which contain the response
// channels for outstanding requests.
//
// This function MUST be called with the request lock held.
func (c *Client) removeAllRequests() {
c.requestMap = make(map[uint64]*list.Element)
c.requestList.Init()
}
// trackRegisteredNtfns examines the passed command to see if it is one of
// the notification commands and updates the notification state that is used
// to automatically re-establish registered notifications on reconnects.
func (c *Client) trackRegisteredNtfns(cmd interface{}) {
// Nothing to do if the caller is not interested in notifications.
if c.ntfnHandlers == nil {
return
}
c.ntfnStateLock.Lock()
defer c.ntfnStateLock.Unlock()
switch bcmd := cmd.(type) {
case *btcjson.NotifyBlocksCmd:
c.ntfnState.notifyBlocks = true
case *btcjson.NotifyNewTransactionsCmd:
if bcmd.Verbose != nil && *bcmd.Verbose {
c.ntfnState.notifyNewTxVerbose = true
} else {
c.ntfnState.notifyNewTx = true
}
case *btcjson.NotifySpentCmd:
for _, op := range bcmd.OutPoints {
c.ntfnState.notifySpent[op] = struct{}{}
}
case *btcjson.NotifyReceivedCmd:
for _, addr := range bcmd.Addresses {
c.ntfnState.notifyReceived[addr] = struct{}{}
}
}
}
// FutureGetBulkResult waits for the responses promised by the future
// and returns them in a channel
type FutureGetBulkResult chan *Response
// Receive waits for the response promised by the future and returns an map
// of results by request id
func (r FutureGetBulkResult) Receive() (BulkResult, error) {
m := make(BulkResult)
res, err := ReceiveFuture(r)
if err != nil {
return nil, err
}
var arr []IndividualBulkResult
err = json.Unmarshal(res, &arr)
if err != nil {
return nil, err
}
for _, results := range arr {
m[results.Id] = results
}
return m, nil
}
// IndividualBulkResult represents one result
// from a bulk json rpc api
type IndividualBulkResult struct {
Result interface{} `json:"result"`
Error *btcjson.RPCError `json:"error"`
Id uint64 `json:"id"`
}
type BulkResult = map[uint64]IndividualBulkResult
// inMessage is the first type that an incoming message is unmarshaled
// into. It supports both requests (for notification support) and
// responses. The partially-unmarshaled message is a notification if
// the embedded ID (from the response) is nil. Otherwise, it is a
// response.
type inMessage struct {
ID *float64 `json:"id"`
*rawNotification
*rawResponse
}
// rawNotification is a partially-unmarshaled JSON-RPC notification.
type rawNotification struct {
Method string `json:"method"`
Params []json.RawMessage `json:"params"`
}
// rawResponse is a partially-unmarshaled JSON-RPC response. For this
// to be valid (according to JSON-RPC 1.0 spec), ID may not be nil.
type rawResponse struct {
Result json.RawMessage `json:"result"`
Error *btcjson.RPCError `json:"error"`
}
// Response is the raw bytes of a JSON-RPC result, or the error if the response
// error object was non-null.
type Response struct {
result []byte
err error
}
// result checks whether the unmarshaled response contains a non-nil error,
// returning an unmarshaled btcjson.RPCError (or an unmarshaling error) if so.
// If the response is not an error, the raw bytes of the request are
// returned for further unmashaling into specific result types.
func (r rawResponse) result() (result []byte, err error) {
if r.Error != nil {
return nil, r.Error
}
return r.Result, nil
}
// handleMessage is the main handler for incoming notifications and responses.
func (c *Client) handleMessage(msg []byte) {
// Attempt to unmarshal the message as either a notification or
// response.
var in inMessage
in.rawResponse = new(rawResponse)
in.rawNotification = new(rawNotification)
err := json.Unmarshal(msg, &in)
if err != nil {
log.Warnf("Remote server sent invalid message: %v", err)
return
}
// JSON-RPC 1.0 notifications are requests with a null id.
if in.ID == nil {
ntfn := in.rawNotification
if ntfn == nil {
log.Warn("Malformed notification: missing " +
"method and parameters")
return
}
if ntfn.Method == "" {
log.Warn("Malformed notification: missing method")
return
}
// params are not optional: nil isn't valid (but len == 0 is)
if ntfn.Params == nil {
log.Warn("Malformed notification: missing params")
return
}
// Deliver the notification.
log.Tracef("Received notification [%s]", in.Method)
c.handleNotification(in.rawNotification)
return
}
// ensure that in.ID can be converted to an integer without loss of precision
if *in.ID < 0 || *in.ID != math.Trunc(*in.ID) {
log.Warn("Malformed response: invalid identifier")
return
}
if in.rawResponse == nil {
log.Warn("Malformed response: missing result and error")
return
}
id := uint64(*in.ID)
log.Tracef("Received response for id %d (result %s)", id, in.Result)
request := c.removeRequest(id)
// Nothing more to do if there is no request associated with this reply.
if request == nil || request.responseChan == nil {
log.Warnf("Received unexpected reply: %s (id %d)", in.Result,
id)
return
}
// Since the command was successful, examine it to see if it's a
// notification, and if is, add it to the notification state so it
// can automatically be re-established on reconnect.
c.trackRegisteredNtfns(request.cmd)
// Deliver the response.
result, err := in.rawResponse.result()
request.responseChan <- &Response{result: result, err: err}
}
// shouldLogReadError returns whether or not the passed error, which is expected
// to have come from reading from the websocket connection in wsInHandler,
// should be logged.
func (c *Client) shouldLogReadError(err error) bool {
// No logging when the connetion is being forcibly disconnected.
select {
case <-c.shutdown:
return false
default:
}
// No logging when the connection has been disconnected.
if err == io.EOF {
return false
}
if opErr, ok := err.(*net.OpError); ok && !opErr.Temporary() {
return false
}
return true
}
// wsInHandler handles all incoming messages for the websocket connection
// associated with the client. It must be run as a goroutine.
func (c *Client) wsInHandler() {
out:
for {
// Break out of the loop once the shutdown channel has been
// closed. Use a non-blocking select here so we fall through
// otherwise.
select {
case <-c.shutdown:
break out
default:
}
_, msg, err := c.wsConn.ReadMessage()
if err != nil {
// Log the error if it's not due to disconnecting.
if c.shouldLogReadError(err) {
log.Errorf("Websocket receive error from "+
"%s: %v", c.config.Host, err)
}
break out
}
c.handleMessage(msg)
}
// Ensure the connection is closed.
c.Disconnect()
c.wg.Done()
log.Tracef("RPC client input handler done for %s", c.config.Host)
}
// disconnectChan returns a copy of the current disconnect channel. The channel
// is read protected by the client mutex, and is safe to call while the channel
// is being reassigned during a reconnect.
func (c *Client) disconnectChan() <-chan struct{} {
c.mtx.Lock()
ch := c.disconnect
c.mtx.Unlock()
return ch
}
// wsOutHandler handles all outgoing messages for the websocket connection. It
// uses a buffered channel to serialize output messages while allowing the
// sender to continue running asynchronously. It must be run as a goroutine.
func (c *Client) wsOutHandler() {
out:
for {
// Send any messages ready for send until the client is
// disconnected closed.
select {
case msg := <-c.sendChan:
err := c.wsConn.WriteMessage(websocket.TextMessage, msg)
if err != nil {
c.Disconnect()
break out
}
case <-c.disconnectChan():
break out
}
}
// Drain any channels before exiting so nothing is left waiting around
// to send.
cleanup:
for {
select {
case <-c.sendChan:
default:
break cleanup
}
}
c.wg.Done()
log.Tracef("RPC client output handler done for %s", c.config.Host)
}
// sendMessage sends the passed JSON to the connected server using the
// websocket connection. It is backed by a buffered channel, so it will not
// block until the send channel is full.
func (c *Client) sendMessage(marshalledJSON []byte) {
// Don't send the message if disconnected.
select {
case c.sendChan <- marshalledJSON:
case <-c.disconnectChan():
return
}
}
// reregisterNtfns creates and sends commands needed to re-establish the current
// notification state associated with the client. It should only be called on
// on reconnect by the resendRequests function.
func (c *Client) reregisterNtfns() error {
// Nothing to do if the caller is not interested in notifications.
if c.ntfnHandlers == nil {
return nil
}
// In order to avoid holding the lock on the notification state for the
// entire time of the potentially long running RPCs issued below, make a
// copy of it and work from that.
//
// Also, other commands will be running concurrently which could modify
// the notification state (while not under the lock of course) which
// also register it with the remote RPC server, so this prevents double
// registrations.
c.ntfnStateLock.Lock()
stateCopy := c.ntfnState.Copy()
c.ntfnStateLock.Unlock()
// Reregister notifyblocks if needed.
if stateCopy.notifyBlocks {
log.Debugf("Reregistering [notifyblocks]")
if err := c.NotifyBlocks(); err != nil {
return err
}
}
// Reregister notifynewtransactions if needed.
if stateCopy.notifyNewTx || stateCopy.notifyNewTxVerbose {
log.Debugf("Reregistering [notifynewtransactions] (verbose=%v)",
stateCopy.notifyNewTxVerbose)
err := c.NotifyNewTransactions(stateCopy.notifyNewTxVerbose)
if err != nil {
return err
}
}
// Reregister the combination of all previously registered notifyspent
// outpoints in one command if needed.
nslen := len(stateCopy.notifySpent)
if nslen > 0 {
outpoints := make([]btcjson.OutPoint, 0, nslen)
for op := range stateCopy.notifySpent {
outpoints = append(outpoints, op)
}
log.Debugf("Reregistering [notifyspent] outpoints: %v", outpoints)
if err := c.notifySpentInternal(outpoints).Receive(); err != nil {
return err
}
}
// Reregister the combination of all previously registered
// notifyreceived addresses in one command if needed.
nrlen := len(stateCopy.notifyReceived)
if nrlen > 0 {
addresses := make([]string, 0, nrlen)
for addr := range stateCopy.notifyReceived {
addresses = append(addresses, addr)
}
log.Debugf("Reregistering [notifyreceived] addresses: %v", addresses)
if err := c.notifyReceivedInternal(addresses).Receive(); err != nil {
return err
}
}
return nil
}
// ignoreResends is a set of all methods for requests that are "long running"
// are not be reissued by the client on reconnect.
var ignoreResends = map[string]struct{}{
"rescan": {},
}
// resendRequests resends any requests that had not completed when the client
// disconnected. It is intended to be called once the client has reconnected as
// a separate goroutine.
func (c *Client) resendRequests() {
// Set the notification state back up. If anything goes wrong,
// disconnect the client.
if err := c.reregisterNtfns(); err != nil {
log.Warnf("Unable to re-establish notification state: %v", err)
c.Disconnect()
return
}
// Since it's possible to block on send and more requests might be
// added by the caller while resending, make a copy of all of the
// requests that need to be resent now and work from the copy. This
// also allows the lock to be released quickly.
c.requestLock.Lock()
resendReqs := make([]*jsonRequest, 0, c.requestList.Len())
var nextElem *list.Element
for e := c.requestList.Front(); e != nil; e = nextElem {
nextElem = e.Next()
jReq := e.Value.(*jsonRequest)
if _, ok := ignoreResends[jReq.method]; ok {
// If a request is not sent on reconnect, remove it
// from the request structures, since no reply is
// expected.
delete(c.requestMap, jReq.id)
c.requestList.Remove(e)
} else {
resendReqs = append(resendReqs, jReq)
}
}
c.requestLock.Unlock()
for _, jReq := range resendReqs {
// Stop resending commands if the client disconnected again
// since the next reconnect will handle them.
if c.Disconnected() {
return
}
log.Tracef("Sending command [%s] with id %d", jReq.method,
jReq.id)
c.sendMessage(jReq.marshalledJSON)
}
}
// wsReconnectHandler listens for client disconnects and automatically tries
// to reconnect with retry interval that scales based on the number of retries.
// It also resends any commands that had not completed when the client
// disconnected so the disconnect/reconnect process is largely transparent to
// the caller. This function is not run when the DisableAutoReconnect config
// options is set.
//
// This function must be run as a goroutine.
func (c *Client) wsReconnectHandler() {
out:
for {
select {
case <-c.disconnect:
// On disconnect, fallthrough to reestablish the
// connection.
case <-c.shutdown:
break out
}
reconnect:
for {
select {
case <-c.shutdown:
break out
default:
}
wsConn, err := dial(c.config)
if err != nil {
c.retryCount++
log.Infof("Failed to connect to %s: %v",
c.config.Host, err)
// Scale the retry interval by the number of
// retries so there is a backoff up to a max
// of 1 minute.
scaledInterval := connectionRetryInterval.Nanoseconds() * c.retryCount
scaledDuration := time.Duration(scaledInterval)
if scaledDuration > time.Minute {
scaledDuration = time.Minute
}
log.Infof("Retrying connection to %s in "+
"%s", c.config.Host, scaledDuration)
time.Sleep(scaledDuration)
continue reconnect
}
log.Infof("Reestablished connection to RPC server %s",
c.config.Host)
// Reset the version in case the backend was
// disconnected due to an upgrade.
c.backendVersionMu.Lock()
c.backendVersion = nil
c.backendVersionMu.Unlock()
// Reset the connection state and signal the reconnect
// has happened.
c.wsConn = wsConn
c.retryCount = 0
c.mtx.Lock()
c.disconnect = make(chan struct{})
c.disconnected = false
c.mtx.Unlock()
// Start processing input and output for the
// new connection.
c.start()
// Reissue pending requests in another goroutine since
// the send can block.
go c.resendRequests()
// Break out of the reconnect loop back to wait for
// disconnect again.
break reconnect
}
}
c.wg.Done()
log.Tracef("RPC client reconnect handler done for %s", c.config.Host)
}
// handleSendPostMessage handles performing the passed HTTP request, reading the
// result, unmarshalling it, and delivering the unmarshalled result to the
// provided response channel.
func (c *Client) handleSendPostMessage(jReq *jsonRequest,
shutdown chan struct{}) {
protocol := "http"
if !c.config.DisableTLS {
protocol = "https"
}
url := protocol + "://" + c.config.Host
var (
err, lastErr error
backoff time.Duration
httpResponse *http.Response
)
tries := 10
for i := 0; i < tries; i++ {
var httpReq *http.Request
bodyReader := bytes.NewReader(jReq.marshalledJSON)
httpReq, err = http.NewRequest("POST", url, bodyReader)
if err != nil {
jReq.responseChan <- &Response{result: nil, err: err}
return
}
httpReq.Close = true
httpReq.Header.Set("Content-Type", "application/json")
for key, value := range c.config.ExtraHeaders {
httpReq.Header.Set(key, value)
}
// Configure basic access authorization.
user, pass, err := c.config.getAuth()
if err != nil {
jReq.responseChan <- &Response{result: nil, err: err}
return
}
httpReq.SetBasicAuth(user, pass)
httpResponse, err = c.httpClient.Do(httpReq)
// Quit the retry loop on success or if we can't retry anymore.
if err == nil || i == tries-1 {
break
}
// Save the last error for the case where we backoff further,
// retry and get an invalid response but no error. If this
// happens the saved last error will be used to enrich the error
// message that we pass back to the caller.
lastErr = err
// Backoff sleep otherwise.
backoff = requestRetryInterval * time.Duration(i+1)
if backoff > time.Minute {
backoff = time.Minute
}
log.Debugf("Failed command [%s] with id %d attempt %d."+
" Retrying in %v... \n", jReq.method, jReq.id,
i, backoff)
select {
case <-time.After(backoff):
case <-shutdown:
return
}
}
if err != nil {
jReq.responseChan <- &Response{err: err}
return
}
// We still want to return an error if for any reason the respone
// remains empty.
if httpResponse == nil {
jReq.responseChan <- &Response{
err: fmt.Errorf("invalid http POST response (nil), "+
"method: %s, id: %d, last error=%v",
jReq.method, jReq.id, lastErr),
}
return
}
// Read the raw bytes and close the response.
respBytes, err := ioutil.ReadAll(httpResponse.Body)
httpResponse.Body.Close()
if err != nil {
err = fmt.Errorf("error reading json reply: %v", err)
jReq.responseChan <- &Response{err: err}
return
}
// Try to unmarshal the response as a regular JSON-RPC response.
var resp rawResponse
var batchResponse json.RawMessage
if c.batch {
err = json.Unmarshal(respBytes, &batchResponse)
} else {
err = json.Unmarshal(respBytes, &resp)
}
if err != nil {
// When the response itself isn't a valid JSON-RPC response
// return an error which includes the HTTP status code and raw
// response bytes.
err = fmt.Errorf("status code: %d, response: %q",
httpResponse.StatusCode, string(respBytes))
jReq.responseChan <- &Response{err: err}
return
}
var res []byte
if c.batch {
// errors must be dealt with downstream since a whole request cannot
// "error out" other than through the status code error handled above
res, err = batchResponse, nil
} else {
res, err = resp.result()
}
jReq.responseChan <- &Response{result: res, err: err}
}
// sendPostHandler handles all outgoing messages when the client is running
// in HTTP POST mode. It uses a buffered channel to serialize output messages
// while allowing the sender to continue running asynchronously. It must be run
// as a goroutine.
func (c *Client) sendPostHandler() {
out:
for {
// Send any messages ready for send until the shutdown channel
// is closed.
select {
case jReq := <-c.sendPostChan:
c.handleSendPostMessage(jReq, c.shutdown)
case <-c.shutdown:
break out
}
}
// Drain any wait channels before exiting so nothing is left waiting
// around to send.
cleanup:
for {
select {
case jReq := <-c.sendPostChan:
jReq.responseChan <- &Response{
result: nil,
err: ErrClientShutdown,
}
default:
break cleanup
}
}
c.wg.Done()
log.Tracef("RPC client send handler done for %s", c.config.Host)
}
// sendPostRequest sends the passed HTTP request to the RPC server using the
// HTTP client associated with the client. It is backed by a buffered channel,
// so it will not block until the send channel is full.
func (c *Client) sendPostRequest(jReq *jsonRequest) {
// Don't send the message if shutting down.
select {
case <-c.shutdown:
jReq.responseChan <- &Response{result: nil, err: ErrClientShutdown}
default:
}
log.Tracef("Sending command [%s] with id %d", jReq.method, jReq.id)
c.sendPostChan <- jReq
}
// newFutureError returns a new future result channel that already has the
// passed error waitin on the channel with the reply set to nil. This is useful
// to easily return errors from the various Async functions.
func newFutureError(err error) chan *Response {
responseChan := make(chan *Response, 1)
responseChan <- &Response{err: err}
return responseChan
}
// ReceiveFuture receives from the passed futureResult channel to extract a
// reply or any errors. The examined errors include an error in the
// futureResult and the error in the reply from the server. This will block
// until the result is available on the passed channel.
func ReceiveFuture(f chan *Response) ([]byte, error) {
// Wait for a response on the returned channel.
r := <-f
return r.result, r.err
}
// sendRequest sends the passed json request to the associated server using the
// provided response channel for the reply. It handles both websocket and HTTP
// POST mode depending on the configuration of the client.
func (c *Client) sendRequest(jReq *jsonRequest) {
// Choose which marshal and send function to use depending on whether
// the client running in HTTP POST mode or not. When running in HTTP
// POST mode, the command is issued via an HTTP client. Otherwise,
// the command is issued via the asynchronous websocket channels.
if c.config.HTTPPostMode {
if c.batch {
if err := c.addRequest(jReq); err != nil {
log.Warn(err)
}
} else {
c.sendPostRequest(jReq)
}
return
}
// Check whether the websocket connection has never been established,
// in which case the handler goroutines are not running.
select {
case <-c.connEstablished:
default:
jReq.responseChan <- &Response{err: ErrClientNotConnected}
return
}
// Add the request to the internal tracking map so the response from the
// remote server can be properly detected and routed to the response
// channel. Then send the marshalled request via the websocket
// connection.
if err := c.addRequest(jReq); err != nil {
jReq.responseChan <- &Response{err: err}
return
}
log.Tracef("Sending command [%s] with id %d", jReq.method, jReq.id)
c.sendMessage(jReq.marshalledJSON)
}
// SendCmd sends the passed command to the associated server and returns a
// response channel on which the reply will be delivered at some point in the
// future. It handles both websocket and HTTP POST mode depending on the