feat: database management — custom credentials, dump upload/restore
Backend: - Add dbUsername/dbPassword columns to Application entity - Add optional DB credential fields to CreateApplicationDto - Auto-generate dbPassword (crypto.randomBytes) and default dbUsername='appuser' when databaseType != 'none' on app creation - Store both username and password in K8s DB secret (was password-only) - Read DB_USER/POSTGRES_USER/MYSQL_USER from secretKeyRef instead of hardcoded - New restoreDatabaseDump() in KubernetesService: creates K8s Job with psql/mysql client to restore uploaded SQL dump, waits for completion, returns logs - New POST /applications/:id/db-upload endpoint with 500MB file limit Frontend: - Add dbUsername/dbPassword to Application and CreateApplicationDto types - Deploy page: show username/password fields when database is selected, with generate-random-password button and show/hide toggle - App detail page: new Database section with connection info (host, port, db name, username, password with copy-to-clipboard), SQL dump upload area with drag-and-drop, and restore output logs display Security: - Database remains ClusterIP only (no external exposure) - Credentials stored in K8s Secrets (base64-encoded) - Dump file uploaded as temporary K8s Secret, auto-cleaned after restore
This commit is contained in:
@@ -14,6 +14,7 @@ import {
|
|||||||
Logger,
|
Logger,
|
||||||
Inject,
|
Inject,
|
||||||
forwardRef,
|
forwardRef,
|
||||||
|
BadRequestException,
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
import { AuthGuard } from '@nestjs/passport';
|
import { AuthGuard } from '@nestjs/passport';
|
||||||
import { FileInterceptor } from '@nestjs/platform-express';
|
import { FileInterceptor } from '@nestjs/platform-express';
|
||||||
@@ -22,7 +23,7 @@ import { ApplicationsService } from './applications.service';
|
|||||||
import { CreateApplicationDto, UpdateApplicationDto, ScaleResourcesDto } from './dto/application.dto';
|
import { CreateApplicationDto, UpdateApplicationDto, ScaleResourcesDto } from './dto/application.dto';
|
||||||
import { RolesGuard } from '../common/guards/roles.guard';
|
import { RolesGuard } from '../common/guards/roles.guard';
|
||||||
import { Roles } from '../common/decorators/roles.decorator';
|
import { Roles } from '../common/decorators/roles.decorator';
|
||||||
import { UserRole } from '../common/enums';
|
import { UserRole, DatabaseType } from '../common/enums';
|
||||||
import { KubernetesService } from '../kubernetes/kubernetes.service';
|
import { KubernetesService } from '../kubernetes/kubernetes.service';
|
||||||
import { DeploymentsService } from '../deployments/deployments.service';
|
import { DeploymentsService } from '../deployments/deployments.service';
|
||||||
|
|
||||||
@@ -60,6 +61,38 @@ export class ApplicationsController {
|
|||||||
return this.applicationsService.uploadCode(id, req.user.id, file);
|
return this.applicationsService.uploadCode(id, req.user.id, file);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Post(':id/db-upload')
|
||||||
|
@ApiOperation({ summary: 'Upload and restore a SQL dump into the application database' })
|
||||||
|
@ApiConsumes('multipart/form-data')
|
||||||
|
@UseInterceptors(FileInterceptor('file', {
|
||||||
|
limits: { fileSize: 500 * 1024 * 1024 }, // 500MB for DB dumps
|
||||||
|
}))
|
||||||
|
async uploadDbDump(
|
||||||
|
@Param('id') id: string,
|
||||||
|
@Request() req: any,
|
||||||
|
@UploadedFile() file: Express.Multer.File,
|
||||||
|
) {
|
||||||
|
if (!file) {
|
||||||
|
throw new BadRequestException('No file uploaded');
|
||||||
|
}
|
||||||
|
|
||||||
|
const isStaff = req.user.role === UserRole.ADMIN || req.user.role === UserRole.TECHNICAL;
|
||||||
|
const app = await this.applicationsService.findOne(id, isStaff ? undefined : req.user.id);
|
||||||
|
|
||||||
|
if (app.databaseType === DatabaseType.NONE) {
|
||||||
|
throw new BadRequestException('This application does not have a database configured');
|
||||||
|
}
|
||||||
|
|
||||||
|
this.logger.log(`DB dump upload for ${app.name} — ${(file.size / 1024).toFixed(1)} KB`);
|
||||||
|
const result = await this.kubernetesService.restoreDatabaseDump(app, file.buffer);
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: result.success,
|
||||||
|
message: result.success ? 'Database restored successfully' : 'Database restore failed',
|
||||||
|
logs: result.logs,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
@Get()
|
@Get()
|
||||||
@ApiOperation({ summary: 'List my applications' })
|
@ApiOperation({ summary: 'List my applications' })
|
||||||
async findAll(@Request() req: any) {
|
async findAll(@Request() req: any) {
|
||||||
|
|||||||
@@ -4,10 +4,11 @@ import { Repository } from 'typeorm';
|
|||||||
import { ConfigService } from '@nestjs/config';
|
import { ConfigService } from '@nestjs/config';
|
||||||
import * as fs from 'fs';
|
import * as fs from 'fs';
|
||||||
import * as path from 'path';
|
import * as path from 'path';
|
||||||
|
import * as crypto from 'crypto';
|
||||||
import { Application } from './entities/application.entity';
|
import { Application } from './entities/application.entity';
|
||||||
import { CreateApplicationDto, UpdateApplicationDto } from './dto/application.dto';
|
import { CreateApplicationDto, UpdateApplicationDto } from './dto/application.dto';
|
||||||
import { ClustersService } from '../clusters/clusters.service';
|
import { ClustersService } from '../clusters/clusters.service';
|
||||||
import { UserRole } from '../common/enums';
|
import { UserRole, DatabaseType } from '../common/enums';
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class ApplicationsService {
|
export class ApplicationsService {
|
||||||
@@ -66,11 +67,22 @@ export class ApplicationsService {
|
|||||||
this.logger.log(`Manual cluster assignment for app "${dto.name}" → cluster ${clusterId}`);
|
this.logger.log(`Manual cluster assignment for app "${dto.name}" → cluster ${clusterId}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Generate database credentials if a database is requested
|
||||||
|
let dbUsername: string | undefined;
|
||||||
|
let dbPassword: string | undefined;
|
||||||
|
if (dto.databaseType && dto.databaseType !== DatabaseType.NONE) {
|
||||||
|
dbUsername = dto.dbUsername?.trim() || 'appuser';
|
||||||
|
dbPassword = dto.dbPassword?.trim() || crypto.randomBytes(16).toString('hex');
|
||||||
|
this.logger.log(`Generated DB credentials for app "${dto.name}" — user: ${dbUsername}`);
|
||||||
|
}
|
||||||
|
|
||||||
const app = this.appsRepository.create({
|
const app = this.appsRepository.create({
|
||||||
...dto,
|
...dto,
|
||||||
userId,
|
userId,
|
||||||
clusterId,
|
clusterId,
|
||||||
poolId,
|
poolId,
|
||||||
|
dbUsername,
|
||||||
|
dbPassword,
|
||||||
subdomain: `${dto.name}-${userId.split('-')[0]}`,
|
subdomain: `${dto.name}-${userId.split('-')[0]}`,
|
||||||
});
|
});
|
||||||
return this.appsRepository.save(app);
|
return this.appsRepository.save(app);
|
||||||
|
|||||||
@@ -32,6 +32,16 @@ export class CreateApplicationDto {
|
|||||||
@IsEnum(DatabaseType)
|
@IsEnum(DatabaseType)
|
||||||
databaseType: DatabaseType;
|
databaseType: DatabaseType;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({ example: 'appuser', description: 'Database username (default: appuser)' })
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
dbUsername?: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({ example: 'mySecurePass123', description: 'Database password (auto-generated if empty)' })
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
dbPassword?: string;
|
||||||
|
|
||||||
@ApiPropertyOptional({ example: 'https://github.com/user/repo.git' })
|
@ApiPropertyOptional({ example: 'https://github.com/user/repo.git' })
|
||||||
@IsOptional()
|
@IsOptional()
|
||||||
@IsString()
|
@IsString()
|
||||||
|
|||||||
@@ -29,6 +29,12 @@ export class Application {
|
|||||||
@Column({ type: 'enum', enum: DatabaseType, default: DatabaseType.NONE })
|
@Column({ type: 'enum', enum: DatabaseType, default: DatabaseType.NONE })
|
||||||
databaseType: DatabaseType;
|
databaseType: DatabaseType;
|
||||||
|
|
||||||
|
@Column({ nullable: true })
|
||||||
|
dbUsername: string;
|
||||||
|
|
||||||
|
@Column({ nullable: true })
|
||||||
|
dbPassword: string;
|
||||||
|
|
||||||
@Column({ nullable: true })
|
@Column({ nullable: true })
|
||||||
gitUrl: string;
|
gitUrl: string;
|
||||||
|
|
||||||
|
|||||||
@@ -23,6 +23,8 @@ interface ManifestContext {
|
|||||||
databaseType: DatabaseType;
|
databaseType: DatabaseType;
|
||||||
domain: string;
|
domain: string;
|
||||||
subdomain: string;
|
subdomain: string;
|
||||||
|
dbUsername: string;
|
||||||
|
dbPassword: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
@@ -93,6 +95,8 @@ export class KubernetesService implements OnModuleInit {
|
|||||||
databaseType: app.databaseType,
|
databaseType: app.databaseType,
|
||||||
domain: domain,
|
domain: domain,
|
||||||
subdomain: app.subdomain || app.name,
|
subdomain: app.subdomain || app.name,
|
||||||
|
dbUsername: app.dbUsername || 'appuser',
|
||||||
|
dbPassword: app.dbPassword || this.generatePassword(),
|
||||||
};
|
};
|
||||||
|
|
||||||
const manifests: Record<string, any> = {};
|
const manifests: Record<string, any> = {};
|
||||||
@@ -177,7 +181,7 @@ export class KubernetesService implements OnModuleInit {
|
|||||||
{ name: 'DB_HOST', value: `${ctx.appName}-db` },
|
{ name: 'DB_HOST', value: `${ctx.appName}-db` },
|
||||||
{ name: 'DB_PORT', value: '5432' },
|
{ name: 'DB_PORT', value: '5432' },
|
||||||
{ name: 'DB_NAME', value: ctx.appName.replace(/-/g, '_') },
|
{ name: 'DB_NAME', value: ctx.appName.replace(/-/g, '_') },
|
||||||
{ name: 'DB_USER', value: 'appuser' },
|
{ name: 'DB_USER', valueFrom: { secretKeyRef: { name: `${ctx.appName}-db-secret`, key: 'username' } } },
|
||||||
{ name: 'DB_PASSWORD', valueFrom: { secretKeyRef: { name: `${ctx.appName}-db-secret`, key: 'password' } } },
|
{ name: 'DB_PASSWORD', valueFrom: { secretKeyRef: { name: `${ctx.appName}-db-secret`, key: 'password' } } },
|
||||||
);
|
);
|
||||||
} else if (ctx.databaseType === DatabaseType.MYSQL) {
|
} else if (ctx.databaseType === DatabaseType.MYSQL) {
|
||||||
@@ -185,7 +189,7 @@ export class KubernetesService implements OnModuleInit {
|
|||||||
{ name: 'DB_HOST', value: `${ctx.appName}-db` },
|
{ name: 'DB_HOST', value: `${ctx.appName}-db` },
|
||||||
{ name: 'DB_PORT', value: '3306' },
|
{ name: 'DB_PORT', value: '3306' },
|
||||||
{ name: 'DB_NAME', value: ctx.appName.replace(/-/g, '_') },
|
{ name: 'DB_NAME', value: ctx.appName.replace(/-/g, '_') },
|
||||||
{ name: 'DB_USER', value: 'appuser' },
|
{ name: 'DB_USER', valueFrom: { secretKeyRef: { name: `${ctx.appName}-db-secret`, key: 'username' } } },
|
||||||
{ name: 'DB_PASSWORD', valueFrom: { secretKeyRef: { name: `${ctx.appName}-db-secret`, key: 'password' } } },
|
{ name: 'DB_PASSWORD', valueFrom: { secretKeyRef: { name: `${ctx.appName}-db-secret`, key: 'password' } } },
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -318,11 +322,10 @@ export class KubernetesService implements OnModuleInit {
|
|||||||
appsApi: k8s.AppsV1Api,
|
appsApi: k8s.AppsV1Api,
|
||||||
ctx: ManifestContext,
|
ctx: ManifestContext,
|
||||||
): Promise<any> {
|
): Promise<any> {
|
||||||
const dbPassword = this.generatePassword();
|
|
||||||
const dbName = `${ctx.appName}-db`;
|
const dbName = `${ctx.appName}-db`;
|
||||||
|
|
||||||
// Create DB secret
|
// Create DB secret with username + password from app entity
|
||||||
await this.createDbSecret(coreApi, ctx.namespace, ctx.appName, dbPassword);
|
await this.createDbSecret(coreApi, ctx.namespace, ctx.appName, ctx.dbPassword, ctx.dbUsername);
|
||||||
|
|
||||||
// Create PVC for DB
|
// Create PVC for DB
|
||||||
await this.createPVC(coreApi, ctx.namespace, dbName, '5Gi');
|
await this.createPVC(coreApi, ctx.namespace, dbName, '5Gi');
|
||||||
@@ -334,12 +337,12 @@ export class KubernetesService implements OnModuleInit {
|
|||||||
const envVars = isPostgres
|
const envVars = isPostgres
|
||||||
? [
|
? [
|
||||||
{ name: 'POSTGRES_DB', value: ctx.appName.replace(/-/g, '_') },
|
{ name: 'POSTGRES_DB', value: ctx.appName.replace(/-/g, '_') },
|
||||||
{ name: 'POSTGRES_USER', value: 'appuser' },
|
{ name: 'POSTGRES_USER', valueFrom: { secretKeyRef: { name: `${ctx.appName}-db-secret`, key: 'username' } } },
|
||||||
{ name: 'POSTGRES_PASSWORD', valueFrom: { secretKeyRef: { name: `${ctx.appName}-db-secret`, key: 'password' } } },
|
{ name: 'POSTGRES_PASSWORD', valueFrom: { secretKeyRef: { name: `${ctx.appName}-db-secret`, key: 'password' } } },
|
||||||
]
|
]
|
||||||
: [
|
: [
|
||||||
{ name: 'MYSQL_DATABASE', value: ctx.appName.replace(/-/g, '_') },
|
{ name: 'MYSQL_DATABASE', value: ctx.appName.replace(/-/g, '_') },
|
||||||
{ name: 'MYSQL_USER', value: 'appuser' },
|
{ name: 'MYSQL_USER', valueFrom: { secretKeyRef: { name: `${ctx.appName}-db-secret`, key: 'username' } } },
|
||||||
{ name: 'MYSQL_PASSWORD', valueFrom: { secretKeyRef: { name: `${ctx.appName}-db-secret`, key: 'password' } } },
|
{ name: 'MYSQL_PASSWORD', valueFrom: { secretKeyRef: { name: `${ctx.appName}-db-secret`, key: 'password' } } },
|
||||||
{ name: 'MYSQL_ROOT_PASSWORD', valueFrom: { secretKeyRef: { name: `${ctx.appName}-db-secret`, key: 'password' } } },
|
{ name: 'MYSQL_ROOT_PASSWORD', valueFrom: { secretKeyRef: { name: `${ctx.appName}-db-secret`, key: 'password' } } },
|
||||||
];
|
];
|
||||||
@@ -407,12 +410,16 @@ export class KubernetesService implements OnModuleInit {
|
|||||||
namespace: string,
|
namespace: string,
|
||||||
appName: string,
|
appName: string,
|
||||||
password: string,
|
password: string,
|
||||||
|
username: string = 'appuser',
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
const secret = {
|
const secret = {
|
||||||
apiVersion: 'v1',
|
apiVersion: 'v1',
|
||||||
kind: 'Secret',
|
kind: 'Secret',
|
||||||
metadata: { name: `${appName}-db-secret`, namespace },
|
metadata: { name: `${appName}-db-secret`, namespace },
|
||||||
data: { password: Buffer.from(password).toString('base64') },
|
data: {
|
||||||
|
username: Buffer.from(username).toString('base64'),
|
||||||
|
password: Buffer.from(password).toString('base64'),
|
||||||
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
try {
|
try {
|
||||||
@@ -787,6 +794,165 @@ export class KubernetesService implements OnModuleInit {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Restore a SQL dump file into the application's database.
|
||||||
|
* Creates a K8s Job that runs psql/mysql to import the dump.
|
||||||
|
*/
|
||||||
|
async restoreDatabaseDump(app: Application, fileBuffer: Buffer): Promise<{ success: boolean; logs: string }> {
|
||||||
|
const { coreApi, kc } = await this.getK8sClient(app.clusterId);
|
||||||
|
const batchApi = kc.makeApiClient(k8s.BatchV1Api);
|
||||||
|
const namespace = `user-${app.userId.split('-')[0]}`;
|
||||||
|
const dbName = `${app.name}-db`;
|
||||||
|
const jobName = `${app.name}-db-restore-${Date.now()}`;
|
||||||
|
const secretName = `${jobName}-dump`;
|
||||||
|
const isPostgres = app.databaseType === DatabaseType.POSTGRESQL;
|
||||||
|
const dbDatabase = app.name.replace(/-/g, '_');
|
||||||
|
|
||||||
|
// 1. Create a temporary secret holding the dump file
|
||||||
|
const dumpSecret = {
|
||||||
|
apiVersion: 'v1',
|
||||||
|
kind: 'Secret',
|
||||||
|
metadata: { name: secretName, namespace },
|
||||||
|
data: {
|
||||||
|
'dump.sql': fileBuffer.toString('base64'),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
try {
|
||||||
|
await coreApi.createNamespacedSecret(namespace, dumpSecret);
|
||||||
|
} catch (e: any) {
|
||||||
|
this.logger.error(`Failed to create dump secret: ${e.message}`);
|
||||||
|
throw new Error('Failed to prepare database dump for restore');
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Build the restore command
|
||||||
|
const command = isPostgres
|
||||||
|
? [
|
||||||
|
'sh', '-c',
|
||||||
|
`PGPASSWORD="$DB_PASSWORD" psql -h ${dbName} -U "$DB_USER" -d ${dbDatabase} -f /dump/dump.sql 2>&1`,
|
||||||
|
]
|
||||||
|
: [
|
||||||
|
'sh', '-c',
|
||||||
|
`mysql -h ${dbName} -u "$DB_USER" -p"$DB_PASSWORD" ${dbDatabase} < /dump/dump.sql 2>&1`,
|
||||||
|
];
|
||||||
|
|
||||||
|
const image = isPostgres ? 'postgres:16-alpine' : 'mysql:8.0';
|
||||||
|
|
||||||
|
// 3. Create the restore Job
|
||||||
|
const job: k8s.V1Job = {
|
||||||
|
apiVersion: 'batch/v1',
|
||||||
|
kind: 'Job',
|
||||||
|
metadata: { name: jobName, namespace },
|
||||||
|
spec: {
|
||||||
|
ttlSecondsAfterFinished: 300,
|
||||||
|
backoffLimit: 0,
|
||||||
|
template: {
|
||||||
|
spec: {
|
||||||
|
restartPolicy: 'Never',
|
||||||
|
containers: [
|
||||||
|
{
|
||||||
|
name: 'restore',
|
||||||
|
image,
|
||||||
|
command,
|
||||||
|
env: [
|
||||||
|
{ name: 'DB_USER', valueFrom: { secretKeyRef: { name: `${app.name}-db-secret`, key: 'username' } } },
|
||||||
|
{ name: 'DB_PASSWORD', valueFrom: { secretKeyRef: { name: `${app.name}-db-secret`, key: 'password' } } },
|
||||||
|
],
|
||||||
|
volumeMounts: [
|
||||||
|
{ name: 'dump-volume', mountPath: '/dump', readOnly: true },
|
||||||
|
],
|
||||||
|
resources: {
|
||||||
|
requests: { cpu: '100m', memory: '128Mi' },
|
||||||
|
limits: { cpu: '500m', memory: '512Mi' },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
volumes: [
|
||||||
|
{
|
||||||
|
name: 'dump-volume',
|
||||||
|
secret: { secretName },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
try {
|
||||||
|
await batchApi.createNamespacedJob(namespace, job);
|
||||||
|
this.logger.log(`Created DB restore job ${jobName} for ${app.name}`);
|
||||||
|
} catch (e: any) {
|
||||||
|
// Clean up the dump secret on failure
|
||||||
|
try { await coreApi.deleteNamespacedSecret(secretName, namespace); } catch {}
|
||||||
|
this.logger.error(`Failed to create restore job: ${e.message}`);
|
||||||
|
throw new Error('Failed to create database restore job');
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. Wait for the job to complete (max 5 minutes)
|
||||||
|
const timeout = 300_000;
|
||||||
|
const start = Date.now();
|
||||||
|
let completed = false;
|
||||||
|
let failed = false;
|
||||||
|
|
||||||
|
while (Date.now() - start < timeout) {
|
||||||
|
await new Promise((r) => setTimeout(r, 3000));
|
||||||
|
try {
|
||||||
|
const jobStatus = await batchApi.readNamespacedJob(jobName, namespace);
|
||||||
|
const status = jobStatus.body.status;
|
||||||
|
if (status?.succeeded && status.succeeded > 0) {
|
||||||
|
completed = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if (status?.failed && status.failed > 0) {
|
||||||
|
failed = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// Job may not be ready yet
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 5. Get logs from the job pod
|
||||||
|
let logs = '';
|
||||||
|
try {
|
||||||
|
const pods = await coreApi.listNamespacedPod(
|
||||||
|
namespace,
|
||||||
|
undefined,
|
||||||
|
undefined,
|
||||||
|
undefined,
|
||||||
|
undefined,
|
||||||
|
`job-name=${jobName}`,
|
||||||
|
);
|
||||||
|
if (pods.body.items.length > 0) {
|
||||||
|
const podName = pods.body.items[0].metadata?.name;
|
||||||
|
if (podName) {
|
||||||
|
const logResponse = await coreApi.readNamespacedPodLog(podName, namespace);
|
||||||
|
logs = logResponse.body || '';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e: any) {
|
||||||
|
this.logger.warn(`Could not get restore job logs: ${e.message}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 6. Clean up the dump secret
|
||||||
|
try {
|
||||||
|
await coreApi.deleteNamespacedSecret(secretName, namespace);
|
||||||
|
} catch {}
|
||||||
|
|
||||||
|
if (!completed && !failed) {
|
||||||
|
this.logger.warn(`DB restore job ${jobName} timed out`);
|
||||||
|
return { success: false, logs: logs || 'Restore job timed out after 5 minutes' };
|
||||||
|
}
|
||||||
|
|
||||||
|
if (failed) {
|
||||||
|
this.logger.warn(`DB restore job ${jobName} failed`);
|
||||||
|
return { success: false, logs: logs || 'Restore job failed' };
|
||||||
|
}
|
||||||
|
|
||||||
|
this.logger.log(`DB restore for ${app.name} completed successfully`);
|
||||||
|
return { success: true, logs };
|
||||||
|
}
|
||||||
|
|
||||||
private generatePassword(length = 24): string {
|
private generatePassword(length = 24): string {
|
||||||
const chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%';
|
const chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%';
|
||||||
let password = '';
|
let password = '';
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ import api from '@/lib/api';
|
|||||||
import { toast } from 'react-toastify';
|
import { toast } from 'react-toastify';
|
||||||
import type { Application, Deployment, ResourceUsage, ClusterPublic, ClusterPoolPublic } from '@/types';
|
import type { Application, Deployment, ResourceUsage, ClusterPublic, ClusterPoolPublic } from '@/types';
|
||||||
import { useState, useRef, useCallback, useEffect } from 'react';
|
import { useState, useRef, useCallback, useEffect } from 'react';
|
||||||
import { Hexagon, Rocket, Play, Square, RotateCw, Globe, Package, Server, Scale, CheckCircle, Clock, XCircle, AlertCircle, Link, GitBranch, KeyRound, FolderUp, BarChart3, ChevronDown, FileText, Monitor, Hammer, Settings, RefreshCw, Upload, Circle, Pin } from 'lucide-react';
|
import { Hexagon, Rocket, Play, Square, RotateCw, Globe, Package, Server, Scale, CheckCircle, Clock, XCircle, AlertCircle, Link, GitBranch, KeyRound, FolderUp, BarChart3, ChevronDown, FileText, Monitor, Hammer, Settings, RefreshCw, Upload, Circle, Pin, Database, Eye, EyeOff, Copy, Check } from 'lucide-react';
|
||||||
|
|
||||||
const statusColors: Record<string, string> = {
|
const statusColors: Record<string, string> = {
|
||||||
running: 'badge-green',
|
running: 'badge-green',
|
||||||
@@ -54,6 +54,11 @@ export default function AppDetailPage() {
|
|||||||
const [uploadProgress, setUploadProgress] = useState(0);
|
const [uploadProgress, setUploadProgress] = useState(0);
|
||||||
const [isDragging, setIsDragging] = useState(false);
|
const [isDragging, setIsDragging] = useState(false);
|
||||||
const [showResources, setShowResources] = useState(false);
|
const [showResources, setShowResources] = useState(false);
|
||||||
|
const [showDbPassword, setShowDbPassword] = useState(false);
|
||||||
|
const [copiedField, setCopiedField] = useState<string | null>(null);
|
||||||
|
const [dbRestoreLogs, setDbRestoreLogs] = useState<string | null>(null);
|
||||||
|
const dbFileInputRef = useRef<HTMLInputElement>(null);
|
||||||
|
const [isDraggingDb, setIsDraggingDb] = useState(false);
|
||||||
const [resourceForm, setResourceForm] = useState({
|
const [resourceForm, setResourceForm] = useState({
|
||||||
cpuRequest: '',
|
cpuRequest: '',
|
||||||
cpuLimit: '',
|
cpuLimit: '',
|
||||||
@@ -227,6 +232,29 @@ export default function AppDetailPage() {
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const dbUploadMutation = useMutation({
|
||||||
|
mutationFn: (file: File) => {
|
||||||
|
const formData = new FormData();
|
||||||
|
formData.append('file', file);
|
||||||
|
return api.post(`/applications/${appId}/db-upload`, formData, {
|
||||||
|
headers: { 'Content-Type': 'multipart/form-data' },
|
||||||
|
});
|
||||||
|
},
|
||||||
|
onSuccess: (res) => {
|
||||||
|
const data = res.data;
|
||||||
|
setDbRestoreLogs(data.logs || null);
|
||||||
|
if (data.success) {
|
||||||
|
toast.success('Database restored successfully!');
|
||||||
|
} else {
|
||||||
|
toast.error(data.message || 'Database restore failed');
|
||||||
|
}
|
||||||
|
},
|
||||||
|
onError: (err: any) => {
|
||||||
|
toast.error(err.response?.data?.message || 'Failed to upload database dump');
|
||||||
|
setDbRestoreLogs(null);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
const handleFileUpload = useCallback((file: File) => {
|
const handleFileUpload = useCallback((file: File) => {
|
||||||
if (!file.name.endsWith('.zip') && !file.name.endsWith('.tar.gz') && !file.name.endsWith('.tgz')) {
|
if (!file.name.endsWith('.zip') && !file.name.endsWith('.tar.gz') && !file.name.endsWith('.tgz')) {
|
||||||
toast.error('Please upload a .zip or .tar.gz file');
|
toast.error('Please upload a .zip or .tar.gz file');
|
||||||
@@ -255,6 +283,41 @@ export default function AppDetailPage() {
|
|||||||
setIsDragging(false);
|
setIsDragging(false);
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
|
const handleDbFileUpload = useCallback((file: File) => {
|
||||||
|
if (!file.name.endsWith('.sql') && !file.name.endsWith('.gz') && !file.name.endsWith('.dump')) {
|
||||||
|
toast.error('Please upload a .sql, .dump, or .gz file');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (file.size > 500 * 1024 * 1024) {
|
||||||
|
toast.error('File size must be less than 500MB');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setDbRestoreLogs(null);
|
||||||
|
dbUploadMutation.mutate(file);
|
||||||
|
}, [dbUploadMutation]);
|
||||||
|
|
||||||
|
const handleDbDrop = useCallback((e: React.DragEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
setIsDraggingDb(false);
|
||||||
|
const file = e.dataTransfer.files[0];
|
||||||
|
if (file) handleDbFileUpload(file);
|
||||||
|
}, [handleDbFileUpload]);
|
||||||
|
|
||||||
|
const handleDbDragOver = useCallback((e: React.DragEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
setIsDraggingDb(true);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const handleDbDragLeave = useCallback(() => {
|
||||||
|
setIsDraggingDb(false);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const copyToClipboard = useCallback((text: string, field: string) => {
|
||||||
|
navigator.clipboard.writeText(text);
|
||||||
|
setCopiedField(field);
|
||||||
|
setTimeout(() => setCopiedField(null), 2000);
|
||||||
|
}, []);
|
||||||
|
|
||||||
if (isLoading || !app) {
|
if (isLoading || !app) {
|
||||||
return (
|
return (
|
||||||
<div className="space-y-6 animate-fade-in">
|
<div className="space-y-6 animate-fade-in">
|
||||||
@@ -537,6 +600,122 @@ export default function AppDetailPage() {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* Database Info & Dump Upload */}
|
||||||
|
{app.databaseType !== 'none' && (
|
||||||
|
<div className="card">
|
||||||
|
<h2 className="text-lg font-semibold text-gray-900 mb-4 flex items-center gap-2">
|
||||||
|
<Database className="w-5 h-5" /> Database
|
||||||
|
<span className="badge badge-blue text-xs">{app.databaseType}</span>
|
||||||
|
</h2>
|
||||||
|
|
||||||
|
{/* Connection Info */}
|
||||||
|
<div className="bg-gray-50 rounded-xl p-4 mb-4 space-y-2">
|
||||||
|
<h3 className="text-sm font-semibold text-gray-700 mb-3">Connection Info (Internal Cluster)</h3>
|
||||||
|
{[
|
||||||
|
{ label: 'Host', value: `${app.name}-db`, field: 'host' },
|
||||||
|
{ label: 'Port', value: app.databaseType === 'postgresql' ? '5432' : '3306', field: 'port' },
|
||||||
|
{ label: 'Database', value: app.name.replace(/-/g, '_'), field: 'database' },
|
||||||
|
{ label: 'Username', value: app.dbUsername || 'appuser', field: 'username' },
|
||||||
|
].map(({ label, value, field }) => (
|
||||||
|
<div key={field} className="flex items-center justify-between">
|
||||||
|
<span className="text-sm text-gray-500">{label}</span>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<span className="text-sm font-mono text-gray-800">{value}</span>
|
||||||
|
<button
|
||||||
|
onClick={() => copyToClipboard(value, field)}
|
||||||
|
className="p-1 text-gray-400 hover:text-gray-600 transition-colors"
|
||||||
|
title="Copy"
|
||||||
|
>
|
||||||
|
{copiedField === field ? <Check className="w-3.5 h-3.5 text-green-500" /> : <Copy className="w-3.5 h-3.5" />}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
{/* Password row with show/hide */}
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<span className="text-sm text-gray-500">Password</span>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<span className="text-sm font-mono text-gray-800">
|
||||||
|
{showDbPassword ? (app.dbPassword || '—') : '••••••••••••'}
|
||||||
|
</span>
|
||||||
|
<button
|
||||||
|
onClick={() => setShowDbPassword(!showDbPassword)}
|
||||||
|
className="p-1 text-gray-400 hover:text-gray-600 transition-colors"
|
||||||
|
title={showDbPassword ? 'Hide' : 'Show'}
|
||||||
|
>
|
||||||
|
{showDbPassword ? <EyeOff className="w-3.5 h-3.5" /> : <Eye className="w-3.5 h-3.5" />}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => copyToClipboard(app.dbPassword || '', 'password')}
|
||||||
|
className="p-1 text-gray-400 hover:text-gray-600 transition-colors"
|
||||||
|
title="Copy"
|
||||||
|
>
|
||||||
|
{copiedField === 'password' ? <Check className="w-3.5 h-3.5 text-green-500" /> : <Copy className="w-3.5 h-3.5" />}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<p className="text-xs text-gray-400 mt-2 pt-2 border-t border-gray-200">
|
||||||
|
Database is only accessible within the cluster. Not exposed externally.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* DB Dump Upload */}
|
||||||
|
<h3 className="text-sm font-semibold text-gray-700 mb-3">Restore Database Dump</h3>
|
||||||
|
<div
|
||||||
|
onDrop={handleDbDrop}
|
||||||
|
onDragOver={handleDbDragOver}
|
||||||
|
onDragLeave={handleDbDragLeave}
|
||||||
|
onClick={() => dbFileInputRef.current?.click()}
|
||||||
|
className={`border-2 border-dashed rounded-xl p-6 text-center cursor-pointer transition-all
|
||||||
|
${isDraggingDb
|
||||||
|
? 'border-blue-500 bg-blue-50'
|
||||||
|
: 'border-gray-300 hover:border-blue-400 hover:bg-gray-50'
|
||||||
|
}
|
||||||
|
${dbUploadMutation.isPending ? 'pointer-events-none opacity-60' : ''}
|
||||||
|
`}
|
||||||
|
>
|
||||||
|
<input
|
||||||
|
ref={dbFileInputRef}
|
||||||
|
type="file"
|
||||||
|
accept=".sql,.gz,.dump"
|
||||||
|
className="hidden"
|
||||||
|
onChange={(e) => {
|
||||||
|
const file = e.target.files?.[0];
|
||||||
|
if (file) handleDbFileUpload(file);
|
||||||
|
e.target.value = '';
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{dbUploadMutation.isPending ? (
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Database className="w-8 h-8 mx-auto text-blue-400 animate-pulse" />
|
||||||
|
<p className="text-sm font-medium text-gray-700">Restoring database...</p>
|
||||||
|
<p className="text-xs text-gray-500">This may take a few minutes</p>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Database className="w-8 h-8 mx-auto text-gray-400" />
|
||||||
|
<p className="text-sm font-medium text-gray-700">Upload SQL dump to restore</p>
|
||||||
|
<p className="text-xs text-gray-500">
|
||||||
|
Drag & drop a <strong>.sql</strong> file here, or click to browse
|
||||||
|
</p>
|
||||||
|
<p className="text-xs text-gray-400">Max size: 500MB</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Restore Logs */}
|
||||||
|
{dbRestoreLogs && (
|
||||||
|
<div className="mt-4">
|
||||||
|
<h4 className="text-xs font-semibold text-gray-600 mb-2">Restore Output</h4>
|
||||||
|
<pre className="bg-gray-900 text-green-400 p-4 rounded-xl text-xs font-mono overflow-x-auto max-h-[300px] overflow-y-auto whitespace-pre-wrap break-words">
|
||||||
|
{dbRestoreLogs}
|
||||||
|
</pre>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
{/* Resource Monitoring & Scaling */}
|
{/* Resource Monitoring & Scaling */}
|
||||||
<div className="card">
|
<div className="card">
|
||||||
<div className="flex items-center justify-between mb-4">
|
<div className="flex items-center justify-between mb-4">
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ import api from '@/lib/api';
|
|||||||
import { useAuthStore } from '@/lib/store';
|
import { useAuthStore } from '@/lib/store';
|
||||||
import { toast } from 'react-toastify';
|
import { toast } from 'react-toastify';
|
||||||
import type { CreateApplicationDto, ClusterPublic, ClusterPoolPublic } from '@/types';
|
import type { CreateApplicationDto, ClusterPublic, ClusterPoolPublic } from '@/types';
|
||||||
import { Hexagon, FolderUp, Link as LinkIcon, CheckCircle, Package, Server, Scale, Home, Target, BarChart3, RotateCw, KeyRound, Rocket, Clock, Upload, XCircle } from 'lucide-react';
|
import { Hexagon, FolderUp, Link as LinkIcon, CheckCircle, Package, Server, Scale, Home, Target, BarChart3, RotateCw, KeyRound, Rocket, Clock, Upload, XCircle, Database, Eye, EyeOff, RefreshCw } from 'lucide-react';
|
||||||
|
|
||||||
const steps = ['Basic Info', 'Runtime & Database', 'Resources', 'Review'];
|
const steps = ['Basic Info', 'Runtime & Database', 'Resources', 'Review'];
|
||||||
|
|
||||||
@@ -39,6 +39,7 @@ export default function DeployPage() {
|
|||||||
const [uploadProgress, setUploadProgress] = useState(0);
|
const [uploadProgress, setUploadProgress] = useState(0);
|
||||||
const [isDragging, setIsDragging] = useState(false);
|
const [isDragging, setIsDragging] = useState(false);
|
||||||
const [clusterMode, setClusterMode] = useState<'default' | 'manual' | 'pool'>('default');
|
const [clusterMode, setClusterMode] = useState<'default' | 'manual' | 'pool'>('default');
|
||||||
|
const [showDbPassword, setShowDbPassword] = useState(false);
|
||||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||||
|
|
||||||
const { data: clusters = [] } = useQuery<ClusterPublic[]>({
|
const { data: clusters = [] } = useQuery<ClusterPublic[]>({
|
||||||
@@ -389,6 +390,66 @@ export default function DeployPage() {
|
|||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* Database Credentials — shown when a DB is selected */}
|
||||||
|
{form.databaseType !== 'none' && (
|
||||||
|
<div className="p-4 bg-blue-50/50 border border-blue-200 rounded-xl space-y-4">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<Database className="w-5 h-5 text-blue-500" />
|
||||||
|
<h3 className="text-sm font-semibold text-gray-800">Database Credentials</h3>
|
||||||
|
<span className="text-xs text-gray-400">(optional — auto-generated if empty)</span>
|
||||||
|
</div>
|
||||||
|
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
||||||
|
<div>
|
||||||
|
<label className="block text-xs text-gray-500 mb-1">Username</label>
|
||||||
|
<input
|
||||||
|
className="input-field"
|
||||||
|
placeholder="appuser"
|
||||||
|
value={form.dbUsername || ''}
|
||||||
|
onChange={(e) => setForm({ ...form, dbUsername: e.target.value })}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="block text-xs text-gray-500 mb-1">Password</label>
|
||||||
|
<div className="relative">
|
||||||
|
<input
|
||||||
|
className="input-field pr-20"
|
||||||
|
type={showDbPassword ? 'text' : 'password'}
|
||||||
|
placeholder="Auto-generated"
|
||||||
|
value={form.dbPassword || ''}
|
||||||
|
onChange={(e) => setForm({ ...form, dbPassword: e.target.value })}
|
||||||
|
/>
|
||||||
|
<div className="absolute inset-y-0 right-0 flex items-center gap-1 pr-2">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => {
|
||||||
|
const chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
|
||||||
|
let pass = '';
|
||||||
|
for (let i = 0; i < 20; i++) pass += chars.charAt(Math.floor(Math.random() * chars.length));
|
||||||
|
setForm({ ...form, dbPassword: pass });
|
||||||
|
setShowDbPassword(true);
|
||||||
|
}}
|
||||||
|
className="p-1 text-gray-400 hover:text-blue-500 transition-colors"
|
||||||
|
title="Generate random password"
|
||||||
|
>
|
||||||
|
<RefreshCw className="w-4 h-4" />
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setShowDbPassword(!showDbPassword)}
|
||||||
|
className="p-1 text-gray-400 hover:text-gray-600 transition-colors"
|
||||||
|
>
|
||||||
|
{showDbPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<p className="text-xs text-gray-400">
|
||||||
|
These credentials are used for internal cluster communication only. The database is not exposed externally.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
@@ -682,6 +743,18 @@ export default function DeployPage() {
|
|||||||
<span className="text-sm text-gray-500">Database</span>
|
<span className="text-sm text-gray-500">Database</span>
|
||||||
<span className="text-sm font-medium">{form.databaseType}</span>
|
<span className="text-sm font-medium">{form.databaseType}</span>
|
||||||
</div>
|
</div>
|
||||||
|
{form.databaseType !== 'none' && (
|
||||||
|
<>
|
||||||
|
<div className="flex justify-between">
|
||||||
|
<span className="text-sm text-gray-500">DB Username</span>
|
||||||
|
<span className="text-sm font-medium">{form.dbUsername || 'appuser (default)'}</span>
|
||||||
|
</div>
|
||||||
|
<div className="flex justify-between">
|
||||||
|
<span className="text-sm text-gray-500">DB Password</span>
|
||||||
|
<span className="text-sm font-medium">{form.dbPassword ? '••••••••' : 'Auto-generated'}</span>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
<div className="flex justify-between">
|
<div className="flex justify-between">
|
||||||
<span className="text-sm text-gray-500">Source</span>
|
<span className="text-sm text-gray-500">Source</span>
|
||||||
<span className="text-sm font-medium">
|
<span className="text-sm font-medium">
|
||||||
|
|||||||
@@ -15,6 +15,8 @@ export interface Application {
|
|||||||
description?: string;
|
description?: string;
|
||||||
runtime: 'nodejs' | 'laravel';
|
runtime: 'nodejs' | 'laravel';
|
||||||
databaseType: 'mysql' | 'postgresql' | 'none';
|
databaseType: 'mysql' | 'postgresql' | 'none';
|
||||||
|
dbUsername?: string;
|
||||||
|
dbPassword?: string;
|
||||||
gitUrl?: string;
|
gitUrl?: string;
|
||||||
gitToken?: string;
|
gitToken?: string;
|
||||||
gitBranch?: string;
|
gitBranch?: string;
|
||||||
@@ -87,6 +89,8 @@ export interface CreateApplicationDto {
|
|||||||
description?: string;
|
description?: string;
|
||||||
runtime: 'nodejs' | 'laravel';
|
runtime: 'nodejs' | 'laravel';
|
||||||
databaseType: 'mysql' | 'postgresql' | 'none';
|
databaseType: 'mysql' | 'postgresql' | 'none';
|
||||||
|
dbUsername?: string;
|
||||||
|
dbPassword?: string;
|
||||||
gitUrl?: string;
|
gitUrl?: string;
|
||||||
gitToken?: string;
|
gitToken?: string;
|
||||||
gitBranch?: string;
|
gitBranch?: string;
|
||||||
|
|||||||
File diff suppressed because one or more lines are too long
Reference in New Issue
Block a user