diff --git a/create-a-container/client/src/components/containers/ResourceValueInput.tsx b/create-a-container/client/src/components/containers/ResourceValueInput.tsx index 9533372f..396e76d1 100644 --- a/create-a-container/client/src/components/containers/ResourceValueInput.tsx +++ b/create-a-container/client/src/components/containers/ResourceValueInput.tsx @@ -24,6 +24,8 @@ interface ResourceValueInputProps { presets: readonly number[]; value: number; onChange: (value: number) => void; + /** Preset label override; defaults to the value with its unit. */ + formatValue?: (value: number) => string; } /** @@ -39,6 +41,7 @@ export function ResourceValueInput({ presets, value, onChange, + formatValue, }: ResourceValueInputProps) { const [isCustom, setIsCustom] = useState(() => !presets.includes(value)); @@ -50,7 +53,7 @@ export function ResourceValueInput({ const options = [ ...presets.map((preset) => ({ value: String(preset), - label: formatPreset(preset, unit), + label: formatValue ? formatValue(preset) : formatPreset(preset, unit), })), { value: CUSTOM_OPTION, label: 'Custom…' }, ]; diff --git a/create-a-container/client/src/components/containers/ResourcesSection.tsx b/create-a-container/client/src/components/containers/ResourcesSection.tsx index a69f0533..e55a8706 100644 --- a/create-a-container/client/src/components/containers/ResourcesSection.tsx +++ b/create-a-container/client/src/components/containers/ResourcesSection.tsx @@ -15,6 +15,7 @@ import { Save } from 'lucide-react'; import { api, ApiError } from '@/lib/api'; import { keys, queries } from '@/lib/queries'; import { useSession } from '@/lib/auth'; +import { RESOURCE_DEFAULTS, formatIdleTime } from '@/lib/resources'; import type { EffectiveResources, ResourceRequest } from '@/lib/types'; import { ResourceValueInput } from './ResourceValueInput'; @@ -44,9 +45,21 @@ const RESOURCE_OPTIONS = [ min: 5, presets: [5, 10, 20, 50, 100, 200, 500], }, + { + key: 'idleTime', + label: 'Idle shutdown', + unit: 'hours', + step: 1, + min: 0, + presets: [0, 1, 4, 8, 24, 72, 168, 336, 720], + }, ] as const; -const DEFAULTS: EffectiveResources = { memory: 8192, swap: 0, cpus: 4, rootfs: 50 }; +/** Display value for a resource row; idleTime reads as "Never" / "3 days". */ +function formatResource(key: keyof EffectiveResources, value: number, unit: string): string { + if (key === 'idleTime') return formatIdleTime(value); + return unit ? `${value} ${unit}` : `${value}`; +} interface ResourcesSectionProps { siteId: string; @@ -121,7 +134,7 @@ export function ResourcesSection({ onError: (err: ApiError) => toast.error(err.message), }); - const resources = effective || DEFAULTS; + const resources = effective || RESOURCE_DEFAULTS; if (!hostname) { return ( @@ -162,6 +175,11 @@ export function ResourcesSection({

Resource allocations for this container. Changes above the default require admin approval.

+

+ Idle shutdown stops the container after that long without traffic through the proxy + (SSH and direct connections don't count). Shortening it applies immediately; longer + or Never requires admin approval. +

{!isOwner && (

Only owners can make resource requests on their containers. @@ -174,9 +192,9 @@ export function ResourcesSection({ )}

{RESOURCE_OPTIONS.map((opt) => { - const currentValue = resources[opt.key as keyof EffectiveResources]; + const currentValue = resources[opt.key]; const isEditing = editingResource === opt.key; - const isDefault = currentValue === DEFAULTS[opt.key as keyof EffectiveResources]; + const isDefault = currentValue === RESOURCE_DEFAULTS[opt.key]; return (
{!isEditing && ( - {currentValue} - {opt.unit ? ` ${opt.unit}` : ''} + {formatResource(opt.key, currentValue, opt.unit)} )}
@@ -209,6 +226,7 @@ export function ResourcesSection({ presets={opt.presets} value={editValue} onChange={setEditValue} + formatValue={opt.key === 'idleTime' ? formatIdleTime : undefined} /> = { + memory: 'RAM', + swap: 'Swap', + cpus: 'CPU', + rootfs: 'Storage', + idleTime: 'Idle shutdown', +}; + +/** idleTime value that exempts a container from idle shutdown. */ +export const IDLE_TIME_NEVER = 0; + +/** Idle-shutdown threshold in hours -> "Never", "8 hours", "3 days". */ +export function formatIdleTime(hours: number): string { + if (hours === IDLE_TIME_NEVER) return 'Never'; + if (hours % 24 === 0) { + const days = hours / 24; + return `${days} ${days === 1 ? 'day' : 'days'}`; + } + return `${hours} ${hours === 1 ? 'hour' : 'hours'}`; +} + +/** Compact value for request tables, e.g. "8.0GB", "50GB", "3 days". */ +export function formatResourceValue(type: string, value: number): string { + if (type === 'memory' || type === 'swap') { + return value >= 1024 ? `${(value / 1024).toFixed(1)}GB` : `${value}MB`; + } + if (type === 'rootfs') return `${value}GB`; + if (type === 'idleTime') return formatIdleTime(value); + return `${value}`; +} diff --git a/create-a-container/client/src/lib/types.ts b/create-a-container/client/src/lib/types.ts index 063ecaa2..f81cd1a0 100644 --- a/create-a-container/client/src/lib/types.ts +++ b/create-a-container/client/src/lib/types.ts @@ -481,7 +481,7 @@ export interface AppSettings { mailMessageSizeLimitMb: string; } -export type ResourceType = 'memory' | 'swap' | 'cpus' | 'rootfs'; +export type ResourceType = 'memory' | 'swap' | 'cpus' | 'rootfs' | 'idleTime'; export interface ResourceRequest { id: number; @@ -506,4 +506,6 @@ export interface EffectiveResources { swap: number; cpus: number; rootfs: number; + /** Hours without proxied access before an idle stop; 0 = never. */ + idleTime: number; } diff --git a/create-a-container/client/src/pages/resource-requests/MyRequestsPage.tsx b/create-a-container/client/src/pages/resource-requests/MyRequestsPage.tsx index 4c439abe..f2942e09 100644 --- a/create-a-container/client/src/pages/resource-requests/MyRequestsPage.tsx +++ b/create-a-container/client/src/pages/resource-requests/MyRequestsPage.tsx @@ -14,28 +14,8 @@ import { import { ClipboardList } from 'lucide-react'; import { keys, queries } from '@/lib/queries'; import { FormPageHeader } from '@/components/FormPageHeader'; - -const RESOURCE_LABELS: Record = { - memory: 'RAM', - swap: 'Swap', - cpus: 'CPU', - rootfs: 'Storage', -}; - -const RESOURCE_DEFAULTS: Record = { - memory: 8192, - swap: 0, - cpus: 4, - rootfs: 50, -}; - -function formatValue(type: string, value: number) { - if (type === 'memory' || type === 'swap') { - return value >= 1024 ? `${(value / 1024).toFixed(1)}GB` : `${value}MB`; - } - if (type === 'rootfs') return `${value}GB`; - return `${value}`; -} +import { RESOURCE_DEFAULTS, RESOURCE_LABELS, formatResourceValue } from '@/lib/resources'; +import type { ResourceType } from '@/lib/types'; function statusBadgeVariant(status: string) { if (status === 'approved') return 'success' as const; @@ -120,7 +100,7 @@ export function MyRequestsPage() { interface Request { id: number; hostname: string; - resourceType: string; + resourceType: ResourceType; value: number; status: string; comment: string | null; @@ -172,17 +152,17 @@ function RequestTable({ {req.hostname} - + {RESOURCE_LABELS[req.resourceType] || req.resourceType} - + - {formatValue(req.resourceType, prevValue)} + {formatResourceValue(req.resourceType, prevValue)} → - {formatValue(req.resourceType, req.value)} + {formatResourceValue(req.resourceType, req.value)} diff --git a/create-a-container/client/src/pages/resource-requests/ResourceRequestsPage.tsx b/create-a-container/client/src/pages/resource-requests/ResourceRequestsPage.tsx index d3787a3d..46408b30 100644 --- a/create-a-container/client/src/pages/resource-requests/ResourceRequestsPage.tsx +++ b/create-a-container/client/src/pages/resource-requests/ResourceRequestsPage.tsx @@ -19,30 +19,9 @@ import { CheckCircle, XCircle, ClipboardList } from 'lucide-react'; import { api, ApiError } from '@/lib/api'; import { keys, queries } from '@/lib/queries'; import { FormPageHeader } from '@/components/FormPageHeader'; +import { RESOURCE_DEFAULTS, RESOURCE_LABELS, formatResourceValue } from '@/lib/resources'; import type { ResourceRequest } from '@/lib/types'; -const RESOURCE_LABELS: Record = { - memory: 'RAM', - swap: 'Swap', - cpus: 'CPU', - rootfs: 'Storage', -}; - -const RESOURCE_DEFAULTS: Record = { - memory: 8192, - swap: 0, - cpus: 4, - rootfs: 50, -}; - -function formatValue(type: string, value: number) { - if (type === 'memory' || type === 'swap') { - return value >= 1024 ? `${(value / 1024).toFixed(1)}GB` : `${value}MB`; - } - if (type === 'rootfs') return `${value}GB`; - return `${value}`; -} - export function ResourceRequestsPage() { const qc = useQueryClient(); const toast = useToast(); @@ -142,17 +121,17 @@ export function ResourceRequestsPage() { {req.hostname} {req.username} - + {RESOURCE_LABELS[req.resourceType] || req.resourceType} - + - {formatValue(req.resourceType, prevValue)} + {formatResourceValue(req.resourceType, prevValue)} → - {formatValue(req.resourceType, req.value)} + {formatResourceValue(req.resourceType, req.value)} @@ -260,17 +239,17 @@ export function ResourceRequestsPage() { {req.hostname} {req.username} - + {RESOURCE_LABELS[req.resourceType] || req.resourceType} - + - {formatValue(req.resourceType, prevValue)} + {formatResourceValue(req.resourceType, prevValue)} → - {formatValue(req.resourceType, req.value)} + {formatResourceValue(req.resourceType, req.value)} diff --git a/create-a-container/models/resourcerequest.js b/create-a-container/models/resourcerequest.js index 3534d3c4..6d7879f0 100644 --- a/create-a-container/models/resourcerequest.js +++ b/create-a-container/models/resourcerequest.js @@ -3,17 +3,18 @@ const { Model } = require('sequelize'); /** - * Default resource values for containers. - * Requests at or below these values are auto-approved for non-admin users. + * Default resource values for containers, keyed by resource type. Per-type + * approval and apply rules live in resources/resource-requests/service.js. */ const RESOURCE_DEFAULTS = { memory: 8192, // MB swap: 0, // MB cpus: 4, rootfs: 50, // GB + idleTime: 72, // hours without proxied access before an idle stop; 0 = never }; -const VALID_RESOURCE_TYPES = ['memory', 'swap', 'cpus', 'rootfs']; +const VALID_RESOURCE_TYPES = Object.keys(RESOURCE_DEFAULTS); module.exports = (sequelize, DataTypes) => { class ResourceRequest extends Model { diff --git a/create-a-container/openapi.v1.yaml b/create-a-container/openapi.v1.yaml index 32100fac..af8ff5fc 100644 --- a/create-a-container/openapi.v1.yaml +++ b/create-a-container/openapi.v1.yaml @@ -581,6 +581,23 @@ components: recipient: { type: string } source: { type: string, enum: [one-click, admin] } createdAt: { type: string, format: date-time } + ResourceType: + type: string + enum: [memory, swap, cpus, rootfs, idleTime] + ResourceValue: + type: integer + minimum: 0 + description: >- + memory/swap in MB, rootfs in GB, cpus as a count, idleTime in hours + without proxied access before the container is stopped (0 = never). + EffectiveResources: + type: object + properties: + memory: { type: integer } + swap: { type: integer } + cpus: { type: integer } + rootfs: { type: integer } + idleTime: { type: integer, description: 'Hours; default 72, 0 = never stop' } ResourceRequest: type: object properties: @@ -588,8 +605,8 @@ components: siteId: { type: integer } hostname: { type: string } username: { type: string } - resourceType: { type: string, enum: [memory, swap, cpus, rootfs] } - value: { type: integer, description: 'memory/swap in MB, rootfs in GB, cpus as a count' } + resourceType: { $ref: '#/components/schemas/ResourceType' } + value: { $ref: '#/components/schemas/ResourceValue' } status: { type: string, enum: [pending, approved, denied] } comment: { type: string, nullable: true } adminComment: { type: string, nullable: true } @@ -2410,10 +2427,13 @@ paths: operationId: create_resource_request tags: [Resource Requests] summary: >- - Request a resource adjustment for a container. Auto-approved (and - applied to matching provisioned containers) when the caller is an admin - or the value is at or below the default (memory 8192 MB, swap 0 MB, - cpus 4, rootfs 50 GB); otherwise left pending for admin review. + Request a resource adjustment for a container. Auto-approved when the + caller is an admin or the value is at or below the default (memory + 8192 MB, swap 0 MB, cpus 4, rootfs 50 GB); otherwise left pending for + admin review. idleTime is inverted: 1..72 hours auto-approves, while + longer values and 0 (never) need review. Approved memory/swap/cpus/ + rootfs are applied to matching provisioned containers; idleTime is + read by the idle sweep and enqueues no reconfigure job. requestBody: required: true content: @@ -2424,8 +2444,8 @@ paths: properties: siteId: { type: integer } hostname: { type: string } - resourceType: { type: string, enum: [memory, swap, cpus, rootfs] } - value: { type: integer, minimum: 0, description: 'memory/swap in MB, rootfs in GB, cpus as a count' } + resourceType: { $ref: '#/components/schemas/ResourceType' } + value: { $ref: '#/components/schemas/ResourceValue' } comment: { type: string } responses: '201': @@ -2460,13 +2480,13 @@ paths: description: Effective resource values content: application/json: - schema: { type: object, properties: { data: { type: object, properties: { memory: { type: integer }, swap: { type: integer }, cpus: { type: integer }, rootfs: { type: integer } } } } } + schema: { type: object, properties: { data: { $ref: '#/components/schemas/EffectiveResources' } } } '403': { description: 'forbidden — non-admins may only query their own username', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } } /resource-requests/{id}/approve: put: operationId: approve_resource_request tags: [Resource Requests] - summary: Approve a pending request and apply it to matching provisioned containers (admin) + summary: Approve a pending request and apply it to matching provisioned containers (admin). idleTime needs no provisioned container and enqueues no reconfigure job. parameters: [{ in: path, name: id, required: true, schema: { type: integer } }] requestBody: content: @@ -2484,7 +2504,7 @@ paths: '403': { $ref: '#/components/responses/Forbidden' } '404': { $ref: '#/components/responses/NotFound' } '409': { description: 'Request already reviewed (code: already_reviewed)', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } } - '422': { description: 'No provisioned container matches the request (code: container_not_found)', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } } + '422': { description: 'No provisioned container matches a memory/swap/cpus/rootfs request (code: container_not_found)', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } } /resource-requests/{id}/deny: put: operationId: deny_resource_request diff --git a/create-a-container/resources/resource-requests/__tests__/resource-requests.api.test.js b/create-a-container/resources/resource-requests/__tests__/resource-requests.api.test.js new file mode 100644 index 00000000..62475e9f --- /dev/null +++ b/create-a-container/resources/resource-requests/__tests__/resource-requests.api.test.js @@ -0,0 +1,353 @@ +/** + * Integration tests for /api/v1/resource-requests — pin the wire contract + * (manifesto §6 step 1): status codes, envelopes, auto-approval and the + * reconfigure jobs enqueued on approval. + */ + +const request = require('supertest'); +const { buildApp, bearer } = require('../../../tests/helpers/app'); +const { resetDb, closeDb, createUser, createApiKey } = require('../../../tests/helpers/db'); +const { Site, Node, Container, Job, ResourceRequest } = require('../../../models'); + +const BASE = '/api/v1/resource-requests'; + +describe('/api/v1/resource-requests', () => { + let app; + let site; + let node; + let adminKey; + let aliceKey; + let bobKey; + + beforeAll(async () => { + await resetDb(); + app = buildApp(); + const admin = await createUser({ uid: 'admin' }); // first user is auto-promoted to sysadmins + const alice = await createUser({ uid: 'alice' }); + const bob = await createUser({ uid: 'bob' }); + adminKey = (await createApiKey(admin)).plainKey; + aliceKey = (await createApiKey(alice)).plainKey; + bobKey = (await createApiKey(bob)).plainKey; + site = await Site.create({ name: 'test-site', internalDomain: 'test.internal' }); + node = await Node.create({ siteId: site.id, name: 'n1', nodeType: 'dummy' }); + }); + + beforeEach(async () => { + await ResourceRequest.destroy({ where: {} }); + await Container.destroy({ where: {} }); + await Job.destroy({ where: {} }); + }); + + afterAll(closeDb); + + const as = (key) => ({ + get: (path) => request(app).get(`${BASE}${path}`).set(...bearer(key)), + post: (path, body) => request(app).post(`${BASE}${path}`).set(...bearer(key)).send(body), + put: (path, body) => request(app).put(`${BASE}${path}`).set(...bearer(key)).send(body), + }); + + const makeRequest = (fields) => + ResourceRequest.create({ + siteId: site.id, + hostname: 'web', + username: 'alice', + resourceType: 'memory', + value: 16384, + status: 'pending', + ...fields, + }); + + const makeContainer = (fields) => + Container.create({ + hostname: 'web', + username: 'alice', + nodeId: node.id, + siteId: site.id, + ...fields, + }); + + const reconfigureJobs = () => Job.findAll({ where: { createdBy: 'system' } }); + + test('401 without credentials', async () => { + const res = await request(app).get(BASE); + expect(res.status).toBe(401); + expect(res.body.error.code).toBe('unauthorized'); + }); + + describe('GET /', () => { + test('serializes every request column plus the site', async () => { + await makeRequest({}); + const res = await as(aliceKey).get('/'); + expect(Object.keys(res.body.data[0]).sort()).toEqual([ + 'adminComment', 'comment', 'createdAt', 'hostname', 'id', 'resourceType', 'reviewedAt', + 'reviewedBy', 'site', 'siteId', 'status', 'updatedAt', 'username', 'value', + ]); + }); + + test('non-admins only see their own requests, with the site included', async () => { + await makeRequest({ username: 'alice' }); + await makeRequest({ username: 'bob' }); + const res = await as(aliceKey).get('/'); + expect(res.status).toBe(200); + expect(res.body.data).toHaveLength(1); + expect(res.body.data[0]).toMatchObject({ + username: 'alice', + site: { id: site.id, name: 'test-site' }, + }); + }); + + test('admins see every request', async () => { + await makeRequest({ username: 'alice' }); + await makeRequest({ username: 'bob' }); + const res = await as(adminKey).get('/'); + expect(res.status).toBe(200); + expect(res.body.data).toHaveLength(2); + }); + + test('filters by status, where "closed" means approved or denied', async () => { + await makeRequest({ status: 'pending' }); + await makeRequest({ status: 'approved' }); + await makeRequest({ status: 'denied' }); + const pending = await as(adminKey).get('/?status=pending'); + expect(pending.body.data.map((r) => r.status)).toEqual(['pending']); + const closed = await as(adminKey).get('/?status=closed'); + expect(closed.body.data.map((r) => r.status).sort()).toEqual(['approved', 'denied']); + }); + + test('filters by siteId', async () => { + const other = await Site.create({ name: 'other', internalDomain: 'other.internal' }); + await makeRequest({}); + await makeRequest({ siteId: other.id }); + const res = await as(adminKey).get(`/?siteId=${other.id}`); + expect(res.body.data).toHaveLength(1); + expect(res.body.data[0].siteId).toBe(other.id); + }); + }); + + describe('GET /count', () => { + test('returns the global pending count to any authenticated user', async () => { + await makeRequest({ username: 'bob' }); + await makeRequest({ username: 'bob', status: 'approved' }); + const res = await as(aliceKey).get('/count'); + expect(res.status).toBe(200); + expect(res.body).toEqual({ data: { count: 1 } }); + }); + }); + + describe('GET /effective/:siteId/:hostname/:username', () => { + test('returns defaults merged with the latest approvals', async () => { + await makeRequest({ status: 'approved', value: 16384, reviewedAt: new Date('2026-01-01') }); + await makeRequest({ status: 'pending', resourceType: 'cpus', value: 16 }); + const res = await as(aliceKey).get(`/effective/${site.id}/web/alice`); + expect(res.status).toBe(200); + expect(res.body.data).toEqual({ + ...ResourceRequest.RESOURCE_DEFAULTS, + memory: 16384, + }); + expect(res.body.data.idleTime).toBe(72); + }); + + test('returns an approved idleTime of 0 (never)', async () => { + await makeRequest({ status: 'approved', resourceType: 'idleTime', value: 0, reviewedAt: new Date() }); + const res = await as(aliceKey).get(`/effective/${site.id}/web/alice`); + expect(res.body.data.idleTime).toBe(0); + }); + + test('403 when a non-admin asks about another user', async () => { + const res = await as(bobKey).get(`/effective/${site.id}/web/alice`); + expect(res.status).toBe(403); + expect(res.body.error.code).toBe('forbidden'); + }); + + test('admins may query any user', async () => { + const res = await as(adminKey).get(`/effective/${site.id}/web/alice`); + expect(res.status).toBe(200); + }); + }); + + describe('POST /', () => { + const valid = () => ({ siteId: site.id, hostname: 'web', resourceType: 'memory', value: 4096 }); + + test.each([ + ['siteId', { siteId: undefined }], + ['hostname', { hostname: ' ' }], + ['resourceType', { resourceType: undefined }], + ['resourceType', { resourceType: 'gpus' }], + ['value', { value: undefined }], + ['value', { value: -1 }], + ['value', { value: 'abc' }], + ])('400 invalid_request for a bad %s', async (_field, override) => { + const res = await as(aliceKey).post('/', { ...valid(), ...override }); + expect(res.status).toBe(400); + expect(res.body.error.code).toBe('invalid_request'); + }); + + test('404 for an unknown site', async () => { + const res = await as(aliceKey).post('/', { ...valid(), siteId: 999999 }); + expect(res.status).toBe(404); + expect(res.body.error.code).toBe('site_not_found'); + }); + + test('auto-approves values at or below the default as "system"', async () => { + const res = await as(aliceKey).post('/', { ...valid(), hostname: ' WEB ', comment: 'pls' }); + expect(res.status).toBe(201); + expect(res.body.data).toMatchObject({ + siteId: site.id, + hostname: 'web', + username: 'alice', + resourceType: 'memory', + value: 4096, + status: 'approved', + comment: 'pls', + reviewedBy: 'system', + }); + expect(res.body.data.reviewedAt).toEqual(expect.any(String)); + }); + + test('leaves values above the default pending', async () => { + const res = await as(aliceKey).post('/', { ...valid(), value: 65536 }); + expect(res.status).toBe(201); + expect(res.body.data).toMatchObject({ status: 'pending', reviewedBy: null, reviewedAt: null }); + }); + + test('admins are always auto-approved as themselves', async () => { + const res = await as(adminKey).post('/', { ...valid(), value: 65536 }); + expect(res.body.data).toMatchObject({ status: 'approved', reviewedBy: 'admin', username: 'admin' }); + }); + + test('accepts numeric strings', async () => { + const res = await as(aliceKey).post('/', { ...valid(), siteId: String(site.id), value: '2048' }); + expect(res.status).toBe(201); + expect(res.body.data.value).toBe(2048); + }); + + test('auto-approval enqueues a reconfigure job per provisioned container only', async () => { + const provisioned = await makeContainer({ containerId: '101' }); + await makeContainer({ hostname: 'web2' }); + await as(aliceKey).post('/', valid()); + const jobs = await reconfigureJobs(); + expect(jobs.map((j) => j.command)).toEqual([ + `node bin/reconfigure-container.js --container-id=${provisioned.id}`, + ]); + }); + + test('pending requests enqueue nothing', async () => { + await makeContainer({ containerId: '101' }); + await as(aliceKey).post('/', { ...valid(), value: 65536 }); + expect(await reconfigureJobs()).toHaveLength(0); + }); + + describe('idleTime', () => { + const idle = (value) => ({ ...valid(), resourceType: 'idleTime', value }); + + test.each([1, 24, 72])('auto-approves a shorter-or-equal %i hours', async (value) => { + const res = await as(aliceKey).post('/', idle(value)); + expect(res.status).toBe(201); + expect(res.body.data).toMatchObject({ resourceType: 'idleTime', value, status: 'approved' }); + }); + + test.each([73, 720, 0])('leaves a longer or "never" (%i) pending', async (value) => { + const res = await as(aliceKey).post('/', idle(value)); + expect(res.status).toBe(201); + expect(res.body.data.status).toBe('pending'); + }); + + test('auto-approval does not enqueue a reconfigure job', async () => { + await makeContainer({ containerId: '101' }); + await as(aliceKey).post('/', idle(8)); + expect(await reconfigureJobs()).toHaveLength(0); + }); + }); + }); + + describe('PUT /:id/approve', () => { + test('403 for non-admins', async () => { + const pending = await makeRequest({}); + const res = await as(aliceKey).put(`/${pending.id}/approve`, {}); + expect(res.status).toBe(403); + }); + + test('404 for an unknown request', async () => { + const res = await as(adminKey).put('/999999/approve', {}); + expect(res.status).toBe(404); + expect(res.body.error.code).toBe('not_found'); + }); + + test('409 when already reviewed', async () => { + const done = await makeRequest({ status: 'approved' }); + const res = await as(adminKey).put(`/${done.id}/approve`, {}); + expect(res.status).toBe(409); + expect(res.body.error.code).toBe('already_reviewed'); + }); + + test('422 without a provisioned container', async () => { + await makeContainer({}); + const pending = await makeRequest({}); + const res = await as(adminKey).put(`/${pending.id}/approve`, {}); + expect(res.status).toBe(422); + expect(res.body.error.code).toBe('container_not_found'); + expect((await pending.reload()).status).toBe('pending'); + }); + + test('approves and enqueues a reconfigure job', async () => { + const container = await makeContainer({ containerId: '101' }); + const pending = await makeRequest({}); + const res = await as(adminKey).put(`/${pending.id}/approve`, { adminComment: 'ok' }); + expect(res.status).toBe(200); + expect(res.body.data).toMatchObject({ + id: pending.id, + status: 'approved', + reviewedBy: 'admin', + adminComment: 'ok', + }); + const jobs = await reconfigureJobs(); + expect(jobs.map((j) => j.command)).toEqual([ + `node bin/reconfigure-container.js --container-id=${container.id}`, + ]); + }); + + test('approves idleTime without a provisioned container or reconfigure job', async () => { + await makeContainer({}); + const pending = await makeRequest({ resourceType: 'idleTime', value: 0 }); + const res = await as(adminKey).put(`/${pending.id}/approve`, {}); + expect(res.status).toBe(200); + expect(res.body.data.status).toBe('approved'); + expect(await reconfigureJobs()).toHaveLength(0); + }); + + test('approving idleTime for a provisioned container enqueues nothing', async () => { + await makeContainer({ containerId: '101' }); + const pending = await makeRequest({ resourceType: 'idleTime', value: 168 }); + await as(adminKey).put(`/${pending.id}/approve`, {}); + expect(await reconfigureJobs()).toHaveLength(0); + }); + }); + + describe('PUT /:id/deny', () => { + test('403 for non-admins', async () => { + const pending = await makeRequest({}); + const res = await as(aliceKey).put(`/${pending.id}/deny`, {}); + expect(res.status).toBe(403); + }); + + test('404 for an unknown request', async () => { + const res = await as(adminKey).put('/999999/deny', {}); + expect(res.status).toBe(404); + }); + + test('409 when already reviewed', async () => { + const done = await makeRequest({ status: 'denied' }); + const res = await as(adminKey).put(`/${done.id}/deny`, {}); + expect(res.status).toBe(409); + }); + + test('denies with an admin comment and enqueues nothing', async () => { + await makeContainer({ containerId: '101' }); + const pending = await makeRequest({}); + const res = await as(adminKey).put(`/${pending.id}/deny`, { adminComment: 'no' }); + expect(res.status).toBe(200); + expect(res.body.data).toMatchObject({ status: 'denied', reviewedBy: 'admin', adminComment: 'no' }); + expect(await reconfigureJobs()).toHaveLength(0); + }); + }); +}); diff --git a/create-a-container/resources/resource-requests/__tests__/service.test.js b/create-a-container/resources/resource-requests/__tests__/service.test.js new file mode 100644 index 00000000..59643a8f --- /dev/null +++ b/create-a-container/resources/resource-requests/__tests__/service.test.js @@ -0,0 +1,62 @@ +jest.mock('../repository'); + +const repo = require('../repository'); +const svc = require('../service'); +const { ResourceRequest } = require('../../../models'); + +describe('resource-requests service', () => { + afterEach(() => jest.resetAllMocks()); + + test('every valid resource type has a review policy', () => { + expect(Object.keys(svc.RESOURCE_POLICIES).sort()) + .toEqual([...ResourceRequest.VALID_RESOURCE_TYPES].sort()); + }); + + test('idleTime defaults to 72 hours', () => { + expect(ResourceRequest.RESOURCE_DEFAULTS.idleTime).toBe(72); + }); + + describe('shouldAutoApprove', () => { + test.each([ + ['memory', 8192, true], + ['memory', 8193, false], + ['swap', 0, true], + ['cpus', 5, false], + ['rootfs', 10, true], + // idleTime is inverted: shorter than the default is self-service. + ['idleTime', 1, true], + ['idleTime', 72, true], + ['idleTime', 73, false], + ['idleTime', svc.IDLE_TIME_NEVER, false], + ])('non-admin %s=%i -> %s', (type, value, expected) => { + expect(svc.shouldAutoApprove(false, type, value)).toBe(expected); + }); + + test.each([ + ['memory', 65536], + ['idleTime', 0], + ['idleTime', 720], + ])('admins always auto-approve %s=%i', (type, value) => { + expect(svc.shouldAutoApprove(true, type, value)).toBe(true); + }); + + test('unknown types never auto-approve for non-admins', () => { + expect(svc.shouldAutoApprove(false, 'gpus', 0)).toBe(false); + }); + }); + + describe('getIdleTimeHours', () => { + const container = { siteId: 1, hostname: 'web', username: 'alice' }; + + test('falls back to the default without an approval', async () => { + repo.findApprovedResources.mockResolvedValue({ memory: 16384 }); + expect(await svc.getIdleTimeHours(container)).toBe(72); + expect(repo.findApprovedResources).toHaveBeenCalledWith(1, 'web', 'alice'); + }); + + test('keeps an approved "never" (0) rather than treating it as unset', async () => { + repo.findApprovedResources.mockResolvedValue({ idleTime: svc.IDLE_TIME_NEVER }); + expect(await svc.getIdleTimeHours(container)).toBe(0); + }); + }); +}); diff --git a/create-a-container/resources/resource-requests/controller.js b/create-a-container/resources/resource-requests/controller.js new file mode 100644 index 00000000..a0bddcf0 --- /dev/null +++ b/create-a-container/resources/resource-requests/controller.js @@ -0,0 +1,35 @@ +const svc = require('./service'); +const { serializeResourceRequest } = require('./serializer'); +const { asyncHandler, ok, created } = require('../../middlewares/api'); + +const actorOf = (req) => ({ username: req.session.user, isAdmin: !!req.session.isAdmin }); + +const list = asyncHandler(async (req, res) => { + const rows = await svc.list(actorOf(req), req.validated.query); + return ok(res, rows.map(serializeResourceRequest)); +}); + +const count = asyncHandler(async (_req, res) => { + return ok(res, { count: await svc.countPending() }); +}); + +const effective = asyncHandler(async (req, res) => { + return ok(res, await svc.getEffectiveResourcesFor(actorOf(req), req.validated.params)); +}); + +const create = asyncHandler(async (req, res) => { + const request = await svc.create(actorOf(req), req.validated.body); + return created(res, serializeResourceRequest(request)); +}); + +const approve = asyncHandler(async (req, res) => { + const request = await svc.approve(actorOf(req), req.validated.params.id, req.validated.body); + return ok(res, serializeResourceRequest(request)); +}); + +const deny = asyncHandler(async (req, res) => { + const request = await svc.deny(actorOf(req), req.validated.params.id, req.validated.body); + return ok(res, serializeResourceRequest(request)); +}); + +module.exports = { list, count, effective, create, approve, deny }; diff --git a/create-a-container/resources/resource-requests/repository.js b/create-a-container/resources/resource-requests/repository.js new file mode 100644 index 00000000..eacb62e8 --- /dev/null +++ b/create-a-container/resources/resource-requests/repository.js @@ -0,0 +1,56 @@ +const { Op } = require('sequelize'); +const { ResourceRequest, Container, Site, Job } = require('../../models'); + +async function findAll({ username, statuses, siteId } = {}) { + const where = {}; + if (username) where.username = username; + if (statuses) where.status = { [Op.in]: statuses }; + if (siteId) where.siteId = siteId; + return ResourceRequest.findAll({ + where, + order: [['createdAt', 'DESC']], + include: [{ association: 'site', attributes: ['id', 'name'] }], + }); +} + +async function countPending() { + return ResourceRequest.count({ where: { status: 'pending' } }); +} + +async function findById(id) { + return ResourceRequest.findByPk(id); +} + +async function create(fields) { + return ResourceRequest.create(fields); +} + +async function findApprovedResources(siteId, hostname, username) { + return ResourceRequest.getApprovedResources(siteId, hostname, username); +} + +async function findSiteById(id) { + return Site.findByPk(id); +} + +// A container is provisioned once it has a hypervisor id (containerId). +async function findProvisionedContainers(siteId, hostname, username) { + return Container.findAll({ + where: { siteId, hostname, username, containerId: { [Op.ne]: null } }, + }); +} + +async function createJob(fields) { + return Job.create(fields); +} + +module.exports = { + findAll, + countPending, + findById, + create, + findApprovedResources, + findSiteById, + findProvisionedContainers, + createJob, +}; diff --git a/create-a-container/resources/resource-requests/router.js b/create-a-container/resources/resource-requests/router.js new file mode 100644 index 00000000..9b6d585a --- /dev/null +++ b/create-a-container/resources/resource-requests/router.js @@ -0,0 +1,28 @@ +/** + * /api/v1/resource-requests — container resource requests. + * + * GET / own requests (admins: all) + * GET /count pending-request count (badge) + * GET /effective/:siteId/:hostname/:username defaults + latest approvals + * POST / request a resource value + * PUT /:id/approve admin approves a pending request + * PUT /:id/deny admin denies a pending request + */ + +const express = require('express'); +const { apiAuth, apiAdmin } = require('../../middlewares/api'); +const { validate } = require('../../middlewares/validate'); +const { createRequest, reviewRequest, listQuery, idParam, effectiveParams } = require('./validator'); +const ctrl = require('./controller'); + +const router = express.Router(); +router.use(apiAuth); + +router.get('/', validate({ query: listQuery }), ctrl.list); +router.get('/count', ctrl.count); +router.get('/effective/:siteId/:hostname/:username', validate({ params: effectiveParams }), ctrl.effective); +router.post('/', validate(createRequest), ctrl.create); +router.put('/:id/approve', apiAdmin, validate({ params: idParam, body: reviewRequest }), ctrl.approve); +router.put('/:id/deny', apiAdmin, validate({ params: idParam, body: reviewRequest }), ctrl.deny); + +module.exports = router; diff --git a/create-a-container/resources/resource-requests/serializer.js b/create-a-container/resources/resource-requests/serializer.js new file mode 100644 index 00000000..5cabd8bd --- /dev/null +++ b/create-a-container/resources/resource-requests/serializer.js @@ -0,0 +1,22 @@ +/** ResourceRequest row -> API JSON. `site` is included when it was loaded. */ +function serializeResourceRequest(r) { + const out = { + id: r.id, + siteId: r.siteId, + hostname: r.hostname, + username: r.username, + resourceType: r.resourceType, + value: r.value, + status: r.status, + comment: r.comment ?? null, + adminComment: r.adminComment ?? null, + reviewedBy: r.reviewedBy ?? null, + reviewedAt: r.reviewedAt ?? null, + createdAt: r.createdAt, + updatedAt: r.updatedAt, + }; + if (r.site) out.site = { id: r.site.id, name: r.site.name }; + return out; +} + +module.exports = { serializeResourceRequest }; diff --git a/create-a-container/resources/resource-requests/service.js b/create-a-container/resources/resource-requests/service.js new file mode 100644 index 00000000..e8558efc --- /dev/null +++ b/create-a-container/resources/resource-requests/service.js @@ -0,0 +1,180 @@ +const repo = require('./repository'); +const { ResourceRequest } = require('../../models'); +const { ApiError } = require('../../middlewares/api'); + +const { RESOURCE_DEFAULTS } = ResourceRequest; + +/** idleTime value that exempts a container from idle shutdown. */ +const IDLE_TIME_NEVER = 0; + +// Hypervisor-backed capacity: requesting more than the default needs review, +// and approval reconfigures the container (so it must already be provisioned). +const CAPACITY_POLICY = { + autoApprove: (value, defaultValue) => value <= defaultValue, + reconfigures: true, +}; + +/** + * How each resource type is reviewed and applied. + * autoApprove(value, default) - may a non-admin skip admin review? + * reconfigures - approval changes hypervisor config: it requires a + * provisioned container and enqueues reconfigure-container.js. + */ +const RESOURCE_POLICIES = { + memory: CAPACITY_POLICY, + swap: CAPACITY_POLICY, + cpus: CAPACITY_POLICY, + rootfs: CAPACITY_POLICY, + // Inverted: stopping sooner than the default frees resources, so 1..default + // is self-service; longer, or 0 (never stop), needs review. Read by the idle + // sweep rather than the hypervisor. + idleTime: { + autoApprove: (value, defaultValue) => value !== IDLE_TIME_NEVER && value <= defaultValue, + reconfigures: false, + }, +}; + +// "closed" in the list filter is shorthand for every reviewed status. +const STATUS_FILTERS = { + pending: ['pending'], + approved: ['approved'], + denied: ['denied'], + closed: ['approved', 'denied'], +}; + +/** Admins always auto-approve; others per the resource type's policy. */ +function shouldAutoApprove(isAdmin, resourceType, value) { + if (isAdmin) return true; + const policy = RESOURCE_POLICIES[resourceType]; + if (!policy) return false; + return policy.autoApprove(value, RESOURCE_DEFAULTS[resourceType]); +} + +/** Admins see every request; everyone else only their own. */ +async function list(actor, { status, siteId } = {}) { + return repo.findAll({ + username: actor.isAdmin ? undefined : actor.username, + statuses: status ? STATUS_FILTERS[status] : undefined, + siteId, + }); +} + +async function countPending() { + return repo.countPending(); +} + +/** Defaults overlaid with the latest approval per resource type. */ +async function getEffectiveResources(siteId, hostname, username) { + const approved = await repo.findApprovedResources(siteId, hostname, username); + return { ...RESOURCE_DEFAULTS, ...approved }; +} + +async function getEffectiveResourcesFor(actor, { siteId, hostname, username }) { + if (!actor.isAdmin && username !== actor.username) { + throw new ApiError(403, 'forbidden', 'Cannot view resources for other users'); + } + return getEffectiveResources(siteId, hostname, username); +} + +/** + * Effective idle-shutdown threshold in hours for a container (any object with + * siteId/hostname/username, e.g. a Container row). IDLE_TIME_NEVER = exempt. + */ +async function getIdleTimeHours({ siteId, hostname, username }) { + const { idleTime } = await getEffectiveResources(siteId, hostname, username); + return idleTime; +} + +/** + * Enqueue a reconfigure job for each provisioned container with this identity, + * unless the resource type isn't applied by the hypervisor. The job derives + * the desired resources (defaults + approvals) itself. + */ +async function applyToExistingContainers({ siteId, hostname, username, resourceType }) { + if (!RESOURCE_POLICIES[resourceType].reconfigures) return; + const containers = await repo.findProvisionedContainers(siteId, hostname, username); + for (const container of containers) { + await repo.createJob({ + command: `node bin/reconfigure-container.js --container-id=${container.id}`, + createdBy: 'system', + status: 'pending', + }); + } +} + +async function create(actor, { siteId, hostname, resourceType, value, comment }) { + const site = await repo.findSiteById(siteId); + if (!site) throw new ApiError(404, 'site_not_found', 'Site not found'); + + const autoApprove = shouldAutoApprove(actor.isAdmin, resourceType, value); + const request = await repo.create({ + siteId: site.id, + hostname, + username: actor.username, + resourceType, + value, + status: autoApprove ? 'approved' : 'pending', + comment: comment || null, + reviewedBy: autoApprove ? (actor.isAdmin ? actor.username : 'system') : null, + reviewedAt: autoApprove ? new Date() : null, + }); + + if (autoApprove) await applyToExistingContainers(request); + return request; +} + +async function findPending(id) { + const request = await repo.findById(id); + if (!request) throw new ApiError(404, 'not_found', 'Request not found'); + if (request.status !== 'pending') { + throw new ApiError(409, 'already_reviewed', 'Request has already been reviewed'); + } + return request; +} + +function review(request, actor, status, adminComment) { + return request.update({ + status, + reviewedBy: actor.username, + reviewedAt: new Date(), + adminComment: adminComment || null, + }); +} + +async function approve(actor, id, { adminComment } = {}) { + const request = await findPending(id); + + if (RESOURCE_POLICIES[request.resourceType].reconfigures) { + const provisioned = await repo.findProvisionedContainers(request.siteId, request.hostname, request.username); + if (provisioned.length === 0) { + throw new ApiError( + 422, + 'container_not_found', + `No provisioned container found for '${request.hostname}' : cannot apply resource changes.`, + ); + } + } + + await review(request, actor, 'approved', adminComment); + await applyToExistingContainers(request); + return request; +} + +async function deny(actor, id, { adminComment } = {}) { + const request = await findPending(id); + return review(request, actor, 'denied', adminComment); +} + +module.exports = { + RESOURCE_POLICIES, + IDLE_TIME_NEVER, + shouldAutoApprove, + list, + countPending, + getEffectiveResources, + getEffectiveResourcesFor, + getIdleTimeHours, + create, + approve, + deny, +}; diff --git a/create-a-container/resources/resource-requests/validator.js b/create-a-container/resources/resource-requests/validator.js new file mode 100644 index 00000000..49a9fd23 --- /dev/null +++ b/create-a-container/resources/resource-requests/validator.js @@ -0,0 +1,47 @@ +const { z } = require('zod'); +const { ResourceRequest } = require('../../models'); + +// JSON clients send numbers, URL/query params and older clients send numeric +// strings. Blank strings and null stay invalid instead of coercing to 0. +const intLike = (schema) => + z.preprocess((v) => (typeof v === 'string' && v.trim() !== '' ? Number(v) : v), schema); + +const siteId = (message) => intLike(z.number({ error: message }).int({ error: message }).positive({ error: message })); +const nonNegativeInt = (message) => intLike(z.number({ error: message }).int({ error: message }).min(0, { error: message })); + +const resourceTypeMessage = `resourceType must be one of: ${ResourceRequest.VALID_RESOURCE_TYPES.join(', ')}`; + +const createRequest = z.object({ + siteId: siteId('siteId is required'), + hostname: z + .string({ error: 'hostname is required' }) + .trim() + .toLowerCase() + .min(1, { error: 'hostname is required' }) + .max(255), + resourceType: z.enum(ResourceRequest.VALID_RESOURCE_TYPES, { error: resourceTypeMessage }), + value: nonNegativeInt('value must be a non-negative integer'), + comment: z.string().nullish(), +}); + +const reviewRequest = z.object({ + adminComment: z.string().nullish(), +}); + +const listQuery = z.object({ + // "closed" is shorthand for approved + denied. + status: z.enum(['pending', 'approved', 'denied', 'closed']).optional(), + siteId: siteId('siteId must be a positive integer').optional(), +}); + +const idParam = z.object({ + id: intLike(z.number().int().positive()), +}); + +const effectiveParams = z.object({ + siteId: siteId('siteId must be a positive integer'), + hostname: z.string().min(1), + username: z.string().min(1), +}); + +module.exports = { createRequest, reviewRequest, listQuery, idParam, effectiveParams }; diff --git a/create-a-container/routers/api/v1/index.js b/create-a-container/routers/api/v1/index.js index 93bd01d0..c36fd9a8 100644 --- a/create-a-container/routers/api/v1/index.js +++ b/create-a-container/routers/api/v1/index.js @@ -94,7 +94,7 @@ router.use('/apikeys', require('../../../resources/apikeys/router')); router.use('/mail-accounts', require('../../../resources/mailaccounts/router')); router.use('/settings', require('./settings')); router.use('/jobs', require('./jobs')); -router.use('/resource-requests', require('./resource-requests')); +router.use('/resource-requests', require('../../../resources/resource-requests/router')); router.use('/notifications', require('../../../resources/notifications/router')); router.use('/services', require('../../../resources/services/router')); diff --git a/create-a-container/routers/api/v1/resource-requests.js b/create-a-container/routers/api/v1/resource-requests.js deleted file mode 100644 index 1c0763cc..00000000 --- a/create-a-container/routers/api/v1/resource-requests.js +++ /dev/null @@ -1,244 +0,0 @@ -/** - * /api/v1/resource-requests — Resource request management. - * Users can request resource adjustments for their containers. - * Admins can view and approve/deny pending requests. - */ - -const express = require('express'); -const { Op } = require('sequelize'); -const { - ResourceRequest, - Container, - Site, -} = require('../../../models'); -const { - apiAuth, - apiAdmin, - asyncHandler, - ok, - created, - ApiError, -} = require('../../../middlewares/api'); - -const router = express.Router(); - -router.use(apiAuth); - -const { RESOURCE_DEFAULTS, VALID_RESOURCE_TYPES } = ResourceRequest; - -/** - * Determine if a request should be auto-approved: - * - Admin users always get auto-approved - * - Requests for values <= the default are auto-approved - */ -function shouldAutoApprove(isAdmin, resourceType, value) { - if (isAdmin) return true; - const defaultValue = RESOURCE_DEFAULTS[resourceType]; - if (defaultValue === undefined) return false; - return value <= defaultValue; -} - -// GET / — list resource requests -// Admins see all (optionally filtered by status), users see only their own -router.get( - '/', - asyncHandler(async (req, res) => { - const where = {}; - if (!req.session.isAdmin) { - where.username = req.session.user; - } - if (req.query.status) { - if (req.query.status === 'closed') { - where.status = { [Op.in]: ['approved', 'denied'] }; - } else { - where.status = req.query.status; - } - } - if (req.query.siteId) { - where.siteId = parseInt(req.query.siteId, 10); - } - const rows = await ResourceRequest.findAll({ - where, - order: [['createdAt', 'DESC']], - include: [{ association: 'site', attributes: ['id', 'name'] }], - }); - return ok(res, rows); - }), -); - -// GET /count — get count of pending requests (for badge display) -router.get( - '/count', - asyncHandler(async (req, res) => { - const count = await ResourceRequest.count({ where: { status: 'pending' } }); - return ok(res, { count }); - }), -); - -// GET /effective/:siteId/:hostname/:username — get effective approved resources -router.get( - '/effective/:siteId/:hostname/:username', - asyncHandler(async (req, res) => { - const { siteId, hostname, username } = req.params; - // Users can only query their own, admins can query any - if (!req.session.isAdmin && username !== req.session.user) { - throw new ApiError(403, 'forbidden', 'Cannot view resources for other users'); - } - const resources = await ResourceRequest.getApprovedResources( - parseInt(siteId, 10), - hostname, - username, - ); - return ok(res, { ...RESOURCE_DEFAULTS, ...resources }); - }), -); - -// POST / — create a resource request -router.post( - '/', - asyncHandler(async (req, res) => { - const { siteId, hostname, resourceType, value, comment } = req.body || {}; - - if (!siteId) throw new ApiError(400, 'invalid_request', 'siteId is required'); - if (!hostname || !hostname.trim()) throw new ApiError(400, 'invalid_request', 'hostname is required'); - if (!resourceType) throw new ApiError(400, 'invalid_request', 'resourceType is required'); - if (!VALID_RESOURCE_TYPES.includes(resourceType)) { - throw new ApiError(400, 'invalid_request', `resourceType must be one of: ${VALID_RESOURCE_TYPES.join(', ')}`); - } - if (value === undefined || value === null || value < 0) { - throw new ApiError(400, 'invalid_request', 'value must be a non-negative integer'); - } - - const site = await Site.findByPk(parseInt(siteId, 10)); - if (!site) throw new ApiError(404, 'site_not_found', 'Site not found'); - - const parsedValue = parseInt(value, 10); - if (!Number.isFinite(parsedValue) || parsedValue < 0) { - throw new ApiError(400, 'invalid_request', 'value must be a non-negative integer'); - } - - const username = req.session.user; - const autoApprove = shouldAutoApprove(req.session.isAdmin, resourceType, parsedValue); - - const request = await ResourceRequest.create({ - siteId: site.id, - hostname: hostname.trim().toLowerCase(), - username, - resourceType, - value: parsedValue, - status: autoApprove ? 'approved' : 'pending', - comment: comment || null, - reviewedBy: autoApprove ? (req.session.isAdmin ? username : 'system') : null, - reviewedAt: autoApprove ? new Date() : null, - }); - - // If auto-approved, apply to any existing matching containers - if (autoApprove) { - await applyResourceToExistingContainers(site.id, request.hostname, username, resourceType, parsedValue); - } - - return created(res, request); - }), -); - -// PUT /:id/approve — admin approves a request -router.put( - '/:id/approve', - apiAdmin, - asyncHandler(async (req, res) => { - const request = await ResourceRequest.findByPk(parseInt(req.params.id, 10)); - if (!request) throw new ApiError(404, 'not_found', 'Request not found'); - if (request.status !== 'pending') { - throw new ApiError(409, 'already_reviewed', 'Request has already been reviewed'); - } - - // Verify at least one provisioned container exists for this request before approving. - // A container is considered provisioned when it has a Proxmox VMID (containerId is not null). - const provisionedContainer = await Container.findOne({ - where: { - siteId: request.siteId, - hostname: request.hostname, - username: request.username, - containerId: { [Op.ne]: null }, - }, - }); - if (!provisionedContainer) { - throw new ApiError( - 422, - 'container_not_found', - `No provisioned container found for '${request.hostname}' : cannot apply resource changes.`, - ); - } - - const { adminComment } = req.body || {}; - - await request.update({ - status: 'approved', - reviewedBy: req.session.user, - reviewedAt: new Date(), - adminComment: adminComment || null, - }); - - // Apply to existing containers - await applyResourceToExistingContainers( - request.siteId, - request.hostname, - request.username, - request.resourceType, - request.value, - ); - - return ok(res, request); - }), -); - -// PUT /:id/deny — admin denies a request -router.put( - '/:id/deny', - apiAdmin, - asyncHandler(async (req, res) => { - const request = await ResourceRequest.findByPk(parseInt(req.params.id, 10)); - if (!request) throw new ApiError(404, 'not_found', 'Request not found'); - if (request.status !== 'pending') { - throw new ApiError(409, 'already_reviewed', 'Request has already been reviewed'); - } - - const { adminComment } = req.body || {}; - - await request.update({ - status: 'denied', - reviewedBy: req.session.user, - reviewedAt: new Date(), - adminComment: adminComment || null, - }); - - return ok(res, request); - }), -); - -/** - * Apply a resource change to existing provisioned containers matching the identity. - * This creates a reconfigure job for each matching container. - */ -async function applyResourceToExistingContainers(siteId, hostname, username, resourceType, value) { - const containers = await Container.findAll({ - // Only containers that exist in Proxmox (have a VMID) can be reconfigured. - // The status column was removed; reconfigure-container.js exits early without - // a containerId, so this is the correct provisioned predicate. - where: { siteId, hostname, username, containerId: { [Op.ne]: null } }, - }); - - if (containers.length === 0) return; - - const { Job } = require('../../../models'); - for (const container of containers) { - await Job.create({ - // The job derives desired resources (defaults + approvals) itself. - command: `node bin/reconfigure-container.js --container-id=${container.id}`, - createdBy: 'system', - status: 'pending', - }); - } -} - -module.exports = router; diff --git a/mie-opensource-landing/docs/admins/core-concepts/containers.md b/mie-opensource-landing/docs/admins/core-concepts/containers.md index 68661155..ef73d477 100644 --- a/mie-opensource-landing/docs/admins/core-concepts/containers.md +++ b/mie-opensource-landing/docs/admins/core-concepts/containers.md @@ -28,6 +28,22 @@ Admins can hand a container to another active user from the container's edit pag The new owner's sharing grant, if any, is removed. The previous owner loses access unless the new owner shares it back. API (admin only): `PUT /api/v1/sites/{siteId}/containers/{id}` with `{ "username": "" }`. +## Resource Requests + +Owners change a container's resources from its **Resources** card; admins review pending requests under **Resource Requests**. Admin requests are always auto-approved. + +| Type | Unit | Default | Auto-approved for non-admins | Applied by | +|------|------|---------|------------------------------|------------| +| `memory` | MB | 8192 | ≤ default | Reconfigure job | +| `swap` | MB | 0 | ≤ default | Reconfigure job | +| `cpus` | count | 4 | ≤ default | Reconfigure job | +| `rootfs` | GB | 50 | ≤ default | Reconfigure job | +| `idleTime` | hours | 72 | 1–72 (`0` = never and > 72 need review) | [Idle shutdown](../../developers/idle-shutdown.md) | + +Approving a reconfigure-job type requires a provisioned container. `idleTime` can be approved before the container exists. Idle time counts only traffic through the proxy, so SSH-only or direct-IP containers look idle; request `idleTime = 0` for those. + +API: `/api/v1/resource-requests` (see the OpenAPI spec at `/api/v1/openapi.json`). + ## Volumes Containers can attach persistent **[volumes](volumes.md)** — bind-mount diff --git a/mie-opensource-landing/docs/developers/idle-shutdown.md b/mie-opensource-landing/docs/developers/idle-shutdown.md new file mode 100644 index 00000000..9b6f9db3 --- /dev/null +++ b/mie-opensource-landing/docs/developers/idle-shutdown.md @@ -0,0 +1,65 @@ +# Idle Shutdown + +Design reference for the idle container shutdown epic ([#525](https://github.com/mieweb/opensource-server/issues/525)): stop containers nobody has reached through the proxy for a while, notify owners, and start them again when a request arrives. + +## Stages + +| Issue | Scope | Status | +|-------|-------|--------| +| [#526](https://github.com/mieweb/opensource-server/issues/526) | `idleTime` resource request | Implemented | +| [#527](https://github.com/mieweb/opensource-server/issues/527) | Periodic sweep job stops idle containers | Planned | +| [#528](https://github.com/mieweb/opensource-server/issues/528) | Owner digest email + bell notification, unsubscribe | Planned | +| [#529](https://github.com/mieweb/opensource-server/issues/529) | Wake-on-request API, hooked into the nginx agent | Planned | +| [#530](https://github.com/mieweb/opensource-server/issues/530) | Container start/stop API and UI buttons | Planned | +| [#531](https://github.com/mieweb/opensource-server/issues/531) | "Please wait" interstitial while a container starts | Planned | + +## Flow + +```mermaid +flowchart TD + req[Client request] --> proxy[nginx proxy] + proxy -->|accounting, at most every 10 min| access["POST /services/:id/last-access
Service.lastAccessedAt"] + proxy -->|container stopped for idle| wake["Wake API (#529)"] + wake --> start[provider.startLxc] + proxy -->|HTML client while starting| wait["Interstitial (#531)"] + + timer[systemd timer] --> job["Job: idle sweep (#527)"] + job --> idle{"idle longer than
getIdleTimeHours()?"} + idle -->|yes| stop["provider.stopLxc
stoppedReason = idle"] + idle -->|no / idleTime = 0| skip[skip] + stop --> notify["Digest + bell (#528)"] + + classDef done fill:#d1fae5,stroke:#059669; + classDef planned fill:#f3f4f6,stroke:#6b7280,stroke-dasharray:4; + class access,start done; + class wake,wait,job,stop,notify planned; +``` + +## Idle Rule + +A running container is idle when: + +``` +now - (max(service.lastAccessedAt) ?? container.createdAt) > idleTime hours +``` + +- `idleTime = 0` exempts the container. +- A container younger than its `idleTime` is never stopped, even if never accessed. +- Only proxied HTTP and TCP/UDP traffic counts. SSH, direct-IP, SRV-only and service-less containers look idle; owners request `idleTime = 0`. + +## Building Blocks + +| Piece | Location | Used by | +|-------|----------|---------| +| `idleTime` default (72 h) | `RESOURCE_DEFAULTS` in `create-a-container/models/resourcerequest.js` | All stages | +| Per-type review/apply rules | `RESOURCE_POLICIES` in `create-a-container/resources/resource-requests/service.js` | #526 | +| Effective `idleTime` for a container | `getIdleTimeHours(container)` in the same service | #527 | +| "Never stop" sentinel | `IDLE_TIME_NEVER` (`0`) in the same service; client mirror in `client/src/lib/resources.ts` | #527, UI | +| Last proxied access | `Service.lastAccessedAt`, set by `resources/services` | #527 | +| Start/stop | `startLxc` / `stopLxc` on the Proxmox, Docker and dummy providers in `create-a-container/utils/` | #527, #529, #530 | + +`idleTime` approval is inverted relative to capacity types: 1–72 hours auto-approves, while longer values and `0` need admin review. It is not a hypervisor setting, so approval enqueues no `reconfigure-container.js` job and does not require a provisioned container. See [Containers — Resource Requests](../admins/core-concepts/containers.md#resource-requests) for the full approval table. + +## Planned State + +#527 adds `stoppedReason` (`idle` | `manual` | null), `stoppedAt`, and `stoppedBy` to `Container`, cleared on start. Wake (#529) only starts containers with `stoppedReason = idle`; manual stops (#530) set `manual`. Update [Database Schema](database-schema.md) when that migration lands. diff --git a/mie-opensource-landing/zensical.toml b/mie-opensource-landing/zensical.toml index 799aebce..e8e69f98 100644 --- a/mie-opensource-landing/zensical.toml +++ b/mie-opensource-landing/zensical.toml @@ -60,6 +60,7 @@ nav = [ { "Release Pipeline" = "developers/release-pipeline.md" }, { "Database Schema" = "developers/database-schema.md" }, { "Agent" = "developers/agent.md" }, + { "Idle Shutdown" = "developers/idle-shutdown.md" }, { "Contributing" = "developers/contributing.md" }, ] }, ] },