Skip to content

Commit

Permalink
fix: simplify logic
Browse files Browse the repository at this point in the history
  • Loading branch information
IvanJosipovic committed Apr 20, 2023
1 parent 6e53437 commit de0aa5a
Showing 1 changed file with 12 additions and 31 deletions.
43 changes: 12 additions & 31 deletions src/KubernetesClient/KubernetesClientConfiguration.ConfigFile.cs
Original file line number Diff line number Diff line change
Expand Up @@ -558,46 +558,27 @@ public static ExecCredentialResponse ExecuteExternalCommand(ExternalExecution co
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 buffer = new char[4096];
var stdErrorTask = process.StandardError.ReadAsync(buffer, 0, buffer.Length); // Assumes process will continue

var stopwatch = Stopwatch.StartNew();
var result = Task.WaitAny(new Task[] { stdErrorTask, stdOutTask }, TimeSpan.FromSeconds(10));

// Wait for a maximum of 5 seconds, if a response takes longer probably something went wrong...
while (!stdOutTask.IsCompleted && stopwatch.Elapsed < TimeSpan.FromSeconds(5))
if (result == -1)
{
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;
}
throw new KubeConfigException("external exec failed due to timeout");
}

var stdError = stderrBuilder.ToString();

if (!string.IsNullOrWhiteSpace(stdError))
else if (result == 0)
{
throw new KubeConfigException($"external exec failed due to: {stdError}");
}
var stderrBuilder = new StringBuilder();
stderrBuilder.Append(buffer, 0, stdErrorTask.Result);

if (!stdOutTask.IsCompleted)
{
throw new KubeConfigException("external exec failed due to timeout");
if (stderrBuilder.Length > 0)
{
throw new KubeConfigException($"external exec failed due to: {stderrBuilder}");
}
}

try
Expand Down

0 comments on commit de0aa5a

Please sign in to comment.