2018-11-07 18:15:05 +00:00
|
|
|
/**
|
|
|
|
* @license
|
|
|
|
* Copyright 2018 Balena Ltd.
|
|
|
|
*
|
|
|
|
* 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.
|
|
|
|
*/
|
|
|
|
|
2018-10-16 10:25:37 +00:00
|
|
|
import * as Bluebird from 'bluebird';
|
|
|
|
import * as Docker from 'dockerode';
|
|
|
|
import * as _ from 'lodash';
|
|
|
|
import { Composition } from 'resin-compose-parse';
|
2019-02-07 15:10:16 +00:00
|
|
|
import {
|
|
|
|
BuildTask,
|
|
|
|
getAuthConfigObj,
|
|
|
|
LocalImage,
|
|
|
|
RegistrySecrets,
|
|
|
|
} from 'resin-multibuild';
|
2018-10-16 15:41:38 +00:00
|
|
|
import * as semver from 'resin-semver';
|
2018-10-16 10:25:37 +00:00
|
|
|
import { Readable } from 'stream';
|
|
|
|
|
2019-02-07 15:10:16 +00:00
|
|
|
import { makeBuildTasks } 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';
|
2018-10-16 10:25:37 +00:00
|
|
|
|
|
|
|
// Define the logger here so the debug output
|
|
|
|
// can be used everywhere
|
2019-03-12 22:07:57 +00:00
|
|
|
const globalLogger = new Logger();
|
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;
|
2019-03-28 12:20:08 +00:00
|
|
|
nocache: boolean;
|
2019-01-14 16:51:57 +00:00
|
|
|
live: boolean;
|
2019-04-24 13:31:30 +00:00
|
|
|
detached: boolean;
|
2019-04-24 13:59:07 +00:00
|
|
|
service?: string;
|
2019-04-24 16:30:18 +00:00
|
|
|
system: boolean;
|
2018-10-16 10:25:37 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
async function checkSource(source: string): Promise<boolean> {
|
|
|
|
const { fs } = await import('mz');
|
|
|
|
return (await fs.exists(source)) && (await fs.stat(source)).isDirectory();
|
|
|
|
}
|
|
|
|
|
|
|
|
export async function deployToDevice(opts: DeviceDeployOptions): Promise<void> {
|
|
|
|
const { loadProject, tarDirectory } = await import('../compose');
|
|
|
|
const { exitWithExpectedError } = await import('../patterns');
|
|
|
|
|
|
|
|
const { displayDeviceLogs } = await import('./logs');
|
|
|
|
|
|
|
|
if (!(await checkSource(opts.source))) {
|
|
|
|
exitWithExpectedError(`Could not access source directory: ${opts.source}`);
|
|
|
|
}
|
|
|
|
|
2019-03-12 22:07:57 +00:00
|
|
|
const api = new DeviceAPI(globalLogger, opts.deviceHost);
|
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) {
|
|
|
|
exitWithExpectedError(
|
|
|
|
`Could not communicate with local mode device at address ${
|
|
|
|
opts.deviceHost
|
|
|
|
}`,
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
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();
|
2019-01-14 16:51:57 +00:00
|
|
|
globalLogger.logDebug(`Checking device version: ${version}`);
|
2018-10-16 15:41:38 +00:00
|
|
|
if (!semver.satisfies(version, '>=7.21.4')) {
|
|
|
|
exitWithExpectedError(versionError);
|
|
|
|
}
|
2019-04-23 10:38:13 +00:00
|
|
|
if (opts.live && !semver.satisfies(version, '>=9.7.0')) {
|
2019-01-14 16:51:57 +00:00
|
|
|
exitWithExpectedError(
|
2019-04-23 10:38:13 +00:00
|
|
|
new Error('Using livepush requires a supervisor >= v9.7.0'),
|
2019-01-14 16:51:57 +00:00
|
|
|
);
|
|
|
|
}
|
2018-10-16 15:41:38 +00:00
|
|
|
} catch {
|
|
|
|
exitWithExpectedError(versionError);
|
|
|
|
}
|
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
|
|
|
|
2019-04-11 11:49:19 +00:00
|
|
|
const project = await loadProject(
|
|
|
|
globalLogger,
|
|
|
|
opts.source, // project path
|
|
|
|
'local', // project name
|
|
|
|
undefined, // name of a pre-built image
|
|
|
|
opts.dockerfilePath, // alternative Dockerfile; OK to be undefined
|
|
|
|
);
|
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,
|
|
|
|
);
|
|
|
|
|
|
|
|
const tarStream = await tarDirectory(opts.source);
|
|
|
|
|
|
|
|
// Try to detect the device information
|
|
|
|
const deviceInfo = await api.getDeviceInformation();
|
|
|
|
|
2019-01-14 16:51:57 +00:00
|
|
|
let buildLogs: Dictionary<string> | undefined;
|
|
|
|
if (opts.live) {
|
|
|
|
buildLogs = {};
|
|
|
|
}
|
|
|
|
const buildTasks = await 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,
|
2019-01-14 16:51:57 +00:00
|
|
|
buildLogs,
|
2018-10-16 10:25:37 +00:00
|
|
|
);
|
|
|
|
|
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-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)
|
|
|
|
if (opts.live) {
|
|
|
|
const livepush = new LivepushManager({
|
|
|
|
api,
|
|
|
|
buildContext: opts.source,
|
|
|
|
buildTasks,
|
|
|
|
docker,
|
|
|
|
logger: globalLogger,
|
|
|
|
composition: project.composition,
|
|
|
|
buildLogs: buildLogs!,
|
2019-04-19 15:17:06 +00:00
|
|
|
deployOpts: opts,
|
2019-01-14 16:51:57 +00:00
|
|
|
});
|
|
|
|
|
2019-04-26 14:13:41 +00:00
|
|
|
const promises = [livepush.init()];
|
|
|
|
// Only show logs if we're not detaching
|
|
|
|
if (!opts.detached) {
|
|
|
|
console.log();
|
|
|
|
const logStream = await api.getLogStream();
|
|
|
|
globalLogger.logInfo('Streaming device logs...');
|
|
|
|
promises.push(
|
|
|
|
displayDeviceLogs(logStream, globalLogger, opts.system, opts.service),
|
|
|
|
);
|
2019-04-30 12:00:52 +00:00
|
|
|
} else {
|
|
|
|
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...');
|
2019-04-26 14:13:41 +00:00
|
|
|
await Promise.all(promises);
|
2019-04-19 15:17:06 +00:00
|
|
|
} else {
|
2019-04-26 14:13:41 +00:00
|
|
|
if (opts.detached) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
// Print an empty newline to separate the build output
|
|
|
|
// from the device output
|
|
|
|
console.log();
|
|
|
|
// Now all we need to do is stream back the logs
|
|
|
|
const logStream = await api.getLogStream();
|
|
|
|
globalLogger.logInfo('Streaming device logs...');
|
2019-04-24 16:30:18 +00:00
|
|
|
await displayDeviceLogs(logStream, globalLogger, opts.system, opts.service);
|
2019-01-14 16:51:57 +00:00
|
|
|
}
|
2018-10-16 10:25:37 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
function connectToDocker(host: string, port: number): Docker {
|
|
|
|
return new Docker({
|
|
|
|
host,
|
|
|
|
port,
|
|
|
|
Promise: Bluebird as any,
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
export async function performBuilds(
|
|
|
|
composition: Composition,
|
|
|
|
tarStream: Readable,
|
|
|
|
docker: Docker,
|
|
|
|
deviceInfo: DeviceInfo,
|
|
|
|
logger: Logger,
|
2018-11-07 18:15:05 +00:00
|
|
|
opts: DeviceDeployOptions,
|
2019-01-14 16:51:57 +00:00
|
|
|
buildLogs?: Dictionary<string>,
|
|
|
|
): Promise<BuildTask[]> {
|
2018-10-16 10:25:37 +00:00
|
|
|
const multibuild = await import('resin-multibuild');
|
|
|
|
|
2019-02-07 15:10:16 +00:00
|
|
|
const buildTasks = await makeBuildTasks(
|
|
|
|
composition,
|
|
|
|
tarStream,
|
|
|
|
deviceInfo,
|
|
|
|
logger,
|
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
|
|
|
|
|
|
|
logger.logDebug('Starting builds...');
|
2019-01-14 16:51:57 +00:00
|
|
|
await assignOutputHandlers(buildTasks, logger, buildLogs);
|
2018-10-16 10:25:37 +00:00
|
|
|
const localImages = await multibuild.performBuilds(buildTasks, docker);
|
|
|
|
|
|
|
|
// Check for failures
|
|
|
|
await inspectBuildResults(localImages);
|
|
|
|
|
|
|
|
// Now tag any external images with the correct name that they should be,
|
|
|
|
// as this won't be done by resin-multibuild
|
|
|
|
await Bluebird.map(localImages, 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({
|
|
|
|
repo: generateImageName(localImage.serviceName),
|
|
|
|
force: true,
|
|
|
|
});
|
|
|
|
await image.remove({ force: true });
|
|
|
|
}
|
|
|
|
});
|
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,
|
|
|
|
): Promise<string> {
|
|
|
|
const { tarDirectory } = await import('../compose');
|
|
|
|
const multibuild = await import('resin-multibuild');
|
|
|
|
// First we run the build task, to get the new image id
|
|
|
|
const buildLogs: Dictionary<string> = {};
|
|
|
|
|
|
|
|
const tarStream = await tarDirectory(source);
|
|
|
|
|
|
|
|
const task = _.find(
|
|
|
|
await makeBuildTasks(composition, tarStream, deviceInfo, logger),
|
|
|
|
{ serviceName },
|
|
|
|
);
|
|
|
|
|
|
|
|
if (task == null) {
|
|
|
|
throw new Error(`Could not find build task for service ${serviceName}`);
|
|
|
|
}
|
|
|
|
|
|
|
|
await assignDockerBuildOpts(docker, [task], opts);
|
|
|
|
await assignOutputHandlers([task], logger, buildLogs);
|
|
|
|
|
|
|
|
const [localImage] = await multibuild.performBuilds([task], docker);
|
|
|
|
|
|
|
|
if (!localImage.successful) {
|
|
|
|
throw new LocalPushErrors.BuildError([
|
|
|
|
{
|
|
|
|
error: localImage.error!,
|
|
|
|
serviceName,
|
|
|
|
},
|
|
|
|
]);
|
|
|
|
}
|
|
|
|
|
|
|
|
return buildLogs[task.serviceName];
|
|
|
|
}
|
|
|
|
|
2019-01-14 16:51:57 +00:00
|
|
|
function assignOutputHandlers(
|
|
|
|
buildTasks: BuildTask[],
|
|
|
|
logger: Logger,
|
|
|
|
buildLogs?: Dictionary<string>,
|
|
|
|
) {
|
2018-10-16 10:25:37 +00:00
|
|
|
_.each(buildTasks, task => {
|
|
|
|
if (task.external) {
|
|
|
|
task.progressHook = progressObj => {
|
|
|
|
displayBuildLog(
|
|
|
|
{ serviceName: task.serviceName, message: progressObj.progress },
|
|
|
|
logger,
|
|
|
|
);
|
|
|
|
};
|
|
|
|
} else {
|
2019-01-14 16:51:57 +00:00
|
|
|
if (buildLogs) {
|
|
|
|
buildLogs[task.serviceName] = '';
|
|
|
|
}
|
2018-10-16 10:25:37 +00:00
|
|
|
task.streamHook = stream => {
|
|
|
|
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
|
|
|
|
|
|
|
if (buildLogs) {
|
|
|
|
buildLogs[task.serviceName] = `${
|
|
|
|
buildLogs[task.serviceName]
|
|
|
|
}\n${str}`;
|
|
|
|
}
|
2018-10-16 10:25:37 +00:00
|
|
|
}
|
|
|
|
});
|
|
|
|
};
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
async function getDeviceDockerImages(docker: Docker): Promise<string[]> {
|
|
|
|
const images = await docker.listImages();
|
|
|
|
|
|
|
|
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
|
|
|
|
2019-02-07 15:10:16 +00:00
|
|
|
await Bluebird.map(buildTasks, async (task: BuildTask) => {
|
2018-10-16 10:25:37 +00:00
|
|
|
task.dockerOpts = {
|
|
|
|
cachefrom: images,
|
|
|
|
labels: {
|
|
|
|
'io.resin.local.image': '1',
|
|
|
|
'io.resin.local.service': task.serviceName,
|
|
|
|
},
|
|
|
|
t: generateImageName(task.serviceName),
|
2019-03-28 12:20:08 +00:00
|
|
|
nocache: opts.nocache,
|
2018-10-16 10:25:37 +00:00
|
|
|
};
|
2019-02-07 15:10:16 +00:00
|
|
|
if (task.external) {
|
|
|
|
task.dockerOpts.authconfig = await getAuthConfigObj(
|
|
|
|
task.imageName!,
|
|
|
|
opts.registrySecrets,
|
|
|
|
);
|
|
|
|
} else {
|
|
|
|
task.dockerOpts.registryconfig = opts.registrySecrets;
|
|
|
|
}
|
2018-10-16 10:25:37 +00:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
function generateImageName(serviceName: string): string {
|
|
|
|
return `local_image_${serviceName}:latest`;
|
|
|
|
}
|
|
|
|
|
2019-04-19 15:17:06 +00:00
|
|
|
export function generateTargetState(
|
2018-10-16 10:25:37 +00:00
|
|
|
currentTargetState: any,
|
|
|
|
composition: Composition,
|
|
|
|
): any {
|
|
|
|
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: {},
|
|
|
|
};
|
|
|
|
|
|
|
|
services[idx] = _.merge(defaults, opts, {
|
|
|
|
imageId: idx,
|
|
|
|
serviceName: name,
|
|
|
|
serviceId: idx,
|
|
|
|
image: generateImageName(name),
|
|
|
|
running: true,
|
|
|
|
});
|
|
|
|
idx += 1;
|
|
|
|
});
|
|
|
|
|
|
|
|
const targetState = _.cloneDeep(currentTargetState);
|
|
|
|
delete targetState.local.apps;
|
|
|
|
|
|
|
|
targetState.local.apps = {
|
|
|
|
1: {
|
|
|
|
name: 'localapp',
|
2019-02-05 16:55:49 +00:00
|
|
|
commit: 'localrelease',
|
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 { exitWithExpectedError } = await import('../patterns');
|
|
|
|
|
|
|
|
const failures: LocalPushErrors.BuildFailure[] = [];
|
|
|
|
|
|
|
|
_.each(images, image => {
|
|
|
|
if (!image.successful) {
|
|
|
|
failures.push({
|
|
|
|
error: image.error!,
|
|
|
|
serviceName: image.serviceName,
|
|
|
|
});
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
if (failures.length > 0) {
|
2018-11-07 18:15:05 +00:00
|
|
|
exitWithExpectedError(new LocalPushErrors.BuildError(failures).toString());
|
2018-10-16 10:25:37 +00:00
|
|
|
}
|
|
|
|
}
|