/
http_client_new.go
214 lines (176 loc) · 5.58 KB
/
http_client_new.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
/*
Copyright 2023 The Knative Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package kncloudevents
import (
"context"
"fmt"
nethttp "net/http"
"sync"
"time"
"go.opencensus.io/plugin/ochttp"
"knative.dev/eventing/pkg/eventingtls"
duckv1 "knative.dev/pkg/apis/duck/v1"
"knative.dev/pkg/tracing/propagation/tracecontextb3"
)
const (
defaultRetryWaitMin = 1 * time.Second
defaultRetryWaitMax = 30 * time.Second
defaultCleanupInterval = 5 * time.Minute
)
var (
clients clientsHolder
)
type clientsHolder struct {
clientsMu sync.Mutex
clients map[string]*nethttp.Client
timerMu sync.Mutex
connectionArgs *ConnectionArgs
cleanupInterval time.Duration
cancelCleanup context.CancelFunc
}
func init() {
ctx, cancel := context.WithCancel(context.Background())
clients = clientsHolder{
clients: make(map[string]*nethttp.Client),
cancelCleanup: cancel,
cleanupInterval: defaultCleanupInterval,
}
go cleanupClientsMap(ctx)
}
func getClientForAddressable(addressable duckv1.Addressable) (*nethttp.Client, error) {
clients.clientsMu.Lock()
defer clients.clientsMu.Unlock()
clientKey := addressable.URL.String()
client, ok := clients.clients[clientKey]
if !ok {
newClient, err := createNewClient(addressable)
if err != nil {
return nil, fmt.Errorf("failed to create new client for addressable: %w", err)
}
clients.clients[clientKey] = newClient
client = newClient
}
return client, nil
}
func createNewClient(addressable duckv1.Addressable) (*nethttp.Client, error) {
var base = nethttp.DefaultTransport.(*nethttp.Transport).Clone()
if addressable.CACerts != nil && *addressable.CACerts != "" {
var err error
clientConfig := eventingtls.NewDefaultClientConfig()
clientConfig.CACerts = addressable.CACerts
base.TLSClientConfig, err = eventingtls.GetTLSClientConfig(clientConfig)
if err != nil {
return nil, err
}
}
clients.connectionArgs.configureTransport(base)
client := &nethttp.Client{
// Add output tracing.
Transport: &ochttp.Transport{
Base: base,
Propagation: tracecontextb3.TraceContextEgress,
},
}
return client, nil
}
func AddOrUpdateAddressableHandler(addressable duckv1.Addressable) {
clients.clientsMu.Lock()
defer clients.clientsMu.Unlock()
clientKey := addressable.URL.String()
client, err := createNewClient(addressable)
if err != nil {
fmt.Printf("failed to create new client: %v", err)
return
}
clients.clients[clientKey] = client
}
func DeleteAddressableHandler(addressable duckv1.Addressable) {
clients.clientsMu.Lock()
defer clients.clientsMu.Unlock()
clientKey := addressable.URL.String()
delete(clients.clients, clientKey)
}
// ConfigureConnectionArgs configures the new connection args.
// Use sparingly, because it might lead to creating a lot of clients, none of them sharing their connection pool!
func ConfigureConnectionArgs(ca *ConnectionArgs) {
configureConnectionArgsOldClient(ca) //also configure the connection args of the old client
clients.clientsMu.Lock()
defer clients.clientsMu.Unlock()
// Check if same config
if clients.connectionArgs != nil &&
ca != nil &&
ca.MaxIdleConns == clients.connectionArgs.MaxIdleConns &&
ca.MaxIdleConnsPerHost == clients.connectionArgs.MaxIdleConnsPerHost {
return
}
if len(clients.clients) > 0 {
// Let's try to clean up a bit the existing clients
// Note: this won't remove it nor close it
for _, clientEntry := range clients.clients {
clientEntry.CloseIdleConnections()
}
// Resetting clients
clients.clients = make(map[string]*nethttp.Client)
}
clients.connectionArgs = ca
}
// SetClientCleanupInterval sets the interval before the clients map is re-checked for expired entries.
// forceRestart will force the loop to restart with the new interval, cancelling the current iteration.
func SetClientCleanupInterval(cleanupInterval time.Duration, forceRestart bool) {
clients.timerMu.Lock()
clients.cleanupInterval = cleanupInterval
clients.timerMu.Unlock()
if forceRestart {
clients.clientsMu.Lock()
clients.cancelCleanup()
ctx, cancel := context.WithCancel(context.Background())
clients.cancelCleanup = cancel
clients.clientsMu.Unlock()
go cleanupClientsMap(ctx)
}
}
// ConnectionArgs allow to configure connection parameters to the underlying
// HTTP Client transport.
type ConnectionArgs struct {
// MaxIdleConns refers to the max idle connections, as in net/http/transport.
MaxIdleConns int
// MaxIdleConnsPerHost refers to the max idle connections per host, as in net/http/transport.
MaxIdleConnsPerHost int
}
func (ca *ConnectionArgs) configureTransport(transport *nethttp.Transport) {
if ca == nil {
return
}
transport.MaxIdleConns = ca.MaxIdleConns
transport.MaxIdleConnsPerHost = ca.MaxIdleConnsPerHost
}
func cleanupClientsMap(ctx context.Context) {
for {
clients.timerMu.Lock()
t := time.NewTimer(clients.cleanupInterval)
clients.timerMu.Unlock()
select {
case <-ctx.Done():
clients.timerMu.Lock()
t.Stop()
clients.timerMu.Unlock()
return
case <-t.C:
clients.clientsMu.Lock()
for _, cme := range clients.clients {
cme.CloseIdleConnections()
}
clients.clientsMu.Unlock()
}
}
}