Skip to content

Commit

Permalink
support standalone mode and display version
Browse files Browse the repository at this point in the history
Signed-off-by: CrazyMax <[email protected]>
  • Loading branch information
crazy-max committed Apr 17, 2022
1 parent 2a6fbda commit 3472856
Show file tree
Hide file tree
Showing 9 changed files with 223 additions and 46 deletions.
34 changes: 31 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ ___
* [BuildKit daemon configuration](#buildkit-daemon-configuration)
* [Registry mirror](#registry-mirror)
* [Max parallelism](#max-parallelism)
* [Standalone mode](#standalone-mode)
* [Customizing](#customizing)
* [inputs](#inputs)
* [outputs](#outputs)
Expand Down Expand Up @@ -180,6 +181,33 @@ jobs:
config: .github/buildkitd.toml
```

### Standalone mode

If you don't have the Docker CLI installed on the GitHub Runner, buildx binary
is invoked directly, instead of calling it as a docker plugin. This can be
useful if you want to use the `kubernetes` driver in your self-hosted runner:

```yaml
name: ci

on:
push:

jobs:
buildx:
runs-on: ubuntu-latest
steps:
-
name: Set up Docker Buildx
uses: docker/setup-buildx-action@v1
with:
driver: kubernetes
-
name: Build
run: |
buildx build .
```

## Customizing

### inputs
Expand All @@ -195,10 +223,10 @@ Following inputs can be used as `step.with` keys
| `install` | Bool | Sets up `docker build` command as an alias to `docker buildx` (default `false`) |
| `use` | Bool | Switch to this builder instance (default `true`) |
| `endpoint` | String | [Optional address for docker socket](https://github.com/docker/buildx/blob/master/docs/reference/buildx_create.md#description) or context from `docker context ls` |
| `config` | String | [BuildKit config file](https://github.com/docker/buildx/blob/master/docs/reference/buildx_create.md#config) |
| `config-inline` | String | Same as `config` but inline |
| `config`¹ | String | [BuildKit config file](https://github.com/docker/buildx/blob/master/docs/reference/buildx_create.md#config) |
| `config-inline`¹ | String | Same as `config` but inline |

> `config` and `config-inline` are mutually exclusive.
> * ¹ `config` and `config-inline` are mutually exclusive
> `CSV` type must be a newline-delimited string
> ```yaml
Expand Down
38 changes: 26 additions & 12 deletions __tests__/buildx.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,17 @@ describe('isAvailable', () => {
});
});

describe('isAvailable standalone', () => {
const execSpy = jest.spyOn(exec, 'getExecOutput');
buildx.isAvailable(true);

// eslint-disable-next-line jest/no-standalone-expect
expect(execSpy).toHaveBeenCalledWith(`buildx`, [], {
silent: true,
ignoreReturnCode: true
});
});

describe('getVersion', () => {
it('valid', async () => {
const version = await buildx.getVersion();
Expand Down Expand Up @@ -75,29 +86,32 @@ describe('build', () => {

// eslint-disable-next-line jest/no-disabled-tests
it.skip('builds refs/pull/648/head', async () => {
const buildxBin = await buildx.build('https://github.com/docker/buildx.git#refs/pull/648/head', tmpDir);
const buildxBin = await buildx.build('https://github.com/docker/buildx.git#refs/pull/648/head', tmpDir, false);
expect(fs.existsSync(buildxBin)).toBe(true);
}, 100000);

// eslint-disable-next-line jest/no-disabled-tests
it.skip('builds 67bd6f4dc82a9cd96f34133dab3f6f7af803bb14', async () => {
const buildxBin = await buildx.build('https://github.com/docker/buildx.git#67bd6f4dc82a9cd96f34133dab3f6f7af803bb14', tmpDir);
const buildxBin = await buildx.build('https://github.com/docker/buildx.git#67bd6f4dc82a9cd96f34133dab3f6f7af803bb14', tmpDir, false);
expect(fs.existsSync(buildxBin)).toBe(true);
}, 100000);
});

describe('install', () => {
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'setup-buildx-'));

it('acquires v0.4.1 version of buildx', async () => {
const buildxBin = await buildx.install('v0.4.1', tmpDir);
expect(fs.existsSync(buildxBin)).toBe(true);
}, 100000);

it('acquires latest version of buildx', async () => {
const buildxBin = await buildx.install('latest', tmpDir);
expect(fs.existsSync(buildxBin)).toBe(true);
}, 100000);
test.each([
['v0.4.1', false],
['latest', false],
['v0.4.1', true],
['latest', true]
])(
'acquires %p of buildx (standalone: %p)',
async (version, standalone) => {
const buildxBin = await buildx.install(version, tmpDir, standalone);
expect(fs.existsSync(buildxBin)).toBe(true);
},
100000
);
});

describe('getConfig', () => {
Expand Down
16 changes: 16 additions & 0 deletions __tests__/docker.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import {describe, expect, it, jest} from '@jest/globals';
import * as docker from '../src/docker';
import * as exec from '@actions/exec';

describe('isAvailable', () => {
it('cli', () => {
const execSpy = jest.spyOn(exec, 'getExecOutput');
docker.isAvailable();

// eslint-disable-next-line jest/no-standalone-expect
expect(execSpy).toHaveBeenCalledWith(`docker`, undefined, {
silent: true,
ignoreReturnCode: true
});
});
});
4 changes: 2 additions & 2 deletions dist/index.js

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion dist/index.js.map

Large diffs are not rendered by default.

90 changes: 78 additions & 12 deletions src/buildx.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,10 @@ export async function getConfig(s: string, file: boolean): Promise<string> {
return configFile;
}

export async function isAvailable(): Promise<boolean> {
export async function isAvailable(standalone?: boolean): Promise<boolean> {
const cmd = getCommand([], standalone);
return await exec
.getExecOutput('docker', ['buildx'], {
.getExecOutput(cmd.commandLine, cmd.args, {
ignoreReturnCode: true,
silent: true
})
Expand All @@ -52,12 +53,17 @@ export async function isAvailable(): Promise<boolean> {
return false;
}
return res.exitCode == 0;
})
// eslint-disable-next-line @typescript-eslint/no-unused-vars
.catch(error => {
return false;
});
}

export async function getVersion(): Promise<string> {
export async function getVersion(standalone?: boolean): Promise<string> {
const cmd = getCommand(['version'], standalone);
return await exec
.getExecOutput('docker', ['buildx', 'version'], {
.getExecOutput(cmd.commandLine, cmd.args, {
ignoreReturnCode: true,
silent: true
})
Expand All @@ -81,9 +87,10 @@ export function satisfies(version: string, range: string): boolean {
return semver.satisfies(version, range) || /^[0-9a-f]{7}$/.exec(version) !== null;
}

export async function inspect(name: string): Promise<Builder> {
export async function inspect(name: string, standalone?: boolean): Promise<Builder> {
const cmd = getCommand(['inspect', name], standalone);
return await exec
.getExecOutput(`docker`, ['buildx', 'inspect', name], {
.getExecOutput(cmd.commandLine, cmd.args, {
ignoreReturnCode: true,
silent: true
})
Expand Down Expand Up @@ -133,7 +140,7 @@ export async function inspect(name: string): Promise<Builder> {
});
}

export async function build(inputBuildRef: string, dockerConfigHome: string): Promise<string> {
export async function build(inputBuildRef: string, dest: string, standalone: boolean): Promise<string> {
// eslint-disable-next-line prefer-const
let [repo, ref] = inputBuildRef.split('#');
if (ref.length == 0) {
Expand All @@ -152,8 +159,27 @@ export async function build(inputBuildRef: string, dockerConfigHome: string): Pr
toolPath = tc.find('buildx', vspec);
if (!toolPath) {
const outFolder = path.join(context.tmpDir(), 'out').split(path.sep).join(path.posix.sep);
let buildWithStandalone = false;
const standaloneFound = await isAvailable(true);
const pluginFound = await isAvailable(false);
if (standalone && standaloneFound) {
core.debug(`Buildx standalone found, build with it`);
buildWithStandalone = true;
} else if (!standalone && pluginFound) {
core.debug(`Buildx plugin found, build with it`);
buildWithStandalone = false;
} else if (standaloneFound) {
core.debug(`Buildx plugin not found, but standalone found so trying to build with it`);
buildWithStandalone = true;
} else if (pluginFound) {
core.debug(`Buildx standalone not found, but plugin found so trying to build with it`);
buildWithStandalone = false;
} else {
throw new Error(`Neither buildx standalone or plugin have been found to build from ref`);
}
const buildCmd = getCommand(['build', '--target', 'binaries', '--build-arg', 'BUILDKIT_CONTEXT_KEEP_GIT_DIR=1', '--output', `type=local,dest=${outFolder}`, inputBuildRef], buildWithStandalone);
toolPath = await exec
.getExecOutput('docker', ['buildx', 'build', '--target', 'binaries', '--build-arg', 'BUILDKIT_CONTEXT_KEEP_GIT_DIR=1', '--output', `type=local,dest=${outFolder}`, inputBuildRef], {
.getExecOutput(buildCmd.commandLine, buildCmd.args, {
ignoreReturnCode: true
})
.then(res => {
Expand All @@ -164,10 +190,13 @@ export async function build(inputBuildRef: string, dockerConfigHome: string): Pr
});
}

return setPlugin(toolPath, dockerConfigHome);
if (standalone) {
return setStandalone(toolPath, dest);
}
return setPlugin(toolPath, dest);
}

export async function install(inputVersion: string, dockerConfigHome: string): Promise<string> {
export async function install(inputVersion: string, dest: string, standalone: boolean): Promise<string> {
const release: github.GitHubRelease | null = await github.getRelease(inputVersion);
if (!release) {
throw new Error(`Cannot find buildx ${inputVersion} release`);
Expand All @@ -185,10 +214,40 @@ export async function install(inputVersion: string, dockerConfigHome: string): P
toolPath = await download(version);
}

return setPlugin(toolPath, dockerConfigHome);
if (standalone) {
return setStandalone(toolPath, dest);
}
return setPlugin(toolPath, dest);
}

async function setStandalone(toolPath: string, dest: string): Promise<string> {
core.info('Standalone mode');
const toolBinPath = path.join(toolPath, context.osPlat == 'win32' ? 'docker-buildx.exe' : 'docker-buildx');

const binDir = path.join(dest, 'bin');
core.debug(`Bin dir is ${binDir}`);
if (!fs.existsSync(binDir)) {
fs.mkdirSync(binDir, {recursive: true});
}

const filename: string = context.osPlat == 'win32' ? 'buildx.exe' : 'buildx';
const buildxPath: string = path.join(binDir, filename);
core.debug(`Bin path is ${buildxPath}`);
fs.copyFileSync(toolBinPath, buildxPath);

core.info('Fixing perms');
fs.chmodSync(buildxPath, '0755');

core.addPath(binDir);
core.info('Added buildx to the path');

return buildxPath;
}

async function setPlugin(toolPath: string, dockerConfigHome: string): Promise<string> {
core.info('Docker plugin mode');
const toolBinPath = path.join(toolPath, context.osPlat == 'win32' ? 'docker-buildx.exe' : 'docker-buildx');

const pluginsDir: string = path.join(dockerConfigHome, 'cli-plugins');
core.debug(`Plugins dir is ${pluginsDir}`);
if (!fs.existsSync(pluginsDir)) {
Expand All @@ -198,7 +257,7 @@ async function setPlugin(toolPath: string, dockerConfigHome: string): Promise<st
const filename: string = context.osPlat == 'win32' ? 'docker-buildx.exe' : 'docker-buildx';
const pluginPath: string = path.join(pluginsDir, filename);
core.debug(`Plugin path is ${pluginPath}`);
fs.copyFileSync(path.join(toolPath, filename), pluginPath);
fs.copyFileSync(toolBinPath, pluginPath);

core.info('Fixing perms');
fs.chmodSync(pluginPath, '0755');
Expand Down Expand Up @@ -269,3 +328,10 @@ export async function getBuildKitVersion(containerID: string): Promise<string> {
return bkitimage.stdout.trim();
});
}

export function getCommand(args: Array<string>, standalone?: boolean) {
return {
commandLine: standalone ? 'buildx' : 'docker',
args: standalone ? args : ['buildx', ...args]
};
}
19 changes: 19 additions & 0 deletions src/docker.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import * as exec from '@actions/exec';

export async function isAvailable(): Promise<boolean> {
return await exec
.getExecOutput('docker', undefined, {
ignoreReturnCode: true,
silent: true
})
.then(res => {
if (res.stderr.length > 0 && res.exitCode != 0) {
return false;
}
return res.exitCode == 0;
})
// eslint-disable-next-line @typescript-eslint/no-unused-vars
.catch(error => {
return false;
});
}
Loading

0 comments on commit 3472856

Please sign in to comment.