mirror of
https://github.com/nestriness/nestri.git
synced 2026-11-27 01:19:56 +02:00
fix(api): rooms book cards atomically, free never gets a non-entry card, slots identify GPUs
Create a room under a per-user advisory lock (limit, card and insert in one transaction) and book cards under per-machine locks. A free plan with no model is placed on an entry card only. Boxes with no card hold their machine's first card; the new migration backfills single-GPU fleet boxes and adds box.gpu_slot. Machine.Gpu accepts slot and renderNode; session.start carries gpuSlot and gpuPciId. A stopped room re-checks its card when a run is requested.
This commit is contained in:
+23
-13
@@ -52,13 +52,17 @@ export namespace BoxApi {
|
||||
pciId: z.string().optional().meta({
|
||||
description: 'With `on: "own"`: the GPU on that host, as `GET /location` lists it'
|
||||
}),
|
||||
slot: z.string().optional().meta({
|
||||
description:
|
||||
'With `on: "own"`: the card’s PCI address, to tell apart cards of one model'
|
||||
}),
|
||||
model: z.string().optional().meta({
|
||||
description: 'With `on: "fleet"`: the GPU model, as `GET /location` lists it'
|
||||
})
|
||||
})
|
||||
),
|
||||
async (c) => {
|
||||
const { label, tier, on, machineId, pciId, model } = c.req.valid('json');
|
||||
const { label, tier, on, machineId, pciId, slot, model } = c.req.valid('json');
|
||||
const userId = Actor.userID;
|
||||
if (on === 'own' && Boolean(machineId) !== Boolean(pciId)) {
|
||||
throw new VisibleError(
|
||||
@@ -68,6 +72,8 @@ export namespace BoxApi {
|
||||
machineId ? 'pciId' : 'machineId'
|
||||
);
|
||||
}
|
||||
let guard: (() => Promise<void>) | undefined;
|
||||
let placer: Placement.Placer;
|
||||
if (on === 'fleet') {
|
||||
// Plans count cloud rooms; your own GPUs are never limited.
|
||||
const team = await Team.personalFor(userId);
|
||||
@@ -75,21 +81,25 @@ export namespace BoxApi {
|
||||
if (model && !Rooms.mayUseModel(plan, model)) {
|
||||
throw Rooms.needsPro(model);
|
||||
}
|
||||
if ((await Billing.cloudRooms(userId)) >= Rooms.allowed(plan)) {
|
||||
throw Rooms.atLimit(model ?? null, plan);
|
||||
}
|
||||
}
|
||||
const placer =
|
||||
on === 'fleet'
|
||||
? model
|
||||
? Placement.onFleetModel(model)
|
||||
: Placement.fleet
|
||||
: machineId && pciId
|
||||
? Placement.onOwn({ machineId, pciId })
|
||||
// Runs inside the creation transaction, under the person's lock.
|
||||
guard = async () => {
|
||||
if ((await Billing.cloudRooms(userId)) >= Rooms.allowed(plan)) {
|
||||
throw Rooms.atLimit(model ?? null, plan);
|
||||
}
|
||||
};
|
||||
placer = model
|
||||
? Placement.onFleetModel(model)
|
||||
: Placement.onFleetAny({ entryOnly: !Rooms.isPro(plan) });
|
||||
} else {
|
||||
placer =
|
||||
machineId && pciId
|
||||
? Placement.onOwn({ machineId, pciId, slot })
|
||||
: Placement.onlyHost;
|
||||
}
|
||||
const box = await Box.createPlaced(
|
||||
{ id: Identifier.ascending('box'), userId, label, tier },
|
||||
placer
|
||||
placer,
|
||||
guard
|
||||
);
|
||||
return c.json({ data: box }, 201);
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import { ErrorCodes, VisibleError } from '@nestri/core/error';
|
||||
import { Examples } from '@nestri/core/examples';
|
||||
import { Game } from '@nestri/core/game/index';
|
||||
import { Identifier } from '@nestri/core/id';
|
||||
import { Placement } from '@nestri/core/box/placement';
|
||||
import { Session } from '@nestri/core/session/index';
|
||||
import { Launch } from '@nestri/core/session/launch';
|
||||
import { Team } from '@nestri/core/team/index';
|
||||
@@ -287,6 +288,10 @@ export namespace SessionApi {
|
||||
conflict(Session.BOX_BUSY);
|
||||
}
|
||||
|
||||
// A stopped cloud room gave its card up: hold one again (its own,
|
||||
// or the same model elsewhere) or refuse with 429.
|
||||
await Placement.reclaim(box.id);
|
||||
|
||||
// Plans count rooms, not time: nothing here refuses a run for time
|
||||
// spent. The standing is returned so a client can show it.
|
||||
const payer = await Billing.teamForBox(box.id);
|
||||
|
||||
@@ -266,3 +266,95 @@ describe('the idle limit', () => {
|
||||
expect((await Box.fromID(box.id))!.state).toBe('running');
|
||||
});
|
||||
});
|
||||
|
||||
describe('review blockers on rooms', () => {
|
||||
test('free with no model is placed on an entry card only', async () => {
|
||||
await fleet([[BIG], [V710]]);
|
||||
const p = await person('free-any');
|
||||
const res = await post(p.headers, { on: 'fleet' });
|
||||
expect(res.status).toBe(201);
|
||||
expect((await json(res)).data.gpuPciId).toBe(V710.pciId);
|
||||
|
||||
const only = await fleet([[BIG]]);
|
||||
const q = await person('free-none');
|
||||
const refused = await post(q.headers, { on: 'fleet' });
|
||||
expect(refused.status).toBe(429);
|
||||
expect(only.machines.length).toBe(1);
|
||||
});
|
||||
|
||||
test('two concurrent POST /box for a free user: exactly one room', async () => {
|
||||
await fleet([[V710], [V710], [V710]]);
|
||||
const p = await person('race-limit');
|
||||
const res = await Promise.all([
|
||||
post(p.headers, { on: 'fleet', model: V710.model }),
|
||||
post(p.headers, { on: 'fleet', model: V710.model })
|
||||
]);
|
||||
expect(res.map((r) => r.status).sort()).toEqual([201, 403]);
|
||||
expect(await Box.onFleet({ userId: p.owner.userId, organisationId: Env.get().FLEET_ORGANISATION_ID! }))
|
||||
.toHaveLength(1);
|
||||
});
|
||||
|
||||
test('two people racing for the last card: one gets it', async () => {
|
||||
await fleet([[V710]]);
|
||||
const a = await person('race-a');
|
||||
const b = await person('race-b');
|
||||
const res = await Promise.all([
|
||||
post(a.headers, { on: 'fleet', model: V710.model }),
|
||||
post(b.headers, { on: 'fleet', model: V710.model })
|
||||
]);
|
||||
expect(res.map((r) => r.status).sort()).toEqual([201, 429]);
|
||||
});
|
||||
|
||||
test('a box with no card holds its machine’s first card; slots tell identical cards apart', async () => {
|
||||
const f = await fleet([[V710]]);
|
||||
const legacy = await person('legacy');
|
||||
await Box.create({
|
||||
id: Identifier.ascending('box'),
|
||||
userId: legacy.owner.userId,
|
||||
machineId: f.machines[0]!.id,
|
||||
gpuPciId: null,
|
||||
label: 'old',
|
||||
tier: 'md'
|
||||
});
|
||||
const other = await person('legacy-other', 'paid');
|
||||
expect((await post(other.headers, { on: 'fleet', model: V710.model })).status).toBe(429);
|
||||
const loc = (await json(await app.request('/location', { headers: other.headers }))).data;
|
||||
expect(loc.fleet[0].available).toBe(false);
|
||||
|
||||
const g = await fleet([[
|
||||
{ ...V710, slot: '0000:45:00.0' },
|
||||
{ ...V710, slot: '0000:46:00.0' }
|
||||
]]);
|
||||
const p = await person('slots', 'paid');
|
||||
const one = (await json(await post(p.headers, { on: 'fleet', model: V710.model }))).data;
|
||||
const two = (await json(await post(p.headers, { on: 'fleet', model: V710.model }))).data;
|
||||
expect([one.gpuSlot, two.gpuSlot].sort()).toEqual(['0000:45:00.0', '0000:46:00.0']);
|
||||
expect(g.machines.length).toBe(1);
|
||||
const jobs = (await import('@nestri/core/session/index')).Session;
|
||||
expect(jobs.StartJob.shape.gpuSlot).toBeDefined();
|
||||
});
|
||||
|
||||
test('a stopped room whose card was taken is re-placed on the same model, or refused', async () => {
|
||||
const f = await fleet([[V710], [V710]]);
|
||||
const a = await person('reclaim-a');
|
||||
const room = (await json(await post(a.headers, { on: 'fleet', model: V710.model }))).data;
|
||||
await Box.setState({ id: room.id, state: 'stopped', stopReason: 'idle for 3 hours', stopClean: true });
|
||||
const b = await person('reclaim-b');
|
||||
const bBox = (await json(await post(b.headers, { on: 'fleet', model: V710.model }))).data;
|
||||
const c = await person('reclaim-c', 'paid');
|
||||
const cBox = (await json(await post(c.headers, { on: 'fleet', model: V710.model }))).data;
|
||||
expect(cBox.machineId).toBe(room.machineId);
|
||||
expect(bBox.machineId).not.toBe(room.machineId);
|
||||
|
||||
const { Placement } = await import('@nestri/core/box/placement');
|
||||
await expect(Placement.reclaim(room.id)).rejects.toThrow(/free right now/);
|
||||
expect((await Box.fromID(room.id))!.state).toBe('stopped');
|
||||
|
||||
await Box.setState({ id: bBox.id, state: 'stopped', stopReason: 'x', stopClean: true });
|
||||
await Placement.reclaim(room.id);
|
||||
const moved = (await Box.fromID(room.id))!;
|
||||
expect(moved.machineId).toBe(bBox.machineId);
|
||||
expect(moved.state).toBe('created');
|
||||
expect(f.machines.length).toBe(2);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -442,7 +442,9 @@ describe('GET /machine/jobs', () => {
|
||||
steamAppId: 5520,
|
||||
linkedAccountId: s.owner.linkedAccountId,
|
||||
userId: s.owner.userId,
|
||||
launchId: body.data.launches[0].id
|
||||
launchId: body.data.launches[0].id,
|
||||
gpuSlot: null,
|
||||
gpuPciId: null
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
ALTER TABLE "box" ADD COLUMN "gpu_slot" text;
|
||||
--> statement-breakpoint
|
||||
-- Boxes made before a box named its card hold one card of their machine.
|
||||
-- Where the machine has exactly one GPU that card is known, so name it.
|
||||
UPDATE "box" SET "gpu_pci_id" = m."gpus"->0->>'pciId'
|
||||
FROM "machine" m
|
||||
WHERE "box"."machine_id" = m."id"
|
||||
AND "box"."gpu_pci_id" IS NULL
|
||||
AND m."organisation_id" IS NOT NULL
|
||||
AND jsonb_typeof(m."gpus") = 'array'
|
||||
AND jsonb_array_length(m."gpus") = 1;
|
||||
File diff suppressed because it is too large
Load Diff
@@ -211,6 +211,13 @@
|
||||
"when": 1792436256695,
|
||||
"tag": "0029_box_gpu_pci_id",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 30,
|
||||
"version": "7",
|
||||
"when": 1792436540630,
|
||||
"tag": "0030_box_gpu_slot",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -63,6 +63,12 @@ export const BoxTable = pgTable(
|
||||
* (`vendor:device`). Null on boxes made before a box named its card.
|
||||
*/
|
||||
gpuPciId: text('gpu_pci_id'),
|
||||
/**
|
||||
* The card's PCI address on that host (`0000:45:00.0`), when the host
|
||||
* reports slots. Told apart from `gpuPciId`, which is only vendor:device
|
||||
* and is the same for every card of one model.
|
||||
*/
|
||||
gpuSlot: text('gpu_slot'),
|
||||
tier: BoxTier('tier').notNull().default('md'),
|
||||
state: BoxState('state').notNull().default('created'),
|
||||
/** Why it stopped, verbatim from the agent. Null while it has never run. */
|
||||
|
||||
@@ -38,6 +38,11 @@ export namespace Box {
|
||||
'The GPU on its host the box is pinned to (`vendor:device`). Null for a box made before boxes named a card',
|
||||
example: null
|
||||
}),
|
||||
gpuSlot: z.string().nullable().optional().meta({
|
||||
description:
|
||||
'The PCI address of that card on its host, when the host reports slots. Null otherwise',
|
||||
example: null
|
||||
}),
|
||||
label: z.string().meta({
|
||||
description: 'Editable display name. Not unique, and not the DNS label',
|
||||
example: Examples.Box.label
|
||||
@@ -87,6 +92,7 @@ export namespace Box {
|
||||
userId: true,
|
||||
machineId: true,
|
||||
gpuPciId: true,
|
||||
gpuSlot: true,
|
||||
label: true,
|
||||
tier: true
|
||||
}),
|
||||
@@ -99,6 +105,7 @@ export namespace Box {
|
||||
userId: input.userId,
|
||||
machineId: input.machineId,
|
||||
gpuPciId: input.gpuPciId ?? null,
|
||||
gpuSlot: input.gpuSlot ?? null,
|
||||
label: input.label,
|
||||
tier: input.tier
|
||||
})
|
||||
@@ -119,16 +126,26 @@ export namespace Box {
|
||||
*/
|
||||
export const createPlaced = async (
|
||||
input: { id: string; userId: string; label: string; tier: Info['tier'] },
|
||||
placer?: Placement.Placer
|
||||
placer?: Placement.Placer,
|
||||
guard?: () => Promise<void>
|
||||
) => {
|
||||
const placed = await Placement.choose({ userId: input.userId, tier: input.tier }, placer);
|
||||
return create({
|
||||
id: input.id,
|
||||
userId: input.userId,
|
||||
machineId: placed.machineId,
|
||||
gpuPciId: placed.gpuPciId,
|
||||
label: input.label,
|
||||
tier: input.tier
|
||||
// One transaction under a per-person lock: the limit check, the card
|
||||
// choice and the insert are one step, so two requests from one person
|
||||
// cannot both pass a limit of one. Card booking is locked per machine
|
||||
// inside the placer.
|
||||
return Database.transaction(async () => {
|
||||
await Placement.lock([`user:${input.userId}`]);
|
||||
await guard?.();
|
||||
const placed = await Placement.choose({ userId: input.userId, tier: input.tier }, placer);
|
||||
return create({
|
||||
id: input.id,
|
||||
userId: input.userId,
|
||||
machineId: placed.machineId,
|
||||
gpuPciId: placed.gpuPciId,
|
||||
gpuSlot: placed.gpuSlot ?? null,
|
||||
label: input.label,
|
||||
tier: input.tier
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
@@ -488,6 +505,7 @@ export namespace Box {
|
||||
userId: input.userId,
|
||||
machineId: input.machineId,
|
||||
gpuPciId: input.gpuPciId,
|
||||
gpuSlot: input.gpuSlot,
|
||||
label: input.label,
|
||||
tier: input.tier as Info['tier'],
|
||||
state: input.state as Info['state'],
|
||||
|
||||
@@ -16,6 +16,9 @@ export namespace Location {
|
||||
.object({
|
||||
machineId: z.string().meta({ description: 'The host the card is in' }),
|
||||
pciId: z.string().meta({ description: 'vendor:device, as the host reported it' }),
|
||||
slot: z.string().nullable().meta({
|
||||
description: 'PCI address on the host, when it reports one. Tells apart cards of one model'
|
||||
}),
|
||||
model: z.string().meta({ description: 'What the card is called' }),
|
||||
vramMib: z.number().int().nullable().meta({ description: 'Card memory in MiB, if reported' }),
|
||||
online: z.boolean().meta({ description: 'Whether its host is reporting in' })
|
||||
@@ -48,6 +51,7 @@ export namespace Location {
|
||||
(m.gpus ?? []).map((g) => ({
|
||||
machineId: m.id,
|
||||
pciId: g.pciId,
|
||||
slot: g.slot ?? null,
|
||||
model: g.model,
|
||||
vramMib: g.vramMib ?? null,
|
||||
online: Machine.isOnline(m.lastSeen ?? null)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { and, count, eq, inArray, isNotNull, isNull, ne } from 'drizzle-orm';
|
||||
import { and, count, eq, inArray, isNull, ne, sql } from 'drizzle-orm';
|
||||
import z from 'zod';
|
||||
|
||||
import { Database } from '../db/index.js';
|
||||
@@ -6,6 +6,7 @@ import { Env } from '../env.js';
|
||||
import { ErrorCodes, VisibleError } from '../error.js';
|
||||
import { Machine } from '../machine/index.js';
|
||||
import { MachineTable } from '../machine/machine.sql.js';
|
||||
import { Rooms } from '../billing/rooms.js';
|
||||
import { BoxTable, BoxTier } from './box.sql.js';
|
||||
|
||||
/**
|
||||
@@ -42,6 +43,22 @@ export namespace Placement {
|
||||
export interface Placed {
|
||||
machineId: string;
|
||||
gpuPciId: string | null;
|
||||
/** The card's PCI address, when its host reports slots. */
|
||||
gpuSlot?: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Serialise whoever books the same thing, for the rest of the transaction.
|
||||
* Keyed by a name (`user:<id>`, `machine:<id>`); in a transaction it is
|
||||
* released at commit, outside one it is a no-op. Always take several in
|
||||
* sorted order.
|
||||
*/
|
||||
export async function lock(keys: string[]) {
|
||||
for (const key of [...new Set(keys)].sort()) {
|
||||
await Database.use((tx) =>
|
||||
tx.execute(sql`select pg_advisory_xact_lock(hashtextextended(${key}, 0))`)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -156,94 +173,172 @@ export namespace Placement {
|
||||
* with the same answer for both so a stranger's host id learns nothing.
|
||||
*/
|
||||
export const onOwn =
|
||||
(target: { machineId: string; pciId: string }): Placer =>
|
||||
(target: { machineId: string; pciId: string; slot?: string }): Placer =>
|
||||
async (request) => {
|
||||
const host = (await Machine.listByOwner(request.userId)).find(
|
||||
(m) => m.id === target.machineId
|
||||
);
|
||||
if (!host || !host.gpus?.some((g) => g.pciId === target.pciId)) {
|
||||
const cards = (host?.gpus ?? []).filter(
|
||||
(g) => g.pciId === target.pciId && (!target.slot || g.slot === target.slot)
|
||||
);
|
||||
if (!host || cards.length === 0) {
|
||||
throw new VisibleError(
|
||||
'not_found',
|
||||
ErrorCodes.NotFound.RESOURCE_NOT_FOUND,
|
||||
'No such GPU on a host of yours'
|
||||
);
|
||||
}
|
||||
return { machineId: host.id, gpuPciId: target.pciId };
|
||||
return {
|
||||
machineId: host.id,
|
||||
gpuPciId: target.pciId,
|
||||
gpuSlot: target.slot ?? (cards.length === 1 ? (cards[0]!.slot ?? null) : null)
|
||||
};
|
||||
};
|
||||
|
||||
type Gpu = NonNullable<Machine.Info['gpus']>[number];
|
||||
interface Held {
|
||||
gpuPciId: string | null;
|
||||
gpuSlot: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Which of a machine's cards the boxes on it hold, as booleans in `gpus`
|
||||
* order. Boxes that name a slot hold that card; boxes that name only a
|
||||
* model hold the first unheld card of it; boxes from before a box named a
|
||||
* card (null) hold one card of the machine's first GPU, since all they
|
||||
* were ever given was that.
|
||||
*/
|
||||
export function heldCards(gpus: readonly Gpu[], boxes: readonly Held[]): boolean[] {
|
||||
const taken = gpus.map(() => false);
|
||||
const take = (match: (g: Gpu) => boolean) => {
|
||||
const i = gpus.findIndex((g, n) => !taken[n] && match(g));
|
||||
if (i >= 0) taken[i] = true;
|
||||
};
|
||||
for (const b of boxes) if (b.gpuSlot) take((g) => g.slot === b.gpuSlot);
|
||||
for (const b of boxes) if (!b.gpuSlot && b.gpuPciId) take((g) => g.pciId === b.gpuPciId);
|
||||
const first = gpus[0]?.pciId;
|
||||
for (const b of boxes) if (!b.gpuSlot && !b.gpuPciId && first) take((g) => g.pciId === first);
|
||||
return taken;
|
||||
}
|
||||
|
||||
export interface Card {
|
||||
machineId: string;
|
||||
pciId: string;
|
||||
slot: string | null;
|
||||
model: string;
|
||||
vramMib: number | null;
|
||||
online: boolean;
|
||||
free: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* The fleet's GPUs, one entry per card, with whether each is free: online
|
||||
* host, and no room on it that is not stopped. Cards of one model on one
|
||||
* host that share a `vendor:device` id are told apart only by count.
|
||||
* host, and no room on it that is not stopped.
|
||||
*/
|
||||
export async function fleetCards(organisationId: string) {
|
||||
export async function fleetCards(organisationId: string): Promise<Card[]> {
|
||||
const machines = await Machine.listByOrganisation(organisationId);
|
||||
const pinned = await Database.use((tx) =>
|
||||
tx
|
||||
.select({
|
||||
machineId: BoxTable.machineId,
|
||||
pci: BoxTable.gpuPciId,
|
||||
held: count()
|
||||
})
|
||||
.from(BoxTable)
|
||||
.where(
|
||||
and(
|
||||
inArray(
|
||||
BoxTable.machineId,
|
||||
machines.map((m) => m.id)
|
||||
),
|
||||
isNull(BoxTable.timeDeleted),
|
||||
ne(BoxTable.state, 'stopped'),
|
||||
isNotNull(BoxTable.gpuPciId)
|
||||
)
|
||||
)
|
||||
.groupBy(BoxTable.machineId, BoxTable.gpuPciId)
|
||||
);
|
||||
const held = new Map(pinned.map((p) => [`${p.machineId}/${p.pci}`, p.held]));
|
||||
const cards: {
|
||||
machineId: string;
|
||||
pciId: string;
|
||||
model: string;
|
||||
vramMib: number | null;
|
||||
online: boolean;
|
||||
free: boolean;
|
||||
}[] = [];
|
||||
const rows =
|
||||
machines.length === 0
|
||||
? []
|
||||
: await Database.use((tx) =>
|
||||
tx
|
||||
.select({
|
||||
machineId: BoxTable.machineId,
|
||||
gpuPciId: BoxTable.gpuPciId,
|
||||
gpuSlot: BoxTable.gpuSlot
|
||||
})
|
||||
.from(BoxTable)
|
||||
.where(
|
||||
and(
|
||||
inArray(
|
||||
BoxTable.machineId,
|
||||
machines.map((m) => m.id)
|
||||
),
|
||||
isNull(BoxTable.timeDeleted),
|
||||
ne(BoxTable.state, 'stopped')
|
||||
)
|
||||
)
|
||||
);
|
||||
const cards: Card[] = [];
|
||||
for (const m of machines) {
|
||||
const online = Machine.isOnline(m.lastSeen ?? null);
|
||||
const taken = new Map<string, number>();
|
||||
for (const g of m.gpus ?? []) {
|
||||
const seen = taken.get(g.pciId) ?? 0;
|
||||
taken.set(g.pciId, seen + 1);
|
||||
const gpus = m.gpus ?? [];
|
||||
const taken = heldCards(
|
||||
gpus,
|
||||
rows.filter((r) => r.machineId === m.id)
|
||||
);
|
||||
gpus.forEach((g, i) =>
|
||||
cards.push({
|
||||
machineId: m.id,
|
||||
pciId: g.pciId,
|
||||
slot: g.slot ?? null,
|
||||
model: g.model,
|
||||
vramMib: g.vramMib ?? null,
|
||||
online,
|
||||
// The n-th identical card is free when fewer than n rooms hold that id.
|
||||
free: online && (held.get(`${m.id}/${g.pciId}`) ?? 0) < seen + 1
|
||||
});
|
||||
}
|
||||
free: online && !taken[i]
|
||||
})
|
||||
);
|
||||
}
|
||||
return cards;
|
||||
}
|
||||
|
||||
function fleetOrganisation() {
|
||||
const organisationId = Env.get().FLEET_ORGANISATION_ID;
|
||||
if (!organisationId) {
|
||||
throw new VisibleError(
|
||||
'internal',
|
||||
ErrorCodes.Server.SERVICE_UNAVAILABLE,
|
||||
'Nestri GPUs are not available on this deployment'
|
||||
);
|
||||
}
|
||||
return organisationId;
|
||||
}
|
||||
|
||||
/** Free cards, after taking the booking lock of every fleet machine. */
|
||||
async function lockedFreeCards(organisationId: string) {
|
||||
await lock(
|
||||
(await Machine.listByOrganisation(organisationId)).map((m) => `machine:${m.id}`)
|
||||
);
|
||||
return (await fleetCards(organisationId)).filter((c) => c.free);
|
||||
}
|
||||
|
||||
/** Of free cards, the one on the machine holding the fewest boxes for its slots. */
|
||||
async function leastLoaded(free: Card[]): Promise<Card> {
|
||||
const ids = [...new Set(free.map((c) => c.machineId))];
|
||||
const counts = await Database.use((tx) =>
|
||||
tx
|
||||
.select({
|
||||
id: MachineTable.id,
|
||||
slots: MachineTable.slots,
|
||||
boxes: count(BoxTable.id)
|
||||
})
|
||||
.from(MachineTable)
|
||||
.leftJoin(
|
||||
BoxTable,
|
||||
and(eq(BoxTable.machineId, MachineTable.id), isNull(BoxTable.timeDeleted))
|
||||
)
|
||||
.where(inArray(MachineTable.id, ids))
|
||||
.groupBy(MachineTable.id)
|
||||
);
|
||||
const load = new Map(counts.map((c) => [c.id, c.boxes / Math.max(1, c.slots ?? 1)]));
|
||||
return [...free].sort((a, b) => (load.get(a.machineId) ?? 0) - (load.get(b.machineId) ?? 0))[0]!;
|
||||
}
|
||||
|
||||
const placedOn = (c: Card): Placed => ({
|
||||
machineId: c.machineId,
|
||||
gpuPciId: c.pciId,
|
||||
gpuSlot: c.slot
|
||||
});
|
||||
|
||||
/**
|
||||
* Place it on a fleet GPU of one model: of the hosts with a free card of
|
||||
* that model, the one holding the fewest boxes for its slots.
|
||||
* that model, the one holding the fewest boxes for its slots. Cards are
|
||||
* booked under a per-machine lock, so two callers never get the same one.
|
||||
*/
|
||||
export const onFleetModel =
|
||||
(model: string): Placer =>
|
||||
async () => {
|
||||
const organisationId = Env.get().FLEET_ORGANISATION_ID;
|
||||
if (!organisationId) {
|
||||
throw new VisibleError(
|
||||
'internal',
|
||||
ErrorCodes.Server.SERVICE_UNAVAILABLE,
|
||||
'Nestri GPUs are not available on this deployment'
|
||||
);
|
||||
}
|
||||
const free = (await fleetCards(organisationId)).filter((c) => c.model === model && c.free);
|
||||
const free = (await lockedFreeCards(fleetOrganisation())).filter((c) => c.model === model);
|
||||
if (free.length === 0) {
|
||||
throw new VisibleError(
|
||||
'rate_limit',
|
||||
@@ -251,29 +346,96 @@ export namespace Placement {
|
||||
`No ${model} is free right now. Try again in a few minutes`
|
||||
);
|
||||
}
|
||||
const ids = [...new Set(free.map((c) => c.machineId))];
|
||||
const counts = await Database.use((tx) =>
|
||||
tx
|
||||
.select({
|
||||
id: MachineTable.id,
|
||||
slots: MachineTable.slots,
|
||||
boxes: count(BoxTable.id)
|
||||
})
|
||||
.from(MachineTable)
|
||||
.leftJoin(
|
||||
BoxTable,
|
||||
and(eq(BoxTable.machineId, MachineTable.id), isNull(BoxTable.timeDeleted))
|
||||
)
|
||||
.where(inArray(MachineTable.id, ids))
|
||||
.groupBy(MachineTable.id)
|
||||
);
|
||||
const load = new Map(counts.map((c) => [c.id, c.boxes / Math.max(1, c.slots ?? 1)]));
|
||||
const pick = [...free].sort(
|
||||
(a, b) => (load.get(a.machineId) ?? 0) - (load.get(b.machineId) ?? 0)
|
||||
)[0]!;
|
||||
return { machineId: pick.machineId, gpuPciId: pick.pciId };
|
||||
return placedOn(await leastLoaded(free));
|
||||
};
|
||||
|
||||
/**
|
||||
* Place it on whichever fleet card is free and least loaded, when no model
|
||||
* was named. With `entryOnly` (every plan but Pro) only entry models are
|
||||
* considered. A fleet whose hosts report no cards at all (nothing to protect) falls back to
|
||||
* {@link fleet}, which places on a machine and names no card.
|
||||
*/
|
||||
export const onFleetAny =
|
||||
(opts: { entryOnly: boolean }): Placer =>
|
||||
async (request) => {
|
||||
const organisationId = fleetOrganisation();
|
||||
const free = (await lockedFreeCards(organisationId)).filter(
|
||||
(c) => !opts.entryOnly || Rooms.isEntry(c.model)
|
||||
);
|
||||
if (free.length === 0) {
|
||||
const reported = (await fleetCards(organisationId)).length > 0;
|
||||
if (!reported) return fleet(request);
|
||||
throw new VisibleError(
|
||||
'rate_limit',
|
||||
ErrorCodes.Server.SERVICE_UNAVAILABLE,
|
||||
'No Nestri GPU is free right now. Try again in a few minutes'
|
||||
);
|
||||
}
|
||||
return placedOn(await leastLoaded(free));
|
||||
};
|
||||
|
||||
/**
|
||||
* A stopped room is about to run again: make sure a card is held for it.
|
||||
* Its own card when still free, else a free card of the same model
|
||||
* elsewhere, else a refusal (429, SERVICE_UNAVAILABLE). Holding is a state
|
||||
* change to `created`, so nobody else is placed on the card meanwhile.
|
||||
* Does nothing for a box that is not stopped or not on the fleet.
|
||||
*/
|
||||
export async function reclaim(boxId: string): Promise<void> {
|
||||
const organisationId = Env.get().FLEET_ORGANISATION_ID;
|
||||
if (!organisationId) return;
|
||||
await Database.transaction(async () => {
|
||||
const machines = await Machine.listByOrganisation(organisationId);
|
||||
await lock(machines.map((m) => `machine:${m.id}`));
|
||||
const box = await Database.use((tx) =>
|
||||
tx
|
||||
.select()
|
||||
.from(BoxTable)
|
||||
.where(and(eq(BoxTable.id, boxId), isNull(BoxTable.timeDeleted)))
|
||||
.then((r) => r[0])
|
||||
);
|
||||
if (!box || box.state !== 'stopped') return;
|
||||
const home = machines.find((m) => m.id === box.machineId);
|
||||
if (!home) return;
|
||||
const cards = await fleetCards(organisationId);
|
||||
const first = home.gpus?.[0];
|
||||
const pci = box.gpuPciId ?? first?.pciId ?? null;
|
||||
const mine = cards.find(
|
||||
(c) =>
|
||||
c.machineId === box.machineId &&
|
||||
c.free &&
|
||||
(box.gpuSlot ? c.slot === box.gpuSlot : c.pciId === pci)
|
||||
);
|
||||
const model = (home.gpus ?? []).find((g) => g.pciId === pci)?.model ?? first?.model;
|
||||
const target =
|
||||
mine ??
|
||||
(model && cards.find((c) => c.free && c.model === model
|
||||
)
|
||||
? await leastLoaded(cards.filter((c) => c.free && c.model === model))
|
||||
: null);
|
||||
if (!target) {
|
||||
throw new VisibleError(
|
||||
'rate_limit',
|
||||
ErrorCodes.Server.SERVICE_UNAVAILABLE,
|
||||
`No ${model ?? 'Nestri GPU'} is free right now. Try again in a few minutes`
|
||||
);
|
||||
}
|
||||
await Database.use((tx) =>
|
||||
tx
|
||||
.update(BoxTable)
|
||||
.set({
|
||||
state: 'created',
|
||||
stopReason: null,
|
||||
stopClean: null,
|
||||
machineId: target.machineId,
|
||||
gpuPciId: target.pciId,
|
||||
gpuSlot: target.slot
|
||||
})
|
||||
.where(eq(BoxTable.id, boxId))
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/** Place a box, using `onlyHost` unless a caller supplies its own placer. */
|
||||
export async function choose(request: Request, placer: Placer = onlyHost): Promise<Placed> {
|
||||
return placer(Request.parse(request));
|
||||
|
||||
@@ -57,7 +57,20 @@ export namespace Machine {
|
||||
.meta({
|
||||
description: 'vendor:device, the ids the model was looked up by',
|
||||
example: '1002:7590'
|
||||
})
|
||||
}),
|
||||
slot: z
|
||||
.string()
|
||||
.regex(/^[0-9a-f]{4}:[0-9a-f]{2}:[0-9a-f]{2}\.[0-7]$/)
|
||||
.optional()
|
||||
.meta({
|
||||
description:
|
||||
'The card’s PCI address on the host. Tells apart cards of one model; absent from hosts that do not report it',
|
||||
example: '0000:45:00.0'
|
||||
}),
|
||||
renderNode: z.string().max(64).optional().meta({
|
||||
description: 'The card’s DRM render node on the host. Absent when not reported',
|
||||
example: '/dev/dri/renderD132'
|
||||
})
|
||||
})
|
||||
.meta({ ref: 'Gpu' });
|
||||
|
||||
|
||||
@@ -101,7 +101,7 @@ export const MachineTable = pgTable(
|
||||
// calls the machine ("AMD Radeon RX 9060 XT"), and the first measured part
|
||||
// of the capacity a scheduler will place by. Null until a report carries
|
||||
// them; never filled in by guessing.
|
||||
gpus: jsonb('gpus').$type<{ model: string; vramMib?: number; pciId: string }[]>(),
|
||||
gpus: jsonb('gpus').$type<{ model: string; vramMib?: number; pciId: string; slot?: string; renderNode?: string }[]>(),
|
||||
// How many runs this host will hold at once, as its last heartbeat said.
|
||||
// Null for an agent that does not say, which is handed every waiting
|
||||
// run as before; a number is what makes the rest wait their turn.
|
||||
|
||||
@@ -479,6 +479,15 @@ export namespace Session {
|
||||
description:
|
||||
'The run’s first launch: the game above. Report its exit against it, and give it to the launched process as `NESTRI_LAUNCH_ID`. Null only for a run older than launches',
|
||||
example: Examples.Launch.id
|
||||
}),
|
||||
gpuSlot: z.string().nullable().optional().meta({
|
||||
description:
|
||||
'The PCI address of the card the box is pinned to. Preferred over `gpuPciId` when present; null when the box or its host never named one',
|
||||
example: null
|
||||
}),
|
||||
gpuPciId: z.string().nullable().optional().meta({
|
||||
description: 'The card as vendor:device, for a host that does not report slots',
|
||||
example: null
|
||||
})
|
||||
})
|
||||
.meta({
|
||||
@@ -598,7 +607,9 @@ export namespace Session {
|
||||
steamAppId: row.game.steamAppId,
|
||||
linkedAccountId: row.session.linkedAccountId,
|
||||
userId: row.box.userId,
|
||||
launchId: row.launchId
|
||||
launchId: row.launchId,
|
||||
gpuSlot: row.box.gpuSlot,
|
||||
gpuPciId: row.box.gpuPciId
|
||||
}))
|
||||
)
|
||||
);
|
||||
|
||||
Reference in New Issue
Block a user