diff --git a/apps/api/test/modules/deployments/compose-host-channel-notice.test.ts b/apps/api/test/modules/deployments/compose-host-channel-notice.test.ts index 58861d410..7ef67833d 100644 --- a/apps/api/test/modules/deployments/compose-host-channel-notice.test.ts +++ b/apps/api/test/modules/deployments/compose-host-channel-notice.test.ts @@ -1599,7 +1599,8 @@ describe("compose deploy — host channel unavailable", () => { expect(base.deployServiceWorkload).not.toHaveBeenCalled(); }); - it("refuses ambiguous duplicate containers before repairing or activating anything", async () => { + it.each([null, "server-original"])("refuses ambiguous duplicate containers on %s before repairing or activating anything", async (serverId) => { + h.previousDeployment.meta = { serverId }; const base = startingRuntime(); const liveContainer = (id: string, name: string) => ({ id, @@ -1665,11 +1666,18 @@ describe("compose deploy — host channel unavailable", () => { { executor: {} as CommandExecutor, hostPortTarget: localHostPortTarget, + serverId: serverId ?? undefined, }, ), - ).rejects.toThrow( - /more than one container matching active service "api".*no service activation/i, - ); + ).rejects.toMatchObject({ + code: "SERVICE_CONTAINER_CONFLICT", + message: expect.stringMatching(/more than one container matching active service "api".*no service activation/i), + details: { + projectId: "p1", serviceId: "svc-api", serviceName: "api", + containerNames: ["openship-app-api-a", "openship-app-api-b"], + serverId, workspaceId: null, + }, + }); expect(h.updateServiceDeployment).not.toHaveBeenCalled(); expect(h.allocateAndReservePinnedHostPort).not.toHaveBeenCalled(); diff --git a/apps/api/test/modules/deployments/resource-guidance.test.ts b/apps/api/test/modules/deployments/resource-guidance.test.ts index 3e0533151..68b7f89ee 100644 --- a/apps/api/test/modules/deployments/resource-guidance.test.ts +++ b/apps/api/test/modules/deployments/resource-guidance.test.ts @@ -237,3 +237,21 @@ it("retains resource guidance for a published partial rollout without turning it errorDetails: { resourceIssue: "storage-full" }, }); }); + + +it.each([true, false])("restores a container conflict on a Cloud=%s attempt without relabeling it as capacity", async (cloud) => { + const ctx = await attempt(cloud); + const details = { + projectId: ctx.project.id, + serviceId: "app-service", + containerNames: ["app-current", "app-duplicate"], + serverId: ctx.project.serverId ?? "ssh-original", + workspaceId: ctx.project.workspaceId, + }; + await onFailure(ctx, "More than one container matches the active service", undefined, { + errorCode: "SERVICE_CONTAINER_CONFLICT", errorDetails: details, + }); + expect(await getBuildSessionStatus(ctx.dep.id)).toMatchObject({ + status: "failed", errorCode: "SERVICE_CONTAINER_CONFLICT", errorDetails: details, + }); +}); diff --git a/apps/dashboard/src/components/import-project/DeploymentContainerConflictNotice.test.tsx b/apps/dashboard/src/components/import-project/DeploymentContainerConflictNotice.test.tsx new file mode 100644 index 000000000..838edb9f4 --- /dev/null +++ b/apps/dashboard/src/components/import-project/DeploymentContainerConflictNotice.test.tsx @@ -0,0 +1,89 @@ +// @vitest-environment happy-dom +import { act } from "react"; +import { createRoot, type Root } from "react-dom/client"; +import { afterEach, beforeEach, expect, it, vi } from "vitest"; +import { baseDictionary } from "@/i18n"; +import { + DEFAULT_CONFIG, + INITIAL_STATE, + type DeploymentContextType, +} from "@/context/deployment/types"; +import { DeploymentContainerConflictNotice } from "./DeploymentContainerConflictNotice"; + +let deployment: Pick; +vi.mock("@/context/DeploymentContext", () => ({ useDeployment: () => deployment })); +vi.mock("@/components/i18n-provider", () => ({ useI18n: () => ({ t: baseDictionary }) })); +let root: Root; +let host: HTMLDivElement; +const copy = baseDictionary.deployments.containerConflict; +beforeEach(() => { + vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true); + deployment = { + config: { + ...structuredClone(DEFAULT_CONFIG), + serverId: "server-current", + workspaceId: "space-current", + }, + state: { + ...structuredClone(INITIAL_STATE), + deploymentId: "attempt-original", + deploymentFailed: true, + errorCode: "SERVICE_CONTAINER_CONFLICT", + errorDetails: { + containerNames: ['', "app-duplicate"], + serverId: "server-original", + }, + }, + deploymentStatus: "failed", + }; + host = document.createElement("div"); + document.body.append(host); + root = createRoot(host); +}); +afterEach(async () => { + await act(async () => root.unmount()); + host.remove(); + vi.unstubAllGlobals(); +}); +async function render() { + await act(async () => root.render()); +} + +it("explains the conflict and links to the recorded server and support, without destructive actions", async () => { + await render(); + expect(host.textContent).toContain(copy.title); + expect(host.textContent).toContain("app-duplicate"); + expect(host.textContent).toContain("attempt-original"); + expect(host.querySelector('a[href="/servers/server-original"]')).not.toBeNull(); + expect(host.querySelector('a[href="/support"]')).not.toBeNull(); + expect(host.querySelectorAll("button")).toHaveLength(0); + expect(host.querySelector("img")).toBeNull(); +}); +it("opens the recorded managed space when no standalone server was recorded", async () => { + deployment.state.errorDetails = { containerNames: ["a", "b"], workspaceId: "space-original" }; + await render(); + expect(host.querySelector('a[href="/resources?pool=space-original"]')).not.toBeNull(); +}); +it("does not guess a missing historical target from current configuration", async () => { + deployment.state.errorDetails = null; + await render(); + expect(host.querySelectorAll("a")).toHaveLength(1); + expect(host.querySelector('a[href="/support"]')).not.toBeNull(); +}); +it.each(["building", "verifying", "ready", "cancelled"] as const)( + "clears the notice for %s", + async (status) => { + deployment.deploymentStatus = status; + await render(); + expect(host.textContent).toBe(""); + }, +); +it("does not reinterpret another error or a cancelled attempt as a container conflict", async () => { + deployment.state.errorCode = "HOST_UNREACHABLE"; + await render(); + expect(host.textContent).toBe(""); + deployment.state.errorCode = "SERVICE_CONTAINER_CONFLICT"; + deployment.state.deploymentCanceled = true; + await render(); + expect(host.textContent).toBe(""); +}); diff --git a/apps/dashboard/src/components/import-project/DeploymentContainerConflictNotice.tsx b/apps/dashboard/src/components/import-project/DeploymentContainerConflictNotice.tsx new file mode 100644 index 000000000..5c30828b0 --- /dev/null +++ b/apps/dashboard/src/components/import-project/DeploymentContainerConflictNotice.tsx @@ -0,0 +1,61 @@ +"use client"; + +import Link from "next/link"; +import { useDeployment } from "@/context/DeploymentContext"; +import { useI18n } from "@/components/i18n-provider"; +import { Button } from "@/components/ui/button"; + +/** Use this attempt's recorded target, even after the project has moved. */ +export function DeploymentContainerConflictNotice() { + const { state, deploymentStatus } = useDeployment(); + const { t } = useI18n(); + if ( + deploymentStatus !== "failed" || + state.deploymentCanceled || + state.errorCode !== "SERVICE_CONTAINER_CONFLICT" + ) + return null; + const copy = t.deployments.containerConflict; + const details = state.errorDetails; + const names = Array.isArray(details?.containerNames) + ? details.containerNames.filter((value): value is string => typeof value === "string") + : []; + const serverId = typeof details?.serverId === "string" && details.serverId; + const workspaceId = typeof details?.workspaceId === "string" && details.workspaceId; + const targetHref = serverId + ? `/servers/${encodeURIComponent(serverId)}` + : workspaceId + ? `/resources?pool=${encodeURIComponent(workspaceId)}` + : null; + + return ( +
+

{copy.title}

+

{copy.description}

+ {names.length > 0 && ( +
    + {names.map((name, index) => ( +
  • + {name} +
  • + ))} +
+ )} + {state.deploymentId && ( +

+ {copy.reference}: {state.deploymentId} +

+ )} +
+ {targetHref && ( + + )} + +
+
+ ); +} diff --git a/apps/dashboard/src/components/import-project/compose/ComposeDeploymentProcessing.tsx b/apps/dashboard/src/components/import-project/compose/ComposeDeploymentProcessing.tsx index cf4cc6d1c..ee5d48346 100644 --- a/apps/dashboard/src/components/import-project/compose/ComposeDeploymentProcessing.tsx +++ b/apps/dashboard/src/components/import-project/compose/ComposeDeploymentProcessing.tsx @@ -12,6 +12,7 @@ import { DeploymentHeader } from "../DeploymentHeader"; import { DeploymentHealthWarning } from "../DeploymentHealthWarning"; import { CloudBuildQueueNotice } from "../CloudBuildQueueNotice"; import { CloudDeploymentResourceNotice } from "../CloudDeploymentResourceNotice"; +import { DeploymentContainerConflictNotice } from "../DeploymentContainerConflictNotice"; import { DeploymentLayout } from "../DeploymentLayout"; import { DeploymentLogsPanel } from "../DeploymentLogsPanel"; import { PageContainer } from "@/components/ui/PageContainer"; @@ -576,7 +577,7 @@ function ComposeDeploymentBody({ return ( } + notice={<>} details={} navigation={
diff --git a/apps/dashboard/src/i18n/locales/ar/deployments.json b/apps/dashboard/src/i18n/locales/ar/deployments.json index a6067abae..98aa49310 100644 --- a/apps/dashboard/src/i18n/locales/ar/deployments.json +++ b/apps/dashboard/src/i18n/locales/ar/deployments.json @@ -202,6 +202,13 @@ "pageOf": "الصفحة {page} من {total}", "range": "عمليات النشر {from}–{to} من {total}" }, + "containerConflict": { + "title": "حل تعارض الحاويات المكررة", + "description": "افحص الحاويات ووحدات التخزين المتصلة بها على الخادم المستهدف. احتفظ بالحاوية المطلوبة وبياناتها، واحذف فقط نسخة مكررة تأكدت أنها غير مستخدمة، ثم أعد النشر. إذا لم تكن متأكدًا من الحاوية التي يجب الاحتفاظ بها، فتواصل مع الدعم وأرفق مرجع النشر هذا.", + "containers": "الحاويات المتطابقة", + "reviewServer": "مراجعة الخادم", + "reference": "مرجع النشر" + }, "resourceGuidance": { "label": "إرشادات موارد النشر", "reviewCapacity": "مراجعة السعة", diff --git a/apps/dashboard/src/i18n/locales/de/deployments.json b/apps/dashboard/src/i18n/locales/de/deployments.json index 2d40185de..5f868daed 100644 --- a/apps/dashboard/src/i18n/locales/de/deployments.json +++ b/apps/dashboard/src/i18n/locales/de/deployments.json @@ -202,6 +202,13 @@ "pageOf": "Seite {page} von {total}", "range": "Bereitstellungen {from}–{to} von {total}" }, + "containerConflict": { + "title": "Doppelte Container prüfen", + "description": "Prüfe die Container und ihre eingebundenen Datenträger auf dem Zielserver. Behalte den vorgesehenen Container und seine Daten. Entferne nur ein nachweislich ungenutztes Duplikat und stelle dann erneut bereit. Bei Unsicherheit kontaktiere den Support mit dieser Bereitstellungsreferenz.", + "containers": "Übereinstimmende Container", + "reviewServer": "Server prüfen", + "reference": "Bereitstellungsreferenz" + }, "resourceGuidance": { "label": "Ressourcenhinweise zur Bereitstellung", "reviewCapacity": "Kapazität prüfen", diff --git a/apps/dashboard/src/i18n/locales/en/deployments.json b/apps/dashboard/src/i18n/locales/en/deployments.json index a4af5e414..3478e9803 100644 --- a/apps/dashboard/src/i18n/locales/en/deployments.json +++ b/apps/dashboard/src/i18n/locales/en/deployments.json @@ -202,6 +202,13 @@ "confirm": "Roll back", "cancel": "Cancel" }, + "containerConflict": { + "title": "Resolve duplicate containers", + "description": "Inspect the containers and their mounts on the target server. Keep the intended container and its data, remove only a confirmed unused duplicate, then redeploy. If you are unsure which to keep, contact support with this deployment reference.", + "containers": "Matching containers", + "reviewServer": "Review server", + "reference": "Deployment reference" + }, "resourceGuidance": { "label": "Deployment resource guidance", "reviewCapacity": "Review capacity", diff --git a/apps/dashboard/src/i18n/locales/es/deployments.json b/apps/dashboard/src/i18n/locales/es/deployments.json index 2d367f0c3..894727750 100644 --- a/apps/dashboard/src/i18n/locales/es/deployments.json +++ b/apps/dashboard/src/i18n/locales/es/deployments.json @@ -202,6 +202,13 @@ "pageOf": "Página {page} de {total}", "range": "Despliegues {from}–{to} de {total}" }, + "containerConflict": { + "title": "Resolver contenedores duplicados", + "description": "Revisa los contenedores y sus volúmenes montados en el servidor de destino. Conserva el contenedor correcto y sus datos, elimina solo un duplicado que hayas confirmado que no se usa y vuelve a desplegar. Si tienes dudas sobre cuál conservar, contacta con soporte con esta referencia de despliegue.", + "containers": "Contenedores coincidentes", + "reviewServer": "Revisar servidor", + "reference": "Referencia del despliegue" + }, "resourceGuidance": { "label": "Orientación sobre recursos del despliegue", "reviewCapacity": "Revisar capacidad", diff --git a/apps/dashboard/src/i18n/locales/fr/deployments.json b/apps/dashboard/src/i18n/locales/fr/deployments.json index 8a44f466a..ecdbfb85b 100644 --- a/apps/dashboard/src/i18n/locales/fr/deployments.json +++ b/apps/dashboard/src/i18n/locales/fr/deployments.json @@ -202,6 +202,13 @@ "pageOf": "Page {page} sur {total}", "range": "Déploiements {from}–{to} sur {total}" }, + "containerConflict": { + "title": "Résoudre les conteneurs en double", + "description": "Inspectez les conteneurs et leurs volumes montés sur le serveur cible. Conservez le conteneur prévu et ses données, supprimez uniquement un doublon dont vous avez confirmé qu’il est inutilisé, puis redéployez. En cas de doute, contactez le support avec cette référence de déploiement.", + "containers": "Conteneurs correspondants", + "reviewServer": "Examiner le serveur", + "reference": "Référence du déploiement" + }, "resourceGuidance": { "label": "Conseils sur les ressources du déploiement", "reviewCapacity": "Examiner la capacité", diff --git a/apps/dashboard/src/i18n/locales/ja/deployments.json b/apps/dashboard/src/i18n/locales/ja/deployments.json index b60d86f1b..d6dfe0db0 100644 --- a/apps/dashboard/src/i18n/locales/ja/deployments.json +++ b/apps/dashboard/src/i18n/locales/ja/deployments.json @@ -202,6 +202,13 @@ "pageOf": "{page} / {total} ページ", "range": "全 {total} 件中 {from}–{to} 件" }, + "containerConflict": { + "title": "重複するコンテナを確認", + "description": "対象サーバーでコンテナとマウントを確認してください。使用するコンテナとそのデータを保持し、未使用と確認できた重複コンテナのみを削除してから再デプロイしてください。判断できない場合は、このデプロイ参照番号を添えてサポートにお問い合わせください。", + "containers": "一致するコンテナ", + "reviewServer": "サーバーを確認", + "reference": "デプロイ参照番号" + }, "resourceGuidance": { "label": "デプロイのリソースガイド", "reviewCapacity": "容量を確認", diff --git a/apps/dashboard/src/i18n/locales/pt/deployments.json b/apps/dashboard/src/i18n/locales/pt/deployments.json index 5b6e0dd7c..9f9fc3858 100644 --- a/apps/dashboard/src/i18n/locales/pt/deployments.json +++ b/apps/dashboard/src/i18n/locales/pt/deployments.json @@ -202,6 +202,13 @@ "pageOf": "Página {page} de {total}", "range": "Implantações {from}–{to} de {total}" }, + "containerConflict": { + "title": "Resolver contêineres duplicados", + "description": "Inspecione os contêineres e seus volumes montados no servidor de destino. Mantenha o contêiner correto e seus dados, remova apenas uma duplicata confirmada como não utilizada e implante novamente. Em caso de dúvida sobre qual manter, contate o suporte com esta referência da implantação.", + "containers": "Contêineres correspondentes", + "reviewServer": "Revisar servidor", + "reference": "Referência da implantação" + }, "resourceGuidance": { "label": "Orientações sobre recursos da implantação", "reviewCapacity": "Revisar capacidade", diff --git a/apps/dashboard/src/i18n/locales/ru/deployments.json b/apps/dashboard/src/i18n/locales/ru/deployments.json index de87897c9..fd49ec67d 100644 --- a/apps/dashboard/src/i18n/locales/ru/deployments.json +++ b/apps/dashboard/src/i18n/locales/ru/deployments.json @@ -202,6 +202,13 @@ "confirm": "Откатить", "cancel": "Отмена" }, + "containerConflict": { + "title": "Устраните дублирование контейнеров", + "description": "Проверьте контейнеры и их подключённые тома на целевом сервере. Сохраните нужный контейнер и его данные, удалите только подтверждённый неиспользуемый дубликат, затем повторите развёртывание. Если вы не уверены, какой контейнер сохранить, обратитесь в поддержку с этим идентификатором развёртывания.", + "containers": "Совпадающие контейнеры", + "reviewServer": "Проверить сервер", + "reference": "Идентификатор развёртывания" + }, "resourceGuidance": { "label": "Рекомендации по ресурсам развёртывания", "reviewCapacity": "Проверить ресурсы", diff --git a/apps/dashboard/src/i18n/locales/tr/deployments.json b/apps/dashboard/src/i18n/locales/tr/deployments.json index a079add8b..484a9dce8 100644 --- a/apps/dashboard/src/i18n/locales/tr/deployments.json +++ b/apps/dashboard/src/i18n/locales/tr/deployments.json @@ -202,6 +202,13 @@ "pageOf": "Sayfa {page} / {total}", "range": "{total} dağıtımdan {from}–{to}" }, + "containerConflict": { + "title": "Yinelenen kapsayıcıları çözün", + "description": "Hedef sunucudaki kapsayıcıları ve bağlı birimlerini inceleyin. Kullanılacak kapsayıcıyı ve verilerini koruyun, yalnızca kullanılmadığını doğruladığınız kopyayı kaldırın ve yeniden dağıtın. Hangisini koruyacağınızdan emin değilseniz bu dağıtım referansıyla destek ekibine ulaşın.", + "containers": "Eşleşen kapsayıcılar", + "reviewServer": "Sunucuyu incele", + "reference": "Dağıtım referansı" + }, "resourceGuidance": { "label": "Dağıtım kaynak rehberi", "reviewCapacity": "Kapasiteyi incele", diff --git a/apps/dashboard/src/i18n/locales/zh/deployments.json b/apps/dashboard/src/i18n/locales/zh/deployments.json index 925a48d96..b0816d8ab 100644 --- a/apps/dashboard/src/i18n/locales/zh/deployments.json +++ b/apps/dashboard/src/i18n/locales/zh/deployments.json @@ -202,6 +202,13 @@ "pageOf": "第 {page} 页,共 {total} 页", "range": "第 {from}–{to} 条部署,共 {total} 条" }, + "containerConflict": { + "title": "处理重复容器", + "description": "检查目标服务器上的容器及其挂载。保留预期使用的容器和数据,仅删除已确认不再使用的重复容器,然后重新部署。如果无法确定应保留哪一个,请提供此部署编号并联系支持。", + "containers": "匹配的容器", + "reviewServer": "查看服务器", + "reference": "部署编号" + }, "resourceGuidance": { "label": "部署资源指引", "reviewCapacity": "检查容量", diff --git a/packages/core/src/errors.ts b/packages/core/src/errors.ts index b9b9067ef..0974f072b 100644 --- a/packages/core/src/errors.ts +++ b/packages/core/src/errors.ts @@ -72,6 +72,7 @@ export class HostUnreachableError extends AppError { * Codes: * PORT_IN_USE - target port is occupied by another process * FOREIGN_COMPOSE_STACK - an unowned same-project Compose stack exists on the target + * SERVICE_CONTAINER_CONFLICT - more than one live container matches an active service */ export class DeployError extends AppError { constructor( diff --git a/packages/platform/src/engine/modules/deployments/build-pipeline.ts b/packages/platform/src/engine/modules/deployments/build-pipeline.ts index 7dd1d6746..2f2087d1b 100644 --- a/packages/platform/src/engine/modules/deployments/build-pipeline.ts +++ b/packages/platform/src/engine/modules/deployments/build-pipeline.ts @@ -34,6 +34,7 @@ import { recordRuntimeImageReceipts, runtimeImageTrackingRef } from "../../lib/r import { BUILD_ENV_VARS, AppError, + DeployError, safeErrorMessage, sanitizeProxySettings, normalizeServiceLabel, @@ -1757,9 +1758,17 @@ async function executeBuildAndDeploy( // outcome was recorded is bookkeeping: reporting it as a failure would // invert a working deploy and tear its containers down. const capacityError = cloudCapacityFailure(err, project.id, buildResourcesForRecovery, project.workspaceId); - await reportPipelineError(ctx, capacityError?.message ?? message, logger, capacityError - ? { errorCode: capacityError.code, errorDetails: capacityError.details } - : deploymentResourceFailure({ project, message, cause: err })); + await reportPipelineError( + ctx, capacityError?.message ?? message, logger, + capacityError + ? { errorCode: capacityError.code, errorDetails: capacityError.details } + : deploymentResourceFailure({ + project, message, cause: err, + meta: err instanceof DeployError + ? { errorCode: err.code, errorDetails: err.details } + : undefined, + }), + ); } finally { await finishBuildCancellation?.(); // The deploy is over either way — release the loopback bridges it opened. diff --git a/packages/platform/src/engine/modules/deployments/compose/deploy.service.ts b/packages/platform/src/engine/modules/deployments/compose/deploy.service.ts index 498647ce7..58c21d670 100644 --- a/packages/platform/src/engine/modules/deployments/compose/deploy.service.ts +++ b/packages/platform/src/engine/modules/deployments/compose/deploy.service.ts @@ -1421,8 +1421,18 @@ async function deployComposeServicesCore( continue; } if ((match?.duplicates.length ?? 0) > 0) { - throw new Error( - `Deployment preflight found more than one container matching active service "${row.serviceName ?? row.serviceId}" (${[liveSummary.names[0] ?? liveSummary.id.slice(0, 12), ...match!.duplicates].join(", ")}), so no service activation was started. Remove or reconcile the duplicate container before redeploying.`, + const containerNames = [liveSummary.names[0] ?? liveSummary.id.slice(0, 12), ...match!.duplicates]; + throw new DeployError( + `Deployment preflight found more than one container matching active service "${row.serviceName ?? row.serviceId}" (${containerNames.join(", ")}), so no service activation was started. Inspect the containers and their mounts on the target server. Keep the intended container and its data, remove only a confirmed unused duplicate, then redeploy. If ownership is unclear, contact support with deployment ${dep.id}.`, + "SERVICE_CONTAINER_CONFLICT", + { + projectId: project.id, + serviceId: row.serviceId, + serviceName: row.serviceName ?? row.serviceId, + containerNames, + serverId: opts?.serverId ?? null, + workspaceId: project.workspaceId ?? null, + }, ); }