grpclb_test_util_test.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. /*
  2. *
  3. * Copyright 2019 gRPC authors.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. *
  17. */
  18. package grpclb
  19. import (
  20. "net"
  21. "sync"
  22. )
  23. type tempError struct{}
  24. func (*tempError) Error() string {
  25. return "grpclb test temporary error"
  26. }
  27. func (*tempError) Temporary() bool {
  28. return true
  29. }
  30. type restartableListener struct {
  31. net.Listener
  32. addr string
  33. mu sync.Mutex
  34. closed bool
  35. conns []net.Conn
  36. }
  37. func newRestartableListener(l net.Listener) *restartableListener {
  38. return &restartableListener{
  39. Listener: l,
  40. addr: l.Addr().String(),
  41. }
  42. }
  43. func (l *restartableListener) Accept() (conn net.Conn, err error) {
  44. conn, err = l.Listener.Accept()
  45. if err == nil {
  46. l.mu.Lock()
  47. if l.closed {
  48. conn.Close()
  49. l.mu.Unlock()
  50. return nil, &tempError{}
  51. }
  52. l.conns = append(l.conns, conn)
  53. l.mu.Unlock()
  54. }
  55. return
  56. }
  57. func (l *restartableListener) Close() error {
  58. return l.Listener.Close()
  59. }
  60. func (l *restartableListener) stopPreviousConns() {
  61. l.mu.Lock()
  62. l.closed = true
  63. tmp := l.conns
  64. l.conns = nil
  65. l.mu.Unlock()
  66. for _, conn := range tmp {
  67. conn.Close()
  68. }
  69. }
  70. func (l *restartableListener) restart() {
  71. l.mu.Lock()
  72. l.closed = false
  73. l.mu.Unlock()
  74. }