-
Notifications
You must be signed in to change notification settings - Fork 301
/
Copy pathKubernetes.WebSocket.cs
348 lines (295 loc) · 13.3 KB
/
Kubernetes.WebSocket.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
using System.Globalization;
using System.Net;
using System.Net.Http;
using System.Net.WebSockets;
using System.Security.Cryptography.X509Certificates;
using System.Text;
namespace k8s
{
public partial class Kubernetes
{
/// <summary>
/// Gets a function which returns a <see cref="WebSocketBuilder"/> which <see cref="Kubernetes"/> will use to
/// create a new <see cref="WebSocket"/> connection to the Kubernetes cluster.
/// </summary>
public Func<WebSocketBuilder> CreateWebSocketBuilder { get; set; } = () => new WebSocketBuilder();
/// <inheritdoc/>
public Task<WebSocket> WebSocketNamespacedPodExecAsync(string name, string @namespace = "default",
string command = null, string container = null, bool stderr = true, bool stdin = true, bool stdout = true,
bool tty = true, string webSocketSubProtol = null, Dictionary<string, List<string>> customHeaders = null,
CancellationToken cancellationToken = default)
{
return WebSocketNamespacedPodExecAsync(name, @namespace, new string[] { command }, container, stderr, stdin,
stdout, tty, webSocketSubProtol, customHeaders, cancellationToken);
}
/// <inheritdoc/>
public virtual async Task<IStreamDemuxer> MuxedStreamNamespacedPodExecAsync(
string name,
string @namespace = "default", IEnumerable<string> command = null, string container = null,
bool stderr = true, bool stdin = true, bool stdout = true, bool tty = true,
string webSocketSubProtol = WebSocketProtocol.V4BinaryWebsocketProtocol,
Dictionary<string, List<string>> customHeaders = null,
CancellationToken cancellationToken = default)
{
var webSocket = await WebSocketNamespacedPodExecAsync(name, @namespace,
command, container, tty: tty, cancellationToken: cancellationToken)
.ConfigureAwait(false);
var muxer = new StreamDemuxer(webSocket);
return muxer;
}
/// <inheritdoc/>
public virtual Task<WebSocket> WebSocketNamespacedPodExecAsync(string name, string @namespace = "default",
IEnumerable<string> command = null, string container = null, bool stderr = true, bool stdin = true,
bool stdout = true, bool tty = true,
string webSocketSubProtol = WebSocketProtocol.V4BinaryWebsocketProtocol,
Dictionary<string, List<string>> customHeaders = null,
CancellationToken cancellationToken = default)
{
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
if (@namespace == null)
{
throw new ArgumentNullException(nameof(@namespace));
}
if (command == null)
{
throw new ArgumentNullException(nameof(command));
}
if (!command.Any())
{
throw new ArgumentOutOfRangeException(nameof(command));
}
var commandArray = command.ToArray();
foreach (var c in commandArray)
{
if (c.Length > 0 && c[0] == 0xfeff)
{
throw new InvalidOperationException(
$"Detected an attempt to execute a command which starts with a Unicode byte order mark (BOM). This is probably incorrect. The command was {c}");
}
}
// Construct URL
var uriBuilder = new UriBuilder(BaseUri)
{
Scheme = BaseUri.Scheme == "https" ? "wss" : "ws",
};
if (!uriBuilder.Path.EndsWith("/", StringComparison.InvariantCulture))
{
uriBuilder.Path += "/";
}
uriBuilder.Path += $"api/v1/namespaces/{@namespace}/pods/{name}/exec";
var query = new StringBuilder();
foreach (var c in command)
{
Utilities.AddQueryParameter(query, "command", c);
}
if (!string.IsNullOrEmpty(container))
{
Utilities.AddQueryParameter(query, "container", container);
}
query.Append("&stderr=")
.Append(stderr
? '1'
: '0'); // the query string is guaranteed not to be empty here because it has a 'command' param
query.Append("&stdin=").Append(stdin ? '1' : '0');
query.Append("&stdout=").Append(stdout ? '1' : '0');
query.Append("&tty=").Append(tty ? '1' : '0');
uriBuilder.Query =
query.ToString(1, query.Length - 1); // UriBuilder.Query doesn't like leading '?' chars, so trim it
return StreamConnectAsync(uriBuilder.Uri, webSocketSubProtol, customHeaders,
cancellationToken);
}
/// <inheritdoc/>
public Task<WebSocket> WebSocketNamespacedPodPortForwardAsync(string name, string @namespace,
IEnumerable<int> ports, string webSocketSubProtocol = null,
Dictionary<string, List<string>> customHeaders = null,
CancellationToken cancellationToken = default)
{
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
if (@namespace == null)
{
throw new ArgumentNullException(nameof(@namespace));
}
if (ports == null)
{
throw new ArgumentNullException(nameof(ports));
}
// Construct URL
var uriBuilder = new UriBuilder(BaseUri)
{
Scheme = BaseUri.Scheme == "https" ? "wss" : "ws",
};
if (!uriBuilder.Path.EndsWith("/", StringComparison.InvariantCulture))
{
uriBuilder.Path += "/";
}
uriBuilder.Path += $"api/v1/namespaces/{@namespace}/pods/{name}/portforward";
var q = new StringBuilder();
foreach (var port in ports)
{
if (q.Length != 0)
{
q.Append('&');
}
q.Append("ports=").Append(port.ToString(CultureInfo.InvariantCulture));
}
uriBuilder.Query = q.ToString();
return StreamConnectAsync(uriBuilder.Uri, webSocketSubProtocol, customHeaders,
cancellationToken);
}
/// <inheritdoc/>
public Task<WebSocket> WebSocketNamespacedPodAttachAsync(string name, string @namespace,
string container = default, bool stderr = true, bool stdin = false, bool stdout = true,
bool tty = false, string webSocketSubProtol = null, Dictionary<string, List<string>> customHeaders = null,
CancellationToken cancellationToken = default)
{
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
if (@namespace == null)
{
throw new ArgumentNullException(nameof(@namespace));
}
// Construct URL
var uriBuilder = new UriBuilder(BaseUri)
{
Scheme = BaseUri.Scheme == "https" ? "wss" : "ws",
};
if (!uriBuilder.Path.EndsWith("/", StringComparison.InvariantCulture))
{
uriBuilder.Path += "/";
}
uriBuilder.Path += $"api/v1/namespaces/{@namespace}/pods/{name}/attach";
var query = new StringBuilder();
query.Append("?stderr=").Append(stderr ? '1' : '0');
query.Append("&stdin=").Append(stdin ? '1' : '0');
query.Append("&stdout=").Append(stdout ? '1' : '0');
query.Append("&tty=").Append(tty ? '1' : '0');
Utilities.AddQueryParameter(query, "container", container);
uriBuilder.Query =
query.ToString(1, query.Length - 1); // UriBuilder.Query doesn't like leading '?' chars, so trim it
return StreamConnectAsync(uriBuilder.Uri, webSocketSubProtol, customHeaders,
cancellationToken);
}
partial void BeforeRequest();
partial void AfterRequest();
protected async Task<WebSocket> StreamConnectAsync(Uri uri, string webSocketSubProtocol = null, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default)
{
if (uri == null)
{
throw new ArgumentNullException(nameof(uri));
}
// Create WebSocket transport objects
var webSocketBuilder = CreateWebSocketBuilder();
// Set Headers
if (customHeaders != null)
{
foreach (var header in customHeaders)
{
webSocketBuilder.SetRequestHeader(header.Key, string.Join(" ", header.Value));
}
}
// Set Credentials
if (this.HttpClientHandler != null)
{
#if NET5_0_OR_GREATER
foreach (var cert in this.HttpClientHandler.SslOptions.ClientCertificates.OfType<X509Certificate2>())
#else
foreach (var cert in this.HttpClientHandler.ClientCertificates.OfType<X509Certificate2>())
#endif
{
webSocketBuilder.AddClientCertificate(cert);
}
}
if (Credentials != null)
{
// Copy the default (credential-related) request headers from the HttpClient to the WebSocket
var message = new HttpRequestMessage();
await Credentials.ProcessHttpRequestAsync(message, cancellationToken).ConfigureAwait(false);
foreach (var header in message.Headers)
{
webSocketBuilder.SetRequestHeader(header.Key, string.Join(" ", header.Value));
}
}
if (this.CaCerts != null)
{
webSocketBuilder.ExpectServerCertificate(this.CaCerts);
}
if (this.SkipTlsVerify)
{
webSocketBuilder.SkipServerCertificateValidation();
}
if (webSocketSubProtocol != null)
{
webSocketBuilder.Options.AddSubProtocol(webSocketSubProtocol);
}
// Send Request
cancellationToken.ThrowIfCancellationRequested();
WebSocket webSocket = null;
try
{
BeforeRequest();
webSocket = await webSocketBuilder.BuildAndConnectAsync(uri, cancellationToken).ConfigureAwait(false);
}
catch (WebSocketException wse) when (wse.WebSocketErrorCode == WebSocketError.HeaderError ||
(wse.InnerException is WebSocketException &&
((WebSocketException)wse.InnerException).WebSocketErrorCode ==
WebSocketError.HeaderError))
{
// This usually indicates the server sent an error message, like 400 Bad Request. Unfortunately, the WebSocket client
// class doesn't give us a lot of information about what went wrong. So, retry the connection.
var uriBuilder = new UriBuilder(uri)
{
Scheme = uri.Scheme == "wss" ? "https" : "http",
};
var response = await HttpClient.GetAsync(uriBuilder.Uri, cancellationToken).ConfigureAwait(false);
if (response.StatusCode == HttpStatusCode.SwitchingProtocols)
{
// This should never happen - the server just allowed us to switch to WebSockets but the previous call didn't work.
// Rethrow the original exception
response.Dispose();
throw;
}
else
{
#if NET5_0_OR_GREATER
var content = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false);
#else
var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
#endif
// Try to parse the content as a V1Status object
var genericObject = KubernetesJson.Deserialize<KubernetesObject>(content);
V1Status status = null;
if (genericObject.ApiVersion == "v1" && genericObject.Kind == "Status")
{
status = KubernetesJson.Deserialize<V1Status>(content);
}
var ex =
new HttpOperationException(
$"The operation returned an invalid status code: {response.StatusCode}", wse)
{
Response = new HttpResponseMessageWrapper(response, content),
Body = status != null ? status : content,
};
response.Dispose();
throw ex;
}
}
catch (Exception)
{
throw;
}
finally
{
AfterRequest();
}
return webSocket;
}
}
}