Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 14 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,19 @@ yarn --cwd packages/app add @noderings/backstage-plugin-noderings
yarn --cwd packages/backend add @noderings/backstage-plugin-noderings-backend @noderings/backstage-plugin-scaffolder-backend-module-noderings
```

Apps created with `@backstage/create-app` 0.9 or later set `npmMinimalAgeGate: 3d` in
`.yarnrc.yml`, so Yarn refuses a package version until it is three days old (`The version for
tag "latest" is quarantined`). To install a fresh release, add the packages to
`npmPreapprovedPackages`:

```yaml
# .yarnrc.yml
npmPreapprovedPackages:
- '@backstage/*'
- '@noderings/*'
- noderings
```

```ts
// packages/backend/src/index.ts
backend.add(import('@noderings/backstage-plugin-noderings-backend'));
Expand Down Expand Up @@ -177,7 +190,7 @@ registration to you (commented `publish:github` and `catalog:register` steps). R
| ----------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `noderings:vm:create` | **Orders a billed server.** Checks the plan and region allowlists, sends the order with an idempotency key stored in a task checkpoint (a retried task never orders a second server), tags it for the entity and waits until it runs. Dry run reads the plan and orders nothing. |
| `noderings:vm:delete` | **Permanent.** Only registered with `scaffolder.allowDelete: true`, only for servers with a `backstage-` tag, and only when `confirmHostname` matches. Snapshots and backups are deleted with the server; if it is the last server on its subscription, the subscription is cancelled with a final usage charge. |
| `noderings:dns:record:upsert` | Writes an `A`, `AAAA`, `CNAME`, `MX` or `TXT` record set. Refuses to replace a different existing record set unless `allowOverwrite: true`. |
| `noderings:dns:record:upsert` | Writes an `A`, `AAAA`, `CNAME`, `MX` or `TXT` record set. Takes `www`, `@` or a full name (`www.example.com`). Refuses to replace a different existing record set unless `allowOverwrite: true`; a rerun with the same values changes nothing. |

Billing: servers are billed from the moment they are created. Usage-billed (hourly) plans need
prepaid credit; if the credit is too low, the action fails with the API's message, which states
Expand Down
Binary file modified docs/screenshots/entity-card.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified docs/screenshots/entity-tab-snapshots.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified docs/screenshots/entity-tab.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified docs/screenshots/power-confirm.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
14 changes: 14 additions & 0 deletions plugins/noderings-backend/src/__fixtures__/fakeApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,20 @@ export function fakeFetch(handler: Handler) {
const method = (init?.method ?? 'GET').toUpperCase();
const body = init?.body ? JSON.parse(String(init.body)) : undefined;
calls.push({ method, path: url.pathname, body });
// Like the real API: list endpoints accept at most 100 items per page.
const size = Number(
url.searchParams.get('pageSize') ?? url.searchParams.get('page_size'),
);
if (size > 100) {
return new Response(
JSON.stringify({
code: 3,
message:
'validation error:\n - page_size: must be greater than or equal to 0 and less than or equal to 100',
}),
{ status: 400, headers: { 'content-type': 'application/json' } },
);
}
const r = handler({
method,
path: url.pathname,
Expand Down
2 changes: 1 addition & 1 deletion plugins/noderings-backend/src/plugin.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ describe('noderings backend plugin', () => {
await request(server)
.get('/api/noderings/health')
.set('Authorization', mockCredentials.none.header())
.expect(200, { ok: true, organizationName: 'Example Org' });
.expect(200, { ok: true });
});

it('answers 503 on health when not configured', async () => {
Expand Down
6 changes: 4 additions & 2 deletions plugins/noderings-backend/src/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,8 +98,10 @@ export async function createRouter(
}

router.get('/health', async (_req, res) => {
const body: HealthResponse = await nodeRings.health();
res.status(body.ok ? 200 : 503).json(body);
// Unauthenticated: report only whether the token works, not whose it is.
const { ok } = await nodeRings.health();
const body: HealthResponse = { ok };
res.status(ok ? 200 : 503).json(body);
});

router.get('/entity/virtual-machines', async (req, res) => {
Expand Down
25 changes: 25 additions & 0 deletions plugins/noderings-backend/src/service/NodeRingsService.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,31 @@ describe('DefaultNodeRingsService', () => {
]);
});

it('pages through DNS records 100 at a time', async () => {
const all = Array.from({ length: 150 }, (_, i) => ({
name: `r${i}`,
type: 'A',
ttl: 300,
rdata: ['203.0.113.1'],
}));
const { svc, calls } = make(req => {
const page = Number(req.query.get('page') ?? 0);
const size = Number(
req.query.get('pageSize') ?? req.query.get('page_size'),
);
return {
body: {
records: all.slice(page * size, (page + 1) * size),
totalCount: all.length,
},
};
});
const records = await svc.listDnsRecords('z1');
expect(records).toHaveLength(150);
expect(records[149].name).toBe('r149');
expect(calls).toHaveLength(2);
});

it('reports health and caches it', async () => {
const { svc, calls } = make();
expect(await svc.health()).toEqual({
Expand Down
3 changes: 2 additions & 1 deletion plugins/noderings-backend/src/service/NodeRingsService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,8 @@ export class DefaultNodeRingsService implements NodeRingsService {
async listDnsRecords(zoneId: string): Promise<DnsRecordSummary[]> {
const api = this.#api();
const out: DnsRecordSummary[] = [];
const pageSize = 500;
// The API accepts at most 100 records per page.
const pageSize = 100;
for (let page = 0; out.length < MAX_DNS_RECORDS; page++) {
const res = await api.dnsRecord.listDnsRecords(zoneId, {
page,
Expand Down
34 changes: 34 additions & 0 deletions plugins/noderings-backend/src/service/mappers.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { toSnapshotSummary } from './mappers';

describe('toSnapshotSummary', () => {
it('shows the operation status while a snapshot is being taken', () => {
expect(
toSnapshotSummary({
id: 's1',
snapshotStatus: 'SNAPSHOT_STATUS_ACTIVE',
operationStatus: 'SNAPSHOT_OPERATION_STATUS_PROCESSING',
createdAt: '2026-11-29T21:49:44Z',
}).status,
).toBe('SNAPSHOT_OPERATION_STATUS_PROCESSING');
});

it('shows a failed operation', () => {
expect(
toSnapshotSummary({
id: 's1',
snapshotStatus: 'SNAPSHOT_STATUS_ACTIVE',
operationStatus: 'SNAPSHOT_OPERATION_STATUS_FAILED',
}).status,
).toBe('SNAPSHOT_OPERATION_STATUS_FAILED');
});

it('shows the snapshot status once the operation has completed', () => {
expect(
toSnapshotSummary({
id: 's1',
snapshotStatus: 'SNAPSHOT_STATUS_ACTIVE',
operationStatus: 'SNAPSHOT_OPERATION_STATUS_COMPLETED',
}).status,
).toBe('SNAPSHOT_STATUS_ACTIVE');
});
});
9 changes: 8 additions & 1 deletion plugins/noderings-backend/src/service/mappers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,14 @@ export function toSnapshotSummary(s: Snapshot): SnapshotSummary {
id: s.id ?? s.snapshotId ?? '',
name: s.name || undefined,
description: s.description || undefined,
status: s.snapshotStatus || undefined,
// A new snapshot is SNAPSHOT_STATUS_ACTIVE while it is still being taken;
// show the operation status until the operation has completed.
status:
s.operationStatus &&
s.operationStatus !== 'SNAPSHOT_OPERATION_STATUS_COMPLETED' &&
s.operationStatus !== 'SNAPSHOT_OPERATION_STATUS_UNSPECIFIED'
? s.operationStatus
: s.snapshotStatus || undefined,
createdAt: s.createdAt || s.timestamps?.createTime || undefined,
};
}
Expand Down
4 changes: 2 additions & 2 deletions plugins/noderings/dev/mockApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ export const mockVirtualMachines: VirtualMachineSummary[] = [
ipv6: '2001:db8::10',
additionalIpv4: [],
distro: 'DISTRO_UBUNTU_24_04',
tags: ['example-website', 'web'],
tags: ['example-website', 'backstage-default-component-example-website'],
createdAt: '2026-11-02T09:14:00Z',
},
{
Expand All @@ -42,7 +42,7 @@ export const mockVirtualMachines: VirtualMachineSummary[] = [
ipv6: '2001:db8::11',
additionalIpv4: ['203.0.113.50'],
distro: 'DISTRO_DEBIAN_13',
tags: ['example-website', 'web'],
tags: ['example-website', 'backstage-default-component-example-website'],
createdAt: '2026-11-05T16:40:00Z',
},
{
Expand Down
3 changes: 2 additions & 1 deletion plugins/noderings/src/components/SnapshotsTable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@ const columns: TableColumn<SnapshotSummary>[] = [
{
title: 'Status',
render: s =>
s.status?.replace(/^SNAPSHOT_STATUS_/, '').toLowerCase() ?? '–',
s.status?.replace(/^SNAPSHOT_(OPERATION_)?STATUS_/, '').toLowerCase() ??
'–',
},
{ title: 'Created', render: s => date(s.createdAt) },
];
Expand Down
22 changes: 22 additions & 0 deletions plugins/noderings/src/components/TagChips.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import Box from '@material-ui/core/Box';
import Chip from '@material-ui/core/Chip';
import Tooltip from '@material-ui/core/Tooltip';

/**
* The tags of a server as small chips. Long tags (such as the
* `backstage-<namespace>-<kind>-<name>` tags of noderings:vm:create) are cut
* with an ellipsis and shown in full on hover, so they do not widen the table.
*/
export function TagChips(props: { tags: string[]; maxWidth?: number }) {
const { tags, maxWidth = 200 } = props;
if (tags.length === 0) return <>–</>;
return (
<Box display="flex" flexWrap="wrap" style={{ gap: 4 }}>
{tags.map(t => (
<Tooltip key={t} title={t}>
<Chip label={t} size="small" style={{ maxWidth }} />
</Tooltip>
))}
</Box>
);
}
6 changes: 0 additions & 6 deletions plugins/noderings/src/components/VirtualMachinesCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import {
type TableColumn,
} from '@backstage/core-components';
import Box from '@material-ui/core/Box';
import Chip from '@material-ui/core/Chip';
import IconButton from '@material-ui/core/IconButton';
import Tooltip from '@material-ui/core/Tooltip';
import Typography from '@material-ui/core/Typography';
Expand All @@ -28,16 +27,11 @@ const columns: TableColumn<VirtualMachineSummary>[] = [
render: vm => <StatusChip status={vm.status} />,
},
{ title: 'Location', render: vm => location(vm) },
{ title: 'Provider', render: vm => vm.provider ?? '–' },
{
title: 'IPv4',
cellStyle: { whiteSpace: 'nowrap' },
render: vm => vm.ipv4 ?? '–',
},
{
title: 'Tags',
render: vm => vm.tags.map(t => <Chip key={t} label={t} size="small" />),
},
];

/** Counts servers by status label, for example "2 Running, 1 Stopped". */
Expand Down
14 changes: 8 additions & 6 deletions plugins/noderings/src/components/VirtualMachinesContent.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import { useEntity } from '@backstage/plugin-catalog-react';
import { usePermission } from '@backstage/plugin-permission-react';
import Box from '@material-ui/core/Box';
import Button from '@material-ui/core/Button';
import Chip from '@material-ui/core/Chip';
import Grid from '@material-ui/core/Grid';
import Typography from '@material-ui/core/Typography';
import RefreshIcon from '@material-ui/icons/Refresh';
Expand All @@ -25,6 +24,7 @@ import { DnsRecordsTable } from './DnsRecordsTable';
import { PowerButton } from './PowerButton';
import { SnapshotsTable } from './SnapshotsTable';
import { StatusChip } from './StatusChip';
import { TagChips } from './TagChips';
import { statusCounts } from './VirtualMachinesCard';
import { billing, date, location, size } from './format';
import { useVirtualMachines } from './useVirtualMachines';
Expand Down Expand Up @@ -103,10 +103,6 @@ export function VirtualMachinesContent() {
/>
),
},
{
title: 'Tags',
render: vm => vm.tags.map(t => <Chip key={t} label={t} size="small" />),
},
];
if (showPower) {
columns.push({
Expand Down Expand Up @@ -177,6 +173,12 @@ export function VirtualMachinesContent() {
]}
detailPanel={({ rowData }) => (
<Box px={4} pb={2}>
<Box display="flex" alignItems="center" py={1} style={{ gap: 8 }}>
<Typography variant="body2" color="textSecondary">
Tags
</Typography>
<TagChips tags={rowData.tags} maxWidth={400} />
</Box>
<SnapshotsTable entityRef={entityRef} vmId={rowData.id} />
</Box>
)}
Expand All @@ -199,7 +201,7 @@ export function VirtualMachinesContent() {
<InfoCard>
<Typography variant="body2">
Servers are <Link to="https://noderings.com">NodeRings</Link>{' '}
Compute Instances. Expand a row to see its snapshots.
Compute Instances. Expand a row to see its tags and snapshots.
{value &&
!value.powerActionsEnabled &&
' Start, stop and restart are turned off (noderings.allowPowerActions).'}
Expand Down
13 changes: 13 additions & 0 deletions plugins/noderings/src/components/components.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { MockNodeRingsApi } from '../../dev/mockApi';
import { VirtualMachinesCard } from './VirtualMachinesCard';
import { VirtualMachinesContent } from './VirtualMachinesContent';
import { StatusChip } from './StatusChip';
import { TagChips } from './TagChips';

const entity: Entity = {
apiVersion: 'backstage.io/v1alpha1',
Expand Down Expand Up @@ -232,3 +233,15 @@ describe('StatusChip', () => {
expect(screen.getByText(label)).toBeInTheDocument();
});
});

describe('TagChips', () => {
it('shows a dash without tags and the full tag on hover', async () => {
const long = 'backstage-default-resource-a-rather-long-server-name';
const { rerender } = await renderInTestApp(<TagChips tags={[]} />);
expect(screen.getByText('–')).toBeInTheDocument();
rerender(<TagChips tags={[long]} maxWidth={120} />);
const chip = screen.getByText(long);
fireEvent.mouseOver(chip);
expect(await screen.findByRole('tooltip')).toHaveTextContent(long);
});
});
5 changes: 5 additions & 0 deletions plugins/scaffolder-backend-module-noderings/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -82,4 +82,9 @@ Input: `zoneId`, `name`, `type`, `ttl` (default 300), `values`, `allowOverwrite`
`false`). Refuses to replace an existing, different record set with the same name and type unless
`allowOverwrite` is true; does nothing when the record set already has these values.

`name` is relative to the zone (`www`, `@` for the apex) or fully qualified (`www.example.com`,
with or without the final dot); output `name` is the zone-relative name. Values are compared the
way the API stores them, so `hello` matches the stored TXT value `"hello"` and
`target.example.com` matches `target.example.com.`.

License: Apache-2.0. Source: <https://github.com/noderings/backstage-plugins>.
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,11 @@ import { examples } from './upsertDnsRecord.examples';

function fakeClient(records: any[] = []) {
return {
dnsZone: {
getDnsZone: jest.fn(async () => ({
zone: { id: 'z1', name: 'example.com' },
})),
},
dnsRecord: {
listDnsRecords: jest.fn(async () => ({ records })),
upsertDnsRecord: jest.fn(async (_z: string, b: any) => b.record),
Expand Down Expand Up @@ -80,6 +85,52 @@ describe('noderings:dns:record:upsert', () => {
).rejects.toThrow(/allowOverwrite/);
});

it.each([
['www.example.com', 'www'],
['WWW.Example.com.', 'www'],
['example.com.', '@'],
['@', '@'],
['a.b', 'a.b'],
])('writes %s as the zone-relative name %s', async (name, rel) => {
const client = fakeClient();
const ctx = ctxWith({ ...input, name });
await action(client).handler(ctx);
expect(client.dnsRecord.listDnsRecords).toHaveBeenCalledWith('z1', {
name: rel,
type: 'A',
});
expect(client.dnsRecord.upsertDnsRecord).toHaveBeenCalledWith('z1', {
record: expect.objectContaining({ name: rel }),
});
expect(ctx.output).toHaveBeenCalledWith('name', rel);
});

it('refuses to overwrite a record set given by its full name', async () => {
const client = fakeClient([
{ name: 'www', type: 'A', ttl: 300, rdata: ['203.0.113.99'] },
]);
await expect(
action(client).handler(ctxWith({ ...input, name: 'www.example.com.' })),
).rejects.toThrow(/allowOverwrite/);
expect(client.dnsRecord.upsertDnsRecord).not.toHaveBeenCalled();
});

it.each([
['TXT', ['"hello world"'], ['hello world']],
['CNAME', ['target.example.net.'], ['Target.example.net']],
['MX', ['10 mail.example.net.'], ['10 mail.example.net']],
['AAAA', ['2001:db8::1'], ['2001:0db8:0000::1']],
])(
'treats %s values as the API returns them as unchanged',
async (type, stored, given) => {
const client = fakeClient([
{ name: 'www', type, ttl: 300, rdata: stored },
]);
await action(client).handler(ctxWith({ ...input, type, values: given }));
expect(client.dnsRecord.upsertDnsRecord).not.toHaveBeenCalled();
},
);

it('has examples that parse', () => {
for (const e of examples) {
expect(yaml.parse(e.example).steps[0].action).toBe(
Expand Down
Loading