File: client.go

package info (click to toggle)
golang-github-ionos-cloud-sdk-go 6.3.4-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 6,360 kB
  • sloc: sh: 35; makefile: 3
file content (1186 lines) | stat: -rw-r--r-- 32,656 bytes parent folder | download
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
/*
 * CLOUD API
 *
 *  IONOS Enterprise-grade Infrastructure as a Service (IaaS) solutions can be managed through the Cloud API, in addition or as an alternative to the \"Data Center Designer\" (DCD) browser-based tool.    Both methods employ consistent concepts and features, deliver similar power and flexibility, and can be used to perform a multitude of management tasks, including adding servers, volumes, configuring networks, and so on.
 *
 * API version: 6.0
 */

// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT.

package ionoscloud

import (
	"bytes"
	"context"
	"crypto/sha256"
	"crypto/tls"
	"crypto/x509"
	"encoding/hex"
	"encoding/json"
	"encoding/xml"
	"errors"
	"fmt"
	"io"
	"mime/multipart"
	"net"
	"net/http"
	"net/http/httputil"
	"net/url"
	"os"
	"path/filepath"
	"reflect"
	"regexp"
	"strconv"
	"strings"
	"time"
	"unicode/utf8"

	"golang.org/x/oauth2"
)

var (
	jsonCheck = regexp.MustCompile(`(?i:(?:application|text)/(?:vnd\.[^;]+\+)?json)`)
	xmlCheck  = regexp.MustCompile(`(?i:(?:application|text)/xml)`)
)

const DepthParam = "depth"

const (
	RequestStatusQueued  = "QUEUED"
	RequestStatusRunning = "RUNNING"
	RequestStatusFailed  = "FAILED"
	RequestStatusDone    = "DONE"

	Version = "6.3.4"
)

// Constants for APIs
const FilterQueryParam = "filter.%s"
const FormatStringErr = "%s %s"

// APIClient manages communication with the CLOUD API API v6.0
// In most cases there should be only one, shared, APIClient.
type APIClient struct {
	cfg    *Configuration
	common service // Reuse a single struct instead of allocating one for each service on the heap.

	// API Services

	DefaultApi *DefaultApiService

	ApplicationLoadBalancersApi *ApplicationLoadBalancersApiService

	BackupUnitsApi *BackupUnitsApiService

	ContractResourcesApi *ContractResourcesApiService

	DataCentersApi *DataCentersApiService

	FirewallRulesApi *FirewallRulesApiService

	FlowLogsApi *FlowLogsApiService

	IPBlocksApi *IPBlocksApiService

	ImagesApi *ImagesApiService

	KubernetesApi *KubernetesApiService

	LANsApi *LANsApiService

	LabelsApi *LabelsApiService

	LoadBalancersApi *LoadBalancersApiService

	LocationsApi *LocationsApiService

	NATGatewaysApi *NATGatewaysApiService

	NetworkInterfacesApi *NetworkInterfacesApiService

	NetworkLoadBalancersApi *NetworkLoadBalancersApiService

	PrivateCrossConnectsApi *PrivateCrossConnectsApiService

	RequestsApi *RequestsApiService

	SecurityGroupsApi *SecurityGroupsApiService

	ServersApi *ServersApiService

	SnapshotsApi *SnapshotsApiService

	TargetGroupsApi *TargetGroupsApiService

	TemplatesApi *TemplatesApiService

	UserManagementApi *UserManagementApiService

	UserS3KeysApi *UserS3KeysApiService

	VolumesApi *VolumesApiService
}

type service struct {
	client *APIClient
}

// NewAPIClient creates a new API client. Requires a userAgent string describing your application.
// optionally a custom http.Client to allow for advanced features such as caching.
func NewAPIClient(cfg *Configuration) *APIClient {
	if cfg.HTTPClient == nil {
		cfg.HTTPClient = http.DefaultClient
	}
	//enable certificate pinning if the env variable is set
	pkFingerprint := os.Getenv(IonosPinnedCertEnvVar)
	if pkFingerprint != "" {
		httpTransport := &http.Transport{}
		AddPinnedCert(httpTransport, pkFingerprint)
		cfg.HTTPClient.Transport = httpTransport
	}

	c := &APIClient{}
	c.cfg = cfg
	c.common.client = c

	// API Services
	c.DefaultApi = (*DefaultApiService)(&c.common)
	c.ApplicationLoadBalancersApi = (*ApplicationLoadBalancersApiService)(&c.common)
	c.BackupUnitsApi = (*BackupUnitsApiService)(&c.common)
	c.ContractResourcesApi = (*ContractResourcesApiService)(&c.common)
	c.DataCentersApi = (*DataCentersApiService)(&c.common)
	c.FirewallRulesApi = (*FirewallRulesApiService)(&c.common)
	c.FlowLogsApi = (*FlowLogsApiService)(&c.common)
	c.IPBlocksApi = (*IPBlocksApiService)(&c.common)
	c.ImagesApi = (*ImagesApiService)(&c.common)
	c.KubernetesApi = (*KubernetesApiService)(&c.common)
	c.LANsApi = (*LANsApiService)(&c.common)
	c.LabelsApi = (*LabelsApiService)(&c.common)
	c.LoadBalancersApi = (*LoadBalancersApiService)(&c.common)
	c.LocationsApi = (*LocationsApiService)(&c.common)
	c.NATGatewaysApi = (*NATGatewaysApiService)(&c.common)
	c.NetworkInterfacesApi = (*NetworkInterfacesApiService)(&c.common)
	c.NetworkLoadBalancersApi = (*NetworkLoadBalancersApiService)(&c.common)
	c.PrivateCrossConnectsApi = (*PrivateCrossConnectsApiService)(&c.common)
	c.RequestsApi = (*RequestsApiService)(&c.common)
	c.SecurityGroupsApi = (*SecurityGroupsApiService)(&c.common)
	c.ServersApi = (*ServersApiService)(&c.common)
	c.SnapshotsApi = (*SnapshotsApiService)(&c.common)
	c.TargetGroupsApi = (*TargetGroupsApiService)(&c.common)
	c.TemplatesApi = (*TemplatesApiService)(&c.common)
	c.UserManagementApi = (*UserManagementApiService)(&c.common)
	c.UserS3KeysApi = (*UserS3KeysApiService)(&c.common)
	c.VolumesApi = (*VolumesApiService)(&c.common)

	return c
}

// AddPinnedCert - enables pinning of the sha256 public fingerprint to the http client's transport
func AddPinnedCert(transport *http.Transport, pkFingerprint string) {
	if pkFingerprint != "" {
		transport.DialTLSContext = addPinnedCertVerification([]byte(pkFingerprint), new(tls.Config))
	}
}

// TLSDial can be assigned to a http.Transport's DialTLS field.
type TLSDial func(ctx context.Context, network, addr string) (net.Conn, error)

// AddPinnedCertVerification returns a TLSDial function which checks that
// the remote server provides a certificate whose SHA256 fingerprint matches
// the provided value.
//
// The returned dialer function can be plugged into a http.Transport's DialTLS
// field to allow for certificate pinning.
func addPinnedCertVerification(fingerprint []byte, tlsConfig *tls.Config) TLSDial {
	return func(ctx context.Context, network, addr string) (net.Conn, error) {
		//fingerprints can be added with ':', we need to trim
		fingerprint = bytes.ReplaceAll(fingerprint, []byte(":"), []byte(""))
		fingerprint = bytes.ReplaceAll(fingerprint, []byte(" "), []byte(""))
		//we are manually checking a certificate, so we need to enable insecure
		tlsConfig.InsecureSkipVerify = true

		// Dial the connection to get certificates to check
		conn, err := tls.Dial(network, addr, tlsConfig)
		if err != nil {
			return nil, err
		}

		if err := verifyPinnedCert(fingerprint, conn.ConnectionState().PeerCertificates); err != nil {
			_ = conn.Close()
			return nil, err
		}

		return conn, nil
	}
}

// verifyPinnedCert iterates the list of peer certificates and attempts to
// locate a certificate that is not a CA and whose public key fingerprint matches pkFingerprint.
func verifyPinnedCert(pkFingerprint []byte, peerCerts []*x509.Certificate) error {
	for _, cert := range peerCerts {
		fingerprint := sha256.Sum256(cert.Raw)

		var bytesFingerPrint = make([]byte, hex.EncodedLen(len(fingerprint[:])))
		hex.Encode(bytesFingerPrint, fingerprint[:])

		// we have a match, and it's not an authority certificate
		if cert.IsCA == false && bytes.EqualFold(bytesFingerPrint, pkFingerprint) {
			return nil
		}
	}

	return fmt.Errorf("remote server presented a certificate which does not match the provided fingerprint")
}

func atoi(in string) (int, error) {
	return strconv.Atoi(in)
}

// selectHeaderContentType select a content type from the available list.
func selectHeaderContentType(contentTypes []string) string {
	if len(contentTypes) == 0 {
		return ""
	}
	if contains(contentTypes, "application/json") {
		return "application/json"
	}
	return contentTypes[0] // use the first content type specified in 'consumes'
}

// selectHeaderAccept join all accept types and return
func selectHeaderAccept(accepts []string) string {
	if len(accepts) == 0 {
		return ""
	}

	if contains(accepts, "application/json") {
		return "application/json"
	}

	return strings.Join(accepts, ",")
}

// contains is a case insenstive match, finding needle in a haystack
func contains(haystack []string, needle string) bool {
	for _, a := range haystack {
		if strings.ToLower(a) == strings.ToLower(needle) {
			return true
		}
	}
	return false
}

// Verify optional parameters are of the correct type.
func typeCheckParameter(obj interface{}, expected string, name string) error {
	// Make sure there is an object.
	if obj == nil {
		return nil
	}

	// Check the type is as expected.
	if reflect.TypeOf(obj).String() != expected {
		return fmt.Errorf("Expected %s to be of type %s but received %s.", name, expected, reflect.TypeOf(obj).String())
	}
	return nil
}

// parameterToString convert interface{} parameters to string, using a delimiter if format is provided.
func parameterToString(obj interface{}, collectionFormat string) string {
	var delimiter string

	switch collectionFormat {
	case "pipes":
		delimiter = "|"
	case "ssv":
		delimiter = " "
	case "tsv":
		delimiter = "\t"
	case "csv":
		delimiter = ","
	}

	if reflect.TypeOf(obj).Kind() == reflect.Slice {
		return strings.Trim(strings.Replace(fmt.Sprint(obj), " ", delimiter, -1), "[]")
	} else if t, ok := obj.(time.Time); ok {
		return t.Format(time.RFC3339)
	}

	return fmt.Sprintf("%v", obj)
}

// helper for converting interface{} parameters to json strings
func parameterToJson(obj interface{}) (string, error) {
	jsonBuf, err := json.Marshal(obj)
	if err != nil {
		return "", err
	}
	return string(jsonBuf), err
}

// callAPI do the request.
func (c *APIClient) callAPI(request *http.Request) (*http.Response, time.Duration, error) {
	retryCount := 0

	var resp *http.Response
	var httpRequestTime time.Duration
	var err error

	for {

		retryCount++

		/* we need to clone the request with every retry time because Body closes after the request */
		var clonedRequest *http.Request = request.Clone(request.Context())
		if request.Body != nil {
			clonedRequest.Body, err = request.GetBody()
			if err != nil {
				return nil, httpRequestTime, err
			}
		}

		if c.cfg.Debug || c.cfg.LogLevel.Satisfies(Debug) {
			logRequest := request.Clone(request.Context())

			// Remove the Authorization header if Debug is enabled (but not in Trace mode)
			if !c.cfg.LogLevel.Satisfies(Trace) {
				logRequest.Header.Del("Authorization")
			}

			dump, err := httputil.DumpRequestOut(logRequest, true)
			if err == nil {
				c.cfg.Logger.Printf(" DumpRequestOut : %s\n", string(dump))
			} else {
				c.cfg.Logger.Printf(" DumpRequestOut err: %+v", err)
			}
			c.cfg.Logger.Printf("\n try no: %d\n", retryCount)
		}

		httpRequestStartTime := time.Now()
		clonedRequest.Close = true
		resp, err = c.cfg.HTTPClient.Do(clonedRequest)
		httpRequestTime = time.Since(httpRequestStartTime)
		if err != nil {
			return resp, httpRequestTime, err
		}

		if c.cfg.Debug || c.cfg.LogLevel.Satisfies(Debug) {
			dump, err := httputil.DumpResponse(resp, true)
			if err == nil {
				c.cfg.Logger.Printf("\n DumpResponse : %s\n", string(dump))
			} else {
				c.cfg.Logger.Printf(" DumpResponse err %+v", err)
			}
		}

		var backoffTime time.Duration

		switch resp.StatusCode {
		case http.StatusServiceUnavailable,
			http.StatusGatewayTimeout,
			http.StatusBadGateway:
			if request.Method == http.MethodPost {
				return resp, httpRequestTime, err
			}
			backoffTime = c.GetConfig().WaitTime

		case http.StatusTooManyRequests:
			if retryAfterSeconds := resp.Header.Get("Retry-After"); retryAfterSeconds != "" {
				waitTime, err := time.ParseDuration(retryAfterSeconds + "s")
				if err != nil {
					return resp, httpRequestTime, err
				}
				backoffTime = waitTime
			} else {
				backoffTime = c.GetConfig().WaitTime
			}
		default:
			return resp, httpRequestTime, err

		}

		if retryCount >= c.GetConfig().MaxRetries {
			if c.cfg.Debug || c.cfg.LogLevel.Satisfies(Debug) {
				c.cfg.Logger.Printf(" Number of maximum retries exceeded (%d retries)\n", c.cfg.MaxRetries)
			}
			break
		} else {
			c.backOff(request.Context(), backoffTime)
		}
	}

	return resp, httpRequestTime, err
}

func (c *APIClient) backOff(ctx context.Context, t time.Duration) {
	if t > c.GetConfig().MaxWaitTime {
		t = c.GetConfig().MaxWaitTime
	}
	if c.cfg.Debug || c.cfg.LogLevel.Satisfies(Debug) {
		c.cfg.Logger.Printf(" sleeping %s before retrying request\n", t.String())
	}

	if t <= 0 {
		return
	}

	timer := time.NewTimer(t)
	defer timer.Stop()

	select {
	case <-ctx.Done():
	case <-timer.C:
	}
}

// Allow modification of underlying config for alternate implementations and testing
// Caution: modifying the configuration while live can cause data races and potentially unwanted behavior
func (c *APIClient) GetConfig() *Configuration {
	return c.cfg
}

// prepareRequest build the request
func (c *APIClient) prepareRequest(
	ctx context.Context,
	path string, method string,
	postBody interface{},
	headerParams map[string]string,
	queryParams url.Values,
	formParams url.Values,
	formFileName string,
	fileName string,
	fileBytes []byte) (localVarRequest *http.Request, err error) {

	var body *bytes.Buffer

	val, isSetInEnv := os.LookupEnv(IonosContractNumber)
	_, isSetInMap := headerParams["X-Contract-Number"]
	if headerParams == nil {
		headerParams = make(map[string]string)
	}
	if !isSetInMap && isSetInEnv {
		headerParams["X-Contract-Number"] = val
	}

	// Detect postBody type and post.
	if postBody != nil {
		contentType := headerParams["Content-Type"]
		if contentType == "" {
			contentType = detectContentType(postBody)
			headerParams["Content-Type"] = contentType
		}

		body, err = setBody(postBody, contentType)
		if err != nil {
			return nil, err
		}
	}

	// add form parameters and file if available.
	if strings.HasPrefix(headerParams["Content-Type"], "multipart/form-data") && len(formParams) > 0 || (len(fileBytes) > 0 && fileName != "") {
		if body != nil {
			return nil, errors.New("Cannot specify postBody and multipart form at the same time.")
		}
		body = &bytes.Buffer{}
		w := multipart.NewWriter(body)

		for k, v := range formParams {
			for _, iv := range v {
				if strings.HasPrefix(k, "@") { // file
					err = addFile(w, k[1:], iv)
					if err != nil {
						return nil, err
					}
				} else { // form value
					w.WriteField(k, iv)
				}
			}
		}
		if len(fileBytes) > 0 && fileName != "" {
			w.Boundary()
			//_, fileNm := filepath.Split(fileName)
			part, err := w.CreateFormFile(formFileName, filepath.Base(fileName))
			if err != nil {
				return nil, err
			}
			_, err = part.Write(fileBytes)
			if err != nil {
				return nil, err
			}
		}

		// Set the Boundary in the Content-Type
		headerParams["Content-Type"] = w.FormDataContentType()

		// Set Content-Length
		headerParams["Content-Length"] = fmt.Sprintf("%d", body.Len())
		w.Close()
	}

	if strings.HasPrefix(headerParams["Content-Type"], "application/x-www-form-urlencoded") && len(formParams) > 0 {
		if body != nil {
			return nil, errors.New("Cannot specify postBody and x-www-form-urlencoded form at the same time.")
		}
		body = &bytes.Buffer{}
		body.WriteString(formParams.Encode())
		// Set Content-Length
		headerParams["Content-Length"] = fmt.Sprintf("%d", body.Len())
	}

	if queryParams == nil {
		queryParams = make(url.Values)
	}

	// Setup path and query parameters
	url, err := url.Parse(path)
	if err != nil {
		return nil, err
	}

	// Override request host, if applicable
	if c.cfg.Host != "" {
		url.Host = c.cfg.Host
	}

	// Override request scheme, if applicable
	if c.cfg.Scheme != "" {
		url.Scheme = c.cfg.Scheme
	}

	// Adding Query Param
	query := url.Query()
	/* adding default query params */
	for k, v := range c.cfg.DefaultQueryParams {
		if _, ok := queryParams[k]; !ok {
			queryParams[k] = v
		}
	}
	for k, v := range queryParams {
		for _, iv := range v {
			query.Add(k, iv)
		}
	}

	// Encode the parameters.
	url.RawQuery = query.Encode()

	// Generate a new request
	if body != nil {
		localVarRequest, err = http.NewRequest(method, url.String(), body)
	} else {
		localVarRequest, err = http.NewRequest(method, url.String(), nil)
	}
	if err != nil {
		return nil, err
	}

	// add header parameters, if any
	if len(headerParams) > 0 {
		headers := http.Header{}
		for h, v := range headerParams {
			headers.Set(h, v)
		}
		localVarRequest.Header = headers
	}

	// Add the user agent to the request.
	localVarRequest.Header.Add("User-Agent", c.cfg.UserAgent)

	if c.cfg.Token != "" {
		localVarRequest.Header.Add("Authorization", "Bearer "+c.cfg.Token)
	} else {
		if c.cfg.Username != "" {
			localVarRequest.SetBasicAuth(c.cfg.Username, c.cfg.Password)
		}
	}

	if ctx != nil {
		// add context to the request
		localVarRequest = localVarRequest.WithContext(ctx)

		// Walk through any authentication.

		// OAuth2 authentication
		if tok, ok := ctx.Value(ContextOAuth2).(oauth2.TokenSource); ok {
			// We were able to grab an oauth2 token from the context
			var latestToken *oauth2.Token
			if latestToken, err = tok.Token(); err != nil {
				return nil, err
			}

			latestToken.SetAuthHeader(localVarRequest)
		}

		// Basic HTTP Authentication
		if auth, ok := ctx.Value(ContextBasicAuth).(BasicAuth); ok {
			localVarRequest.SetBasicAuth(auth.UserName, auth.Password)
		}

		// AccessToken Authentication
		if auth, ok := ctx.Value(ContextAccessToken).(string); ok {
			localVarRequest.Header.Add("Authorization", "Bearer "+auth)
		}

	}

	for header, value := range c.cfg.DefaultHeader {
		localVarRequest.Header.Add(header, value)
	}
	return localVarRequest, nil
}

func (c *APIClient) decode(v interface{}, b []byte, contentType string) (err error) {
	if len(b) == 0 {
		return nil
	}
	if s, ok := v.(*string); ok {
		*s = string(b)
		return nil
	}
	if xmlCheck.MatchString(contentType) {
		if err = xml.Unmarshal(b, v); err != nil {
			return err
		}
		return nil
	}
	if jsonCheck.MatchString(contentType) {
		if actualObj, ok := v.(interface{ GetActualInstance() interface{} }); ok { // oneOf, anyOf schemas
			if unmarshalObj, ok := actualObj.(interface{ UnmarshalJSON([]byte) error }); ok { // make sure it has UnmarshalJSON defined
				if err = unmarshalObj.UnmarshalJSON(b); err != nil {
					return err
				}
			} else {
				return errors.New("unknown type with GetActualInstance but no unmarshalObj.UnmarshalJSON defined")
			}
		} else if err = json.Unmarshal(b, v); err != nil { // simple model
			return err
		}
		return nil
	}
	return fmt.Errorf("undefined response type for content %s", contentType)
}

func (c *APIClient) GetRequestStatus(ctx context.Context, path string) (*RequestStatus, *APIResponse, error) {

	r, err := c.prepareRequest(ctx, path, http.MethodGet, nil, nil, nil, nil, "", "", nil)
	if err != nil {
		return nil, nil, err
	}

	resp, httpRequestTime, err := c.callAPI(r)

	var responseBody = make([]byte, 0)
	if resp != nil {
		var errRead error
		responseBody, errRead = io.ReadAll(resp.Body)
		_ = resp.Body.Close()
		if errRead != nil {
			return nil, nil, errRead
		}

	}

	apiResponse := &APIResponse{
		Response:    resp,
		Method:      http.MethodGet,
		RequestTime: httpRequestTime,
		RequestURL:  path,
		Operation:   "GetRequestStatus",
	}

	apiResponse.Payload = responseBody

	if err != nil {
		return nil, apiResponse, err
	}

	status := &RequestStatus{}
	err = c.decode(status, responseBody, resp.Header.Get("Content-Type"))
	if err != nil {
		return nil, apiResponse, err
	}

	return status, apiResponse, nil

}

type ResourceHandler interface {
	GetMetadata() *DatacenterElementMetadata
	GetMetadataOk() (*DatacenterElementMetadata, bool)
}

const (
	Available        string = "AVAILABLE"
	Busy                    = "BUSY"
	Inactive                = "INACTIVE"
	Deploying               = "DEPLOYING"
	Active                  = "ACTIVE"
	Failed                  = "FAILED"
	Suspended               = "SUSPENDED"
	FailedSuspended         = "FAILED_SUSPENDED"
	Updating                = "UPDATING"
	FailedUpdating          = "FAILED_UPDATING"
	Destroying              = "DESTROYING"
	FailedDestroying        = "FAILED_DESTROYING"
	Terminated              = "TERMINATED"
)

type resourceGetCallFn func(apiClient *APIClient, resourceID string) (ResourceHandler, error)
type resourceDeleteCallFn func(apiClient *APIClient, resourceID string) (*APIResponse, error)

type StateChannel struct {
	Msg string
	Err error
}

type DeleteStateChannel struct {
	Msg int
	Err error
}

// fn() is a function that returns from the API the resource you want to check it's state.
// Successful states that can be checked: Available, or Active
func (c *APIClient) WaitForState(ctx context.Context, fn resourceGetCallFn, resourceID string) (bool, error) {
	ticker := time.NewTicker(c.cfg.PollInterval)
	defer ticker.Stop()

	for {
		select {
		case <-ctx.Done():
			return false, ctx.Err()
		case <-ticker.C:
			resource, err := fn(c, resourceID)
			if err != nil {
				return false, fmt.Errorf("error occurred when calling the fn function: %w", err)
			}
			if resource == nil {
				return false, errors.New("fail to get resource")
			}
			if metadata := resource.GetMetadata(); metadata != nil {
				if state, ok := metadata.GetStateOk(); ok && state != nil {
					if *state == Available || *state == Active {
						return true, nil
					}
					if *state == Failed || *state == FailedSuspended || *state == FailedUpdating {
						return false, errors.New("state of the resource is " + *state)
					}
				}
			} else {
				return false, errors.New("metadata could not be retrieved from the fn API call")
			}
		}
		continue
	}
}

// fn() is a function that returns from the API the resource you want to check it's state
// the channel is of type StateChannel and it represents the state of the resource. Successful states that can be checked: Available, or Active
func (c *APIClient) waitForStateWithChanel(ctx context.Context, fn resourceGetCallFn, resourceID string, ch chan<- StateChannel) {
	ticker := time.NewTicker(c.cfg.PollInterval)
	defer ticker.Stop()
	done := make(chan bool, 1)

	for {
		select {
		case <-ctx.Done():
			ch <- StateChannel{
				"",
				ctx.Err(),
			}
			return
		case <-done:
			return
		case <-ticker.C:
			resource, err := fn(c, resourceID)
			if err != nil {
				ch <- StateChannel{
					"",
					fmt.Errorf("error occurred when calling the fn function: %w", err),
				}
			} else if resource == nil {
				ch <- StateChannel{
					"",
					errors.New("fail to get resource"),
				}
			} else if metadata := resource.GetMetadata(); metadata != nil {
				if state, ok := metadata.GetStateOk(); ok && state != nil {
					if *state == Available || *state == Active {
						ch <- StateChannel{
							*state,
							nil,
						}
					}
					if *state == Failed || *state == FailedSuspended || *state == FailedUpdating {
						ch <- StateChannel{
							"",
							errors.New("state of the resource is " + *state),
						}
					}
				}
			} else {
				ch <- StateChannel{
					"",
					errors.New("metadata could not be retrieved from the fn API call"),
				}
			}
			done <- true
		}
		continue
	}
}

// fn() is a function that returns from the API the resource you want to check it's state
// the channel is of type StateChannel and it represents the state of the resource. Successful states that can be checked: Available, or Active
func (c *APIClient) WaitForStateAsync(ctx context.Context, fn resourceGetCallFn, resourceID string, ch chan<- StateChannel) {
	go c.waitForStateWithChanel(ctx, fn, resourceID, ch)
}

// fn() is a function that returns from the API the resource you want to check it's state.
// a resource is deleted when status code 404 is returned from the get call to API
func (c *APIClient) WaitForDeletion(ctx context.Context, fn resourceDeleteCallFn, resourceID string) (bool, error) {
	ticker := time.NewTicker(c.cfg.PollInterval)
	defer ticker.Stop()

	for {
		select {
		case <-ctx.Done():
			return false, ctx.Err()
		case <-ticker.C:
			apiResponse, err := fn(c, resourceID)
			if err != nil {
				if apiResponse == nil {
					return false, fmt.Errorf("fail to get response: %w", err)
				}
				if apiResp := apiResponse.Response; apiResp != nil {
					if apiResp.StatusCode == http.StatusNotFound {
						return true, nil
					}
				}
				return false, err
			}
		}
		continue
	}
}

// fn() is a function that returns from the API the resource you want to check it's state
// the channel is of type int and it represents the status response of the resource, which in this case is 404 to check when the resource is not found.
func (c *APIClient) waitForDeletionWithChannel(ctx context.Context, fn resourceDeleteCallFn, resourceID string, ch chan<- DeleteStateChannel) {
	ticker := time.NewTicker(c.cfg.PollInterval)
	defer ticker.Stop()
	done := make(chan bool, 1)

	for {
		select {
		case <-ctx.Done():
			ch <- DeleteStateChannel{
				0,
				ctx.Err(),
			}
			return
		case <-done:
			return
		case <-ticker.C:
			apiResponse, err := fn(c, resourceID)
			if err != nil {
				if apiResponse == nil {
					ch <- DeleteStateChannel{
						0,
						fmt.Errorf("API Response from fn is empty: %w ", err),
					}
				} else if apiresp := apiResponse.Response; apiresp != nil {
					if statusCode := apiresp.StatusCode; statusCode == http.StatusNotFound {
						ch <- DeleteStateChannel{
							statusCode,
							nil,
						}
					} else {
						ch <- DeleteStateChannel{
							statusCode,
							err,
						}
					}
					done <- true
				}
			}
		}
		continue
	}
}

// fn() is a function that returns from the API the resource you want to check it's state
// the channel is of type int and it represents the status response of the resource, which in this case is 404 to check when the resource is not found.
func (c *APIClient) WaitForDeletionAsync(ctx context.Context, fn resourceDeleteCallFn, resourceID string, ch chan<- DeleteStateChannel) {
	go c.waitForDeletionWithChannel(ctx, fn, resourceID, ch)
}

func (c *APIClient) WaitForRequest(ctx context.Context, path string) (*APIResponse, error) {

	var (
		localVarHTTPMethod   = http.MethodGet
		localVarPostBody     interface{}
		localVarFormFileName string
		localVarFileName     string
		localVarFileBytes    []byte
	)

	// create path and map variables
	localVarHeaderParams := make(map[string]string)
	localVarQueryParams := url.Values{}
	localVarFormParams := url.Values{}

	r, err := c.prepareRequest(ctx, path, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)
	if err != nil {
		return nil, err
	}

	ticker := time.NewTicker(c.cfg.PollInterval)
	defer ticker.Stop()
	for {
		resp, httpRequestTime, err := c.callAPI(r)

		var localVarBody = make([]byte, 0)
		if resp != nil {
			var errRead error
			localVarBody, errRead = io.ReadAll(resp.Body)
			_ = resp.Body.Close()
			if errRead != nil {
				return nil, errRead
			}

		}

		localVarAPIResponse := &APIResponse{
			Response:    resp,
			Method:      localVarHTTPMethod,
			RequestTime: httpRequestTime,
			RequestURL:  path,
			Operation:   "WaitForRequest",
		}

		localVarAPIResponse.Payload = localVarBody

		if err != nil {
			return localVarAPIResponse, err
		}

		status := RequestStatus{}
		err = c.decode(&status, localVarBody, resp.Header.Get("Content-Type"))
		if err != nil {
			return localVarAPIResponse, err
		}

		if resp.StatusCode != http.StatusOK {
			msg := fmt.Sprintf("WaitForRequest failed; received status code %d from API", resp.StatusCode)
			return localVarAPIResponse, NewGenericOpenAPIError(msg, localVarBody, nil, resp.StatusCode)
		}
		if status.Metadata != nil && status.Metadata.Status != nil {
			switch *status.Metadata.Status {
			case RequestStatusDone:
				return localVarAPIResponse, nil
			case RequestStatusFailed:
				var id = "<none>"
				var message = "<none>"
				if status.Id != nil {
					id = *status.Id
				}
				if status.Metadata.Message != nil {
					message = *status.Metadata.Message
				}
				return localVarAPIResponse, fmt.Errorf("Request %s failed: %s", id, message)
			}
		}
		select {
		case <-ctx.Done():
			return nil, ctx.Err()
		case <-ticker.C:
			continue
		}
	}
}

// Add a file to the multipart request
func addFile(w *multipart.Writer, fieldName, path string) error {
	file, err := os.Open(path)
	if err != nil {
		return err
	}
	defer file.Close()

	part, err := w.CreateFormFile(fieldName, filepath.Base(path))
	if err != nil {
		return err
	}
	_, err = io.Copy(part, file)

	return err
}

// Prevent trying to import "fmt"
func reportError(format string, a ...interface{}) error {
	return fmt.Errorf(format, a...)
}

// Set request body from an interface{}
func setBody(body interface{}, contentType string) (bodyBuf *bytes.Buffer, err error) {
	if bodyBuf == nil {
		bodyBuf = &bytes.Buffer{}
	}

	if reader, ok := body.(io.Reader); ok {
		_, err = bodyBuf.ReadFrom(reader)
	} else if b, ok := body.([]byte); ok {
		_, err = bodyBuf.Write(b)
	} else if s, ok := body.(string); ok {
		_, err = bodyBuf.WriteString(s)
	} else if s, ok := body.(*string); ok {
		_, err = bodyBuf.WriteString(*s)
	} else if jsonCheck.MatchString(contentType) {
		err = json.NewEncoder(bodyBuf).Encode(body)
	} else if xmlCheck.MatchString(contentType) {
		err = xml.NewEncoder(bodyBuf).Encode(body)
	}

	if err != nil {
		return nil, err
	}

	if bodyBuf.Len() == 0 {
		err = fmt.Errorf("Invalid body type %s\n", contentType)
		return nil, err
	}
	return bodyBuf, nil
}

// detectContentType method is used to figure out `Request.Body` content type for request header
func detectContentType(body interface{}) string {
	contentType := "text/plain; charset=utf-8"
	kind := reflect.TypeOf(body).Kind()

	switch kind {
	case reflect.Struct, reflect.Map, reflect.Ptr:
		contentType = "application/json; charset=utf-8"
	case reflect.String:
		contentType = "text/plain; charset=utf-8"
	default:
		if b, ok := body.([]byte); ok {
			contentType = http.DetectContentType(b)
		} else if kind == reflect.Slice {
			contentType = "application/json; charset=utf-8"
		}
	}

	return contentType
}

// Ripped from https://github.com/gregjones/httpcache/blob/master/httpcache.go
type cacheControl map[string]string

func parseCacheControl(headers http.Header) cacheControl {
	cc := cacheControl{}
	ccHeader := headers.Get("Cache-Control")
	for _, part := range strings.Split(ccHeader, ",") {
		part = strings.Trim(part, " ")
		if part == "" {
			continue
		}
		if strings.ContainsRune(part, '=') {
			keyval := strings.Split(part, "=")
			cc[strings.Trim(keyval[0], " ")] = strings.Trim(keyval[1], ",")
		} else {
			cc[part] = ""
		}
	}
	return cc
}

// CacheExpires helper function to determine remaining time before repeating a request.
func CacheExpires(r *http.Response) time.Time {
	// Figure out when the cache expires.
	var expires time.Time
	now, err := time.Parse(time.RFC1123, r.Header.Get("date"))
	if err != nil {
		return time.Now()
	}
	respCacheControl := parseCacheControl(r.Header)

	if maxAge, ok := respCacheControl["max-age"]; ok {
		lifetime, err := time.ParseDuration(maxAge + "s")
		if err != nil {
			expires = now
		} else {
			expires = now.Add(lifetime)
		}
	} else {
		expiresHeader := r.Header.Get("Expires")
		if expiresHeader != "" {
			expires, err = time.Parse(time.RFC1123, expiresHeader)
			if err != nil {
				expires = now
			}
		}
	}
	return expires
}

func strlen(s string) int {
	return utf8.RuneCountInString(s)
}

// GenericOpenAPIError provides access to the body, error and model on returned errors.
type GenericOpenAPIError struct {
	statusCode int
	body       []byte
	error      string
	model      interface{}
}

// NewGenericOpenAPIError - constructor for GenericOpenAPIError
func NewGenericOpenAPIError(message string, body []byte, model interface{}, statusCode int) GenericOpenAPIError {
	return GenericOpenAPIError{
		statusCode: statusCode,
		body:       body,
		error:      message,
		model:      model,
	}
}

// Error returns non-empty string if there was an error.
func (e GenericOpenAPIError) Error() string {
	return e.error
}

// SetError sets the error string
func (e *GenericOpenAPIError) SetError(error string) {
	e.error = error
}

// Body returns the raw bytes of the response
func (e GenericOpenAPIError) Body() []byte {
	return e.body
}

// SetBody sets the raw body of the error
func (e *GenericOpenAPIError) SetBody(body []byte) {
	e.body = body
}

// Model returns the unpacked model of the error
func (e GenericOpenAPIError) Model() interface{} {
	return e.model
}

// SetModel sets the model of the error
func (e *GenericOpenAPIError) SetModel(model interface{}) {
	e.model = model
}

// StatusCode returns the status code of the error
func (e GenericOpenAPIError) StatusCode() int {
	return e.statusCode
}

// SetStatusCode sets the status code of the error
func (e *GenericOpenAPIError) SetStatusCode(statusCode int) {
	e.statusCode = statusCode
}