forked from stmcginnis/gofish
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
604 lines (499 loc) · 17.7 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
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
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
//
// SPDX-License-Identifier: BSD-3-Clause
//
package gofish
import (
"bytes"
"context"
"crypto/tls"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"mime/multipart"
"net/http"
"net/http/httputil"
"net/textproto"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/stmcginnis/gofish/common"
"github.com/stmcginnis/gofish/redfish"
)
const userAgent = "gofish/1.0"
const applicationJSON = "application/json"
// APIClient represents a connection to a Redfish/Swordfish enabled service
// or device.
type APIClient struct {
// ctx is the context used in the HTTP requests
ctx context.Context
// Endpoint is the URL of the *fish service
endpoint string
// HTTPClient is for direct http actions
HTTPClient *http.Client
// Service is the ServiceRoot of this Redfish instance
Service *Service
// Auth information saved for later to be able to log out
auth *redfish.AuthToken
// sem used to limit number of concurrent requests
sem chan bool
// dumpWriter will receive HTTP dumps if non-nil.
dumpWriter io.Writer
// keepAlive is a flag to indicate if we should try to keep idle connections open
keepAlive bool
}
// Session holds the session ID and auth token needed to identify an
// authenticated client
type Session struct {
ID string
Token string
}
// ClientConfig holds the settings for establishing a connection.
type ClientConfig struct {
// Endpoint is the URL of the redfish service
Endpoint string
// Username is the optional user name to authenticate with.
Username string
// Password is the password to use for authentication.
Password string
// Session is an optional session ID+token obtained from a previous session
// If this is set, it is preferred over Username and Password
Session *Session
// Insecure controls whether to enforce SSL certificate validity.
Insecure bool
// Controls TLS handshake timeout
TLSHandshakeTimeout int
// HTTPClient is the optional client to connect with.
HTTPClient *http.Client
// DumpWriter is an optional io.Writer to receive dumps of HTTP
// requests and responses.
DumpWriter io.Writer
// BasicAuth tells the APIClient if basic auth should be used (true) or token based auth must be used (false)
BasicAuth bool
// The maximum number of concurrent HTTP requests that will be made (default: 1)
MaxConcurrentRequests int64
// ReuseConnections can be useful if executing a lot of requests. Setting to `true` allows
// the TCP sessions to remain open and reused betweeen subsequent calls.
ReuseConnections bool
}
// setupClientWithConfig setups the client using the client config
func setupClientWithConfig(ctx context.Context, config *ClientConfig) (c *APIClient, err error) {
if !strings.HasPrefix(config.Endpoint, "http") {
return c, fmt.Errorf("endpoint must starts with http or https")
}
client := &APIClient{
endpoint: config.Endpoint,
dumpWriter: config.DumpWriter,
ctx: ctx,
}
if config.MaxConcurrentRequests <= 0 {
client.sem = make(chan bool, 1)
} else {
client.sem = make(chan bool, config.MaxConcurrentRequests)
}
if config.TLSHandshakeTimeout == 0 {
config.TLSHandshakeTimeout = 10
}
if config.HTTPClient == nil {
defaultTransport := http.DefaultTransport.(*http.Transport)
transport := &http.Transport{
Proxy: defaultTransport.Proxy,
DialContext: defaultTransport.DialContext,
MaxIdleConns: defaultTransport.MaxIdleConns,
IdleConnTimeout: defaultTransport.IdleConnTimeout,
ExpectContinueTimeout: defaultTransport.ExpectContinueTimeout,
TLSHandshakeTimeout: time.Duration(config.TLSHandshakeTimeout) * time.Second,
TLSClientConfig: &tls.Config{
InsecureSkipVerify: config.Insecure,
},
}
if config.ReuseConnections {
client.keepAlive = true
transport.DisableKeepAlives = false
transport.IdleConnTimeout = 1 * time.Minute
}
client.HTTPClient = &http.Client{Transport: transport}
} else {
client.HTTPClient = config.HTTPClient
}
// Fetch the service root
client.Service, err = ServiceRoot(client)
if err != nil {
return nil, err
}
return client, nil
}
// setupClientWithEndpoint setups the client using only the endpoint
func setupClientWithEndpoint(ctx context.Context, endpoint string) (c *APIClient, err error) {
if !strings.HasPrefix(endpoint, "http") {
return c, fmt.Errorf("endpoint must starts with http or https")
}
client := &APIClient{
endpoint: endpoint,
ctx: ctx,
sem: make(chan bool, 1),
}
client.HTTPClient = &http.Client{}
// Fetch the service root
client.Service, err = ServiceRoot(client)
if err != nil {
return nil, err
}
return client, nil
}
// setupClientAuth setups the authentication in the client using the client config
func (c *APIClient) setupClientAuth(config *ClientConfig) error {
if config.Session != nil {
c.auth = &redfish.AuthToken{
Session: config.Session.ID,
Token: config.Session.Token,
}
} else if config.Username != "" {
var auth *redfish.AuthToken
if config.BasicAuth {
auth = &redfish.AuthToken{
Username: config.Username,
Password: config.Password,
BasicAuth: true,
}
} else {
var err error
auth, err = c.Service.CreateSession(config.Username, config.Password)
if err != nil {
return err
}
}
c.auth = auth
}
return nil
}
// Connect creates a new client connection to a Redfish service.
func Connect(config ClientConfig) (c *APIClient, err error) { //nolint:gocritic
return ConnectContext(context.Background(), config)
}
// ConnectContext is the same as Connect, but sets the ctx.
func ConnectContext(ctx context.Context, config ClientConfig) (c *APIClient, err error) { //nolint:gocritic
client, err := setupClientWithConfig(ctx, &config)
if err != nil {
return c, err
}
// Authenticate with the service
err = client.setupClientAuth(&config)
if err != nil {
return c, err
}
return client, err
}
// ConnectDefault creates an unauthenticated connection to a Redfish service.
func ConnectDefault(endpoint string) (c *APIClient, err error) {
return ConnectDefaultContext(context.Background(), endpoint)
}
// ConnectDefaultContext is the same as ConnectDefault, but sets the ctx.
func ConnectDefaultContext(ctx context.Context, endpoint string) (c *APIClient, err error) {
client, err := setupClientWithEndpoint(ctx, endpoint)
if err != nil {
return c, err
}
return client, err
}
// GetService returns the APIClient's service.
func (c *APIClient) GetService() *Service {
return c.Service
}
// CloneWithSession will create a new Client with a session instead of basic auth.
func (c *APIClient) CloneWithSession() (*APIClient, error) {
if c.auth.Session != "" {
return nil, fmt.Errorf("client already has a session")
}
newClient := *c
newClient.HTTPClient = c.HTTPClient
service, err := ServiceRoot(&newClient)
if err != nil {
return nil, err
}
newClient.Service = service
auth, err := newClient.Service.CreateSession(
newClient.auth.Username,
newClient.auth.Password)
if err != nil {
return nil, err
}
newClient.auth = auth
return &newClient, err
}
// GetSession retrieves the session data from an initialized APIClient. An error
// is returned if the client is not authenticated.
func (c *APIClient) GetSession() (*Session, error) {
if c.auth == nil || c.auth.Session == "" {
return nil, fmt.Errorf("client not authenticated")
}
return &Session{
ID: c.auth.Session,
Token: c.auth.Token,
}, nil
}
// Get performs a HEAD request against the Redfish service.
func (c *APIClient) Head(url string) (*http.Response, error) {
return c.HeadWithHeaders(url, nil)
}
// GetWithHeaders performs a HEAD request against the Redfish service but allowing custom headers
func (c *APIClient) HeadWithHeaders(url string, customHeaders map[string]string) (*http.Response, error) {
relativePath := url
if relativePath == "" {
relativePath = common.DefaultServiceRoot
}
return c.runRequestWithHeaders(http.MethodHead, relativePath, nil, customHeaders)
}
// Get performs a GET request against the Redfish service.
func (c *APIClient) Get(url string) (*http.Response, error) {
return c.GetWithHeaders(url, nil)
}
// GetWithHeaders performs a GET request against the Redfish service but allowing custom headers
func (c *APIClient) GetWithHeaders(url string, customHeaders map[string]string) (*http.Response, error) {
relativePath := url
if relativePath == "" {
relativePath = common.DefaultServiceRoot
}
return c.runRequestWithHeaders(http.MethodGet, relativePath, nil, customHeaders)
}
// Post performs a Post request against the Redfish service.
func (c *APIClient) Post(url string, payload interface{}) (*http.Response, error) {
return c.PostWithHeaders(url, payload, nil)
}
// PostWithHeaders performs a Post request against the Redfish service but allowing custom headers
func (c *APIClient) PostWithHeaders(url string, payload interface{}, customHeaders map[string]string) (*http.Response, error) {
return c.runRequestWithHeaders(http.MethodPost, url, payload, customHeaders)
}
// PostMultipart performs a Post request against the Redfish service with multipart payload.
func (c *APIClient) PostMultipart(url string, payload map[string]io.Reader) (*http.Response, error) {
return c.PostMultipartWithHeaders(url, payload, nil)
}
// PostMultipartWithHeadersperforms a Post request against the Redfish service with multipart payload but allowing custom headers
func (c *APIClient) PostMultipartWithHeaders(url string, payload map[string]io.Reader, customHeaders map[string]string) (*http.Response, error) {
return c.runRequestWithMultipartPayloadWithHeaders(http.MethodPost, url, payload, customHeaders)
}
// Put performs a Put request against the Redfish service.
func (c *APIClient) Put(url string, payload interface{}) (*http.Response, error) {
return c.PutWithHeaders(url, payload, nil)
}
// PutWithHeaders performs a Put request against the Redfish service but allowing custom headers
func (c *APIClient) PutWithHeaders(url string, payload interface{}, customHeaders map[string]string) (*http.Response, error) {
return c.runRequestWithHeaders(http.MethodPut, url, payload, customHeaders)
}
// Patch performs a Patch request against the Redfish service.
func (c *APIClient) Patch(url string, payload interface{}) (*http.Response, error) {
return c.PatchWithHeaders(url, payload, nil)
}
// PatchWithHeaders performs a Patch request against the Redfish service but allowing custom headers
func (c *APIClient) PatchWithHeaders(url string, payload interface{}, customHeaders map[string]string) (*http.Response, error) {
return c.runRequestWithHeaders(http.MethodPatch, url, payload, customHeaders)
}
// Delete performs a Delete request against the Redfish service
func (c *APIClient) Delete(url string) (*http.Response, error) {
return c.DeleteWithHeaders(url, nil)
}
// DeleteWithHeaders performs a Delete request against the Redfish service but allowing custom headers
func (c *APIClient) DeleteWithHeaders(url string, customHeaders map[string]string) (*http.Response, error) {
resp, err := c.runRequestWithHeaders(http.MethodDelete, url, nil, customHeaders)
if err != nil {
return nil, err
}
if resp != nil && resp.Body != nil {
resp.Body.Close()
}
return resp, nil
}
// runRequestWithHeaders performs JSON REST calls but allowing custom headers
func (c *APIClient) runRequestWithHeaders(method, url string, payload interface{}, customHeaders map[string]string) (*http.Response, error) {
if url == "" {
return nil, fmt.Errorf("unable to execute request, no target provided")
}
var payloadBuffer io.ReadSeeker
if payload != nil {
body, err := json.Marshal(payload)
if err != nil {
return nil, err
}
payloadBuffer = bytes.NewReader(body)
}
return c.runRawRequestWithHeaders(method, url, payloadBuffer, applicationJSON, customHeaders)
}
// runRequestWithMultipartPayloadWithHeaders performs REST calls with a multipart payload but allowing custom headers
func (c *APIClient) runRequestWithMultipartPayloadWithHeaders(method, url string, payload map[string]io.Reader, customHeaders map[string]string) (*http.Response, error) {
if url == "" {
return nil, fmt.Errorf("unable to execute request, no target provided")
}
var payloadBuffer bytes.Buffer
var err error
payloadWriter := multipart.NewWriter(&payloadBuffer)
for key, reader := range payload {
var partWriter io.Writer
if file, ok := reader.(*os.File); ok {
// Add a file stream
if partWriter, err = payloadWriter.CreateFormFile(key, filepath.Base(file.Name())); err != nil {
return nil, err
}
} else {
// Add other fields
if partWriter, err = createFormField(key, payloadWriter); err != nil {
return nil, err
}
}
if _, err = io.Copy(partWriter, reader); err != nil {
return nil, err
}
}
payloadWriter.Close()
return c.runRawRequestWithHeaders(method, url, bytes.NewReader(payloadBuffer.Bytes()), payloadWriter.FormDataContentType(), customHeaders)
}
var quoteEscaper = strings.NewReplacer("\\", "\\\\", `"`, "\\\"")
func escapeQuotes(s string) string {
return quoteEscaper.Replace(s)
}
// createFormField create form field with Content-Type
func createFormField(fieldname string, w *multipart.Writer) (io.Writer, error) {
h := make(textproto.MIMEHeader)
h.Set("Content-Disposition",
fmt.Sprintf(`form-data; name=%q`, escapeQuotes(fieldname)))
h.Set("Content-Type", "application/json")
return w.CreatePart(h)
}
// runRawRequest actually performs the REST calls
func (c *APIClient) runRawRequest(method, url string, payloadBuffer io.ReadSeeker, contentType string) (*http.Response, error) {
return c.runRawRequestWithHeaders(method, url, payloadBuffer, contentType, nil)
}
// RunRawRequestWithHeaders actually performs the REST calls but allowing custom headers
func (c *APIClient) RunRawRequestWithHeaders(method, url string, payloadBuffer io.ReadSeeker, contentType string, customHeaders map[string]string) (*http.Response, error) {
return c.runRawRequestWithHeaders(method, url, payloadBuffer, contentType, customHeaders)
}
// acquireSemaphore blocks until either the http concurrency semaphore is acquired or the context is cancelled
func (c *APIClient) acquireSemaphore() error {
select {
case <-c.ctx.Done():
return c.ctx.Err()
case c.sem <- true:
return nil
}
}
// releaseSemaphore releases the http concurrency semaphore
func (c *APIClient) releaseSemaphore() {
<-c.sem
}
// runRawRequestWithHeaders actually performs the REST calls but allowing custom headers
func (c *APIClient) runRawRequestWithHeaders(method, url string, payloadBuffer io.ReadSeeker, contentType string, customHeaders map[string]string) (*http.Response, error) {
if url == "" {
return nil, common.ConstructError(0, []byte("unable to execute request, no target provided"))
}
endpoint := fmt.Sprintf("%s%s", c.endpoint, url)
req, err := http.NewRequestWithContext(c.ctx, method, endpoint, payloadBuffer)
if err != nil {
return nil, err
}
// Add common headers
req.Header.Set("User-Agent", userAgent)
req.Header.Set("Accept", applicationJSON)
// Add custom headers
for k, v := range customHeaders {
if k == "" && v == "" { // Quick check to avoid empty headers
continue
}
// Set Content-Length custom headers on the request
// since its ignored when set using Header.Set()
if strings.EqualFold("Content-Length", k) {
req.ContentLength, err = strconv.ParseInt(v, 10, 64) // base 10, 64 bit
if err != nil {
return nil, common.ConstructError(0, []byte("error parsing custom Content-Length header"))
}
continue
}
req.Header.Set(k, v)
}
// Add content info if present
if contentType != "" {
req.Header.Set("Content-Type", contentType)
}
// Add auth info if authenticated
if c.auth != nil {
if c.auth.Token != "" {
req.Header.Set("X-Auth-Token", c.auth.Token)
} else if c.auth.BasicAuth && c.auth.Username != "" && c.auth.Password != "" {
encodedAuth := base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%v:%v", c.auth.Username, c.auth.Password)))
req.Header.Set("Authorization", fmt.Sprintf("Basic %v", encodedAuth))
}
}
req.Close = true
if c.keepAlive {
req.Close = false
req.Header.Add("Connection", "keep-alive")
}
// Dump request if needed.
if c.dumpWriter != nil {
if err := c.dumpRequest(req); err != nil {
return nil, err
}
}
if err := c.acquireSemaphore(); err != nil {
return nil, err
}
resp, err := c.HTTPClient.Do(req)
c.releaseSemaphore()
if err != nil {
return nil, err
}
// Dump response if needed.
if c.dumpWriter != nil {
if err := c.dumpResponse(resp); err != nil {
defer resp.Body.Close()
return nil, err
}
}
if resp.StatusCode != 200 && resp.StatusCode != 201 && resp.StatusCode != 202 && resp.StatusCode != 204 {
payload, err := io.ReadAll(resp.Body)
if err != nil {
return nil, common.ConstructError(0, []byte(err.Error()))
}
defer resp.Body.Close()
return nil, common.ConstructError(resp.StatusCode, payload)
}
return resp, err
}
// dumpRequest writes outgoing client requests to dumpWriter
func (c *APIClient) dumpRequest(req *http.Request) error {
d, err := httputil.DumpRequestOut(req, true)
if err != nil {
return common.ConstructError(0, []byte(err.Error()))
}
d = append(d, '\n')
_, err = c.dumpWriter.Write(d)
if err != nil {
panic(err)
}
return nil
}
// dumpRequest writes incoming responses to dumpWriter
func (c *APIClient) dumpResponse(resp *http.Response) error {
d, err := httputil.DumpResponse(resp, true)
if err != nil {
return common.ConstructError(0, []byte(err.Error()))
}
d = append(d, '\n')
_, err = c.dumpWriter.Write(d)
if err != nil {
panic(err)
}
return nil
}
// Logout will delete any active session. Useful to defer logout when creating
// a new connection.
func (c *APIClient) Logout() {
if c != nil && c.Service != nil && c.auth != nil {
_ = c.Service.DeleteSession(c.auth.Session)
c.HTTPClient.CloseIdleConnections()
}
}
// SetDumpWriter sets the client the DumpWriter dynamically
func (c *APIClient) SetDumpWriter(writer io.Writer) {
c.dumpWriter = writer
}