-
Notifications
You must be signed in to change notification settings - Fork 22
/
nginx.go
1767 lines (1514 loc) · 50.6 KB
/
nginx.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
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package client
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"reflect"
"slices"
"strings"
"time"
)
const (
// APIVersion is the default version of NGINX Plus API supported by the client.
APIVersion = 9
pathNotFoundCode = "PathNotFound"
streamContext = true
httpContext = false
defaultServerPort = "80"
)
var (
supportedAPIVersions = versions{4, 5, 6, 7, 8, 9}
// Default values for servers in Upstreams.
defaultMaxConns = 0
defaultMaxFails = 1
defaultFailTimeout = "10s"
defaultSlowStart = "0s"
defaultBackup = false
defaultDown = false
defaultWeight = 1
)
// ErrUnsupportedVer means that client's API version is not supported by NGINX plus API
var ErrUnsupportedVer = errors.New("API version of the client is not supported by running NGINX Plus")
// NginxClient lets you access NGINX Plus API.
type NginxClient struct {
apiVersion int
apiEndpoint string
httpClient *http.Client
checkAPI bool
}
type Option func(*NginxClient)
type versions []int
// UpstreamServer lets you configure HTTP upstreams.
type UpstreamServer struct {
ID int `json:"id,omitempty"`
Server string `json:"server"`
MaxConns *int `json:"max_conns,omitempty"`
MaxFails *int `json:"max_fails,omitempty"`
FailTimeout string `json:"fail_timeout,omitempty"`
SlowStart string `json:"slow_start,omitempty"`
Route string `json:"route,omitempty"`
Backup *bool `json:"backup,omitempty"`
Down *bool `json:"down,omitempty"`
Drain bool `json:"drain,omitempty"`
Weight *int `json:"weight,omitempty"`
Service string `json:"service,omitempty"`
}
// StreamUpstreamServer lets you configure Stream upstreams.
type StreamUpstreamServer struct {
ID int `json:"id,omitempty"`
Server string `json:"server"`
MaxConns *int `json:"max_conns,omitempty"`
MaxFails *int `json:"max_fails,omitempty"`
FailTimeout string `json:"fail_timeout,omitempty"`
SlowStart string `json:"slow_start,omitempty"`
Backup *bool `json:"backup,omitempty"`
Down *bool `json:"down,omitempty"`
Weight *int `json:"weight,omitempty"`
Service string `json:"service,omitempty"`
}
type apiErrorResponse struct {
Error apiError
RequestID string `json:"request_id"`
Href string
}
func (resp *apiErrorResponse) toString() string {
return fmt.Sprintf("error.status=%v; error.text=%v; error.code=%v; request_id=%v; href=%v",
resp.Error.Status, resp.Error.Text, resp.Error.Code, resp.RequestID, resp.Href)
}
type apiError struct {
Status int
Text string
Code string
}
type internalError struct {
apiError
err string
}
// Error allows internalError to match the Error interface.
func (internalError *internalError) Error() string {
return internalError.err
}
// Wrap is a way of including current context while preserving previous error information,
// similar to `return fmt.Errorf("error doing foo, err: %v", err)` but for our internalError type.
func (internalError *internalError) Wrap(err string) *internalError {
internalError.err = fmt.Sprintf("%v. %v", err, internalError.err)
return internalError
}
// Stats represents NGINX Plus stats fetched from the NGINX Plus API.
// https://nginx.org/en/docs/http/ngx_http_api_module.html
type Stats struct {
NginxInfo NginxInfo
Caches Caches
Processes Processes
Connections Connections
Slabs Slabs
HTTPRequests HTTPRequests
SSL SSL
ServerZones ServerZones
Upstreams Upstreams
StreamServerZones StreamServerZones
StreamUpstreams StreamUpstreams
StreamZoneSync *StreamZoneSync
LocationZones LocationZones
Resolvers Resolvers
HTTPLimitRequests HTTPLimitRequests
HTTPLimitConnections HTTPLimitConnections
StreamLimitConnections StreamLimitConnections
Workers []*Workers
}
// NginxInfo contains general information about NGINX Plus.
type NginxInfo struct {
Version string
Build string
Address string
Generation uint64
LoadTimestamp string `json:"load_timestamp"`
Timestamp string
ProcessID uint64 `json:"pid"`
ParentProcessID uint64 `json:"ppid"`
}
// Caches is a map of cache stats by cache zone
type Caches = map[string]HTTPCache
// HTTPCache represents a zone's HTTP Cache
type HTTPCache struct {
Size uint64
MaxSize uint64 `json:"max_size"`
Cold bool
Hit CacheStats
Stale CacheStats
Updating CacheStats
Revalidated CacheStats
Miss CacheStats
Expired ExtendedCacheStats
Bypass ExtendedCacheStats
}
// CacheStats are basic cache stats.
type CacheStats struct {
Responses uint64
Bytes uint64
}
// ExtendedCacheStats are extended cache stats.
type ExtendedCacheStats struct {
CacheStats
ResponsesWritten uint64 `json:"responses_written"`
BytesWritten uint64 `json:"bytes_written"`
}
// Connections represents connection related stats.
type Connections struct {
Accepted uint64
Dropped uint64
Active uint64
Idle uint64
}
// Slabs is map of slab stats by zone name.
type Slabs map[string]Slab
// Slab represents slab related stats.
type Slab struct {
Pages Pages
Slots Slots
}
// Pages represents the slab memory usage stats.
type Pages struct {
Used uint64
Free uint64
}
// Slots is a map of slots by slot size
type Slots map[string]Slot
// Slot represents slot related stats.
type Slot struct {
Used uint64
Free uint64
Reqs uint64
Fails uint64
}
// HTTPRequests represents HTTP request related stats.
type HTTPRequests struct {
Total uint64
Current uint64
}
// SSL represents SSL related stats.
type SSL struct {
Handshakes uint64
HandshakesFailed uint64 `json:"handshakes_failed"`
SessionReuses uint64 `json:"session_reuses"`
NoCommonProtocol uint64 `json:"no_common_protocol"`
NoCommonCipher uint64 `json:"no_common_cipher"`
HandshakeTimeout uint64 `json:"handshake_timeout"`
PeerRejectedCert uint64 `json:"peer_rejected_cert"`
VerifyFailures VerifyFailures `json:"verify_failures"`
}
type VerifyFailures struct {
NoCert uint64 `json:"no_cert"`
ExpiredCert uint64 `json:"expired_cert"`
RevokedCert uint64 `json:"revoked_cert"`
HostnameMismatch uint64 `json:"hostname_mismatch"`
Other uint64 `json:"other"`
}
// ServerZones is map of server zone stats by zone name
type ServerZones map[string]ServerZone
// ServerZone represents server zone related stats.
type ServerZone struct {
Processing uint64
Requests uint64
Responses Responses
Discarded uint64
Received uint64
Sent uint64
SSL SSL
}
// StreamServerZones is map of stream server zone stats by zone name.
type StreamServerZones map[string]StreamServerZone
// StreamServerZone represents stream server zone related stats.
type StreamServerZone struct {
Processing uint64
Connections uint64
Sessions Sessions
Discarded uint64
Received uint64
Sent uint64
SSL SSL
}
// StreamZoneSync represents the sync information per each shared memory zone and the sync information per node in a cluster
type StreamZoneSync struct {
Zones map[string]SyncZone
Status StreamZoneSyncStatus
}
// SyncZone represents the synchronization status of a shared memory zone
type SyncZone struct {
RecordsPending uint64 `json:"records_pending"`
RecordsTotal uint64 `json:"records_total"`
}
// StreamZoneSyncStatus represents the status of a shared memory zone
type StreamZoneSyncStatus struct {
BytesIn uint64 `json:"bytes_in"`
MsgsIn uint64 `json:"msgs_in"`
MsgsOut uint64 `json:"msgs_out"`
BytesOut uint64 `json:"bytes_out"`
NodesOnline uint64 `json:"nodes_online"`
}
// Responses represents HTTP response related stats.
type Responses struct {
Codes HTTPCodes
Responses1xx uint64 `json:"1xx"`
Responses2xx uint64 `json:"2xx"`
Responses3xx uint64 `json:"3xx"`
Responses4xx uint64 `json:"4xx"`
Responses5xx uint64 `json:"5xx"`
Total uint64
}
// HTTPCodes represents HTTP response codes
type HTTPCodes struct {
HTTPContinue uint64 `json:"100,omitempty"`
HTTPSwitchingProtocols uint64 `json:"101,omitempty"`
HTTPProcessing uint64 `json:"102,omitempty"`
HTTPOk uint64 `json:"200,omitempty"`
HTTPCreated uint64 `json:"201,omitempty"`
HTTPAccepted uint64 `json:"202,omitempty"`
HTTPNoContent uint64 `json:"204,omitempty"`
HTTPPartialContent uint64 `json:"206,omitempty"`
HTTPSpecialResponse uint64 `json:"300,omitempty"`
HTTPMovedPermanently uint64 `json:"301,omitempty"`
HTTPMovedTemporarily uint64 `json:"302,omitempty"`
HTTPSeeOther uint64 `json:"303,omitempty"`
HTTPNotModified uint64 `json:"304,omitempty"`
HTTPTemporaryRedirect uint64 `json:"307,omitempty"`
HTTPBadRequest uint64 `json:"400,omitempty"`
HTTPUnauthorized uint64 `json:"401,omitempty"`
HTTPForbidden uint64 `json:"403,omitempty"`
HTTPNotFound uint64 `json:"404,omitempty"`
HTTPNotAllowed uint64 `json:"405,omitempty"`
HTTPRequestTimeOut uint64 `json:"408,omitempty"`
HTTPConflict uint64 `json:"409,omitempty"`
HTTPLengthRequired uint64 `json:"411,omitempty"`
HTTPPreconditionFailed uint64 `json:"412,omitempty"`
HTTPRequestEntityTooLarge uint64 `json:"413,omitempty"`
HTTPRequestURITooLarge uint64 `json:"414,omitempty"`
HTTPUnsupportedMediaType uint64 `json:"415,omitempty"`
HTTPRangeNotSatisfiable uint64 `json:"416,omitempty"`
HTTPTooManyRequests uint64 `json:"429,omitempty"`
HTTPClose uint64 `json:"444,omitempty"`
HTTPRequestHeaderTooLarge uint64 `json:"494,omitempty"`
HTTPSCertError uint64 `json:"495,omitempty"`
HTTPSNoCert uint64 `json:"496,omitempty"`
HTTPToHTTPS uint64 `json:"497,omitempty"`
HTTPClientClosedRequest uint64 `json:"499,omitempty"`
HTTPInternalServerError uint64 `json:"500,omitempty"`
HTTPNotImplemented uint64 `json:"501,omitempty"`
HTTPBadGateway uint64 `json:"502,omitempty"`
HTTPServiceUnavailable uint64 `json:"503,omitempty"`
HTTPGatewayTimeOut uint64 `json:"504,omitempty"`
HTTPInsufficientStorage uint64 `json:"507,omitempty"`
}
// Sessions represents stream session related stats.
type Sessions struct {
Sessions2xx uint64 `json:"2xx"`
Sessions4xx uint64 `json:"4xx"`
Sessions5xx uint64 `json:"5xx"`
Total uint64
}
// Upstreams is a map of upstream stats by upstream name.
type Upstreams map[string]Upstream
// Upstream represents upstream related stats.
type Upstream struct {
Peers []Peer
Keepalives int
Zombies int
Zone string
Queue Queue
}
// StreamUpstreams is a map of stream upstream stats by upstream name.
type StreamUpstreams map[string]StreamUpstream
// StreamUpstream represents stream upstream related stats.
type StreamUpstream struct {
Peers []StreamPeer
Zombies int
Zone string
}
// Queue represents queue related stats for an upstream.
type Queue struct {
Size int
MaxSize int `json:"max_size"`
Overflows uint64
}
// Peer represents peer (upstream server) related stats.
type Peer struct {
ID int
Server string
Service string
Name string
Backup bool
Weight int
State string
Active uint64
SSL SSL
MaxConns int `json:"max_conns"`
Requests uint64
Responses Responses
Sent uint64
Received uint64
Fails uint64
Unavail uint64
HealthChecks HealthChecks `json:"health_checks"`
Downtime uint64
Downstart string
Selected string
HeaderTime uint64 `json:"header_time"`
ResponseTime uint64 `json:"response_time"`
}
// StreamPeer represents peer (stream upstream server) related stats.
type StreamPeer struct {
ID int
Server string
Service string
Name string
Backup bool
Weight int
State string
Active uint64
SSL SSL
MaxConns int `json:"max_conns"`
Connections uint64
ConnectTime int `json:"connect_time"`
FirstByteTime int `json:"first_byte_time"`
ResponseTime uint64 `json:"response_time"`
Sent uint64
Received uint64
Fails uint64
Unavail uint64
HealthChecks HealthChecks `json:"health_checks"`
Downtime uint64
Downstart string
Selected string
}
// HealthChecks represents health check related stats for a peer.
type HealthChecks struct {
Checks uint64
Fails uint64
Unhealthy uint64
LastPassed bool `json:"last_passed"`
}
// LocationZones represents location_zones related stats
type LocationZones map[string]LocationZone
// Resolvers represents resolvers related stats
type Resolvers map[string]Resolver
// LocationZone represents location_zones related stats
type LocationZone struct {
Requests int64
Responses Responses
Discarded int64
Received int64
Sent int64
}
// Resolver represents resolvers related stats
type Resolver struct {
Requests ResolverRequests `json:"requests"`
Responses ResolverResponses `json:"responses"`
}
// ResolverRequests represents resolver requests
type ResolverRequests struct {
Name int64
Srv int64
Addr int64
}
// ResolverResponses represents resolver responses
type ResolverResponses struct {
Noerror int64
Formerr int64
Servfail int64
Nxdomain int64
Notimp int64
Refused int64
Timedout int64
Unknown int64
}
// Processes represents processes related stats
type Processes struct {
Respawned int64
}
// HTTPLimitRequest represents HTTP Requests Rate Limiting
type HTTPLimitRequest struct {
Passed uint64
Delayed uint64
Rejected uint64
DelayedDryRun uint64 `json:"delayed_dry_run"`
RejectedDryRun uint64 `json:"rejected_dry_run"`
}
// HTTPLimitRequests represents limit requests related stats
type HTTPLimitRequests map[string]HTTPLimitRequest
// LimitConnection represents Connections Limiting
type LimitConnection struct {
Passed uint64
Rejected uint64
RejectedDryRun uint64 `json:"rejected_dry_run"`
}
// HTTPLimitConnections represents limit connections related stats
type HTTPLimitConnections map[string]LimitConnection
// StreamLimitConnections represents limit connections related stats
type StreamLimitConnections map[string]LimitConnection
// Workers represents worker connections related stats
type Workers struct {
ID int
ProcessID uint64 `json:"pid"`
HTTP WorkersHTTP `json:"http"`
Connections Connections
}
// WorkersHTTP represents HTTP worker connections
type WorkersHTTP struct {
HTTPRequests HTTPRequests `json:"requests"`
}
// WithHTTPClient sets the HTTP client to use for accessing the API.
func WithHTTPClient(httpClient *http.Client) Option {
return func(o *NginxClient) {
o.httpClient = httpClient
}
}
// WithAPIVersion sets the API version to use for accessing the API.
func WithAPIVersion(apiVersion int) Option {
return func(o *NginxClient) {
o.apiVersion = apiVersion
}
}
// WithCheckAPI sets the flag to check the API version of the server.
func WithCheckAPI() Option {
return func(o *NginxClient) {
o.checkAPI = true
}
}
// NewNginxClient creates a new NginxClient.
func NewNginxClient(apiEndpoint string, opts ...Option) (*NginxClient, error) {
c := &NginxClient{
httpClient: http.DefaultClient,
apiEndpoint: apiEndpoint,
apiVersion: APIVersion,
checkAPI: false,
}
for _, opt := range opts {
opt(c)
}
if c.httpClient == nil {
return nil, fmt.Errorf("http client is not set")
}
if !versionSupported(c.apiVersion) {
return nil, fmt.Errorf("API version %v is not supported by the client", c.apiVersion)
}
if c.checkAPI {
versions, err := getAPIVersions(c.httpClient, apiEndpoint)
if err != nil {
return nil, fmt.Errorf("error accessing the API: %w", err)
}
found := false
for _, v := range *versions {
if v == c.apiVersion {
found = true
break
}
}
if !found {
return nil, fmt.Errorf("API version %v is not supported by the server", c.apiVersion)
}
}
return c, nil
}
func versionSupported(n int) bool {
for _, version := range supportedAPIVersions {
if n == version {
return true
}
}
return false
}
func getAPIVersions(httpClient *http.Client, endpoint string) (*versions, error) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
if err != nil {
return nil, fmt.Errorf("failed to create a get request: %w", err)
}
resp, err := httpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("%v is not accessible: %w", endpoint, err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("%v is not accessible: expected %v response, got %v", endpoint, http.StatusOK, resp.StatusCode)
}
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("error while reading body of the response: %w", err)
}
var vers versions
err = json.Unmarshal(body, &vers)
if err != nil {
return nil, fmt.Errorf("error unmarshalling versions, got %q response: %w", string(body), err)
}
return &vers, nil
}
func createResponseMismatchError(respBody io.ReadCloser) *internalError {
apiErrResp, err := readAPIErrorResponse(respBody)
if err != nil {
return &internalError{
err: fmt.Sprintf("failed to read the response body: %v", err),
}
}
return &internalError{
err: apiErrResp.toString(),
apiError: apiErrResp.Error,
}
}
func readAPIErrorResponse(respBody io.ReadCloser) (*apiErrorResponse, error) {
body, err := io.ReadAll(respBody)
if err != nil {
return nil, fmt.Errorf("failed to read the response body: %w", err)
}
var apiErr apiErrorResponse
err = json.Unmarshal(body, &apiErr)
if err != nil {
return nil, fmt.Errorf("error unmarshalling apiErrorResponse: got %q response: %w", string(body), err)
}
return &apiErr, nil
}
// CheckIfUpstreamExists checks if the upstream exists in NGINX. If the upstream doesn't exist, it returns the error.
func (client *NginxClient) CheckIfUpstreamExists(upstream string) error {
_, err := client.GetHTTPServers(upstream)
return err
}
// GetHTTPServers returns the servers of the upstream from NGINX.
func (client *NginxClient) GetHTTPServers(upstream string) ([]UpstreamServer, error) {
path := fmt.Sprintf("http/upstreams/%v/servers", upstream)
var servers []UpstreamServer
err := client.get(path, &servers)
if err != nil {
return nil, fmt.Errorf("failed to get the HTTP servers of upstream %v: %w", upstream, err)
}
return servers, nil
}
// AddHTTPServer adds the server to the upstream.
func (client *NginxClient) AddHTTPServer(upstream string, server UpstreamServer) error {
id, err := client.getIDOfHTTPServer(upstream, server.Server)
if err != nil {
return fmt.Errorf("failed to add %v server to %v upstream: %w", server.Server, upstream, err)
}
if id != -1 {
return fmt.Errorf("failed to add %v server to %v upstream: server already exists", server.Server, upstream)
}
path := fmt.Sprintf("http/upstreams/%v/servers/", upstream)
err = client.post(path, &server)
if err != nil {
return fmt.Errorf("failed to add %v server to %v upstream: %w", server.Server, upstream, err)
}
return nil
}
// DeleteHTTPServer the server from the upstream.
func (client *NginxClient) DeleteHTTPServer(upstream string, server string) error {
id, err := client.getIDOfHTTPServer(upstream, server)
if err != nil {
return fmt.Errorf("failed to remove %v server from %v upstream: %w", server, upstream, err)
}
if id == -1 {
return fmt.Errorf("failed to remove %v server from %v upstream: server doesn't exist", server, upstream)
}
path := fmt.Sprintf("http/upstreams/%v/servers/%v", upstream, id)
err = client.delete(path, http.StatusOK)
if err != nil {
return fmt.Errorf("failed to remove %v server from %v upstream: %w", server, upstream, err)
}
return nil
}
// UpdateHTTPServers updates the servers of the upstream.
// Servers that are in the slice, but don't exist in NGINX will be added to NGINX.
// Servers that aren't in the slice, but exist in NGINX, will be removed from NGINX.
// Servers that are in the slice and exist in NGINX, but have different parameters, will be updated.
func (client *NginxClient) UpdateHTTPServers(upstream string, servers []UpstreamServer) (added []UpstreamServer, deleted []UpstreamServer, updated []UpstreamServer, err error) {
serversInNginx, err := client.GetHTTPServers(upstream)
if err != nil {
return nil, nil, nil, fmt.Errorf("failed to update servers of %v upstream: %w", upstream, err)
}
// We assume port 80 if no port is set for servers.
var formattedServers []UpstreamServer
for _, server := range servers {
server.Server = addPortToServer(server.Server)
formattedServers = append(formattedServers, server)
}
toAdd, toDelete, toUpdate := determineUpdates(formattedServers, serversInNginx)
for _, server := range toAdd {
err := client.AddHTTPServer(upstream, server)
if err != nil {
return nil, nil, nil, fmt.Errorf("failed to update servers of %v upstream: %w", upstream, err)
}
}
for _, server := range toDelete {
err := client.DeleteHTTPServer(upstream, server.Server)
if err != nil {
return nil, nil, nil, fmt.Errorf("failed to update servers of %v upstream: %w", upstream, err)
}
}
for _, server := range toUpdate {
err := client.UpdateHTTPServer(upstream, server)
if err != nil {
return nil, nil, nil, fmt.Errorf("failed to update servers of %v upstream: %w", upstream, err)
}
}
return toAdd, toDelete, toUpdate, nil
}
// haveSameParameters checks if a given server has the same parameters as a server already present in NGINX. Order matters
func haveSameParameters(newServer UpstreamServer, serverNGX UpstreamServer) bool {
newServer.ID = serverNGX.ID
if serverNGX.MaxConns != nil && newServer.MaxConns == nil {
newServer.MaxConns = &defaultMaxConns
}
if serverNGX.MaxFails != nil && newServer.MaxFails == nil {
newServer.MaxFails = &defaultMaxFails
}
if serverNGX.FailTimeout != "" && newServer.FailTimeout == "" {
newServer.FailTimeout = defaultFailTimeout
}
if serverNGX.SlowStart != "" && newServer.SlowStart == "" {
newServer.SlowStart = defaultSlowStart
}
if serverNGX.Backup != nil && newServer.Backup == nil {
newServer.Backup = &defaultBackup
}
if serverNGX.Down != nil && newServer.Down == nil {
newServer.Down = &defaultDown
}
if serverNGX.Weight != nil && newServer.Weight == nil {
newServer.Weight = &defaultWeight
}
return reflect.DeepEqual(newServer, serverNGX)
}
func determineUpdates(updatedServers []UpstreamServer, nginxServers []UpstreamServer) (toAdd []UpstreamServer, toRemove []UpstreamServer, toUpdate []UpstreamServer) {
for _, server := range updatedServers {
updateFound := false
for _, serverNGX := range nginxServers {
if server.Server == serverNGX.Server && !haveSameParameters(server, serverNGX) {
server.ID = serverNGX.ID
updateFound = true
break
}
}
if updateFound {
toUpdate = append(toUpdate, server)
}
}
for _, server := range updatedServers {
found := false
for _, serverNGX := range nginxServers {
if server.Server == serverNGX.Server {
found = true
break
}
}
if !found {
toAdd = append(toAdd, server)
}
}
for _, serverNGX := range nginxServers {
found := false
for _, server := range updatedServers {
if serverNGX.Server == server.Server {
found = true
break
}
}
if !found {
toRemove = append(toRemove, serverNGX)
}
}
return
}
func (client *NginxClient) getIDOfHTTPServer(upstream string, name string) (int, error) {
servers, err := client.GetHTTPServers(upstream)
if err != nil {
return -1, fmt.Errorf("error getting id of server %v of upstream %v: %w", name, upstream, err)
}
for _, s := range servers {
if s.Server == name {
return s.ID, nil
}
}
return -1, nil
}
func (client *NginxClient) get(path string, data interface{}) error {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
url := fmt.Sprintf("%v/%v/%v", client.apiEndpoint, client.apiVersion, path)
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return fmt.Errorf("failed to create a get request: %w", err)
}
resp, err := client.httpClient.Do(req)
if err != nil {
return fmt.Errorf("failed to get %v: %w", path, err)
}
if resp.StatusCode != http.StatusOK {
return createResponseMismatchError(resp.Body).Wrap(fmt.Sprintf(
"expected %v response, got %v",
http.StatusOK, resp.StatusCode))
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("failed to read the response body: %w", err)
}
err = json.Unmarshal(body, data)
if err != nil {
return fmt.Errorf("error unmarshaling response %q: %w", string(body), err)
}
return nil
}
func (client *NginxClient) post(path string, input interface{}) error {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
url := fmt.Sprintf("%v/%v/%v", client.apiEndpoint, client.apiVersion, path)
jsonInput, err := json.Marshal(input)
if err != nil {
return fmt.Errorf("failed to marshall input: %w", err)
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewBuffer(jsonInput))
if err != nil {
return fmt.Errorf("failed to create a post request: %w", err)
}
req.Header.Set("Content-Type", "application/json")
resp, err := client.httpClient.Do(req)
if err != nil {
return fmt.Errorf("failed to post %v: %w", path, err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusCreated {
return createResponseMismatchError(resp.Body).Wrap(fmt.Sprintf(
"expected %v response, got %v",
http.StatusCreated, resp.StatusCode))
}
return nil
}
func (client *NginxClient) delete(path string, expectedStatusCode int) error {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
path = fmt.Sprintf("%v/%v/%v/", client.apiEndpoint, client.apiVersion, path)
req, err := http.NewRequestWithContext(ctx, http.MethodDelete, path, nil)
if err != nil {
return fmt.Errorf("failed to create a delete request: %w", err)
}
resp, err := client.httpClient.Do(req)
if err != nil {
return fmt.Errorf("failed to create delete request: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != expectedStatusCode {
return createResponseMismatchError(resp.Body).Wrap(fmt.Sprintf(
"failed to complete delete request: expected %v response, got %v",
expectedStatusCode, resp.StatusCode))
}
return nil
}
func (client *NginxClient) patch(path string, input interface{}, expectedStatusCode int) error {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
path = fmt.Sprintf("%v/%v/%v/", client.apiEndpoint, client.apiVersion, path)
jsonInput, err := json.Marshal(input)
if err != nil {
return fmt.Errorf("failed to marshall input: %w", err)
}
req, err := http.NewRequestWithContext(ctx, http.MethodPatch, path, bytes.NewBuffer(jsonInput))
if err != nil {
return fmt.Errorf("failed to create a patch request: %w", err)
}
resp, err := client.httpClient.Do(req)
if err != nil {
return fmt.Errorf("failed to create patch request: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != expectedStatusCode {
return createResponseMismatchError(resp.Body).Wrap(fmt.Sprintf(
"failed to complete patch request: expected %v response, got %v",
expectedStatusCode, resp.StatusCode))
}
return nil
}
// CheckIfStreamUpstreamExists checks if the stream upstream exists in NGINX. If the upstream doesn't exist, it returns the error.
func (client *NginxClient) CheckIfStreamUpstreamExists(upstream string) error {
_, err := client.GetStreamServers(upstream)
return err
}
// GetStreamServers returns the stream servers of the upstream from NGINX.
func (client *NginxClient) GetStreamServers(upstream string) ([]StreamUpstreamServer, error) {
path := fmt.Sprintf("stream/upstreams/%v/servers", upstream)
var servers []StreamUpstreamServer
err := client.get(path, &servers)
if err != nil {
return nil, fmt.Errorf("failed to get stream servers of upstream server %v: %w", upstream, err)
}
return servers, nil
}
// AddStreamServer adds the stream server to the upstream.
func (client *NginxClient) AddStreamServer(upstream string, server StreamUpstreamServer) error {
id, err := client.getIDOfStreamServer(upstream, server.Server)
if err != nil {
return fmt.Errorf("failed to add %v stream server to %v upstream: %w", server.Server, upstream, err)
}
if id != -1 {
return fmt.Errorf("failed to add %v stream server to %v upstream: server already exists", server.Server, upstream)