feat(delivery): refine base service integrations

This commit is contained in:
mac
2026-07-29 16:47:41 +08:00
parent 2ca08f9360
commit 35875218c9
22 changed files with 1042 additions and 377 deletions
+152 -23
View File
@@ -176,7 +176,20 @@
<div class="form-grid resource-fields">
<label class="form-field" :class="{ 'is-invalid': dataDiskError }">
数据盘挂载点
<el-input v-model="deliveryForm.dataDisk" placeholder="/data" />
<el-autocomplete
v-model="deliveryForm.dataDisk"
:fetch-suggestions="queryMountPathSuggestions"
placeholder="/data"
:loading="mountPathsLoading"
clearable
>
<template #default="{ item }">
<div class="mount-path-option">
<span>{{ item.path }}</span>
<small>{{ mountPathMeta(item) }}</small>
</div>
</template>
</el-autocomplete>
<small v-if="dataDiskError" class="field-error">{{ dataDiskError }}</small>
<small v-else class="field-help">填写目标主机上的绝对挂载点,例如 /data 或 /data/ax;实例数据会写入其下的标准目录。</small>
</label>
@@ -415,10 +428,20 @@
<p>请立即复制或下载凭证文件;关闭后页面不再显示明文密码。</p>
<el-button v-if="!credentialRevealed" type="warning" :loading="credentialRevealing" @click="revealCredential">查看一次性密码</el-button>
<div v-else class="credential-secret">
<code>{{ revealedRootCredential?.password }}</code>
<div v-for="credential in revealedCredentials" :key="`${credential.username}@${credential.account_host || credential.host}`" class="credential-account">
<div class="credential-field">
<span>用户名</span>
<code>{{ formatCredentialUsername(credential) }}</code>
<el-button text :icon="CopyDocument" aria-label="复制用户名" title="复制用户名" @click="copyText(formatCredentialUsername(credential), '用户名已复制')" />
</div>
<div class="credential-field">
<span>密码</span>
<code>{{ credential.password }}</code>
<el-button text :icon="CopyDocument" aria-label="复制密码" title="复制密码" @click="copyText(credential.password, '密码已复制')" />
</div>
</div>
<div class="credential-actions">
<el-button :icon="CopyDocument" @click="copyText(revealedRootCredential?.password || '', 'root 密码已复制')">复制密码</el-button>
<el-button :icon="Download" @click="downloadCredentialFile">下载凭证文件</el-button>
<el-button :icon="Download" @click="downloadCredentialFile">下载 Excel 凭证</el-button>
<el-button type="success" plain :icon="CircleCheck" @click="dismissCredential">已保存,关闭</el-button>
</div>
</div>
@@ -495,7 +518,7 @@ import { computed, onBeforeUnmount, onMounted, reactive, ref, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowDown, Back, CircleCheck, Connection, CopyDocument, DocumentCopy, Download, Monitor, Promotion, Refresh, Setting, Tickets } from '@element-plus/icons-vue'
import { useRoute, useRouter } from 'vue-router'
import { deliveryApi, type DeliveryTarget, type DeploymentCredential, type TaskEvent } from '@/api/delivery'
import { deliveryApi, type DeliveryMountPath, type DeliveryTarget, type DeploymentCredential, type TaskEvent } from '@/api/delivery'
import { useAuthStore } from '@/stores/auth'
import { useBusinessLineStore } from '@/stores/businessLine'
import { useBusinessLineMockProfile } from '@/utils/businessLineMock'
@@ -780,6 +803,8 @@ const targetsLoading = ref(false)
const pollTimer = ref<number | undefined>()
const seenEventIds = ref(new Set<number>())
const deliveryLog = ref('[ready] 等待创建交付任务...')
const mountPathsLoading = ref(false)
let mountPathSuggestSeq = 0
const lastDeliveryStatus = ref('')
const deliveryRolledBack = computed(() => lastDeliveryStatus.value === 'rolled_back')
const deliveryAcknowledged = computed(() => lastDeliveryStatus.value === 'rollback_acknowledged')
@@ -1536,6 +1561,48 @@ function mysqlVersionValue(version: string) {
return matched.split('.').slice(0, 2).join('.')
}
function mountPathMeta(item: DeliveryMountPath) {
const parts = []
if (item.available_gi > 0) parts.push(`可用 ${item.available_gi}GiB`)
if (item.fstype) parts.push(item.fstype)
return parts.join(' · ')
}
function queryMountPathSuggestions(query: string, callback: (items: Array<DeliveryMountPath & { value: string }>) => void) {
const prefix = query.trim()
if (!prefix) {
callback(defaultMountPathOptions().map((item) => ({ ...item, value: item.path })))
return
}
const host = deliveryForm.targetHost || targetHosts.value[0]?.name || ''
if (!selectedTargetId.value || !host || !prefix.startsWith('/')) {
callback([])
return
}
const seq = ++mountPathSuggestSeq
mountPathsLoading.value = true
deliveryApi
.listTargetMountPaths(selectedTargetId.value, host, prefix)
.then((items) => {
if (seq !== mountPathSuggestSeq) return
callback(items.map((item) => ({ ...item, value: item.path })))
})
.catch(() => {
if (seq !== mountPathSuggestSeq) return
callback([])
})
.finally(() => {
if (seq === mountPathSuggestSeq) {
mountPathsLoading.value = false
}
})
}
function defaultMountPathOptions(): DeliveryMountPath[] {
return ['/data', '/disk1', '/mnt', '/opt/mysql-delivery'].map((path) => ({ path, available_gi: 0 }))
}
function normalizeDNSLabel(value: string) {
const normalized = value
.toLowerCase()
@@ -1552,7 +1619,6 @@ function generateRootPassword() {
'ABCDEFGHJKLMNPQRSTUVWXYZ',
'abcdefghijkmnopqrstuvwxyz',
'23456789',
'!@#$%^&*_-+=',
]
const alphabet = groups.join('')
const pick = (characters: string) => {
@@ -1576,8 +1642,9 @@ function generateRootPassword() {
function rootPasswordValidationError(value: string) {
if (!value) return '请输入 root 密码'
if (value.length < 16 || value.length > 64) return '密码长度必须为 16–64 位'
if (!/[A-Z]/.test(value) || !/[a-z]/.test(value) || !/[0-9]/.test(value) || !/[^A-Za-z0-9]/.test(value)) {
return '密码需同时包含大小写字母、数字和特殊字符'
if (!/^[A-Za-z0-9]+$/.test(value)) return '密码只能包含大小写字母和数字'
if (!/[A-Z]/.test(value) || !/[a-z]/.test(value) || !/[0-9]/.test(value)) {
return '密码需同时包含大小写字母和数字'
}
return ''
}
@@ -1606,7 +1673,15 @@ async function revealCredential() {
credentialRevealing.value = true
try {
if (deploymentId.value === 'PREVIEW-CREDENTIAL') {
revealedCredentials.value = [{ username: 'root', host: 'localhost', password: deliveryForm.rootPassword }]
revealedCredentials.value = [{
service: 'mysql',
instance_name: deliveryForm.instanceName,
host: deliveredHost.value || '10.24.18.21',
port: deliveredPort.value || 13306,
username: 'root',
account_host: 'localhost',
password: deliveryForm.rootPassword,
}]
} else {
revealedCredentials.value = await deliveryApi.revealCredentials(deploymentId.value)
}
@@ -1628,24 +1703,55 @@ function dismissCredential() {
revealedCredentials.value = []
}
function formatCredentialUsername(credential: DeploymentCredential) {
return credential.account_host ? `${credential.username}@${credential.account_host}` : credential.username
}
function escapeExcelCell(value: unknown) {
return String(value ?? '')
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#39;')
}
function downloadCredentialFile() {
const password = revealedRootCredential.value?.password
if (!credentialRevealed.value || !password) return
const content = [
'# XInfra MySQL delivery credential',
`instance=${deliveryForm.instanceName}`,
`host=${deliveredHost.value}`,
`port=${deliveredPort.value || ''}`,
'username=root',
`password=${password}`,
].join('\n') + '\n'
const url = URL.createObjectURL(new Blob([content], { type: 'text/plain;charset=utf-8' }))
if (!credentialRevealed.value || !revealedCredentials.value.length) return
const primary = revealedRootCredential.value || revealedCredentials.value[0]
const headers = ['服务', '实例名称', '主机', '端口', '用户名', '账号 Host', '密码']
const rows = revealedCredentials.value.map((credential) => [
credential.service || activeService.value?.key || 'mysql',
credential.instance_name || deliveryForm.instanceName,
credential.host || deliveredHost.value,
credential.port || deliveredPort.value || '',
credential.username,
credential.account_host || '',
credential.password,
])
const tableRows = [headers, ...rows]
.map((row) => `<tr>${row.map((cell) => `<td>${escapeExcelCell(cell)}</td>`).join('')}</tr>`)
.join('')
const content = `<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<style>
table { border-collapse: collapse; }
td { border: 1px solid #d9e2ef; padding: 8px; mso-number-format: "\\@"; }
</style>
</head>
<body>
<table>${tableRows}</table>
</body>
</html>`
const url = URL.createObjectURL(new Blob([content], { type: 'application/vnd.ms-excel;charset=utf-8' }))
const link = document.createElement('a')
link.href = url
link.download = `${deliveryForm.instanceName}-root-credential.txt`
link.download = `${primary.instance_name || deliveryForm.instanceName}-credential.xls`
link.click()
URL.revokeObjectURL(url)
ElMessage.success('凭证文件已下载,请妥善保管')
ElMessage.success('Excel 凭证已下载,请妥善保管')
}
function loadDeliveryHistory(): DeliveryHistoryItem[] {
@@ -2795,7 +2901,25 @@ h4 {
gap: 10px;
}
.credential-secret > code {
.credential-account {
display: grid;
gap: 8px;
}
.credential-field {
display: grid;
grid-template-columns: 64px minmax(0, 1fr) 32px;
align-items: center;
gap: 8px;
}
.credential-field > span {
color: var(--text-dim);
font-size: 11.5px;
font-weight: 700;
}
.credential-field > code {
overflow-wrap: anywhere;
padding: 9px 10px;
border: 1px solid var(--line-soft);
@@ -2805,6 +2929,11 @@ h4 {
font-size: 12px;
}
.credential-field .el-button {
width: 32px;
min-width: 32px;
}
.credential-actions {
display: flex;
flex-wrap: wrap;
+16 -9
View File
@@ -223,7 +223,7 @@
<p>凭证仅可领取一次,领取后服务端立即销毁明文。</p>
<el-button type="warning" :loading="credentialRevealing" @click="revealDeliveryCredential(selectedDeliveryTask)">领取一次性凭证</el-button>
</template>
<p v-else-if="consumedCredentialTasks.has(selectedDeliveryTask.id)">该任务的一次性凭证已领取或不可用,平台不再提供明文密码。</p>
<p v-else-if="['finished', 'register_failed'].includes(selectedDeliveryTask.status)">该任务的一次性凭证已领取或不可用,平台不再提供明文密码。</p>
<p v-else>仅交付成功的任务提供一次性凭证。</p>
</div>
</template>
@@ -266,7 +266,6 @@ const deliveryDetailVisible = ref(false)
const selectedDeliveryTask = ref<DeliveryTask>()
const revealedCredentials = ref<DeploymentCredential[]>([])
const credentialRevealing = ref(false)
const consumedCredentialTasks = ref<Set<string>>(new Set())
const containerServices = ref<ContainerWorkload[]>([])
const containerSummary = ref<ContainerServiceSummary>({ ...emptyContainerServiceSummary })
@@ -354,32 +353,40 @@ function deliveryTasksForService(serviceName: string) {
}
function credentialEligible(task: DeliveryTask) {
return ['finished', 'register_failed'].includes(task.status) && !consumedCredentialTasks.value.has(task.id)
return ['finished', 'register_failed'].includes(task.status) && Boolean(task.credential_available)
}
function credentialStatusText(task: DeliveryTask) {
if (consumedCredentialTasks.value.has(task.id)) return '已领取'
return credentialEligible(task) ? '可领取' : '不提供'
if (credentialEligible(task)) return '可领取'
if (['finished', 'register_failed'].includes(task.status)) return '已领取'
return '不提供'
}
function credentialStatusClass(task: DeliveryTask) {
if (consumedCredentialTasks.value.has(task.id)) return 'tag-green'
return credentialEligible(task) ? 'tag-amber' : ''
}
function markCredentialUnavailable(taskID: string) {
const task = deliveryRecords.value.find((item) => item.id === taskID)
if (task) task.credential_available = false
if (selectedDeliveryTask.value?.id === taskID) {
selectedDeliveryTask.value.credential_available = false
}
}
async function revealDeliveryCredential(task: DeliveryTask) {
credentialRevealing.value = true
try {
const items = await deliveryApi.revealCredentials(task.id)
if (items.length === 0) {
consumedCredentialTasks.value.add(task.id)
markCredentialUnavailable(task.id)
ElMessage.warning('该任务没有可领取的凭证')
return
}
revealedCredentials.value = items
consumedCredentialTasks.value.add(task.id)
markCredentialUnavailable(task.id)
} catch (error) {
consumedCredentialTasks.value.add(task.id)
markCredentialUnavailable(task.id)
ElMessage.error(error instanceof Error ? error.message : '凭证领取失败')
} finally {
credentialRevealing.value = false