-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathclient.go
More file actions
531 lines (468 loc) · 15.3 KB
/
client.go
File metadata and controls
531 lines (468 loc) · 15.3 KB
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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
package kong
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"net/http"
"net/http/httputil"
"net/url"
"os"
"sync"
"time"
"github.com/kong/go-kong/kong/custom"
)
const (
defaultBaseURL = "http://localhost:8001"
// DefaultTimeout is the timeout used for network connections and requests
// including TCP, TLS and HTTP layers.
DefaultTimeout = 60 * time.Second
)
var pageSize = 1000
type service struct {
client *Client
}
// Doer is the function signature for a Client request dispatcher.
type Doer func(ctx context.Context, client *http.Client, req *http.Request) (*http.Response, error)
var defaultCtx = context.Background()
// Client talks to the Admin API or control plane of a
// Kong cluster
type Client struct {
client *http.Client
baseRootURL string
workspace string // Do not access directly. Use Workspace()/SetWorkspace().
UserAgent string // User-Agent for the client.
workspaceLock sync.RWMutex // Synchronizes access to workspace.
common service
ConsumerGroupConsumers AbstractConsumerGroupConsumerService
ConsumerGroups AbstractConsumerGroupService
Consumers AbstractConsumerService
Developers AbstractDeveloperService
DeveloperRoles AbstractDeveloperRoleService
Services AbstractSvcService
Routes AbstractRouteService
CACertificates AbstractCACertificateService
Certificates AbstractCertificateService
Plugins AbstractPluginService
SNIs AbstractSNIService
Upstreams AbstractUpstreamService
UpstreamNodeHealth AbstractUpstreamNodeHealthService
Targets AbstractTargetService
Workspaces AbstractWorkspaceService
Admins AbstractAdminService
RBACUsers AbstractRBACUserService
RBACRoles AbstractRBACRoleService
RBACEndpointPermissions AbstractRBACEndpointPermissionService
RBACEntityPermissions AbstractRBACEntityPermissionService
Vaults AbstractVaultService
Keys AbstractKeyService
KeySets AbstractKeySetService
KonnectApplication AbstractKonnectApplicationService
Licenses AbstractLicenseService
FilterChains AbstractFilterChainService
Partials AbstractPartialService
credentials abstractCredentialService
KeyAuths AbstractKeyAuthService
BasicAuths AbstractBasicAuthService
HMACAuths AbstractHMACAuthService
JWTAuths AbstractJWTAuthService
MTLSAuths AbstractMTLSAuthService
ACLs AbstractACLService
Oauth2Credentials AbstractOauth2Service
Tags AbstractTagService
Info AbstractInfoService
GraphqlRateLimitingCostDecorations AbstractGraphqlRateLimitingCostDecorationService
DegraphqlRoutes AbstractDegraphqlRouteService
Schemas AbstractSchemaService
logger io.Writer
debug bool
CustomEntities AbstractCustomEntityService
doer Doer
isKonnect bool
custom.Registry
}
// Status respresents current status of a Kong node.
type Status struct {
Database struct {
Reachable bool `json:"reachable"`
} `json:"database"`
Server struct {
ConnectionsAccepted int `json:"connections_accepted"`
ConnectionsActive int `json:"connections_active"`
ConnectionsHandled int `json:"connections_handled"`
ConnectionsReading int `json:"connections_reading"`
ConnectionsWaiting int `json:"connections_waiting"`
ConnectionsWriting int `json:"connections_writing"`
TotalRequests int `json:"total_requests"`
} `json:"server"`
ConfigurationHash string `json:"configuration_hash,omitempty" yaml:"configuration_hash,omitempty"`
}
// NewClient returns a Client which talks to Admin API of Kong
func NewClient(baseURL *string, client *http.Client) (*Client, error) {
if client == nil {
transport := &http.Transport{
DialContext: (&net.Dialer{
Timeout: DefaultTimeout,
}).DialContext,
TLSHandshakeTimeout: DefaultTimeout,
}
client = &http.Client{
Timeout: DefaultTimeout,
Transport: transport,
}
}
kong := new(Client)
kong.client = client
var rootURL string
if baseURL != nil {
rootURL = *baseURL
} else if urlFromEnv := os.Getenv("KONG_ADMIN_URL"); urlFromEnv != "" {
rootURL = urlFromEnv
} else {
rootURL = defaultBaseURL
}
url, err := url.ParseRequestURI(rootURL)
if err != nil {
return nil, fmt.Errorf("parsing URL: %w", err)
}
kong.baseRootURL = url.String()
kong.common.client = kong
kong.ConsumerGroupConsumers = (*ConsumerGroupConsumerService)(&kong.common)
kong.ConsumerGroups = (*ConsumerGroupService)(&kong.common)
kong.Consumers = (*ConsumerService)(&kong.common)
kong.Developers = (*DeveloperService)(&kong.common)
kong.DeveloperRoles = (*DeveloperRoleService)(&kong.common)
kong.Services = (*Svcservice)(&kong.common)
kong.Routes = (*RouteService)(&kong.common)
kong.Plugins = (*PluginService)(&kong.common)
kong.Certificates = (*CertificateService)(&kong.common)
kong.CACertificates = (*CACertificateService)(&kong.common)
kong.SNIs = (*SNIService)(&kong.common)
kong.Upstreams = (*UpstreamService)(&kong.common)
kong.UpstreamNodeHealth = (*UpstreamNodeHealthService)(&kong.common)
kong.Targets = (*TargetService)(&kong.common)
kong.Workspaces = (*WorkspaceService)(&kong.common)
kong.Admins = (*AdminService)(&kong.common)
kong.RBACUsers = (*RBACUserService)(&kong.common)
kong.RBACRoles = (*RBACRoleService)(&kong.common)
kong.RBACEndpointPermissions = (*RBACEndpointPermissionService)(&kong.common)
kong.RBACEntityPermissions = (*RBACEntityPermissionService)(&kong.common)
kong.Vaults = (*VaultService)(&kong.common)
kong.Keys = (*KeyService)(&kong.common)
kong.KeySets = (*KeySetService)(&kong.common)
kong.KonnectApplication = (*KonnectApplicationService)(&kong.common)
kong.Licenses = (*LicenseService)(&kong.common)
kong.FilterChains = (*FilterChainService)(&kong.common)
kong.Partials = (*PartialService)(&kong.common)
kong.credentials = (*credentialService)(&kong.common)
kong.KeyAuths = (*KeyAuthService)(&kong.common)
kong.BasicAuths = (*BasicAuthService)(&kong.common)
kong.HMACAuths = (*HMACAuthService)(&kong.common)
kong.JWTAuths = (*JWTAuthService)(&kong.common)
kong.MTLSAuths = (*MTLSAuthService)(&kong.common)
kong.ACLs = (*ACLService)(&kong.common)
kong.GraphqlRateLimitingCostDecorations = (*GraphqlRateLimitingCostDecorationService)(&kong.common)
kong.DegraphqlRoutes = (*DegraphqlRouteService)(&kong.common)
kong.Schemas = (*SchemaService)(&kong.common)
kong.Oauth2Credentials = (*Oauth2Service)(&kong.common)
kong.Tags = (*TagService)(&kong.common)
kong.Info = (*InfoService)(&kong.common)
kong.CustomEntities = (*CustomEntityService)(&kong.common)
kong.Registry = custom.NewDefaultRegistry()
for i := 0; i < len(defaultCustomEntities); i++ {
err := kong.Register(defaultCustomEntities[i].Type(),
&defaultCustomEntities[i])
if err != nil {
return nil, err
}
}
kong.logger = os.Stderr
return kong, nil
}
// SetDoer sets a Doer implementation to be used for custom request dispatching.
func (c *Client) SetDoer(doer Doer) *Client {
c.doer = doer
return c
}
// Doer returns the Doer used by this client.
func (c *Client) Doer() Doer {
return c.doer
}
// SetWorkspace sets the Kong Enteprise workspace in the client.
// Calling this function with an empty string resets the workspace to default workspace.
func (c *Client) SetWorkspace(workspace string) {
c.workspaceLock.Lock()
defer c.workspaceLock.Unlock()
c.workspace = workspace
}
// Workspace return the workspace
func (c *Client) Workspace() string {
c.workspaceLock.RLock()
defer c.workspaceLock.RUnlock()
return c.workspace
}
func (c *Client) IsKonnectMode() bool {
return c.isKonnect
}
// baseURL build the base URL from the rootURL and the workspace
func (c *Client) workspacedBaseURL(workspace string) string {
if len(workspace) > 0 {
return c.baseRootURL + "/" + workspace
}
return c.baseRootURL
}
// DoRAW executes an HTTP request and returns an http.Response
// the caller is responsible for closing the response body.
func (c *Client) DoRAW(ctx context.Context, req *http.Request) (*http.Response, error) {
var err error
if req == nil {
return nil, fmt.Errorf("request cannot be nil")
}
if ctx != nil {
req = req.WithContext(ctx)
}
// log the request
err = c.logRequest(req)
if err != nil {
return nil, err
}
// Make the request
resp, err := c.client.Do(req)
if err != nil {
return nil, fmt.Errorf("making HTTP request: %w", err)
}
return resp, err
}
// Do executes an HTTP request and returns a Response.
//
// The caller can optionally provide v parameter, which when provided will contain
// the response body. Do supports wither an io.Writer (which will contain the
// response body verbatim) or anything else which the body should be unmarshalled
// into.
//
// By default, Do() calls DoRaw() to send the request and return the response before unmarshalling, logging,
// and error handling. The Client's WithDoer() method allows overriding this to inject custom behavior.
func (c *Client) Do(
ctx context.Context,
req *http.Request,
v interface{},
) (*Response, error) {
if c.UserAgent != "" && req != nil {
req.Header.Add("User-Agent", c.UserAgent)
}
var resp *http.Response
var err error
if c.doer != nil {
resp, err = c.doer(ctx, c.client, req)
} else {
resp, err = c.DoRAW(ctx, req)
}
if err != nil {
return nil, err
}
defer resp.Body.Close()
if err = c.logResponse(resp); err != nil {
return nil, err
}
response := newResponse(resp)
// Check for API errors.
// If an error status code was returned, then parse the body and create
// an API Error out of it.
if err = hasError(resp); err != nil {
return response, err
}
if v != nil {
switch v := v.(type) {
case io.Writer:
_, err = io.Copy(v, resp.Body)
if err != nil {
return nil, fmt.Errorf("failed copying response body: %w", err)
}
return response, nil
default:
err = json.NewDecoder(resp.Body).Decode(v)
if err != nil {
return nil, fmt.Errorf("failed decoding response body: %w", err)
}
return response, nil
}
}
return response, nil
}
// ErrorOrResponseError helps to handle the case where
// there might not be a "hard" (connection) error but the
// response itself represents an error.
func ErrorOrResponseError(res *Response, err error) error {
if err != nil {
return err
}
if res.StatusCode >= http.StatusBadRequest { // errors start at 400
return fmt.Errorf("unexpected response: %q", res.Status)
}
return nil
}
// SetDebugMode enables or disables logging of
// the request to the logger set by SetLogger().
// By default, debug logging is disabled.
func (c *Client) SetDebugMode(enableDebug bool) {
c.debug = enableDebug
}
func (c *Client) logRequest(r *http.Request) error {
if !c.debug {
return nil
}
dump, err := httputil.DumpRequestOut(r, true)
if err != nil {
return err
}
_, err = c.logger.Write(append(dump, '\n'))
return err
}
func (c *Client) logResponse(r *http.Response) error {
if !c.debug {
return nil
}
dump, err := httputil.DumpResponse(r, true)
if err != nil {
return err
}
_, err = c.logger.Write(append(dump, '\n'))
return err
}
// SetLogger sets the debug logger, defaults to os.StdErr
func (c *Client) SetLogger(w io.Writer) {
if w == nil {
return
}
c.logger = w
}
// SetKonnectFlag sets the konnect boolean true, if konnect flow
func (c *Client) SetKonnectFlag(isKonnect bool) {
c.isKonnect = isKonnect
}
// Status returns the status of a Kong node
func (c *Client) Status(ctx context.Context) (*Status, error) {
req, err := c.NewRequest("GET", "/status", nil, nil)
if err != nil {
return nil, err
}
var s Status
_, err = c.Do(ctx, req, &s)
if err != nil {
return nil, err
}
return &s, nil
}
// Config gets the specified config from the configured Admin API endpoint
// and should contain the JSON serialized body that adheres to the configuration
// format specified at:
// https://docs.konghq.com/gateway/latest/production/deployment-topologies/db-less-and-declarative-config/#declarative-configuration-format
// It returns the response body and an error, if it encounters any.
func (c *Client) Config(ctx context.Context) ([]byte, error) {
req, err := c.NewRequest("GET", "/config", nil, nil)
if err != nil {
return nil, err
}
var configWrapper map[string]string
_, err = c.Do(ctx, req, &configWrapper)
if err != nil {
return nil, err
}
config, ok := configWrapper["config"]
if !ok {
return nil, errors.New("config field not found in GET /config response body")
}
return []byte(config), nil
}
// Root returns the response of GET request on root of Admin API (GET / or /kong with a workspace).
func (c *Client) Root(ctx context.Context) (map[string]interface{}, error) {
endpoint := "/"
ws := c.Workspace()
if len(ws) > 0 {
endpoint = "/kong"
}
req, err := c.NewRequestRaw("GET", c.workspacedBaseURL(ws), endpoint, nil, nil)
if err != nil {
return nil, err
}
var info map[string]interface{}
_, err = c.Do(ctx, req, &info)
if err != nil {
return nil, err
}
return info, nil
}
// RootJSON returns the response of GET request on the root of the Admin API
// (GET / or /kong with a workspace) returning the raw JSON response data.
func (c *Client) RootJSON(ctx context.Context) ([]byte, error) {
endpoint := "/"
ws := c.Workspace()
if len(ws) > 0 {
endpoint = "/kong"
}
req, err := c.NewRequestRaw("GET", c.workspacedBaseURL(ws), endpoint, nil, nil)
if err != nil {
return nil, err
}
resp, err := c.DoRAW(ctx, req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return body, nil
}
func (c *Client) BaseRootURL() string {
return c.baseRootURL
}
// ReloadDeclarativeRawConfig sends out the specified config to configured Admin
// API endpoint using the provided reader which should contain the JSON
// serialized body that adheres to the configuration format specified at:
// https://docs.konghq.com/gateway/latest/production/deployment-topologies/db-less-and-declarative-config/#declarative-configuration-format
// It returns APIError with a response body in case it receives a valid HTTP response with <200 or >=400 status codes.
func (c *Client) ReloadDeclarativeRawConfig(
ctx context.Context,
config io.Reader,
checkHash bool,
flattenErrors bool,
) error {
type sendConfigParams struct {
CheckHash int `url:"check_hash,omitempty"`
FlattenErrors int `url:"flatten_errors,omitempty"`
}
var checkHashI int
if checkHash {
checkHashI = 1
}
var flattenErrorsI int
if flattenErrors {
flattenErrorsI = 1
}
req, err := c.NewRequest(
"POST",
"/config",
sendConfigParams{CheckHash: checkHashI, FlattenErrors: flattenErrorsI},
config,
)
if err != nil {
return fmt.Errorf("creating new HTTP request for /config: %w", err)
}
resp, err := c.DoRAW(ctx, req)
if err != nil {
return fmt.Errorf("failed posting new config to /config: %w", err)
}
defer resp.Body.Close()
b, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("could not read /config %d status response body: %w", resp.StatusCode, err)
}
if resp.StatusCode < 200 || resp.StatusCode >= 400 {
return NewAPIErrorWithRaw(resp.StatusCode, "failed posting new config to /config", b)
}
return nil
}