-
Notifications
You must be signed in to change notification settings - Fork 625
/
Copy pathDefaultAcsClient.cs
619 lines (526 loc) · 22.3 KB
/
DefaultAcsClient.cs
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
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using Aliyun.Acs.Core.Auth;
using Aliyun.Acs.Core.Auth.Provider;
using Aliyun.Acs.Core.Exceptions;
using Aliyun.Acs.Core.Http;
using Aliyun.Acs.Core.Profile;
using Aliyun.Acs.Core.Reader;
using Aliyun.Acs.Core.Regions;
using Aliyun.Acs.Core.Retry;
using Aliyun.Acs.Core.Retry.Condition;
using Aliyun.Acs.Core.Timeout.Util;
using Aliyun.Acs.Core.Transform;
using Aliyun.Acs.Core.Utils;
namespace Aliyun.Acs.Core
{
public class DefaultAcsClient : IAcsClient
{
private static readonly HttpWebProxy WebProxy = new HttpWebProxy();
private readonly IClientProfile clientProfile;
private readonly AlibabaCloudCredentialsProvider credentialsProvider;
private readonly RetryPolicy retryPolicy;
private readonly UserAgent userAgentConfig = new UserAgent();
private bool autoRetry = true;
private int maxRetryNumber = 3;
public DefaultAcsClient()
{
retryPolicy = AutoRetry ? new RetryPolicy(maxRetryNumber, true) : new RetryPolicy();
}
public DefaultAcsClient(IClientProfile profile) : this()
{
clientProfile = profile;
credentialsProvider = new StaticCredentialsProvider(profile);
clientProfile.SetCredentialsProvider(credentialsProvider);
}
public DefaultAcsClient(IClientProfile profile, AlibabaCloudCredentials credentials) : this()
{
clientProfile = profile;
credentialsProvider = new StaticCredentialsProvider(credentials);
clientProfile.SetCredentialsProvider(credentialsProvider);
}
public DefaultAcsClient(IClientProfile profile, AlibabaCloudCredentialsProvider credentialsProvider) : this()
{
clientProfile = profile;
this.credentialsProvider = credentialsProvider;
clientProfile.SetCredentialsProvider(this.credentialsProvider);
}
[Obsolete("readTimeout is deprecated as does not match Properties rule, please use readTimeout instead.")]
public int readTimeout
{
get { return ReadTimeout; }
}
public int ReadTimeout { get; private set; }
[Obsolete("connectTimeout is deprecated as does not match Properties rule, please use connectTimeout instead.")]
public int connectTimeout
{
get { return ConnectTimeout; }
}
public int ConnectTimeout { get; private set; }
public bool IgnoreCertificate { get; private set; }
public int MaxRetryNumber
{
get { return maxRetryNumber; }
set { maxRetryNumber = value; }
}
public bool AutoRetry
{
get { return autoRetry; }
set { autoRetry = value; }
}
public T GetAcsResponse<T>(AcsRequest<T> request) where T : AcsResponse
{
var httpResponse = DoAction(request);
return ParseAcsResponse(request, httpResponse);
}
public T GetAcsResponse<T>(AcsRequest<T> request, bool autoRetry, int maxRetryNumber) where T : AcsResponse
{
var httpResponse = DoAction(request, autoRetry, maxRetryNumber);
return ParseAcsResponse(request, httpResponse);
}
public T GetAcsResponse<T>(AcsRequest<T> request, IClientProfile profile) where T : AcsResponse
{
var httpResponse = DoAction(request, profile);
return ParseAcsResponse(request, httpResponse);
}
public T GetAcsResponse<T>(AcsRequest<T> request, string regionId, Credential credential)
where T : AcsResponse
{
var httpResponse = DoAction(request, regionId, credential);
return ParseAcsResponse(request, httpResponse);
}
public CommonResponse GetCommonResponse(CommonRequest request)
{
var httpResponse = DoAction(request.BuildRequest());
string data = null;
if (httpResponse.Content != null)
{
data = Encoding.UTF8.GetString(httpResponse.Content);
}
var response = new CommonResponse
{
Data = data,
HttpResponse = httpResponse,
HttpStatus = httpResponse.Status
};
return response;
}
public HttpResponse DoAction<T>(AcsRequest<T> request) where T : AcsResponse
{
return DoAction(request, AutoRetry, MaxRetryNumber, clientProfile);
}
public HttpResponse DoAction<T>(AcsRequest<T> request, bool autoRetry, int maxRetryNumber)
where T : AcsResponse
{
return DoAction(request, autoRetry, maxRetryNumber, clientProfile);
}
public HttpResponse DoAction<T>(AcsRequest<T> request, IClientProfile profile) where T : AcsResponse
{
return DoAction(request, AutoRetry, MaxRetryNumber, profile);
}
public HttpResponse DoAction<T>(AcsRequest<T> request, string regionId, Credential credential)
where T : AcsResponse
{
var signer = Signer.GetSigner(new LegacyCredentials(credential));
FormatType? format = null;
if (null == request.RegionId)
{
request.RegionId = regionId;
}
if (request.ProductDomain == null)
{
request.ProductDomain = EndpointUserConfig.GetProductDomain(request.Product, request.RegionId);
if (request.ProductDomain == null)
{
request.SetProductDomain();
}
}
List<Endpoint> endpoints = null;
if (null != clientProfile)
{
format = clientProfile.GetFormat();
if (request.ProductDomain == null)
{
endpoints = clientProfile.GetEndpoints(request.Product, request.RegionId, request.LocationProduct,
request.LocationEndpointType);
}
}
return DoAction(request, AutoRetry, MaxRetryNumber, request.RegionId, credential, signer, format, endpoints);
}
public HttpResponse DoAction<T>(AcsRequest<T> request, bool autoRetry, int maxRetryNumber, IClientProfile profile) where T : AcsResponse
{
if (null == profile)
{
throw new ClientException("SDK.InvalidProfile", "No active profile found.");
}
var retry = autoRetry;
var retryNumber = maxRetryNumber;
var region = profile.GetRegionId();
if (null == request.RegionId)
{
request.RegionId = region;
}
if (request.ProductDomain == null)
{
request.ProductDomain = EndpointUserConfig.GetProductDomain(request.Product, request.RegionId);
if (request.ProductDomain == null)
{
request.SetProductDomain();
}
}
var credentials = credentialsProvider.GetCredentials();
if (credentials == null)
{
credentials = new DefaultCredentialProvider().GetAlibabaCloudClientCredential();
}
var signer = Signer.GetSigner(credentials);
var format = profile.GetFormat();
List<Endpoint> endpoints = null;
if (request.ProductDomain == null)
{
endpoints = clientProfile.GetEndpoints(request.Product, request.RegionId,
request.LocationProduct,
request.LocationEndpointType);
}
return DoAction(request, retry, retryNumber, request.RegionId, credentials, signer, format, endpoints);
}
public HttpResponse DoAction<T>(AcsRequest<T> request, bool autoRetry, int maxRetryNumber, string regionId,
Credential credential, Signer signer, FormatType? format, List<Endpoint> endpoints) where T : AcsResponse
{
return DoAction(request, autoRetry, maxRetryNumber, regionId, new LegacyCredentials(credential), signer,
format, endpoints);
}
private T ParseAcsResponse<T>(AcsRequest<T> request, HttpResponse httpResponse) where T : AcsResponse
{
CommonLog.LogInfo(request, httpResponse, CommonLog.ExecuteTime);
var format = httpResponse.ContentType;
if (httpResponse.isSuccess())
{
return ReadResponse(request, httpResponse, format);
}
try
{
var error = ReadError(request, httpResponse, format);
if (null != error.ErrorCode)
{
if (500 <= httpResponse.Status)
{
throw new ServerException(error.ErrorCode,
string.Format("{0}, the request url is {1}, the RequestId is {2}.", error.ErrorMessage,
httpResponse.Url ?? "empty", error.RequestId));
}
if (400 == httpResponse.Status && (error.ErrorCode.Equals("SignatureDoesNotMatch") ||
error.ErrorCode.Equals("IncompleteSignature")))
{
var errorMessage = error.ErrorMessage;
var re = new Regex(@"string to sign is:", RegexOptions.Compiled | RegexOptions.IgnoreCase);
var matches = re.Match(errorMessage);
if (matches.Success)
{
var errorStringToSign = errorMessage.Substring(matches.Index + matches.Length);
if (request.StringToSign.Equals(errorStringToSign))
{
throw new ClientException("SDK.InvalidAccessKeySecret",
"Specified Access Key Secret is not valid.", error.RequestId);
}
}
}
throw new ClientException(error.ErrorCode, error.ErrorMessage, error.RequestId);
}
}
catch (ServerException ex)
{
CommonLog.LogException(ex, ex.ErrorCode, ex.ErrorMessage);
throw new ServerException(ex.ErrorCode, ex.ErrorMessage, ex.RequestId);
}
catch (ClientException ex)
{
CommonLog.LogException(ex, ex.ErrorCode, ex.ErrorMessage);
throw new ClientException(ex.ErrorCode, ex.ErrorMessage, ex.RequestId);
}
var t = Activator.CreateInstance<T>();
t.HttpResponse = httpResponse;
return t;
}
public virtual HttpResponse DoAction<T>(AcsRequest<T> request, bool autoRetry, int maxRetryNumber,
string regionId,
AlibabaCloudCredentials credentials, Signer signer, FormatType? format, List<Endpoint> endpoints)
where T : AcsResponse
{
var httpStatusCode = "";
var retryAttemptTimes = 0;
ClientException exception;
RetryPolicyContext retryPolicyContext;
do
{
try
{
var watch = Stopwatch.StartNew();
FormatType? requestFormatType = request.AcceptFormat;
format = requestFormatType;
var domain = request.ProductDomain ??
Endpoint.FindProductDomain(regionId, request.Product, endpoints);
if (null == domain)
{
throw new ClientException("SDK.InvalidRegionId", "Can not find endpoint to access.");
}
var userAgent = UserAgent.Resolve(request.GetSysUserAgentConfig(), userAgentConfig);
DictionaryUtil.Add(request.Headers, "User-Agent", userAgent);
DictionaryUtil.Add(request.Headers, "x-acs-version", request.Version);
if (!string.IsNullOrWhiteSpace(request.ActionName))
{
DictionaryUtil.Add(request.Headers, "x-acs-action", request.ActionName);
}
var httpRequest = request.SignRequest(signer, credentials, format, domain);
ResolveTimeout(httpRequest, request.Product, request.Version, request.ActionName);
SetHttpsInsecure(IgnoreCertificate);
ResolveProxy(httpRequest, request);
var response = GetResponse(httpRequest);
httpStatusCode = response.Status.ToString();
PrintHttpDebugMsg(request, response);
watch.Stop();
CommonLog.ExecuteTime = watch.ElapsedMilliseconds;
return response;
}
catch (ClientException ex)
{
retryPolicyContext = new RetryPolicyContext(ex, httpStatusCode, retryAttemptTimes, request.Product,
request.Version,
request.ActionName, RetryCondition.BlankStatus);
CommonLog.LogException(ex, ex.ErrorCode, ex.ErrorMessage);
exception = ex;
}
Thread.Sleep(retryPolicy.GetDelayTimeBeforeNextRetry(retryPolicyContext));
} while ((retryPolicy.ShouldRetry(retryPolicyContext) & RetryCondition.NoRetry) != RetryCondition.NoRetry);
if (exception != null)
{
CommonLog.LogException(exception, exception.ErrorCode, exception.ErrorMessage);
throw new ClientException(exception.ErrorCode, exception.ErrorMessage);
}
return null;
}
private void PrintHttpDebugMsg(HttpRequest request, HttpResponse response)
{
var environmentDebugValue = Environment.GetEnvironmentVariable("DEBUG");
if (null != environmentDebugValue && environmentDebugValue.ToLower().Equals("sdk"))
{
if (null != request.Headers)
{
Console.WriteLine(
"> " + request.Method + "\n" +
"> " + request.Url + "\n"
);
DictionaryUtil.Print(request.Headers, '>');
Console.WriteLine(
"< " + response.Status
);
DictionaryUtil.Print(response.Headers, '<');
}
Environment.SetEnvironmentVariable("DEBUG", null);
}
}
private T ReadResponse<T>(AcsRequest<T> request, HttpResponse httpResponse, FormatType? format)
where T : AcsResponse
{
var reader = ReaderFactory.CreateInstance(format);
var context = new UnmarshallerContext();
var body = Encoding.UTF8.GetString(httpResponse.Content);
context.ResponseDictionary = request.CheckShowJsonItemName() ?
reader.Read(body, request.ActionName) :
reader.ReadForHideArrayItem(body, request.ActionName);
context.HttpResponse = httpResponse;
return request.GetResponse(context);
}
private AcsError ReadError<T>(AcsRequest<T> request, HttpResponse httpResponse, FormatType? format)
where T : AcsResponse
{
var responseEndpoint = "Error";
var reader = ReaderFactory.CreateInstance(format);
var context = new UnmarshallerContext();
var body = Encoding.Default.GetString(httpResponse.Content);
context.ResponseDictionary =
null == reader ? new Dictionary<string, string>() : reader.Read(body, responseEndpoint);
return AcsErrorUnmarshaller.Unmarshall(context);
}
public virtual HttpResponse GetResponse(HttpRequest httpRequest)
{
return HttpResponse.GetResponse(httpRequest);
}
public void AppendUserAgent(string key, string value)
{
userAgentConfig.AppendUserAgent(key, value);
}
public UserAgent GetUserAgentConfig()
{
return userAgentConfig;
}
public void SetConnectTimeoutInMilliSeconds(int connectTimeout)
{
ConnectTimeout = connectTimeout;
}
public void SetReadTimeoutInMilliSeconds(int readTimeout)
{
ReadTimeout = readTimeout;
}
private void ResolveTimeout(HttpRequest request, string product, string version, string actionName)
{
var apiReadTimeout = TimeoutConfig.GetSpecificApiReadTimeoutValue(product, version, actionName);
int finalReadTimeout;
if (request.ReadTimeout > 0)
{
finalReadTimeout = request.ReadTimeout;
}
else if (ReadTimeout > 0)
{
finalReadTimeout = ReadTimeout;
}
else if (apiReadTimeout > 0)
{
finalReadTimeout = apiReadTimeout;
}
else
{
finalReadTimeout = 0;
}
request.SetReadTimeoutInMilliSeconds(finalReadTimeout);
int finalConnectTimeout;
if (request.ConnectTimeout > 0)
{
finalConnectTimeout = request.ConnectTimeout;
}
else if (ConnectTimeout > 0)
{
finalConnectTimeout = ConnectTimeout;
}
else
{
finalConnectTimeout = 0;
}
request.SetConnectTimeoutInMilliSeconds(finalConnectTimeout);
}
public void SetHttpsInsecure(bool ignoreCertificate = false)
{
IgnoreCertificate = ignoreCertificate;
}
/// <summary>
/// Set Http Proxy
/// </summary>
/// <param name="httpProxy"></param>
public void SetHttpProxy(string httpProxy)
{
WebProxy.HttpProxy = httpProxy;
}
/// <summary>
/// Set Https Proxy
/// </summary>
/// <param name="httpsProxy"></param>
public void SetHttpsProxy(string httpsProxy)
{
WebProxy.HttpsProxy = httpsProxy;
}
/// <summary>
/// Set Proxy White List
/// </summary>
/// <param name="urls"></param>
public void SetNoProxy(string urls)
{
WebProxy.NoProxy = urls;
}
/// <summary>
/// Get Http Proxy
/// </summary>
/// <returns></returns>
public string GetHttpProxy()
{
return WebProxy.HttpProxy ?? Environment.GetEnvironmentVariable("HTTP_PROXY") ??
Environment.GetEnvironmentVariable("http_proxy");
}
/// <summary>
/// Get Https Proxy
/// </summary>
/// <returns></returns>
public string GetHttpsProxy()
{
return WebProxy.HttpsProxy ?? Environment.GetEnvironmentVariable("HTTPS_PROXY") ??
Environment.GetEnvironmentVariable("https_proxy");
}
/// <summary>
/// Get Proxy White List
/// </summary>
/// <returns></returns>
public string GetNoProxy()
{
return WebProxy.NoProxy ?? Environment.GetEnvironmentVariable("NO_PROXY") ??
Environment.GetEnvironmentVariable("no_proxy");
}
private void ResolveProxy<T>(HttpRequest httpRequest, AcsRequest<T> request) where T : AcsResponse
{
string authorization;
string proxy;
var noProxy = GetNoProxy() == null ? null : GetNoProxy().Split(',');
if (request.Protocol == ProtocolType.HTTP)
{
proxy = GetHttpProxy();
}
else
{
proxy = GetHttpsProxy();
}
if (!string.IsNullOrEmpty(proxy))
{
var originProxyUri = new Uri(proxy);
Uri finalProxyUri;
if (!string.IsNullOrEmpty(originProxyUri.UserInfo))
{
authorization =
Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1").GetBytes(originProxyUri.UserInfo));
finalProxyUri = new Uri(originProxyUri.Scheme + "://" + originProxyUri.Authority);
var userInfoArray = originProxyUri.UserInfo.Split(':');
ICredentials credential = new NetworkCredential(userInfoArray[0], userInfoArray[1]);
httpRequest.WebProxy = new WebProxy(finalProxyUri, false, noProxy, credential);
if (httpRequest.Headers.ContainsKey("Authorization"))
{
httpRequest.Headers.Remove("Authorization");
}
httpRequest.Headers.Add("Authorization", "Basic " + authorization);
}
else
{
finalProxyUri = originProxyUri;
httpRequest.WebProxy = new WebProxy(finalProxyUri, false, noProxy);
}
}
}
public static void EnableLogger(string template = CommonLog.DefaultTemplate)
{
CommonLog.EnableLogger(template);
}
public static void DisableLogger()
{
CommonLog.DisableLogger();
}
}
}