-
Notifications
You must be signed in to change notification settings - Fork 274
/
azure_armclient.go
680 lines (583 loc) · 23.9 KB
/
azure_armclient.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
/*
Copyright 2020 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package armclient
import (
"context"
"crypto/tls"
"fmt"
"html"
"net"
"net/http"
"net/http/cookiejar"
"net/url"
"strings"
"sync"
"time"
"unicode"
"sigs.k8s.io/cloud-provider-azure/pkg/azureclients"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure"
"github.com/Azure/go-autorest/tracing"
"k8s.io/klog/v2"
"sigs.k8s.io/cloud-provider-azure/pkg/retry"
"sigs.k8s.io/cloud-provider-azure/pkg/version"
)
// there is one sender per TLS renegotiation type, i.e. count of tls.RenegotiationSupport enums
type defaultSender struct {
sender autorest.Sender
init *sync.Once
}
// each type of sender will be created on demand in sender()
var defaultSenders defaultSender
func init() {
defaultSenders.init = &sync.Once{}
}
var _ Interface = &Client{}
// Client implements ARM client Interface.
type Client struct {
client autorest.Client
baseURI string
apiVersion string
regionalEndpoint string
}
func sender() autorest.Sender {
// note that we can't init defaultSenders in init() since it will
// execute before calling code has had a chance to enable tracing
defaultSenders.init.Do(func() {
// copied from http.DefaultTransport with a TLS minimum version.
transport := &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{
Timeout: 30 * time.Second, // the same as default transport
KeepAlive: 30 * time.Second, // the same as default transport
}).DialContext,
ForceAttemptHTTP2: true, // always attempt HTTP/2 even though custom dialer is provided
MaxIdleConns: 100, // Zero means no limit, the same as default transport
MaxIdleConnsPerHost: 100, // Default is 2, ref:https://cs.opensource.google/go/go/+/go1.18.4:src/net/http/transport.go;l=58
IdleConnTimeout: 90 * time.Second, // the same as default transport
TLSHandshakeTimeout: 10 * time.Second, // the same as default transport
ExpectContinueTimeout: 1 * time.Second, // the same as default transport
TLSClientConfig: &tls.Config{
MinVersion: tls.VersionTLS12, //force to use TLS 1.2
Renegotiation: tls.RenegotiateNever, // the same as default transport https://pkg.go.dev/crypto/tls#RenegotiationSupport
},
}
var roundTripper http.RoundTripper = transport
if tracing.IsEnabled() {
roundTripper = tracing.NewTransport(transport)
}
j, _ := cookiejar.New(nil)
defaultSenders.sender = &http.Client{Jar: j, Transport: roundTripper}
})
return defaultSenders.sender
}
// New creates a ARM client
func New(authorizer autorest.Authorizer, clientConfig azureclients.ClientConfig, baseURI, apiVersion string, sendDecoraters ...autorest.SendDecorator) *Client {
restClient := autorest.NewClientWithUserAgent(clientConfig.UserAgent)
restClient.Authorizer = authorizer
restClient.Sender = sender()
if clientConfig.UserAgent == "" {
restClient.UserAgent = GetUserAgent(restClient)
}
if clientConfig.RestClientConfig.PollingDelay == nil {
restClient.PollingDelay = 5 * time.Second
} else {
restClient.PollingDelay = *clientConfig.RestClientConfig.PollingDelay
}
if clientConfig.RestClientConfig.RetryAttempts == nil {
restClient.RetryAttempts = 3
} else {
restClient.RetryAttempts = *clientConfig.RestClientConfig.RetryAttempts
}
if clientConfig.RestClientConfig.RetryDuration == nil {
restClient.RetryDuration = 1 * time.Second
} else {
restClient.RetryDuration = *clientConfig.RestClientConfig.RetryDuration
}
backoff := clientConfig.Backoff
if backoff == nil {
backoff = &retry.Backoff{}
}
if backoff.Steps == 0 {
// 1 steps means no retry.
backoff.Steps = 1
}
url, _ := url.Parse(baseURI)
client := &Client{
client: restClient,
baseURI: baseURI,
apiVersion: apiVersion,
regionalEndpoint: fmt.Sprintf("%s.%s", clientConfig.Location, url.Host),
}
client.client.Sender = autorest.DecorateSender(client.client,
autorest.DoCloseIfError(),
retry.DoExponentialBackoffRetry(backoff),
DoHackRegionalRetryDecorator(client),
DoDumpRequest(10),
)
client.client.Sender = autorest.DecorateSender(client.client.Sender, sendDecoraters...)
return client
}
// GetUserAgent gets the autorest client with a user agent that
// includes "kubernetes" and the full kubernetes git version string
// example:
// Azure-SDK-for-Go/7.0.1 arm-network/2016-09-01; kubernetes-cloudprovider/v1.17.0;
func GetUserAgent(client autorest.Client) string {
k8sVersion := version.Get().GitVersion
return fmt.Sprintf("%s; kubernetes-cloudprovider/%s", client.UserAgent, k8sVersion)
}
// NormalizeAzureRegion returns a normalized Azure region with white spaces removed and converted to lower case
func NormalizeAzureRegion(name string) string {
region := ""
for _, runeValue := range name {
if !unicode.IsSpace(runeValue) {
region += string(runeValue)
}
}
return strings.ToLower(region)
}
// Send sends a http request to ARM service with possible retry to regional ARM endpoint.
func (c *Client) Send(ctx context.Context, request *http.Request, decorators ...autorest.SendDecorator) (*http.Response, *retry.Error) {
response, err := autorest.SendWithSender(
c.client,
request,
decorators...,
)
if response == nil && err == nil {
return response, retry.NewError(false, fmt.Errorf("Empty response and no HTTP code"))
}
return response, retry.GetError(response, err)
}
// PreparePutRequest prepares put request
func (c *Client) PreparePutRequest(ctx context.Context, decorators ...autorest.PrepareDecorator) (*http.Request, error) {
decorators = append(
[]autorest.PrepareDecorator{
autorest.AsContentType("application/json; charset=utf-8"),
autorest.AsPut(),
autorest.WithBaseURL(c.baseURI)},
decorators...)
return c.prepareRequest(ctx, decorators...)
}
// PreparePatchRequest prepares patch request
func (c *Client) PreparePatchRequest(ctx context.Context, decorators ...autorest.PrepareDecorator) (*http.Request, error) {
decorators = append(
[]autorest.PrepareDecorator{
autorest.AsContentType("application/json; charset=utf-8"),
autorest.AsPatch(),
autorest.WithBaseURL(c.baseURI)},
decorators...)
return c.prepareRequest(ctx, decorators...)
}
// PreparePostRequest prepares post request
func (c *Client) PreparePostRequest(ctx context.Context, decorators ...autorest.PrepareDecorator) (*http.Request, error) {
decorators = append(
[]autorest.PrepareDecorator{
autorest.AsContentType("application/json; charset=utf-8"),
autorest.AsPost(),
autorest.WithBaseURL(c.baseURI)},
decorators...)
return c.prepareRequest(ctx, decorators...)
}
// PrepareGetRequest prepares get request
func (c *Client) PrepareGetRequest(ctx context.Context, decorators ...autorest.PrepareDecorator) (*http.Request, error) {
decorators = append(
[]autorest.PrepareDecorator{
autorest.AsGet(),
autorest.WithBaseURL(c.baseURI)},
decorators...)
return c.prepareRequest(ctx, decorators...)
}
// PrepareDeleteRequest preparse delete request
func (c *Client) PrepareDeleteRequest(ctx context.Context, decorators ...autorest.PrepareDecorator) (*http.Request, error) {
decorators = append(
[]autorest.PrepareDecorator{
autorest.AsDelete(),
autorest.WithBaseURL(c.baseURI)},
decorators...)
return c.prepareRequest(ctx, decorators...)
}
// PrepareHeadRequest prepares head request
func (c *Client) PrepareHeadRequest(ctx context.Context, decorators ...autorest.PrepareDecorator) (*http.Request, error) {
decorators = append(
[]autorest.PrepareDecorator{
autorest.AsHead(),
autorest.WithBaseURL(c.baseURI)},
decorators...)
return c.prepareRequest(ctx, decorators...)
}
// WaitForAsyncOperationCompletion waits for an operation completion
func (c *Client) WaitForAsyncOperationCompletion(ctx context.Context, future *azure.Future, asyncOperationName string) error {
err := future.WaitForCompletionRef(ctx, c.client)
if err != nil {
klog.V(5).Infof("Received error in WaitForCompletionRef: '%v'", err)
return err
}
var done bool
done, err = future.DoneWithContext(ctx, c.client)
if err != nil {
klog.V(5).Infof("Received error in DoneWithContext: '%v'", err)
return autorest.NewErrorWithError(err, asyncOperationName, "Result", future.Response(), "Polling failure")
}
if !done {
return azure.NewAsyncOpIncompleteError(asyncOperationName)
}
return nil
}
// WaitForAsyncOperationResult waits for an operation result.
func (c *Client) WaitForAsyncOperationResult(ctx context.Context, future *azure.Future, asyncOperationName string) (*http.Response, error) {
if err := future.WaitForCompletionRef(ctx, c.client); err != nil {
klog.V(5).Infof("Received error in WaitForAsyncOperationCompletion: '%v'", err)
return nil, err
}
return future.GetResult(c.client)
}
// SendAsync send a request and return a future object representing the async result as well as the origin http response
func (c *Client) SendAsync(ctx context.Context, request *http.Request) (*azure.Future, *http.Response, *retry.Error) {
asyncResponse, rerr := c.Send(ctx, request)
if rerr != nil {
klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "sendAsync.send", html.EscapeString(request.URL.String()), rerr.Error())
return nil, nil, rerr
}
future, err := azure.NewFutureFromResponse(asyncResponse)
if err != nil {
klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "sendAsync.respond", html.EscapeString(request.URL.String()), err)
return nil, asyncResponse, retry.GetError(asyncResponse, err)
}
return &future, asyncResponse, nil
}
// GetResourceWithExpandQuery get a resource by resource ID with expand
func (c *Client) GetResourceWithExpandQuery(ctx context.Context, resourceID, expand string) (*http.Response, *retry.Error) {
var decorators []autorest.PrepareDecorator
if expand != "" {
queryParameters := map[string]interface{}{
"$expand": autorest.Encode("query", expand),
}
decorators = append(decorators, autorest.WithQueryParameters(queryParameters))
}
return c.GetResource(ctx, resourceID, decorators...)
}
// GetResourceWithExpandAPIVersionQuery get a resource by resource ID with expand and API version.
func (c *Client) GetResourceWithExpandAPIVersionQuery(ctx context.Context, resourceID, expand, apiVersion string) (*http.Response, *retry.Error) {
decorators := []autorest.PrepareDecorator{
autorest.AsGet(),
autorest.WithBaseURL(c.baseURI),
autorest.WithPathParameters("{resourceID}", map[string]interface{}{"resourceID": resourceID}),
withAPIVersion(apiVersion),
}
if expand != "" {
decorators = append(decorators, autorest.WithQueryParameters(map[string]interface{}{
"$expand": autorest.Encode("query", expand),
}))
}
preparer := autorest.CreatePreparer(decorators...)
request, err := preparer.Prepare((&http.Request{}).WithContext(ctx))
if err != nil {
klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "get.prepare", resourceID, err)
return nil, retry.NewError(false, err)
}
return c.Send(ctx, request)
}
// GetResourceWithDecorators get a resource with decorators by resource ID
func (c *Client) GetResource(ctx context.Context, resourceID string, decorators ...autorest.PrepareDecorator) (*http.Response, *retry.Error) {
getDecorators := append([]autorest.PrepareDecorator{
autorest.WithPathParameters("{resourceID}", map[string]interface{}{"resourceID": resourceID}),
}, decorators...)
request, err := c.PrepareGetRequest(ctx, getDecorators...)
if err != nil {
klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "get.prepare", resourceID, err)
return nil, retry.NewError(false, err)
}
return c.Send(ctx, request)
}
// PutResource puts a resource by resource ID
func (c *Client) PutResource(ctx context.Context, resourceID string, parameters interface{}, decorators ...autorest.PrepareDecorator) (*http.Response, *retry.Error) {
future, rerr := c.PutResourceAsync(ctx, resourceID, parameters, decorators...)
if rerr != nil {
return nil, rerr
}
response, err := c.WaitForAsyncOperationResult(ctx, future, "armclient.PutResource")
if err != nil {
if response != nil {
klog.V(5).Infof("Received error in WaitForAsyncOperationResult: '%s', response code %d", err.Error(), response.StatusCode)
} else {
klog.V(5).Infof("Received error in WaitForAsyncOperationResult: '%s', no response", err.Error())
}
retriableErr := retry.GetError(response, err)
if !retriableErr.Retriable &&
strings.Contains(strings.ToUpper(err.Error()), strings.ToUpper("InternalServerError")) {
klog.V(5).Infof("Received InternalServerError in WaitForAsyncOperationResult: '%s', setting error retriable", err.Error())
retriableErr.Retriable = true
}
return nil, retriableErr
}
return response, nil
}
// PutResourcesInBatches is similar with PutResources, but it sends sync request concurrently in batches.
func (c *Client) PutResourcesInBatches(ctx context.Context, resources map[string]interface{}, batchSize int) map[string]*PutResourcesResponse {
if len(resources) == 0 {
return nil
}
if batchSize <= 0 {
klog.V(4).Infof("PutResourcesInBatches: batch size %d, put resources in sequence", batchSize)
batchSize = 1
}
if batchSize > len(resources) {
klog.V(4).Infof("PutResourcesInBatches: batch size %d, but the number of the resources is %d", batchSize, resources)
batchSize = len(resources)
}
klog.V(4).Infof("PutResourcesInBatches: send sync requests in parallel with the batch size %d", batchSize)
rateLimiter := make(chan struct{}, batchSize)
// Concurrent sync requests in batches.
responses := make(map[string]*PutResourcesResponse)
wg := sync.WaitGroup{}
var responseLock sync.Mutex
for resourceID, parameters := range resources {
rateLimiter <- struct{}{}
wg.Add(1)
go func(resourceID string, parameters interface{}) {
defer wg.Done()
defer func() { <-rateLimiter }()
resp, rerr := c.PutResource(ctx, resourceID, parameters)
responseLock.Lock()
defer responseLock.Unlock()
responses[resourceID] = &PutResourcesResponse{
Error: rerr,
Response: resp,
}
}(resourceID, parameters)
}
wg.Wait()
close(rateLimiter)
return responses
}
// PatchResource patches a resource by resource ID
func (c *Client) PatchResource(ctx context.Context, resourceID string, parameters interface{}, decorators ...autorest.PrepareDecorator) (*http.Response, *retry.Error) {
future, rerr := c.PatchResourceAsync(ctx, resourceID, parameters, decorators...)
if rerr != nil {
return nil, rerr
}
response, err := c.WaitForAsyncOperationResult(ctx, future, "armclient.PatchResource")
if err != nil {
if response != nil {
klog.V(5).Infof("Received error in WaitForAsyncOperationResult: '%s', response code %d", err.Error(), response.StatusCode)
} else {
klog.V(5).Infof("Received error in WaitForAsyncOperationResult: '%s', no response", err.Error())
}
retriableErr := retry.GetError(response, err)
if !retriableErr.Retriable &&
strings.Contains(strings.ToUpper(err.Error()), strings.ToUpper("InternalServerError")) {
klog.V(5).Infof("Received InternalServerError in WaitForAsyncOperationResult: '%s', setting error retriable", err.Error())
retriableErr.Retriable = true
}
return nil, retriableErr
}
return response, nil
}
// PatchResourceAsync patches a resource by resource ID asynchronously
func (c *Client) PatchResourceAsync(ctx context.Context, resourceID string, parameters interface{}, decorators ...autorest.PrepareDecorator) (*azure.Future, *retry.Error) {
decorators = append(decorators,
autorest.WithPathParameters("{resourceID}", map[string]interface{}{"resourceID": resourceID}),
autorest.WithJSON(parameters),
)
request, err := c.PreparePatchRequest(ctx, decorators...)
if err != nil {
klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "patch.prepare", resourceID, err)
return nil, retry.NewError(false, err)
}
future, resp, clientErr := c.SendAsync(ctx, request)
defer c.CloseResponse(ctx, resp)
if clientErr != nil {
klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "patch.send", resourceID, clientErr.Error())
return nil, clientErr
}
return future, clientErr
}
// PutResourceAsync puts a resource by resource ID in async mode
func (c *Client) PutResourceAsync(ctx context.Context, resourceID string, parameters interface{}, decorators ...autorest.PrepareDecorator) (*azure.Future, *retry.Error) {
decorators = append(decorators,
autorest.WithPathParameters("{resourceID}", map[string]interface{}{"resourceID": resourceID}),
autorest.WithJSON(parameters),
)
request, err := c.PreparePutRequest(ctx, decorators...)
if err != nil {
klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "put.prepare", resourceID, err)
return nil, retry.NewError(false, err)
}
future, resp, rErr := c.SendAsync(ctx, request)
defer c.CloseResponse(ctx, resp)
if rErr != nil {
klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "put.send", resourceID, err)
return nil, rErr
}
return future, nil
}
// PostResource posts a resource by resource ID
func (c *Client) PostResource(ctx context.Context, resourceID, action string, parameters interface{}, queryParameters map[string]interface{}) (*http.Response, *retry.Error) {
pathParameters := map[string]interface{}{
"resourceID": resourceID,
"action": action,
}
decorators := []autorest.PrepareDecorator{
autorest.WithPathParameters("{resourceID}/{action}", pathParameters),
autorest.WithJSON(parameters),
}
if len(queryParameters) > 0 {
decorators = append(decorators, autorest.WithQueryParameters(queryParameters))
}
request, err := c.PreparePostRequest(ctx, decorators...)
if err != nil {
klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "post.prepare", resourceID, err)
return nil, retry.NewError(false, err)
}
return c.Send(ctx, request)
}
// DeleteResource deletes a resource by resource ID
func (c *Client) DeleteResource(ctx context.Context, resourceID string, decorators ...autorest.PrepareDecorator) *retry.Error {
future, clientErr := c.DeleteResourceAsync(ctx, resourceID)
if clientErr != nil {
klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "delete.request", resourceID, clientErr.Error())
return clientErr
}
if future == nil {
return nil
}
if err := future.WaitForCompletionRef(ctx, c.client); err != nil {
klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "delete.wait", resourceID, clientErr.Error())
return retry.NewError(true, err)
}
return nil
}
// HeadResource heads a resource by resource ID
func (c *Client) HeadResource(ctx context.Context, resourceID string) (*http.Response, *retry.Error) {
decorators := []autorest.PrepareDecorator{
autorest.WithPathParameters("{resourceID}", map[string]interface{}{"resourceID": resourceID}),
}
request, err := c.PrepareHeadRequest(ctx, decorators...)
if err != nil {
klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "head.prepare", resourceID, err)
return nil, retry.NewError(false, err)
}
return c.Send(ctx, request)
}
// DeleteResourceAsync delete a resource by resource ID and returns a future representing the async result
func (c *Client) DeleteResourceAsync(ctx context.Context, resourceID string, decorators ...autorest.PrepareDecorator) (*azure.Future, *retry.Error) {
decorators = append(decorators,
autorest.WithPathParameters("{resourceID}", map[string]interface{}{"resourceID": resourceID}),
)
deleteRequest, err := c.PrepareDeleteRequest(ctx, decorators...)
if err != nil {
klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "deleteAsync.prepare", resourceID, err)
return nil, retry.NewError(false, err)
}
resp, rerr := c.Send(ctx, deleteRequest)
defer c.CloseResponse(ctx, resp)
if rerr != nil {
klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "deleteAsync.send", resourceID, rerr.Error())
return nil, rerr
}
err = autorest.Respond(
resp,
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent, http.StatusNotFound))
if err != nil {
klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "deleteAsync.respond", resourceID, err)
return nil, retry.GetError(resp, err)
}
if resp.StatusCode == http.StatusNotFound {
return nil, nil
}
future, err := azure.NewFutureFromResponse(resp)
if err != nil {
klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "deleteAsync.future", resourceID, err)
return nil, retry.GetError(resp, err)
}
return &future, nil
}
// CloseResponse closes a response
func (c *Client) CloseResponse(ctx context.Context, response *http.Response) {
if response != nil && response.Body != nil {
if err := response.Body.Close(); err != nil {
klog.Errorf("Error closing the response body: %v", err)
}
}
}
func (c *Client) prepareRequest(ctx context.Context, decorators ...autorest.PrepareDecorator) (*http.Request, error) {
decorators = append(
decorators,
withAPIVersion(c.apiVersion))
preparer := autorest.CreatePreparer(decorators...)
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
func withAPIVersion(apiVersion string) autorest.PrepareDecorator {
const apiVersionKey = "api-version"
return func(p autorest.Preparer) autorest.Preparer {
return autorest.PreparerFunc(func(r *http.Request) (*http.Request, error) {
r, err := p.Prepare(r)
if err == nil {
if r.URL == nil {
return r, fmt.Errorf("Error in withAPIVersion: Invoked with a nil URL")
}
v := r.URL.Query()
if len(v.Get(apiVersionKey)) > 0 {
return r, nil
}
v.Add(apiVersionKey, apiVersion)
r.URL.RawQuery = v.Encode()
}
return r, err
})
}
}
// GetResourceID gets Azure resource ID
func GetResourceID(subscriptionID, resourceGroupName, resourceType, resourceName string) string {
return fmt.Sprintf("/subscriptions/%s/resourceGroups/%s/providers/%s/%s",
autorest.Encode("path", subscriptionID),
autorest.Encode("path", resourceGroupName),
resourceType,
autorest.Encode("path", resourceName))
}
// GetResourceListID gets Azure resource list ID
func GetResourceListID(subscriptionID, resourceGroupName, resourceType string) string {
return fmt.Sprintf("/subscriptions/%s/resourceGroups/%s/providers/%s",
autorest.Encode("path", subscriptionID),
autorest.Encode("path", resourceGroupName),
resourceType)
}
// GetChildResourceID gets Azure child resource ID
func GetChildResourceID(subscriptionID, resourceGroupName, resourceType, resourceName, childResourceType, childResourceName string) string {
return fmt.Sprintf("/subscriptions/%s/resourceGroups/%s/providers/%s/%s/%s/%s",
autorest.Encode("path", subscriptionID),
autorest.Encode("path", resourceGroupName),
resourceType,
autorest.Encode("path", resourceName),
childResourceType,
autorest.Encode("path", childResourceName))
}
// GetChildResourcesListID gets Azure child resources list ID
func GetChildResourcesListID(subscriptionID, resourceGroupName, resourceType, resourceName, childResourceType string) string {
return fmt.Sprintf("/subscriptions/%s/resourceGroups/%s/providers/%s/%s/%s",
autorest.Encode("path", subscriptionID),
autorest.Encode("path", resourceGroupName),
resourceType,
autorest.Encode("path", resourceName),
childResourceType)
}
// GetProviderResourceID gets Azure RP resource ID
func GetProviderResourceID(subscriptionID, providerNamespace string) string {
return fmt.Sprintf("/subscriptions/%s/providers/%s",
autorest.Encode("path", subscriptionID),
providerNamespace)
}
// GetProviderResourcesListID gets Azure RP resources list ID
func GetProviderResourcesListID(subscriptionID string) string {
return fmt.Sprintf("/subscriptions/%s/providers", autorest.Encode("path", subscriptionID))
}