blob: 235a9e019873471257e4534f6ed963ef970c3c1f [file] [log] [blame]
sslobodrd046be82019-01-16 10:02:22 -05001/*
2Copyright 2018 The Kubernetes Authors.
3
4Licensed under the Apache License, Version 2.0 (the "License");
5you may not use this file except in compliance with the License.
6You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10Unless required by applicable law or agreed to in writing, software
11distributed under the License is distributed on an "AS IS" BASIS,
12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13See the License for the specific language governing permissions and
14limitations under the License.
15*/
16
17// Package connrotation implements a connection dialer that tracks and can close
18// all created connections.
19//
20// This is used for credential rotation of long-lived connections, when there's
21// no way to re-authenticate on a live connection.
22package connrotation
23
24import (
25 "context"
26 "net"
27 "sync"
28)
29
30// DialFunc is a shorthand for signature of net.DialContext.
31type DialFunc func(ctx context.Context, network, address string) (net.Conn, error)
32
33// Dialer opens connections through Dial and tracks them.
34type Dialer struct {
35 dial DialFunc
36
37 mu sync.Mutex
38 conns map[*closableConn]struct{}
39}
40
41// NewDialer creates a new Dialer instance.
42//
43// If dial is not nil, it will be used to create new underlying connections.
44// Otherwise net.DialContext is used.
45func NewDialer(dial DialFunc) *Dialer {
46 return &Dialer{
47 dial: dial,
48 conns: make(map[*closableConn]struct{}),
49 }
50}
51
52// CloseAll forcibly closes all tracked connections.
53//
54// Note: new connections may get created before CloseAll returns.
55func (d *Dialer) CloseAll() {
56 d.mu.Lock()
57 conns := d.conns
58 d.conns = make(map[*closableConn]struct{})
59 d.mu.Unlock()
60
61 for conn := range conns {
62 conn.Close()
63 }
64}
65
66// Dial creates a new tracked connection.
67func (d *Dialer) Dial(network, address string) (net.Conn, error) {
68 return d.DialContext(context.Background(), network, address)
69}
70
71// DialContext creates a new tracked connection.
72func (d *Dialer) DialContext(ctx context.Context, network, address string) (net.Conn, error) {
73 conn, err := d.dial(ctx, network, address)
74 if err != nil {
75 return nil, err
76 }
77
78 closable := &closableConn{Conn: conn}
79
80 // Start tracking the connection
81 d.mu.Lock()
82 d.conns[closable] = struct{}{}
83 d.mu.Unlock()
84
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()
87 // is called.
88 closable.onClose = func() {
89 d.mu.Lock()
90 delete(d.conns, closable)
91 d.mu.Unlock()
92 }
93
94 return closable, nil
95}
96
97type closableConn struct {
98 onClose func()
99 net.Conn
100}
101
102func (c *closableConn) Close() error {
103 go c.onClose()
104 return c.Conn.Close()
105}