feat: multi-cluster management with pool-based load balancing

- Add ClusterPool entity for grouping clusters into named pools
- Support 3 deployment modes: manual cluster, pool load-balanced, default fallback
- Pool strategies: least-apps (fewest deployed apps) and round-robin
- Add pool CRUD API endpoints (admin) and public pool listing
- Frontend deploy page: 3-mode cluster selector (Default/Manual/Pool)
- Frontend app detail: shows assigned cluster and pool info
- Admin pools management page with cluster selection and strategy picker
- Application entity extended with poolId field
This commit is contained in:
keyhan
2026-04-05 17:37:05 +03:30
parent 1b1ccfc18f
commit 2621dc0cc6
14 changed files with 976 additions and 14 deletions
@@ -20,22 +20,46 @@ export class ApplicationsService {
) {}
async create(userId: string, dto: CreateApplicationDto): Promise<Application> {
// Auto-assign default cluster if not specified
// Cluster assignment: 3 modes
// 1. Manual: specific clusterId provided
// 2. Pool-based LB: poolId provided → pick from pool using pool's strategy
// 3. Default fallback: no clusterId/poolId → use default cluster
let clusterId = dto.clusterId;
let poolId = dto.poolId;
if (!clusterId) {
try {
const defaultCluster = await this.clustersService.getDefault();
clusterId = defaultCluster.id;
this.logger.log(`Auto-assigned default cluster "${defaultCluster.name}" to app "${dto.name}"`);
} catch {
this.logger.warn('No default cluster found — app will be created without cluster assignment');
if (poolId) {
// Mode 2: Pool-based load balancing
try {
const optimal = await this.clustersService.getOptimalClusterFromPool(poolId);
clusterId = optimal.id;
this.logger.log(`Pool-assigned cluster "${optimal.name}" to app "${dto.name}" (pool LB)`);
} catch (err: any) {
this.logger.warn(`Pool assignment failed for app "${dto.name}": ${err.message}`);
poolId = undefined; // Clear invalid pool
}
}
// Mode 3: Default fallback (no manual cluster, no pool, or pool failed)
if (!clusterId) {
try {
const defaultCluster = await this.clustersService.getDefault();
clusterId = defaultCluster.id;
this.logger.log(`Default-assigned cluster "${defaultCluster.name}" to app "${dto.name}"`);
} catch {
this.logger.warn('No cluster available — app will be created without cluster assignment');
}
}
} else {
this.logger.log(`Manual cluster assignment for app "${dto.name}" → cluster ${clusterId}`);
}
const app = this.appsRepository.create({
...dto,
userId,
clusterId,
poolId,
subdomain: `${dto.name}-${userId.split('-')[0]}`,
});
return this.appsRepository.save(app);
@@ -88,6 +88,11 @@ export class CreateApplicationDto {
@IsOptional()
@IsString()
clusterId?: string;
@ApiPropertyOptional({ description: 'Cluster pool ID for load-balanced deployment' })
@IsOptional()
@IsString()
poolId?: string;
}
export class UpdateApplicationDto {
@@ -74,6 +74,9 @@ export class Application {
@Column({ nullable: true })
clusterId: string;
@Column({ nullable: true })
poolId: string; // Cluster pool used for load-balanced assignment
@OneToMany(() => Deployment, (deployment: Deployment) => deployment.application)
deployments: Deployment[];
+61 -1
View File
@@ -12,6 +12,7 @@ import { AuthGuard } from '@nestjs/passport';
import { ApiTags, ApiOperation, ApiBearerAuth } from '@nestjs/swagger';
import { ClustersService } from './clusters.service';
import { CreateClusterDto, UpdateClusterDto } from './dto/cluster.dto';
import { CreateClusterPoolDto, UpdateClusterPoolDto } from './dto/cluster-pool.dto';
import { RolesGuard } from '../common/guards/roles.guard';
import { Roles } from '../common/decorators/roles.decorator';
import { UserRole } from '../common/enums';
@@ -20,44 +21,103 @@ import { UserRole } from '../common/enums';
@ApiBearerAuth()
@Controller('clusters')
@UseGuards(AuthGuard('jwt'), RolesGuard)
@Roles(UserRole.ADMIN)
export class ClustersController {
constructor(private readonly clustersService: ClustersService) {}
// ─── Public endpoints (any authenticated user) ────────────────────
@Get('public')
@ApiOperation({ summary: 'List available clusters (public info, no kubeconfig)' })
async findAllPublic() {
return this.clustersService.findAllPublic();
}
@Get('pools/public')
@ApiOperation({ summary: 'List active cluster pools with resolved cluster names' })
async findAllPoolsPublic() {
return this.clustersService.findAllPoolsPublic();
}
// ─── Cluster admin endpoints ──────────────────────────────────────
@Post()
@Roles(UserRole.ADMIN)
@ApiOperation({ summary: 'Register a new Kubernetes cluster (Admin only)' })
async create(@Body() dto: CreateClusterDto) {
return this.clustersService.create(dto);
}
@Get()
@Roles(UserRole.ADMIN)
@ApiOperation({ summary: 'List all clusters (Admin only)' })
async findAll() {
return this.clustersService.findAll();
}
@Get(':id')
@Roles(UserRole.ADMIN)
@ApiOperation({ summary: 'Get cluster details (Admin only)' })
async findOne(@Param('id') id: string) {
return this.clustersService.findOne(id);
}
@Patch(':id')
@Roles(UserRole.ADMIN)
@ApiOperation({ summary: 'Update cluster configuration (Admin only)' })
async update(@Param('id') id: string, @Body() dto: UpdateClusterDto) {
return this.clustersService.update(id, dto);
}
@Post(':id/test')
@Roles(UserRole.ADMIN)
@ApiOperation({ summary: 'Test connectivity to a registered cluster (Admin only)' })
async testConnection(@Param('id') id: string) {
return this.clustersService.testClusterById(id);
}
@Delete(':id')
@Roles(UserRole.ADMIN)
@ApiOperation({ summary: 'Remove a cluster (Admin only)' })
async delete(@Param('id') id: string) {
await this.clustersService.delete(id);
return { message: 'Cluster deleted' };
}
// ─── Cluster Pool admin endpoints ─────────────────────────────────
@Post('pools')
@Roles(UserRole.ADMIN)
@ApiOperation({ summary: 'Create a cluster pool for load balancing (Admin only)' })
async createPool(@Body() dto: CreateClusterPoolDto) {
return this.clustersService.createPool(dto);
}
@Get('pools')
@Roles(UserRole.ADMIN)
@ApiOperation({ summary: 'List all cluster pools (Admin only)' })
async findAllPools() {
return this.clustersService.findAllPools();
}
@Get('pools/:id')
@Roles(UserRole.ADMIN)
@ApiOperation({ summary: 'Get cluster pool details (Admin only)' })
async findOnePool(@Param('id') id: string) {
return this.clustersService.findOnePool(id);
}
@Patch('pools/:id')
@Roles(UserRole.ADMIN)
@ApiOperation({ summary: 'Update cluster pool (Admin only)' })
async updatePool(@Param('id') id: string, @Body() dto: UpdateClusterPoolDto) {
return this.clustersService.updatePool(id, dto);
}
@Delete('pools/:id')
@Roles(UserRole.ADMIN)
@ApiOperation({ summary: 'Delete a cluster pool (Admin only)' })
async deletePool(@Param('id') id: string) {
await this.clustersService.deletePool(id);
return { message: 'Cluster pool deleted' };
}
}
+2 -1
View File
@@ -3,9 +3,10 @@ import { TypeOrmModule } from '@nestjs/typeorm';
import { ClustersService } from './clusters.service';
import { ClustersController } from './clusters.controller';
import { Cluster } from './entities/cluster.entity';
import { ClusterPool } from './entities/cluster-pool.entity';
@Module({
imports: [TypeOrmModule.forFeature([Cluster])],
imports: [TypeOrmModule.forFeature([Cluster, ClusterPool])],
controllers: [ClustersController],
providers: [ClustersService],
exports: [ClustersService],
+210 -1
View File
@@ -1,18 +1,25 @@
import { Injectable, NotFoundException, Logger, BadRequestException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Repository, DataSource, In } from 'typeorm';
import * as k8s from '@kubernetes/client-node';
import { Cluster } from './entities/cluster.entity';
import { ClusterPool } from './entities/cluster-pool.entity';
import { CreateClusterDto, UpdateClusterDto } from './dto/cluster.dto';
import { CreateClusterPoolDto, UpdateClusterPoolDto } from './dto/cluster-pool.dto';
import { ClusterStatus } from '../common/enums';
@Injectable()
export class ClustersService {
private readonly logger = new Logger(ClustersService.name);
private roundRobinIndex = 0;
private poolRoundRobinIndices = new Map<string, number>();
constructor(
@InjectRepository(Cluster)
private clustersRepository: Repository<Cluster>,
@InjectRepository(ClusterPool)
private poolsRepository: Repository<ClusterPool>,
private dataSource: DataSource,
) {}
/**
@@ -135,8 +142,210 @@ export class ClustersService {
return result;
}
/**
* Public cluster list (no sensitive data) — for users to select a cluster.
*/
async findAllPublic(): Promise<Pick<Cluster, 'id' | 'name' | 'region' | 'provider' | 'isDefault' | 'status'>[]> {
return this.clustersRepository.find({
select: ['id', 'name', 'region', 'provider', 'isDefault', 'status'],
where: { status: ClusterStatus.ACTIVE },
order: { isDefault: 'DESC', name: 'ASC' },
});
}
/**
* Get the optimal cluster using load-balancing strategy.
* Strategy: 'least-apps' — picks the active cluster with fewest deployed applications.
* Falls back to default cluster if only one active cluster exists.
*/
async getOptimalCluster(strategy: 'least-apps' | 'round-robin' = 'least-apps'): Promise<Cluster> {
const activeClusters = await this.clustersRepository.find({
where: { status: ClusterStatus.ACTIVE },
});
if (activeClusters.length === 0) {
throw new NotFoundException('No active clusters available');
}
if (activeClusters.length === 1) {
return activeClusters[0];
}
if (strategy === 'round-robin') {
const cluster = activeClusters[this.roundRobinIndex % activeClusters.length];
this.roundRobinIndex++;
this.logger.log(`Round-robin selected cluster "${cluster.name}" (index: ${this.roundRobinIndex - 1})`);
return cluster;
}
// least-apps: count applications per cluster
const appCounts: { clusterId: string; count: string }[] = await this.dataSource.query(`
SELECT "clusterId", COUNT(*) as count
FROM applications
WHERE "clusterId" IS NOT NULL
GROUP BY "clusterId"
`);
const countMap = new Map<string, number>();
for (const row of appCounts) {
countMap.set(row.clusterId, parseInt(row.count, 10));
}
// Sort by app count ascending (least apps first)
activeClusters.sort((a, b) => {
const countA = countMap.get(a.id) || 0;
const countB = countMap.get(b.id) || 0;
return countA - countB;
});
const selected = activeClusters[0];
const selectedCount = countMap.get(selected.id) || 0;
this.logger.log(`Least-apps selected cluster "${selected.name}" (${selectedCount} apps)`);
return selected;
}
async delete(id: string): Promise<void> {
const cluster = await this.findOne(id);
await this.clustersRepository.remove(cluster);
}
// ─── Cluster Pool Methods ─────────────────────────────────────────
async createPool(dto: CreateClusterPoolDto): Promise<ClusterPool> {
// Validate that all cluster IDs exist
if (dto.clusterIds.length === 0) {
throw new BadRequestException('Pool must contain at least one cluster');
}
const clusters = await this.clustersRepository.find({
where: { id: In(dto.clusterIds) },
});
if (clusters.length !== dto.clusterIds.length) {
const foundIds = clusters.map((c) => c.id);
const missingIds = dto.clusterIds.filter((id) => !foundIds.includes(id));
throw new BadRequestException(`Clusters not found: ${missingIds.join(', ')}`);
}
const pool = this.poolsRepository.create(dto);
const saved = await this.poolsRepository.save(pool);
this.logger.log(`Cluster pool "${saved.name}" created with ${dto.clusterIds.length} clusters (strategy: ${dto.strategy})`);
return saved;
}
async findAllPools(): Promise<ClusterPool[]> {
return this.poolsRepository.find({ order: { createdAt: 'DESC' } });
}
/**
* Public pool list — returns pools with resolved cluster names for UI.
*/
async findAllPoolsPublic(): Promise<(ClusterPool & { clusters: Pick<Cluster, 'id' | 'name' | 'region' | 'provider' | 'status'>[] })[]> {
const pools = await this.poolsRepository.find({
where: { isActive: true },
order: { createdAt: 'DESC' },
});
const allClusterIds = [...new Set(pools.flatMap((p) => p.clusterIds))];
const clusters = allClusterIds.length > 0
? await this.clustersRepository.find({
where: { id: In(allClusterIds) },
select: ['id', 'name', 'region', 'provider', 'status'],
})
: [];
const clusterMap = new Map(clusters.map((c) => [c.id, c]));
return pools.map((pool) => ({
...pool,
clusters: pool.clusterIds
.map((id) => clusterMap.get(id))
.filter(Boolean) as Pick<Cluster, 'id' | 'name' | 'region' | 'provider' | 'status'>[],
}));
}
async findOnePool(id: string): Promise<ClusterPool> {
const pool = await this.poolsRepository.findOne({ where: { id } });
if (!pool) {
throw new NotFoundException('Cluster pool not found');
}
return pool;
}
async updatePool(id: string, dto: UpdateClusterPoolDto): Promise<ClusterPool> {
const pool = await this.findOnePool(id);
if (dto.clusterIds && dto.clusterIds.length > 0) {
const clusters = await this.clustersRepository.find({
where: { id: In(dto.clusterIds) },
});
if (clusters.length !== dto.clusterIds.length) {
const foundIds = clusters.map((c) => c.id);
const missingIds = dto.clusterIds.filter((cid) => !foundIds.includes(cid));
throw new BadRequestException(`Clusters not found: ${missingIds.join(', ')}`);
}
}
Object.assign(pool, dto);
return this.poolsRepository.save(pool);
}
async deletePool(id: string): Promise<void> {
const pool = await this.findOnePool(id);
await this.poolsRepository.remove(pool);
this.poolRoundRobinIndices.delete(id);
}
/**
* Get the optimal cluster from a specific pool using the pool's strategy.
* Only considers ACTIVE clusters within the pool.
*/
async getOptimalClusterFromPool(poolId: string): Promise<Cluster> {
const pool = await this.findOnePool(poolId);
if (!pool.isActive) {
throw new BadRequestException(`Pool "${pool.name}" is not active`);
}
const activeClusters = await this.clustersRepository.find({
where: {
id: In(pool.clusterIds),
status: ClusterStatus.ACTIVE,
},
});
if (activeClusters.length === 0) {
throw new NotFoundException(`No active clusters in pool "${pool.name}"`);
}
if (activeClusters.length === 1) {
return activeClusters[0];
}
if (pool.strategy === 'round-robin') {
const idx = this.poolRoundRobinIndices.get(pool.id) || 0;
const cluster = activeClusters[idx % activeClusters.length];
this.poolRoundRobinIndices.set(pool.id, idx + 1);
this.logger.log(`Pool "${pool.name}" round-robin → cluster "${cluster.name}"`);
return cluster;
}
// least-apps strategy
const appCounts: { clusterId: string; count: string }[] = await this.dataSource.query(`
SELECT "clusterId", COUNT(*) as count
FROM applications
WHERE "clusterId" = ANY($1)
GROUP BY "clusterId"
`, [pool.clusterIds]);
const countMap = new Map<string, number>();
for (const row of appCounts) {
countMap.set(row.clusterId, parseInt(row.count, 10));
}
activeClusters.sort((a, b) => {
return (countMap.get(a.id) || 0) - (countMap.get(b.id) || 0);
});
const selected = activeClusters[0];
this.logger.log(`Pool "${pool.name}" least-apps → cluster "${selected.name}" (${countMap.get(selected.id) || 0} apps)`);
return selected;
}
}
@@ -0,0 +1,50 @@
import { IsString, IsOptional, IsBoolean, IsArray, IsIn } from 'class-validator';
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
export class CreateClusterPoolDto {
@ApiProperty({ example: 'production-pool' })
@IsString()
name: string;
@ApiPropertyOptional({ example: 'Load-balanced pool for production workloads' })
@IsOptional()
@IsString()
description?: string;
@ApiProperty({ example: 'least-apps', enum: ['least-apps', 'round-robin'] })
@IsIn(['least-apps', 'round-robin'])
strategy: 'least-apps' | 'round-robin';
@ApiProperty({ example: ['uuid-1', 'uuid-2'], description: 'Array of cluster IDs in this pool' })
@IsArray()
@IsString({ each: true })
clusterIds: string[];
}
export class UpdateClusterPoolDto {
@ApiPropertyOptional({ example: 'production-pool-v2' })
@IsOptional()
@IsString()
name?: string;
@ApiPropertyOptional()
@IsOptional()
@IsString()
description?: string;
@ApiPropertyOptional({ enum: ['least-apps', 'round-robin'] })
@IsOptional()
@IsIn(['least-apps', 'round-robin'])
strategy?: 'least-apps' | 'round-robin';
@ApiPropertyOptional({ description: 'Array of cluster IDs in this pool' })
@IsOptional()
@IsArray()
@IsString({ each: true })
clusterIds?: string[];
@ApiPropertyOptional()
@IsOptional()
@IsBoolean()
isActive?: boolean;
}
@@ -0,0 +1,40 @@
import {
Entity,
PrimaryGeneratedColumn,
Column,
CreateDateColumn,
UpdateDateColumn,
} from 'typeorm';
export type PoolStrategy = 'least-apps' | 'round-robin';
@Entity('cluster_pools')
export class ClusterPool {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column()
name: string;
@Column({ nullable: true })
description: string;
@Column({ default: 'least-apps' })
strategy: PoolStrategy;
/**
* Array of cluster UUIDs that belong to this pool.
* Only active clusters from this list will be considered for load balancing.
*/
@Column({ type: 'jsonb', default: [] })
clusterIds: string[];
@Column({ default: true })
isActive: boolean;
@CreateDateColumn()
createdAt: Date;
@UpdateDateColumn()
updatedAt: Date;
}
@@ -0,0 +1,326 @@
'use client';
import { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import api from '@/lib/api';
import toast from 'react-hot-toast';
import type { Cluster, ClusterPool } from '@/types';
export default function AdminPoolsPage() {
const queryClient = useQueryClient();
const [showForm, setShowForm] = useState(false);
const [editingPool, setEditingPool] = useState<ClusterPool | null>(null);
const [form, setForm] = useState({
name: '',
description: '',
strategy: 'least-apps' as 'least-apps' | 'round-robin',
clusterIds: [] as string[],
});
const { data: pools = [], isLoading } = useQuery<ClusterPool[]>({
queryKey: ['admin-pools'],
queryFn: () => api.get('/clusters/pools').then((r) => r.data),
});
const { data: clusters = [] } = useQuery<Cluster[]>({
queryKey: ['admin-clusters'],
queryFn: () => api.get('/clusters').then((r) => r.data),
});
const createMutation = useMutation({
mutationFn: (data: typeof form) => api.post('/clusters/pools', data),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['admin-pools'] });
toast.success('Cluster pool created!');
resetForm();
},
onError: (err: any) => {
toast.error(err?.response?.data?.message || 'Failed to create pool');
},
});
const updateMutation = useMutation({
mutationFn: ({ id, data }: { id: string; data: typeof form }) =>
api.patch(`/clusters/pools/${id}`, data),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['admin-pools'] });
toast.success('Cluster pool updated!');
resetForm();
},
onError: (err: any) => {
toast.error(err?.response?.data?.message || 'Failed to update pool');
},
});
const deleteMutation = useMutation({
mutationFn: (id: string) => api.delete(`/clusters/pools/${id}`),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['admin-pools'] });
toast.success('Cluster pool deleted');
},
});
const resetForm = () => {
setShowForm(false);
setEditingPool(null);
setForm({ name: '', description: '', strategy: 'least-apps', clusterIds: [] });
};
const startEdit = (pool: ClusterPool) => {
setEditingPool(pool);
setForm({
name: pool.name,
description: pool.description || '',
strategy: pool.strategy,
clusterIds: pool.clusterIds,
});
setShowForm(true);
};
const handleSubmit = () => {
if (editingPool) {
updateMutation.mutate({ id: editingPool.id, data: form });
} else {
createMutation.mutate(form);
}
};
const toggleCluster = (clusterId: string) => {
setForm((prev) => ({
...prev,
clusterIds: prev.clusterIds.includes(clusterId)
? prev.clusterIds.filter((id) => id !== clusterId)
: [...prev.clusterIds, clusterId],
}));
};
return (
<div className="space-y-6">
<div className="flex justify-between items-center">
<div>
<h1 className="text-2xl font-bold text-gray-900">Cluster Pools</h1>
<p className="text-sm text-gray-500 mt-1">
Create load-balanced groups of clusters for automatic app distribution
</p>
</div>
<button
onClick={() => { showForm ? resetForm() : setShowForm(true); }}
className="btn-primary"
>
{showForm ? 'Cancel' : '+ Create Pool'}
</button>
</div>
{/* Create/Edit Form */}
{showForm && (
<div className="card space-y-4">
<h2 className="text-lg font-semibold">
{editingPool ? `Edit "${editingPool.name}"` : 'Create New Cluster Pool'}
</h2>
<div className="grid grid-cols-2 gap-4">
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Pool Name</label>
<input
className="input-field"
placeholder="production-pool"
value={form.name}
onChange={(e) => setForm({ ...form, name: e.target.value })}
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Strategy</label>
<select
className="input-field"
value={form.strategy}
onChange={(e) => setForm({ ...form, strategy: e.target.value as any })}
>
<option value="least-apps">📊 Least Apps deploy to cluster with fewest apps</option>
<option value="round-robin">🔄 Round Robin rotate across clusters evenly</option>
</select>
</div>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Description</label>
<input
className="input-field"
placeholder="Load-balanced pool for production workloads"
value={form.description}
onChange={(e) => setForm({ ...form, description: e.target.value })}
/>
</div>
{/* Cluster selection */}
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">
Select Clusters ({form.clusterIds.length} selected)
</label>
{clusters.length === 0 ? (
<p className="text-sm text-gray-400 py-4 text-center">
No clusters registered. Add clusters first.
</p>
) : (
<div className="grid grid-cols-1 md:grid-cols-2 gap-3">
{clusters.map((cluster) => {
const isSelected = form.clusterIds.includes(cluster.id);
return (
<button
key={cluster.id}
type="button"
onClick={() => toggleCluster(cluster.id)}
className={`p-3 rounded-xl border-2 text-left transition-all ${
isSelected
? 'border-primary-500 bg-primary-50 shadow-sm'
: 'border-gray-200 hover:border-gray-300'
}`}
>
<div className="flex items-center justify-between">
<div className="flex items-center space-x-3">
<div className={`w-5 h-5 rounded border-2 flex items-center justify-center ${
isSelected ? 'border-primary-500 bg-primary-500' : 'border-gray-300'
}`}>
{isSelected && <span className="text-white text-xs"></span>}
</div>
<div>
<p className="font-semibold text-sm text-gray-900">
{cluster.name}
{cluster.isDefault && (
<span className="ml-2 text-xs bg-blue-100 text-blue-700 px-1.5 py-0.5 rounded">
Default
</span>
)}
</p>
<p className="text-xs text-gray-500">
{cluster.provider || 'Unknown'} · {cluster.region || 'N/A'}
</p>
</div>
</div>
<span className={`px-2 py-0.5 rounded-full text-xs font-medium ${
cluster.status === 'active'
? 'bg-green-100 text-green-700'
: 'bg-red-100 text-red-700'
}`}>
{cluster.status}
</span>
</div>
</button>
);
})}
</div>
)}
</div>
<div className="flex space-x-3">
<button
onClick={handleSubmit}
disabled={
!form.name ||
form.clusterIds.length === 0 ||
createMutation.isPending ||
updateMutation.isPending
}
className="btn-primary disabled:opacity-50"
>
{createMutation.isPending || updateMutation.isPending
? '⏳ Saving...'
: editingPool
? 'Update Pool'
: 'Create Pool'}
</button>
<button onClick={resetForm} className="btn-secondary">
Cancel
</button>
</div>
</div>
)}
{/* Pool List */}
{isLoading ? (
<div className="card text-center py-12 text-gray-500">Loading pools...</div>
) : pools.length === 0 ? (
<div className="card text-center py-12">
<div className="text-4xl mb-3"></div>
<p className="text-gray-500">No cluster pools created yet</p>
<p className="text-sm text-gray-400 mt-1">
Create a pool to enable load-balanced deployment across multiple clusters
</p>
</div>
) : (
<div className="grid gap-4">
{pools.map((pool) => {
const poolClusters = clusters.filter((c) => pool.clusterIds.includes(c.id));
const activeClusters = poolClusters.filter((c) => c.status === 'active');
return (
<div key={pool.id} className="card">
<div className="flex items-start justify-between">
<div className="flex-1">
<div className="flex items-center space-x-3 mb-2">
<h3 className="text-lg font-semibold text-gray-900">{pool.name}</h3>
<span className={`px-2 py-0.5 rounded-full text-xs font-medium ${
pool.isActive ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-500'
}`}>
{pool.isActive ? 'Active' : 'Inactive'}
</span>
<span className="px-2 py-0.5 bg-purple-100 text-purple-700 text-xs rounded-full font-medium">
{pool.strategy === 'least-apps' ? '📊 Least Apps' : '🔄 Round Robin'}
</span>
</div>
{pool.description && (
<p className="text-sm text-gray-500 mb-3">{pool.description}</p>
)}
{/* Cluster chips */}
<div className="flex flex-wrap gap-2">
{poolClusters.length > 0 ? poolClusters.map((cluster) => (
<div
key={cluster.id}
className={`inline-flex items-center space-x-1.5 px-3 py-1.5 rounded-lg text-xs font-medium ${
cluster.status === 'active'
? 'bg-green-50 text-green-700 border border-green-200'
: 'bg-red-50 text-red-700 border border-red-200'
}`}
>
<span>{cluster.status === 'active' ? '✅' : '❌'}</span>
<span>{cluster.name}</span>
<span className="text-gray-400">
({cluster.provider || 'N/A'} · {cluster.region || 'N/A'})
</span>
</div>
)) : (
<p className="text-xs text-gray-400">No clusters in this pool (they may have been deleted)</p>
)}
</div>
<p className="text-xs text-gray-400 mt-2">
{activeClusters.length}/{poolClusters.length} clusters active · Created {new Date(pool.createdAt).toLocaleDateString()}
</p>
</div>
<div className="flex items-center space-x-3 ml-4">
<button
onClick={() => startEdit(pool)}
className="text-sm px-3 py-1.5 bg-blue-50 text-blue-700 rounded-md hover:bg-blue-100 transition-colors"
>
Edit
</button>
<button
onClick={() => {
if (confirm(`Delete pool "${pool.name}"? Apps already assigned to this pool will keep their current cluster.`)) {
deleteMutation.mutate(pool.id);
}
}}
className="text-sm text-red-600 hover:text-red-800"
>
Remove
</button>
</div>
</div>
</div>
);
})}
</div>
)}
</div>
);
}
+27 -1
View File
@@ -4,7 +4,7 @@ import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useParams, useRouter } from 'next/navigation';
import api from '@/lib/api';
import toast from 'react-hot-toast';
import type { Application, Deployment, ResourceUsage } from '@/types';
import type { Application, Deployment, ResourceUsage, ClusterPublic, ClusterPoolPublic } from '@/types';
import { useState, useRef, useCallback, useEffect } from 'react';
const statusColors: Record<string, string> = {
@@ -85,6 +85,16 @@ export default function AppDetailPage() {
refetchInterval: showResources ? 5000 : false,
});
const { data: clusters = [] } = useQuery<ClusterPublic[]>({
queryKey: ['clusters-public'],
queryFn: () => api.get('/clusters/public').then((r) => r.data),
});
const { data: pools = [] } = useQuery<ClusterPoolPublic[]>({
queryKey: ['pools-public'],
queryFn: () => api.get('/clusters/pools/public').then((r) => r.data),
});
// Sync form when resource data loads
useEffect(() => {
if (resourceUsage?.configured) {
@@ -378,6 +388,22 @@ export default function AppDetailPage() {
<dt className="text-sm text-gray-500">Port</dt>
<dd className="text-sm font-medium text-gray-900">{app.port}</dd>
</div>
{app.clusterId && (
<div className="flex justify-between">
<dt className="text-sm text-gray-500">Cluster</dt>
<dd className="text-sm font-medium text-gray-900">
🖥 {clusters.find((c) => c.id === app.clusterId)?.name || 'Unknown'}
</dd>
</div>
)}
{app.poolId && (
<div className="flex justify-between">
<dt className="text-sm text-gray-500">Pool</dt>
<dd className="text-sm font-medium text-gray-900">
{pools.find((p) => p.id === app.poolId)?.name || 'Unknown'}
</dd>
</div>
)}
{app.latestImageTag && (
<div className="flex justify-between">
<dt className="text-sm text-gray-500">Image</dt>
+187 -2
View File
@@ -2,10 +2,10 @@
import { useState, useRef, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import { useMutation } from '@tanstack/react-query';
import { useMutation, useQuery } from '@tanstack/react-query';
import api from '@/lib/api';
import toast from 'react-hot-toast';
import type { CreateApplicationDto } from '@/types';
import type { CreateApplicationDto, ClusterPublic, ClusterPoolPublic } from '@/types';
const steps = ['Basic Info', 'Runtime & Database', 'Resources', 'Review'];
@@ -34,8 +34,19 @@ export default function DeployPage() {
const [zipFile, setZipFile] = useState<File | null>(null);
const [uploadProgress, setUploadProgress] = useState(0);
const [isDragging, setIsDragging] = useState(false);
const [clusterMode, setClusterMode] = useState<'default' | 'manual' | 'pool'>('default');
const fileInputRef = useRef<HTMLInputElement>(null);
const { data: clusters = [] } = useQuery<ClusterPublic[]>({
queryKey: ['clusters-public'],
queryFn: () => api.get('/clusters/public').then((r) => r.data),
});
const { data: pools = [] } = useQuery<ClusterPoolPublic[]>({
queryKey: ['pools-public'],
queryFn: () => api.get('/clusters/pools/public').then((r) => r.data),
});
const createMutation = useMutation({
mutationFn: async (data: CreateApplicationDto) => {
const res = await api.post('/applications', data);
@@ -367,6 +378,170 @@ export default function DeployPage() {
{step === 2 && (
<div className="space-y-6">
<h2 className="text-lg font-semibold">Resources & Configuration</h2>
{/* Cluster Assignment Mode */}
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">Cluster Assignment</label>
<div className="grid grid-cols-3 gap-3 mb-4">
<button
type="button"
onClick={() => {
setClusterMode('default');
setForm({ ...form, clusterId: undefined, poolId: undefined });
}}
className={`p-3 rounded-xl border-2 text-center transition-colors ${
clusterMode === 'default'
? 'border-primary-500 bg-primary-50'
: 'border-gray-200 hover:border-gray-300'
}`}
>
<span className="text-xl">🏠</span>
<p className="mt-1 font-semibold text-sm text-gray-900">Default</p>
<p className="text-xs text-gray-500">Use default cluster</p>
</button>
<button
type="button"
onClick={() => {
setClusterMode('manual');
setForm({ ...form, poolId: undefined });
}}
className={`p-3 rounded-xl border-2 text-center transition-colors ${
clusterMode === 'manual'
? 'border-primary-500 bg-primary-50'
: 'border-gray-200 hover:border-gray-300'
}`}
>
<span className="text-xl">🎯</span>
<p className="mt-1 font-semibold text-sm text-gray-900">Manual</p>
<p className="text-xs text-gray-500">Pick a specific cluster</p>
</button>
<button
type="button"
onClick={() => {
setClusterMode('pool');
setForm({ ...form, clusterId: undefined });
}}
className={`p-3 rounded-xl border-2 text-center transition-colors ${
clusterMode === 'pool'
? 'border-primary-500 bg-primary-50'
: 'border-gray-200 hover:border-gray-300'
}`}
>
<span className="text-xl"></span>
<p className="mt-1 font-semibold text-sm text-gray-900">Load Balanced</p>
<p className="text-xs text-gray-500">Pick a cluster pool</p>
</button>
</div>
{/* Manual: show cluster list */}
{clusterMode === 'manual' && (
<div className="space-y-2">
{clusters.length === 0 ? (
<p className="text-sm text-gray-400 text-center py-4">No clusters available</p>
) : (
clusters.map((cluster) => (
<button
key={cluster.id}
type="button"
onClick={() => setForm({ ...form, clusterId: cluster.id })}
className={`w-full p-3 rounded-xl border-2 text-left transition-colors ${
form.clusterId === cluster.id
? 'border-primary-500 bg-primary-50'
: 'border-gray-200 hover:border-gray-300'
}`}
>
<div className="flex items-center justify-between">
<div className="flex items-center space-x-3">
<span className="text-lg">🖥</span>
<div>
<p className="font-semibold text-sm text-gray-900">
{cluster.name}
{cluster.isDefault && (
<span className="ml-2 text-xs bg-blue-100 text-blue-700 px-1.5 py-0.5 rounded">Default</span>
)}
</p>
<p className="text-xs text-gray-500">
{[cluster.provider, cluster.region].filter(Boolean).join(' · ') || 'No region info'}
</p>
</div>
</div>
<span className={`px-2 py-0.5 rounded-full text-xs font-medium ${
cluster.status === 'active' ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-500'
}`}>
{cluster.status}
</span>
</div>
</button>
))
)}
</div>
)}
{/* Pool: show pool list */}
{clusterMode === 'pool' && (
<div className="space-y-2">
{pools.length === 0 ? (
<div className="text-center py-4">
<p className="text-sm text-gray-400">No cluster pools configured</p>
<p className="text-xs text-gray-400 mt-1">Ask your admin to create a cluster pool</p>
</div>
) : (
pools.map((pool) => (
<button
key={pool.id}
type="button"
onClick={() => setForm({ ...form, poolId: pool.id })}
className={`w-full p-3 rounded-xl border-2 text-left transition-colors ${
form.poolId === pool.id
? 'border-primary-500 bg-primary-50'
: 'border-gray-200 hover:border-gray-300'
}`}
>
<div className="flex items-center justify-between">
<div className="flex items-center space-x-3">
<span className="text-lg"></span>
<div>
<p className="font-semibold text-sm text-gray-900">{pool.name}</p>
{pool.description && (
<p className="text-xs text-gray-500">{pool.description}</p>
)}
<div className="flex items-center space-x-2 mt-1">
<span className="text-xs bg-purple-100 text-purple-700 px-1.5 py-0.5 rounded">
{pool.strategy === 'least-apps' ? '📊 Least Apps' : '🔄 Round Robin'}
</span>
<span className="text-xs text-gray-400">
{pool.clusters.length} cluster{pool.clusters.length !== 1 ? 's' : ''}:
{' '}{pool.clusters.map((c) => c.name).join(', ')}
</span>
</div>
</div>
</div>
</div>
</button>
))
)}
</div>
)}
{/* Default: info text */}
{clusterMode === 'default' && (
<div className="p-3 bg-gray-50 rounded-xl border border-gray-200">
<div className="flex items-center space-x-3">
<span className="text-lg">🏠</span>
<div>
<p className="text-sm font-medium text-gray-700">Default cluster will be used</p>
<p className="text-xs text-gray-500">
Your app will be deployed to the platform&apos;s default cluster
{clusters.find((c) => c.isDefault) && (
<> <strong>{clusters.find((c) => c.isDefault)?.name}</strong></>
)}
</p>
</div>
</div>
</div>
)}
</div>
<div className="grid grid-cols-2 gap-4">
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">CPU Request</label>
@@ -497,6 +672,16 @@ export default function DeployPage() {
<span className="text-sm font-medium text-green-600">🔑 Token provided</span>
</div>
)}
<div className="flex justify-between">
<span className="text-sm text-gray-500">Cluster</span>
<span className="text-sm font-medium">
{clusterMode === 'manual' && form.clusterId
? `🎯 ${clusters.find((c) => c.id === form.clusterId)?.name || form.clusterId}`
: clusterMode === 'pool' && form.poolId
? `⚖️ ${pools.find((p) => p.id === form.poolId)?.name || 'Pool'} (Load Balanced)`
: '🏠 Default Cluster'}
</span>
</div>
<div className="flex justify-between">
<span className="text-sm text-gray-500">CPU</span>
<span className="text-sm font-medium">{form.cpuRequest} / {form.cpuLimit}</span>
+1
View File
@@ -14,6 +14,7 @@ const userNavItems = [
const adminNavItems = [
{ href: '/dashboard/admin/users', label: 'Users', icon: '👥' },
{ href: '/dashboard/admin/clusters', label: 'Clusters', icon: '🖥️' },
{ href: '/dashboard/admin/pools', label: 'Cluster Pools', icon: '⚖️' },
];
export default function DashboardLayout({ children }: { children: React.ReactNode }) {
+32
View File
@@ -28,6 +28,7 @@ export interface Application {
port: number;
userId: string;
clusterId?: string;
poolId?: string;
latestImageTag?: string;
subdomain?: string;
deployments?: Deployment[];
@@ -95,6 +96,37 @@ export interface CreateApplicationDto {
memoryLimit?: string;
replicas?: number;
port?: number;
clusterId?: string;
poolId?: string;
}
export interface ClusterPublic {
id: string;
name: string;
region?: string;
provider?: string;
isDefault: boolean;
status: 'active' | 'inactive' | 'maintenance';
}
export interface ClusterPoolPublic {
id: string;
name: string;
description?: string;
strategy: 'least-apps' | 'round-robin';
clusterIds: string[];
isActive: boolean;
clusters: Pick<ClusterPublic, 'id' | 'name' | 'region' | 'provider' | 'status'>[];
}
export interface ClusterPool {
id: string;
name: string;
description?: string;
strategy: 'least-apps' | 'round-robin';
clusterIds: string[];
isActive: boolean;
createdAt: string;
}
export interface PodInfo {
File diff suppressed because one or more lines are too long