remote_client.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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. }
  72. func (r *remoteClient) acquire(ctx context.Context) error {
  73. for {
  74. r.client.mu.RLock()
  75. c := r.client.conn
  76. r.mu.Lock()
  77. match := r.conn == c
  78. r.mu.Unlock()
  79. if match {
  80. return nil
  81. }
  82. r.client.mu.RUnlock()
  83. if err := r.reconnectWait(ctx, nil); err != nil {
  84. return err
  85. }
  86. }
  87. }
  88. func (r *remoteClient) release() { r.client.mu.RUnlock() }