feat(storage): probe backend health independently

go
codex 3 weeks ago
parent adbaa7539e
commit a03056ad4b

@ -0,0 +1,25 @@
[Unit]
Description=Virt Cloud object storage health probe worker
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
User=apache
Group=apache
WorkingDirectory=/home/virt-cloud/web
ExecStart=/usr/bin/php /home/virt-cloud/web/xcat cloudStorageHealthWorker
Restart=on-failure
RestartSec=5
LimitCORE=0
UMask=0077
NoNewPrivileges=true
PrivateTmp=true
ProtectHome=false
ProtectSystem=strict
ReadWritePaths=-/home/virt-cloud/runtime/php
ReadWritePaths=-/home/virt-cloud/web/storage
TimeoutStopSec=30
[Install]
WantedBy=multi-user.target

@ -230,6 +230,7 @@ cp /home/virt-cloud/deploy/virt-cloud-vpc-worker@.service /etc/systemd/system/
cp /home/virt-cloud/deploy/virt-cloud-recovery-worker.service /etc/systemd/system/
cp /home/virt-cloud/deploy/virt-cloud-notification-worker.service /etc/systemd/system/
cp /home/virt-cloud/deploy/virt-cloud-storage-replica-worker.service /etc/systemd/system/
cp /home/virt-cloud/deploy/virt-cloud-storage-health-worker.service /etc/systemd/system/
cd /home/virt-cloud/agent
go build -trimpath -o /home/virt-cloud/bin/virt-cloud-storage-replicator \
./cmd/virt-cloud-storage-replicator
@ -238,7 +239,7 @@ chmod 0755 /home/virt-cloud/bin/virt-cloud-storage-replicator
systemctl daemon-reload
systemctl enable --now virt-cloud-worker.service \
virt-cloud-recovery-worker.service virt-cloud-notification-worker.service \
virt-cloud-storage-replica-worker.service \
virt-cloud-storage-replica-worker.service virt-cloud-storage-health-worker.service \
virt-cloud-lifecycle.service \
virt-cloud-policy-worker@1.service virt-cloud-policy-worker@2.service \
virt-cloud-vpc-worker@{1..8}.service
@ -250,6 +251,8 @@ systemctl enable --now virt-cloud-worker.service \
`virt-cloud-storage-replica-worker.service` 独立流式复制已冻结的对象存储制品,不占用虚拟机任务 worker。PHP 只通过标准输入把短期、限方法的 capability 交给 helper;命令行、环境、数据库和日志都不保存 capability 或对象存储凭据。复制租约覆盖 helper 的完整六小时硬截止;进程中断、回执损坏或完成结果不确定时只对固定目标对象执行 HEAD 与精确对象键的 Multipart 列表查询,不自动重放复制或 Abort。只有连续两次确认目标对象和对应 Multipart 会话都不存在后,才会重排同一复制意图;唯一且时间窗口匹配的未持久化会话可被原操作接管。同一对象键出现多个会话、记录会话与远端不匹配或会话无法归属原操作时,连续两次稳定证据会使原操作进入“副本人工核对”;管理员在提供商侧清理多余会话后只能重开该原操作的只读核对,本次点击不会由面板 Abort 或直接新建上传;只有两次确认无远端效果后才会沿用原操作安全重试。该 worker 独立写入 `storage_replica` 运行心跳;后台运行状态出现警告时应同时核对制品发布状态和该 unit 的 journal,不能仅凭 systemd 的 `active` 判断复制正常。
`virt-cloud-storage-health-worker.service` 与副本复制 worker 彻底隔离:它每次只领取一个到期后端,在数据库事务外执行最长 15 秒的 `HeadBucket`,并且只能按领取时冻结的配置版本结算。成功只恢复健康证据,不会把人工设置的 `read_only`、`draining` 或 `disabled` 改回 `active`;失败使正在 `active` 的后端转为 `read_only`、按 60 秒到 1 小时退避,新写入随即停止选择它。这个 worker 不执行 PUT、COPY、DELETE 或 Abort,也不把凭据写入心跳、日志或命令行。
实例补偿要求 v35 的批次、明细和收件人账本。`php xcat cloudInit` 只能为全新空数据库创建和验证它们,不能冒充既有数据库的增量升级。既有安装发布前必须备份数据库,使用经过审核的一次性迁移落地完整 v35 结构并核对 schema 指纹;升级成功后删除迁移脚本。然后重启普通 worker 和 notification worker。补偿不调用 Agent/Gateway,因此这一功能本身不要求更新或重新编译宿主机 Agent 和面板 Gateway。完整语义见 [`SERVICE_COMPENSATION.md`](SERVICE_COMPENSATION.md)。
共享流量池必须严格按 `disabled -> shadow -> enforced` 上线,并在强制执行前通过全部账本、采样和网络策略门禁。现有数据库不能使用 `php xcat cloudInit` 冒充增量升级,旧服务周期也不能通过 SQL 回填到流量池;完整步骤、验收项和故障处置见 [`TRAFFIC_POOL_ROLLOUT.md`](TRAFFIC_POOL_ROLLOUT.md)。
@ -440,6 +443,7 @@ location = /agent/console {
journalctl -u virt-cloud-agent.service -n 200 --no-pager
journalctl -u virt-cloud-worker.service -u virt-cloud-recovery-worker.service \
-u virt-cloud-storage-replica-worker.service \
-u virt-cloud-storage-health-worker.service \
-u virt-cloud-lifecycle.service \
-u 'virt-cloud-policy-worker@*' -u 'virt-cloud-vpc-worker@*' \
-n 200 --no-pager

@ -0,0 +1,58 @@
<?php
namespace App\Command;
use App\Services\Cloud\CloudObjectStorageHealthProbeService;
use App\Services\Cloud\CloudRuntimeHeartbeat;
/** Short periodic provider probes, intentionally isolated from replica copy. */
final class CloudStorageHealthWorker
{
public static function run(
array $argv = [],
?CloudRuntimeHeartbeat $heartbeat = null
): int {
$once = in_array('--once', $argv, true);
$heartbeat ??= CloudRuntimeHeartbeat::start('storage_health', $once);
$unresolved = false;
try {
$worker = new CloudObjectStorageHealthProbeService();
do {
$heartbeat->busy('storage_health_probe');
try {
$worked = $worker->tick();
$errors = $worker->observationErrors();
} catch (\Throwable $error) {
$errors = ['storage_health_failed'];
$heartbeat->error('storage_health_failed');
fwrite(STDERR, 'storage health worker temporarily unavailable: '
. get_class($error) . PHP_EOL);
if ($once) {
return 1;
}
$worked = false;
}
if ($errors === []) {
if ($worked) {
$unresolved = false;
$heartbeat->success();
} elseif (!$unresolved) {
$heartbeat->success();
}
} else {
$unresolved = true;
$heartbeat->error($errors[0]);
}
if (!$once && !$worked) {
usleep(1000000);
}
} while (!$once);
} catch (\Throwable $error) {
$heartbeat->error('storage_health_failed');
throw $error;
} finally {
$heartbeat->stopped();
}
return 0;
}
}

@ -24,6 +24,8 @@ class XCat
'cloudWorker' => CloudWorker::run($this->argv) === 0,
'cloudStorageReplicaWorker' =>
CloudStorageReplicaWorker::run($this->argv) === 0,
'cloudStorageHealthWorker' =>
CloudStorageHealthWorker::run($this->argv) === 0,
'cloudLifecycle' => CloudLifecycle::run($this->argv) === 0,
'cloudTrafficPoolAttention' =>
CloudTrafficPoolAttention::run($this->argv) === 0,
@ -104,6 +106,7 @@ class XCat
. " php xcat cloudInit\n"
. " php xcat cloudWorker [--once] [--policy-only|--vpc-batch-only|--recovery-only|--notification-only]\n"
. " php xcat cloudStorageReplicaWorker [--once]\n"
. " php xcat cloudStorageHealthWorker [--once]\n"
. " php xcat cloudLifecycle [--once]\n"
. " php xcat cloudTrafficPoolAttention inspect --pool-id=N\n"
. " php xcat cloudTrafficPoolAttention inspect-resolution --resolution-key=UUID\n"

@ -0,0 +1,209 @@
<?php
namespace App\Services\Cloud;
use App\Models\CloudStorageBackend;
/** Periodic read-only provider checks, isolated from long replica copies. */
final class CloudObjectStorageHealthProbeService
{
private const CLAIM_SECONDS = 45;
private const HEALTHY_INTERVAL_SECONDS = 300;
private \Closure $runtimeResolver;
private \Closure $headBucket;
private \Closure $clock;
/** @var list<string> */
private array $observationErrors = [];
public function __construct(
?callable $runtimeResolver = null,
?callable $headBucket = null,
?callable $clock = null
) {
$this->runtimeResolver = \Closure::fromCallable(
$runtimeResolver ?? static fn (int $backendId): array =>
CloudObjectStorageBackendRegistry::runtime($backendId, false)
);
$this->headBucket = \Closure::fromCallable(
$headBucket ?? static function (array $config, array $credentials): void {
(new CloudObjectStorageS3Client())->headBucket($config, $credentials);
}
);
$this->clock = \Closure::fromCallable($clock ?? 'time');
}
/** Claim and inspect at most one due backend. */
public function tick(): bool
{
$this->observationErrors = [];
$claim = $this->claimDueBackend();
if ($claim === null) {
return false;
}
try {
$runtime = ($this->runtimeResolver)($claim['backend_id']);
if ((int) ($runtime['backend_id'] ?? 0) !== $claim['backend_id']
|| (int) ($runtime['revision'] ?? 0) !== $claim['revision']) {
$this->releaseChangedRevision($claim);
return true;
}
// Deliberately outside every database transaction. Credentials
// exist only in this call frame and are never persisted or logged.
($this->headBucket)($runtime['config'], $runtime['credentials']);
$this->settleSuccess($claim);
} catch (CloudObjectStorageTestError $error) {
$this->settleFailure($claim, $error->publicCode);
$this->observationErrors[] = 'storage_backend_unhealthy';
} catch (\Throwable $error) {
// Runtime/decryption/client failures are bounded to a public code;
// exception messages can contain deployment details and stay local.
$this->settleFailure($claim, 'request_rejected');
$this->observationErrors[] = 'storage_health_failed';
}
return true;
}
/** @return list<string> */
public function observationErrors(): array
{
return $this->observationErrors;
}
/** @return array{backend_id:int,revision:int,claim_until:int}|null */
private function claimDueBackend(): ?array
{
$now = $this->now();
$connection = (new CloudStorageBackend())->getConnection();
return $connection->transaction(static function () use ($now): ?array {
$backend = CloudStorageBackend::query()
->where('admin_state', '<>', 'retired')
->where(static function ($query) use ($now): void {
$query->where(static function ($due) use ($now): void {
$due->where('next_probe_at', '>', 0)
->where('next_probe_at', '<=', $now);
})->orWhere(static function ($bootstrap): void {
// Earlier registry imports can carry valid current
// health evidence without a first periodic schedule.
$bootstrap->where('next_probe_at', 0)
->where('health_state', 'healthy')
->where('tested_revision', '>', 0)
->whereColumn('tested_revision', 'config_revision');
});
})
->orderBy('next_probe_at')->orderBy('id')
->lockForUpdate()->first();
if (!$backend instanceof CloudStorageBackend) {
return null;
}
$claimUntil = $now + self::CLAIM_SECONDS;
$backend->next_probe_at = $claimUntil;
$backend->updated_at = $now;
$backend->save();
return [
'backend_id' => (int) $backend->id,
'revision' => (int) $backend->config_revision,
'claim_until' => $claimUntil,
];
});
}
/** @param array{backend_id:int,revision:int,claim_until:int} $claim */
private function settleSuccess(array $claim): bool
{
$now = $this->now();
return $this->settle($claim, static function (
CloudStorageBackend $backend
) use ($now): void {
$backend->tested_revision = (int) $backend->config_revision;
$backend->health_state = 'healthy';
$backend->consecutive_failures = 0;
$backend->consecutive_successes =
(int) $backend->consecutive_successes + 1;
$backend->last_error_code = '';
$backend->last_tested_at = $now;
$backend->last_healthy_at = $now;
$backend->next_probe_at = $now + self::HEALTHY_INTERVAL_SECONDS;
$backend->updated_at = $now;
// admin_state is intentionally untouched. A successful probe can
// restore evidence, but cannot override an administrator decision.
});
}
/** @param array{backend_id:int,revision:int,claim_until:int} $claim */
private function settleFailure(array $claim, string $code): bool
{
$now = $this->now();
return $this->settle($claim, static function (
CloudStorageBackend $backend
) use ($now, $code): void {
$backend->tested_revision = 0;
$backend->health_state = in_array($code, [
'endpoint_unreachable', 'service_unavailable', 'rate_limited',
], true) ? 'unreachable' : 'degraded';
$failures = (int) $backend->consecutive_failures + 1;
$backend->consecutive_failures = $failures;
$backend->consecutive_successes = 0;
$backend->last_error_code = $code;
$backend->last_tested_at = $now;
$backend->next_probe_at = $now + min(
3600,
60 * (2 ** min(5, $failures - 1))
);
if ((string) $backend->admin_state === 'active') {
$backend->admin_state = 'read_only';
}
$backend->updated_at = $now;
});
}
/**
* @param array{backend_id:int,revision:int,claim_until:int} $claim
* @param callable(CloudStorageBackend):void $mutation
*/
private function settle(array $claim, callable $mutation): bool
{
$connection = (new CloudStorageBackend())->getConnection();
return $connection->transaction(static function () use (
$claim,
$mutation
): bool {
$backend = CloudStorageBackend::query()
->whereKey($claim['backend_id'])->lockForUpdate()->first();
if (!$backend instanceof CloudStorageBackend
|| (int) $backend->config_revision !== $claim['revision']
|| (int) $backend->next_probe_at !== $claim['claim_until']) {
return false;
}
$mutation($backend);
$backend->save();
return true;
});
}
/** @param array{backend_id:int,revision:int,claim_until:int} $claim */
private function releaseChangedRevision(array $claim): void
{
$now = $this->now();
$connection = (new CloudStorageBackend())->getConnection();
$connection->transaction(static function () use ($claim, $now): void {
$backend = CloudStorageBackend::query()
->whereKey($claim['backend_id'])->lockForUpdate()->first();
if ($backend instanceof CloudStorageBackend
&& (int) $backend->config_revision !== $claim['revision']
&& (int) $backend->next_probe_at === $claim['claim_until']) {
// Metadata-only transitions preserve the probe schedule. Let
// their new revision be inspected immediately. Runtime edits
// already reset next_probe_at to zero and do not match here.
$backend->next_probe_at = $now;
$backend->updated_at = $now;
$backend->save();
}
});
}
private function now(): int
{
return max(1, (int) ($this->clock)());
}
}

@ -93,6 +93,7 @@ final class CloudRuntimeHealthService
'recovery' => '任务安全收敛',
'notification' => '维护邮件投递',
'storage_replica' => '对象存储副本复制',
'storage_health' => '对象存储健康探测',
'lifecycle' => '到期与流量调度'] as $key => $label) {
$found = null;
foreach (is_array($heartbeats) ? $heartbeats : [] as $row) {

@ -10,6 +10,7 @@ final class CloudRuntimeHeartbeat
'recovery' => ['recovery', '任务安全收敛 worker'],
'notification' => ['notification', '客户通知 worker'],
'storage_replica' => ['storage_replica', '对象存储副本 worker'],
'storage_health' => ['storage_health', '对象存储健康探测 worker'],
'lifecycle' => ['lifecycle', '生命周期调度']];
private const PHASES = ['startup' => '启动', 'worker_tick' => '任务消费或核对',
'recovery_tick' => '任务安全收敛',
@ -23,6 +24,7 @@ final class CloudRuntimeHeartbeat
'rescue_template_reconcile' => '救援 ISO 副本核对',
'rescue_template_cleanup' => '救援 ISO 退役清理',
'storage_replica_tick' => '对象存储副本复制或核对',
'storage_health_probe' => '对象存储健康探测',
'traffic_sync' => '流量同步',
'runtime_status_sync' => '实例状态同步',
'instance_reconcile' => '实例策略核对',
@ -37,6 +39,7 @@ final class CloudRuntimeHeartbeat
'rescue_template_reconcile_failed',
'rescue_template_cleanup_failed',
'storage_replica_failed',
'storage_health_failed', 'storage_backend_unhealthy',
'traffic_sync_failed', 'runtime_status_sync_failed',
'runtime_status_sync_unconfigured', 'traffic_collection_unconfigured',
'traffic_log_schema_missing', 'traffic_agent_unavailable',
@ -226,7 +229,7 @@ final class CloudRuntimeHeartbeat
if (++$scanned > self::SCAN_LIMIT || $removed >= 32) {
break;
}
if (preg_match('/^(normal|policy|vpc|recovery|notification|storage_replica|lifecycle)-[1-9][0-9]*-[a-f0-9]{24}\.json(?:\.tmp)?$/D',
if (preg_match('/^(normal|policy|vpc|recovery|notification|storage_replica|storage_health|lifecycle)-[1-9][0-9]*-[a-f0-9]{24}\.json(?:\.tmp)?$/D',
$entry->getFilename()) !== 1) {
continue;
}
@ -316,7 +319,7 @@ final class CloudRuntimeHeartbeat
$incomplete = true;
break;
}
if (preg_match('/^(normal|policy|vpc|recovery|notification|storage_replica|lifecycle)-[1-9][0-9]*-[a-f0-9]{24}\.json$/D',
if (preg_match('/^(normal|policy|vpc|recovery|notification|storage_replica|storage_health|lifecycle)-[1-9][0-9]*-[a-f0-9]{24}\.json$/D',
$entry->getFilename(), $match) !== 1) {
continue;
}

@ -0,0 +1,250 @@
<?php
require dirname(__DIR__) . '/vendor/autoload.php';
use App\Models\CloudStorageBackend;
use App\Services\Cloud\CloudObjectStorageHealthProbeService;
use App\Services\Cloud\CloudObjectStorageTestError;
use Illuminate\Database\Capsule\Manager as Capsule;
use Illuminate\Database\Schema\Blueprint;
$assert = static function (bool $condition, string $message): void {
if (!$condition) {
throw new RuntimeException($message);
}
};
$capsule = new Capsule();
$capsule->addConnection(['driver' => 'sqlite', 'database' => ':memory:']);
$capsule->setAsGlobal();
$capsule->bootEloquent();
$capsule->schema()->create('cloud_storage_backends', static function (
Blueprint $table
): void {
$table->increments('id');
$table->string('backend_key')->unique();
$table->string('identity_sha256')->unique();
$table->string('name');
$table->string('driver');
$table->string('endpoint');
$table->string('region');
$table->string('bucket');
$table->string('prefix');
$table->boolean('path_style');
$table->string('failure_domain');
$table->text('sealed_credentials');
$table->unsignedBigInteger('config_revision');
$table->unsignedBigInteger('tested_revision');
$table->string('admin_state');
$table->string('health_state');
$table->unsignedInteger('write_priority');
$table->unsignedInteger('consecutive_failures');
$table->unsignedInteger('consecutive_successes');
$table->string('last_error_code');
$table->unsignedBigInteger('last_tested_at');
$table->unsignedBigInteger('last_healthy_at');
$table->unsignedBigInteger('next_probe_at');
$table->unsignedBigInteger('created_at');
$table->unsignedBigInteger('updated_at');
});
$now = 2000000000;
$clock = static function () use (&$now): int { return $now; };
$insert = static function (array $values = []) use (&$now): int {
$id = CloudStorageBackend::query()->max('id') + 1;
return (int) Capsule::table('cloud_storage_backends')->insertGetId(array_replace([
'backend_key' => str_pad(dechex($id), 32, '0', STR_PAD_LEFT),
'identity_sha256' => str_repeat(dechex(($id % 15) + 1), 64),
'name' => 'Backend ' . $id,
'driver' => 's3',
'endpoint' => 'https://storage-' . $id . '.example.test',
'region' => 'test-1',
'bucket' => 'bucket-' . $id,
'prefix' => 'virt',
'path_style' => 0,
'failure_domain' => 'provider-' . $id,
'sealed_credentials' => 'sealed-marker-' . $id,
'config_revision' => 3,
'tested_revision' => 3,
'admin_state' => 'active',
'health_state' => 'healthy',
'write_priority' => 10,
'consecutive_failures' => 0,
'consecutive_successes' => 1,
'last_error_code' => '',
'last_tested_at' => $now - 600,
'last_healthy_at' => $now - 600,
'next_probe_at' => $now - 1,
'created_at' => $now - 1000,
'updated_at' => $now - 600,
], $values));
};
$runtime = static function (int $backendId): array {
$row = CloudStorageBackend::query()->findOrFail($backendId);
return [
'backend_id' => $backendId,
'revision' => (int) $row->config_revision,
'config' => [
'endpoint' => (string) $row->endpoint,
'region' => (string) $row->region,
'bucket' => (string) $row->bucket,
'prefix' => (string) $row->prefix,
'path_style' => (bool) $row->path_style,
],
'credentials' => [
'access_key_id' => 'runtime-access-key',
'secret_access_key' => 'runtime-secret-key',
],
];
};
$clear = static function (): void {
Capsule::table('cloud_storage_backends')->delete();
};
// Successful probes restore current health evidence but preserve every manual
// non-active state. Provider work must never execute inside a transaction.
foreach (['read_only', 'draining', 'disabled'] as $manualState) {
$clear();
$backendId = $insert([
'admin_state' => $manualState,
'health_state' => 'unreachable',
'tested_revision' => 0,
'consecutive_failures' => 2,
'consecutive_successes' => 0,
'last_error_code' => 'service_unavailable',
]);
$providerCalls = 0;
$service = new CloudObjectStorageHealthProbeService(
static function (int $id) use ($runtime, $assert, $backendId): array {
$assert($id === $backendId
&& Capsule::connection()->transactionLevel() === 0,
'Runtime credentials were resolved inside a claim transaction.');
return $runtime($id);
},
static function (array $config, array $credentials) use (
&$providerCalls,
$assert
): void {
$providerCalls++;
$assert(Capsule::connection()->transactionLevel() === 0,
'HeadBucket ran inside a database transaction.');
$assert($config['bucket'] !== ''
&& $credentials['secret_access_key'] === 'runtime-secret-key',
'Probe did not receive the frozen backend runtime.');
},
$clock
);
$assert($service->tick() && $providerCalls === 1
&& $service->observationErrors() === [],
'A due healthy backend was not probed exactly once.');
$row = CloudStorageBackend::query()->findOrFail($backendId);
$assert($row->admin_state === $manualState
&& $row->health_state === 'healthy'
&& $row->tested_revision === $row->config_revision
&& $row->consecutive_failures === 0
&& $row->consecutive_successes === 1
&& $row->last_error_code === ''
&& $row->last_tested_at === $now
&& $row->last_healthy_at === $now
&& $row->next_probe_at === $now + 300,
'Success changed manual state or failed to restore current health evidence.');
}
// Provider failure removes the active backend from new-write placement and
// applies bounded exponential backoff without persisting runtime credentials.
$clear();
$backendId = $insert(['consecutive_failures' => 2]);
$service = new CloudObjectStorageHealthProbeService(
$runtime,
static function (): void {
if (Capsule::connection()->transactionLevel() !== 0) {
throw new RuntimeException('provider_io_in_transaction');
}
throw new CloudObjectStorageTestError(
'secret provider detail must not persist',
'endpoint_unreachable'
);
},
$clock
);
$assert($service->tick()
&& $service->observationErrors() === ['storage_backend_unhealthy'],
'Provider failure was not exposed as a bounded worker observation.');
$row = CloudStorageBackend::query()->findOrFail($backendId);
$databaseJson = json_encode($row->toArray(), JSON_THROW_ON_ERROR);
$assert($row->admin_state === 'read_only'
&& $row->health_state === 'unreachable'
&& $row->tested_revision === 0
&& $row->consecutive_failures === 3
&& $row->next_probe_at === $now + 240
&& $row->last_error_code === 'endpoint_unreachable'
&& !str_contains($databaseJson, 'runtime-secret-key')
&& !str_contains($databaseJson, 'secret provider detail'),
'Failure did not stop writes, apply backoff, or leaked private details.');
// One tick claims only one due backend. A later tick handles the next row.
$clear();
$firstId = $insert(['next_probe_at' => $now - 2]);
$secondId = $insert(['next_probe_at' => $now - 1]);
$calls = [];
$service = new CloudObjectStorageHealthProbeService(
$runtime,
static function (array $config) use (&$calls): void {
$calls[] = $config['bucket'];
},
$clock
);
$assert($service->tick() && count($calls) === 1
&& CloudStorageBackend::query()->findOrFail($firstId)->last_tested_at === $now
&& CloudStorageBackend::query()->findOrFail($secondId)->last_tested_at === $now - 600,
'One health tick claimed more than one due backend.');
// A configuration revision changed during the remote read makes the result
// stale. Settlement must leave the newer row untouched.
$clear();
$backendId = $insert();
$service = new CloudObjectStorageHealthProbeService(
$runtime,
static function () use ($backendId, $now): void {
Capsule::table('cloud_storage_backends')->where('id', $backendId)->update([
'config_revision' => 4,
'tested_revision' => 0,
'health_state' => 'unknown',
'admin_state' => 'draft',
'last_error_code' => '',
'updated_at' => $now + 1,
]);
},
$clock
);
$assert($service->tick(), 'Revision-race probe did not complete its bounded attempt.');
$row = CloudStorageBackend::query()->findOrFail($backendId);
$assert($row->config_revision === 4 && $row->tested_revision === 0
&& $row->health_state === 'unknown' && $row->admin_state === 'draft'
&& $row->last_tested_at === $now - 600,
'A stale HeadBucket result overwrote a newer backend revision.');
// A previously imported healthy backend may predate the periodic schedule.
// Current tested evidence is enough to bootstrap it once; an untested draft is
// still excluded so automation cannot bypass first-time administrator review.
$clear();
$importedId = $insert(['next_probe_at' => 0]);
$draftId = $insert([
'next_probe_at' => 0,
'tested_revision' => 0,
'health_state' => 'unknown',
'admin_state' => 'draft',
]);
$providerCalls = 0;
$service = new CloudObjectStorageHealthProbeService(
$runtime,
static function () use (&$providerCalls): void { $providerCalls++; },
$clock
);
$assert($service->tick() && $providerCalls === 1
&& CloudStorageBackend::query()->findOrFail($importedId)->next_probe_at
=== $now + 300
&& CloudStorageBackend::query()->findOrFail($draftId)->next_probe_at === 0,
'Legacy current health was not scheduled or an untested draft was probed.');
echo "Object storage health probe service tests passed.\n";

@ -52,12 +52,13 @@ foreach ([['user_id' => 42, 'is_admin' => false], ['user_id' => 0, 'is_admin' =>
$assert($calls === [], 'Unauthorized requests performed probes.');
$payload = $service->snapshot($actor);
$checks = array_column($payload['checks'], null, 'key');
$assert(count($checks) === 11 && $calls === ['default', 'log', 'agents', 'redis'], 'Missing or duplicate probes.');
$assert(count($checks) === 12 && $calls === ['default', 'log', 'agents', 'redis'], 'Missing or duplicate probes.');
$assert($checks['agents']['status'] === 'ok' && $checks['worker']['status'] === 'busy'
&& $checks['policy']['status'] === 'unknown'
&& $checks['vpc']['status'] === 'unknown'
&& $checks['notification']['status'] === 'unknown'
&& $checks['storage_replica']['status'] === 'unknown'
&& $checks['storage_health']['status'] === 'unknown'
&& $checks['lifecycle']['status'] === 'warning',
'Health or heartbeat semantics changed.');
$assert(!str_contains(json_encode($payload), 'MUST_NOT_EXPOSE'), 'Heartbeat internal fields leaked.');
@ -182,7 +183,7 @@ $response = (new CloudAdminRuntimeController())->index($request, new Response())
$assert($response->getStatusCode() === 200
&& $response->getHeaderLine('Cache-Control') === 'private, no-store', 'Runtime response cached or unavailable.');
$decoded = json_decode((string) $response->getBody(), true);
$assert(count($decoded['checks']) === 11
$assert(count($decoded['checks']) === 12
&& array_column($decoded['checks'], 'status', 'key')['agents'] === 'error',
'Partial failure lost other checks or fabricated Agent configuration health.');
$routes = file_get_contents(dirname(__DIR__) . '/config/routes_cloud.php');

@ -48,7 +48,7 @@ try {
$empty = $checks($missing);
$assert(array_keys($empty) === [
'worker', 'policy', 'vpc', 'recovery', 'notification',
'storage_replica', 'lifecycle',
'storage_replica', 'storage_health', 'lifecycle',
]
&& array_unique(array_column($empty, 'status')) === ['unknown'] && !file_exists($missing),
'Missing snapshot must be unknown, cover all kinds, and never create runtime files.');
@ -64,7 +64,10 @@ try {
$storageReplica = CloudRuntimeHeartbeat::start(
'storage_replica', false, $directory, $clock
);
$assert(count($files($directory)) === 6, 'Concurrent worker identities overwrite one another.');
$storageHealth = CloudRuntimeHeartbeat::start(
'storage_health', false, $directory, $clock
);
$assert(count($files($directory)) === 7, 'Concurrent worker identities overwrite one another.');
$assert(is_readable($directory) && is_writable($directory),
'Runtime directory is not readable and writable.');
foreach ($files($directory) as $path) {
@ -77,7 +80,9 @@ try {
&& $checks($directory)['notification']['active_count'] === 1
&& $checks($directory)['notification']['label'] === '客户通知 worker'
&& $checks($directory)['storage_replica']['active_count'] === 1
&& $checks($directory)['storage_replica']['label'] === '对象存储副本 worker',
&& $checks($directory)['storage_replica']['label'] === '对象存储副本 worker'
&& $checks($directory)['storage_health']['active_count'] === 1
&& $checks($directory)['storage_health']['label'] === '对象存储健康探测 worker',
'Starting workers or multiple policy reporters were not represented.');
$notification->busy('notification');
$assert(str_contains(
@ -89,6 +94,11 @@ try {
$checks($directory)['storage_replica']['message'],
'对象存储副本复制或核对'
), 'Object replica work did not receive an isolated runtime phase.');
$storageHealth->busy('storage_health_probe');
$assert(str_contains(
$checks($directory)['storage_health']['message'],
'对象存储健康探测'
), 'Object storage health probes did not receive an isolated runtime phase.');
$normal->busy('worker_tick');
$assert(str_contains($checks($directory)['worker']['message'], '任务消费或核对'),

@ -0,0 +1,59 @@
<?php
$root = dirname(__DIR__, 2);
$read = static function (string $path) use ($root): string {
$contents = file_get_contents($root . '/' . $path);
if (!is_string($contents)) {
throw new RuntimeException('Unable to read ' . $path);
}
return $contents;
};
$assert = static function (bool $condition, string $message): void {
if (!$condition) {
throw new RuntimeException($message);
}
};
$xcat = $read('web/app/Command/XCat.php');
$command = $read('web/app/Command/CloudStorageHealthWorker.php');
$service = $read('web/app/Services/Cloud/CloudObjectStorageHealthProbeService.php');
$heartbeat = $read('web/app/Services/Cloud/CloudRuntimeHeartbeat.php');
$runtime = $read('web/app/Services/Cloud/CloudRuntimeHealthService.php');
$unit = $read('deploy/virt-cloud-storage-health-worker.service');
$replicaUnit = $read('deploy/virt-cloud-storage-replica-worker.service');
$deployment = $read('docs/DEPLOYMENT.md');
$assert(str_contains($xcat, "'cloudStorageHealthWorker'")
&& str_contains($xcat, 'CloudStorageHealthWorker::run'),
'Health worker command is not reachable through xcat.');
$assert(str_contains($command, 'CloudObjectStorageHealthProbeService')
&& str_contains($command, "in_array('--once'")
&& str_contains($command, "'storage_health'")
&& str_contains($command, "busy('storage_health_probe')")
&& str_contains($command, "error('storage_health_failed')"),
'Health worker lost its independent loop, heartbeat, or once mode.');
$assert(str_contains($service, '->lockForUpdate()->first()')
&& str_contains($service, "where('next_probe_at', '<=', \$now)")
&& str_contains($service, "'claim_until' => \$claimUntil")
&& str_contains($service, "config_revision !== \$claim['revision']")
&& str_contains($service, "next_probe_at !== \$claim['claim_until']")
&& str_contains($service, "admin_state === 'active'")
&& str_contains($service, "admin_state = 'read_only'")
&& !str_contains($service, 'access_key_id')
&& !str_contains($service, 'secret_access_key'),
'Probe lost its one-row claim, frozen revision settlement, write fence, or credential boundary.');
$assert(str_contains($unit,
'ExecStart=/usr/bin/php /home/virt-cloud/web/xcat cloudStorageHealthWorker')
&& str_contains($unit, 'NoNewPrivileges=true')
&& str_contains($unit, 'ProtectSystem=strict')
&& str_contains($unit, 'LimitCORE=0')
&& !str_contains($replicaUnit, 'cloudStorageHealthWorker'),
'Health worker systemd isolation or hardening is incomplete.');
$assert(str_contains($heartbeat, "'storage_health'")
&& str_contains($heartbeat, "'storage_health_probe'")
&& str_contains($runtime, "'storage_health' => '对象存储健康探测'")
&& str_contains($deployment, 'virt-cloud-storage-health-worker.service')
&& str_contains($deployment, '事务外执行最长 15 秒'),
'Health worker deployment or runtime observability is incomplete.');
echo "Storage health worker contract tests passed.\n";
Loading…
Cancel
Save