| 1 |
/* |
| 2 |
Copyright 2024 The Kubernetes Authors. |
| 3 |
|
| 4 |
Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 |
you may not use this file except in compliance with the License. |
| 6 |
You may obtain a copy of the License at |
| 7 |
|
| 8 |
http://www.apache.org/licenses/LICENSE-2.0 |
| 9 |
|
| 10 |
Unless required by applicable law or agreed to in writing, software |
| 11 |
distributed under the License is distributed on an "AS IS" BASIS, |
| 12 |
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 |
See the License for the specific language governing permissions and |
| 14 |
limitations under the License. |
| 15 |
*/ |
| 16 |
|
| 17 |
package net |
| 18 |
|
| 19 |
import ( |
| 20 |
"context" |
| 21 |
"fmt" |
| 22 |
"net" |
| 23 |
"sync" |
| 24 |
"sync/atomic" |
| 25 |
) |
| 26 |
|
| 27 |
// connErrPair pairs conn and error which is returned by accept on sub-listeners. |
| 28 |
type connErrPair struct { |
| 29 |
conn net.Conn |
| 30 |
err error |
| 31 |
} |
| 32 |
|
| 33 |
// multiListener implements net.Listener |
| 34 |
type multiListener struct { |
| 35 |
listeners []net.Listener |
| 36 |
wg sync.WaitGroup |
| 37 |
|
| 38 |
// connCh passes accepted connections, from child listeners to parent. |
| 39 |
connCh chan connErrPair |
| 40 |
// stopCh communicates from parent to child listeners. |
| 41 |
stopCh chan struct{} |
| 42 |
closed atomic.Bool |
| 43 |
} |
| 44 |
|
| 45 |
// compile time check to ensure *multiListener implements net.Listener |
| 46 |
var _ net.Listener = &multiListener{} |
| 47 |
|
| 48 |
// MultiListen returns net.Listener which can listen on and accept connections for |
| 49 |
// the given network on multiple addresses. Internally it uses stdlib to create |
| 50 |
// sub-listener and multiplexes connection requests using go-routines. |
| 51 |
// The network must be "tcp", "tcp4" or "tcp6". |
| 52 |
// It follows the semantics of net.Listen that primarily means: |
| 53 |
// 1. If the host is an unspecified/zero IP address with "tcp" network, MultiListen |
| 54 |
// listens on all available unicast and anycast IP addresses of the local system. |
| 55 |
// 2. Use "tcp4" or "tcp6" to exclusively listen on IPv4 or IPv6 family, respectively. |
| 56 |
// 3. The host can accept names (e.g, localhost) and it will create a listener for at |
| 57 |
// most one of the host's IP. |
| 58 |
func MultiListen(ctx context.Context, network string, addrs ...string) (net.Listener, error) { |
| 59 |
var lc net.ListenConfig |
| 60 |
return multiListen( |
| 61 |
ctx, |
| 62 |
network, |
| 63 |
addrs, |
| 64 |
func(ctx context.Context, network, address string) (net.Listener, error) { |
| 65 |
return lc.Listen(ctx, network, address) |
| 66 |
}) |
| 67 |
} |
| 68 |
|
| 69 |
// multiListen implements MultiListen by consuming stdlib functions as dependency allowing |
| 70 |
// mocking for unit-testing. |
| 71 |
func multiListen( |
| 72 |
ctx context.Context, |
| 73 |
network string, |
| 74 |
addrs []string, |
| 75 |
listenFunc func(ctx context.Context, network, address string) (net.Listener, error), |
| 76 |
) (net.Listener, error) { |
| 77 |
if !(network == "tcp" || network == "tcp4" || network == "tcp6") { |
| 78 |
return nil, fmt.Errorf("network %q not supported", network) |
| 79 |
} |
| 80 |
if len(addrs) == 0 { |
| 81 |
return nil, fmt.Errorf("no address provided to listen on") |
| 82 |
} |
| 83 |
|
| 84 |
ml := &multiListener{ |
| 85 |
connCh: make(chan connErrPair), |
| 86 |
stopCh: make(chan struct{}), |
| 87 |
} |
| 88 |
for _, addr := range addrs { |
| 89 |
l, err := listenFunc(ctx, network, addr) |
| 90 |
if err != nil { |
| 91 |
// close all the sub-listeners and exit |
| 92 |
_ = ml.Close() |
| 93 |
return nil, err |
| 94 |
} |
| 95 |
ml.listeners = append(ml.listeners, l) |
| 96 |
} |
| 97 |
|
| 98 |
for _, l := range ml.listeners { |
| 99 |
ml.wg.Add(1) |
| 100 |
go func(l net.Listener) { |
| 101 |
defer ml.wg.Done() |
| 102 |
for { |
| 103 |
// Accept() is blocking, unless ml.Close() is called, in which |
| 104 |
// case it will return immediately with an error. |
| 105 |
conn, err := l.Accept() |
| 106 |
// This assumes that ANY error from Accept() will terminate the |
| 107 |
// sub-listener. We could maybe be more precise, but it |
| 108 |
// doesn't seem necessary. |
| 109 |
terminate := err != nil |
| 110 |
|
| 111 |
select { |
| 112 |
case ml.connCh <- connErrPair{conn: conn, err: err}: |
| 113 |
case <-ml.stopCh: |
| 114 |
// In case we accepted a connection AND were stopped, and |
| 115 |
// this select-case was chosen, just throw away the |
| 116 |
// connection. This avoids potentially blocking on connCh |
| 117 |
// or leaking a connection. |
| 118 |
if conn != nil { |
| 119 |
_ = conn.Close() |
| 120 |
} |
| 121 |
terminate = true |
| 122 |
} |
| 123 |
// Make sure we don't loop on Accept() returning an error and |
| 124 |
// the select choosing the channel case. |
| 125 |
if terminate { |
| 126 |
return |
| 127 |
} |
| 128 |
} |
| 129 |
}(l) |
| 130 |
} |
| 131 |
return ml, nil |
| 132 |
} |
| 133 |
|
| 134 |
// Accept implements net.Listener. It waits for and returns a connection from |
| 135 |
// any of the sub-listener. |
| 136 |
func (ml *multiListener) Accept() (net.Conn, error) { |
| 137 |
// wait for any sub-listener to enqueue an accepted connection |
| 138 |
connErr, ok := <-ml.connCh |
| 139 |
if !ok { |
| 140 |
// The channel will be closed only when Close() is called on the |
| 141 |
// multiListener. Closing of this channel implies that all |
| 142 |
// sub-listeners are also closed, which causes a "use of closed |
| 143 |
// network connection" error on their Accept() calls. We return the |
| 144 |
// same error for multiListener.Accept() if multiListener.Close() |
| 145 |
// has already been called. |
| 146 |
return nil, fmt.Errorf("use of closed network connection") |
| 147 |
} |
| 148 |
return connErr.conn, connErr.err |
| 149 |
} |
| 150 |
|
| 151 |
// Close implements net.Listener. It will close all sub-listeners and wait for |
| 152 |
// the go-routines to exit. |
| 153 |
func (ml *multiListener) Close() error { |
| 154 |
// Make sure this can be called repeatedly without explosions. |
| 155 |
if !ml.closed.CompareAndSwap(false, true) { |
| 156 |
return fmt.Errorf("use of closed network connection") |
| 157 |
} |
| 158 |
|
| 159 |
// Tell all sub-listeners to stop. |
| 160 |
close(ml.stopCh) |
| 161 |
|
| 162 |
// Closing the listeners causes Accept() to immediately return an error in |
| 163 |
// the sub-listener go-routines. |
| 164 |
for _, l := range ml.listeners { |
| 165 |
_ = l.Close() |
| 166 |
} |
| 167 |
|
| 168 |
// Wait for all the sub-listener go-routines to exit. |
| 169 |
ml.wg.Wait() |
| 170 |
close(ml.connCh) |
| 171 |
|
| 172 |
// Drain any already-queued connections. |
| 173 |
for connErr := range ml.connCh { |
| 174 |
if connErr.conn != nil { |
| 175 |
_ = connErr.conn.Close() |
| 176 |
} |
| 177 |
} |
| 178 |
return nil |
| 179 |
} |
| 180 |
|
| 181 |
// Addr is an implementation of the net.Listener interface. It always returns |
| 182 |
// the address of the first listener. Callers should use conn.LocalAddr() to |
| 183 |
// obtain the actual local address of the sub-listener. |
| 184 |
func (ml *multiListener) Addr() net.Addr { |
| 185 |
return ml.listeners[0].Addr() |
| 186 |
} |
| 187 |
|
| 188 |
// Addrs is like Addr, but returns the address for all registered listeners. |
| 189 |
func (ml *multiListener) Addrs() []net.Addr { |
| 190 |
var ret []net.Addr |
| 191 |
for _, l := range ml.listeners { |
| 192 |
ret = append(ret, l.Addr()) |
| 193 |
} |
| 194 |
return ret |
| 195 |
} |