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
49 changes: 21 additions & 28 deletions .devcontainer/devcontainer.json
Original file line number Diff line number Diff line change
@@ -1,47 +1,40 @@
// For format details, see https://aka.ms/devcontainer.json. For config options, see the
// README at: https://github.com/devcontainers/templates/tree/main/src/dotnet
{
"name": "Aspire",
// Or use a Dockerfile or Docker Compose file. More info: https://containers.dev/guide/dockerfile
"image": "mcr.microsoft.com/devcontainers/dotnet:dev-10.0-noble",
"image": "mcr.microsoft.com/devcontainers/base:3-ubuntu24.04",
"features": {
"ghcr.io/microsoft/aspire-devcontainer-feature/aspire:2": {},
"ghcr.io/devcontainers/features/docker-in-docker:2": {},
"ghcr.io/devcontainers/features/powershell:1": {},
"ghcr.io/devcontainers/features/node:1": {},
"ghcr.io/devcontainers/features/python:1": {},
"ghcr.io/devcontainers-extra/features/uv:1": {}
"ghcr.io/devcontainers/features/node:1": {
"version": "lts"
},
"ghcr.io/devcontainers/features/python:1": {
"version": "os-provided"
},
"ghcr.io/devcontainers-extra/features/uv:1": {},
"ghcr.io/devcontainers/features/dotnet:2": {
"version": "10.0"
},
"ghcr.io/devcontainers/features/powershell:1": {}
},

"hostRequirements": {
"cpus": 8,
"memory": "32gb",
"storage": "64gb"
},

// Use 'forwardPorts' to make a list of ports inside the container available locally.
// "forwardPorts": [5000, 5001],
// "portsAttributes": {
// "5001": {
// "protocol": "https"
// }
// }

// Use 'postCreateCommand' to run commands after the container is created.
// "postCreateCommand": "dotnet restore",
"postStartCommand": "dotnet dev-certs https --trust",
"remoteEnv": {
"SSL_CERT_DIR": "/usr/lib/ssl/certs:/home/vscode/.aspnet/dev-certs/trust"
},
"postStartCommand": "aspire certs trust --non-interactive",
"customizations": {
"vscode": {
"extensions": [
"ms-dotnettools.csdevkit",
"microsoft-aspire.aspire-vscode",
"GitHub.copilot-chat",
"microsoft-aspire.aspire-vscode"
"dbaeumer.vscode-eslint",
"ms-python.python",
"ms-python.vscode-pylance",
"ms-dotnettools.csdevkit"
]
}
}
// Configure tool-specific properties.
// "customizations": {},

// Uncomment to connect as root instead. More info: https://aka.ms/dev-containers-non-root.
// "remoteUser": "root"
}
27 changes: 27 additions & 0 deletions .github/scripts/prepare-config.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import assert from 'node:assert/strict';
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { basename, dirname, resolve } from 'node:path';
import { parseArgs } from 'node:util';

const { values } = parseArgs({
options: {
output: { type: 'string' },
'without-dotnet': { type: 'boolean', default: false },
},
});
assert.ok(values.output, '--output is required.');

const configuration = JSON.parse(readFileSync('.devcontainer/devcontainer.json', 'utf8'));
if (values['without-dotnet']) {
const features = Object.keys(configuration.features)
.filter(feature => feature.startsWith('ghcr.io/devcontainers/features/dotnet:'));
assert.equal(features.length, 1, 'Expected one standalone .NET SDK feature to omit.');
delete configuration.features[features[0]];
}

const output = resolve(values.output);
assert.notEqual(output, resolve('.devcontainer/devcontainer.json'), 'Use a separate output path for the test configuration.');
assert.ok(['devcontainer.json', '.devcontainer.json'].includes(basename(output)),
'The test configuration must be named devcontainer.json or .devcontainer.json.');
mkdirSync(dirname(output), { recursive: true });
writeFileSync(output, `${JSON.stringify(configuration, null, 2)}\n`);
188 changes: 188 additions & 0 deletions .github/scripts/smoke-test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,188 @@
import assert from 'node:assert/strict';
import { execFileSync, spawnSync } from 'node:child_process';
import { accessSync, constants, mkdirSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
import { homedir } from 'node:os';
import { join } from 'node:path';

process.env.ASPIRE_CLI_TELEMETRY_OPTOUT = '1';
process.env.DOTNET_CLI_TELEMETRY_OPTOUT = '1';

const scenarios = {
python: { template: 'aspire-py-starter', api: 'app', frontend: 'frontend', cache: true },
csharp: { template: 'aspire-starter', api: 'apiservice', frontend: 'webfrontend', cache: true },
'typescript-no-dotnet': { template: 'aspire-ts-starter', api: 'app', frontend: 'frontend', cache: false },
};
const scenarioName = process.argv[2] ?? 'python';
assert.ok(Object.hasOwn(scenarios, scenarioName), `Unknown scenario: ${scenarioName}`);
const scenario = scenarios[scenarioName];
const withoutDotnet = scenarioName === 'typescript-no-dotnet';

function execute(command, args, { cwd = process.cwd(), capture = false, input } = {}) {
console.log(`> ${command} ${args.join(' ')}`);
return execFileSync(command, args, {
cwd,
encoding: 'utf8',
input,
stdio: [input === undefined ? 'ignore' : 'pipe', capture ? 'pipe' : 'inherit', 'inherit'],
});
}

function assertNoDotnet() {
const result = spawnSync('dotnet', ['--version'], { encoding: 'utf8' });
assert.equal(result.error?.code, 'ENOENT', 'The TypeScript scenario must have no standalone dotnet on PATH.');
console.log('No standalone dotnet found on PATH.');
}

assert.equal(process.platform, 'linux', 'Run this script inside the devcontainer.');
assert.notEqual(process.getuid(), 0, 'The remote user must not be root.');
accessSync('.devcontainer/devcontainer.json', constants.R_OK);
accessSync('.', constants.W_OK);

// Check the lifecycle hook before Aspire starts and can perform its own certificate setup.
const trustDirectory = join(homedir(), '.aspnet', 'dev-certs', 'trust');
const certificates = readdirSync(trustDirectory).filter(name => name.endsWith('.pem'));
assert.ok(certificates.length > 0, 'The startup hook must create a development certificate.');
for (const certificate of certificates) {
execute('openssl', ['verify', join(trustDirectory, certificate)]);
}

for (const command of ['node', 'npm', 'python3', 'uv', 'pwsh', 'aspire']) {
execute(command, ['--version']);
}
if (withoutDotnet) {
assertNoDotnet();
} else {
execute('dotnet', ['--version']);
}

execute('docker', ['info', '--format', 'Docker server: {{.ServerVersion}}']);
execute('docker', ['run', '--rm', 'hello-world']);

const testDirectory = mkdtempSync(join(homedir(), '.aspire-devcontainer-test-'));
const appDirectory = join(testDirectory, 'app');
const dotnetDirectory = join(testDirectory, 'dotnet');
let startAttempted = false;

try {
if (scenarioName === 'python') {
execute('dotnet', ['new', 'console', '--output', dotnetDirectory, '--no-restore']);
const consoleOutput = execute('dotnet', ['run', '--project', dotnetDirectory], { capture: true });
assert.ok(consoleOutput.includes('Hello, World!'), '.NET must restore, compile, and run a project.');
}

execute('aspire', [
'new', scenario.template,
'--name', 'DevcontainerSmoke',
'--output', appDirectory,
...(scenario.cache ? ['--use-redis-cache', 'true'] : []),
'--suppress-agent-init',
'--non-interactive',
], { cwd: testDirectory });

startAttempted = true;
execute('aspire', ['start', '--isolated', '--non-interactive'], { cwd: appDirectory });
for (const name of [...(scenario.cache ? ['cache'] : []), scenario.api, scenario.frontend]) {
execute('aspire', ['wait', name, '--timeout', '180', '--non-interactive'], { cwd: appDirectory });
}

const description = execute('aspire', ['describe', '--format', 'Json', '--non-interactive'], {
cwd: appDirectory,
capture: true,
});
// The CLI can print a discovery message before its JSON output.
const jsonStart = description.indexOf('{');
assert.ok(jsonStart >= 0, 'Aspire must return a resource description.');
const { resources } = JSON.parse(description.slice(jsonStart));
const resource = name => {
const result = resources.find(item => item.displayName === name);
assert.ok(result, `Missing resource: ${name}`);
assert.equal(result.healthStatus, 'Healthy', `${name} must be healthy.`);
return result;
};

const api = resource(scenario.api);
const frontend = resource(scenario.frontend);
const endpoint = item => item.urls.find(url => url.url.startsWith('https:'))?.url
?? item.urls.find(url => url.url.startsWith('http:'))?.url;
const apiUrl = endpoint(api);
const frontendUrl = endpoint(frontend);
assert.ok(apiUrl, 'The API must expose an endpoint.');
assert.ok(frontendUrl, 'The frontend must expose an endpoint.');
if (!withoutDotnet) {
assert.equal(new URL(apiUrl).protocol, 'https:', 'The API smoke test must exercise HTTPS.');
}
if (scenario.cache) {
assert.equal(resource('cache').resourceType, 'Container');
}

const get = url => execute('curl', [
'--fail', '--silent', '--show-error', '--location', '--max-time', '30', url,
], { capture: true });

assert.equal(get(new URL('/health', apiUrl).href), 'Healthy');
const forecastPath = scenarioName === 'csharp' ? '/weatherforecast' : '/api/weatherforecast';
const direct = JSON.parse(get(new URL(forecastPath, apiUrl).href));
assert.equal(direct.length, 5, 'The API must return five forecasts.');
for (const forecast of direct) {
assert.equal(typeof forecast.temperatureC, 'number');
assert.equal(typeof forecast.summary, 'string');
}

if (scenarioName === 'csharp') {
assert.equal(api.resourceType, 'Project');
assert.equal(frontend.resourceType, 'Project');
assert.equal(get(new URL('/health', frontendUrl).href), 'Healthy');
const weatherPage = get(new URL('/weather', frontendUrl).href);
assert.ok(weatherPage.includes('<h1>Weather</h1>'), 'Blazor must render the weather page.');
assert.equal([...weatherPage.matchAll(/<td>/g)].length, 20, 'Blazor must render all five API forecasts.');
} else {
assert.ok(get(frontendUrl).includes('id="root"'), 'The frontend must serve the React app.');
const proxied = JSON.parse(get(new URL(forecastPath, frontendUrl).href));
assert.equal(proxied.length, 5, 'The frontend must proxy requests to the API.');
}

if (scenarioName === 'python') {
// Seed a non-expiring value so this checks cache hits without depending on the sample's five-second TTL.
const cached = direct.map(forecast => ({ ...forecast, summary: 'CI cache sentinel' }));
const result = execute('docker', [
'exec', '-i', resource('cache').properties['container.id'],
'sh', '-c',
'REDISCLI_AUTH="$REDIS_PASSWORD" redis-cli --tls --cacert /usr/lib/ssl/aspire/cert.pem --raw -x SET weatherforecast',
], { capture: true, input: JSON.stringify(cached) });
assert.equal(result.trim(), 'OK', 'The test must seed Redis successfully.');
assert.deepEqual(JSON.parse(get(new URL(forecastPath, apiUrl).href)), cached, 'The API must read Redis.');
assert.deepEqual(JSON.parse(get(new URL(forecastPath, frontendUrl).href)), cached, 'The frontend must return cached API data.');
}

const dashboardStatus = execute('curl', [
'--fail', '--silent', '--show-error', '--location', '--max-time', '30',
'--output', '/dev/null', '--write-out', '%{http_code}',
new URL(api.dashboardUrl).origin,
], { capture: true });
assert.equal(dashboardStatus, '200', 'The dashboard must be reachable over trusted HTTPS.');
if (withoutDotnet) {
assertNoDotnet();
}
} catch (error) {
console.error(error);
if (startAttempted) {
const logs = spawnSync('aspire', [
'logs', '--tail', '200', '--include-hidden', '--format', 'Json', '--non-interactive',
], { cwd: appDirectory, encoding: 'utf8', timeout: 30_000 });
const logDirectory = join(homedir(), '.aspire', 'logs');
mkdirSync(logDirectory, { recursive: true });
writeFileSync(join(logDirectory, `smoke-${scenarioName}-resources.log`),
[logs.stdout, logs.stderr, logs.error?.stack, `Log capture exit status: ${logs.status}`].filter(Boolean).join('\n'));
if (logs.error || logs.status !== 0) {
console.error('Resource log capture failed:', logs.error ?? logs.stderr);
}
}
throw error;
} finally {
if (startAttempted) {
execute('aspire', ['stop', '--non-interactive'], { cwd: appDirectory });
}
}

rmSync(testDirectory, { recursive: true });
console.log(`Devcontainer ${scenarioName} checks passed.`);
109 changes: 109 additions & 0 deletions .github/workflows/devcontainer.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
name: Devcontainer

on:
pull_request:
push:
branches: [main]
workflow_dispatch:

permissions:
contents: read

concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true

jobs:
smoke-test:
name: ${{ matrix.name }}
runs-on: ubuntu-24.04
timeout-minutes: 30
strategy:
fail-fast: false
matrix:
include:
- scenario: python
name: Python and React
- scenario: csharp
name: C# and Blazor
- scenario: typescript-no-dotnet
name: TypeScript without .NET SDK
env:
SCENARIO: ${{ matrix.scenario }}
defaults:
run:
shell: bash
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false

- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
with:
node-version: '24'

- name: Install Dev Containers CLI
run: npm install --global @devcontainers/cli@0.89.0

- name: Prepare test configuration
run: |
mkdir -p "$RUNNER_TEMP/devcontainer-diagnostics"
config="$RUNNER_TEMP/devcontainer-test/devcontainer.json"
args=(--output "$config")
if [ "$SCENARIO" = typescript-no-dotnet ]; then
args+=(--without-dotnet)
fi
node .github/scripts/prepare-config.mjs "${args[@]}"
echo "DEVCONTAINER_CONFIG=$config" >> "$GITHUB_ENV"

- name: Start devcontainer
id: container
run: |
devcontainer up --workspace-folder . --config "$DEVCONTAINER_CONFIG" --mount-workspace-git-root false --no-lockfile \
> "$RUNNER_TEMP/devcontainer-up.json" \
2> >(tee "$RUNNER_TEMP/devcontainer-diagnostics/startup.log" >&2)
container_id=$(jq --exit-status --raw-output '.containerId' "$RUNNER_TEMP/devcontainer-up.json")
echo "container_id=$container_id" >> "$GITHUB_OUTPUT"

- name: Test fresh container
run: |
devcontainer exec --workspace-folder . --config "$DEVCONTAINER_CONFIG" node .github/scripts/smoke-test.mjs "$SCENARIO" \
2>&1 | tee "$RUNNER_TEMP/devcontainer-diagnostics/fresh.log"

- name: Stop and reopen devcontainer
env:
CONTAINER_ID: ${{ steps.container.outputs.container_id }}
run: |
docker stop "$CONTAINER_ID"
devcontainer up --workspace-folder . --config "$DEVCONTAINER_CONFIG" --mount-workspace-git-root false --no-lockfile --expect-existing-container \
2> >(tee "$RUNNER_TEMP/devcontainer-diagnostics/restart.log" >&2)

- name: Test restarted container
run: |
devcontainer exec --workspace-folder . --config "$DEVCONTAINER_CONFIG" node .github/scripts/smoke-test.mjs "$SCENARIO" \
2>&1 | tee "$RUNNER_TEMP/devcontainer-diagnostics/restarted.log"

- name: Collect failure diagnostics
if: failure() && steps.container.outputs.container_id != ''
env:
CONTAINER_ID: ${{ steps.container.outputs.container_id }}
run: |
mkdir -p "$RUNNER_TEMP/devcontainer-diagnostics"
docker logs "$CONTAINER_ID" > "$RUNNER_TEMP/devcontainer-diagnostics/container.log" 2>&1
docker inspect --format '{{json .State}}' "$CONTAINER_ID" > "$RUNNER_TEMP/devcontainer-diagnostics/container-state.json"
docker cp "$CONTAINER_ID:/home/vscode/.aspire/logs" "$RUNNER_TEMP/devcontainer-diagnostics/aspire"

- name: Upload failure diagnostics
if: failure()
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: devcontainer-${{ matrix.scenario }}-diagnostics
path: ${{ runner.temp }}/devcontainer-diagnostics
if-no-files-found: ignore
retention-days: 7

- name: Remove test container
if: always() && steps.container.outputs.container_id != ''
env:
CONTAINER_ID: ${{ steps.container.outputs.container_id }}
run: docker rm --force --volumes "$CONTAINER_ID"
Loading