/
AWSConfigs.cs
642 lines (565 loc) · 22.2 KB
/
AWSConfigs.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
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
/*******************************************************************************
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use
* this file except in compliance with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file.
* This file 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.
* *****************************************************************************
* __ _ _ ___
* ( )( \/\/ )/ __)
* /__\ \ / \__ \
* (_)(_) \/\/ (___/
*
* AWS SDK for .NET
*
*/
using System;
using System.ComponentModel;
using System.Globalization;
using Amazon.Util;
using Amazon.Util.Internal;
using System.Collections.Generic;
using Amazon.Runtime;
namespace Amazon
{
/// <summary>
/// Configuration options that apply to the entire SDK.
///
/// These settings can be configured through app.config or web.config.
/// Below is a full sample configuration that illustrates all the possible options.
/// <code>
/// <configSections>
/// <section name="aws" type="Amazon.AWSSection, AWSSDK.Core"/>
/// </configSections>
/// <aws region="us-west-2">
/// <logging logTo="Log4Net, SystemDiagnostics" logResponses="Always" logMetrics="true" />
/// <s3 useSignatureVersion4="true" />
/// <proxy host="localhost" port="8888" username="1" password="1" />
///
/// <dynamoDB>
/// <dynamoDBContext tableNamePrefix="Prod-">
///
/// <tableAliases>
/// <alias fromTable="FakeTable" toTable="People" />
/// <alias fromTable="Persons" toTable="People" />
/// </tableAliases>
///
/// <mappings>
/// <map type="Sample.Tests.Author, SampleDLL" targetTable="People" />
/// <map type="Sample.Tests.Editor, SampleDLL" targetTable="People">
/// <property name="FullName" attribute="Name" />
/// <property name="EmployeeId" attribute="Id" />
/// <property name="ComplexData" converter="Sample.Tests.ComplexDataConverter, SampleDLL" />
/// <property name="Version" version="true" />
/// <property name="Password" ignore="true" />
/// </map>
/// </mappings>
///
/// </dynamoDBContext>
/// </dynamoDB>
/// </aws>
/// </code>
/// </summary>
public static partial class AWSConfigs
{
#region Private static members
private static char[] validSeparators = new char[] { ' ', ',' };
// Tests can override this DateTime source.
internal static Func<DateTime> utcNowSource = GetUtcNow;
// Deprecated configs
internal static string _awsRegion = GetConfig(AWSRegionKey);
internal static LoggingOptions _logging = GetLoggingSetting();
internal static ResponseLoggingOption _responseLogging = GetConfigEnum<ResponseLoggingOption>(ResponseLoggingKey);
internal static bool _logMetrics = GetConfigBool(LogMetricsKey);
internal static string _endpointDefinition = GetConfig(EndpointDefinitionKey);
internal static string _awsProfileName = GetConfig(AWSProfileNameKey);
internal static string _awsAccountsLocation = GetConfig(AWSProfilesLocationKey);
internal static bool _useSdkCache = GetConfigBool(UseSdkCacheKey, defaultValue: true);
// for reading from awsconfigs.xml
private static object _lock = new object();
private static List<string> standardConfigs = new List<string>() { "region", "logging", "correctForClockSkew" };
#pragma warning disable 414
private static bool configPresent = true;
#pragma warning restore 414
// New config section
private static RootConfig _rootConfig = new RootConfig();
#endregion
#region Clock Skew
/// <summary>
/// Manual offset to apply to client clock. This is a global setting that overrides
/// ClockOffset value calculated for all service endpoints.
/// </summary>
public static TimeSpan? ManualClockCorrection
{
get
{
return Runtime.CorrectClockSkew.GlobalClockCorrection;
}
set
{
Runtime.CorrectClockSkew.GlobalClockCorrection = value;
}
}
/// <summary>
/// Determines if the SDK should correct for client clock skew
/// by determining the correct server time and reissuing the
/// request with the correct time.
/// Default value of this field is True.
/// <seealso cref="ClockOffset"/> will be updated with the calculated
/// offset even if this field is set to false, though requests
/// will not be corrected or retried.
/// Ignored if <seealso cref="ManualClockCorrection"/> is set.
/// </summary>
public static bool CorrectForClockSkew
{
get { return _rootConfig.CorrectForClockSkew; }
set { _rootConfig.CorrectForClockSkew = value; }
}
/// <summary>
/// The calculated clock skew correction, if there is one.
/// This field will be set if a service call resulted in an exception
/// and the SDK has determined that there is a difference between local
/// and server times.
///
/// If <seealso cref="CorrectForClockSkew"/> is set to true, this
/// value will be set to the correction, but it will not be used by the
/// SDK and clock skew errors will not be retried.
/// </summary>
[Obsolete("This value is deprecated in favor of IClientConfig.ClockOffset")]
public static TimeSpan ClockOffset
{
get;
internal set;
}
#endregion
#region Region
/// <summary>
/// Key for the AWSRegion property.
/// <seealso cref="Amazon.AWSConfigs.AWSRegion"/>
/// </summary>
public const string AWSRegionKey = "AWSRegion";
/// <summary>
/// Configures the default AWS region for clients which have not explicitly specified a region.
/// Changes to this setting will only take effect for newly constructed instances of AWS clients.
///
/// This setting can be configured through the App.config. For example:
/// <code>
/// <configSections>
/// <section name="aws" type="Amazon.AWSSection, AWSSDK.Core"/>
/// </configSections>
/// <aws region="us-west-2" />
/// </code>
/// </summary>
public static string AWSRegion
{
get { return _rootConfig.Region; }
set { _rootConfig.Region = value; }
}
#endregion
#region Account Name
/// <summary>
/// Key for the AWSProfileName property.
/// <seealso cref="Amazon.AWSConfigs.AWSProfileName"/>
/// </summary>
public const string AWSProfileNameKey = "AWSProfileName";
/// <summary>
/// Profile name for stored AWS credentials that will be used to make service calls.
/// Changes to this setting will only take effect in newly-constructed clients.
/// <para>
/// To reference the account from an application's App.config or Web.config use the AWSProfileName setting.
/// <code>
/// <?xml version="1.0" encoding="utf-8" ?>
/// <configuration>
/// <appSettings>
/// <add key="AWSProfileName" value="development"/>
/// </appSettings>
/// </configuration>
/// </code>
/// </para>
/// </summary>
public static string AWSProfileName
{
get { return _rootConfig.ProfileName; }
set { _rootConfig.ProfileName = value; }
}
#endregion
#region Accounts Location
/// <summary>
/// Key for the AWSProfilesLocation property.
/// <seealso cref="Amazon.AWSConfigs.LogMetrics"/>
/// </summary>
public const string AWSProfilesLocationKey = "AWSProfilesLocation";
/// <summary>
/// Location of the credentials file shared with other AWS SDKs.
/// By default, the credentials file is stored in the .aws directory in the current user's home directory.
///
/// Changes to this setting will only take effect in newly-constructed clients.
/// <para>
/// To reference the profile from an application's App.config or Web.config use the AWSProfileName setting.
/// <code>
/// <?xml version="1.0" encoding="utf-8" ?>
/// <configuration>
/// <appSettings>
/// <add key="AWSProfilesLocation" value="c:\config"/>
/// </appSettings>
/// </configuration>
/// </code>
/// </para>
/// </summary>
public static string AWSProfilesLocation
{
get { return _rootConfig.ProfilesLocation; }
set { _rootConfig.ProfilesLocation = value; }
}
#endregion
#region Logging
/// <summary>
/// Key for the Logging property.
/// <seealso cref="Amazon.AWSConfigs.Logging"/>
/// </summary>
public const string LoggingKey = "AWSLogging";
/// <summary>
/// Configures how the SDK should log events, if at all.
/// Changes to this setting will only take effect in newly-constructed clients.
///
/// The setting can be configured through App.config, for example:
/// <code>
/// <appSettings>
/// <add key="AWSLogging" value="log4net"/>
/// </appSettings>
/// </code>
/// </summary>
[Obsolete("This property is obsolete. Use LoggingConfig.LogTo instead.")]
public static LoggingOptions Logging
{
get { return _rootConfig.Logging.LogTo; }
set { _rootConfig.Logging.LogTo = value; }
}
private static LoggingOptions GetLoggingSetting()
{
string value = GetConfig(LoggingKey);
if (string.IsNullOrEmpty(value))
return LoggingOptions.None;
string[] settings = value.Split(validSeparators, StringSplitOptions.RemoveEmptyEntries);
if (settings == null || settings.Length == 0)
return LoggingOptions.None;
LoggingOptions totalSetting = LoggingOptions.None;
foreach (string setting in settings)
{
LoggingOptions l = ParseEnum<LoggingOptions>(setting);
totalSetting |= l;
}
return totalSetting;
}
#endregion
#region Response Logging
/// <summary>
/// Key for the ResponseLogging property.
///
/// <seealso cref="Amazon.AWSConfigs.ResponseLogging"/>
/// </summary>
public const string ResponseLoggingKey = "AWSResponseLogging";
/// <summary>
/// Configures when the SDK should log service responses.
/// Changes to this setting will take effect immediately.
///
/// The setting can be configured through App.config, for example:
/// <code>
/// <appSettings>
/// <add key="AWSResponseLogging" value="OnError"/>
/// </appSettings>
/// </code>
/// </summary>
[Obsolete("This property is obsolete. Use LoggingConfig.LogResponses instead.")]
public static ResponseLoggingOption ResponseLogging
{
get { return _rootConfig.Logging.LogResponses; }
set { _rootConfig.Logging.LogResponses = value; }
}
#endregion
#region Log Metrics
/// <summary>
/// Key for the LogMetrics property.
/// <seealso cref="Amazon.AWSConfigs.LogMetrics"/>
/// </summary>
public const string LogMetricsKey = "AWSLogMetrics";
/// <summary>
/// Configures if the SDK should log performance metrics.
/// This setting configures the default LogMetrics property for all clients/configs.
/// Changes to this setting will only take effect in newly-constructed clients.
///
/// The setting can be configured through App.config, for example:
/// <code>
/// <appSettings>
/// <add key="AWSLogMetrics" value="true"/>
/// </appSettings>
/// </code>
/// </summary>
[Obsolete("This property is obsolete. Use LoggingConfig.LogMetrics instead.")]
public static bool LogMetrics
{
get { return _rootConfig.Logging.LogMetrics; }
set { _rootConfig.Logging.LogMetrics = value; }
}
#endregion
#region Endpoint Configuration
/// <summary>
/// Key for the EndpointDefinition property.
/// <seealso cref="Amazon.AWSConfigs.EndpointDefinition"/>
/// </summary>
public const string EndpointDefinitionKey = "AWSEndpointDefinition";
/// <summary>
/// Configures if the SDK should use a custom configuration file that defines the regions and endpoints.
/// <code>
/// <configSections>
/// <section name="aws" type="Amazon.AWSSection, AWSSDK.Core"/>
/// </configSections>
/// <aws endpointDefinition="c:\config\endpoints.json" />
/// </code>
/// </summary>
public static string EndpointDefinition
{
get { return _rootConfig.EndpointDefinition; }
set { _rootConfig.EndpointDefinition = value; }
}
#endregion
#region SDK Cache
/// <summary>
/// Key for the UseSdkCache property.
/// <seealso cref="Amazon.AWSConfigs.UseSdkCache"/>
/// </summary>
public const string UseSdkCacheKey = "AWSCache";
/// <summary>
/// Configures if the SDK Cache should be used, the default value is true.
/// <code>
/// <configSections>
/// <section name="aws" type="Amazon.AWSSection, AWSSDK.Core"/>
/// </configSections>
/// <aws useSdkCache="true" />
/// </code>
/// </summary>
public static bool UseSdkCache
{
get { return _rootConfig.UseSdkCache; }
set { _rootConfig.UseSdkCache = value; }
}
#endregion
#region AWS Config Sections
/// <summary>
/// Configuration for the Logging section of AWS configuration.
/// Changes to some settings may not take effect until a new client is constructed.
///
/// Example section:
/// <code>
/// <configSections>
/// <section name="aws" type="Amazon.AWSSection, AWSSDK.Core"/>
/// </configSections>
/// <aws>
/// <logging logTo="Log4Net, SystemDiagnostics" logResponses="Always" logMetrics="true" />
/// </aws>
/// </code>
/// </summary>
public static LoggingConfig LoggingConfig { get { return _rootConfig.Logging; } }
/// <summary>
/// Configuration for the Proxy section of AWS configuration.
/// Changes to some settings may not take effect until a new client is constructed.
///
/// Example section:
/// <code>
/// <configSections>
/// <section name="aws" type="Amazon.AWSSection, AWSSDK.Core"/>
/// </configSections>
/// <aws>
/// <proxy host="localhost" port="8888" username="1" password="1" bypassList="addressexpr1;addressexpr2;..." bypassOnLocal="true" />
/// </aws>
/// </code>
/// </summary>
public static ProxyConfig ProxyConfig { get { return _rootConfig.Proxy; } }
/// <summary>
/// When set to true, the service client will use the x-amz-user-agent
/// header instead of the User-Agent header to report version and
/// environment information to the AWS service.
///
/// Note: This is especially useful when using a platform like WebAssembly
/// which doesn't allow to specify the User-Agent header.
/// </summary>
public static bool UseAlternateUserAgentHeader
{
get { return _rootConfig.UseAlternateUserAgentHeader; }
set { _rootConfig.UseAlternateUserAgentHeader = value; }
}
/// <summary>
/// Configuration for the region endpoint section of AWS configuration.
/// Changes may not take effect until a new client is constructed.
///
/// Example section:
/// <code>
/// <configSections>
/// <section name="aws" type="Amazon.AWSSection, AWSSDK.Core"/>
/// </configSections>
/// <aws region="us-west-2" />
/// </code>
/// </summary>
public static RegionEndpoint RegionEndpoint
{
get { return _rootConfig.RegionEndpoint; }
set { _rootConfig.RegionEndpoint = value; }
}
public static CSMConfig CSMConfig
{
get { return _rootConfig.CSMConfig; }
set { _rootConfig.CSMConfig = value; }
}
#endregion
#region Internal members
internal const string LoggingDestinationProperty = "LogTo";
internal static PropertyChangedEventHandler mPropertyChanged;
/// <summary>
/// Lock for SomeEvent delegate access.
/// </summary>
internal static readonly object propertyChangedLock = new object();
internal static event PropertyChangedEventHandler PropertyChanged
{
add
{
lock (propertyChangedLock)
{
mPropertyChanged += value;
}
}
remove
{
lock (propertyChangedLock)
{
mPropertyChanged -= value;
}
}
}
internal static void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = mPropertyChanged;
if (handler != null)
{
handler(null, new PropertyChangedEventArgs(name));
}
}
#endregion
#region Private general methods
private static bool GetConfigBool(string name, bool defaultValue = false)
{
string value = GetConfig(name);
bool result;
if (bool.TryParse(value, out result))
return result;
return defaultValue;
}
private static T GetConfigEnum<T>(string name)
{
var type = TypeFactory.GetTypeInfo(typeof(T));
if (!type.IsEnum) throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "Type {0} must be enum", type.FullName));
string value = GetConfig(name);
if (string.IsNullOrEmpty(value))
return default(T);
T result = ParseEnum<T>(value);
return result;
}
private static T ParseEnum<T>(string value)
{
T t;
if (TryParseEnum<T>(value, out t))
return t;
Type type = typeof(T);
string messageFormat = "Unable to parse value {0} as enum of type {1}. Valid values are: {2}";
string enumNames = string.Join(", ", Enum.GetNames(type));
throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, messageFormat, value, type.FullName, enumNames));
}
private static bool TryParseEnum<T>(string value, out T result)
{
result = default(T);
if (string.IsNullOrEmpty(value))
return false;
try
{
T t = (T)Enum.Parse(typeof(T), value, true);
result = t;
return true;
}
catch (ArgumentException)
{
return false;
}
}
/// <summary>
/// This method should never be called directly.
/// Call AWSSDKUtils.CorrectedUtcNow instead.
/// </summary>
/// <returns></returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("AwsSdkRules", "CR1003:PreventDateTimeNowUseRule")]
private static DateTime GetUtcNow()
{
return DateTime.UtcNow;
}
#endregion
}
/// <summary>
/// Logging options.
/// Can be combined to enable multiple loggers.
/// </summary>
[Flags]
public enum LoggingOptions
{
/// <summary>
/// No logging
/// </summary>
None = 0,
/// <summary>
/// Log using log4net
/// </summary>
Log4Net = 1,
/// <summary>
/// Log using System.Diagnostics
/// </summary>
SystemDiagnostics = 2,
/// <summary>
/// Log to the console
/// </summary>
Console = 16
}
/// <summary>
/// Response logging option.
/// </summary>
public enum ResponseLoggingOption
{
/// <summary>
/// Never log service response
/// </summary>
Never = 0,
/// <summary>
/// Only log service response when there's an error
/// </summary>
OnError = 1,
/// <summary>
/// Always log service response
/// </summary>
Always = 2
}
/// <summary>
/// Format for metrics data in the logs
/// </summary>
public enum LogMetricsFormatOption
{
/// <summary>
/// Emit metrics in human-readable format
/// </summary>
Standard = 0,
/// <summary>
/// Emit metrics as JSON data
/// </summary>
JSON = 1
}
}