2 Copyright 2018 The Kubernetes Authors.
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
8 http://www.apache.org/licenses/LICENSE-2.0
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.
17 // Package connrotation implements a connection dialer that tracks and can close
18 // all created connections.
20 // This is used for credential rotation of long-lived connections, when there's
21 // no way to re-authenticate on a live connection.
30 // DialFunc is a shorthand for signature of net.DialContext.
31 type DialFunc func(ctx context.Context, network, address string) (net.Conn, error)
33 // Dialer opens connections through Dial and tracks them.
38 conns map[*closableConn]struct{}
41 // NewDialer creates a new Dialer instance.
43 // If dial is not nil, it will be used to create new underlying connections.
44 // Otherwise net.DialContext is used.
45 func NewDialer(dial DialFunc) *Dialer {
48 conns: make(map[*closableConn]struct{}),
52 // CloseAll forcibly closes all tracked connections.
54 // Note: new connections may get created before CloseAll returns.
55 func (d *Dialer) CloseAll() {
58 d.conns = make(map[*closableConn]struct{})
61 for conn := range conns {
66 // Dial creates a new tracked connection.
67 func (d *Dialer) Dial(network, address string) (net.Conn, error) {
68 return d.DialContext(context.Background(), network, address)
71 // DialContext creates a new tracked connection.
72 func (d *Dialer) DialContext(ctx context.Context, network, address string) (net.Conn, error) {
73 conn, err := d.dial(ctx, network, address)
78 closable := &closableConn{Conn: conn}
80 // Start tracking the connection
82 d.conns[closable] = struct{}{}
85 // When the connection is closed, remove it from the map. This will
86 // be no-op if the connection isn't in the map, e.g. if CloseAll()
88 closable.onClose = func() {
90 delete(d.conns, closable)
97 type closableConn struct {
102 func (c *closableConn) Close() error {
104 return c.Conn.Close()