2018-04-25 14:20:07 +00:00
|
|
|
/*
|
2020-01-29 11:10:59 +00:00
|
|
|
Copyright 2016-2020 Balena Ltd.
|
2018-04-25 14:20:07 +00:00
|
|
|
|
|
|
|
Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
you may not use this file except in compliance with the License.
|
|
|
|
You may obtain a copy of the License at
|
|
|
|
|
|
|
|
http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
|
|
|
|
Unless required by applicable law or agreed to in writing, software
|
|
|
|
distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
See the License for the specific language governing permissions and
|
|
|
|
limitations under the License.
|
|
|
|
*/
|
2020-02-27 12:38:50 +00:00
|
|
|
import type { BalenaSDK } from 'balena-sdk';
|
2018-04-25 14:20:07 +00:00
|
|
|
import * as JSONStream from 'JSONStream';
|
2019-03-04 15:06:31 +00:00
|
|
|
import * as readline from 'readline';
|
2018-04-25 14:20:07 +00:00
|
|
|
import * as request from 'request';
|
2019-03-12 22:07:57 +00:00
|
|
|
import { RegistrySecrets } from 'resin-multibuild';
|
2020-02-27 12:38:50 +00:00
|
|
|
import type * as Stream from 'stream';
|
2019-07-25 09:11:41 +00:00
|
|
|
import streamToPromise = require('stream-to-promise');
|
2020-02-27 12:38:50 +00:00
|
|
|
import type { Pack } from 'tar-stream';
|
2018-04-25 14:20:07 +00:00
|
|
|
|
2020-03-05 01:02:46 +00:00
|
|
|
import { ExpectedError } from '../errors';
|
2020-04-30 08:45:16 +00:00
|
|
|
import { exitWithExpectedError } from '../errors';
|
2018-04-25 14:20:07 +00:00
|
|
|
import { tarDirectory } from './compose';
|
2020-05-04 14:57:23 +00:00
|
|
|
import { getVisuals, stripIndent } from './lazy';
|
2020-03-05 01:02:46 +00:00
|
|
|
import Logger = require('./logger');
|
2018-04-25 14:20:07 +00:00
|
|
|
|
2020-01-29 11:10:59 +00:00
|
|
|
const globalLogger = Logger.getLogger();
|
|
|
|
|
2018-04-25 14:20:07 +00:00
|
|
|
const DEBUG_MODE = !!process.env.DEBUG;
|
|
|
|
|
|
|
|
const CURSOR_METADATA_REGEX = /([a-z]+)([0-9]+)?/;
|
|
|
|
const TRIM_REGEX = /\n+$/;
|
|
|
|
|
2018-06-21 13:29:25 +00:00
|
|
|
export interface BuildOpts {
|
2019-04-11 11:49:19 +00:00
|
|
|
dockerfilePath: string;
|
2018-06-21 13:29:25 +00:00
|
|
|
emulated: boolean;
|
|
|
|
nocache: boolean;
|
2018-11-07 18:15:05 +00:00
|
|
|
registrySecrets: RegistrySecrets;
|
2019-07-25 09:11:41 +00:00
|
|
|
headless: boolean;
|
2020-01-29 11:10:59 +00:00
|
|
|
convertEol: boolean;
|
2020-06-24 23:01:53 +00:00
|
|
|
multiDockerignore: boolean;
|
2018-06-21 13:29:25 +00:00
|
|
|
}
|
|
|
|
|
2018-04-25 14:20:07 +00:00
|
|
|
export interface RemoteBuild {
|
|
|
|
app: string;
|
|
|
|
owner: string;
|
|
|
|
source: string;
|
|
|
|
auth: string;
|
|
|
|
baseUrl: string;
|
2020-05-01 11:18:11 +00:00
|
|
|
nogitignore: boolean;
|
2018-06-21 13:29:25 +00:00
|
|
|
opts: BuildOpts;
|
2018-04-25 14:20:07 +00:00
|
|
|
|
2018-10-19 14:38:50 +00:00
|
|
|
sdk: BalenaSDK;
|
2018-04-25 14:20:07 +00:00
|
|
|
|
|
|
|
// For internal use
|
|
|
|
releaseId?: number;
|
2018-08-17 00:33:12 +00:00
|
|
|
hadError?: boolean;
|
2018-04-25 14:20:07 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
interface BuilderMessage {
|
|
|
|
message: string;
|
|
|
|
type?: string;
|
|
|
|
replace?: boolean;
|
2018-08-17 00:33:12 +00:00
|
|
|
isError?: boolean;
|
2018-04-25 14:20:07 +00:00
|
|
|
// These will be set when the type === 'metadata'
|
|
|
|
resource?: string;
|
|
|
|
value?: string;
|
|
|
|
}
|
|
|
|
|
2019-07-25 09:11:41 +00:00
|
|
|
interface HeadlessBuilderMessage {
|
|
|
|
started: boolean;
|
|
|
|
error?: string;
|
|
|
|
message?: string;
|
|
|
|
releaseId?: number;
|
|
|
|
}
|
|
|
|
|
2020-03-05 01:02:46 +00:00
|
|
|
export class RemoteBuildFailedError extends ExpectedError {
|
2018-09-04 21:01:21 +00:00
|
|
|
public constructor(message = 'Remote build failed') {
|
|
|
|
super(message);
|
2018-08-17 00:33:12 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-04-25 14:20:07 +00:00
|
|
|
async function getBuilderEndpoint(
|
|
|
|
baseUrl: string,
|
|
|
|
owner: string,
|
|
|
|
app: string,
|
2018-06-21 13:29:25 +00:00
|
|
|
opts: BuildOpts,
|
2018-04-25 14:20:07 +00:00
|
|
|
): Promise<string> {
|
|
|
|
const querystring = await import('querystring');
|
2018-06-21 13:29:25 +00:00
|
|
|
const args = querystring.stringify({
|
|
|
|
owner,
|
|
|
|
app,
|
2019-04-11 11:49:19 +00:00
|
|
|
dockerfilePath: opts.dockerfilePath,
|
2018-06-21 13:29:25 +00:00
|
|
|
emulated: opts.emulated,
|
|
|
|
nocache: opts.nocache,
|
2019-07-25 09:11:41 +00:00
|
|
|
headless: opts.headless,
|
2018-06-21 13:29:25 +00:00
|
|
|
});
|
2018-11-07 18:15:05 +00:00
|
|
|
// Note that using https (rather than http) is a requirement when using the
|
|
|
|
// --registry-secrets feature, as the secrets are not otherwise encrypted.
|
2020-06-15 22:53:04 +00:00
|
|
|
let builderUrl =
|
|
|
|
process.env.BALENARC_BUILDER_URL || `https://builder.${baseUrl}`;
|
|
|
|
if (builderUrl.endsWith('/')) {
|
|
|
|
builderUrl = builderUrl.slice(0, -1);
|
|
|
|
}
|
|
|
|
return `${builderUrl}/v3/build?${args}`;
|
2018-04-25 14:20:07 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
export async function startRemoteBuild(build: RemoteBuild): Promise<void> {
|
2019-03-04 15:06:31 +00:00
|
|
|
const stream = await getRemoteBuildStream(build);
|
2018-08-15 01:04:36 +00:00
|
|
|
|
|
|
|
// Special windows handling (win64 also reports win32)
|
|
|
|
if (process.platform === 'win32') {
|
2019-03-04 15:06:31 +00:00
|
|
|
const rl = readline.createInterface({
|
2018-08-15 01:04:36 +00:00
|
|
|
input: process.stdin,
|
|
|
|
output: process.stdout,
|
|
|
|
});
|
2018-04-25 14:20:07 +00:00
|
|
|
|
2019-04-25 17:39:16 +00:00
|
|
|
rl.on('SIGINT', () => process.emit('SIGINT' as any));
|
2018-08-15 01:04:36 +00:00
|
|
|
}
|
2018-04-25 14:20:07 +00:00
|
|
|
|
2019-07-25 09:11:41 +00:00
|
|
|
if (!build.opts.headless) {
|
2020-06-30 20:24:35 +00:00
|
|
|
return new Promise((resolve, reject) => {
|
2019-07-25 09:11:41 +00:00
|
|
|
// Setup interrupt handlers so we can cancel the build if the user presses
|
|
|
|
// ctrl+c
|
|
|
|
|
|
|
|
// This is necessary because the `exit-hook` module is used by several
|
|
|
|
// dependencies, and will exit without calling the following handler.
|
|
|
|
// Once https://github.com/balena-io/balena-cli/issues/867 has been solved,
|
|
|
|
// we are free to (and definitely should) remove the below line
|
|
|
|
process.removeAllListeners('SIGINT');
|
|
|
|
process.on('SIGINT', () => {
|
|
|
|
process.stderr.write('Received SIGINT, cleaning up. Please wait.\n');
|
|
|
|
cancelBuildIfNecessary(build).then(() => {
|
|
|
|
stream.end();
|
|
|
|
process.exit(130);
|
|
|
|
});
|
2018-04-25 14:20:07 +00:00
|
|
|
});
|
2019-07-25 09:11:41 +00:00
|
|
|
|
|
|
|
stream.on('data', getBuilderMessageHandler(build));
|
|
|
|
stream.on('end', resolve);
|
|
|
|
stream.on('error', reject);
|
|
|
|
}).then(() => {
|
2020-03-05 01:02:46 +00:00
|
|
|
globalLogger.outputDeferredMessages();
|
2019-07-25 09:11:41 +00:00
|
|
|
if (build.hadError) {
|
|
|
|
throw new RemoteBuildFailedError();
|
|
|
|
}
|
2018-04-25 14:20:07 +00:00
|
|
|
});
|
2019-07-25 09:11:41 +00:00
|
|
|
}
|
2018-04-25 14:20:07 +00:00
|
|
|
|
2019-07-25 09:11:41 +00:00
|
|
|
// We're running a headless build, which means we'll
|
|
|
|
// get a single object back, detailing if the build has
|
|
|
|
// been started
|
|
|
|
let result: HeadlessBuilderMessage;
|
|
|
|
try {
|
|
|
|
const response = await streamToPromise(stream);
|
|
|
|
result = JSON.parse(response.toString());
|
|
|
|
} catch (e) {
|
|
|
|
throw new Error(
|
|
|
|
`There was an error reading the response from the remote builder: ${e}`,
|
|
|
|
);
|
|
|
|
}
|
|
|
|
handleHeadlessBuildMessage(result);
|
|
|
|
}
|
|
|
|
|
|
|
|
function handleHeadlessBuildMessage(message: HeadlessBuilderMessage) {
|
|
|
|
if (!process.stdout.isTTY) {
|
|
|
|
process.stdout.write(JSON.stringify(message));
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (message.started) {
|
|
|
|
console.log('Build successfully started');
|
|
|
|
console.log(` Release ID: ${message.releaseId!}`);
|
|
|
|
} else {
|
|
|
|
console.log('Failed to start remote build');
|
|
|
|
console.log(` Error: ${message.error!}`);
|
|
|
|
console.log(` Message: ${message.message!}`);
|
|
|
|
}
|
2018-04-25 14:20:07 +00:00
|
|
|
}
|
|
|
|
|
2019-03-04 15:06:31 +00:00
|
|
|
function handleBuilderMetadata(obj: BuilderMessage, build: RemoteBuild) {
|
2018-04-25 14:20:07 +00:00
|
|
|
switch (obj.resource) {
|
|
|
|
case 'cursor':
|
|
|
|
if (obj.value == null) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
const match = obj.value.match(CURSOR_METADATA_REGEX);
|
|
|
|
|
|
|
|
if (!match) {
|
|
|
|
// FIXME: Make this error nicer.
|
|
|
|
console.log(
|
|
|
|
stripIndent`
|
|
|
|
Warning: ignoring unknown builder command. You may experience
|
2018-10-19 14:38:50 +00:00
|
|
|
odd build output. Maybe you need to update balena-cli?`,
|
2018-04-25 14:20:07 +00:00
|
|
|
);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
const value = match[1];
|
|
|
|
const amount = match[2] || 1;
|
|
|
|
|
|
|
|
switch (value) {
|
|
|
|
case 'erase':
|
|
|
|
readline.clearLine(process.stdout, 0);
|
|
|
|
process.stdout.write('\r');
|
|
|
|
break;
|
|
|
|
case 'up':
|
|
|
|
readline.moveCursor(process.stdout, 0, -amount);
|
|
|
|
break;
|
|
|
|
case 'down':
|
|
|
|
readline.moveCursor(process.stdout, 0, amount);
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
|
|
|
|
break;
|
|
|
|
case 'buildLogId':
|
|
|
|
// The name of this resource is slightly dated, but this is the release
|
|
|
|
// id from the API. We need to save this so that if the user ctrl+c's the
|
|
|
|
// build we can cancel it on the API.
|
|
|
|
build.releaseId = parseInt(obj.value!, 10);
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
function getBuilderMessageHandler(
|
|
|
|
build: RemoteBuild,
|
2019-03-04 15:06:31 +00:00
|
|
|
): (obj: BuilderMessage) => void {
|
|
|
|
return (obj: BuilderMessage) => {
|
2018-04-25 14:20:07 +00:00
|
|
|
if (DEBUG_MODE) {
|
2019-09-18 12:13:35 +00:00
|
|
|
console.error(`[debug] handling message: ${JSON.stringify(obj)}`);
|
2018-04-25 14:20:07 +00:00
|
|
|
}
|
|
|
|
if (obj.type != null && obj.type === 'metadata') {
|
|
|
|
return handleBuilderMetadata(obj, build);
|
|
|
|
}
|
|
|
|
if (obj.message) {
|
|
|
|
readline.clearLine(process.stdout, 0);
|
|
|
|
|
|
|
|
const message = obj.message.replace(TRIM_REGEX, '');
|
|
|
|
if (obj.replace) {
|
|
|
|
process.stdout.write(`\r${message}`);
|
|
|
|
} else {
|
|
|
|
process.stdout.write(`\r${message}\n`);
|
|
|
|
}
|
|
|
|
}
|
2018-08-17 00:33:12 +00:00
|
|
|
if (obj.isError) {
|
|
|
|
build.hadError = true;
|
|
|
|
}
|
2018-04-25 14:20:07 +00:00
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
async function cancelBuildIfNecessary(build: RemoteBuild): Promise<void> {
|
|
|
|
if (build.releaseId != null) {
|
|
|
|
await build.sdk.pine.patch({
|
|
|
|
resource: 'release',
|
|
|
|
id: build.releaseId,
|
2019-04-22 17:09:00 +00:00
|
|
|
options: {
|
|
|
|
$filter: {
|
|
|
|
status: { $ne: 'success' },
|
|
|
|
},
|
|
|
|
},
|
2018-04-25 14:20:07 +00:00
|
|
|
body: {
|
|
|
|
status: 'cancelled',
|
|
|
|
end_timestamp: Date.now(),
|
|
|
|
},
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-11-07 18:15:05 +00:00
|
|
|
/**
|
2019-03-04 15:06:31 +00:00
|
|
|
* Call tarDirectory() with a suitable callback to insert registry secrets in
|
|
|
|
* the tar stream, and return the stream.
|
2018-11-07 18:15:05 +00:00
|
|
|
*/
|
2019-03-04 15:06:31 +00:00
|
|
|
async function getTarStream(build: RemoteBuild): Promise<Stream.Readable> {
|
2019-07-25 09:11:41 +00:00
|
|
|
let tarSpinner = {
|
|
|
|
start: () => {
|
|
|
|
/*noop*/
|
|
|
|
},
|
|
|
|
stop: () => {
|
|
|
|
/*noop*/
|
|
|
|
},
|
|
|
|
};
|
|
|
|
if (process.stdout.isTTY) {
|
2020-02-28 13:06:14 +00:00
|
|
|
const visuals = getVisuals();
|
2019-07-25 09:11:41 +00:00
|
|
|
tarSpinner = new visuals.Spinner('Packaging the project source...');
|
|
|
|
}
|
|
|
|
|
2018-04-25 14:20:07 +00:00
|
|
|
const path = await import('path');
|
2019-03-04 15:06:31 +00:00
|
|
|
const preFinalizeCallback = (pack: Pack) => {
|
|
|
|
pack.entry(
|
|
|
|
{ name: '.balena/registry-secrets.json' },
|
|
|
|
JSON.stringify(build.opts.registrySecrets),
|
|
|
|
);
|
|
|
|
};
|
2018-04-25 14:20:07 +00:00
|
|
|
|
2019-03-04 15:06:31 +00:00
|
|
|
try {
|
|
|
|
tarSpinner.start();
|
2020-01-29 11:10:59 +00:00
|
|
|
const preFinalizeCb =
|
2019-03-04 15:06:31 +00:00
|
|
|
Object.keys(build.opts.registrySecrets).length > 0
|
|
|
|
? preFinalizeCallback
|
2020-01-29 11:10:59 +00:00
|
|
|
: undefined;
|
|
|
|
return await tarDirectory(path.resolve(build.source), {
|
|
|
|
preFinalizeCallback: preFinalizeCb,
|
|
|
|
convertEol: build.opts.convertEol,
|
2020-06-24 23:01:53 +00:00
|
|
|
multiDockerignore: build.opts.multiDockerignore,
|
2020-05-01 11:18:11 +00:00
|
|
|
nogitignore: build.nogitignore,
|
2020-01-29 11:10:59 +00:00
|
|
|
});
|
2019-03-04 15:06:31 +00:00
|
|
|
} finally {
|
|
|
|
tarSpinner.stop();
|
|
|
|
}
|
|
|
|
}
|
2018-11-07 18:15:05 +00:00
|
|
|
|
2019-03-04 15:06:31 +00:00
|
|
|
/**
|
|
|
|
* Initiate a POST HTTP request to the remote builder and add some event
|
|
|
|
* listeners.
|
|
|
|
*
|
|
|
|
* ¡! Note: this function must be synchronous because of a bug in the `request`
|
|
|
|
* library that requires the following two steps to take place in the same
|
|
|
|
* iteration of Node's event loop: (1) adding a listener for the 'response'
|
|
|
|
* event and (2) calling request.pipe():
|
|
|
|
* https://github.com/request/request/issues/887
|
|
|
|
*/
|
|
|
|
function createRemoteBuildRequest(
|
|
|
|
build: RemoteBuild,
|
|
|
|
tarStream: Stream.Readable,
|
|
|
|
builderUrl: string,
|
|
|
|
onError: (error: Error) => void,
|
|
|
|
): request.Request {
|
2020-06-30 19:54:35 +00:00
|
|
|
const zlib = require('zlib') as typeof import('zlib');
|
2018-04-25 14:20:07 +00:00
|
|
|
if (DEBUG_MODE) {
|
2019-09-18 12:13:35 +00:00
|
|
|
console.error(`[debug] Connecting to builder at ${builderUrl}`);
|
2018-04-25 14:20:07 +00:00
|
|
|
}
|
2019-03-04 15:06:31 +00:00
|
|
|
return request
|
|
|
|
.post({
|
|
|
|
url: builderUrl,
|
|
|
|
auth: { bearer: build.auth },
|
|
|
|
headers: { 'Content-Encoding': 'gzip' },
|
|
|
|
body: tarStream.pipe(zlib.createGzip({ level: 6 })),
|
|
|
|
})
|
|
|
|
.on('error', onError)
|
|
|
|
.once('response', (response: request.RequestResponse) => {
|
|
|
|
if (response.statusCode >= 100 && response.statusCode < 400) {
|
|
|
|
if (DEBUG_MODE) {
|
2019-09-18 12:13:35 +00:00
|
|
|
console.error(
|
2020-01-20 21:21:05 +00:00
|
|
|
`[debug] received HTTP ${response.statusCode} ${response.statusMessage}`,
|
2019-03-04 15:06:31 +00:00
|
|
|
);
|
|
|
|
}
|
|
|
|
} else {
|
2019-03-12 22:07:57 +00:00
|
|
|
const msgArr = [
|
2019-03-04 15:06:31 +00:00
|
|
|
'Remote builder responded with HTTP error:',
|
|
|
|
`${response.statusCode} ${response.statusMessage}`,
|
|
|
|
];
|
|
|
|
if (response.body) {
|
|
|
|
msgArr.push(response.body);
|
|
|
|
}
|
|
|
|
onError(new Error(msgArr.join('\n')));
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
2018-04-25 14:20:07 +00:00
|
|
|
|
2019-03-04 15:06:31 +00:00
|
|
|
async function getRemoteBuildStream(
|
|
|
|
build: RemoteBuild,
|
|
|
|
): Promise<NodeJS.ReadWriteStream> {
|
2019-07-25 09:11:41 +00:00
|
|
|
const builderUrl = await getBuilderEndpoint(
|
|
|
|
build.baseUrl,
|
|
|
|
build.owner,
|
|
|
|
build.app,
|
|
|
|
build.opts,
|
2018-04-25 14:20:07 +00:00
|
|
|
);
|
2019-07-25 09:11:41 +00:00
|
|
|
|
|
|
|
let uploadSpinner = {
|
|
|
|
stop: () => {
|
|
|
|
/* noop */
|
|
|
|
},
|
|
|
|
};
|
|
|
|
let exitOnError = (error: Error) => {
|
2019-03-04 15:06:31 +00:00
|
|
|
return exitWithExpectedError(error);
|
|
|
|
};
|
2019-07-25 09:11:41 +00:00
|
|
|
// We only show the spinner when outputting to a tty
|
|
|
|
if (process.stdout.isTTY) {
|
2020-02-28 13:06:14 +00:00
|
|
|
const visuals = getVisuals();
|
2019-07-25 09:11:41 +00:00
|
|
|
uploadSpinner = new visuals.Spinner(
|
2020-09-18 14:35:36 +00:00
|
|
|
'Uploading source package to balenaCloud',
|
2019-07-25 09:11:41 +00:00
|
|
|
);
|
|
|
|
exitOnError = (error: Error): never => {
|
|
|
|
uploadSpinner.stop();
|
|
|
|
return exitWithExpectedError(error);
|
|
|
|
};
|
|
|
|
// This is not strongly typed to start with, so we cast
|
|
|
|
// to any to allow the method call
|
|
|
|
(uploadSpinner as any).start();
|
|
|
|
}
|
2018-04-25 14:20:07 +00:00
|
|
|
|
2019-03-04 15:06:31 +00:00
|
|
|
try {
|
2019-07-25 09:11:41 +00:00
|
|
|
const tarStream = await getTarStream(build);
|
2019-03-04 15:06:31 +00:00
|
|
|
const buildRequest = createRemoteBuildRequest(
|
|
|
|
build,
|
|
|
|
tarStream,
|
|
|
|
builderUrl,
|
|
|
|
exitOnError,
|
|
|
|
);
|
2019-07-25 09:11:41 +00:00
|
|
|
let stream: NodeJS.ReadWriteStream;
|
|
|
|
if (build.opts.headless) {
|
|
|
|
stream = (buildRequest as unknown) as NodeJS.ReadWriteStream;
|
|
|
|
} else {
|
|
|
|
stream = buildRequest.pipe(JSONStream.parse('*'));
|
|
|
|
}
|
|
|
|
return stream
|
|
|
|
.once('close', () => uploadSpinner.stop())
|
|
|
|
.once('data', () => uploadSpinner.stop())
|
|
|
|
.once('end', () => uploadSpinner.stop())
|
|
|
|
.once('error', () => uploadSpinner.stop())
|
|
|
|
.once('finish', () => uploadSpinner.stop());
|
2019-03-04 15:06:31 +00:00
|
|
|
} catch (error) {
|
|
|
|
return exitOnError(error);
|
|
|
|
}
|
2018-04-25 14:20:07 +00:00
|
|
|
}
|