feat: 打通 Jenkins 直构导入闭环
This commit is contained in:
@@ -52,6 +52,8 @@ describe('DeployExecutionService', () => {
|
||||
matchedBuildNumber?: number;
|
||||
buildResult?: 'SUCCESS' | 'FAILURE' | 'ABORTED' | 'UNSTABLE';
|
||||
buildRunning?: boolean;
|
||||
buildTimestamp?: string;
|
||||
buildDurationMs?: number;
|
||||
logText?: string;
|
||||
}) {
|
||||
const repository = createRepository();
|
||||
@@ -135,6 +137,8 @@ describe('DeployExecutionService', () => {
|
||||
building: options.buildRunning ?? false,
|
||||
result: options.buildResult,
|
||||
url: `https://jenkins.example/job/${buildNumber}/`,
|
||||
timestamp: options.buildTimestamp,
|
||||
durationMs: options.buildDurationMs,
|
||||
}),
|
||||
),
|
||||
getProgressiveText: jest.fn(() =>
|
||||
@@ -279,6 +283,8 @@ describe('DeployExecutionService', () => {
|
||||
queueId: 'queue_success',
|
||||
queueBuildNumber: 18,
|
||||
buildResult: 'SUCCESS',
|
||||
buildTimestamp: '2026-06-12T08:00:00.000Z',
|
||||
buildDurationMs: 90_000,
|
||||
});
|
||||
const run = await service.execute(
|
||||
await createRun(repository, 'run_success_001'),
|
||||
@@ -289,6 +295,7 @@ describe('DeployExecutionService', () => {
|
||||
|
||||
expect(result.status).toBe('success');
|
||||
expect(result.jenkinsBuildNumber).toBe(18);
|
||||
expect(result.finishedAt).toBe('2026-06-12T08:01:30.000Z');
|
||||
expect(step(result, 'jenkins-build')?.status).toBe('success');
|
||||
expect(step(result, 'health-check')?.status).toBe('success');
|
||||
expect(step(result, 'notify-wecom')?.status).toBe('success');
|
||||
|
||||
@@ -235,6 +235,8 @@ export class DeployExecutionService {
|
||||
currentRun,
|
||||
buildStatus.result,
|
||||
environment.jenkinsJobPath,
|
||||
undefined,
|
||||
this.jenkinsBuildFinishedAt(buildStatus),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -680,6 +682,7 @@ export class DeployExecutionService {
|
||||
|
||||
private async completeSuccessfulJenkinsRun(
|
||||
run: DeployRunSummary,
|
||||
finishedAt?: string,
|
||||
): Promise<DeployRunSummary> {
|
||||
let currentRun = await this.completeStep(run, 'jenkins-build', 'success');
|
||||
currentRun = await this.completeStep(currentRun, 'health-check', 'success');
|
||||
@@ -693,11 +696,12 @@ export class DeployExecutionService {
|
||||
currentRun.id,
|
||||
await this.deployRunRepository.updateRun(
|
||||
currentRun.id,
|
||||
{
|
||||
status: 'success',
|
||||
},
|
||||
currentRun.version,
|
||||
),
|
||||
{
|
||||
status: 'success',
|
||||
finishedAt,
|
||||
},
|
||||
currentRun.version,
|
||||
),
|
||||
);
|
||||
|
||||
await this.auditService.record({
|
||||
@@ -720,6 +724,7 @@ export class DeployExecutionService {
|
||||
result: Exclude<JenkinsTerminalResult, 'SUCCESS'>,
|
||||
jobPath: string,
|
||||
logText?: string,
|
||||
finishedAt?: string,
|
||||
): Promise<DeployRunSummary> {
|
||||
const logExcerpt = logText
|
||||
? this.toLogExcerpt(logText)
|
||||
@@ -743,6 +748,7 @@ export class DeployExecutionService {
|
||||
{
|
||||
status: 'failed',
|
||||
failureSummary,
|
||||
finishedAt,
|
||||
},
|
||||
currentRun.version,
|
||||
)) ?? currentRun;
|
||||
@@ -837,12 +843,25 @@ export class DeployExecutionService {
|
||||
result: JenkinsTerminalResult,
|
||||
jobPath: string,
|
||||
logText?: string,
|
||||
finishedAt?: string,
|
||||
): Promise<DeployRunSummary> {
|
||||
if (result === 'SUCCESS') {
|
||||
return this.completeSuccessfulJenkinsRun(run);
|
||||
return this.completeSuccessfulJenkinsRun(run, finishedAt);
|
||||
}
|
||||
|
||||
return this.failJenkinsRun(run, result, jobPath, logText);
|
||||
return this.failJenkinsRun(run, result, jobPath, logText, finishedAt);
|
||||
}
|
||||
|
||||
private jenkinsBuildFinishedAt(
|
||||
build: Pick<JenkinsBuildStatus, 'timestamp' | 'durationMs'>,
|
||||
): string | undefined {
|
||||
if (!build.timestamp || typeof build.durationMs !== 'number') {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return new Date(
|
||||
new Date(build.timestamp).getTime() + build.durationMs,
|
||||
).toISOString();
|
||||
}
|
||||
|
||||
private extractJenkinsFinishedResult(
|
||||
|
||||
@@ -104,6 +104,7 @@ const triggerToPrisma: Record<
|
||||
manual: PrismaDeployRunTrigger.MANUAL,
|
||||
gitea_webhook: PrismaDeployRunTrigger.GITEA_WEBHOOK,
|
||||
retry: PrismaDeployRunTrigger.RETRY,
|
||||
jenkins_external: PrismaDeployRunTrigger.JENKINS_EXTERNAL,
|
||||
};
|
||||
|
||||
@Injectable()
|
||||
@@ -151,6 +152,52 @@ export class DeployRunRepository {
|
||||
return run ? this.toSummary(run) : null;
|
||||
}
|
||||
|
||||
async findByJenkinsBuild(
|
||||
projectKey: string,
|
||||
environment: DeployRunSummary['environment'],
|
||||
buildNumber: number,
|
||||
): Promise<DeployRunSummary | null> {
|
||||
if (!this.useDatabase()) {
|
||||
return (
|
||||
this.memoryRuns.find(
|
||||
(run) =>
|
||||
run.projectKey === projectKey &&
|
||||
run.environment === environment &&
|
||||
run.jenkinsBuildNumber === buildNumber,
|
||||
) ?? null
|
||||
);
|
||||
}
|
||||
|
||||
const run = await this.prisma.deployRun.findFirst({
|
||||
where: {
|
||||
project: {
|
||||
key: projectKey,
|
||||
},
|
||||
environment: {
|
||||
name:
|
||||
environment === 'test'
|
||||
? EnvironmentKind.TEST
|
||||
: EnvironmentKind.PRODUCTION,
|
||||
},
|
||||
jenkinsBuildNumber: buildNumber,
|
||||
},
|
||||
include: {
|
||||
project: true,
|
||||
environment: true,
|
||||
steps: {
|
||||
orderBy: {
|
||||
order: 'asc',
|
||||
},
|
||||
},
|
||||
},
|
||||
orderBy: {
|
||||
createdAt: 'desc',
|
||||
},
|
||||
});
|
||||
|
||||
return run ? this.toSummary(run) : null;
|
||||
}
|
||||
|
||||
async create(input: CreateDeployRunInput): Promise<CreateDeployRunResult> {
|
||||
const idempotencyKey = this.resolveIdempotencyKey(input);
|
||||
|
||||
|
||||
@@ -28,7 +28,7 @@ export type DeployRunSummary = {
|
||||
environment: DeployEnvironment;
|
||||
ref: string;
|
||||
status: DeployRunStatus;
|
||||
trigger: 'manual' | 'gitea_webhook' | 'retry';
|
||||
trigger: 'manual' | 'gitea_webhook' | 'retry' | 'jenkins_external';
|
||||
operator: string;
|
||||
jenkinsQueueId?: string;
|
||||
jenkinsBuildNumber?: number;
|
||||
@@ -70,6 +70,30 @@ export type DeployRunJenkinsSyncSummary = {
|
||||
failedRuns: DeployRunJenkinsSyncError[];
|
||||
};
|
||||
|
||||
export type DeployRunJenkinsImportSkippedBuild = {
|
||||
projectKey: string;
|
||||
environment: DeployEnvironment;
|
||||
buildNumber: number;
|
||||
reason: 'already_imported' | 'linked_platform_run' | 'parameter_mismatch';
|
||||
};
|
||||
|
||||
export type DeployRunJenkinsImportFailedBuild = {
|
||||
projectKey: string;
|
||||
environment: DeployEnvironment;
|
||||
buildNumber?: number;
|
||||
message: string;
|
||||
};
|
||||
|
||||
export type DeployRunJenkinsImportSummary = {
|
||||
checkedAt: string;
|
||||
totalJobs: number;
|
||||
totalBuilds: number;
|
||||
importedRuns: DeployRunSummary[];
|
||||
syncedRuns: DeployRunSummary[];
|
||||
skippedBuilds: DeployRunJenkinsImportSkippedBuild[];
|
||||
failedBuilds: DeployRunJenkinsImportFailedBuild[];
|
||||
};
|
||||
|
||||
export type DeployRunJenkinsLog = {
|
||||
runId: string;
|
||||
jobPath: string;
|
||||
|
||||
@@ -26,6 +26,7 @@ import { CurrentUser } from '../auth/current-user.decorator';
|
||||
import { PasswordChangeGuard } from '../auth/password-change.guard';
|
||||
import { SuperAdminGuard } from '../auth/super-admin.guard';
|
||||
import {
|
||||
DeployRunJenkinsImportSummary,
|
||||
DeployRunJenkinsLog,
|
||||
DeployRunJenkinsSyncSummary,
|
||||
DeployRunSummary,
|
||||
@@ -110,6 +111,16 @@ export class DeployRunsController {
|
||||
return this.deployRunsService.syncJenkinsRuns(user);
|
||||
}
|
||||
|
||||
@Post('import-jenkins')
|
||||
@UseGuards(SuperAdminGuard)
|
||||
@AdminOnlyMessage('无权限导入 Jenkins 直构记录')
|
||||
@ApiOkResponse({ description: '扫描已纳管 Jenkins job 并导入平台外直构记录。' })
|
||||
async importJenkinsBuilds(
|
||||
@CurrentUser() user: AuthenticatedUser,
|
||||
): Promise<DeployRunJenkinsImportSummary> {
|
||||
return this.deployRunsService.importJenkinsBuilds(user);
|
||||
}
|
||||
|
||||
@Post(':id/sync-jenkins')
|
||||
@ApiOkResponse({ description: '同步单个发布单的 Jenkins 队列或构建状态。' })
|
||||
async syncJenkinsRun(
|
||||
|
||||
@@ -9,7 +9,6 @@ import { DeployExecutionService } from './deploy-execution.service';
|
||||
import { DeployRunRepository } from './deploy-run.repository';
|
||||
import {
|
||||
CreateDeployRunInput,
|
||||
DeployRunStatus,
|
||||
DeployRunSummary,
|
||||
} from './deploy-run.types';
|
||||
import { DeployRunsService } from './deploy-runs.service';
|
||||
@@ -60,47 +59,82 @@ describe('DeployRunsService', () => {
|
||||
findById: jest.fn((id: string) =>
|
||||
Promise.resolve(runs.find((run) => run.id === id) ?? null),
|
||||
),
|
||||
create: jest.fn((input: CreateDeployRunInput) =>
|
||||
Promise.resolve({
|
||||
run: {
|
||||
...baseRun,
|
||||
id: input.idempotencyKey ?? 'generated_run',
|
||||
projectKey: input.projectKey,
|
||||
environment: input.environment,
|
||||
ref: input.ref,
|
||||
operator: input.operator,
|
||||
trigger: input.trigger ?? 'manual',
|
||||
},
|
||||
findByJenkinsBuild: jest.fn(
|
||||
(
|
||||
projectKey: string,
|
||||
environment: DeployRunSummary['environment'],
|
||||
buildNumber: number,
|
||||
) =>
|
||||
Promise.resolve(
|
||||
runs.find(
|
||||
(run) =>
|
||||
run.projectKey === projectKey &&
|
||||
run.environment === environment &&
|
||||
run.jenkinsBuildNumber === buildNumber,
|
||||
) ?? null,
|
||||
),
|
||||
),
|
||||
create: jest.fn((input: CreateDeployRunInput) => {
|
||||
const run: DeployRunSummary = {
|
||||
...baseRun,
|
||||
id: input.idempotencyKey ?? 'generated_run',
|
||||
projectKey: input.projectKey,
|
||||
environment: input.environment,
|
||||
ref: input.ref,
|
||||
operator: input.operator,
|
||||
trigger: input.trigger ?? 'manual',
|
||||
};
|
||||
runs.unshift(run);
|
||||
|
||||
return Promise.resolve({
|
||||
run,
|
||||
created: true,
|
||||
}),
|
||||
),
|
||||
updateRun: jest.fn((id: string, patch: { status?: DeployRunStatus }) =>
|
||||
Promise.resolve(
|
||||
runs.some((run) => run.id === id)
|
||||
? {
|
||||
...(runs.find((run) => run.id === id) ?? baseRun),
|
||||
...patch,
|
||||
}
|
||||
: null,
|
||||
),
|
||||
),
|
||||
updateStep: jest.fn((id: string) =>
|
||||
Promise.resolve(
|
||||
runs.some((run) => run.id === id)
|
||||
? {
|
||||
...(runs.find((run) => run.id === id) ?? baseRun),
|
||||
status: 'canceled' as const,
|
||||
}
|
||||
: null,
|
||||
),
|
||||
),
|
||||
});
|
||||
}),
|
||||
updateRun: jest.fn((id: string, patch: Partial<DeployRunSummary>) => {
|
||||
const index = runs.findIndex((run) => run.id === id);
|
||||
|
||||
if (index === -1) {
|
||||
return Promise.resolve(null);
|
||||
}
|
||||
|
||||
const updated = {
|
||||
...runs[index],
|
||||
...patch,
|
||||
version: runs[index].version + 1,
|
||||
} satisfies DeployRunSummary;
|
||||
runs[index] = updated;
|
||||
|
||||
return Promise.resolve(updated);
|
||||
}),
|
||||
updateStep: jest.fn((id: string) => {
|
||||
const index = runs.findIndex((run) => run.id === id);
|
||||
|
||||
if (index === -1) {
|
||||
return Promise.resolve(null);
|
||||
}
|
||||
|
||||
const updated = {
|
||||
...runs[index],
|
||||
version: runs[index].version + 1,
|
||||
} satisfies DeployRunSummary;
|
||||
runs[index] = updated;
|
||||
|
||||
return Promise.resolve(updated);
|
||||
}),
|
||||
} satisfies Pick<
|
||||
DeployRunRepository,
|
||||
'findMany' | 'findById' | 'create' | 'updateRun' | 'updateStep'
|
||||
| 'findMany'
|
||||
| 'findById'
|
||||
| 'findByJenkinsBuild'
|
||||
| 'create'
|
||||
| 'updateRun'
|
||||
| 'updateStep'
|
||||
>;
|
||||
const projects = {
|
||||
getProject: jest.fn(() => Promise.resolve(resolvedProject)),
|
||||
} satisfies Pick<ProjectsService, 'getProject'>;
|
||||
listProjects: jest.fn(() => Promise.resolve([resolvedProject])),
|
||||
} satisfies Pick<ProjectsService, 'getProject' | 'listProjects'>;
|
||||
const audit = {
|
||||
record: jest.fn(),
|
||||
} satisfies Pick<AuditService, 'record'>;
|
||||
@@ -165,6 +199,11 @@ describe('DeployRunsService', () => {
|
||||
);
|
||||
},
|
||||
),
|
||||
listRecentBuilds: jest.fn(() =>
|
||||
Promise.resolve(
|
||||
[] as Awaited<ReturnType<JenkinsClient['listRecentBuilds']>>,
|
||||
),
|
||||
),
|
||||
getProgressiveText: jest.fn(() =>
|
||||
Promise.resolve({
|
||||
text: 'build log',
|
||||
@@ -179,6 +218,7 @@ describe('DeployRunsService', () => {
|
||||
| 'stopBuild'
|
||||
| 'findBuildByQueueId'
|
||||
| 'findLatestBuildByParameter'
|
||||
| 'listRecentBuilds'
|
||||
| 'getProgressiveText'
|
||||
>;
|
||||
const auth = {
|
||||
@@ -829,4 +869,143 @@ describe('DeployRunsService', () => {
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it('imports a direct Jenkins build and syncs it through the deploy state machine', async () => {
|
||||
const { audit, execution, jenkins, repository, service } = createService({
|
||||
runs: [],
|
||||
});
|
||||
jenkins.listRecentBuilds.mockResolvedValueOnce([
|
||||
{
|
||||
jobPath: 'my-project-dev/test-access-manage-develop',
|
||||
buildNumber: 33,
|
||||
queueId: 'queue_033',
|
||||
building: false,
|
||||
result: 'SUCCESS',
|
||||
url: 'https://jenkins.example/job/my-project-dev/job/test-access-manage-develop/33/',
|
||||
timestamp: '2026-06-12T06:20:00.000Z',
|
||||
parameters: {
|
||||
GIT_REF: 'feature/jenkins-direct',
|
||||
DEPLOY_ENVIRONMENT: 'test',
|
||||
BUILD_USER_ID: 'jenkins-user',
|
||||
},
|
||||
},
|
||||
]);
|
||||
|
||||
const result = await service.importJenkinsBuilds({
|
||||
id: 'user_admin',
|
||||
account: 'ops-admin',
|
||||
displayName: 'ops-admin',
|
||||
role: 'super_admin',
|
||||
status: 'active',
|
||||
mustChangePassword: false,
|
||||
passwordVersion: 1,
|
||||
});
|
||||
|
||||
expect(repository.create).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
projectKey: 'access-manage',
|
||||
environment: 'test',
|
||||
ref: 'feature/jenkins-direct',
|
||||
operator: 'jenkins-user',
|
||||
trigger: 'jenkins_external',
|
||||
idempotencyKey: 'jenkins-external:access-manage:test:33',
|
||||
}),
|
||||
);
|
||||
expect(repository.updateStep).toHaveBeenCalledWith(
|
||||
'jenkins-external:access-manage:test:33',
|
||||
'gitea-check',
|
||||
expect.objectContaining({
|
||||
status: 'skipped',
|
||||
}),
|
||||
expect.any(Number),
|
||||
);
|
||||
expect(repository.updateRun).toHaveBeenCalledWith(
|
||||
'jenkins-external:access-manage:test:33',
|
||||
expect.objectContaining({
|
||||
status: 'running',
|
||||
jenkinsQueueId: 'queue_033',
|
||||
jenkinsBuildNumber: 33,
|
||||
}),
|
||||
expect.any(Number),
|
||||
);
|
||||
expect(execution.syncJenkinsRun).toHaveBeenCalledTimes(1);
|
||||
expect(result.importedRuns).toHaveLength(1);
|
||||
expect(result.syncedRuns).toHaveLength(1);
|
||||
expect(result.failedBuilds).toHaveLength(0);
|
||||
expect(audit.record).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
action: 'JENKINS_EXTERNAL_BUILD_IMPORTED',
|
||||
parameterDigest: {
|
||||
parameterNames: ['BUILD_USER_ID', 'DEPLOY_ENVIRONMENT', 'GIT_REF'],
|
||||
},
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('skips an already represented Jenkins build and syncs the existing run', async () => {
|
||||
const runningRun: DeployRunSummary = {
|
||||
...baseRun,
|
||||
id: 'run_existing',
|
||||
status: 'running',
|
||||
jenkinsBuildNumber: 41,
|
||||
};
|
||||
const { execution, jenkins, repository, service } = createService({
|
||||
runs: [runningRun],
|
||||
});
|
||||
jenkins.listRecentBuilds.mockResolvedValueOnce([
|
||||
{
|
||||
jobPath: 'my-project-dev/test-access-manage-develop',
|
||||
buildNumber: 41,
|
||||
building: true,
|
||||
parameters: {
|
||||
GIT_REF: 'develop',
|
||||
},
|
||||
},
|
||||
]);
|
||||
|
||||
const result = await service.importJenkinsBuilds();
|
||||
|
||||
expect(repository.create).not.toHaveBeenCalled();
|
||||
expect(execution.syncJenkinsRun).toHaveBeenCalledWith(
|
||||
runningRun,
|
||||
expect.objectContaining({ key: 'access-manage' }),
|
||||
);
|
||||
expect(result.importedRuns).toHaveLength(0);
|
||||
expect(result.skippedBuilds).toEqual([
|
||||
{
|
||||
projectKey: 'access-manage',
|
||||
environment: 'test',
|
||||
buildNumber: 41,
|
||||
reason: 'already_imported',
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it('skips Jenkins builds whose platform parameters point to another environment', async () => {
|
||||
const { jenkins, repository, service } = createService();
|
||||
jenkins.listRecentBuilds.mockResolvedValueOnce([
|
||||
{
|
||||
jobPath: 'my-project-dev/test-access-manage-develop',
|
||||
buildNumber: 52,
|
||||
building: false,
|
||||
result: 'SUCCESS',
|
||||
parameters: {
|
||||
PROJECT_KEY: 'access-manage',
|
||||
DEPLOY_ENVIRONMENT: 'production',
|
||||
},
|
||||
},
|
||||
]);
|
||||
|
||||
const result = await service.importJenkinsBuilds();
|
||||
|
||||
expect(repository.create).not.toHaveBeenCalled();
|
||||
expect(result.skippedBuilds).toEqual([
|
||||
{
|
||||
projectKey: 'access-manage',
|
||||
environment: 'test',
|
||||
buildNumber: 52,
|
||||
reason: 'parameter_mismatch',
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -11,7 +11,10 @@ import {
|
||||
DeployNotificationEvent,
|
||||
DeployNotificationService,
|
||||
} from '../notifications/wecom/deploy-notification.service';
|
||||
import { JenkinsCancelResult } from '../integrations/jenkins/jenkins.types';
|
||||
import {
|
||||
JenkinsCancelResult,
|
||||
JenkinsRecentBuild,
|
||||
} from '../integrations/jenkins/jenkins.types';
|
||||
import { JenkinsClient } from '../integrations/jenkins/jenkins.client';
|
||||
import {
|
||||
ProjectEnvironmentSummary,
|
||||
@@ -22,6 +25,8 @@ import { DeployExecutionService } from './deploy-execution.service';
|
||||
import { DeployRunRepository } from './deploy-run.repository';
|
||||
import {
|
||||
CreateDeployRunInput,
|
||||
DeployEnvironment,
|
||||
DeployRunJenkinsImportSummary,
|
||||
DeployRunJenkinsLog,
|
||||
DeployRunJenkinsSyncSummary,
|
||||
DeployRunSummary,
|
||||
@@ -34,6 +39,22 @@ type ReadRunsOptions = {
|
||||
const jenkinsSyncConflictRetryCount = 2;
|
||||
const jenkinsLogBuildLinkMaxAttempts = 5;
|
||||
const jenkinsLogBuildLinkRetryDelayMs = 1000;
|
||||
const jenkinsExternalBuildScanLimit = 20;
|
||||
const jenkinsExternalOperator = 'jenkins-direct';
|
||||
const jenkinsExternalRefParameterNames = [
|
||||
'GIT_REF',
|
||||
'DEPLOY_REF',
|
||||
'BRANCH_NAME',
|
||||
'TAG_NAME',
|
||||
'REF',
|
||||
];
|
||||
const jenkinsExternalOperatorParameterNames = [
|
||||
'OPERATOR',
|
||||
'BUILD_USER_ID',
|
||||
'BUILD_USER',
|
||||
'BUILD_USER_EMAIL',
|
||||
'CAUSE_USER',
|
||||
];
|
||||
const escapeControl = String.fromCharCode(27);
|
||||
const jenkinsConsoleNotePattern = new RegExp(
|
||||
`${escapeControl}\\[8mha:/{4}[A-Za-z0-9+/=]+${escapeControl}\\[0m`,
|
||||
@@ -400,6 +421,131 @@ export class DeployRunsService {
|
||||
};
|
||||
}
|
||||
|
||||
async importJenkinsBuilds(
|
||||
user?: AuthenticatedUser,
|
||||
): Promise<DeployRunJenkinsImportSummary> {
|
||||
if (user) {
|
||||
this.authService.assertSuperAdmin(user, '无权限导入 Jenkins 直构记录');
|
||||
}
|
||||
|
||||
const projects = await this.projectsService.listProjects();
|
||||
const importedRuns: DeployRunSummary[] = [];
|
||||
const syncedRuns: DeployRunSummary[] = [];
|
||||
const skippedBuilds: DeployRunJenkinsImportSummary['skippedBuilds'] = [];
|
||||
const failedBuilds: DeployRunJenkinsImportSummary['failedBuilds'] = [];
|
||||
let totalJobs = 0;
|
||||
let totalBuilds = 0;
|
||||
|
||||
for (const project of projects) {
|
||||
for (const environment of project.environments) {
|
||||
if (!environment.jenkinsJobPath) {
|
||||
continue;
|
||||
}
|
||||
|
||||
totalJobs += 1;
|
||||
|
||||
let builds: JenkinsRecentBuild[];
|
||||
try {
|
||||
builds = await this.jenkinsClient.listRecentBuilds(
|
||||
environment.jenkinsJobPath,
|
||||
jenkinsExternalBuildScanLimit,
|
||||
);
|
||||
totalBuilds += builds.length;
|
||||
} catch (error) {
|
||||
failedBuilds.push({
|
||||
projectKey: project.key,
|
||||
environment: environment.name,
|
||||
message: this.toSafeSyncError(error),
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
for (const build of builds) {
|
||||
try {
|
||||
const mismatchReason = this.externalBuildParameterMismatch(
|
||||
project,
|
||||
environment,
|
||||
build,
|
||||
);
|
||||
|
||||
if (mismatchReason) {
|
||||
skippedBuilds.push({
|
||||
projectKey: project.key,
|
||||
environment: environment.name,
|
||||
buildNumber: build.buildNumber,
|
||||
reason: 'parameter_mismatch',
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
const existing = await this.findExistingJenkinsBuildRun(
|
||||
project,
|
||||
environment,
|
||||
build,
|
||||
);
|
||||
|
||||
if (existing) {
|
||||
skippedBuilds.push({
|
||||
projectKey: project.key,
|
||||
environment: environment.name,
|
||||
buildNumber: build.buildNumber,
|
||||
reason: existing.reason,
|
||||
});
|
||||
|
||||
const syncedRun = await this.syncLinkedJenkinsRun(
|
||||
existing.run,
|
||||
project,
|
||||
);
|
||||
syncedRuns.push(syncedRun);
|
||||
continue;
|
||||
}
|
||||
|
||||
let run = await this.createExternalJenkinsRun(
|
||||
project,
|
||||
environment,
|
||||
build,
|
||||
);
|
||||
importedRuns.push(run);
|
||||
|
||||
run = await this.syncJenkinsRunWithRetry(run, project);
|
||||
syncedRuns.push(run);
|
||||
} catch (error) {
|
||||
failedBuilds.push({
|
||||
projectKey: project.key,
|
||||
environment: environment.name,
|
||||
buildNumber: build.buildNumber,
|
||||
message: this.toSafeSyncError(error),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
await this.auditService.record({
|
||||
action: 'JENKINS_EXTERNAL_IMPORT_COMPLETED',
|
||||
resourceType: 'deploy_run',
|
||||
actorName: user?.account,
|
||||
after: {
|
||||
totalJobs,
|
||||
totalBuilds,
|
||||
importedCount: importedRuns.length,
|
||||
syncedCount: syncedRuns.length,
|
||||
skippedCount: skippedBuilds.length,
|
||||
failedCount: failedBuilds.length,
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
checkedAt: new Date().toISOString(),
|
||||
totalJobs,
|
||||
totalBuilds,
|
||||
importedRuns,
|
||||
syncedRuns,
|
||||
skippedBuilds,
|
||||
failedBuilds,
|
||||
};
|
||||
}
|
||||
|
||||
private async recordNotificationResult(
|
||||
run: DeployRunSummary,
|
||||
event: DeployNotificationEvent,
|
||||
@@ -428,6 +574,250 @@ export class DeployRunsService {
|
||||
);
|
||||
}
|
||||
|
||||
private externalBuildParameterMismatch(
|
||||
project: ProjectSummary,
|
||||
environment: ProjectEnvironmentSummary,
|
||||
build: JenkinsRecentBuild,
|
||||
): string | undefined {
|
||||
const parameterProject = this.trimOptional(
|
||||
build.parameters.PROJECT_KEY,
|
||||
);
|
||||
const parameterEnvironment = this.normalizeDeployEnvironment(
|
||||
build.parameters.DEPLOY_ENVIRONMENT,
|
||||
);
|
||||
|
||||
if (parameterProject && parameterProject !== project.key) {
|
||||
return `PROJECT_KEY=${parameterProject}`;
|
||||
}
|
||||
|
||||
if (parameterEnvironment && parameterEnvironment !== environment.name) {
|
||||
return `DEPLOY_ENVIRONMENT=${parameterEnvironment}`;
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
private async findExistingJenkinsBuildRun(
|
||||
project: ProjectSummary,
|
||||
environment: ProjectEnvironmentSummary,
|
||||
build: JenkinsRecentBuild,
|
||||
): Promise<
|
||||
| {
|
||||
run: DeployRunSummary;
|
||||
reason: 'already_imported' | 'linked_platform_run';
|
||||
}
|
||||
| undefined
|
||||
> {
|
||||
const deployRunId = this.trimOptional(build.parameters.DEPLOY_RUN_ID);
|
||||
|
||||
if (deployRunId) {
|
||||
const linkedRun = await this.deployRunRepository.findById(deployRunId);
|
||||
|
||||
if (linkedRun) {
|
||||
return {
|
||||
run: linkedRun,
|
||||
reason: 'linked_platform_run',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const existingRun = await this.deployRunRepository.findByJenkinsBuild(
|
||||
project.key,
|
||||
environment.name,
|
||||
build.buildNumber,
|
||||
);
|
||||
|
||||
if (!existingRun) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return {
|
||||
run: existingRun,
|
||||
reason: 'already_imported',
|
||||
};
|
||||
}
|
||||
|
||||
private async createExternalJenkinsRun(
|
||||
project: ProjectSummary,
|
||||
environment: ProjectEnvironmentSummary,
|
||||
build: JenkinsRecentBuild,
|
||||
): Promise<DeployRunSummary> {
|
||||
const inferredRef = this.inferExternalBuildRef(project, environment, build);
|
||||
const creation = await this.deployRunRepository.create({
|
||||
projectKey: project.key,
|
||||
environment: environment.name,
|
||||
ref: inferredRef.ref,
|
||||
operator: this.inferExternalBuildOperator(build),
|
||||
remark: `Jenkins 直构 #${build.buildNumber} 导入,ref 来源:${inferredRef.source}`,
|
||||
idempotencyKey: this.externalJenkinsIdempotencyKey(
|
||||
project.key,
|
||||
environment.name,
|
||||
build.buildNumber,
|
||||
),
|
||||
trigger: 'jenkins_external',
|
||||
});
|
||||
|
||||
let run = creation.run;
|
||||
|
||||
if (!creation.created) {
|
||||
return run;
|
||||
}
|
||||
|
||||
run = this.requireRun(
|
||||
run.id,
|
||||
await this.deployRunRepository.updateStep(
|
||||
run.id,
|
||||
'gitea-check',
|
||||
{
|
||||
status: 'skipped',
|
||||
message: 'Jenkins 直接构建导入,平台未执行 Gitea ref 校验。',
|
||||
},
|
||||
run.version,
|
||||
),
|
||||
);
|
||||
run = this.requireRun(
|
||||
run.id,
|
||||
await this.deployRunRepository.updateRun(
|
||||
run.id,
|
||||
{
|
||||
status: 'running',
|
||||
jenkinsQueueId: build.queueId,
|
||||
jenkinsBuildNumber: build.buildNumber,
|
||||
jenkinsBuildUrl: build.url,
|
||||
startedAt: build.timestamp,
|
||||
},
|
||||
run.version,
|
||||
),
|
||||
);
|
||||
run = this.requireRun(
|
||||
run.id,
|
||||
await this.deployRunRepository.updateStep(
|
||||
run.id,
|
||||
'jenkins-build',
|
||||
{
|
||||
status: 'running',
|
||||
message: build.result
|
||||
? `Jenkins 直构 #${build.buildNumber} 已完成,正在回收结果。`
|
||||
: `Jenkins 直构 #${build.buildNumber} 正在运行。`,
|
||||
},
|
||||
run.version,
|
||||
),
|
||||
);
|
||||
|
||||
await this.auditService.record({
|
||||
action: 'JENKINS_EXTERNAL_BUILD_IMPORTED',
|
||||
resourceType: 'deploy_run',
|
||||
resourceId: run.id,
|
||||
actorName: run.operator,
|
||||
after: {
|
||||
projectKey: project.key,
|
||||
environment: environment.name,
|
||||
jobPath: environment.jenkinsJobPath,
|
||||
buildNumber: build.buildNumber,
|
||||
buildUrl: build.url,
|
||||
queueId: build.queueId,
|
||||
ref: inferredRef.ref,
|
||||
refSource: inferredRef.source,
|
||||
},
|
||||
parameterDigest: {
|
||||
parameterNames: Object.keys(build.parameters).sort(),
|
||||
},
|
||||
});
|
||||
|
||||
return run;
|
||||
}
|
||||
|
||||
private async syncLinkedJenkinsRun(
|
||||
run: DeployRunSummary,
|
||||
project: ProjectSummary,
|
||||
): Promise<DeployRunSummary> {
|
||||
if (['success', 'failed', 'canceled'].includes(run.status)) {
|
||||
return run;
|
||||
}
|
||||
|
||||
return this.syncJenkinsRunWithRetry(run, project);
|
||||
}
|
||||
|
||||
private inferExternalBuildRef(
|
||||
project: ProjectSummary,
|
||||
environment: ProjectEnvironmentSummary,
|
||||
build: JenkinsRecentBuild,
|
||||
): { ref: string; source: string } {
|
||||
for (const parameterName of jenkinsExternalRefParameterNames) {
|
||||
const parameterValue = this.trimOptional(build.parameters[parameterName]);
|
||||
|
||||
if (parameterValue) {
|
||||
return {
|
||||
ref: parameterValue,
|
||||
source: parameterName,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
if (environment.releasePolicy === 'master') {
|
||||
return {
|
||||
ref: 'master',
|
||||
source: 'environment.releasePolicy',
|
||||
};
|
||||
}
|
||||
|
||||
const jobLeaf = environment.jenkinsJobPath.split('/').filter(Boolean).pop();
|
||||
|
||||
if (jobLeaf && jobLeaf.endsWith(`-${project.defaultBranch}`)) {
|
||||
return {
|
||||
ref: project.defaultBranch,
|
||||
source: 'jenkinsJobPath',
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
ref: project.defaultBranch,
|
||||
source: 'project.defaultBranch',
|
||||
};
|
||||
}
|
||||
|
||||
private inferExternalBuildOperator(build: JenkinsRecentBuild): string {
|
||||
for (const parameterName of jenkinsExternalOperatorParameterNames) {
|
||||
const parameterValue = this.trimOptional(build.parameters[parameterName]);
|
||||
|
||||
if (parameterValue) {
|
||||
return parameterValue;
|
||||
}
|
||||
}
|
||||
|
||||
return jenkinsExternalOperator;
|
||||
}
|
||||
|
||||
private externalJenkinsIdempotencyKey(
|
||||
projectKey: string,
|
||||
environment: DeployEnvironment,
|
||||
buildNumber: number,
|
||||
): string {
|
||||
return `jenkins-external:${projectKey}:${environment}:${buildNumber}`;
|
||||
}
|
||||
|
||||
private normalizeDeployEnvironment(
|
||||
value: string | undefined,
|
||||
): DeployEnvironment | undefined {
|
||||
const normalized = this.trimOptional(value)?.toLowerCase();
|
||||
|
||||
if (normalized === 'test' || normalized === 'testing') {
|
||||
return 'test';
|
||||
}
|
||||
|
||||
if (normalized === 'production' || normalized === 'prod') {
|
||||
return 'production';
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
private trimOptional(value: string | undefined): string | undefined {
|
||||
const trimmed = value?.trim();
|
||||
|
||||
return trimmed ? trimmed : undefined;
|
||||
}
|
||||
|
||||
private async syncJenkinsCandidatesForRead(
|
||||
runs: DeployRunSummary[],
|
||||
): Promise<DeployRunSummary[]> {
|
||||
|
||||
Reference in New Issue
Block a user