-
Notifications
You must be signed in to change notification settings - Fork 301
/
Copy pathKubernetes.Exec.cs
88 lines (79 loc) · 3.34 KB
/
Kubernetes.Exec.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
namespace k8s
{
public partial class Kubernetes
{
public async Task<int> NamespacedPodExecAsync(string name, string @namespace, string container,
IEnumerable<string> command, bool tty, ExecAsyncCallback action, CancellationToken cancellationToken)
{
// All other parameters are being validated by MuxedStreamNamespacedPodExecAsync
if (action == null)
{
throw new ArgumentNullException(nameof(action));
}
try
{
using var muxedStream = await MuxedStreamNamespacedPodExecAsync(
name,
@namespace, command, container, tty: tty,
cancellationToken: cancellationToken).ConfigureAwait(false);
using var stdIn = muxedStream.GetStream(null, ChannelIndex.StdIn);
using var stdOut = muxedStream.GetStream(ChannelIndex.StdOut, null);
using var stdErr = muxedStream.GetStream(ChannelIndex.StdErr, null);
using var error = muxedStream.GetStream(ChannelIndex.Error, null);
using var errorReader = new StreamReader(error);
muxedStream.Start();
await action(stdIn, stdOut, stdErr).ConfigureAwait(false);
var errors = await errorReader.ReadToEndAsync().ConfigureAwait(false);
// StatusError is defined here:
// https://github.com/kubernetes/kubernetes/blob/068e1642f63a1a8c48c16c18510e8854a4f4e7c5/staging/src/k8s.io/apimachinery/pkg/api/errors/errors.go#L37
var returnMessage = KubernetesJson.Deserialize<V1Status>(errors);
return GetExitCodeOrThrow(returnMessage);
}
catch (HttpOperationException httpEx) when (httpEx.Body is V1Status status)
{
throw new KubernetesException(status, httpEx);
}
}
/// <summary>
/// Determines the process' exit code based on a <see cref="V1Status"/> message.
///
/// This will:
/// - return 0 if the process completed successfully
/// - return the exit code if the process completed with a non-zero exit code
/// - throw a <see cref="KubernetesException"/> in all other cases.
/// </summary>
/// <param name="status">
/// A <see cref="V1Status"/> object.
/// </param>
/// <returns>
/// The process exit code.
/// </returns>
public static int GetExitCodeOrThrow(V1Status status)
{
if (status == null)
{
throw new ArgumentNullException(nameof(status));
}
if (status.Status == "Success")
{
return 0;
}
else if (status.Status == "Failure" && status.Reason == "NonZeroExitCode")
{
var exitCodeString = status.Details.Causes.FirstOrDefault(c => c.Reason == "ExitCode")?.Message;
if (int.TryParse(exitCodeString, out var exitCode))
{
return exitCode;
}
else
{
throw new KubernetesException(status);
}
}
else
{
throw new KubernetesException(status);
}
}
}
}