2018-11-07 18:15:05 +00:00
|
|
|
/**
|
|
|
|
* @license
|
2021-04-27 13:58:54 +00:00
|
|
|
* Copyright 2018-2021 Balena Ltd.
|
2018-11-07 18:15:05 +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-03-02 17:13:16 +00:00
|
|
|
import * as semver from 'balena-semver';
|
2018-10-16 10:25:37 +00:00
|
|
|
import * as Docker from 'dockerode';
|
|
|
|
import * as _ from 'lodash';
|
2022-06-28 12:22:42 +00:00
|
|
|
import { Composition } from '@balena/compose/dist/parse';
|
2019-02-07 15:10:16 +00:00
|
|
|
import {
|
|
|
|
BuildTask,
|
|
|
|
getAuthConfigObj,
|
|
|
|
LocalImage,
|
|
|
|
RegistrySecrets,
|
2022-06-28 12:22:42 +00:00
|
|
|
} from '@balena/compose/dist/multibuild';
|
2020-02-27 12:38:50 +00:00
|
|
|
import type { Readable } from 'stream';
|
2018-10-16 10:25:37 +00:00
|
|
|
|
2019-07-09 14:43:36 +00:00
|
|
|
import { BALENA_ENGINE_TMP_PATH } from '../../config';
|
2020-12-03 20:50:00 +00:00
|
|
|
import { ExpectedError } from '../../errors';
|
2020-02-15 20:20:56 +00:00
|
|
|
import {
|
|
|
|
checkBuildSecretsRequirements,
|
|
|
|
loadProject,
|
|
|
|
makeBuildTasks,
|
2020-10-15 23:26:00 +00:00
|
|
|
tarDirectory,
|
2021-11-25 17:03:38 +00:00
|
|
|
makeImageName,
|
2020-02-15 20:20:56 +00:00
|
|
|
} from '../compose_ts';
|
2019-03-12 22:07:57 +00:00
|
|
|
import Logger = require('../logger');
|
2019-04-19 15:17:06 +00:00
|
|
|
import { DeviceAPI, DeviceInfo } from './api';
|
2018-10-16 10:25:37 +00:00
|
|
|
import * as LocalPushErrors from './errors';
|
2019-01-14 16:51:57 +00:00
|
|
|
import LivepushManager from './live';
|
2019-03-12 22:07:57 +00:00
|
|
|
import { displayBuildLog } from './logs';
|
2021-02-04 08:50:53 +00:00
|
|
|
import { stripIndent } from '../lazy';
|
2018-10-16 10:25:37 +00:00
|
|
|
|
2020-02-18 03:21:12 +00:00
|
|
|
const LOCAL_APPNAME = 'localapp';
|
2023-04-27 16:40:46 +00:00
|
|
|
const LOCAL_RELEASEHASH = '10ca12e1ea5e';
|
2021-11-25 17:03:38 +00:00
|
|
|
const LOCAL_PROJECT_NAME = 'local_image';
|
2020-02-18 03:21:12 +00:00
|
|
|
|
2018-10-16 10:25:37 +00:00
|
|
|
// Define the logger here so the debug output
|
|
|
|
// can be used everywhere
|
2019-09-11 18:34:43 +00:00
|
|
|
const globalLogger = Logger.getLogger();
|
2018-10-16 10:25:37 +00:00
|
|
|
|
|
|
|
export interface DeviceDeployOptions {
|
|
|
|
source: string;
|
|
|
|
deviceHost: string;
|
|
|
|
devicePort?: number;
|
2019-04-11 11:49:19 +00:00
|
|
|
dockerfilePath?: string;
|
2018-11-07 18:15:05 +00:00
|
|
|
registrySecrets: RegistrySecrets;
|
2020-06-24 23:01:53 +00:00
|
|
|
multiDockerignore: boolean;
|
2019-03-28 12:20:08 +00:00
|
|
|
nocache: boolean;
|
2020-02-15 20:20:56 +00:00
|
|
|
noParentCheck: boolean;
|
2019-05-29 14:09:05 +00:00
|
|
|
nolive: boolean;
|
2020-09-08 13:55:56 +00:00
|
|
|
pull: boolean;
|
2019-04-24 13:31:30 +00:00
|
|
|
detached: boolean;
|
2019-05-28 15:56:39 +00:00
|
|
|
services?: string[];
|
2019-04-24 16:30:18 +00:00
|
|
|
system: boolean;
|
2019-05-27 10:32:47 +00:00
|
|
|
env: string[];
|
2020-01-29 11:10:59 +00:00
|
|
|
convertEol: boolean;
|
2019-05-27 10:32:47 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
interface ParsedEnvironment {
|
|
|
|
[serviceName: string]: { [key: string]: string };
|
2018-10-16 10:25:37 +00:00
|
|
|
}
|
|
|
|
|
2019-05-27 10:32:47 +00:00
|
|
|
async function environmentFromInput(
|
|
|
|
envs: string[],
|
|
|
|
serviceNames: string[],
|
|
|
|
logger: Logger,
|
|
|
|
): Promise<ParsedEnvironment> {
|
|
|
|
// A normal environment variable regex, with an added part
|
|
|
|
// to find a colon followed servicename at the start
|
|
|
|
const varRegex = /^(?:([^\s:]+):)?([^\s]+?)=(.*)$/;
|
|
|
|
|
|
|
|
const ret: ParsedEnvironment = {};
|
2019-11-27 10:34:24 +00:00
|
|
|
// Populate the object with the servicenames, as it
|
2019-05-27 10:32:47 +00:00
|
|
|
// also means that we can do a fast lookup of whether a
|
|
|
|
// service exists
|
|
|
|
for (const service of serviceNames) {
|
|
|
|
ret[service] = {};
|
|
|
|
}
|
|
|
|
|
|
|
|
for (const env of envs) {
|
|
|
|
const maybeMatch = env.match(varRegex);
|
|
|
|
if (maybeMatch == null) {
|
2020-12-03 20:50:00 +00:00
|
|
|
throw new ExpectedError(`Unable to parse environment variable: ${env}`);
|
2019-05-27 10:32:47 +00:00
|
|
|
}
|
|
|
|
const match = maybeMatch!;
|
|
|
|
let service: string | undefined;
|
|
|
|
if (match[1]) {
|
|
|
|
// This is for a service, we check that it actually
|
|
|
|
// exists
|
|
|
|
if (!(match[1] in ret)) {
|
|
|
|
logger.logDebug(
|
2020-01-20 21:21:05 +00:00
|
|
|
`Warning: Cannot find a service with name ${match[1]}. Treating the string as part of the environment variable name.`,
|
2019-05-27 10:32:47 +00:00
|
|
|
);
|
|
|
|
match[2] = `${match[1]}:${match[2]}`;
|
|
|
|
} else {
|
|
|
|
service = match[1];
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if (service != null) {
|
|
|
|
ret[service][match[2]] = match[3];
|
|
|
|
} else {
|
|
|
|
for (const serviceName of serviceNames) {
|
|
|
|
ret[serviceName][match[2]] = match[3];
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return ret;
|
|
|
|
}
|
|
|
|
|
2018-10-16 10:25:37 +00:00
|
|
|
export async function deployToDevice(opts: DeviceDeployOptions): Promise<void> {
|
2020-05-22 10:27:19 +00:00
|
|
|
// Resolve .local addresses to IP to avoid
|
|
|
|
// issue with Windows and rapid repeat lookups.
|
|
|
|
// see: https://github.com/balena-io/balena-cli/issues/1518
|
|
|
|
if (opts.deviceHost.includes('.local')) {
|
|
|
|
const util = await import('util');
|
|
|
|
const dns = await import('dns');
|
|
|
|
const { address } = await util.promisify(dns.lookup)(opts.deviceHost, {
|
|
|
|
family: 4,
|
|
|
|
});
|
|
|
|
opts.deviceHost = address;
|
|
|
|
}
|
|
|
|
|
2021-02-04 08:50:53 +00:00
|
|
|
const port = 48484;
|
|
|
|
const api = new DeviceAPI(globalLogger, opts.deviceHost, port);
|
2018-10-16 10:25:37 +00:00
|
|
|
|
2018-10-16 15:41:38 +00:00
|
|
|
// First check that we can access the device with a ping
|
|
|
|
try {
|
2019-01-14 16:51:57 +00:00
|
|
|
globalLogger.logDebug('Checking we can access device');
|
2018-10-16 15:41:38 +00:00
|
|
|
await api.ping();
|
|
|
|
} catch (e) {
|
2021-02-04 08:50:53 +00:00
|
|
|
throw new ExpectedError(stripIndent`
|
|
|
|
Could not communicate with device supervisor at address ${opts.deviceHost}:${port}.
|
|
|
|
Device may not have local mode enabled. Check with:
|
|
|
|
balena device local-mode <device-uuid>
|
|
|
|
`);
|
2018-10-16 15:41:38 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
const versionError = new Error(
|
|
|
|
'The supervisor version on this remote device does not support multicontainer local mode. ' +
|
2018-10-19 14:38:50 +00:00
|
|
|
'Please update your device to balenaOS v2.20.0 or greater from the dashboard.',
|
2018-10-16 15:41:38 +00:00
|
|
|
);
|
|
|
|
|
|
|
|
try {
|
|
|
|
const version = await api.getVersion();
|
2021-01-22 21:53:14 +00:00
|
|
|
globalLogger.logDebug(`Checking device supervisor version: ${version}`);
|
2018-10-16 15:41:38 +00:00
|
|
|
if (!semver.satisfies(version, '>=7.21.4')) {
|
2020-12-03 20:50:00 +00:00
|
|
|
throw new ExpectedError(versionError);
|
2018-10-16 15:41:38 +00:00
|
|
|
}
|
2019-05-29 14:09:05 +00:00
|
|
|
if (!opts.nolive && !semver.satisfies(version, '>=9.7.0')) {
|
|
|
|
globalLogger.logWarn(
|
|
|
|
`Using livepush requires a balena supervisor version >= 9.7.0. A live session will not be started.`,
|
2019-01-14 16:51:57 +00:00
|
|
|
);
|
2019-05-29 14:09:05 +00:00
|
|
|
opts.nolive = true;
|
2019-01-14 16:51:57 +00:00
|
|
|
}
|
2019-11-27 10:34:24 +00:00
|
|
|
} catch (e) {
|
|
|
|
// Very old supervisor versions do not support /version endpoint
|
|
|
|
// a DeviceAPIError is expected in this case
|
2020-12-03 20:50:00 +00:00
|
|
|
if (e instanceof LocalPushErrors.DeviceAPIError) {
|
|
|
|
throw new ExpectedError(versionError);
|
2019-11-27 10:34:24 +00:00
|
|
|
} else {
|
|
|
|
throw e;
|
|
|
|
}
|
2018-10-16 15:41:38 +00:00
|
|
|
}
|
2018-10-16 10:25:37 +00:00
|
|
|
|
2019-03-12 22:07:57 +00:00
|
|
|
globalLogger.logInfo(`Starting build on device ${opts.deviceHost}`);
|
2018-10-16 10:25:37 +00:00
|
|
|
|
2020-02-15 20:20:56 +00:00
|
|
|
const project = await loadProject(globalLogger, {
|
2020-06-03 13:41:12 +00:00
|
|
|
convertEol: opts.convertEol,
|
2020-02-15 20:20:56 +00:00
|
|
|
dockerfilePath: opts.dockerfilePath,
|
2020-06-24 23:01:53 +00:00
|
|
|
multiDockerignore: opts.multiDockerignore,
|
2020-02-15 20:20:56 +00:00
|
|
|
noParentCheck: opts.noParentCheck,
|
|
|
|
projectName: 'local',
|
|
|
|
projectPath: opts.source,
|
2021-02-04 12:32:37 +00:00
|
|
|
isLocal: true,
|
2020-02-15 20:20:56 +00:00
|
|
|
});
|
2018-10-16 10:25:37 +00:00
|
|
|
|
|
|
|
// Attempt to attach to the device's docker daemon
|
|
|
|
const docker = connectToDocker(
|
|
|
|
opts.deviceHost,
|
|
|
|
opts.devicePort != null ? opts.devicePort : 2375,
|
|
|
|
);
|
|
|
|
|
2019-07-09 14:43:36 +00:00
|
|
|
await checkBuildSecretsRequirements(docker, opts.source);
|
2019-08-28 18:37:36 +00:00
|
|
|
globalLogger.logDebug('Tarring all non-ignored files...');
|
2021-11-11 13:01:33 +00:00
|
|
|
const tarStartTime = Date.now();
|
2020-01-29 11:10:59 +00:00
|
|
|
const tarStream = await tarDirectory(opts.source, {
|
2020-06-24 23:01:53 +00:00
|
|
|
composition: project.composition,
|
2020-01-29 11:10:59 +00:00
|
|
|
convertEol: opts.convertEol,
|
2020-06-24 23:01:53 +00:00
|
|
|
multiDockerignore: opts.multiDockerignore,
|
2020-01-29 11:10:59 +00:00
|
|
|
});
|
2021-11-11 13:01:33 +00:00
|
|
|
globalLogger.logDebug(`Tarring complete in ${Date.now() - tarStartTime} ms`);
|
2018-10-16 10:25:37 +00:00
|
|
|
|
|
|
|
// Try to detect the device information
|
2021-11-11 13:01:33 +00:00
|
|
|
globalLogger.logDebug('Fetching device information...');
|
2018-10-16 10:25:37 +00:00
|
|
|
const deviceInfo = await api.getDeviceInformation();
|
|
|
|
|
2022-12-16 21:17:33 +00:00
|
|
|
let imageIds: Dictionary<string[]> | undefined;
|
2019-05-29 14:09:05 +00:00
|
|
|
if (!opts.nolive) {
|
2022-12-16 21:17:33 +00:00
|
|
|
imageIds = {};
|
2019-01-14 16:51:57 +00:00
|
|
|
}
|
2020-12-03 20:50:00 +00:00
|
|
|
|
|
|
|
const { awaitInterruptibleTask } = await import('../helpers');
|
|
|
|
const buildTasks = await awaitInterruptibleTask<typeof performBuilds>(
|
|
|
|
performBuilds,
|
2018-10-16 10:25:37 +00:00
|
|
|
project.composition,
|
|
|
|
tarStream,
|
|
|
|
docker,
|
|
|
|
deviceInfo,
|
2019-03-12 22:07:57 +00:00
|
|
|
globalLogger,
|
2018-11-07 18:15:05 +00:00
|
|
|
opts,
|
2022-12-16 21:17:33 +00:00
|
|
|
imageIds,
|
2018-10-16 10:25:37 +00:00
|
|
|
);
|
|
|
|
|
2020-11-07 22:28:14 +00:00
|
|
|
globalLogger.outputDeferredMessages();
|
|
|
|
// Print a newline to clearly separate build time and runtime
|
|
|
|
console.log();
|
|
|
|
|
2019-05-27 10:32:47 +00:00
|
|
|
const envs = await environmentFromInput(
|
|
|
|
opts.env,
|
|
|
|
Object.getOwnPropertyNames(project.composition.services),
|
|
|
|
globalLogger,
|
|
|
|
);
|
|
|
|
|
2019-03-12 22:07:57 +00:00
|
|
|
globalLogger.logDebug('Setting device state...');
|
2018-10-16 10:25:37 +00:00
|
|
|
// Now set the target state on the device
|
|
|
|
|
|
|
|
const currentTargetState = await api.getTargetState();
|
|
|
|
|
|
|
|
const targetState = generateTargetState(
|
|
|
|
currentTargetState,
|
|
|
|
project.composition,
|
2019-10-14 15:40:46 +00:00
|
|
|
buildTasks,
|
2019-05-27 10:32:47 +00:00
|
|
|
envs,
|
2018-10-16 10:25:37 +00:00
|
|
|
);
|
2019-03-12 22:07:57 +00:00
|
|
|
globalLogger.logDebug(`Sending target state: ${JSON.stringify(targetState)}`);
|
2018-10-16 10:25:37 +00:00
|
|
|
|
|
|
|
await api.setTargetState(targetState);
|
|
|
|
|
2019-01-14 16:51:57 +00:00
|
|
|
// Now that we've set the target state, the device will do it's thing
|
|
|
|
// so we can either just display the logs, or start a livepush session
|
|
|
|
// (whilst also display logs)
|
2020-11-07 22:28:14 +00:00
|
|
|
const promises: Array<Promise<void>> = [streamDeviceLogs(api, opts)];
|
|
|
|
let livepush: LivepushManager | null = null;
|
|
|
|
|
2019-05-29 14:09:05 +00:00
|
|
|
if (!opts.nolive) {
|
2020-11-07 22:28:14 +00:00
|
|
|
livepush = new LivepushManager({
|
2019-01-14 16:51:57 +00:00
|
|
|
api,
|
|
|
|
buildContext: opts.source,
|
|
|
|
buildTasks,
|
|
|
|
docker,
|
|
|
|
logger: globalLogger,
|
|
|
|
composition: project.composition,
|
2022-12-16 21:17:33 +00:00
|
|
|
imageIds: imageIds!,
|
2019-04-19 15:17:06 +00:00
|
|
|
deployOpts: opts,
|
2019-01-14 16:51:57 +00:00
|
|
|
});
|
2020-11-07 22:28:14 +00:00
|
|
|
promises.push(livepush.init());
|
|
|
|
if (opts.detached) {
|
2019-04-30 12:00:52 +00:00
|
|
|
globalLogger.logLivepush(
|
|
|
|
'Running in detached mode, no service logs will be shown',
|
|
|
|
);
|
2019-04-26 14:13:41 +00:00
|
|
|
}
|
2019-04-30 12:00:52 +00:00
|
|
|
globalLogger.logLivepush('Watching for file changes...');
|
2020-11-07 22:28:14 +00:00
|
|
|
}
|
2020-12-03 20:50:00 +00:00
|
|
|
try {
|
|
|
|
await awaitInterruptibleTask(() => Promise.all(promises));
|
|
|
|
} finally {
|
2020-11-07 22:28:14 +00:00
|
|
|
// Stop watching files after log streaming ends (e.g. on SIGINT)
|
|
|
|
livepush?.close();
|
2020-12-03 20:50:00 +00:00
|
|
|
await livepush?.cleanup();
|
|
|
|
}
|
2020-11-07 22:28:14 +00:00
|
|
|
}
|
2020-11-07 23:42:48 +00:00
|
|
|
|
2020-11-07 22:28:14 +00:00
|
|
|
async function streamDeviceLogs(
|
|
|
|
deviceApi: DeviceAPI,
|
|
|
|
opts: DeviceDeployOptions,
|
|
|
|
) {
|
|
|
|
// Only show logs if we're not detaching
|
|
|
|
if (opts.detached) {
|
|
|
|
return;
|
2019-01-14 16:51:57 +00:00
|
|
|
}
|
2020-11-07 22:28:14 +00:00
|
|
|
globalLogger.logInfo('Streaming device logs...');
|
|
|
|
const { connectAndDisplayDeviceLogs } = await import('./logs');
|
|
|
|
return connectAndDisplayDeviceLogs({
|
|
|
|
deviceApi,
|
|
|
|
logger: globalLogger,
|
|
|
|
system: opts.system || false,
|
|
|
|
filterServices: opts.services,
|
|
|
|
maxAttempts: 1001,
|
|
|
|
});
|
2018-10-16 10:25:37 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
function connectToDocker(host: string, port: number): Docker {
|
|
|
|
return new Docker({
|
|
|
|
host,
|
|
|
|
port,
|
2020-07-29 17:27:20 +00:00
|
|
|
Promise: require('bluebird'),
|
2018-10-16 10:25:37 +00:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2022-12-16 21:17:33 +00:00
|
|
|
function extractDockerArrowMessage(outputLine: string): string | undefined {
|
|
|
|
const arrowTest = /^.*\s*-+>\s*(.+)/i;
|
|
|
|
const match = arrowTest.exec(outputLine);
|
|
|
|
if (match != null) {
|
|
|
|
return match[1];
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-09-09 00:22:32 +00:00
|
|
|
async function performBuilds(
|
2018-10-16 10:25:37 +00:00
|
|
|
composition: Composition,
|
|
|
|
tarStream: Readable,
|
|
|
|
docker: Docker,
|
|
|
|
deviceInfo: DeviceInfo,
|
|
|
|
logger: Logger,
|
2018-11-07 18:15:05 +00:00
|
|
|
opts: DeviceDeployOptions,
|
2022-12-16 21:17:33 +00:00
|
|
|
imageIds?: Dictionary<string[]>,
|
2019-01-14 16:51:57 +00:00
|
|
|
): Promise<BuildTask[]> {
|
2022-06-28 12:22:42 +00:00
|
|
|
const multibuild = await import('@balena/compose/dist/multibuild');
|
2018-10-16 10:25:37 +00:00
|
|
|
|
2019-02-07 15:10:16 +00:00
|
|
|
const buildTasks = await makeBuildTasks(
|
|
|
|
composition,
|
|
|
|
tarStream,
|
|
|
|
deviceInfo,
|
|
|
|
logger,
|
2020-02-18 03:21:12 +00:00
|
|
|
LOCAL_APPNAME,
|
|
|
|
LOCAL_RELEASEHASH,
|
2020-06-15 22:53:07 +00:00
|
|
|
(content) => {
|
2020-05-11 17:35:24 +00:00
|
|
|
if (!opts.nolive) {
|
|
|
|
return LivepushManager.preprocessDockerfile(content);
|
|
|
|
} else {
|
|
|
|
return content;
|
|
|
|
}
|
|
|
|
},
|
2018-10-16 10:25:37 +00:00
|
|
|
);
|
|
|
|
|
|
|
|
logger.logDebug('Probing remote daemon for cache images');
|
2018-11-07 18:15:05 +00:00
|
|
|
await assignDockerBuildOpts(docker, buildTasks, opts);
|
2018-10-16 10:25:37 +00:00
|
|
|
|
2019-06-07 14:59:27 +00:00
|
|
|
// If we're passed a build logs object make sure to set it
|
|
|
|
// up properly
|
|
|
|
let logHandlers: ((serviceName: string, line: string) => void) | undefined;
|
2022-12-16 21:17:33 +00:00
|
|
|
|
|
|
|
const lastArrowMessage: Dictionary<string> = {};
|
|
|
|
|
|
|
|
if (imageIds != null) {
|
2019-06-07 14:59:27 +00:00
|
|
|
for (const task of buildTasks) {
|
|
|
|
if (!task.external) {
|
2022-12-16 21:17:33 +00:00
|
|
|
imageIds[task.serviceName] = [];
|
2019-06-07 14:59:27 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
logHandlers = (serviceName: string, line: string) => {
|
2022-12-16 21:17:33 +00:00
|
|
|
// If this was a from line, take the last found
|
|
|
|
// image id and save it
|
|
|
|
if (
|
|
|
|
/step \d+(?:\/\d+)?\s*:\s*FROM/i.test(line) &&
|
|
|
|
lastArrowMessage[serviceName] != null
|
|
|
|
) {
|
|
|
|
imageIds[serviceName].push(lastArrowMessage[serviceName]);
|
|
|
|
} else {
|
|
|
|
const msg = extractDockerArrowMessage(line);
|
|
|
|
if (msg != null) {
|
|
|
|
lastArrowMessage[serviceName] = msg;
|
|
|
|
}
|
|
|
|
}
|
2019-06-07 14:59:27 +00:00
|
|
|
};
|
|
|
|
}
|
|
|
|
|
2018-10-16 10:25:37 +00:00
|
|
|
logger.logDebug('Starting builds...');
|
2021-04-27 13:58:54 +00:00
|
|
|
assignOutputHandlers(buildTasks, logger, logHandlers);
|
2019-07-09 14:43:36 +00:00
|
|
|
const localImages = await multibuild.performBuilds(
|
|
|
|
buildTasks,
|
|
|
|
docker,
|
|
|
|
BALENA_ENGINE_TMP_PATH,
|
|
|
|
);
|
2018-10-16 10:25:37 +00:00
|
|
|
|
|
|
|
// Check for failures
|
|
|
|
await inspectBuildResults(localImages);
|
|
|
|
|
2019-06-20 12:54:43 +00:00
|
|
|
const imagesToRemove: string[] = [];
|
|
|
|
|
2018-10-16 10:25:37 +00:00
|
|
|
// Now tag any external images with the correct name that they should be,
|
2022-06-28 12:22:42 +00:00
|
|
|
// as this won't be done by @balena/compose/multibuild
|
2020-06-30 20:17:24 +00:00
|
|
|
await Promise.all(
|
|
|
|
localImages.map(async (localImage) => {
|
|
|
|
if (localImage.external) {
|
|
|
|
// We can be sure that localImage.name is set here, because of the failure code above
|
|
|
|
const image = docker.getImage(localImage.name!);
|
|
|
|
await image.tag({
|
2021-11-25 17:03:38 +00:00
|
|
|
repo: makeImageName(
|
|
|
|
LOCAL_PROJECT_NAME,
|
|
|
|
localImage.serviceName,
|
|
|
|
'latest',
|
|
|
|
),
|
2020-06-30 20:17:24 +00:00
|
|
|
force: true,
|
|
|
|
});
|
|
|
|
imagesToRemove.push(localImage.name!);
|
|
|
|
}
|
|
|
|
}),
|
|
|
|
);
|
2019-01-14 16:51:57 +00:00
|
|
|
|
2020-06-30 20:17:24 +00:00
|
|
|
await Promise.all(
|
|
|
|
_.uniq(imagesToRemove).map((image) =>
|
|
|
|
docker.getImage(image).remove({ force: true }),
|
|
|
|
),
|
2019-06-20 12:54:43 +00:00
|
|
|
);
|
|
|
|
|
2019-01-14 16:51:57 +00:00
|
|
|
return buildTasks;
|
2018-10-16 10:25:37 +00:00
|
|
|
}
|
|
|
|
|
2019-04-19 15:17:06 +00:00
|
|
|
// Rebuild a single container, execute it on device, and
|
|
|
|
// return the build logs
|
|
|
|
export async function rebuildSingleTask(
|
|
|
|
serviceName: string,
|
|
|
|
docker: Docker,
|
|
|
|
logger: Logger,
|
|
|
|
deviceInfo: DeviceInfo,
|
|
|
|
composition: Composition,
|
|
|
|
source: string,
|
|
|
|
opts: DeviceDeployOptions,
|
2019-06-07 14:59:27 +00:00
|
|
|
// To cancel a running build, you must first find the
|
|
|
|
// container id that it's running in. This is printed in
|
|
|
|
// the logs, so any calller who wants to keep track of
|
|
|
|
// this should provide the following callback
|
|
|
|
containerIdCb?: (id: string) => void,
|
2022-12-16 21:17:33 +00:00
|
|
|
): Promise<string[]> {
|
2022-06-28 12:22:42 +00:00
|
|
|
const multibuild = await import('@balena/compose/dist/multibuild');
|
2019-04-19 15:17:06 +00:00
|
|
|
// First we run the build task, to get the new image id
|
2022-12-16 21:17:33 +00:00
|
|
|
const stageIds = [] as string[];
|
|
|
|
let lastArrowMessage: string | undefined;
|
|
|
|
|
2019-06-07 14:59:27 +00:00
|
|
|
const logHandler = (_s: string, line: string) => {
|
2022-12-16 21:17:33 +00:00
|
|
|
// If this was a FROM line, take the last found
|
|
|
|
// image id and save it as a stage id
|
|
|
|
if (
|
|
|
|
/step \d+(?:\/\d+)?\s*:\s*FROM/i.test(line) &&
|
|
|
|
lastArrowMessage != null
|
|
|
|
) {
|
|
|
|
stageIds.push(lastArrowMessage);
|
|
|
|
} else {
|
|
|
|
const msg = extractDockerArrowMessage(line);
|
|
|
|
if (msg != null) {
|
|
|
|
lastArrowMessage = msg;
|
|
|
|
}
|
|
|
|
}
|
2019-06-07 14:59:27 +00:00
|
|
|
|
|
|
|
if (containerIdCb != null) {
|
|
|
|
const match = line.match(/^\s*--->\s*Running\s*in\s*([a-f0-9]*)\s*$/i);
|
|
|
|
if (match != null) {
|
|
|
|
containerIdCb(match[1]);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
};
|
2019-04-19 15:17:06 +00:00
|
|
|
|
2020-05-01 11:18:11 +00:00
|
|
|
const tarStream = await tarDirectory(source, {
|
2020-06-24 23:01:53 +00:00
|
|
|
composition,
|
2020-05-01 11:18:11 +00:00
|
|
|
convertEol: opts.convertEol,
|
2020-06-24 23:01:53 +00:00
|
|
|
multiDockerignore: opts.multiDockerignore,
|
2020-05-01 11:18:11 +00:00
|
|
|
});
|
2019-04-19 15:17:06 +00:00
|
|
|
|
|
|
|
const task = _.find(
|
2020-02-18 03:21:12 +00:00
|
|
|
await makeBuildTasks(
|
|
|
|
composition,
|
|
|
|
tarStream,
|
|
|
|
deviceInfo,
|
|
|
|
logger,
|
|
|
|
LOCAL_APPNAME,
|
|
|
|
LOCAL_RELEASEHASH,
|
2020-06-15 22:53:07 +00:00
|
|
|
(content) => {
|
2020-05-11 17:35:24 +00:00
|
|
|
if (!opts.nolive) {
|
|
|
|
return LivepushManager.preprocessDockerfile(content);
|
|
|
|
} else {
|
|
|
|
return content;
|
|
|
|
}
|
|
|
|
},
|
2020-02-18 03:21:12 +00:00
|
|
|
),
|
2019-04-19 15:17:06 +00:00
|
|
|
{ serviceName },
|
|
|
|
);
|
|
|
|
|
|
|
|
if (task == null) {
|
2020-12-03 20:50:00 +00:00
|
|
|
throw new ExpectedError(
|
|
|
|
`Could not find build task for service ${serviceName}`,
|
|
|
|
);
|
2019-04-19 15:17:06 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
await assignDockerBuildOpts(docker, [task], opts);
|
2019-06-07 14:59:27 +00:00
|
|
|
await assignOutputHandlers([task], logger, logHandler);
|
2019-04-19 15:17:06 +00:00
|
|
|
|
2019-07-09 14:43:36 +00:00
|
|
|
const [localImage] = await multibuild.performBuilds(
|
|
|
|
[task],
|
|
|
|
docker,
|
|
|
|
BALENA_ENGINE_TMP_PATH,
|
|
|
|
);
|
2019-04-19 15:17:06 +00:00
|
|
|
|
|
|
|
if (!localImage.successful) {
|
|
|
|
throw new LocalPushErrors.BuildError([
|
|
|
|
{
|
|
|
|
error: localImage.error!,
|
|
|
|
serviceName,
|
|
|
|
},
|
|
|
|
]);
|
|
|
|
}
|
|
|
|
|
2022-12-16 21:17:33 +00:00
|
|
|
return stageIds;
|
2019-04-19 15:17:06 +00:00
|
|
|
}
|
|
|
|
|
2019-01-14 16:51:57 +00:00
|
|
|
function assignOutputHandlers(
|
|
|
|
buildTasks: BuildTask[],
|
|
|
|
logger: Logger,
|
2019-06-07 14:59:27 +00:00
|
|
|
logCb?: (serviceName: string, line: string) => void,
|
2019-01-14 16:51:57 +00:00
|
|
|
) {
|
2020-06-15 22:53:07 +00:00
|
|
|
_.each(buildTasks, (task) => {
|
2018-10-16 10:25:37 +00:00
|
|
|
if (task.external) {
|
2020-06-15 22:53:07 +00:00
|
|
|
task.progressHook = (progressObj) => {
|
2018-10-16 10:25:37 +00:00
|
|
|
displayBuildLog(
|
|
|
|
{ serviceName: task.serviceName, message: progressObj.progress },
|
|
|
|
logger,
|
|
|
|
);
|
|
|
|
};
|
|
|
|
} else {
|
2020-06-15 22:53:07 +00:00
|
|
|
task.streamHook = (stream) => {
|
2018-10-16 10:25:37 +00:00
|
|
|
stream.on('data', (buf: Buffer) => {
|
2018-12-13 21:02:27 +00:00
|
|
|
const str = _.trimEnd(buf.toString());
|
2018-10-16 10:25:37 +00:00
|
|
|
if (str !== '') {
|
|
|
|
displayBuildLog(
|
|
|
|
{ serviceName: task.serviceName, message: str },
|
|
|
|
logger,
|
|
|
|
);
|
2019-01-14 16:51:57 +00:00
|
|
|
|
2019-06-07 14:59:27 +00:00
|
|
|
if (logCb) {
|
|
|
|
logCb(task.serviceName, str);
|
2019-01-14 16:51:57 +00:00
|
|
|
}
|
2018-10-16 10:25:37 +00:00
|
|
|
}
|
|
|
|
});
|
|
|
|
};
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
async function getDeviceDockerImages(docker: Docker): Promise<string[]> {
|
2019-10-16 11:45:17 +00:00
|
|
|
const images = await docker.listImages({ all: true });
|
2018-10-16 10:25:37 +00:00
|
|
|
return _.map(images, 'Id');
|
|
|
|
}
|
|
|
|
|
|
|
|
// Mutates buildTasks
|
|
|
|
async function assignDockerBuildOpts(
|
|
|
|
docker: Docker,
|
|
|
|
buildTasks: BuildTask[],
|
2018-11-07 18:15:05 +00:00
|
|
|
opts: DeviceDeployOptions,
|
2018-10-16 10:25:37 +00:00
|
|
|
): Promise<void> {
|
|
|
|
// Get all of the images on the remote docker daemon, so
|
|
|
|
// that we can use all of them for cache
|
|
|
|
const images = await getDeviceDockerImages(docker);
|
|
|
|
|
2019-03-12 22:07:57 +00:00
|
|
|
globalLogger.logDebug(`Using ${images.length} on-device images for cache...`);
|
2018-10-16 10:25:37 +00:00
|
|
|
|
2020-06-30 20:17:24 +00:00
|
|
|
await Promise.all(
|
|
|
|
buildTasks.map(async (task: BuildTask) => {
|
|
|
|
task.dockerOpts = {
|
2022-06-28 12:22:42 +00:00
|
|
|
...(task.dockerOpts || {}),
|
|
|
|
...{
|
|
|
|
cachefrom: images,
|
|
|
|
labels: {
|
|
|
|
'io.resin.local.image': '1',
|
|
|
|
'io.resin.local.service': task.serviceName,
|
|
|
|
},
|
|
|
|
t: getImageNameFromTask(task),
|
|
|
|
nocache: opts.nocache,
|
|
|
|
forcerm: true,
|
|
|
|
pull: opts.pull,
|
2020-06-30 20:17:24 +00:00
|
|
|
},
|
2021-11-25 17:03:38 +00:00
|
|
|
t: getImageNameFromTask(task),
|
2020-06-30 20:17:24 +00:00
|
|
|
nocache: opts.nocache,
|
|
|
|
forcerm: true,
|
2020-09-08 13:55:56 +00:00
|
|
|
pull: opts.pull,
|
2020-06-30 20:17:24 +00:00
|
|
|
};
|
|
|
|
if (task.external) {
|
2023-07-05 19:46:42 +00:00
|
|
|
task.dockerOpts.authconfig = getAuthConfigObj(
|
2020-06-30 20:17:24 +00:00
|
|
|
task.imageName!,
|
|
|
|
opts.registrySecrets,
|
|
|
|
);
|
|
|
|
} else {
|
|
|
|
task.dockerOpts.registryconfig = opts.registrySecrets;
|
|
|
|
}
|
|
|
|
}),
|
|
|
|
);
|
2018-10-16 10:25:37 +00:00
|
|
|
}
|
|
|
|
|
2021-11-25 17:03:38 +00:00
|
|
|
function getImageNameFromTask(task: BuildTask): string {
|
|
|
|
return !task.external && task.tag
|
|
|
|
? task.tag
|
|
|
|
: makeImageName(LOCAL_PROJECT_NAME, task.serviceName, 'latest');
|
2018-10-16 10:25:37 +00:00
|
|
|
}
|
|
|
|
|
2019-04-19 15:17:06 +00:00
|
|
|
export function generateTargetState(
|
2018-10-16 10:25:37 +00:00
|
|
|
currentTargetState: any,
|
|
|
|
composition: Composition,
|
2019-10-14 15:40:46 +00:00
|
|
|
buildTasks: BuildTask[],
|
2019-05-27 10:32:47 +00:00
|
|
|
env: ParsedEnvironment,
|
2018-10-16 10:25:37 +00:00
|
|
|
): any {
|
2019-10-14 15:40:46 +00:00
|
|
|
const keyedBuildTasks = _.keyBy(buildTasks, 'serviceName');
|
|
|
|
|
2018-10-16 10:25:37 +00:00
|
|
|
const services: { [serviceId: string]: any } = {};
|
|
|
|
let idx = 1;
|
|
|
|
_.each(composition.services, (opts, name) => {
|
|
|
|
// Get rid of any build specific stuff
|
|
|
|
opts = _.cloneDeep(opts);
|
|
|
|
delete opts.build;
|
|
|
|
delete opts.image;
|
|
|
|
|
|
|
|
const defaults = {
|
|
|
|
environment: {},
|
|
|
|
labels: {},
|
|
|
|
};
|
|
|
|
|
2019-05-27 10:32:47 +00:00
|
|
|
opts.environment = _.merge(opts.environment, env[name]);
|
2019-10-28 17:50:02 +00:00
|
|
|
// This function can be called with a subset of the
|
|
|
|
// build tasks, when a single dockerfile has changed
|
|
|
|
// when livepushing, so check the build task exists for
|
|
|
|
// this composition entry (everything else in this
|
|
|
|
// function comes from the composition which doesn't
|
|
|
|
// change)
|
2020-03-24 17:52:05 +00:00
|
|
|
let contract;
|
2019-10-28 17:50:02 +00:00
|
|
|
if (name in keyedBuildTasks) {
|
|
|
|
contract = keyedBuildTasks[name].contract;
|
|
|
|
}
|
2019-10-14 15:40:46 +00:00
|
|
|
|
2021-11-25 17:03:38 +00:00
|
|
|
const task = keyedBuildTasks[name];
|
|
|
|
|
2019-10-14 15:40:46 +00:00
|
|
|
services[idx] = {
|
|
|
|
...defaults,
|
|
|
|
...opts,
|
|
|
|
...(contract != null ? { contract } : {}),
|
|
|
|
...{
|
|
|
|
imageId: idx,
|
|
|
|
serviceName: name,
|
|
|
|
serviceId: idx,
|
2021-11-25 17:03:38 +00:00
|
|
|
image: getImageNameFromTask(task),
|
2019-10-14 15:40:46 +00:00
|
|
|
running: true,
|
|
|
|
},
|
|
|
|
};
|
2018-10-16 10:25:37 +00:00
|
|
|
idx += 1;
|
|
|
|
});
|
|
|
|
|
|
|
|
const targetState = _.cloneDeep(currentTargetState);
|
|
|
|
delete targetState.local.apps;
|
|
|
|
|
|
|
|
targetState.local.apps = {
|
|
|
|
1: {
|
2020-02-18 03:21:12 +00:00
|
|
|
name: LOCAL_APPNAME,
|
|
|
|
commit: LOCAL_RELEASEHASH,
|
2018-10-16 10:25:37 +00:00
|
|
|
releaseId: '1',
|
|
|
|
services,
|
|
|
|
volumes: composition.volumes || {},
|
|
|
|
networks: composition.networks || {},
|
|
|
|
},
|
|
|
|
};
|
|
|
|
|
|
|
|
return targetState;
|
|
|
|
}
|
|
|
|
|
|
|
|
async function inspectBuildResults(images: LocalImage[]): Promise<void> {
|
|
|
|
const failures: LocalPushErrors.BuildFailure[] = [];
|
|
|
|
|
2020-06-15 22:53:07 +00:00
|
|
|
_.each(images, (image) => {
|
2018-10-16 10:25:37 +00:00
|
|
|
if (!image.successful) {
|
|
|
|
failures.push({
|
|
|
|
error: image.error!,
|
|
|
|
serviceName: image.serviceName,
|
|
|
|
});
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
if (failures.length > 0) {
|
2020-12-03 20:50:00 +00:00
|
|
|
throw new LocalPushErrors.BuildError(failures).toString();
|
2018-10-16 10:25:37 +00:00
|
|
|
}
|
|
|
|
}
|