-
Notifications
You must be signed in to change notification settings - Fork 129
/
client.go
268 lines (233 loc) · 7.13 KB
/
client.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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
// Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
// or more contributor license agreements. Licensed under the Elastic License;
// you may not use this file except in compliance with the Elastic License.
package remote
import (
"context"
"io"
"net/http"
"net/url"
"strings"
"sync"
"time"
"github.com/pkg/errors"
urlutil "github.com/elastic/elastic-agent-libs/kibana"
"github.com/elastic/elastic-agent-libs/transport/httpcommon"
"github.com/elastic/elastic-agent/internal/pkg/config"
"github.com/elastic/elastic-agent/internal/pkg/id"
"github.com/elastic/elastic-agent/pkg/core/logger"
)
const (
retryOnBadConnTimeout = 5 * time.Minute
)
type requestFunc func(string, string, url.Values, io.Reader) (*http.Request, error)
type wrapperFunc func(rt http.RoundTripper) (http.RoundTripper, error)
type requestClient struct {
request requestFunc
client http.Client
lastUsed time.Time
lastErr error
lastErrOcc time.Time
}
// Client wraps an http.Client and takes care of making the raw calls, the client should
// stay simple and specificals should be implemented in external action instead of adding new methods
// to the client. For authenticated calls or sending fields on every request, create customer RoundTripper
// implementations that will take care of the boiler plates.
type Client struct {
log *logger.Logger
lock sync.Mutex
clients []*requestClient
config Config
}
// NewConfigFromURL returns a Config based on a received host.
func NewConfigFromURL(URL string) (Config, error) {
u, err := url.Parse(URL)
if err != nil {
return Config{}, errors.Wrap(err, "could not parse url")
}
c := DefaultClientConfig()
c.Protocol = Protocol(u.Scheme)
c.Host = u.Host
c.Path = u.Path
return c, nil
}
// NewWithRawConfig returns a new client with a specified configuration.
func NewWithRawConfig(log *logger.Logger, config *config.Config, wrapper wrapperFunc) (*Client, error) {
l := log
if l == nil {
log, err := logger.New("client", false)
if err != nil {
return nil, err
}
l = log
}
cfg := Config{}
if err := config.Unpack(&cfg); err != nil {
return nil, errors.Wrap(err, "invalidate configuration")
}
return NewWithConfig(l, cfg, wrapper)
}
// NewWithConfig takes a Config and return a client.
func NewWithConfig(log *logger.Logger, cfg Config, wrapper wrapperFunc) (*Client, error) {
// Normalize the URL with the path any spaces configured.
var p string
if len(cfg.SpaceID) > 0 {
p = strings.Join([]string{cfg.Path, cfg.SpaceID}, "/")
} else {
p = cfg.Path
}
if !strings.HasSuffix(p, "/") {
p = p + "/"
}
hosts := cfg.GetHosts()
clients := make([]*requestClient, len(hosts))
for i, host := range cfg.GetHosts() {
connStr, err := urlutil.MakeURL(string(cfg.Protocol), p, host, 0)
if err != nil {
return nil, errors.Wrap(err, "invalid fleet-server endpoint")
}
transport, err := cfg.Transport.RoundTripper(
httpcommon.WithAPMHTTPInstrumentation(),
httpcommon.WithForceAttemptHTTP2(true),
)
if err != nil {
return nil, err
}
if wrapper != nil {
transport, err = wrapper(transport)
if err != nil {
return nil, errors.Wrap(err, "fail to create transport client")
}
}
httpClient := http.Client{
Transport: transport,
Timeout: cfg.Transport.Timeout,
}
clients[i] = &requestClient{
request: prefixRequestFactory(connStr),
client: httpClient,
}
}
return new(log, cfg, clients...)
}
// Send executes a direct calls against the API, the method will takes cares of cloning
// also add necessary headers for likes: "Content-Type", "Accept", and "kbn-xsrf".
// No assumptions is done on the response concerning the received format, this will be the responsibility
// of the implementation to correctly unpack any received data.
//
// NOTE:
// - The caller of this method is free to override any value found in the headers.
// - The magic of unpacking of errors is not done in the Send method, a helper method is provided.
func (c *Client) Send(
ctx context.Context,
method, path string,
params url.Values,
headers http.Header,
body io.Reader,
) (*http.Response, error) {
// Generate a request ID for tracking
var reqID string
if u, err := id.Generate(); err == nil {
reqID = u.String()
}
c.log.Debugf("Request method: %s, path: %s, reqID: %s", method, path, reqID)
c.lock.Lock()
defer c.lock.Unlock()
requester := c.nextRequester()
req, err := requester.request(method, path, params, body)
if err != nil {
return nil, errors.Wrapf(err, "fail to create HTTP request using method %s to %s", method, path)
}
// Add generals headers to the request, we are dealing exclusively with JSON.
// Content-Type / Accepted type can be override from the called.
req.Header.Set("Content-Type", "application/json")
req.Header.Add("Accept", "application/json")
// This header should be specific to fleet-server or remove it
req.Header.Set("kbn-xsrf", "1") // Without this Kibana will refuse to answer the request.
// If available, add the request id as an HTTP header
if reqID != "" {
req.Header.Add("X-Request-ID", reqID)
}
// copy headers.
for header, values := range headers {
for _, v := range values {
req.Header.Add(header, v)
}
}
requester.lastUsed = time.Now().UTC()
resp, err := requester.client.Do(req.WithContext(ctx))
if err != nil {
requester.lastErr = err
requester.lastErrOcc = time.Now().UTC()
} else {
requester.lastErr = nil
requester.lastErrOcc = time.Time{}
}
return resp, err
}
// URI returns the remote URI.
func (c *Client) URI() string {
host := c.config.GetHosts()[0]
return string(c.config.Protocol) + "://" + host + "/" + c.config.Path
}
// new creates new API client.
func new(
log *logger.Logger,
cfg Config,
httpClients ...*requestClient,
) (*Client, error) {
c := &Client{
log: log,
clients: httpClients,
config: cfg,
}
return c, nil
}
// nextRequester returns the requester to use.
//
// It excludes clients that have errored in the last 5 minutes.
func (c *Client) nextRequester() *requestClient {
var selected *requestClient
now := time.Now().UTC()
for _, requester := range c.clients {
if requester.lastErr != nil && now.Sub(requester.lastErrOcc) > retryOnBadConnTimeout {
requester.lastErr = nil
requester.lastErrOcc = time.Time{}
}
if requester.lastErr != nil {
continue
}
if requester.lastUsed.IsZero() {
// never been used, instant winner!
selected = requester
break
}
if selected == nil {
selected = requester
continue
}
if requester.lastUsed.Before(selected.lastUsed) {
selected = requester
}
}
if selected == nil {
// all are erroring; select the oldest one that errored
for _, requester := range c.clients {
if selected == nil {
selected = requester
continue
}
if requester.lastErrOcc.Before(selected.lastErrOcc) {
selected = requester
}
}
}
return selected
}
func prefixRequestFactory(URL string) requestFunc {
return func(method, path string, params url.Values, body io.Reader) (*http.Request, error) {
path = strings.TrimPrefix(path, "/")
newPath := strings.Join([]string{URL, path, "?", params.Encode()}, "")
return http.NewRequest(method, newPath, body) //nolint:noctx // keep old behaviour
}
}