This repository has been archived by the owner on Apr 27, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 192
/
Copy pathClient.cs
1850 lines (1603 loc) · 69 KB
/
Client.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
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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Threading;
using Newtonsoft.Json;
using System.Threading.Tasks;
using System.Net.Http.Headers;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
#if !(CORECLR || PORTABLE || PORTABLE40)
using System.Security.Permissions;
using System.Runtime.Serialization;
#endif
namespace Consul
{
/// <summary>
/// Represents errors that occur while sending data to or fetching data from the Consul agent.
/// </summary>
#if !(CORECLR || PORTABLE || PORTABLE40)
[Serializable]
#endif
public class ConsulRequestException : Exception
{
public HttpStatusCode StatusCode { get; set; }
public ConsulRequestException() { }
public ConsulRequestException(string message, HttpStatusCode statusCode) : base(message) { StatusCode = statusCode; }
public ConsulRequestException(string message, HttpStatusCode statusCode, Exception inner) : base(message, inner) { StatusCode = statusCode; }
#if !(CORECLR || PORTABLE || PORTABLE40)
protected ConsulRequestException(
SerializationInfo info,
StreamingContext context) : base(info, context) { }
[SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)]
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
base.GetObjectData(info, context);
info.AddValue("StatusCode", StatusCode);
}
#endif
}
/// <summary>
/// Represents errors that occur during initalization of the Consul client's configuration.
/// </summary>
#if !(CORECLR || PORTABLE || PORTABLE40)
[Serializable]
#endif
public class ConsulConfigurationException : Exception
{
public ConsulConfigurationException() { }
public ConsulConfigurationException(string message) : base(message) { }
public ConsulConfigurationException(string message, Exception inner) : base(message, inner) { }
#if !(CORECLR || PORTABLE || PORTABLE40)
protected ConsulConfigurationException(
System.Runtime.Serialization.SerializationInfo info,
System.Runtime.Serialization.StreamingContext context) : base(info, context) { }
#endif
}
/// <summary>
/// Represents the configuration options for a Consul client.
/// </summary>
public class ConsulClientConfiguration
{
private NetworkCredential _httpauth;
private bool _disableServerCertificateValidation;
private X509Certificate2 _clientCertificate;
internal event EventHandler Updated;
internal static Lazy<bool> _clientCertSupport = new Lazy<bool>(() => { return Type.GetType("Mono.Runtime") == null; });
internal bool ClientCertificateSupported { get { return _clientCertSupport.Value; } }
#if CORECLR
[Obsolete("Use of DisableServerCertificateValidation should be converted to setting the HttpHandler's ServerCertificateCustomValidationCallback in the ConsulClient constructor" +
"This property will be removed when 0.8.0 is released.", false)]
#else
[Obsolete("Use of DisableServerCertificateValidation should be converted to setting the WebRequestHandler's ServerCertificateValidationCallback in the ConsulClient constructor" +
"This property will be removed when 0.8.0 is released.", false)]
#endif
internal bool DisableServerCertificateValidation
{
get
{
return _disableServerCertificateValidation;
}
set
{
_disableServerCertificateValidation = value;
OnUpdated(new EventArgs());
}
}
/// <summary>
/// The Uri to connect to the Consul agent.
/// </summary>
public Uri Address { get; set; }
/// <summary>
/// Datacenter to provide with each request. If not provided, the default agent datacenter is used.
/// </summary>
public string Datacenter { get; set; }
/// <summary>
/// Credentials to use for access to the HTTP API.
/// This is only needed if an authenticating service exists in front of Consul; Token is used for ACL authentication by Consul.
/// </summary>
#if CORECLR
[Obsolete("Use of HttpAuth should be converted to setting the HttpHandler's Credential property in the ConsulClient constructor" +
"This property will be removed when 0.8.0 is released.", false)]
#else
[Obsolete("Use of HttpAuth should be converted to setting the WebRequestHandler's Credential property in the ConsulClient constructor" +
"This property will be removed when 0.8.0 is released.", false)]
#endif
public NetworkCredential HttpAuth
{
internal get
{
return _httpauth;
}
set
{
_httpauth = value;
OnUpdated(new EventArgs());
}
}
/// <summary>
/// TLS Client Certificate used to secure a connection to a Consul agent. Not supported on Mono.
/// This is only needed if an authenticating service exists in front of Consul; Token is used for ACL authentication by Consul. This is not the same as RPC Encryption with TLS certificates.
/// </summary>
/// <exception cref="PlatformNotSupportedException">Setting this property will throw a PlatformNotSupportedException on Mono</exception>
#if __MonoCS__
[Obsolete("Client Certificates are not implemented in Mono", true)]
#elif CORECLR
[Obsolete("Use of ClientCertificate should be converted to adding to the HttpHandler's ClientCertificates list in the ConsulClient constructor." +
"This property will be removed when 0.8.0 is released.", false)]
#else
[Obsolete("Use of ClientCertificate should be converted to adding to the WebRequestHandler's ClientCertificates list in the ConsulClient constructor." +
"This property will be removed when 0.8.0 is released.", false)]
#endif
public X509Certificate2 ClientCertificate
{
internal get
{
return _clientCertificate;
}
set
{
if (!ClientCertificateSupported)
{
throw new PlatformNotSupportedException("Client certificates are not supported on this platform");
}
_clientCertificate = value;
OnUpdated(new EventArgs());
}
}
/// <summary>
/// Token is used to provide an ACL token which overrides the agent's default token. This ACL token is used for every request by
/// clients created using this configuration.
/// </summary>
public string Token { get; set; }
/// <summary>
/// WaitTime limits how long a Watch will block. If not provided, the agent default values will be used.
/// </summary>
public TimeSpan? WaitTime { get; set; }
/// <summary>
/// Creates a new instance of a Consul client configuration.
/// </summary>
/// <exception cref="ConsulConfigurationException">An error that occured while building the configuration.</exception>
public ConsulClientConfiguration()
{
UriBuilder consulAddress = new UriBuilder("http://127.0.0.1:8500");
ConfigureFromEnvironment(consulAddress);
Address = consulAddress.Uri;
}
/// <summary>
/// Builds configuration based on environment variables.
/// </summary>
/// <exception cref="ConsulConfigurationException">An environment variable could not be parsed</exception>
private void ConfigureFromEnvironment(UriBuilder consulAddress)
{
var envAddr = (Environment.GetEnvironmentVariable("CONSUL_HTTP_ADDR") ?? string.Empty).Trim().ToLowerInvariant();
if (!string.IsNullOrEmpty(envAddr))
{
var addrParts = envAddr.Split(':');
for (int i = 0; i < addrParts.Length; i++)
{
addrParts[i] = addrParts[i].Trim();
}
if (!string.IsNullOrEmpty(addrParts[0]))
{
consulAddress.Host = addrParts[0];
}
if (addrParts.Length > 1 && !string.IsNullOrEmpty(addrParts[1]))
{
try
{
consulAddress.Port = ushort.Parse(addrParts[1]);
}
catch (Exception ex)
{
throw new ConsulConfigurationException("Failed parsing port from environment variable CONSUL_HTTP_ADDR", ex);
}
}
}
var useSsl = (Environment.GetEnvironmentVariable("CONSUL_HTTP_SSL") ?? string.Empty).Trim().ToLowerInvariant();
if (!string.IsNullOrEmpty(useSsl))
{
try
{
if (useSsl == "1" || bool.Parse(useSsl))
{
consulAddress.Scheme = "https";
}
}
catch (Exception ex)
{
throw new ConsulConfigurationException("Could not parse environment variable CONSUL_HTTP_SSL", ex);
}
}
var verifySsl = (Environment.GetEnvironmentVariable("CONSUL_HTTP_SSL_VERIFY") ?? string.Empty).Trim().ToLowerInvariant();
if (!string.IsNullOrEmpty(verifySsl))
{
try
{
if (verifySsl == "0" || bool.Parse(verifySsl))
{
#pragma warning disable CS0618 // Type or member is obsolete
DisableServerCertificateValidation = true;
#pragma warning restore CS0618 // Type or member is obsolete
}
}
catch (Exception ex)
{
throw new ConsulConfigurationException("Could not parse environment variable CONSUL_HTTP_SSL_VERIFY", ex);
}
}
var auth = Environment.GetEnvironmentVariable("CONSUL_HTTP_AUTH");
if (!string.IsNullOrEmpty(auth))
{
var credential = new NetworkCredential();
if (auth.Contains(":"))
{
var split = auth.Split(':');
credential.UserName = split[0];
credential.Password = split[1];
}
else
{
credential.UserName = auth;
}
#pragma warning disable CS0618 // Type or member is obsolete
HttpAuth = credential;
#pragma warning restore CS0618 // Type or member is obsolete
}
if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("CONSUL_HTTP_TOKEN")))
{
Token = Environment.GetEnvironmentVariable("CONSUL_HTTP_TOKEN");
}
}
internal virtual void OnUpdated(EventArgs e)
{
// Make a temporary copy of the event to avoid possibility of
// a race condition if the last subscriber unsubscribes
// immediately after the null check and before the event is raised.
EventHandler handler = Updated;
// Event will be null if there are no subscribers
handler?.Invoke(this, e);
}
}
/// <summary>
/// The consistency mode of a request.
/// </summary>
/// <see cref="http://www.consul.io/docs/agent/http.html"/>
public enum ConsistencyMode
{
/// <summary>
/// Default is strongly consistent in almost all cases. However, there is a small window in which a new leader may be elected during which the old leader may service stale values. The trade-off is fast reads but potentially stale values. The condition resulting in stale reads is hard to trigger, and most clients should not need to worry about this case. Also, note that this race condition only applies to reads, not writes.
/// </summary>
Default,
/// <summary>
/// Consistent forces the read to be fully consistent. This mode is strongly consistent without caveats. It requires that a leader verify with a quorum of peers that it is still leader. This introduces an additional round-trip to all server nodes. The trade-off is increased latency due to an extra round trip. Most clients should not use this unless they cannot tolerate a stale read.
/// </summary>
Consistent,
/// <summary>
/// Stale allows any Consul server (non-leader) to service a read. This mode allows any server to service the read regardless of whether it is the leader. This means reads can be arbitrarily stale; however, results are generally consistent to within 50 milliseconds of the leader. The trade-off is very fast and scalable reads with a higher likelihood of stale values. Since this mode allows reads without a leader, a cluster that is unavailable will still be able to respond to queries.
/// </summary>
Stale
}
/// <summary>
/// QueryOptions are used to parameterize a query
/// </summary>
public class QueryOptions
{
public static readonly QueryOptions Default = new QueryOptions()
{
Consistency = ConsistencyMode.Default,
Datacenter = string.Empty,
Token = string.Empty,
WaitIndex = 0
};
/// <summary>
/// Providing a datacenter overwrites the DC provided by the Config
/// </summary>
public string Datacenter { get; set; }
/// <summary>
/// The consistency level required for the operation
/// </summary>
public ConsistencyMode Consistency { get; set; }
/// <summary>
/// WaitIndex is used to enable a blocking query. Waits until the timeout or the next index is reached
/// </summary>
public ulong WaitIndex { get; set; }
/// <summary>
/// WaitTime is used to bound the duration of a wait. Defaults to that of the Config, but can be overridden.
/// </summary>
public TimeSpan? WaitTime { get; set; }
/// <summary>
/// Token is used to provide a per-request ACL token which overrides the agent's default token.
/// </summary>
public string Token { get; set; }
/// <summary>
/// Near is used to provide a node name that will sort the results
/// in ascending order based on the estimated round trip time from
/// that node. Setting this to "_agent" will use the agent's node
/// for the sort.
/// </summary>
public string Near { get; set; }
}
/// <summary>
/// WriteOptions are used to parameterize a write
/// </summary>
public class WriteOptions
{
public static readonly WriteOptions Default = new WriteOptions()
{
Datacenter = string.Empty,
Token = string.Empty
};
/// <summary>
/// Providing a datacenter overwrites the DC provided by the Config
/// </summary>
public string Datacenter { get; set; }
/// <summary>
/// Token is used to provide a per-request ACL token which overrides the agent's default token.
/// </summary>
public string Token { get; set; }
}
public abstract class ConsulResult
{
/// <summary>
/// How long the request took
/// </summary>
public TimeSpan RequestTime { get; set; }
/// <summary>
/// Exposed so that the consumer can to check for a specific status code
/// </summary>
public HttpStatusCode StatusCode { get; set; }
public ConsulResult() { }
public ConsulResult(ConsulResult other)
{
RequestTime = other.RequestTime;
StatusCode = other.StatusCode;
}
}
/// <summary>
/// The result of a Consul API query
/// </summary>
public class QueryResult : ConsulResult
{
/// <summary>
/// The index number when the query was serviced. This can be used as a WaitIndex to perform a blocking query
/// </summary>
public ulong LastIndex { get; set; }
/// <summary>
/// Time of last contact from the leader for the server servicing the request
/// </summary>
public TimeSpan LastContact { get; set; }
/// <summary>
/// Is there a known leader
/// </summary>
public bool KnownLeader { get; set; }
/// <summary>
/// Is address translation enabled for HTTP responses on this agent
/// </summary>
public bool AddressTranslationEnabled { get; set; }
public QueryResult() { }
public QueryResult(QueryResult other) : base(other)
{
LastIndex = other.LastIndex;
LastContact = other.LastContact;
KnownLeader = other.KnownLeader;
}
}
/// <summary>
/// The result of a Consul API query
/// </summary>
/// <typeparam name="T">Must be able to be deserialized from JSON</typeparam>
public class QueryResult<T> : QueryResult
{
/// <summary>
/// The result of the query
/// </summary>
public T Response { get; set; }
public QueryResult() { }
public QueryResult(QueryResult other) : base(other) { }
public QueryResult(QueryResult other, T value) : base(other)
{
Response = value;
}
}
/// <summary>
/// The result of a Consul API write
/// </summary>
public class WriteResult : ConsulResult
{
public WriteResult() { }
public WriteResult(WriteResult other) : base(other) { }
}
/// <summary>
/// The result of a Consul API write
/// </summary>
/// <typeparam name="T">Must be able to be deserialized from JSON. Some writes return nothing, in which case this should be an empty Object</typeparam>
public class WriteResult<T> : WriteResult
{
/// <summary>
/// The result of the write
/// </summary>
public T Response { get; set; }
public WriteResult() { }
public WriteResult(WriteResult other) : base(other) { }
public WriteResult(WriteResult other, T value) : base(other)
{
Response = value;
}
}
/// <summary>
/// Represents a persistant connection to a Consul agent. Instances of this class should be created rarely and reused often.
/// </summary>
public partial class ConsulClient : IDisposable
{
/// <summary>
/// This class is used to group all the configurable bits of a ConsulClient into a single pointer reference
/// which is great for implementing reconfiguration later.
/// </summary>
private class ConsulClientConfigurationContainer
{
internal readonly bool skipClientDispose;
internal readonly HttpClient HttpClient;
#if CORECLR
internal readonly HttpClientHandler HttpHandler;
#else
internal readonly WebRequestHandler HttpHandler;
#endif
public readonly ConsulClientConfiguration Config;
public ConsulClientConfigurationContainer()
{
Config = new ConsulClientConfiguration();
#if CORECLR
HttpHandler = new HttpClientHandler();
#else
HttpHandler = new WebRequestHandler();
#endif
HttpClient = new HttpClient(HttpHandler);
HttpClient.Timeout = TimeSpan.FromMinutes(15);
HttpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpClient.DefaultRequestHeaders.Add("Keep-Alive", "true");
}
#region Old style config handling
public ConsulClientConfigurationContainer(ConsulClientConfiguration config, HttpClient client)
{
skipClientDispose = true;
Config = config;
HttpClient = client;
}
public ConsulClientConfigurationContainer(ConsulClientConfiguration config)
{
Config = config;
#if CORECLR
HttpHandler = new HttpClientHandler();
#else
HttpHandler = new WebRequestHandler();
#endif
HttpClient = new HttpClient(HttpHandler);
HttpClient.Timeout = TimeSpan.FromMinutes(15);
HttpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpClient.DefaultRequestHeaders.Add("Keep-Alive", "true");
}
#endregion
#region IDisposable Support
private bool disposedValue = false; // To detect redundant calls
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
if (HttpClient != null && !skipClientDispose)
{
HttpClient.Dispose();
}
if (HttpHandler != null)
{
HttpHandler.Dispose();
}
}
disposedValue = true;
}
}
//~ConsulClient()
//{
// // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
// Dispose(false);
//}
// This code added to correctly implement the disposable pattern.
public void Dispose()
{
// Do not change this code. Put cleanup code in Dispose(bool disposing) above.
Dispose(true);
GC.SuppressFinalize(this);
}
public void CheckDisposed()
{
if (disposedValue)
{
throw new ObjectDisposedException(typeof(ConsulClientConfigurationContainer).FullName.ToString());
}
}
#endregion
}
private ConsulClientConfigurationContainer ConfigContainer;
internal HttpClient HttpClient { get { return ConfigContainer.HttpClient; } }
#if CORECLR
internal HttpClientHandler HttpHandler { get { return ConfigContainer.HttpHandler; } }
#else
internal WebRequestHandler HttpHandler { get { return ConfigContainer.HttpHandler; } }
#endif
public ConsulClientConfiguration Config { get { return ConfigContainer.Config; } }
internal readonly JsonSerializer serializer = new JsonSerializer();
#region New style config with Actions
/// <summary>
/// Initializes a new Consul client with a default configuration that connects to 127.0.0.1:8500.
/// </summary>
public ConsulClient() : this(null, null, null) { }
/// <summary>
/// Initializes a new Consul client with the ability to set portions of the configuration.
/// </summary>
/// <param name="configOverride">The Action to modify the default configuration with</param>
public ConsulClient(Action<ConsulClientConfiguration> configOverride) : this(configOverride, null, null) { }
/// <summary>
/// Initializes a new Consul client with the ability to set portions of the configuration and access the underlying HttpClient for modification.
/// The HttpClient is modified to set options like the request timeout and headers.
/// The Timeout property also applies to all long-poll requests and should be set to a value that will encompass all successful requests.
/// </summary>
/// <param name="configOverride">The Action to modify the default configuration with</param>
/// <param name="clientOverride">The Action to modify the HttpClient with</param>
public ConsulClient(Action<ConsulClientConfiguration> configOverride, Action<HttpClient> clientOverride) : this(configOverride, clientOverride, null) { }
/// <summary>
/// Initializes a new Consul client with the ability to set portions of the configuration and access the underlying HttpClient and WebRequestHandler for modification.
/// The HttpClient is modified to set options like the request timeout and headers.
/// The WebRequestHandler is modified to set options like Proxy and Credentials.
/// The Timeout property also applies to all long-poll requests and should be set to a value that will encompass all successful requests.
/// </summary>
/// <param name="configOverride">The Action to modify the default configuration with</param>
/// <param name="clientOverride">The Action to modify the HttpClient with</param>
/// <param name="handlerOverride">The Action to modify the WebRequestHandler with</param>
#if !CORECLR
public ConsulClient(Action<ConsulClientConfiguration> configOverride, Action<HttpClient> clientOverride, Action<WebRequestHandler> handlerOverride)
#else
public ConsulClient(Action<ConsulClientConfiguration> configOverride, Action<HttpClient> clientOverride, Action<HttpClientHandler> handlerOverride)
#endif
{
var ctr = new ConsulClientConfigurationContainer();
configOverride?.Invoke(ctr.Config);
ApplyConfig(ctr.Config, ctr.HttpHandler, ctr.HttpClient);
handlerOverride?.Invoke(ctr.HttpHandler);
clientOverride?.Invoke(ctr.HttpClient);
ConfigContainer = ctr;
InitializeEndpoints();
}
#endregion
#region Old style config
/// <summary>
/// Initializes a new Consul client with the configuration specified.
/// </summary>
/// <param name="config">A Consul client configuration</param>
[Obsolete("This constructor is no longer necessary due to the new Action based constructors and will be removed when 0.8.0 is released." +
"Please use the ConsulClient(Action<ConsulClientConfiguration>) constructor to set configuration options.", false)]
public ConsulClient(ConsulClientConfiguration config)
{
config.Updated += HandleConfigUpdateEvent;
var ctr = new ConsulClientConfigurationContainer(config);
ApplyConfig(ctr.Config, ctr.HttpHandler, ctr.HttpClient);
ConfigContainer = ctr;
InitializeEndpoints();
}
/// <summary>
/// Initializes a new Consul client with the configuration specified and a custom HttpClient, which is useful for setting proxies/custom timeouts.
/// The HttpClient must accept the "application/json" content type and the Timeout property should be set to at least 15 minutes to allow for blocking queries.
/// </summary>
/// <param name="config">A Consul client configuration</param>
/// <param name="client">A custom HttpClient</param>
[Obsolete("This constructor is no longer necessary due to the new Action based constructors and will be removed when 0.8.0 is released." +
"Please use one of the ConsulClient(Action<>) constructors instead to set internal options on the HttpClient/WebRequestHandler.", false)]
public ConsulClient(ConsulClientConfiguration config, HttpClient client)
{
var ctr = new ConsulClientConfigurationContainer(config, client);
if (!ctr.HttpClient.DefaultRequestHeaders.Accept.Contains(new MediaTypeWithQualityHeaderValue("application/json")))
{
throw new ArgumentException("HttpClient must accept the application/json content type", nameof(client));
}
ConfigContainer = ctr;
InitializeEndpoints();
}
#endregion
private void InitializeEndpoints()
{
_acl = new Lazy<ACL>(() => new ACL(this));
_agent = new Lazy<Agent>(() => new Agent(this));
_catalog = new Lazy<Catalog>(() => new Catalog(this));
_coordinate = new Lazy<Coordinate>(() => new Coordinate(this));
_event = new Lazy<Event>(() => new Event(this));
_health = new Lazy<Health>(() => new Health(this));
_kv = new Lazy<KV>(() => new KV(this));
_operator = new Lazy<Operator>(() => new Operator(this));
_preparedquery = new Lazy<PreparedQuery>(() => new PreparedQuery(this));
_raw = new Lazy<Raw>(() => new Raw(this));
_session = new Lazy<Session>(() => new Session(this));
_snapshot = new Lazy<Snapshot>(() => new Snapshot(this));
_status = new Lazy<Status>(() => new Status(this));
}
#region IDisposable Support
private bool disposedValue = false; // To detect redundant calls
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
Config.Updated -= HandleConfigUpdateEvent;
if (ConfigContainer != null)
{
ConfigContainer.Dispose();
}
}
disposedValue = true;
}
}
//~ConsulClient()
//{
// // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
// Dispose(false);
//}
// This code added to correctly implement the disposable pattern.
public void Dispose()
{
// Do not change this code. Put cleanup code in Dispose(bool disposing) above.
Dispose(true);
GC.SuppressFinalize(this);
}
public void CheckDisposed()
{
if (disposedValue)
{
throw new ObjectDisposedException(typeof(ConsulClient).FullName.ToString());
}
}
#endregion
void HandleConfigUpdateEvent(object sender, EventArgs e)
{
ApplyConfig(sender as ConsulClientConfiguration, HttpHandler, HttpClient);
}
#if !CORECLR
void ApplyConfig(ConsulClientConfiguration config, WebRequestHandler handler, HttpClient client)
#else
void ApplyConfig(ConsulClientConfiguration config, HttpClientHandler handler, HttpClient client)
#endif
{
#pragma warning disable CS0618 // Type or member is obsolete
if (config.HttpAuth != null)
#pragma warning restore CS0618 // Type or member is obsolete
{
#pragma warning disable CS0618 // Type or member is obsolete
handler.Credentials = config.HttpAuth;
#pragma warning restore CS0618 // Type or member is obsolete
}
#if !__MonoCS__
if (config.ClientCertificateSupported)
{
#pragma warning disable CS0618 // Type or member is obsolete
if (config.ClientCertificate != null)
#pragma warning restore CS0618 // Type or member is obsolete
{
handler.ClientCertificateOptions = ClientCertificateOption.Manual;
#pragma warning disable CS0618 // Type or member is obsolete
handler.ClientCertificates.Add(config.ClientCertificate);
#pragma warning restore CS0618 // Type or member is obsolete
}
else
{
handler.ClientCertificateOptions = ClientCertificateOption.Manual;
handler.ClientCertificates.Clear();
}
}
#endif
#if !CORECLR
#pragma warning disable CS0618 // Type or member is obsolete
if (config.DisableServerCertificateValidation)
#pragma warning restore CS0618 // Type or member is obsolete
{
handler.ServerCertificateValidationCallback += (certSender, cert, chain, sslPolicyErrors) => { return true; };
}
else
{
handler.ServerCertificateValidationCallback = null;
}
#else
#pragma warning disable CS0618 // Type or member is obsolete
if (config.DisableServerCertificateValidation)
#pragma warning restore CS0618 // Type or member is obsolete
{
handler.ServerCertificateCustomValidationCallback += (certSender, cert, chain, sslPolicyErrors) => { return true; };
}
else
{
handler.ServerCertificateCustomValidationCallback = null;
}
#endif
if (!string.IsNullOrEmpty(config.Token))
{
if (client.DefaultRequestHeaders.Contains("X-Consul-Token"))
{
client.DefaultRequestHeaders.Remove("X-Consul-Token");
}
client.DefaultRequestHeaders.Add("X-Consul-Token", config.Token);
}
}
internal GetRequest<TOut> Get<TOut>(string path, QueryOptions opts = null)
{
return new GetRequest<TOut>(this, path, opts ?? QueryOptions.Default);
}
internal DeleteReturnRequest<TOut> DeleteReturning<TOut>(string path, WriteOptions opts = null)
{
return new DeleteReturnRequest<TOut>(this, path, opts ?? WriteOptions.Default);
}
internal DeleteRequest Delete(string path, WriteOptions opts = null)
{
return new DeleteRequest(this, path, opts ?? WriteOptions.Default);
}
internal DeleteAcceptingRequest<TIn> DeleteAccepting<TIn>(string path, TIn body, WriteOptions opts = null)
{
return new DeleteAcceptingRequest<TIn>(this, path, body, opts ?? WriteOptions.Default);
}
internal PutReturningRequest<TOut> PutReturning<TOut>(string path, WriteOptions opts = null)
{
return new PutReturningRequest<TOut>(this, path, opts ?? WriteOptions.Default);
}
internal PutRequest<TIn> Put<TIn>(string path, TIn body, WriteOptions opts = null)
{
return new PutRequest<TIn>(this, path, body, opts ?? WriteOptions.Default);
}
internal PutNothingRequest PutNothing(string path, WriteOptions opts = null)
{
return new PutNothingRequest(this, path, opts ?? WriteOptions.Default);
}
internal PutRequest<TIn, TOut> Put<TIn, TOut>(string path, TIn body, WriteOptions opts = null)
{
return new PutRequest<TIn, TOut>(this, path, body, opts ?? WriteOptions.Default);
}
internal PostRequest<TIn> Post<TIn>(string path, TIn body, WriteOptions opts = null)
{
return new PostRequest<TIn>(this, path, body, opts ?? WriteOptions.Default);
}
internal PostRequest<TIn, TOut> Post<TIn, TOut>(string path, TIn body, WriteOptions opts = null)
{
return new PostRequest<TIn, TOut>(this, path, body, opts ?? WriteOptions.Default);
}
}
public abstract class ConsulRequest
{
internal ConsulClient Client { get; set; }
internal HttpMethod Method { get; set; }
internal Dictionary<string, string> Params { get; set; }
internal Stream ResponseStream { get; set; }
internal string Endpoint { get; set; }
protected Stopwatch timer = new Stopwatch();
internal ConsulRequest(ConsulClient client, string url, HttpMethod method)
{
Client = client;
Method = method;
Endpoint = url;
Params = new Dictionary<string, string>();
if (!string.IsNullOrEmpty(client.Config.Datacenter))
{
Params["dc"] = client.Config.Datacenter;
}
if (client.Config.WaitTime.HasValue)
{
Params["wait"] = client.Config.WaitTime.Value.ToGoDuration();
}
}
protected abstract void ApplyOptions(ConsulClientConfiguration clientConfig);
protected abstract void ApplyHeaders(HttpRequestMessage message, ConsulClientConfiguration clientConfig);
protected Uri BuildConsulUri(string url, Dictionary<string, string> p)
{
var builder = new UriBuilder(Client.Config.Address);
builder.Path = url;
ApplyOptions(Client.Config);
var queryParams = new List<string>(Params.Count / 2);
foreach (var queryParam in Params)
{
if (!string.IsNullOrEmpty(queryParam.Value))
{
queryParams.Add(string.Format("{0}={1}", Uri.EscapeDataString(queryParam.Key),
Uri.EscapeDataString(queryParam.Value)));
}
else
{
queryParams.Add(string.Format("{0}", Uri.EscapeDataString(queryParam.Key)));
}
}
builder.Query = string.Join("&", queryParams);
return builder.Uri;
}
protected TOut Deserialize<TOut>(Stream stream)
{
using (var reader = new StreamReader(stream))
{
using (var jsonReader = new JsonTextReader(reader))
{
return Client.serializer.Deserialize<TOut>(jsonReader);
}
}
}
protected byte[] Serialize(object value)
{
return System.Text.Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(value));
}
}
public class GetRequest<TOut> : ConsulRequest
{
public QueryOptions Options { get; set; }
public GetRequest(ConsulClient client, string url, QueryOptions options = null) : base(client, url, HttpMethod.Get)
{
if (string.IsNullOrEmpty(url))
{
throw new ArgumentException(nameof(url));
}
Options = options ?? QueryOptions.Default;
}
public async Task<QueryResult<TOut>> Execute(CancellationToken ct)
{
Client.CheckDisposed();
timer.Start();
var result = new QueryResult<TOut>();
var message = new HttpRequestMessage(HttpMethod.Get, BuildConsulUri(Endpoint, Params));
ApplyHeaders(message, Client.Config);
var response = await Client.HttpClient.SendAsync(message, ct).ConfigureAwait(false);
ParseQueryHeaders(response, result);
result.StatusCode = response.StatusCode;
ResponseStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
if (response.StatusCode != HttpStatusCode.NotFound && !response.IsSuccessStatusCode)
{
if (ResponseStream == null)
{
throw new ConsulRequestException(string.Format("Unexpected response, status code {0}",
response.StatusCode), response.StatusCode);
}
using (var sr = new StreamReader(ResponseStream))
{
throw new ConsulRequestException(string.Format("Unexpected response, status code {0}: {1}",
response.StatusCode, sr.ReadToEnd()), response.StatusCode);
}
}
if (response.IsSuccessStatusCode)
{
result.Response = Deserialize<TOut>(ResponseStream);
}
result.RequestTime = timer.Elapsed;
timer.Stop();
return result;
}
public async Task<QueryResult<Stream>> ExecuteStreaming(CancellationToken ct)
{
Client.CheckDisposed();
timer.Start();
var result = new QueryResult<Stream>();
var message = new HttpRequestMessage(HttpMethod.Get, BuildConsulUri(Endpoint, Params));
ApplyHeaders(message, Client.Config);
var response = await Client.HttpClient.SendAsync(message, HttpCompletionOption.ResponseHeadersRead, ct).ConfigureAwait(false);
ParseQueryHeaders(response, (result as QueryResult<TOut>));
result.StatusCode = response.StatusCode;
ResponseStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
result.Response = ResponseStream;