修掉「本机明明有设备管理服务却走云端」

现场表现:更新/重启后头几十秒里本机查询都提示「改问云端」。原因是
hik-worker 的懒启动被安排在 20 秒后,而 UDP 17310 应答由 worker 提供;
A 探测不到就只能走云端,偏偏是云任务反过来才把 worker 拉起来,形成死循环。

- worker 自检从启动后 20 秒提前到 3 秒(实测 UDP/TCP 约 5 秒内就绪)
- 局域网应答的 UDP 绑定加 30 次重试(约 60 秒),上一条日志里它在重启后
  没绑上且没有任何痕迹;现在失败会记「第 N 次重试」和最终放弃
- AppLog 改为独占写 + 失败落本进程旁路文件 log_<日期>.p<pid>.txt,
  避免并发写把行写截断(FileShare.ReadWrite 会撕裂行)

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
liufumingren 2026-10-22 03:19:09 +08:00
parent 49681b7bdd
commit f38bf082f1
4 changed files with 69 additions and 29 deletions

View File

@ -162,12 +162,14 @@ public static class AgentHost
await scan.StartAsync().ConfigureAwait(false);
scan.StartDiscovery(); // 常驻发现:设备 DHCP 换 IP 时能自己重连
// 延后自检:不抢服务启动的 CPU,也能让状态文件尽快反映「SDK 是否就位」
// 自检要尽早:worker 一就绪,局域网询问才有应答(UDP 17310)。
// 以前延后 20 秒,导致「刚启动/刚更新完」这段时间本机查询探测不到设备管理服务,
// 白白退化成云端中转 —— 而云任务反过来才把 worker 拉起来,形成恶性循环。
_ = Task.Run(async () =>
{
try
{
if (!await DelayAsync(TimeSpan.FromSeconds(20), ct).ConfigureAwait(false)) return;
if (!await DelayAsync(TimeSpan.FromSeconds(3), ct).ConfigureAwait(false)) return;
ApplyHikProbe(hikStatus, await hikWorker.ProbeAsync(ct).ConfigureAwait(false));
hikStatus.Connected = hikWorker.IsConnected;

View File

@ -339,18 +339,45 @@ public static class HikWorker
/// </summary>
private static async Task RunLanResponderAsync(CancellationToken ct)
{
// 上一个 worker 退出后端口可能还没释放(重启/更新时常见),
// 以前直接 return,结果「本机明明有设备管理服务却探测不到」,只能走云端。
// 这里重试 30 次(约 60 秒),第一次失败必记,之后每 10 次记一次。
UdpClient? udp = null;
try
for (var attempt = 1; attempt <= 30 && !ct.IsCancellationRequested; attempt++)
{
udp = new UdpClient(new IPEndPoint(IPAddress.Parse(HikWorkerPorts.BindAddress), HikWorkerPorts.UdpQuery))
try
{
EnableBroadcast = true,
};
udp = new UdpClient(new IPEndPoint(IPAddress.Parse(HikWorkerPorts.BindAddress), HikWorkerPorts.UdpQuery))
{
EnableBroadcast = true,
};
break;
}
catch (Exception ex)
{
udp?.Dispose();
udp = null;
if (attempt == 1 || attempt % 10 == 0)
{
AppLog.Write($"[hik-worker] 局域网应答监听 UDP {HikWorkerPorts.UdpQuery} 失败(第 {attempt} 次,2 秒后重试):{ex.Message}");
}
if (attempt == 30) break;
try
{
await Task.Delay(TimeSpan.FromSeconds(2), ct).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
return;
}
}
}
catch (Exception ex)
if (udp is null)
{
AppLog.Write($"[hik-worker] 局域网应答无法监听 UDP {HikWorkerPorts.UdpQuery}(该功能停用):{ex.Message}");
udp?.Dispose();
AppLog.Write($"[hik-worker] 局域网应答最终未能监听 UDP {HikWorkerPorts.UdpQuery}(该功能停用,本机会退化为云端取流)");
return;
}

View File

@ -39,35 +39,46 @@ public static class AppLog
var now = DateTime.Now;
var line = $"[{now:yyyy-MM-dd HH:mm:ss}] {message}{Environment.NewLine}";
var path = Path.Combine(LogDirectory, FileNameOf(now));
var name = FileNameOf(now);
// 不要用 File.AppendAllText:它按 FileShare.Read 打开,只要日志文件正被
// 记事本/编辑器/日志工具独占打开,每次写入都会失败(2026-10-21 现场丢了 6 小时日志)。
// 这里显式 FileShare.ReadWrite,并重试一次;仍然失败就记一次丢弃计数,
// 由 agent-status.json 暴露出去,避免「日志没了还查不出」。
for (var attempt = 0; attempt < 2; attempt++)
{
try
{
using var stream = new FileStream(path, FileMode.Append, FileAccess.Write,
FileShare.ReadWrite | FileShare.Delete);
var bytes = Utf8NoBom.GetBytes(line);
stream.Write(bytes, 0, bytes.Length);
return;
}
catch
{
if (attempt == 0) Thread.Sleep(20);
}
}
//
// 策略:先用**独占写**打开(避免两个实例同时写导致行被截断),失败就重试;
// 仍然失败则退到本进程专属的旁路文件,宁可多一个文件也不丢日志。
if (TryAppend(Path.Combine(LogDirectory, name), line)) return;
if (TryAppend(Path.Combine(LogDirectory, FileNameOf(now, Environment.ProcessId)), line)) return;
Interlocked.Increment(ref _dropped);
LastDroppedAt = DateTime.Now;
}
private static bool TryAppend(string path, string line)
{
for (var attempt = 0; attempt < 3; attempt++)
{
try
{
using var stream = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.Read);
var bytes = Utf8NoBom.GetBytes(line);
stream.Write(bytes, 0, bytes.Length);
return true;
}
catch
{
if (attempt < 2) Thread.Sleep(30);
}
}
return false;
}
private static string FileNameOf(DateTime time, int processId)
=> $"log_{time:yyyy-MM-dd}.p{processId}.txt";
private static int _dropped;
/// <summary>累计丢弃的日志行数(写文件一直失败时增长)</summary>
/// <summary>累计丢弃的日志行数(连旁路文件都写不进去时增长)</summary>
public static int Dropped => Volatile.Read(ref _dropped);
/// <summary>最近一次丢弃日志的时间</summary>

View File

@ -42,7 +42,7 @@
<ServerBaseUrl Condition="'$(Configuration)' == 'Debug' and '$(ServerBaseUrl)' == ''">http://127.0.0.1:7300</ServerBaseUrl>
<ServerBaseUrl Condition="'$(Configuration)' == 'Release' and '$(ServerBaseUrl)' == ''">https://packs.example.com</ServerBaseUrl>
<Version>1.0.107</Version>
<Version>1.0.108</Version>
<Product>浜戜粨瑙嗛婧簮杞欢</Product>
<Company>浜戜粨</Company>
<AssemblyTitle>浜戜粨瑙嗛婧簮杞欢锛堟湰鏈烘湇鍔★級</AssemblyTitle>