-
Notifications
You must be signed in to change notification settings - Fork 31
/
Program.cs
209 lines (178 loc) · 7.74 KB
/
Program.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
using Microsoft.Extensions.Logging;
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace KubeClient.Samples.NoobExec
{
using Extensions.KubeConfig.Models;
using Extensions.WebSockets;
using Models;
/// <summary>
/// The NoobExec program.
/// </summary>
static class Program
{
/// <summary>
/// The main program's logger.
/// </summary>
static ILogger Log { get; set; }
/// <summary>
/// The main program entry-point.
/// </summary>
/// <param name="commandLineArguments">
/// The program's command-line arguments.
/// </param>
/// <returns>
/// The program exit-code.
/// </returns>
static async Task<int> Main(string[] commandLineArguments)
{
// Show help if no arguments are specified.
bool showHelp = commandLineArguments.Length == 0;
if (showHelp)
commandLineArguments = new[] { "--help" };
ProgramOptions options = ProgramOptions.Parse(commandLineArguments);
if (options == null)
return showHelp ? ExitCodes.Success : ExitCodes.InvalidArguments;
ILoggerFactory loggers = ConfigureLogging(options);
try
{
KubeClientOptions clientOptions = K8sConfig.Load().ToKubeClientOptions(
kubeContextName: options.KubeContext,
defaultKubeNamespace: options.KubeNamespace,
loggerFactory: loggers
);
using (KubeApiClient client = KubeApiClient.Create(clientOptions))
{
Log.LogInformation("Finding target pod...");
PodV1 targetPod = await client.PodsV1().Get(options.PodName,
kubeNamespace: options.KubeNamespace
);
if (targetPod == null)
{
Log.LogError("Pod '{PodName}' not found in namespace '{KubeNamespace}' on cluster ({KubeContextName}).",
options.PodName,
options.KubeNamespace,
options.KubeContext
);
return ExitCodes.NotFound;
}
if (!String.IsNullOrWhiteSpace(options.ContainerName))
{
ContainerStatusV1 targetContainer = targetPod.Status.ContainerStatuses.Find(
container => container.Name == options.ContainerName
);
if (targetContainer == null)
{
Log.LogError("Container '{ContainerName}' not found in Pod '{PodName}' in namespace '{KubeNamespace}' on cluster ({KubeContextName}).",
options.ContainerName,
options.PodName,
options.KubeNamespace,
options.KubeContext
);
return ExitCodes.NotFound;
}
}
else if (targetPod.Status.ContainerStatuses.Count > 1)
{
Log.LogError("Pod '{PodName}' in namespace '{KubeNamespace}' on cluster ({KubeContextName}) has more than one container. Please specify the name of the target container",
options.PodName,
options.KubeNamespace,
options.KubeContext
);
return ExitCodes.InvalidArguments;
}
Log.LogDebug("Connecting...");
K8sMultiplexer multiplexer = await client.PodsV1().ExecAndConnect(
podName: options.PodName,
container: options.ContainerName,
command: options.Command,
kubeNamespace: options.KubeContext,
stdin: true,
stdout: true,
stderr: true,
tty: true // Required for interactivity
);
Log.LogInformation("Connected.");
Task stdInPump, stdOutPump, stdErrPump;
using (multiplexer)
using (CancellationTokenSource pumpCancellation = new CancellationTokenSource())
using (Stream localStdIn = Console.OpenStandardInput())
using (Stream remoteStdIn = multiplexer.GetStdIn())
using (Stream localStdOut = Console.OpenStandardOutput())
using (Stream remoteStdOut = multiplexer.GetStdOut())
using (Stream localStdErr = Console.OpenStandardError())
using (Stream remoteStdErr = multiplexer.GetStdErr())
{
stdInPump = localStdIn.CopyToAsync(remoteStdIn, pumpCancellation.Token);
stdOutPump = remoteStdOut.CopyToAsync(localStdOut, pumpCancellation.Token);
stdErrPump = remoteStdErr.CopyToAsync(localStdErr, pumpCancellation.Token);
await multiplexer.WhenConnectionClosed;
// Terminate stream pumps.
pumpCancellation.Cancel();
}
Log.LogInformation("Connection closed.");
Log.LogInformation("Done.");
}
return ExitCodes.Success;
}
catch (Exception unexpectedError)
{
Log.LogError(unexpectedError.ToString());
Log.LogError(unexpectedError, "Unexpected error.");
return ExitCodes.UnexpectedError;
}
}
/// <summary>
/// Configure application-level logging.
/// </summary>
/// <param name="options">
/// Program options.
/// </param>
/// <returns>
/// The global logger factory.
/// </returns>
static ILoggerFactory ConfigureLogging(ProgramOptions options)
{
if (options == null)
throw new ArgumentNullException(nameof(options));
ILoggerFactory loggerFactory = new LoggerFactory().AddConsole(
minLevel: options.Verbose ? LogLevel.Trace : LogLevel.Information
);
Log = loggerFactory.CreateLogger("Program");
return loggerFactory;
}
/// <summary>
/// Global initialisation.
/// </summary>
static Program()
{
SynchronizationContext.SetSynchronizationContext(
new SynchronizationContext()
);
}
/// <summary>
/// Well-known program exit codes.
/// </summary>
public static class ExitCodes
{
/// <summary>
/// Program completed successfully.
/// </summary>
public const int Success = 0;
/// <summary>
/// One or more command-line arguments were missing or invalid.
/// </summary>
public const int InvalidArguments = 1;
/// <summary>
/// The target resource was not found.
/// </summary>
public const int NotFound = 10;
/// <summary>
/// An unexpected error occurred during program execution.
/// </summary>
public const int UnexpectedError = 50;
}
}
}