Skip to content
Merged

Dev #197

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Directory.Build.props
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@

<PropertyGroup>
<!-- Target-host package versions; the SDK intentionally does not own these pins. -->
<VelaAvaloniaVersion Condition="'$(VelaAvaloniaVersion)' == ''">12.2.0</VelaAvaloniaVersion>
<VelaAvaloniaVersion Condition="'$(VelaAvaloniaVersion)' == ''">12.2.1</VelaAvaloniaVersion>
<VelaAvaloniaEditVersion Condition="'$(VelaAvaloniaEditVersion)' == ''">12.0.0</VelaAvaloniaEditVersion>
</PropertyGroup>

Expand Down
10 changes: 5 additions & 5 deletions Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,13 @@
<ItemGroup Label="Avalonia target-host compile/test assets">
<!-- These are the target host's shared versions. UI plugins reference the compile
assets directly with runtime excluded; test projects supply the runtime assets. -->
<PackageVersion Include="Avalonia" Version="$(VelaAvaloniaVersion)" />
<PackageVersion Include="Avalonia.Headless" Version="$(VelaAvaloniaVersion)" />
<PackageVersion Include="Avalonia" Version="12.2.1" />
<PackageVersion Include="Avalonia.Headless" Version="12.2.1" />
<!-- 菜单等控件的模板由主题提供:没有它 MenuItem 无模板、不可命中,真实点击测不了。 -->
<PackageVersion Include="Avalonia.Themes.Fluent" Version="$(VelaAvaloniaVersion)" />
<PackageVersion Include="Avalonia.Themes.Fluent" Version="12.2.1" />
<!-- 真渲染(Skia)的 headless 截图:MongoDB 插件的界面回归要拿像素和设计稿比,
UseHeadlessDrawing 那条假绘制路径给不出位图。同样只服务于测试工程,版本随上面三个一起走。 -->
<PackageVersion Include="Avalonia.Skia" Version="$(VelaAvaloniaVersion)" />
<PackageVersion Include="Avalonia.Skia" Version="12.2.1" />
</ItemGroup>
<ItemGroup Label="Docker 面板与 MongoDB 插件">
<!-- MIT. AvaloniaEdit is compile-only because the host supplies the shared assembly.
Expand All @@ -51,7 +51,7 @@
<!-- Apache-2.0,与本仓库 AGPL-3.0 + 商业双许可相容。随插件目录分发。
测试工程也要引它(环回服务器要按收到的原始请求行重算 SigV4),
集中管版本正是为了这两处永远一致。 -->
<PackageVersion Include="AWSSDK.S3" Version="4.1.3" />
<PackageVersion Include="AWSSDK.S3" Version="4.1.3.1" />
</ItemGroup>
<ItemGroup Label="串口插件">
<!-- MIT,微软自家维护,Windows / Linux / macOS 的 RID 原生包齐全。
Expand Down
34 changes: 32 additions & 2 deletions plugins/VelaShell.Plugin.DockerPanel/Docker/DiskMath.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,40 @@ public static ReclaimBreakdown Reclaimable(DiskUsage? usage)
ImageSummary[] unusedImages = [.. (usage.Images ?? []).Where(static i => i.Containers <= 0)];
VolumeSummary[] unusedVolumes = [.. (usage.Volumes ?? []).Where(static v => v.UsageData is { RefCount: <= 0 })];
return new(
unusedImages.Sum(static i => i.Size),
ReclaimableImageBytes(usage, unusedImages),
unusedVolumes.Sum(static v => v.UsageData is { Size: > 0 } u ? u.Size : 0),
(usage.BuildCache ?? []).Where(static c => !c.InUse).Sum(static c => c.Size),
unusedImages.Length,
unusedVolumes.Length);
}
}

/// <summary>
/// 镜像这一段的可回收字节,口径同 docker CLI(<c>system df</c> 的 RECLAIMABLE 列):
/// <c>LayersSize − Σ(在用镜像的 Size − SharedSize)</c>,不小于 0。
/// <para>
/// 不能把未使用镜像的 <c>Size</c> 直接相加:<c>Size</c> 含与其它镜像共享的层,
/// 两个基于同一个基础镜像的旧版本会把那几层算两遍,报出一个比磁盘上实际能腾出来的
/// 还大的数。<c>LayersSize</c> 是去重后的层总量,减掉在用镜像独占的那部分才是能删的。
/// </para>
/// <para>
/// 老 daemon 不报 <c>LayersSize</c> 时退回逐个相加 —— 偏大,但总比报 0 强。
/// </para>
/// </summary>
private static long ReclaimableImageBytes(DiskUsage usage, ImageSummary[] unusedImages)
{
if (usage.LayersSize <= 0)
{
return unusedImages.Sum(static i => i.Size);
}
long used = 0;
foreach (ImageSummary image in usage.Images ?? [])
{
// SharedSize 为 -1 表示 daemon 没算;CLI 同样跳过这种镜像。
if (image.Containers > 0 && image.Size >= 0 && image.SharedSize >= 0)
{
used += image.Size - image.SharedSize;
}
}
return Math.Max(0, usage.LayersSize - used);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,8 @@ public Task<ContainerTopResult> TopAsync(string id, string psArgs = "-ef", Cance
/// <summary>可写层相对镜像的变更(<c>docker diff</c>)。</summary>
public async Task<FilesystemChange[]> ChangesAsync(string id, CancellationToken cancellationToken = default)
{
// 没有任何变更时 daemon 返回 JSON null,不是空数组。
// 没有任何变更时 daemon 返回 JSON null,不是空数组。错误状态码已由 GetStringAsync 翻成异常,
// 不会再把 {"message":"No such container"} 静默当成"没有变更"。
string body = await GetStringAsync($"/containers/{Uri.EscapeDataString(id)}/changes", cancellationToken).ConfigureAwait(false);
return DockerJson.TryDeserialize<FilesystemChange[]>(body) ?? [];
}
Expand Down Expand Up @@ -114,13 +115,13 @@ public Task<CommitResponse> CommitContainerAsync(string id, string? repository,
("tag", string.IsNullOrWhiteSpace(tag) ? null : tag),
("comment", string.IsNullOrWhiteSpace(comment) ? null : comment),
("author", string.IsNullOrWhiteSpace(author) ? null : author),
("pause", pause ? "1" : "0")), null, cancellationToken);
("pause", pause ? "1" : "0")), null, NoTimeout, cancellationToken);

/// <summary>
/// 等容器结束并拿退出码。用于"跑一次性容器"的场景。
/// 等容器结束并拿退出码。用于"跑一次性容器"的场景。不设时限 —— 容器跑多久就等多久,只认取消令牌。
/// </summary>
public Task<WaitResponse> WaitContainerAsync(string id, CancellationToken cancellationToken = default) =>
PostJsonAsync<WaitResponse>($"/containers/{Uri.EscapeDataString(id)}/wait", null, cancellationToken);
PostJsonAsync<WaitResponse>($"/containers/{Uri.EscapeDataString(id)}/wait", null, NoTimeout, cancellationToken);
}

/// <summary>等待容器结束的响应。</summary>
Expand Down
159 changes: 132 additions & 27 deletions plugins/VelaShell.Plugin.DockerPanel/Docker/DockerClient.Exec.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,12 @@ public readonly record struct ExecCapture(string StandardOutput, string Standard
/// <summary>退出码为 0。</summary>
public bool IsSuccess => ExitCode == 0;

/// <summary>
/// 输出超过 <see cref="DockerClient.MaxExecCaptureBytes" /> 被截断了。
/// 截断时连接被主动断开,命令若还没跑完,<see cref="ExitCode" /> 记为 <c>-1</c>。
/// </summary>
public bool IsTruncated { get; init; }

/// <summary>给人看的一行失败原因。</summary>
public string FailureText
{
Expand Down Expand Up @@ -50,15 +56,28 @@ public async Task WriteAsync(ReadOnlyMemory<byte> data, CancellationToken cancel
}

/// <summary>持续读出容器的输出,直到会话结束或取消。</summary>
public Task ReadAsync(Action<DockerLogLine> onLine, CancellationToken cancellationToken)
/// <remarks>
/// 取消即释放底层流(会话随之结束):隧道上的劫持流不一定理会取消令牌,
/// 不这么做的话一个没有输出的会话会让取消永远等下去。
/// </remarks>
public async Task ReadAsync(Action<DockerLogLine> onLine, CancellationToken cancellationToken)
{
var decoder = new DockerFrameDecoder(Tty, timestamps: false);
return decoder.ReadAsync(stream, onLine, cancellationToken);
using (cancellationToken.Register(stream.Dispose))
{
await decoder.ReadAsync(stream, onLine, cancellationToken).ConfigureAwait(false);
}
}

/// <summary>把原始字节交给调用方(终端控件要的是字节,不是行)。</summary>
public ValueTask<int> ReadRawAsync(Memory<byte> buffer, CancellationToken cancellationToken = default) =>
stream.ReadAsync(buffer, cancellationToken);
/// <remarks>与 <see cref="ReadAsync" /> 一样:取消一次读取即结束整个会话。</remarks>
public async ValueTask<int> ReadRawAsync(Memory<byte> buffer, CancellationToken cancellationToken = default)
{
using (cancellationToken.Register(stream.Dispose))
{
return await stream.ReadAsync(buffer, cancellationToken).ConfigureAwait(false);
}
}

/// <summary>
/// 底层的双工流,交给终端视图去泵。
Expand All @@ -85,6 +104,16 @@ public Task<ExecInspectResponse> InspectAsync(CancellationToken cancellationToke

public sealed partial class DockerClient
{
/// <summary>
/// <see cref="ExecCaptureAsync" /> 收集输出的上限(stdout + stderr 合计,按 UTF-16 字符计)。
/// 超过就截断并断开 —— 一条意外刷屏的命令不该把宿主进程的内存吃光
/// (插件与宿主同进程,OOM 带走的是整个 VelaShell)。
/// </summary>
public const int MaxExecCaptureBytes = 8 * 1024 * 1024;

/// <summary><see cref="ExecCaptureAsync" /> 的默认时限。</summary>
public static readonly TimeSpan DefaultExecTimeout = TimeSpan.FromMinutes(2);

/// <summary>
/// 在容器里开一条**交互式** exec 会话。返回的会话握着一条独立的隧道,
/// 调用方负责释放它 —— 释放即结束远端进程。
Expand All @@ -106,10 +135,22 @@ public async Task<DockerExecSession> StartExecAsync(string containerId, string[]
try
{
string body = JsonSerializer.Serialize(new { Detach = false, Tty = tty }, DockerJson.Options);
(int status, string? reason, Stream? hijacked) = await DockerRawHttp
.PostAsync(stream, $"/exec/{Uri.EscapeDataString(created.Id)}/start", body, upgrade: true, cancellationToken)
.ConfigureAwait(false);
return status is not (200 or 101) ? throw new DockerApiException((System.Net.HttpStatusCode)status, $"启动 exec 失败:HTTP {status} {reason}") : new(created.Id, hijacked, this, tty);
int status;
string reason, head;
Stream hijacked;
// 握手期间的取消同样靠释放流打断(隧道流的读不一定理会令牌)。
using (cancellationToken.Register(stream.Dispose))
{
(status, reason, head, hijacked) = await DockerRawHttp
.PostAsync(stream, $"/exec/{Uri.EscapeDataString(created.Id)}/start", body, upgrade: true, cancellationToken)
.ConfigureAwait(false);
if (status is not (200 or 101))
{
throw await StartExecFailureAsync(status, reason, head, hijacked, cancellationToken).ConfigureAwait(false);
}
}
cancellationToken.ThrowIfCancellationRequested();
return new(created.Id, hijacked, this, tty);
}
catch
{
Expand All @@ -126,33 +167,97 @@ public async Task<DockerExecSession> StartExecAsync(string containerId, string[]
/// 而"命令失败了"和"命令没有输出"才区分得开。
/// </para>
/// </summary>
/// <param name="containerId">容器 id 或名字。</param>
/// <param name="command">要执行的命令(argv 形态,不经 shell 解析)。</param>
/// <param name="user">以哪个用户执行;留空用镜像默认。</param>
/// <param name="workingDir">工作目录;留空用镜像默认。</param>
/// <param name="timeout">时限;null 用 <see cref="DefaultExecTimeout" />。超时抛 <see cref="TimeoutException" />。</param>
/// <param name="cancellationToken">取消令牌。</param>
public async Task<ExecCapture> ExecCaptureAsync(string containerId, string[] command,
string? user = null, string? workingDir = null, CancellationToken cancellationToken = default)
string? user = null, string? workingDir = null, TimeSpan? timeout = null,
CancellationToken cancellationToken = default)
{
ExecCreateResponse created = await CreateExecAsync(containerId, command, tty: false, attachStdin: false,
user, workingDir, cancellationToken).ConfigureAwait(false);
Stream stream = await Transport.ConnectAsync(cancellationToken).ConfigureAwait(false);
TimeSpan limit = timeout ?? DefaultExecTimeout;
using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
if (limit != Timeout.InfiniteTimeSpan)
{
cts.CancelAfter(limit);
}
CancellationToken token = cts.Token;
var stdout = new StringBuilder();
var stderr = new StringBuilder();
await using (stream.ConfigureAwait(false))
bool truncated = false;
string execId;
try
{
string body = JsonSerializer.Serialize(new { Detach = false, Tty = false }, DockerJson.Options);
(int status, string? reason, Stream? hijacked) = await DockerRawHttp
.PostAsync(stream, $"/exec/{Uri.EscapeDataString(created.Id)}/start", body, upgrade: true, cancellationToken)
.ConfigureAwait(false);
if (status is not (200 or 101))
ExecCreateResponse created = await CreateExecAsync(containerId, command, tty: false, attachStdin: false,
user, workingDir, token).ConfigureAwait(false);
execId = created.Id;
Stream stream = await Transport.ConnectAsync(token).ConfigureAwait(false);
await using (stream.ConfigureAwait(false))
// 隧道上的劫持流不一定理会取消令牌:取消 / 超时一律以释放流来打断读取,
// 否则一条不出声的命令能让调用方永远等下去。
using (token.Register(stream.Dispose))
{
throw new DockerApiException((System.Net.HttpStatusCode)status, $"启动 exec 失败:HTTP {status} {reason}");
string body = JsonSerializer.Serialize(new { Detach = false, Tty = false }, DockerJson.Options);
(int status, string reason, string head, Stream hijacked) = await DockerRawHttp
.PostAsync(stream, $"/exec/{Uri.EscapeDataString(created.Id)}/start", body, upgrade: true, token)
.ConfigureAwait(false);
if (status is not (200 or 101))
{
throw await StartExecFailureAsync(status, reason, head, hijacked, token).ConfigureAwait(false);
}
// 截断时用它停下读取循环;它不连着外面的令牌,停下来不算"被取消"。
using var stop = CancellationTokenSource.CreateLinkedTokenSource(token);
var decoder = new DockerFrameDecoder(tty: false, timestamps: false);
try
{
await decoder.ReadAsync(hijacked, line =>
{
if (truncated)
{
return;
}
if (stdout.Length + stderr.Length + line.Text.Length + 1 > MaxExecCaptureBytes)
{
truncated = true;
stop.Cancel();
return;
}
StringBuilder target = line.Kind == DockerStreamKind.StdErr ? stderr : stdout;
_ = target.Append(line.Text).Append('\n');
}, stop.Token).ConfigureAwait(false);
}
catch (OperationCanceledException) when (truncated && !token.IsCancellationRequested)
{
// 主动截断,不是取消。
}
}
var decoder = new DockerFrameDecoder(tty: false, timestamps: false);
await decoder.ReadAsync(hijacked, line =>
{
StringBuilder target = line.Kind == DockerStreamKind.StdErr ? stderr : stdout;
_ = target.Append(line.Text).Append('\n');
}, cancellationToken).ConfigureAwait(false);
ExecInspectResponse inspect = await InspectExecAsync(execId, token).ConfigureAwait(false);
// 截断时连接已断,命令可能还在跑 —— 那时的退出码没有意义,不能报成成功。
int exitCode = truncated && inspect.Running ? -1 : inspect.ExitCode;
return new(stdout.ToString(), stderr.ToString(), exitCode) { IsTruncated = truncated };
}
catch (Exception ex) when (!cancellationToken.IsCancellationRequested && cts.IsCancellationRequested
&& ex is OperationCanceledException or ObjectDisposedException or IOException
or DockerUnreachableException)
{
throw new TimeoutException($"命令在 {limit.TotalSeconds:0} 秒内没有结束:{string.Join(' ', command)}", ex);
}
ExecInspectResponse inspect = await InspectExecAsync(created.Id, cancellationToken).ConfigureAwait(false);
return new(stdout.ToString(), stderr.ToString(), inspect.ExitCode);
catch (Exception ex) when (cancellationToken.IsCancellationRequested && ex is not OperationCanceledException)
{
// 取消是靠释放流实现的,冒上来的会是 ObjectDisposedException / IOException —— 统一成取消。
throw new OperationCanceledException(cancellationToken);
}
}

/// <summary>exec 启动失败:把 daemon 的原话读出来(容器没在跑、exec 不存在 ……)。</summary>
private static async Task<DockerApiException> StartExecFailureAsync(int status, string reason, string head,
Stream body, CancellationToken cancellationToken)
{
string message = await DockerRawHttp.ReadErrorMessageAsync(status, reason, head, body, cancellationToken)
.ConfigureAwait(false);
return new((System.Net.HttpStatusCode)status, $"启动 exec 失败:{message}");
}

/// <summary>创建一个 exec 实例(还没开始跑)。</summary>
Expand Down
Loading
Loading