Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add multi build support #24

Merged
merged 15 commits into from
Jun 21, 2022
Merged
Show file tree
Hide file tree
Changes from 12 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
2 changes: 2 additions & 0 deletions src/spec-common/injectHeadless.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,8 @@ export interface ResolverParameters {
backgroundTasks: (Promise<void> | (() => Promise<void>))[];
persistedFolder: string; // A path where config can be persisted and restored at a later time. Should default to tmpdir() folder if not provided.
remoteEnv: Record<string, string>;
buildxPlatform: string | undefined;
buildxPush: boolean;
}

export interface PostCreate {
Expand Down
6 changes: 6 additions & 0 deletions src/spec-node/devContainers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,8 @@ export interface ProvisionOptions {
remoteEnv: Record<string, string>;
additionalCacheFroms: string[];
useBuildKit: 'auto' | 'never';
buildxPlatform: string | undefined;
buildxPush: boolean;
}

export async function launch(options: ProvisionOptions, disposables: (() => Promise<unknown> | undefined)[]) {
Expand Down Expand Up @@ -113,6 +115,8 @@ export async function createDockerParams(options: ProvisionOptions, disposables:
backgroundTasks: [],
persistedFolder: persistedFolder || await cliHost.tmpdir(), // Fallback to tmpDir(), even though that isn't 'persistent'
remoteEnv,
buildxPlatform: options.buildxPlatform,
buildxPush: options.buildxPush,
};

const dockerPath = options.dockerPath || 'docker';
Expand Down Expand Up @@ -148,6 +152,8 @@ export async function createDockerParams(options: ProvisionOptions, disposables:
additionalCacheFroms: options.additionalCacheFroms,
buildKitVersion,
isTTY: process.stdin.isTTY || options.logFormat === 'json',
buildxPlatform: common.buildxPlatform,
buildxPush: common.buildxPush,
};
}

Expand Down
24 changes: 19 additions & 5 deletions src/spec-node/devContainersSpecCLI.ts
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,8 @@ async function provision({
remoteEnv: keyValuesToRecord(addRemoteEnvs),
additionalCacheFroms: addCacheFroms,
useBuildKit: buildkit,
buildxPlatform: undefined,
juzuluag marked this conversation as resolved.
Show resolved Hide resolved
buildxPush: false,
};

const result = await doProvision(options);
Expand Down Expand Up @@ -241,6 +243,8 @@ function buildOptions(y: Argv) {
'image-name': { type: 'string', description: 'Image name.' },
'cache-from': { type: 'string', description: 'Additional image to use as potential layer cache' },
'buildkit': { choices: ['auto' as 'auto', 'never' as 'never'], default: 'auto' as 'auto', description: 'Control whether BuildKit should be used' },
'platform': { type: 'string', description: 'Set target platforms.' },
'push': { type: 'boolean', default: false, description: 'Push to a container registry.' },
});
}

Expand Down Expand Up @@ -269,6 +273,8 @@ async function doBuild({
'image-name': argImageName,
'cache-from': addCacheFrom,
'buildkit': buildkit,
'platform': buildxPlatform,
'push': buildxPush,
}: BuildArgs) {
const disposables: (() => Promise<unknown> | undefined)[] = [];
const dispose = async () => {
Expand Down Expand Up @@ -305,7 +311,9 @@ async function doBuild({
updateRemoteUserUIDDefault: 'never',
remoteEnv: {},
additionalCacheFroms: addCacheFroms,
useBuildKit: buildkit
useBuildKit: buildkit,
buildxPlatform,
buildxPush,
}, disposables);

const { common, dockerCLI, dockerComposeCLI } = params;
Expand All @@ -325,10 +333,12 @@ async function doBuild({
if (isDockerFileConfig(config)) {

// Build the base image and extend with features etc.
const { updatedImageName } = await buildNamedImageAndExtend(params, config);
const { updatedImageName } = await buildNamedImageAndExtend(params, config, argImageName);
juzuluag marked this conversation as resolved.
Show resolved Hide resolved

if (argImageName) {
await dockerPtyCLI(params, 'tag', updatedImageName, argImageName);
if (!buildxPush) {
await dockerPtyCLI(params, 'tag', updatedImageName, argImageName);
}
juzuluag marked this conversation as resolved.
Show resolved Hide resolved
imageNameResult = argImageName;
} else {
imageNameResult = updatedImageName;
Expand Down Expand Up @@ -509,7 +519,9 @@ async function doRunUserCommands({
updateRemoteUserUIDDefault: 'never',
remoteEnv: keyValuesToRecord(addRemoteEnvs),
additionalCacheFroms: [],
useBuildKit: 'auto'
useBuildKit: 'auto',
buildxPlatform: undefined,
buildxPush: false,
}, disposables);

const { common } = params;
Expand Down Expand Up @@ -753,7 +765,9 @@ async function doExec({
updateRemoteUserUIDDefault: 'never',
remoteEnv: keyValuesToRecord(addRemoteEnvs),
additionalCacheFroms: [],
useBuildKit: 'auto'
useBuildKit: 'auto',
buildxPlatform: undefined,
buildxPush: false,
}, disposables);

const { common } = params;
Expand Down
24 changes: 18 additions & 6 deletions src/spec-node/singleContainer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,15 +100,19 @@ async function setupContainer(container: ContainerDetails, params: DockerResolve
};
}

export async function buildNamedImageAndExtend(params: DockerResolverParameters, config: DevContainerFromDockerfileConfig | DevContainerFromImageConfig) {
const imageName = 'image' in config ? config.image : getFolderImageName(params.common);
function getDefaultName(config: DevContainerFromDockerfileConfig | DevContainerFromImageConfig, params: DockerResolverParameters) {
return 'image' in config ? config.image : getFolderImageName(params.common);
}
export async function buildNamedImageAndExtend(params: DockerResolverParameters, config: DevContainerFromDockerfileConfig | DevContainerFromImageConfig, argImageName?: string) {
const imageName = argImageName ?? getDefaultName(config, params);
params.common.progress(ResolverProgress.BuildingImage);
if (isDockerFileConfig(config)) {
return await buildAndExtendImage(params, config, imageName, params.buildNoCache ?? false);
}
// image-based dev container - extend
return await extendImage(params, config, imageName, 'image' in config);
}

async function buildAndExtendImage(buildParams: DockerResolverParameters, config: DevContainerFromDockerfileConfig, baseImageName: string, noCache: boolean) {
const { cliHost, output } = buildParams.common;
const dockerfileUri = getDockerfilePath(cliHost, config);
Expand All @@ -126,6 +130,7 @@ async function buildAndExtendImage(buildParams: DockerResolverParameters, config
// Use the last stage in the Dockerfile
// Find the last line that starts with "FROM" (possibly preceeded by white-space)
const { lastStageName, modifiedDockerfile } = ensureDockerfileHasFinalStageName(dockerfile, baseName);
// const { lastStageName, modifiedDockerfile } = ensureDockerfileHasFinalStageName(dockerfile, baseName);
juzuluag marked this conversation as resolved.
Show resolved Hide resolved
baseName = lastStageName;
if (modifiedDockerfile) {
dockerfile = modifiedDockerfile;
Expand Down Expand Up @@ -159,14 +164,21 @@ async function buildAndExtendImage(buildParams: DockerResolverParameters, config

const args: string[] = [];
if (buildParams.buildKitVersion) {
args.push('buildx', 'build',
'--load', // (short for --output=docker, i.e. load into normal 'docker images' collection)
'--build-arg', 'BUILDKIT_INLINE_CACHE=1', // ensure cache manifest is included in the image
);
args.push('buildx', 'build');
if (buildParams.buildxPlatform) {
args.push('--platform', buildParams.buildxPlatform);
juzuluag marked this conversation as resolved.
Show resolved Hide resolved
}
if (buildParams.buildxPush) {
args.push('--push');
} else {
args.push('--load'); // (short for --output=docker, i.e. load into normal 'docker images' collection)
}
args.push('--build-arg', 'BUILDKIT_INLINE_CACHE=1');
} else {
args.push('build');
juzuluag marked this conversation as resolved.
Show resolved Hide resolved
}
args.push('-f', finalDockerfilePath, '-t', baseImageName);

const target = config.build?.target;
if (target) {
args.push('--target', target);
Expand Down
2 changes: 2 additions & 0 deletions src/spec-node/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,8 @@ export interface DockerResolverParameters {
additionalCacheFroms: string[];
buildKitVersion: string | null;
isTTY: boolean;
buildxPlatform: string | undefined;
buildxPush: boolean;
}

export interface ResolverResult {
Expand Down
21 changes: 21 additions & 0 deletions src/test/cli.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,27 @@ describe('Dev Containers CLI', function () {
assert.equal(success, false, 'expect non-successful call');
});

it('should succeed with supported --platform', async () => {
const testFolder = `${__dirname}/configs/dockerfile-with-target`;
const res = await shellExec(`${cli} build --workspace-folder ${testFolder} --platform linux/amd64`);
const response = JSON.parse(res.stdout);
assert.equal(response.outcome, 'success');
});

it('should fail with unsupported --platform', async () => {
let success = false;
const testFolder = `${__dirname}/configs/dockerfile-with-target`;
try {
await shellExec(`${cli} build --workspace-folder ${testFolder} --platform fake/platform`);
success = true;
} catch (error) {
assert.equal(error.error.code, 1, 'Should fail with exit code 1');
const res = JSON.parse(error.stdout);
assert.equal(res.outcome, 'error');
assert.match(res.message, /Command failed/);
}
assert.equal(success, false, 'expect non-successful call');
});

});

Expand Down