2020-11-11 17:05:10 +00:00
|
|
|
/**
|
|
|
|
* @license
|
|
|
|
* Copyright 2019-2020 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.
|
|
|
|
*/
|
|
|
|
|
2019-01-14 16:51:57 +00:00
|
|
|
import * as chokidar from 'chokidar';
|
2020-02-27 12:38:50 +00:00
|
|
|
import type * as Dockerode from 'dockerode';
|
2020-11-11 17:05:10 +00:00
|
|
|
import * as fs from 'fs';
|
2019-06-07 14:59:27 +00:00
|
|
|
import Livepush, { ContainerNotRunningError } from 'livepush';
|
2019-01-14 16:51:57 +00:00
|
|
|
import * as _ from 'lodash';
|
|
|
|
import * as path from 'path';
|
2020-02-27 12:38:50 +00:00
|
|
|
import type { Composition } from 'resin-compose-parse';
|
|
|
|
import type { BuildTask } from 'resin-multibuild';
|
2019-01-14 16:51:57 +00:00
|
|
|
|
2020-04-18 01:31:13 +00:00
|
|
|
import { instanceOf } from '../../errors';
|
2019-01-14 16:51:57 +00:00
|
|
|
import Logger = require('../logger');
|
|
|
|
|
2020-04-29 16:54:41 +00:00
|
|
|
import { Dockerfile } from 'livepush';
|
2020-02-27 12:38:50 +00:00
|
|
|
import type DeviceAPI from './api';
|
|
|
|
import type { DeviceInfo, Status } from './api';
|
2019-04-19 15:17:06 +00:00
|
|
|
import {
|
|
|
|
DeviceDeployOptions,
|
|
|
|
generateTargetState,
|
|
|
|
rebuildSingleTask,
|
|
|
|
} from './deploy';
|
|
|
|
import { BuildError } from './errors';
|
2019-04-30 14:55:58 +00:00
|
|
|
import { getServiceColourFn } from './logs';
|
2020-07-01 14:26:40 +00:00
|
|
|
import { delay } from '../helpers';
|
2019-01-14 16:51:57 +00:00
|
|
|
|
|
|
|
// How often do we want to check the device state
|
|
|
|
// engine has settled (delay in ms)
|
2019-04-19 15:17:06 +00:00
|
|
|
const DEVICE_STATUS_SETTLE_CHECK_INTERVAL = 1000;
|
2019-01-14 16:51:57 +00:00
|
|
|
|
2019-05-13 16:06:57 +00:00
|
|
|
const LIVEPUSH_DEBOUNCE_TIMEOUT = 2000;
|
|
|
|
|
2019-01-14 16:51:57 +00:00
|
|
|
interface MonitoredContainer {
|
|
|
|
context: string;
|
|
|
|
livepush: Livepush;
|
|
|
|
monitor: chokidar.FSWatcher;
|
2019-04-19 15:17:06 +00:00
|
|
|
containerId: string;
|
2019-01-14 16:51:57 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
type BuildLogs = Dictionary<string>;
|
|
|
|
type StageImageIDs = Dictionary<string[]>;
|
|
|
|
|
|
|
|
export interface LivepushOpts {
|
|
|
|
buildContext: string;
|
|
|
|
composition: Composition;
|
|
|
|
buildTasks: BuildTask[];
|
|
|
|
docker: Dockerode;
|
|
|
|
api: DeviceAPI;
|
|
|
|
logger: Logger;
|
|
|
|
buildLogs: BuildLogs;
|
2019-04-19 15:17:06 +00:00
|
|
|
deployOpts: DeviceDeployOptions;
|
2019-01-14 16:51:57 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
export class LivepushManager {
|
|
|
|
private lastDeviceStatus: Status | null = null;
|
|
|
|
private containers: Dictionary<MonitoredContainer> = {};
|
2019-04-19 15:17:06 +00:00
|
|
|
private dockerfilePaths: Dictionary<string[]> = {};
|
|
|
|
private deviceInfo: DeviceInfo;
|
|
|
|
private deployOpts: DeviceDeployOptions;
|
2019-01-14 16:51:57 +00:00
|
|
|
|
|
|
|
private buildContext: string;
|
|
|
|
private composition: Composition;
|
|
|
|
private buildTasks: BuildTask[];
|
|
|
|
private docker: Dockerode;
|
|
|
|
private api: DeviceAPI;
|
|
|
|
private logger: Logger;
|
|
|
|
private imageIds: StageImageIDs;
|
|
|
|
|
2019-05-13 16:06:57 +00:00
|
|
|
// A map of service names to events waiting
|
|
|
|
private updateEventsWaiting: Dictionary<string[]> = {};
|
|
|
|
private deleteEventsWaiting: Dictionary<string[]> = {};
|
|
|
|
|
2019-06-07 14:59:27 +00:00
|
|
|
private rebuildsRunning: Dictionary<boolean> = {};
|
|
|
|
private rebuildRunningIds: Dictionary<string> = {};
|
|
|
|
private rebuildsCancelled: Dictionary<boolean> = {};
|
|
|
|
|
2019-01-14 16:51:57 +00:00
|
|
|
public constructor(opts: LivepushOpts) {
|
|
|
|
this.buildContext = opts.buildContext;
|
|
|
|
this.composition = opts.composition;
|
|
|
|
this.buildTasks = opts.buildTasks;
|
|
|
|
this.docker = opts.docker;
|
|
|
|
this.api = opts.api;
|
|
|
|
this.logger = opts.logger;
|
2019-04-19 15:17:06 +00:00
|
|
|
this.deployOpts = opts.deployOpts;
|
2019-01-14 16:51:57 +00:00
|
|
|
this.imageIds = LivepushManager.getMultistageImageIDs(opts.buildLogs);
|
|
|
|
}
|
|
|
|
|
|
|
|
public async init(): Promise<void> {
|
2019-04-19 15:17:06 +00:00
|
|
|
this.deviceInfo = await this.api.getDeviceInformation();
|
2019-01-14 16:51:57 +00:00
|
|
|
this.logger.logLivepush('Waiting for device state to settle...');
|
|
|
|
// The first thing we need to do is let the state 'settle',
|
|
|
|
// so that all of the containers are running and ready to
|
|
|
|
// be livepush'd into
|
|
|
|
await this.awaitDeviceStateSettle();
|
2019-04-30 12:00:52 +00:00
|
|
|
// Split the composition into a load of differents paths
|
|
|
|
// which we can
|
|
|
|
this.logger.logLivepush('Device state settled');
|
2019-01-14 16:51:57 +00:00
|
|
|
|
2020-11-11 17:05:10 +00:00
|
|
|
// Prepare dockerignore data for file watcher
|
|
|
|
const { getDockerignoreByService } = await import('../ignore');
|
|
|
|
const { getServiceDirsFromComposition } = await import('../compose_ts');
|
|
|
|
const rootContext = path.resolve(this.buildContext);
|
|
|
|
const serviceDirsByService = await getServiceDirsFromComposition(
|
|
|
|
this.deployOpts.source,
|
|
|
|
this.composition,
|
|
|
|
);
|
|
|
|
const dockerignoreByService = await getDockerignoreByService(
|
|
|
|
this.deployOpts.source,
|
|
|
|
this.deployOpts.multiDockerignore,
|
|
|
|
serviceDirsByService,
|
|
|
|
);
|
|
|
|
|
|
|
|
// create livepush instances for each service
|
2019-01-14 16:51:57 +00:00
|
|
|
for (const serviceName of _.keys(this.composition.services)) {
|
|
|
|
const service = this.composition.services[serviceName];
|
|
|
|
const buildTask = _.find(this.buildTasks, { serviceName });
|
|
|
|
|
|
|
|
if (buildTask == null) {
|
|
|
|
throw new Error(
|
|
|
|
`Could not find a build task for service: ${serviceName}`,
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
// We only care about builds
|
|
|
|
if (service.build != null) {
|
2020-04-29 16:54:41 +00:00
|
|
|
if (buildTask.dockerfile == null) {
|
2019-01-14 16:51:57 +00:00
|
|
|
throw new Error(
|
|
|
|
`Could not detect dockerfile for service: ${serviceName}`,
|
|
|
|
);
|
|
|
|
}
|
2020-04-29 16:54:41 +00:00
|
|
|
const dockerfile = new Dockerfile(buildTask.dockerfile);
|
2019-01-14 16:51:57 +00:00
|
|
|
|
2019-04-19 15:17:06 +00:00
|
|
|
if (buildTask.dockerfilePath == null) {
|
|
|
|
// this is a bit of a hack as resin-bundle-resolve
|
|
|
|
// does not always export the dockerfilePath, this
|
|
|
|
// only happens when the dockerfile path is
|
|
|
|
// specified differently - this should be patched
|
|
|
|
// in resin-bundle-resolve
|
|
|
|
this.dockerfilePaths[
|
|
|
|
buildTask.serviceName
|
|
|
|
] = this.getDockerfilePathFromTask(buildTask);
|
|
|
|
} else {
|
|
|
|
this.dockerfilePaths[buildTask.serviceName] = [
|
|
|
|
buildTask.dockerfilePath,
|
|
|
|
];
|
|
|
|
}
|
|
|
|
|
2019-01-14 16:51:57 +00:00
|
|
|
// Find the containerId from the device state
|
|
|
|
const container = _.find(this.lastDeviceStatus!.containers, {
|
|
|
|
serviceName,
|
|
|
|
});
|
|
|
|
if (container == null) {
|
2019-11-05 14:43:34 +00:00
|
|
|
return;
|
2019-01-14 16:51:57 +00:00
|
|
|
}
|
|
|
|
|
2020-11-11 17:05:10 +00:00
|
|
|
// path.resolve() converts to an absolute path, removes trailing slashes,
|
|
|
|
// and also converts forward slashes to backslashes on Windows.
|
|
|
|
const context = path.resolve(rootContext, service.build.context);
|
|
|
|
|
2020-04-29 16:54:41 +00:00
|
|
|
const livepush = await Livepush.init({
|
2019-01-14 16:51:57 +00:00
|
|
|
dockerfile,
|
|
|
|
context,
|
2020-04-29 16:54:41 +00:00
|
|
|
containerId: container.containerId,
|
|
|
|
stageImages: this.imageIds[serviceName],
|
|
|
|
docker: this.docker,
|
|
|
|
});
|
2019-10-22 12:24:00 +00:00
|
|
|
const buildVars = buildTask.buildMetadata.getBuildVarsForService(
|
|
|
|
buildTask.serviceName,
|
|
|
|
);
|
|
|
|
if (!_.isEmpty(buildVars)) {
|
|
|
|
livepush.setBuildArgs(buildVars);
|
|
|
|
}
|
2019-01-14 16:51:57 +00:00
|
|
|
|
2019-06-07 14:59:27 +00:00
|
|
|
this.assignLivepushOutputHandlers(serviceName, livepush);
|
2019-01-14 16:51:57 +00:00
|
|
|
|
2019-05-13 16:06:57 +00:00
|
|
|
this.updateEventsWaiting[serviceName] = [];
|
|
|
|
this.deleteEventsWaiting[serviceName] = [];
|
2020-11-11 17:05:10 +00:00
|
|
|
const addEvent = ($serviceName: string, changedPath: string) => {
|
2019-05-13 16:06:57 +00:00
|
|
|
this.logger.logDebug(
|
2020-11-11 17:05:10 +00:00
|
|
|
`Got an add filesystem event for service: ${$serviceName}. File: ${changedPath}`,
|
2019-05-13 16:06:57 +00:00
|
|
|
);
|
2020-11-11 17:05:10 +00:00
|
|
|
const eventQueue = this.updateEventsWaiting[$serviceName];
|
2019-05-13 16:06:57 +00:00
|
|
|
eventQueue.push(changedPath);
|
2020-11-11 17:05:10 +00:00
|
|
|
this.getDebouncedEventHandler($serviceName)();
|
2019-05-13 16:06:57 +00:00
|
|
|
};
|
2020-11-10 01:08:22 +00:00
|
|
|
|
2020-11-11 17:05:10 +00:00
|
|
|
const monitor = this.setupFilesystemWatcher(
|
|
|
|
serviceName,
|
|
|
|
rootContext,
|
|
|
|
context,
|
|
|
|
addEvent,
|
|
|
|
dockerignoreByService,
|
|
|
|
this.deployOpts.multiDockerignore,
|
2019-01-14 16:51:57 +00:00
|
|
|
);
|
2019-05-13 16:06:57 +00:00
|
|
|
|
2019-01-14 16:51:57 +00:00
|
|
|
this.containers[serviceName] = {
|
|
|
|
livepush,
|
|
|
|
context,
|
|
|
|
monitor,
|
2019-04-19 15:17:06 +00:00
|
|
|
containerId: container.containerId,
|
2019-01-14 16:51:57 +00:00
|
|
|
};
|
2019-06-07 14:59:27 +00:00
|
|
|
|
|
|
|
this.rebuildsRunning[serviceName] = false;
|
|
|
|
this.rebuildsCancelled[serviceName] = false;
|
2019-01-14 16:51:57 +00:00
|
|
|
}
|
|
|
|
}
|
2019-04-23 10:24:14 +00:00
|
|
|
|
|
|
|
// Setup cleanup handlers for the device
|
2020-11-07 23:45:03 +00:00
|
|
|
process.once('SIGINT', async () => {
|
2019-04-23 10:24:14 +00:00
|
|
|
this.logger.logLivepush('Cleaning up device...');
|
|
|
|
await Promise.all(
|
2020-06-15 22:53:07 +00:00
|
|
|
_.map(this.containers, (container) => {
|
2019-04-23 10:24:14 +00:00
|
|
|
container.livepush.cleanupIntermediateContainers();
|
|
|
|
}),
|
|
|
|
);
|
2020-11-07 23:45:03 +00:00
|
|
|
this.logger.logDebug('Cleaning up done.');
|
2019-04-23 10:24:14 +00:00
|
|
|
});
|
2019-01-14 16:51:57 +00:00
|
|
|
}
|
|
|
|
|
2020-11-11 17:05:10 +00:00
|
|
|
protected setupFilesystemWatcher(
|
|
|
|
serviceName: string,
|
|
|
|
rootContext: string,
|
|
|
|
serviceContext: string,
|
|
|
|
changedPathHandler: (serviceName: string, changedPath: string) => void,
|
|
|
|
dockerignoreByService: {
|
|
|
|
[serviceName: string]: import('@balena/dockerignore').Ignore;
|
|
|
|
},
|
|
|
|
multiDockerignore: boolean,
|
|
|
|
): chokidar.FSWatcher {
|
|
|
|
const contextForDockerignore = multiDockerignore
|
|
|
|
? serviceContext
|
|
|
|
: rootContext;
|
|
|
|
const dockerignore = dockerignoreByService[serviceName];
|
|
|
|
// TODO: Memoize this for services that share a context
|
|
|
|
const monitor = chokidar.watch('.', {
|
|
|
|
cwd: serviceContext,
|
|
|
|
followSymlinks: true,
|
|
|
|
ignoreInitial: true,
|
|
|
|
ignored: (filePath: string, stats: fs.Stats | undefined) => {
|
|
|
|
if (!stats) {
|
|
|
|
try {
|
|
|
|
// sync because chokidar defines a sync interface
|
|
|
|
stats = fs.lstatSync(filePath);
|
|
|
|
} catch (err) {
|
|
|
|
// OK: the file may have been deleted. See also:
|
|
|
|
// https://github.com/paulmillr/chokidar/blob/3.4.3/lib/fsevents-handler.js#L326-L328
|
|
|
|
// https://github.com/paulmillr/chokidar/blob/3.4.3/lib/nodefs-handler.js#L364
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if (stats && !stats.isFile() && !stats.isSymbolicLink()) {
|
|
|
|
// never ignore directories for compatibility with
|
|
|
|
// dockerignore exclusion patterns
|
|
|
|
return !stats.isDirectory();
|
|
|
|
}
|
|
|
|
const relPath = path.relative(contextForDockerignore, filePath);
|
|
|
|
return dockerignore.ignores(relPath);
|
|
|
|
},
|
|
|
|
});
|
|
|
|
monitor.on('add', (changedPath: string) =>
|
|
|
|
changedPathHandler(serviceName, changedPath),
|
|
|
|
);
|
|
|
|
monitor.on('change', (changedPath: string) =>
|
|
|
|
changedPathHandler(serviceName, changedPath),
|
|
|
|
);
|
|
|
|
monitor.on('unlink', (changedPath: string) =>
|
|
|
|
changedPathHandler(serviceName, changedPath),
|
|
|
|
);
|
|
|
|
return monitor;
|
|
|
|
}
|
|
|
|
|
2020-11-07 22:28:14 +00:00
|
|
|
/** Stop the filesystem watcher, allowing the Node process to exit gracefully */
|
2020-11-07 23:42:48 +00:00
|
|
|
public close() {
|
|
|
|
for (const container of Object.values(this.containers)) {
|
|
|
|
container.monitor.close().catch((err) => {
|
|
|
|
if (process.env.DEBUG) {
|
|
|
|
this.logger.logDebug(`chokidar.close() ${err.message}`);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-05-11 17:35:24 +00:00
|
|
|
public static preprocessDockerfile(content: string): string {
|
|
|
|
return new Dockerfile(content).generateLiveDockerfile();
|
|
|
|
}
|
|
|
|
|
2019-01-14 16:51:57 +00:00
|
|
|
private static getMultistageImageIDs(buildLogs: BuildLogs): StageImageIDs {
|
|
|
|
const stageIds: StageImageIDs = {};
|
|
|
|
_.each(buildLogs, (log, serviceName) => {
|
|
|
|
stageIds[serviceName] = [];
|
|
|
|
|
|
|
|
const lines = log.split(/\r?\n/);
|
|
|
|
let lastArrowMessage: string | undefined;
|
|
|
|
for (const line of lines) {
|
|
|
|
// 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 != null
|
|
|
|
) {
|
|
|
|
stageIds[serviceName].push(lastArrowMessage);
|
|
|
|
} else {
|
|
|
|
const msg = LivepushManager.extractDockerArrowMessage(line);
|
|
|
|
if (msg != null) {
|
|
|
|
lastArrowMessage = msg;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
return stageIds;
|
|
|
|
}
|
|
|
|
|
|
|
|
private async awaitDeviceStateSettle(): Promise<void> {
|
2019-07-17 19:12:51 +00:00
|
|
|
// Cache the state to avoid unnecessary calls
|
2019-01-14 16:51:57 +00:00
|
|
|
this.lastDeviceStatus = await this.api.getStatus();
|
|
|
|
|
|
|
|
if (this.lastDeviceStatus.appState === 'applied') {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
this.logger.logDebug(
|
|
|
|
`Device state not settled, retrying in ${DEVICE_STATUS_SETTLE_CHECK_INTERVAL}ms`,
|
|
|
|
);
|
2020-07-01 14:26:40 +00:00
|
|
|
await delay(DEVICE_STATUS_SETTLE_CHECK_INTERVAL);
|
2019-01-14 16:51:57 +00:00
|
|
|
await this.awaitDeviceStateSettle();
|
|
|
|
}
|
|
|
|
|
2019-05-13 16:06:57 +00:00
|
|
|
private async handleFSEvents(serviceName: string): Promise<void> {
|
|
|
|
const updated = this.updateEventsWaiting[serviceName];
|
|
|
|
const deleted = this.deleteEventsWaiting[serviceName];
|
|
|
|
this.updateEventsWaiting[serviceName] = [];
|
|
|
|
this.deleteEventsWaiting[serviceName] = [];
|
2019-01-14 16:51:57 +00:00
|
|
|
|
2019-04-19 15:17:06 +00:00
|
|
|
// First we detect if the file changed is the Dockerfile
|
|
|
|
// used to build the service
|
|
|
|
if (
|
2020-06-15 22:53:07 +00:00
|
|
|
_.some(this.dockerfilePaths[serviceName], (name) =>
|
|
|
|
_.some(updated, (changed) => name === changed),
|
2019-04-19 15:17:06 +00:00
|
|
|
)
|
|
|
|
) {
|
|
|
|
this.logger.logLivepush(
|
2019-05-13 16:06:57 +00:00
|
|
|
`Detected Dockerfile change, performing full rebuild of service ${serviceName}`,
|
2019-04-19 15:17:06 +00:00
|
|
|
);
|
2019-05-13 16:06:57 +00:00
|
|
|
await this.handleServiceRebuild(serviceName);
|
2019-04-19 15:17:06 +00:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2019-01-14 16:51:57 +00:00
|
|
|
// Work out if we need to perform any changes on this container
|
2019-05-13 16:06:57 +00:00
|
|
|
const livepush = this.containers[serviceName].livepush;
|
2019-01-14 16:51:57 +00:00
|
|
|
|
2020-03-06 15:17:02 +00:00
|
|
|
if (!livepush.livepushNeeded(updated, deleted)) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2019-01-14 16:51:57 +00:00
|
|
|
this.logger.logLivepush(
|
2019-05-13 16:06:57 +00:00
|
|
|
`Detected changes for container ${serviceName}, updating...`,
|
2019-01-14 16:51:57 +00:00
|
|
|
);
|
2019-04-30 14:55:58 +00:00
|
|
|
|
|
|
|
try {
|
2019-05-13 16:06:57 +00:00
|
|
|
await livepush.performLivepush(updated, deleted);
|
2019-04-30 14:55:58 +00:00
|
|
|
} catch (e) {
|
|
|
|
this.logger.logError(
|
|
|
|
`An error occured whilst trying to perform a livepush: `,
|
|
|
|
);
|
2020-04-18 01:31:13 +00:00
|
|
|
if (instanceOf(e, ContainerNotRunningError)) {
|
2019-05-13 16:06:57 +00:00
|
|
|
this.logger.logError(' Livepush container not running');
|
|
|
|
} else {
|
|
|
|
this.logger.logError(` ${e.message}`);
|
|
|
|
}
|
2019-04-30 14:55:58 +00:00
|
|
|
this.logger.logDebug(e.stack);
|
|
|
|
}
|
2019-01-14 16:51:57 +00:00
|
|
|
}
|
|
|
|
|
2019-04-19 15:17:06 +00:00
|
|
|
private async handleServiceRebuild(serviceName: string): Promise<void> {
|
2019-06-07 14:59:27 +00:00
|
|
|
if (this.rebuildsRunning[serviceName]) {
|
|
|
|
this.logger.logLivepush(
|
|
|
|
`Cancelling ongoing rebuild for service ${serviceName}`,
|
|
|
|
);
|
|
|
|
await this.cancelRebuild(serviceName);
|
|
|
|
while (this.rebuildsCancelled[serviceName]) {
|
2020-07-01 14:26:40 +00:00
|
|
|
await delay(1000);
|
2019-06-07 14:59:27 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
this.rebuildsRunning[serviceName] = true;
|
2019-04-19 15:17:06 +00:00
|
|
|
try {
|
|
|
|
const buildTask = _.find(this.buildTasks, { serviceName });
|
|
|
|
if (buildTask == null) {
|
|
|
|
throw new Error(
|
|
|
|
`Could not find a build task for service ${serviceName}`,
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
let buildLog: string;
|
|
|
|
try {
|
|
|
|
buildLog = await rebuildSingleTask(
|
|
|
|
serviceName,
|
|
|
|
this.docker,
|
|
|
|
this.logger,
|
|
|
|
this.deviceInfo,
|
|
|
|
this.composition,
|
|
|
|
this.buildContext,
|
|
|
|
this.deployOpts,
|
2020-06-15 22:53:07 +00:00
|
|
|
(id) => {
|
2019-06-07 14:59:27 +00:00
|
|
|
this.rebuildRunningIds[serviceName] = id;
|
|
|
|
},
|
2019-04-19 15:17:06 +00:00
|
|
|
);
|
|
|
|
} catch (e) {
|
|
|
|
if (!(e instanceof BuildError)) {
|
|
|
|
throw e;
|
|
|
|
}
|
|
|
|
|
2019-06-07 14:59:27 +00:00
|
|
|
if (this.rebuildsCancelled[serviceName]) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2019-04-19 15:17:06 +00:00
|
|
|
this.logger.logError(
|
|
|
|
`Rebuild of service ${serviceName} failed!\n Error: ${e.getServiceError(
|
|
|
|
serviceName,
|
|
|
|
)}`,
|
|
|
|
);
|
|
|
|
return;
|
2019-06-07 14:59:27 +00:00
|
|
|
} finally {
|
|
|
|
delete this.rebuildRunningIds[serviceName];
|
|
|
|
}
|
|
|
|
|
|
|
|
// If the build has been cancelled, exit early
|
|
|
|
if (this.rebuildsCancelled[serviceName]) {
|
|
|
|
return;
|
2019-04-19 15:17:06 +00:00
|
|
|
}
|
|
|
|
|
2019-05-27 12:19:14 +00:00
|
|
|
// Let's first delete the container from the device
|
|
|
|
const containerId = await this.api.getContainerId(serviceName);
|
|
|
|
await this.docker.getContainer(containerId).remove({ force: true });
|
2019-04-19 15:17:06 +00:00
|
|
|
const currentState = await this.api.getTargetState();
|
2019-05-27 12:19:14 +00:00
|
|
|
// If we re-apply the target state, the supervisor
|
|
|
|
// should recreate the container
|
2019-04-19 15:17:06 +00:00
|
|
|
await this.api.setTargetState(
|
2019-10-14 15:40:46 +00:00
|
|
|
generateTargetState(currentState, this.composition, [buildTask], {}),
|
2019-04-19 15:17:06 +00:00
|
|
|
);
|
|
|
|
|
|
|
|
await this.awaitDeviceStateSettle();
|
|
|
|
|
|
|
|
const instance = this.containers[serviceName];
|
|
|
|
// Get the new container
|
|
|
|
const container = _.find(this.lastDeviceStatus!.containers, {
|
|
|
|
serviceName,
|
|
|
|
});
|
|
|
|
if (container == null) {
|
|
|
|
throw new Error(
|
|
|
|
`Could not find new container for service ${serviceName}`,
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
const buildLogs: Dictionary<string> = {};
|
|
|
|
buildLogs[serviceName] = buildLog;
|
|
|
|
const stageImages = LivepushManager.getMultistageImageIDs(buildLogs);
|
|
|
|
|
2020-04-29 16:54:41 +00:00
|
|
|
const dockerfile = new Dockerfile(buildTask.dockerfile!);
|
|
|
|
|
|
|
|
instance.livepush = await Livepush.init({
|
|
|
|
dockerfile,
|
|
|
|
context: buildTask.context!,
|
|
|
|
containerId: container.containerId,
|
|
|
|
stageImages: stageImages[serviceName],
|
|
|
|
docker: this.docker,
|
|
|
|
});
|
2019-06-07 14:59:27 +00:00
|
|
|
this.assignLivepushOutputHandlers(serviceName, instance.livepush);
|
2019-04-19 15:17:06 +00:00
|
|
|
} catch (e) {
|
|
|
|
this.logger.logError(`There was an error rebuilding the service: ${e}`);
|
2019-06-07 14:59:27 +00:00
|
|
|
} finally {
|
|
|
|
this.rebuildsRunning[serviceName] = false;
|
|
|
|
this.rebuildsCancelled[serviceName] = false;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
private async cancelRebuild(serviceName: string) {
|
|
|
|
this.rebuildsCancelled[serviceName] = true;
|
|
|
|
|
|
|
|
// If we have a container id of the current build,
|
|
|
|
// attempt to kill it
|
|
|
|
if (this.rebuildRunningIds[serviceName] != null) {
|
|
|
|
try {
|
|
|
|
await this.docker
|
|
|
|
.getContainer(this.rebuildRunningIds[serviceName])
|
|
|
|
.remove({ force: true });
|
|
|
|
await this.containers[serviceName].livepush.cancel();
|
|
|
|
} catch {
|
|
|
|
// No need to do anything here
|
|
|
|
}
|
2019-04-19 15:17:06 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-06-07 14:59:27 +00:00
|
|
|
private assignLivepushOutputHandlers(
|
|
|
|
serviceName: string,
|
|
|
|
livepush: Livepush,
|
|
|
|
) {
|
|
|
|
const msgString = (msg: string) =>
|
|
|
|
`[${getServiceColourFn(serviceName)(serviceName)}] ${msg}`;
|
|
|
|
const log = (msg: string) => this.logger.logLivepush(msgString(msg));
|
|
|
|
const error = (msg: string) => this.logger.logError(msgString(msg));
|
|
|
|
const debugLog = (msg: string) => this.logger.logDebug(msgString(msg));
|
|
|
|
|
2020-06-15 22:53:07 +00:00
|
|
|
livepush.on('commandExecute', (command) =>
|
2019-06-07 14:59:27 +00:00
|
|
|
log(`Executing command: \`${command.command}\``),
|
|
|
|
);
|
2020-06-15 22:53:07 +00:00
|
|
|
livepush.on('commandOutput', (output) =>
|
2019-06-07 14:59:27 +00:00
|
|
|
log(` ${output.output.data.toString()}`),
|
|
|
|
);
|
|
|
|
livepush.on('commandReturn', ({ returnCode, command }) => {
|
|
|
|
if (returnCode !== 0) {
|
|
|
|
error(` Command ${command} failed with exit code: ${returnCode}`);
|
|
|
|
} else {
|
|
|
|
debugLog(`Command ${command} exited successfully`);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
livepush.on('containerRestart', () => {
|
|
|
|
log('Restarting service...');
|
|
|
|
});
|
|
|
|
livepush.on('cancel', () => {
|
|
|
|
log('Cancelling current livepush...');
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2019-01-14 16:51:57 +00:00
|
|
|
private static extractDockerArrowMessage(
|
|
|
|
outputLine: string,
|
|
|
|
): string | undefined {
|
|
|
|
const arrowTest = /^.*\s*-+>\s*(.+)/i;
|
|
|
|
const match = arrowTest.exec(outputLine);
|
|
|
|
if (match != null) {
|
|
|
|
return match[1];
|
|
|
|
}
|
|
|
|
}
|
2019-04-19 15:17:06 +00:00
|
|
|
|
|
|
|
private getDockerfilePathFromTask(task: BuildTask): string[] {
|
|
|
|
switch (task.projectType) {
|
|
|
|
case 'Standard Dockerfile':
|
|
|
|
return ['Dockerfile'];
|
|
|
|
case 'Dockerfile.template':
|
|
|
|
return ['Dockerfile.template'];
|
|
|
|
case 'Architecture-specific Dockerfile':
|
|
|
|
return [
|
|
|
|
`Dockerfile.${this.deviceInfo.arch}`,
|
|
|
|
`Dockerfile.${this.deviceInfo.deviceType}`,
|
|
|
|
];
|
|
|
|
default:
|
|
|
|
return [];
|
|
|
|
}
|
|
|
|
}
|
2019-05-13 16:06:57 +00:00
|
|
|
|
|
|
|
// For each service, get a debounced function
|
|
|
|
private getDebouncedEventHandler = _.memoize((serviceName: string) => {
|
|
|
|
return _.debounce(
|
|
|
|
() => this.handleFSEvents(serviceName),
|
|
|
|
LIVEPUSH_DEBOUNCE_TIMEOUT,
|
|
|
|
);
|
|
|
|
});
|
2019-01-14 16:51:57 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
export default LivepushManager;
|