remote_client.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. // Copyright 2016 The etcd Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package clientv3
  15. import (
  16. "sync"
  17. "golang.org/x/net/context"
  18. "google.golang.org/grpc"
  19. )
  20. type remoteClient struct {
  21. client *Client
  22. conn *grpc.ClientConn
  23. updateConn func(*grpc.ClientConn)
  24. mu sync.Mutex
  25. }
  26. func newRemoteClient(client *Client, update func(*grpc.ClientConn)) *remoteClient {
  27. ret := &remoteClient{
  28. client: client,
  29. conn: client.ActiveConnection(),
  30. updateConn: update,
  31. }
  32. ret.mu.Lock()
  33. defer ret.mu.Unlock()
  34. ret.updateConn(ret.conn)
  35. return ret
  36. }
  37. // reconnectWait reconnects the client, returning when connection establishes/fails.
  38. func (r *remoteClient) reconnectWait(ctx context.Context, prevErr error) error {
  39. r.mu.Lock()
  40. updated := r.tryUpdate()
  41. r.mu.Unlock()
  42. if updated {
  43. return nil
  44. }
  45. conn, err := r.client.connWait(ctx, prevErr)
  46. if err == nil {
  47. r.mu.Lock()
  48. r.conn = conn
  49. r.updateConn(conn)
  50. r.mu.Unlock()
  51. }
  52. return err
  53. }
  54. // reconnect will reconnect the client without waiting
  55. func (r *remoteClient) reconnect(err error) {
  56. r.mu.Lock()
  57. defer r.mu.Unlock()
  58. if r.tryUpdate() {
  59. return
  60. }
  61. r.client.connStartRetry(err)
  62. }
  63. func (r *remoteClient) tryUpdate() bool {
  64. activeConn := r.client.ActiveConnection()
  65. if activeConn == nil || activeConn == r.conn {
  66. return false
  67. }
  68. r.conn = activeConn
  69. r.updateConn(activeConn)
  70. return true
  71. }