2017-12-20 21:46:01 +00:00
|
|
|
/*
|
2020-06-26 11:46:58 +00:00
|
|
|
Copyright 2016-2020 Balena Ltd.
|
2017-12-20 21:46:01 +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.
|
|
|
|
*/
|
2021-12-19 23:04:16 +00:00
|
|
|
|
|
|
|
import type { Application, BalenaSDK, Device, Organization } from 'balena-sdk';
|
2019-03-12 22:07:57 +00:00
|
|
|
import _ = require('lodash');
|
2017-12-20 21:46:01 +00:00
|
|
|
|
2021-08-26 23:49:54 +00:00
|
|
|
import { instanceOf, NotLoggedInError, ExpectedError } from '../errors';
|
2020-07-08 17:03:10 +00:00
|
|
|
import { getBalenaSdk, getVisuals, stripIndent, getCliForm } from './lazy';
|
2019-03-12 22:07:57 +00:00
|
|
|
import validation = require('./validation');
|
2020-07-01 14:26:40 +00:00
|
|
|
import { delay } from './helpers';
|
2017-12-20 21:46:01 +00:00
|
|
|
|
2020-07-01 14:26:40 +00:00
|
|
|
export function authenticate(options: {}): Promise<void> {
|
2019-01-12 21:20:19 +00:00
|
|
|
const balena = getBalenaSdk();
|
2020-07-08 17:03:10 +00:00
|
|
|
return getCliForm()
|
2018-01-09 15:05:24 +00:00
|
|
|
.run(
|
|
|
|
[
|
|
|
|
{
|
|
|
|
message: 'Email:',
|
|
|
|
name: 'email',
|
|
|
|
type: 'input',
|
|
|
|
validate: validation.validateEmail,
|
|
|
|
},
|
|
|
|
{
|
|
|
|
message: 'Password:',
|
|
|
|
name: 'password',
|
|
|
|
type: 'password',
|
|
|
|
},
|
|
|
|
],
|
|
|
|
{ override: options },
|
|
|
|
)
|
2018-10-19 14:38:50 +00:00
|
|
|
.then(balena.auth.login)
|
|
|
|
.then(balena.auth.twoFactor.isPassed)
|
2018-01-09 15:05:24 +00:00
|
|
|
.then((isTwoFactorAuthPassed: boolean) => {
|
|
|
|
if (isTwoFactorAuthPassed) {
|
|
|
|
return;
|
|
|
|
}
|
2017-12-20 21:46:01 +00:00
|
|
|
|
2020-07-08 17:03:10 +00:00
|
|
|
return getCliForm()
|
2018-01-09 15:05:24 +00:00
|
|
|
.ask({
|
|
|
|
message: 'Two factor auth challenge:',
|
|
|
|
name: 'code',
|
|
|
|
type: 'input',
|
|
|
|
})
|
2018-10-19 14:38:50 +00:00
|
|
|
.then(balena.auth.twoFactor.challenge)
|
2018-01-09 15:05:24 +00:00
|
|
|
.catch((error: any) => {
|
2018-10-19 14:38:50 +00:00
|
|
|
return balena.auth.logout().then(() => {
|
2018-01-09 15:05:24 +00:00
|
|
|
if (
|
2018-10-19 14:38:50 +00:00
|
|
|
error.name === 'BalenaRequestError' &&
|
2018-01-09 15:05:24 +00:00
|
|
|
error.statusCode === 401
|
|
|
|
) {
|
2020-06-26 11:46:58 +00:00
|
|
|
throw new ExpectedError('Invalid two factor authentication code');
|
2018-01-09 15:05:24 +00:00
|
|
|
}
|
|
|
|
throw error;
|
|
|
|
});
|
|
|
|
});
|
2018-01-04 16:17:43 +00:00
|
|
|
});
|
2018-01-04 14:07:55 +00:00
|
|
|
}
|
2017-12-20 21:46:01 +00:00
|
|
|
|
2020-03-24 08:51:19 +00:00
|
|
|
/**
|
|
|
|
* Check if logged in, and throw `NotLoggedInError` if not.
|
|
|
|
* Note: `NotLoggedInError` is an `ExpectedError`.
|
|
|
|
*/
|
2019-10-31 01:40:57 +00:00
|
|
|
export async function checkLoggedIn(): Promise<void> {
|
2019-03-25 15:16:23 +00:00
|
|
|
const balena = getBalenaSdk();
|
|
|
|
if (!(await balena.auth.isLoggedIn())) {
|
2020-06-26 11:46:58 +00:00
|
|
|
throw new NotLoggedInError(stripIndent`
|
|
|
|
Login required: use the “balena login” command to log in.
|
|
|
|
`);
|
2019-03-25 15:16:23 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-12-20 21:46:01 +00:00
|
|
|
export function askLoginType() {
|
2020-07-08 17:03:10 +00:00
|
|
|
return getCliForm().ask<'web' | 'credentials' | 'token' | 'register'>({
|
2017-12-20 21:46:01 +00:00
|
|
|
message: 'How would you like to login?',
|
|
|
|
name: 'loginType',
|
|
|
|
type: 'list',
|
2018-01-09 15:05:24 +00:00
|
|
|
choices: [
|
|
|
|
{
|
|
|
|
name: 'Web authorization (recommended)',
|
|
|
|
value: 'web',
|
|
|
|
},
|
|
|
|
{
|
|
|
|
name: 'Credentials',
|
|
|
|
value: 'credentials',
|
|
|
|
},
|
|
|
|
{
|
|
|
|
name: 'Authentication token',
|
|
|
|
value: 'token',
|
|
|
|
},
|
|
|
|
{
|
2018-10-19 14:38:50 +00:00
|
|
|
name: "I don't have a balena account!",
|
2018-01-09 15:05:24 +00:00
|
|
|
value: 'register',
|
|
|
|
},
|
|
|
|
],
|
2018-01-04 14:07:55 +00:00
|
|
|
});
|
2017-12-20 21:46:01 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
export function selectDeviceType() {
|
2019-01-12 21:20:19 +00:00
|
|
|
return getBalenaSdk()
|
|
|
|
.models.config.getDeviceTypes()
|
2020-06-15 22:53:07 +00:00
|
|
|
.then((deviceTypes) => {
|
2019-11-14 09:53:38 +00:00
|
|
|
deviceTypes = _.sortBy(deviceTypes, 'name').filter(
|
2020-06-15 22:53:07 +00:00
|
|
|
(dt) => dt.state !== 'DISCONTINUED',
|
2019-11-14 09:53:38 +00:00
|
|
|
);
|
2020-07-08 17:03:10 +00:00
|
|
|
return getCliForm().ask({
|
2019-01-12 21:20:19 +00:00
|
|
|
message: 'Device Type',
|
|
|
|
type: 'list',
|
|
|
|
choices: _.map(deviceTypes, ({ slug: value, name }) => ({
|
|
|
|
name,
|
|
|
|
value,
|
|
|
|
})),
|
|
|
|
});
|
2018-01-04 14:07:55 +00:00
|
|
|
});
|
2017-12-20 21:46:01 +00:00
|
|
|
}
|
|
|
|
|
2020-07-15 19:13:18 +00:00
|
|
|
/**
|
|
|
|
* Display interactive confirmation prompt.
|
2021-08-26 23:49:54 +00:00
|
|
|
* Throw ExpectedError if the user declines.
|
2020-07-15 19:13:18 +00:00
|
|
|
* @param yesOption - automatically confirm if true
|
|
|
|
* @param message - message to display with prompt
|
|
|
|
* @param yesMessage - message to display if automatically confirming
|
|
|
|
*/
|
2020-07-01 14:26:40 +00:00
|
|
|
export async function confirm(
|
2018-10-25 12:57:45 +00:00
|
|
|
yesOption: boolean,
|
2018-01-09 15:05:24 +00:00
|
|
|
message: string,
|
2018-10-25 12:57:45 +00:00
|
|
|
yesMessage?: string,
|
2021-08-26 23:49:54 +00:00
|
|
|
defaultValue = false,
|
2018-01-09 15:05:24 +00:00
|
|
|
) {
|
2020-07-01 14:26:40 +00:00
|
|
|
if (yesOption) {
|
|
|
|
if (yesMessage) {
|
2021-12-19 23:04:16 +00:00
|
|
|
console.log(yesMessage);
|
2017-12-20 21:46:01 +00:00
|
|
|
}
|
2020-07-01 14:26:40 +00:00
|
|
|
return;
|
|
|
|
}
|
2017-12-20 21:46:01 +00:00
|
|
|
|
2020-07-08 17:03:10 +00:00
|
|
|
const confirmed = await getCliForm().ask<boolean>({
|
2020-07-01 14:26:40 +00:00
|
|
|
message,
|
|
|
|
type: 'confirm',
|
2021-08-26 23:49:54 +00:00
|
|
|
default: defaultValue,
|
2018-01-04 14:07:55 +00:00
|
|
|
});
|
2020-07-01 14:26:40 +00:00
|
|
|
|
|
|
|
if (!confirmed) {
|
2021-08-26 23:49:54 +00:00
|
|
|
throw new ExpectedError('Aborted');
|
2020-07-01 14:26:40 +00:00
|
|
|
}
|
2017-12-20 21:46:01 +00:00
|
|
|
}
|
|
|
|
|
2018-10-19 11:14:28 +00:00
|
|
|
export function selectApplication(
|
2020-07-31 14:35:20 +00:00
|
|
|
filter?: (app: ApplicationWithDeviceType) => boolean,
|
2020-07-15 14:26:31 +00:00
|
|
|
errorOnEmptySelection = false,
|
2018-10-19 11:14:28 +00:00
|
|
|
) {
|
2019-01-12 21:20:19 +00:00
|
|
|
const balena = getBalenaSdk();
|
2018-10-19 14:38:50 +00:00
|
|
|
return balena.models.application
|
2018-01-09 15:05:24 +00:00
|
|
|
.hasAny()
|
2020-07-31 15:25:48 +00:00
|
|
|
.then(async (hasAnyApplications) => {
|
2018-01-09 15:05:24 +00:00
|
|
|
if (!hasAnyApplications) {
|
2021-07-15 13:41:38 +00:00
|
|
|
throw new ExpectedError('No fleets found');
|
2018-01-09 15:05:24 +00:00
|
|
|
}
|
2017-12-20 21:46:01 +00:00
|
|
|
|
2021-12-21 00:02:45 +00:00
|
|
|
const apps = (await balena.models.application.getAllDirectlyAccessible({
|
2020-07-31 15:25:48 +00:00
|
|
|
$expand: {
|
|
|
|
is_for__device_type: {
|
|
|
|
$select: 'slug',
|
|
|
|
},
|
|
|
|
},
|
|
|
|
})) as ApplicationWithDeviceType[];
|
|
|
|
return apps.filter(filter || _.constant(true));
|
2018-01-09 15:05:24 +00:00
|
|
|
})
|
2020-06-15 22:53:07 +00:00
|
|
|
.then((applications) => {
|
2020-07-15 14:26:31 +00:00
|
|
|
if (errorOnEmptySelection && applications.length === 0) {
|
2021-07-15 13:41:38 +00:00
|
|
|
throw new ExpectedError('No suitable fleets found for selection');
|
2020-07-15 14:26:31 +00:00
|
|
|
}
|
2020-07-08 17:03:10 +00:00
|
|
|
return getCliForm().ask({
|
2018-01-09 15:05:24 +00:00
|
|
|
message: 'Select an application',
|
|
|
|
type: 'list',
|
2020-06-15 22:53:07 +00:00
|
|
|
choices: _.map(applications, (application) => ({
|
2020-12-10 12:30:17 +00:00
|
|
|
name: `${application.app_name} (${application.slug}) [${application.is_for__device_type[0].slug}]`,
|
|
|
|
value: application,
|
2018-01-09 15:05:24 +00:00
|
|
|
})),
|
|
|
|
});
|
|
|
|
});
|
2017-12-20 21:46:01 +00:00
|
|
|
}
|
|
|
|
|
2020-12-09 15:05:12 +00:00
|
|
|
export async function selectOrganization(organizations?: Organization[]) {
|
|
|
|
// Use either provided orgs (if e.g. already loaded) or load from cloud
|
|
|
|
organizations =
|
|
|
|
organizations || (await getBalenaSdk().models.organization.getAll());
|
|
|
|
return getCliForm().ask({
|
|
|
|
message: 'Select an organization',
|
|
|
|
type: 'list',
|
|
|
|
choices: organizations.map((org) => ({
|
|
|
|
name: `${org.name} (${org.handle})`,
|
|
|
|
value: org.handle,
|
|
|
|
})),
|
|
|
|
});
|
2017-12-20 21:46:01 +00:00
|
|
|
}
|
|
|
|
|
2020-07-01 14:26:40 +00:00
|
|
|
export async function awaitDeviceOsUpdate(
|
|
|
|
uuid: string,
|
|
|
|
targetOsVersion: string,
|
|
|
|
) {
|
2019-06-11 12:08:15 +00:00
|
|
|
const balena = getBalenaSdk();
|
|
|
|
|
2020-07-01 14:26:40 +00:00
|
|
|
const deviceName = await balena.models.device.getName(uuid);
|
|
|
|
const visuals = getVisuals();
|
|
|
|
const progressBar = new visuals.Progress(
|
|
|
|
`Updating the OS of ${deviceName} to v${targetOsVersion}`,
|
|
|
|
);
|
|
|
|
progressBar.update({ percentage: 0 });
|
|
|
|
|
|
|
|
const poll = async (): Promise<void> => {
|
2021-07-20 13:57:00 +00:00
|
|
|
const [osUpdateStatus, { overall_progress: osUpdateProgress }] =
|
|
|
|
await Promise.all([
|
|
|
|
balena.models.device.getOsUpdateStatus(uuid),
|
|
|
|
balena.models.device.get(uuid, { $select: 'overall_progress' }),
|
|
|
|
]);
|
2020-07-01 14:26:40 +00:00
|
|
|
if (osUpdateStatus.status === 'done') {
|
|
|
|
console.info(
|
|
|
|
`The device ${deviceName} has been updated to v${targetOsVersion} and will restart shortly!`,
|
|
|
|
);
|
|
|
|
return;
|
|
|
|
}
|
2019-06-11 12:08:15 +00:00
|
|
|
|
2020-07-01 14:26:40 +00:00
|
|
|
if (osUpdateStatus.error) {
|
2021-08-26 23:49:54 +00:00
|
|
|
throw new ExpectedError(
|
|
|
|
`Failed to complete Host OS update on device ${deviceName}\n${osUpdateStatus.error}`,
|
2020-07-01 14:26:40 +00:00
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
if (osUpdateProgress !== null) {
|
|
|
|
// Avoid resetting to 0% at end of process when device goes offline.
|
|
|
|
progressBar.update({ percentage: osUpdateProgress });
|
|
|
|
}
|
|
|
|
|
|
|
|
await delay(3000);
|
|
|
|
await poll();
|
|
|
|
};
|
|
|
|
|
|
|
|
await poll();
|
|
|
|
return uuid;
|
2019-06-11 12:08:15 +00:00
|
|
|
}
|
|
|
|
|
2017-12-20 21:46:01 +00:00
|
|
|
export function inferOrSelectDevice(preferredUuid: string) {
|
2019-01-12 21:20:19 +00:00
|
|
|
const balena = getBalenaSdk();
|
2020-07-31 15:25:48 +00:00
|
|
|
return balena.models.device.getAll().then((devices) => {
|
|
|
|
const onlineDevices = devices.filter((device) => device.is_online);
|
|
|
|
if (_.isEmpty(onlineDevices)) {
|
|
|
|
throw new ExpectedError("You don't have any devices online");
|
|
|
|
}
|
2017-12-20 21:46:01 +00:00
|
|
|
|
2020-07-31 15:25:48 +00:00
|
|
|
const defaultUuid = _(onlineDevices).map('uuid').includes(preferredUuid)
|
|
|
|
? preferredUuid
|
|
|
|
: onlineDevices[0].uuid;
|
|
|
|
|
|
|
|
return getCliForm().ask({
|
|
|
|
message: 'Select a device',
|
|
|
|
type: 'list',
|
|
|
|
default: defaultUuid,
|
|
|
|
choices: _.map(onlineDevices, (device) => ({
|
|
|
|
name: `${device.device_name || 'Untitled'} (${device.uuid.slice(
|
|
|
|
0,
|
|
|
|
7,
|
|
|
|
)})`,
|
|
|
|
value: device.uuid,
|
|
|
|
})),
|
2018-01-09 15:05:24 +00:00
|
|
|
});
|
2020-07-31 15:25:48 +00:00
|
|
|
});
|
2017-12-20 21:46:01 +00:00
|
|
|
}
|
|
|
|
|
2020-12-16 15:57:25 +00:00
|
|
|
/*
|
|
|
|
* Given applicationOrDevice, which may be
|
|
|
|
* - an application name
|
|
|
|
* - an application slug
|
|
|
|
* - an application id (integer)
|
|
|
|
* - a device uuid
|
|
|
|
* Either:
|
|
|
|
* - in case of device uuid, return uuid of device after verifying that it exists and is online.
|
|
|
|
* - in case of application, return uuid of device user selects from list of online devices.
|
|
|
|
*
|
|
|
|
* TODO: Modify this when app IDs dropped.
|
|
|
|
*/
|
|
|
|
export async function getOnlineTargetDeviceUuid(
|
2021-12-19 23:04:16 +00:00
|
|
|
sdk: BalenaSDK,
|
2020-12-16 15:57:25 +00:00
|
|
|
applicationOrDevice: string,
|
2020-08-25 11:45:39 +00:00
|
|
|
) {
|
2020-12-16 15:57:25 +00:00
|
|
|
const logger = (await import('../utils/logger')).getLogger();
|
|
|
|
|
|
|
|
// If looks like UUID, probably device
|
|
|
|
if (validation.validateUuid(applicationOrDevice)) {
|
|
|
|
let device: Device;
|
2020-08-25 11:45:39 +00:00
|
|
|
try {
|
2020-12-16 15:57:25 +00:00
|
|
|
logger.logDebug(
|
|
|
|
`Trying to fetch device by UUID ${applicationOrDevice} (${typeof applicationOrDevice})`,
|
|
|
|
);
|
|
|
|
device = await sdk.models.device.get(applicationOrDevice, {
|
|
|
|
$select: ['uuid', 'is_online'],
|
|
|
|
});
|
2020-08-25 11:45:39 +00:00
|
|
|
|
2020-12-16 15:57:25 +00:00
|
|
|
if (!device.is_online) {
|
|
|
|
throw new ExpectedError(
|
|
|
|
`Device with UUID ${applicationOrDevice} is offline`,
|
|
|
|
);
|
|
|
|
}
|
2019-06-06 10:24:44 +00:00
|
|
|
|
2020-12-16 15:57:25 +00:00
|
|
|
return device.uuid;
|
|
|
|
} catch (err) {
|
|
|
|
const { BalenaDeviceNotFound } = await import('balena-errors');
|
|
|
|
if (instanceOf(err, BalenaDeviceNotFound)) {
|
|
|
|
logger.logDebug(`Device with UUID ${applicationOrDevice} not found`);
|
|
|
|
// Now try app
|
|
|
|
} else {
|
|
|
|
throw err;
|
|
|
|
}
|
|
|
|
}
|
2019-06-06 10:24:44 +00:00
|
|
|
}
|
|
|
|
|
2020-12-16 15:57:25 +00:00
|
|
|
// Not a device UUID, try app
|
|
|
|
let app: Application;
|
2019-06-06 10:24:44 +00:00
|
|
|
try {
|
2021-07-15 13:41:38 +00:00
|
|
|
logger.logDebug(`Fetching fleet ${applicationOrDevice}`);
|
2021-08-26 23:49:54 +00:00
|
|
|
const { getApplication } = await import('./sdk');
|
2020-12-16 15:57:25 +00:00
|
|
|
app = await getApplication(sdk, applicationOrDevice);
|
2019-06-06 10:24:44 +00:00
|
|
|
} catch (err) {
|
2020-07-08 17:21:37 +00:00
|
|
|
const { BalenaApplicationNotFound } = await import('balena-errors');
|
2020-12-16 15:57:25 +00:00
|
|
|
if (instanceOf(err, BalenaApplicationNotFound)) {
|
|
|
|
throw new ExpectedError(
|
2021-07-15 13:41:38 +00:00
|
|
|
`Fleet or Device not found: ${applicationOrDevice}`,
|
2020-12-16 15:57:25 +00:00
|
|
|
);
|
|
|
|
} else {
|
2019-06-06 10:24:44 +00:00
|
|
|
throw err;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-12-16 15:57:25 +00:00
|
|
|
// App found, load its devices
|
|
|
|
const devices = await sdk.models.device.getAllByApplication(app.id, {
|
|
|
|
$select: ['device_name', 'uuid'],
|
|
|
|
$filter: { is_online: true },
|
|
|
|
});
|
|
|
|
|
|
|
|
// Throw if no devices online
|
|
|
|
if (_.isEmpty(devices)) {
|
|
|
|
throw new ExpectedError(
|
2021-07-15 13:41:38 +00:00
|
|
|
`Fleet ${app.slug} found, but has no devices online.`,
|
2020-12-16 15:57:25 +00:00
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
// Ask user to select from online devices for application
|
|
|
|
return getCliForm().ask({
|
2021-07-15 13:41:38 +00:00
|
|
|
message: `Select a device on fleet ${app.slug}`,
|
2020-12-16 15:57:25 +00:00
|
|
|
type: 'list',
|
|
|
|
default: devices[0].uuid,
|
|
|
|
choices: _.map(devices, (device) => ({
|
|
|
|
name: `${device.device_name || 'Untitled'} (${device.uuid.slice(0, 7)})`,
|
|
|
|
value: device.uuid,
|
|
|
|
})),
|
|
|
|
});
|
2019-06-06 10:24:44 +00:00
|
|
|
}
|
|
|
|
|
2018-05-22 15:12:51 +00:00
|
|
|
export function selectFromList<T>(
|
|
|
|
message: string,
|
|
|
|
choices: Array<T & { name: string }>,
|
2020-07-01 14:26:40 +00:00
|
|
|
): Promise<T> {
|
2020-07-08 17:03:10 +00:00
|
|
|
return getCliForm().ask<T>({
|
2018-04-25 14:20:07 +00:00
|
|
|
message,
|
|
|
|
type: 'list',
|
2020-06-15 22:53:07 +00:00
|
|
|
choices: _.map(choices, (s) => ({
|
2018-04-25 14:20:07 +00:00
|
|
|
name: s.name,
|
|
|
|
value: s,
|
|
|
|
})),
|
|
|
|
});
|
|
|
|
}
|