Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,21 @@
},
"zone:record": {
"description": "display commands for working with dns records"
},
"vm": {
"description": "display commands for working with vms"
},
"vm:disk": {
"description": "display commands for working with vm disks"
},
"vm:snapshot": {
"description": "display commands for working with vm snapshots"
},
"vm:script": {
"description": "display commands for working with vm init scripts"
},
"vm:ip": {
"description": "display commands for working with vm extra IPs"
}
}
},
Expand Down
278 changes: 236 additions & 42 deletions src/commands/vm/create.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import ora, { Ora } from 'ora';
import ora from 'ora';
import inquirer from 'inquirer';
import { Flags } from '@oclif/core';

Expand All @@ -7,13 +7,21 @@ import { IAAS_API_URL } from '../../constants.js';
import {
IGETOperatingSystems,
IGetVMsResponse,
IVMs,
IGetVMInitScriptsResponse,
IGETOperatingSystemsResponse,
} from '../../types/vm.js';
import checkRegexPattern, {
checkVMNameRegexPattern,
} from '../../utils/name-regex.js';
import { createDebugLogger } from '../../utils/output.js';
import {
APPS_WITHOUT_SSH_PORT,
formatPlanChoice,
getDisabledPlans,
getInitScriptTypeForOS,
getOSName,
isWindowsOS,
validateSSHKey,
validateSSHPort,
validateVMName,
} from '../../utils/vm.js';

export default class VmCreate extends Command {
static flags = {
Expand All @@ -22,6 +30,27 @@ export default class VmCreate extends Command {
char: 'v',
description: 'vm name',
}),
os: Flags.string({
description: 'operating system or one-click app (see "liara vm os")',
}),
'os-version': Flags.string({
description: 'version of the operating system or one-click app',
}),
plan: Flags.string({
char: 'p',
description: 'vm plan (see "liara vm plans")',
}),
'ssh-key': Flags.string({
description: 'SSH public key to add to the vm (can be repeated)',
multiple: true,
}),
'ssh-port': Flags.integer({
description: 'SSH port of the vm (default 22)',
}),
'init-script': Flags.string({
description:
'name or id of an init script to run on the first boot (see "liara vm script list")',
}),
detach: Flags.boolean({
char: 'd',
description: 'run command in detach mode',
Expand All @@ -45,31 +74,83 @@ export default class VmCreate extends Command {
await this.setGotConfig(flags);

try {
const interactive = !flags.os || !flags.plan;

const vmName = flags.vm ?? (await this.promptVMName());
this.validateName(vmName);

const oss = await this.getOperatingSystems();

const vmName = await this.promptVMName();
const osName = flags.os ?? (await this.promptOperatingSystems(oss));
if (flags.os && !oss[osName]) {
this.error(
`Unknown operating system "${osName}". Use "liara vm os" to see the available ones.`,
);
}

const osName = await this.promptOperatingSystems(oss);
const osVersion = await this.getOSVersion(
osName,
oss,
flags['os-version'],
);
const os = `${osName}-${osVersion}`;

const plan = await this.getPlan(os, flags.plan);

const config: {
SSHKeys?: string[];
sshPort?: number;
InitScriptID?: string;
} = {};

const windows = isWindowsOS(osName);
const supportsSSHPort =
!windows && !APPS_WITHOUT_SSH_PORT.includes(getOSName(osName));

if (!windows) {
const sshKeys =
flags['ssh-key'] ?? (interactive ? await this.promptSSHKey() : []);
for (const key of sshKeys) {
const keyError = validateSSHKey(key);
if (keyError) {
this.error(keyError);
}
}

const osVersion = await this.promptOperatingSystemVersions(osName, oss);
if (sshKeys.length > 0) {
config.SSHKeys = sshKeys;
}
} else if (flags['ssh-key']) {
this.error('SSH keys are not supported on Windows vms.');
}

if (supportsSSHPort) {
const sshPort =
flags['ssh-port'] ??
(interactive ? await this.promptSSHPort() : undefined);

const plan = await this.promptPlan();
if (sshPort !== undefined) {
this.validatePort(sshPort);
config.sshPort = sshPort;
}
} else if (flags['ssh-port'] !== undefined) {
this.error(`The SSH port cannot be set for ${osName}.`);
}

const SSHKeys = await this.promptSSHKey();
const initScriptID = await this.getInitScript(
osName,
flags['init-script'],
interactive,
);
if (initScriptID) {
config.InitScriptID = initScriptID;
}

const newSSH =
SSHKeys.length > 0
? {
config: {
SSHKeys: SSHKeys,
},
}
: null;
const newVM = {
OS: `${osName}-${osVersion}`,
OS: os,
name: vmName,
plan,
...newSSH,
...(Object.keys(config).length > 0 ? { config } : {}),
};
await this.got.post('vm', {
json: newVM,
Expand Down Expand Up @@ -152,23 +233,148 @@ export default class VmCreate extends Command {
return osVersion;
}

validateName(vmName: string) {
const nameError = validateVMName(vmName);
if (nameError) {
this.error(nameError);
}
}

validatePort(port: number) {
const portError = validateSSHPort(port);
if (portError) {
this.error(portError);
}
}

async promptVMName() {
const { vmName } = (await inquirer.prompt({
message: 'Enter vm name: ',
type: 'input',
name: 'vmName',
validate: (input) => input.length > 3 && input.length < 20,
validate: (input) => validateVMName(input) ?? true,
})) as { vmName: string };
if (!checkVMNameRegexPattern(vmName)) {

return vmName;
}

async getOSVersion(
osName: string,
oss: IGETOperatingSystems,
versionFlag: string | undefined,
) {
if (!versionFlag) {
return this.promptOperatingSystemVersions(osName, oss);
}

if (!oss[osName].includes(versionFlag)) {
this.error(
'Invalid vm name. It must start with a lowercase letter, contain only lowercase letters, numbers, or hyphens, and be between 4 and 19 characters long.',
`Unknown version "${versionFlag}" for ${osName}. Available versions: ${oss[osName].join(', ')}.`,
);
}

return vmName;
return versionFlag;
}

async getPlan(os: string, planFlag: string | undefined) {
if (!planFlag) {
return this.promptPlan(os);
}

const { plans } = await this.got('plans').json<{ plans: any }>();
const available = this.selectablePlans(plans, os);

if (!available.includes(planFlag)) {
this.error(
`The plan "${planFlag}" is not available for ${os}. Available plans: ${available.join(', ')}.`,
);
}

return planFlag;
}

selectablePlans(plans: { [key: string]: any }, os: string) {
const disabled = getDisabledPlans(os);
return Object.keys(plans).filter(
(planKey) => !planKey.startsWith('free') && !disabled.includes(planKey),
);
}

async getInitScript(
osName: string,
flag: string | undefined,
interactive: boolean,
): Promise<string | undefined> {
if (!flag && !interactive) {
return undefined;
}

const type = getInitScriptTypeForOS(osName);
const { initScripts } =
await this.got('init-scripts').json<IGetVMInitScriptsResponse>();
const scripts = initScripts.filter((script) => script.type === type);

if (flag) {
const matches = scripts.filter(
(script) => script._id === flag || script.name === flag,
);

if (matches.length === 0) {
this.error(
`Could not find a ${type} init script named "${flag}". Use "liara vm script list" to see your scripts.`,
);
}

if (matches.length > 1) {
this.error(
`More than one init script is named "${flag}". Use its id instead.`,
);
}

return matches[0]._id;
}

if (scripts.length === 0) {
return undefined;
}

return this.promptInitScript(scripts.map((script) => script));
}

async promptInitScript(
scripts: { _id: string; name: string; description?: string }[],
): Promise<string | undefined> {
const { script } = (await inquirer.prompt({
name: 'script',
type: 'list',
message: 'Select an init script to run on the first boot:',
choices: [
{ name: 'None', value: '' },
...scripts.map((item) => ({
name: item.description
? `${item.name} - ${item.description}`
: item.name,
value: item._id,
})),
],
})) as { script: string };

return script || undefined;
}

async promptSSHPort(): Promise<number | undefined> {
const { sshPort } = (await inquirer.prompt({
name: 'sshPort',
type: 'input',
message: 'SSH port (leave empty for the default, 22):',
validate: (input: string) =>
input.trim() === '' || (validateSSHPort(input.trim()) ?? true),
})) as { sshPort: string };

return sshPort.trim() === '' ? undefined : Number(sshPort);
}

async promptPlan() {
async promptPlan(os?: string) {
this.spinner.start('Loading...');

try {
Expand All @@ -178,22 +384,10 @@ export default class VmCreate extends Command {
name: 'plan',
type: 'list',
message: 'Please select a plan:',
choices: Object.keys(plans)
.filter((planKey) => !planKey.startsWith('free'))
.map((planKey) => {
const planDetails = plans[planKey];
const { RAM, CPU, volume, monthlyPrice } = planDetails;
const ram = `RAM: ${String(RAM.amount).padEnd(4)} GB`;
const cpu = `CPU: ${String(CPU.amount).padEnd(4)} Core${CPU.amount > 1 ? 's' : ' '}`;

const disk = `Disk: ${String(volume).padEnd(4)} GB`;
const price = `Price: ${monthlyPrice.toLocaleString().padEnd(10)} Tomans/Month`;

return {
value: planKey,
name: `${ram.padEnd(8)} | ${cpu.padEnd(10)} | ${disk.padEnd(8)} | ${price}`,
};
}),
choices: this.selectablePlans(plans, os ?? '').map((planKey) => ({
value: planKey,
name: formatPlanChoice(plans[planKey]),
})),
})) as { plan: string };

return plan;
Expand All @@ -210,7 +404,7 @@ export default class VmCreate extends Command {
message: 'Enter SSH Key: ',
name: 'SSHKey',
type: 'input',
validate: (input) => input.length !== 0,
validate: (input) => validateSSHKey(input) ?? true,
})) as { SSHKey: string };
SSHKeys.push(SSHKey);
}
Expand Down
Loading
Loading