Skip to content

Commit

Permalink
fix: revert to non Event based logic
Browse files Browse the repository at this point in the history
  • Loading branch information
IvanJosipovic committed Apr 19, 2023
1 parent 9800711 commit 6e53437
Showing 1 changed file with 37 additions and 13 deletions.
50 changes: 37 additions & 13 deletions src/KubernetesClient/KubernetesClientConfiguration.ConfigFile.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using System.Net;
using System.Runtime.InteropServices;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;

namespace k8s
Expand Down Expand Up @@ -548,37 +549,60 @@ public static ExecCredentialResponse ExecuteExternalCommand(ExternalExecution co

var process = CreateRunnableExternalProcess(config);

var stdout = "";
var stderr = "";

process.OutputDataReceived += (sender, args) => stdout += args.Data;
process.ErrorDataReceived += (sender, args) => stderr += args.Data;

try
{
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
}
catch (Exception ex)
{
throw new KubeConfigException($"external exec failed due to: {ex.Message}");
}

var stderrBuilder = new StringBuilder();

var stdOutTask = process.StandardOutput.ReadToEndAsync(); // Assumes process exits

var buffer = new char[1024];

var stopwatch = Stopwatch.StartNew();

// Wait for a maximum of 5 seconds, if a response takes longer probably something went wrong...
if (!process.WaitForExit(5000) && string.IsNullOrWhiteSpace(stderr))
while (!stdOutTask.IsCompleted && stopwatch.Elapsed < TimeSpan.FromSeconds(5))
{
throw new KubeConfigException("external exec failed due to timeout");
var readTask = process.StandardError.ReadAsync(buffer, 0, buffer.Length);

if (readTask.Wait(TimeSpan.FromMilliseconds(500)))
{
var bytesRead = readTask.Result;
if (bytesRead == 0)
{
break; // end of stream reached
}

stderrBuilder.Append(buffer, 0, bytesRead);
}
else
{
// timeout occurred
break;
}
}

if (!string.IsNullOrWhiteSpace(stderr))
var stdError = stderrBuilder.ToString();

if (!string.IsNullOrWhiteSpace(stdError))
{
throw new KubeConfigException($"external exec failed due to: {stderr}");
throw new KubeConfigException($"external exec failed due to: {stdError}");
}

if (!stdOutTask.IsCompleted)
{
throw new KubeConfigException("external exec failed due to timeout");
}

try
{
var responseObject = KubernetesJson.Deserialize<ExecCredentialResponse>(stdout);
var responseObject = KubernetesJson.Deserialize<ExecCredentialResponse>(stdOutTask.Result);
if (responseObject == null || responseObject.ApiVersion != config.ApiVersion)
{
throw new KubeConfigException(
Expand Down

0 comments on commit 6e53437

Please sign in to comment.