github.com/okex/exchain@v1.8.0/libs/tendermint/privval/signer_dialer_endpoint.go (about) 1 package privval 2 3 import ( 4 "time" 5 6 "github.com/okex/exchain/libs/tendermint/libs/log" 7 "github.com/okex/exchain/libs/tendermint/libs/service" 8 ) 9 10 const ( 11 defaultMaxDialRetries = 10 12 defaultRetryWaitMilliseconds = 100 13 ) 14 15 // SignerServiceEndpointOption sets an optional parameter on the SignerDialerEndpoint. 16 type SignerServiceEndpointOption func(*SignerDialerEndpoint) 17 18 // SignerDialerEndpointTimeoutReadWrite sets the read and write timeout for 19 // connections from client processes. 20 func SignerDialerEndpointTimeoutReadWrite(timeout time.Duration) SignerServiceEndpointOption { 21 return func(ss *SignerDialerEndpoint) { ss.timeoutReadWrite = timeout } 22 } 23 24 // SignerDialerEndpointConnRetries sets the amount of attempted retries to 25 // acceptNewConnection. 26 func SignerDialerEndpointConnRetries(retries int) SignerServiceEndpointOption { 27 return func(ss *SignerDialerEndpoint) { ss.maxConnRetries = retries } 28 } 29 30 // SignerDialerEndpointRetryWaitInterval sets the retry wait interval to a 31 // custom value. 32 func SignerDialerEndpointRetryWaitInterval(interval time.Duration) SignerServiceEndpointOption { 33 return func(ss *SignerDialerEndpoint) { ss.retryWait = interval } 34 } 35 36 // SignerDialerEndpoint dials using its dialer and responds to any signature 37 // requests using its privVal. 38 type SignerDialerEndpoint struct { 39 signerEndpoint 40 41 dialer SocketDialer 42 43 retryWait time.Duration 44 maxConnRetries int 45 } 46 47 // NewSignerDialerEndpoint returns a SignerDialerEndpoint that will dial using the given 48 // dialer and respond to any signature requests over the connection 49 // using the given privVal. 50 func NewSignerDialerEndpoint( 51 logger log.Logger, 52 dialer SocketDialer, 53 ) *SignerDialerEndpoint { 54 55 sd := &SignerDialerEndpoint{ 56 dialer: dialer, 57 retryWait: defaultRetryWaitMilliseconds * time.Millisecond, 58 maxConnRetries: defaultMaxDialRetries, 59 } 60 61 sd.BaseService = *service.NewBaseService(logger, "SignerDialerEndpoint", sd) 62 sd.signerEndpoint.timeoutReadWrite = defaultTimeoutReadWriteSeconds * time.Second 63 64 return sd 65 } 66 67 func (sd *SignerDialerEndpoint) ensureConnection() error { 68 if sd.IsConnected() { 69 return nil 70 } 71 72 retries := 0 73 for retries < sd.maxConnRetries { 74 conn, err := sd.dialer() 75 76 if err != nil { 77 retries++ 78 sd.Logger.Debug("SignerDialer: Reconnection failed", "retries", retries, "max", sd.maxConnRetries, "err", err) 79 // Wait between retries 80 time.Sleep(sd.retryWait) 81 } else { 82 sd.SetConnection(conn) 83 sd.Logger.Debug("SignerDialer: Connection Ready") 84 return nil 85 } 86 } 87 88 sd.Logger.Debug("SignerDialer: Max retries exceeded", "retries", retries, "max", sd.maxConnRetries) 89 90 return ErrNoConnection 91 }