Skip to content

Commit

Permalink
fix nc probe crash issue
Browse files Browse the repository at this point in the history
  • Loading branch information
weibaohui committed May 28, 2024
1 parent f36f021 commit ba4ef7c
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 51 deletions.
47 changes: 23 additions & 24 deletions BlazorApp/Utils/PortForwarding/PortForwardExecutor.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
using System;
using System.Threading.Tasks;
using BlazorApp.Utils.Terminal;
using CliWrap;
using CliWrap.Buffered;
using Entity;
using Microsoft.Extensions.Logging;

Expand Down Expand Up @@ -42,46 +44,43 @@ public async Task Start()
await service.Write(command);
}

public string GetNcProbeCommand()
private string GetNcProbeCommand()
{
return $"nc -v -w 1 -z 127.0.0.1 {PortForward.LocalPort} \r";
}

private string GetNcProbeParameters()
{
return $"-v -w 1 -z 127.0.0.1 {PortForward.LocalPort} \r";
}

public async Task StartProbe()
{
if (PortForward == null)
{
return;
}

var command = GetNcProbeCommand();
var service = TerminalHelper.Instance.GetOrCreate(command);

if (!service.IsRunning)
try
{
await service.Start();
var cmd = Cli.Wrap("nc")
.WithValidation(CommandResultValidation.None)
.WithArguments(GetNcProbeParameters());
// 执行命令并捕获输出
var result = await cmd.ExecuteBufferedAsync();
var all = result.StandardOutput + result.StandardError;
if (all.Contains("failed"))
PortForward.Status = "failed";
else if (all.Contains("succeeded")) PortForward.Status = "succeeded";
}

if (!service.IsStandardOutPutSet)
catch (Exception ex)
{
service.StandardOutput += (sender, e) =>
{
// Logger.LogInformation("PortForwardExecutor Probe StandardOutput: {Command}::::{Data}", GetNcProbeCommand(),e);
if (e.Contains("failed"))
{
PortForward.Status = "failed";
}

if (e.Contains("succeeded"))
{
PortForward.Status = "succeeded";
}

PortForward.StatusTimestamp = DateTime.Now;
};
Logger.LogError(ex, "PortForwardExecutor Probe Error: {Command}", GetNcProbeCommand());
PortForward.Status = "failed";
return;
}

await service.Write(command);
PortForward.StatusTimestamp = DateTime.Now;
}

public void Dispose()
Expand Down
53 changes: 26 additions & 27 deletions BlazorApp/Utils/PortForwarding/PortForwardExecutorHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
using k8s.Models;
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;

namespace BlazorApp.Utils.PortForwarding;

Expand All @@ -20,27 +19,14 @@ public class PortForwardExecutorHelper
LoggingHelper<PortForwardExecutorHelper>.Logger();

private static readonly Dictionary<string, PortForwardExecutor> Map = new();
private readonly ResourceCache<PortForward> _cache = ResourceCacheHelper<PortForward>.Instance.Build();
private readonly object _lockObj = new object();
private readonly ResourceCache<PortForward> _cache = ResourceCacheHelper<PortForward>.Instance.Build();
private readonly object _lockObj = new();

/// <summary>
/// 发送watch event ,使用DI获取后,赋值到本helper
/// </summary>
private IHubContext<ChatHub>? _ctx;

public static PortForwardExecutorHelper Instance => Nested.Instance;

private class Nested
{
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Nested()
{
}

internal static readonly PortForwardExecutorHelper Instance = new PortForwardExecutorHelper();
}

public PortForwardExecutorHelper()
{
//每5秒执行一次端口探活
Expand All @@ -49,6 +35,8 @@ public PortForwardExecutorHelper()
JobManager.AddJob(RemoveFailedPort, (s) => s.ToRunEvery(30).Seconds());
}

public static PortForwardExecutorHelper Instance => Nested.Instance;


/// <summary>
/// 探测端口是否存活
Expand All @@ -71,7 +59,7 @@ private void NcProbe()
continue;
}

pfe.StartProbe().ConfigureAwait(true);
pfe.StartProbe().ConfigureAwait(true).GetAwaiter().GetResult();
WatchUpdate(WatchEventType.Modified, pf);
Logger.LogInformation(
"探测状态:{Port} {Status},{Time}",
Expand Down Expand Up @@ -112,20 +100,20 @@ public async Task ForwardPort(PortForwardType type, string ns, string kubeName,
{
var pf = new PortForward
{
Kind = "PortForward",
ApiVersion = "blazorK8s.io/v1",
Type = type,
LocalPort = localPort,
KubePort = kubePort,
KubeName = kubeName,
Kind = "PortForward",
ApiVersion = "blazorK8s.io/v1",
Type = type,
LocalPort = localPort,
KubePort = kubePort,
KubeName = kubeName,
KubeNamespace = ns,
Metadata = new V1ObjectMeta
{
Name = $"{kubeName}-{kubePort}-{localPort}",
Name = $"{kubeName}-{kubePort}-{localPort}",
NamespaceProperty = ns,
//k8s时间
CreationTimestamp = DateTime.Now.ToUniversalTime(),
Uid = Guid.NewGuid().ToString()
Uid = Guid.NewGuid().ToString()
}
};

Expand Down Expand Up @@ -182,8 +170,8 @@ private Task WatchUpdate(WatchEventType type, PortForward item)
var data = new ResourceWatchEntity<PortForward>
{
Message = $"{type}:{item.Kind}:{item.Metadata.Name}",
Type = type,
Item = item
Type = type,
Item = item
};
Logger.LogInformation("{Type}:{ItemKind}:{MetadataName}", type, item.Kind, item.Metadata.Name);
_cache.Update(type, item);
Expand All @@ -194,4 +182,15 @@ private Task WatchUpdate(WatchEventType type, PortForward item)

return Task.CompletedTask;
}

private class Nested
{
internal static readonly PortForwardExecutorHelper Instance = new();

// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Nested()
{
}
}
}

0 comments on commit ba4ef7c

Please sign in to comment.