From 8eb3a5d09afda95a2bd445f8d2c923f93cf49631 Mon Sep 17 00:00:00 2001 From: Amin Ehterami Date: Sat, 14 Nov 2026 04:25:53 +0330 Subject: [PATCH 1/7] feat(vm): add shared vm command base and utils --- src/constants.ts | 5 + src/types/vm.ts | 97 ++++++++ src/utils/name-regex.ts | 2 +- src/utils/vm-disk-snapshot.ts | 17 ++ src/utils/vm-script.ts | 61 +++++ src/utils/vm.ts | 416 ++++++++++++++++++++++++++++++++++ src/vm-command.ts | 224 ++++++++++++++++++ test/vm/utils.unit.test.ts | 414 +++++++++++++++++++++++++++++++++ 8 files changed, 1235 insertions(+), 1 deletion(-) create mode 100644 src/utils/vm-disk-snapshot.ts create mode 100644 src/utils/vm-script.ts create mode 100644 src/utils/vm.ts create mode 100644 src/vm-command.ts create mode 100644 test/vm/utils.unit.test.ts diff --git a/src/constants.ts b/src/constants.ts index 0762a617..21ef264b 100644 --- a/src/constants.ts +++ b/src/constants.ts @@ -74,3 +74,8 @@ export const TEAM_RESOURCE_NAME_FIELDS: { [type: string]: string } = { vm: 'name', ai: 'name', }; + +// Price of each extra IPv4 address of a vm, used when the plan does not +// provide a price of its own. +export const VM_IPV4_MONTHLY_PRICE = 200_000; +export const VM_IPV4_HOURLY_PRICE = 277; diff --git a/src/types/vm.ts b/src/types/vm.ts index 626e5e1a..7daba517 100644 --- a/src/types/vm.ts +++ b/src/types/vm.ts @@ -14,6 +14,7 @@ export interface IGetVMResponse extends IVMs { SSHKeys: string[]; rootPassword: string; hostname: string; + sshPort?: number | string; }; IPs: { address: string; version: string }[]; planDetails: { @@ -21,6 +22,8 @@ export interface IGetVMResponse extends IVMs { region: string; monthlyPrice: number; hourlyPrice: number; + IPv4MonthlyPrice?: { [ipCount: string]: number }; + IPv4HourlyPrice?: { [ipCount: string]: number }; volume: number; RAM: { amount: number; @@ -51,3 +54,97 @@ export interface IGETOperatingSystemsResponse { 'one-click-apps': IGETOperatingSystems; [key: string]: IGETOperatingSystems | string[]; } + +export interface IVMPlan { + available?: boolean; + region?: string; + monthlyPrice: number; + hourlyPrice?: number; + volume: number; + RAM: { amount: number }; + CPU: { amount: number }; +} + +export interface IGetVMPlansResponse { + plans: { [key: string]: IVMPlan }; +} + +export interface IVMDisk { + _id: string; + name: string; + size: number; + createdAt: string; +} + +export interface IGetVMDisksResponse { + disks: IVMDisk[]; +} + +export interface IVMSnapshot { + _id: string; + name: string; + description?: string; + sizeB: number; + createdAt: string; + isCurrent?: boolean; +} + +export type IGetVMSnapshotsResponse = IVMSnapshot[]; + +export type VMInitScriptType = 'shell' | 'powershell'; + +export interface IVMInitScript { + _id: string; + name: string; + description?: string; + type: VMInitScriptType; + createdAt: string; +} + +export interface IGetVMInitScriptsResponse { + initScripts: IVMInitScript[]; +} + +export interface IVMResetPasswordResponse { + password: string; +} + +export interface IVMMetricPoint { + timestamp: number | string; + value?: number | string | { read?: number; write?: number }; + read?: number; + write?: number; +} + +export interface IVMMetricsHistoryResponse { + result: IVMMetricPoint[]; +} + +export interface IVMMetricsSummaryResponse { + result: { + cpu?: number | null; + memory?: number | null; + disk?: number | null; + diskIO?: { read?: number | null; write?: number | null }; + } | null; +} + +export interface IVMTrafficRow { + dstip: string; + sumbytes: number | string; + minute?: number | string; +} + +export interface IVMTrafficResponse { + result: IVMTrafficRow[]; +} + +export interface IVMDailyTraffic { + day: string; + bytes?: number | string; + price?: number | string; +} + +export interface IVMDailyTrafficResponse { + result: { daily: IVMDailyTraffic[] }; +} diff --git a/src/utils/name-regex.ts b/src/utils/name-regex.ts index 0a188249..f79e17fa 100644 --- a/src/utils/name-regex.ts +++ b/src/utils/name-regex.ts @@ -4,6 +4,6 @@ export default function checkRegexPattern(str: string) { } export function checkVMNameRegexPattern(str: string) { - const regex = /^[a-z][a-z0-9\-]+$/; + const regex = /^[a-z0-9][a-z0-9-]*[a-z0-9]$/; return regex.test(str); } diff --git a/src/utils/vm-disk-snapshot.ts b/src/utils/vm-disk-snapshot.ts new file mode 100644 index 00000000..57279007 --- /dev/null +++ b/src/utils/vm-disk-snapshot.ts @@ -0,0 +1,17 @@ +import { IVMDisk, IVMSnapshot } from '../types/vm.js'; +import { formatBytes, formatDateTime } from './vm.js'; + +export const SNAPSHOT_OPERATIONS = { + create: ['CREATE_VM_SNAPSHOT'], + revert: ['REVERT_VM_SNAPSHOT'], + delete: ['DELETE_VM_SNAPSHOT'], +}; + +export function describeDisk(disk: IVMDisk) { + return `${disk.name} (${disk.size} GB)`; +} + +export function describeSnapshot(snapshot: IVMSnapshot) { + const current = snapshot.isCurrent ? ' [current]' : ''; + return `${snapshot.name}${current} (${formatBytes(snapshot.sizeB)}, ${formatDateTime(snapshot.createdAt)})`; +} diff --git a/src/utils/vm-script.ts b/src/utils/vm-script.ts new file mode 100644 index 00000000..30c9a329 --- /dev/null +++ b/src/utils/vm-script.ts @@ -0,0 +1,61 @@ +import path from 'node:path'; +import fs from 'fs-extra'; + +import { IVMInitScript, VMInitScriptType } from '../types/vm.js'; +import { INIT_SCRIPT_TYPES, getScriptTypeByFileName } from './vm.js'; + +export function describeScript(script: IVMInitScript) { + return `${script.name} (${script.type})`; +} + +export interface IScriptInput { + file?: string; + content?: string; + type?: string; +} + +export interface IResolvedScript { + content?: string; + type?: VMInitScriptType; +} + +// Reads the script body from --file or --content. The type comes from --type, +// or from the extension of --file (.sh or .ps1). +export async function resolveScriptInput( + input: IScriptInput, +): Promise { + if (input.file && input.content !== undefined) { + throw new Error('Use either --file or --content, not both.'); + } + + let type = input.type as VMInitScriptType | undefined; + let content = input.content; + + if (input.file) { + const fileType = getScriptTypeByFileName(path.basename(input.file)); + if (!fileType) { + throw new Error( + 'Only files with the .sh or .ps1 extension are accepted as scripts.', + ); + } + + if (!(await fs.pathExists(input.file))) { + throw new Error(`The file "${input.file}" does not exist.`); + } + + content = await fs.readFile(input.file, 'utf8'); + type = type || fileType; + } + + if (type && !INIT_SCRIPT_TYPES.includes(type)) { + throw new Error( + `The script type must be one of: ${INIT_SCRIPT_TYPES.join(', ')}.`, + ); + } + + if (content !== undefined && !content.trim()) { + throw new Error('The script content cannot be empty.'); + } + + return { content, type }; +} diff --git a/src/utils/vm.ts b/src/utils/vm.ts new file mode 100644 index 00000000..584fd5be --- /dev/null +++ b/src/utils/vm.ts @@ -0,0 +1,416 @@ +import bytes from 'bytes'; +import moment from 'moment'; +import * as shamsi from 'shamsi-date-converter'; + +import { + IVMDailyTraffic, + IVMMetricPoint, + IVMMetricsSummaryResponse, + IVMTrafficRow, + VMInitScriptType, +} from '../types/vm.js'; + +export const APPS_WITHOUT_SSH_PORT = ['bigbluebutton']; + +export const INIT_SCRIPT_TYPES: VMInitScriptType[] = ['shell', 'powershell']; + +export const INIT_SCRIPT_EXTENSIONS: { [type in VMInitScriptType]: string } = { + shell: 'sh', + powershell: 'ps1', +}; + +export const VM_METRICS = ['cpu', 'memory', 'disk', 'diskIO'] as const; +export type VMMetric = (typeof VM_METRICS)[number]; + +interface IRange { + amount: number; + unit: 'hours' | 'days' | 'weeks'; + // Seconds added to the start of the range (the console does this to keep + // the 24h traffic query inside the retention window). + bufferSeconds?: number; +} + +export const METRIC_RANGES: { [range: string]: IRange } = { + '1h': { amount: 1, unit: 'hours' }, + '3h': { amount: 3, unit: 'hours' }, + '24h': { amount: 24, unit: 'hours' }, + '48h': { amount: 48, unit: 'hours' }, + '1w': { amount: 1, unit: 'weeks' }, + '1m': { amount: 30, unit: 'days' }, +}; + +export const TRAFFIC_RANGES: { [range: string]: IRange } = { + '1h': { amount: 1, unit: 'hours' }, + '3h': { amount: 3, unit: 'hours' }, + '24h': { amount: 24, unit: 'hours', bufferSeconds: 60 }, +}; + +export const MAX_DAILY_TRAFFIC_DAYS = 30; + +export function isWindowsOS(os: string) { + return os.includes('windows'); +} + +// The vm OS looks like "ubuntu-22.04" or "gitlabce-16" for one-click apps. +export function getOSName(os: string) { + return os.split('-')[0]; +} + +export function getRootUsername(os: string) { + return isWindowsOS(os) ? 'Administrator' : 'root'; +} + +const BASE_PLAN = 'standard-base-g2'; +const PLUS_PLAN = 'standard-plus-g2'; +const PRO_PLAN = 'pro-g2'; + +// Plans the console does not let you pick for an OS or a one-click app. +export function getDisabledPlans(os: string): string[] { + const name = getOSName(os); + + if (isWindowsOS(os)) { + return [BASE_PLAN]; + } + + if ( + ['gitlabce', 'appwrite', 'supabase', 'jitsi', 'bigbluebutton'].includes( + name, + ) + ) { + return [BASE_PLAN, PLUS_PLAN]; + } + + if (name.includes('sentry')) { + return [BASE_PLAN, PLUS_PLAN, PRO_PLAN]; + } + + return []; +} + +export function validateVMName(name: string): string | null { + if (name.length < 3) { + return 'The vm name must be at least 3 characters long.'; + } + + if (name.length > 20) { + return 'The vm name must be at most 20 characters long.'; + } + + if (!/^[a-z0-9][a-z0-9-]*[a-z0-9]$/.test(name)) { + return 'Invalid vm name. Use only lowercase letters, numbers, or hyphens; it must not start or end with a hyphen.'; + } + + return null; +} + +export function validateSSHKey(key: string): string | null { + const trimmed = key.trim(); + if (!trimmed) { + return 'The SSH key cannot be empty.'; + } + + // The trailing comment may contain anything, the key type and body must not. + const withoutComment = trimmed.split(' ').slice(0, 2).join(' '); + if (/[^\x20-\x7E]/.test(withoutComment)) { + return 'The SSH key is not valid. Please enter a valid key.'; + } + + return null; +} + +export function validateSSHPort(port: number | string): string | null { + const value = Number(port); + + if (value === 25) { + return 'Port 25 cannot be used as the SSH port.'; + } + + if (!Number.isInteger(value) || value < 1 || value > 65_535) { + return 'The SSH port must be a number between 1 and 65535.'; + } + + return null; +} + +export function getScriptTypeByFileName( + fileName: string, +): VMInitScriptType | undefined { + const extension = fileName.split('.').pop()?.toLowerCase(); + + return INIT_SCRIPT_TYPES.find( + (type) => INIT_SCRIPT_EXTENSIONS[type] === extension, + ); +} + +export function getInitScriptTypeForOS(os: string): VMInitScriptType { + return isWindowsOS(os) ? 'powershell' : 'shell'; +} + +export function formatBytes(value: number | string | undefined | null) { + return bytes.format(Number(value) || 0, { + decimalPlaces: 1, + unitSeparator: ' ', + }); +} + +// Jalali date like the other commands show, followed by the time. +export function formatDateTime(date: string | number | Date) { + const value = moment(date); + if (!value.isValid()) { + return String(date ?? '-'); + } + + const [year, month, day] = shamsi.gregorianToJalali(value.toDate()); + const pad = (part: number) => String(part).padStart(2, '0'); + + return `${year}-${pad(month)}-${pad(day)} ${value.format('HH:mm:ss')}`; +} + +export function toNullableNumber(value: unknown): number | null { + if (value === null || value === undefined || value === '') { + return null; + } + + const numeric = Number(value); + return Number.isFinite(numeric) ? numeric : null; +} + +// The first unix second the history of a vm can contain: the start of the +// range, but never before the vm was created. +export function calculateSince( + range: string, + vmCreatedAt?: string, + now = moment(), +): number { + const option = METRIC_RANGES[range] || METRIC_RANGES['1h']; + const rangeStart = now.clone().subtract(option.amount, option.unit).unix(); + const createdAt = vmCreatedAt ? new Date(vmCreatedAt).getTime() : Number.NaN; + + if (!Number.isFinite(createdAt)) { + return rangeStart; + } + + return Math.max(rangeStart, Math.floor(createdAt / 1000) + 1); +} + +export function getTrafficSince(range: string, now = moment()): number { + const option = TRAFFIC_RANGES[range] || TRAFFIC_RANGES['1h']; + + return ( + now.clone().subtract(option.amount, option.unit).unix() + + (option.bufferSeconds || 0) + ); +} + +// Timestamps arrive in seconds or in milliseconds. +export function normalizeTimestamp(value: unknown): number | null { + const timestamp = Number(value); + + if (!Number.isFinite(timestamp) || timestamp <= 0) { + return null; + } + + return timestamp >= 1_000_000_000_000 ? timestamp / 1000 : timestamp; +} + +export interface IScalarPoint { + time: number; + value: number | null; +} + +export function normalizeScalarPoints( + points: IVMMetricPoint[], +): IScalarPoint[] { + const byTime = new Map(); + + for (const point of Array.isArray(points) ? points : []) { + const time = normalizeTimestamp(point?.timestamp); + if (time === null) continue; + + byTime.set(time, toNullableNumber(point?.value)); + } + + return [...byTime.entries()] + .sort(([a], [b]) => a - b) + .map(([time, value]) => ({ time, value })); +} + +export interface IDiskIOPoint { + time: number; + read: number | null; + write: number | null; +} + +export function normalizeDiskIOPoints( + points: IVMMetricPoint[], +): IDiskIOPoint[] { + const byTime = new Map< + number, + { read: number | null; write: number | null } + >(); + + for (const point of Array.isArray(points) ? points : []) { + const time = normalizeTimestamp(point?.timestamp); + if (time === null) continue; + + const values = + point.value && typeof point.value === 'object' ? point.value : point; + + byTime.set(time, { + read: toNullableNumber(values.read), + write: toNullableNumber(values.write), + }); + } + + return [...byTime.entries()] + .sort(([a], [b]) => a - b) + .map(([time, values]) => ({ time, ...values })); +} + +export function normalizeSummary(data: IVMMetricsSummaryResponse) { + const result = data?.result; + + if (!result || typeof result !== 'object') { + return null; + } + + return { + cpu: toNullableNumber(result.cpu), + memory: toNullableNumber(result.memory), + disk: toNullableNumber(result.disk), + diskIO: { + read: toNullableNumber(result.diskIO?.read), + write: toNullableNumber(result.diskIO?.write), + }, + }; +} + +export function formatPercent(value: number | null) { + return value === null ? '-' : `${Math.round(value * 10) / 10}%`; +} + +export function formatDiskIO(value: number | null) { + return value === null ? '-' : `${Math.round(value * 100) / 100} MB/s`; +} + +// Sums the bytes sent to every destination ip, biggest first. +export function aggregateTraffic(rows: IVMTrafficRow[]) { + const byIp = new Map(); + + for (const row of Array.isArray(rows) ? rows : []) { + if (!row?.dstip) continue; + + byIp.set( + row.dstip, + (byIp.get(row.dstip) || 0) + (Number(row.sumbytes) || 0), + ); + } + + return [...byIp.entries()] + .map(([ip, total]) => ({ ip, bytes: total })) + .sort((a, b) => b.bytes - a.bytes); +} + +export function getDailyTrafficStart( + days: number, + vmCreatedAt?: string, + now = moment(), +) { + const rangeStart = now + .clone() + .subtract(days - 1, 'days') + .startOf('day'); + const createdAt = moment(vmCreatedAt); + + return vmCreatedAt && createdAt.isValid() && createdAt.isAfter(rangeStart) + ? createdAt.clone().add(1, 'second') + : rangeStart; +} + +const DAY_FORMAT = 'YYYY-MM-DD'; + +// Every day of the range gets a row, days without a report are zero. +export function normalizeDailyTraffic( + daily: IVMDailyTraffic[], + rangeStart: moment.Moment, + rangeEnd = moment(), +) { + const firstDay = rangeStart.clone().startOf('day'); + const lastDay = rangeEnd.clone().startOf('day'); + const byDay = new Map(); + + for (const item of Array.isArray(daily) ? daily : []) { + const match = /^(\d{4})-(\d{2})-(\d{2})/.exec(String(item?.day ?? '')); + if (!match) continue; + + const day = moment([ + Number(match[1]), + Number(match[2]) - 1, + Number(match[3]), + ]); + if (!day.isValid() || day.isBefore(firstDay) || day.isAfter(lastDay)) { + continue; + } + + const key = day.format(DAY_FORMAT); + const current = byDay.get(key) || { bytes: 0, price: 0 }; + byDay.set(key, { + bytes: current.bytes + (Number(item.bytes) || 0), + price: current.price + (Number(item.price) || 0), + }); + } + + const rows: { day: string; bytes: number; price: number }[] = []; + for ( + const day = firstDay.clone(); + day.isSameOrBefore(lastDay, 'day'); + day.add(1, 'day') + ) { + const key = day.format(DAY_FORMAT); + rows.push({ day: key, ...(byDay.get(key) || { bytes: 0, price: 0 }) }); + } + + return rows; +} + +export const FROZEN_VM_MESSAGE = + 'The vm is frozen. Use "liara vm unfreeze" to activate it first.'; + +export interface IPlanLike { + RAM: { amount: number }; + CPU: { amount: number }; + volume: number; + monthlyPrice: number; +} + +// Free plans are never offered. Plans that the console disables for an OS or +// a one-click app are skipped when the OS is known. +export function getSelectablePlans( + plans: { [key: string]: unknown }, + os?: string, +): string[] { + const disabled = os ? getDisabledPlans(os) : []; + + return Object.keys(plans).filter( + (key) => !key.startsWith('free') && !disabled.includes(key), + ); +} + +export function formatPlanChoice(plan: IPlanLike) { + const { RAM, CPU, volume, monthlyPrice } = plan; + 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 `${ram.padEnd(8)} | ${cpu.padEnd(10)} | ${disk.padEnd(8)} | ${price}`; +} + +// Finds items by their id or name; a name can match more than one item. +export function findByIdOrName( + items: T[], + value: string, +): T[] { + const byId = items.filter((item) => item._id === value); + return byId.length > 0 ? byId : items.filter((item) => item.name === value); +} diff --git a/src/vm-command.ts b/src/vm-command.ts new file mode 100644 index 00000000..2b951815 --- /dev/null +++ b/src/vm-command.ts @@ -0,0 +1,224 @@ +import ora from 'ora'; +import inquirer from 'inquirer'; + +import Command, { IConfig } from './base.js'; +import { IAAS_API_URL } from './constants.js'; +import { IGetVMResponse, IVMOperations, IVMs } from './types/vm.js'; +import { DebugLogger } from './utils/output.js'; +import parseJSON from './utils/json-parse.js'; +import { promptVMs } from './utils/prompt-vms.js'; +import { findByIdOrName } from './utils/vm.js'; + +export const NO_PERMISSION_MESSAGE = + "You don't have permission to do this in the current team."; + +export const OPERATION_TIMEOUT_MESSAGE = + 'The operation is still in progress. Use "liara vm events" to follow it.'; + +export interface ISelectVmOptions { + // Used when no vm matches the filter (or the --vm flag). + notFound: string; + filter?: (vm: IVMs) => boolean; +} + +export type OperationResult = 'SUCCEEDED' | 'FAILED' | 'TIMEOUT'; + +// Shared pieces of the vm commands that talk to the IaaS API. +export default abstract class VmCommand extends Command { + // How many times to check on a running operation before giving up. + get maxPollAttempts() { + return 300; + } + + async setGotConfig(config: IConfig): Promise { + await super.setGotConfig(config); + this.got = this.got.extend({ + prefixUrl: IAAS_API_URL, + }); + } + + async prepare(flags: IConfig) { + this.spinner = ora(); + await this.setGotConfig(flags); + } + + async sleep(ms: number) { + await new Promise((resolve) => { + setTimeout(resolve, ms); + }); + } + + async selectVm( + name: string | undefined, + { notFound, filter }: ISelectVmOptions, + ): Promise { + const matches = (vm: IVMs) => + (!name || vm.name === name) && (!filter || filter(vm)); + const vms = await this.getVms(notFound, matches); + + return name ? vms[0] : promptVMs(vms); + } + + async getVmDetails(vm: IVMs) { + return this.got.get(`vm/${vm._id}`).json(); + } + + async confirm(message: string) { + const { confirmation } = (await inquirer.prompt({ + name: 'confirmation', + type: 'confirm', + message, + default: false, + })) as { confirmation: boolean }; + + return confirmation; + } + + async promptSelect( + message: string, + choices: { name: string; value: T }[], + ): Promise { + const { selected } = (await inquirer.prompt({ + name: 'selected', + type: 'list', + message, + choices, + })) as { selected: T }; + + return selected; + } + + // Logs the failure and rethrows it, or raises a friendlier message for the + // status codes the caller knows about. + fail( + error: any, + debug: DebugLogger, + messages: { [status: number]: string } = {}, + ): never { + debug(error.message); + + if (error.response && error.response.body) { + debug(JSON.stringify(error.response.body)); + } + + const status: number | undefined = error.response?.statusCode; + const code = parseJSON(error.response?.body)?.data?.code; + + if (status === 403 && code === 'no_permission') { + this.error(NO_PERMISSION_MESSAGE); + } + + if (status && messages[status]) { + this.error(messages[status]); + } + + throw error; + } + + // Picks the item the flag points to (by id or name), or asks for one. + async selectItem( + items: T[], + flag: string | undefined, + { label, describe }: { label: string; describe: (item: T) => string }, + ): Promise { + if (flag) { + const matches = findByIdOrName(items, flag); + + if (matches.length === 0) { + this.error(`The ${label} "${flag}" does not exist.`); + } + + if (matches.length > 1) { + this.error( + `More than one ${label} is named "${flag}". Use its id instead.`, + ); + } + + return matches[0]; + } + + const id = await this.promptSelect( + `Please select a ${label}:`, + items.map((item) => ({ name: describe(item), value: item._id })), + ); + + return items.find((item) => item._id === id) as T; + } + + async getLatestOperation( + vm: IVMs, + after?: string, + names?: string[], + ): Promise { + const operations = await this.getVMOperations(vm); + + return operations + .filter((operation) => !after || operation.createdAt > after) + .filter((operation) => !names || names.includes(operation.name)) + .sort((a, b) => b.createdAt.localeCompare(a.createdAt))[0]; + } + + // Remember this before sending the request, so that waitForOperation can + // tell the operation it started from the older ones. + async getLatestOperationTime(vm: IVMs): Promise { + return (await this.getLatestOperation(vm))?.createdAt; + } + + async waitForOperation( + vm: IVMs, + after: string | undefined, + names?: string[], + interval = 2000, + ): Promise { + for (let attempt = 0; attempt < this.maxPollAttempts; attempt++) { + await this.sleep(interval); + + const operation = await this.getLatestOperation(vm, after, names); + + if (operation?.state === 'SUCCEEDED' || operation?.state === 'FAILED') { + return operation.state; + } + } + + return 'TIMEOUT'; + } + + // Shows the spinner while the operation started by the caller runs. + async followOperation( + vm: IVMs, + after: string | undefined, + texts: { doing: string; succeeded: string; failed: string }, + names?: string[], + ) { + this.spinner.start(texts.doing); + const result = await this.waitForOperation(vm, after, names); + + if (result === 'SUCCEEDED') { + this.spinner.succeed(texts.succeeded); + } else if (result === 'FAILED') { + this.spinner.fail(texts.failed); + this.exit(1); + } else { + this.spinner.warn(OPERATION_TIMEOUT_MESSAGE); + } + + return result; + } + + async waitForVm( + vm: IVMs, + isDone: (details: IGetVMResponse) => boolean, + interval = 2000, + ): Promise { + for (let attempt = 0; attempt < this.maxPollAttempts; attempt++) { + await this.sleep(interval); + + const details = await this.getVmDetails(vm); + if (isDone(details)) { + return details; + } + } + + return undefined; + } +} diff --git a/test/vm/utils.unit.test.ts b/test/vm/utils.unit.test.ts new file mode 100644 index 00000000..10e724e9 --- /dev/null +++ b/test/vm/utils.unit.test.ts @@ -0,0 +1,414 @@ +import fs from 'fs-extra'; +import os from 'node:os'; +import path from 'node:path'; +import moment from 'moment'; +import { expect } from 'chai'; + +import { + aggregateTraffic, + calculateSince, + findByIdOrName, + formatBytes, + formatDiskIO, + formatPercent, + formatPlanChoice, + getDailyTrafficStart, + getDisabledPlans, + getInitScriptTypeForOS, + getRootUsername, + getScriptTypeByFileName, + getSelectablePlans, + getTrafficSince, + normalizeDailyTraffic, + normalizeDiskIOPoints, + normalizeScalarPoints, + normalizeSummary, + normalizeTimestamp, + validateSSHKey, + validateSSHPort, + validateVMName, +} from '../../src/utils/vm.ts'; +import { resolveScriptInput } from '../../src/utils/vm-script.ts'; +import { checkVMNameRegexPattern } from '../../src/utils/name-regex.ts'; + +describe('vm utils', () => { + describe('validateVMName', () => { + it('accepts valid names', () => { + for (const name of ['abc', 'my-vm', '1vm', 'a'.repeat(20)]) { + expect(validateVMName(name), name).to.equal(null); + } + }); + + it('rejects names that are too short or too long', () => { + expect(validateVMName('ab')).to.include('at least 3'); + expect(validateVMName('a'.repeat(21))).to.include('at most 20'); + }); + + it('rejects invalid characters and edge hyphens', () => { + for (const name of ['-abc', 'abc-', 'ABC', 'a_b_c', 'a b c']) { + expect(validateVMName(name), name).to.include('Invalid vm name'); + } + }); + + it('matches the regex used by checkVMNameRegexPattern', () => { + expect(checkVMNameRegexPattern('1vm')).to.equal(true); + expect(checkVMNameRegexPattern('vm-')).to.equal(false); + }); + }); + + describe('validateSSHKey', () => { + it('accepts a key with a comment that has any characters', () => { + expect(validateSSHKey('ssh-ed25519 AAAAC3Nz user@host')).to.equal(null); + expect(validateSSHKey('ssh-ed25519 AAAAC3Nz سلام')).to.equal(null); + }); + + it('rejects empty keys', () => { + expect(validateSSHKey(' ')).to.include('cannot be empty'); + }); + + it('rejects non printable characters in the key body', () => { + expect(validateSSHKey('ssh-rsa AAAA\u200bBBB')).to.include('not valid'); + }); + }); + + describe('validateSSHPort', () => { + it('accepts ports between 1 and 65535', () => { + expect(validateSSHPort(1)).to.equal(null); + expect(validateSSHPort('2222')).to.equal(null); + expect(validateSSHPort(65_535)).to.equal(null); + }); + + it('rejects port 25', () => { + expect(validateSSHPort(25)).to.include('Port 25'); + }); + + it('rejects out of range and non integer ports', () => { + for (const port of [0, 65_536, -1, 22.5, 'abc']) { + expect(validateSSHPort(port), String(port)).to.include('between'); + } + }); + }); + + describe('getDisabledPlans', () => { + it('disables the base plan on windows', () => { + expect(getDisabledPlans('windows-2022')).to.deep.equal([ + 'standard-base-g2', + ]); + }); + + it('disables small plans for heavy one-click apps', () => { + for (const app of [ + 'gitlabce', + 'appwrite', + 'supabase', + 'jitsi', + 'bigbluebutton', + ]) { + expect(getDisabledPlans(`${app}-1`), app).to.deep.equal([ + 'standard-base-g2', + 'standard-plus-g2', + ]); + } + }); + + it('disables the three smallest plans for sentry', () => { + expect(getDisabledPlans('sentry-24')).to.deep.equal([ + 'standard-base-g2', + 'standard-plus-g2', + 'pro-g2', + ]); + }); + + it('disables nothing for a regular os', () => { + expect(getDisabledPlans('ubuntu-22.04')).to.deep.equal([]); + }); + }); + + describe('getSelectablePlans', () => { + const plans = { free: {}, 'free-windows': {}, a: {}, b: {} }; + + it('hides free plans', () => { + expect(getSelectablePlans(plans)).to.deep.equal(['a', 'b']); + }); + + it('hides the plans disabled for the os', () => { + const all = { 'standard-base-g2': {}, 'pro-g2': {}, free: {} }; + expect(getSelectablePlans(all, 'windows-2022')).to.deep.equal(['pro-g2']); + }); + }); + + describe('os helpers', () => { + it('picks the username by os', () => { + expect(getRootUsername('windows-2022')).to.equal('Administrator'); + expect(getRootUsername('ubuntu-22.04')).to.equal('root'); + }); + + it('picks the init script type by os', () => { + expect(getInitScriptTypeForOS('windows')).to.equal('powershell'); + expect(getInitScriptTypeForOS('ubuntu')).to.equal('shell'); + }); + + it('detects the script type by file name', () => { + expect(getScriptTypeByFileName('a.sh')).to.equal('shell'); + expect(getScriptTypeByFileName('dir/a.PS1')).to.equal('powershell'); + expect(getScriptTypeByFileName('a.txt')).to.equal(undefined); + }); + }); + + describe('formatters', () => { + it('formats bytes', () => { + expect(formatBytes(0)).to.equal('0 B'); + expect(formatBytes('1048576')).to.equal('1 MB'); + expect(formatBytes(undefined)).to.equal('0 B'); + }); + + it('formats percents and disk io', () => { + expect(formatPercent(12.345)).to.equal('12.3%'); + expect(formatPercent(null)).to.equal('-'); + expect(formatDiskIO(1.234)).to.equal('1.23 MB/s'); + expect(formatDiskIO(null)).to.equal('-'); + }); + + it('formats a plan choice', () => { + const choice = formatPlanChoice({ + RAM: { amount: 2 }, + CPU: { amount: 1 }, + volume: 50, + monthlyPrice: 1000, + }); + + expect(choice).to.include('RAM: 2'); + expect(choice).to.include('CPU: 1'); + expect(choice).to.include('Core '); + expect(choice).to.include('Disk: 50'); + expect(choice).to.include(`${(1000).toLocaleString()}`); + }); + }); + + describe('findByIdOrName', () => { + const items = [ + { _id: '1', name: 'a' }, + { _id: '2', name: 'a' }, + { _id: 'a', name: 'c' }, + ]; + + it('prefers an id match', () => { + expect(findByIdOrName(items, 'a')).to.deep.equal([items[2]]); + }); + + it('returns every name match', () => { + expect(findByIdOrName(items, 'c')).to.have.length(1); + expect(findByIdOrName([items[0], items[1]], 'a')).to.have.length(2); + expect(findByIdOrName(items, 'zzz')).to.deep.equal([]); + }); + }); + + describe('time ranges', () => { + const now = moment.unix(1_700_000_000); + + it('calculates the start of a metric range', () => { + expect(calculateSince('1h', undefined, now)).to.equal( + 1_700_000_000 - 3600, + ); + expect(calculateSince('1m', undefined, now)).to.equal( + 1_700_000_000 - 30 * 86_400, + ); + expect(calculateSince('unknown', undefined, now)).to.equal( + 1_700_000_000 - 3600, + ); + }); + + it('never starts before the vm was created', () => { + const createdAt = new Date((1_700_000_000 - 600) * 1000).toISOString(); + + expect(calculateSince('1h', createdAt, now)).to.equal( + 1_700_000_000 - 599, + ); + expect(calculateSince('1h', 'not a date', now)).to.equal( + 1_700_000_000 - 3600, + ); + }); + + it('calculates the start of a traffic range', () => { + expect(getTrafficSince('3h', now)).to.equal(1_700_000_000 - 3 * 3600); + expect(getTrafficSince('24h', now)).to.equal(1_700_000_000 - 86_400 + 60); + expect(getTrafficSince('bad', now)).to.equal(1_700_000_000 - 3600); + }); + }); + + describe('metric normalization', () => { + it('normalizes timestamps in seconds and milliseconds', () => { + expect(normalizeTimestamp(1_700_000_000)).to.equal(1_700_000_000); + expect(normalizeTimestamp(1_700_000_000_000)).to.equal(1_700_000_000); + expect(normalizeTimestamp(0)).to.equal(null); + expect(normalizeTimestamp('x')).to.equal(null); + }); + + it('sorts and deduplicates scalar points', () => { + const points = normalizeScalarPoints([ + { timestamp: 20, value: 2 }, + { timestamp: 10, value: '1' }, + { timestamp: 20, value: 5 }, + { timestamp: -1, value: 9 }, + { timestamp: 30, value: null as any }, + ]); + + expect(points).to.deep.equal([ + { time: 10, value: 1 }, + { time: 20, value: 5 }, + { time: 30, value: null }, + ]); + expect(normalizeScalarPoints(undefined as any)).to.deep.equal([]); + }); + + it('reads disk io values from the value object or the point', () => { + const points = normalizeDiskIOPoints([ + { timestamp: 2, value: { read: 1, write: 2 } }, + { timestamp: 1, read: 3, write: undefined }, + ]); + + expect(points).to.deep.equal([ + { time: 1, read: 3, write: null }, + { time: 2, read: 1, write: 2 }, + ]); + }); + + it('normalizes the summary', () => { + expect(normalizeSummary({ result: null })).to.equal(null); + expect( + normalizeSummary({ + result: { cpu: 1, memory: '2', diskIO: { read: 3 } }, + }), + ).to.deep.equal({ + cpu: 1, + memory: 2, + disk: null, + diskIO: { read: 3, write: null }, + }); + }); + }); + + describe('traffic', () => { + it('sums the bytes of each destination, biggest first', () => { + expect( + aggregateTraffic([ + { dstip: '1.1.1.1', sumbytes: 10 }, + { dstip: '2.2.2.2', sumbytes: '100' }, + { dstip: '1.1.1.1', sumbytes: 5 }, + { dstip: '', sumbytes: 99 }, + ]), + ).to.deep.equal([ + { ip: '2.2.2.2', bytes: 100 }, + { ip: '1.1.1.1', bytes: 15 }, + ]); + expect(aggregateTraffic(undefined as any)).to.deep.equal([]); + }); + + it('starts the daily report after the vm creation', () => { + const now = moment('2026-05-10T12:00:00'); + + expect( + getDailyTrafficStart(30, undefined, now).format('YYYY-MM-DD'), + ).to.equal('2026-04-11'); + + const created = getDailyTrafficStart(30, '2026-05-09T08:00:00', now); + expect(created.format('YYYY-MM-DD HH:mm:ss')).to.equal( + '2026-05-09 08:00:01', + ); + }); + + it('fills the days without a report', () => { + const rows = normalizeDailyTraffic( + [ + { day: '2026-05-08', bytes: 10, price: 1 }, + { day: '2026-05-08T10:00:00', bytes: '5', price: 2 }, + { day: '2026-05-10', bytes: 7, price: 0 }, + { day: '2026-05-01', bytes: 100, price: 100 }, + { day: 'garbage', bytes: 1 }, + ], + moment('2026-05-08T00:00:00'), + moment('2026-05-10T12:00:00'), + ); + + expect(rows).to.deep.equal([ + { day: '2026-05-08', bytes: 15, price: 3 }, + { day: '2026-05-09', bytes: 0, price: 0 }, + { day: '2026-05-10', bytes: 7, price: 0 }, + ]); + }); + }); + + describe('resolveScriptInput', () => { + let dir: string; + + beforeEach(async () => { + dir = await fs.mkdtemp(path.join(os.tmpdir(), 'liara-vm-script-')); + }); + + afterEach(async () => { + await fs.remove(dir); + }); + + it('reads a script file and infers the type', async () => { + const file = path.join(dir, 'init.ps1'); + await fs.writeFile(file, 'Write-Host hi'); + + expect(await resolveScriptInput({ file })).to.deep.equal({ + content: 'Write-Host hi', + type: 'powershell', + }); + }); + + it('lets --type win over the extension', async () => { + const file = path.join(dir, 'init.sh'); + await fs.writeFile(file, 'echo hi'); + + const result = await resolveScriptInput({ file, type: 'powershell' }); + expect(result.type).to.equal('powershell'); + }); + + it('returns inline content as is', async () => { + expect( + await resolveScriptInput({ content: 'echo hi', type: 'shell' }), + ).to.deep.equal({ content: 'echo hi', type: 'shell' }); + }); + + it('returns nothing when no script is given', async () => { + expect(await resolveScriptInput({})).to.deep.equal({ + content: undefined, + type: undefined, + }); + }); + + it('rejects --file together with --content', async () => { + let message = ''; + try { + await resolveScriptInput({ file: 'a.sh', content: 'x' }); + } catch (error) { + message = error.message; + } + expect(message).to.include('either --file or --content'); + }); + + it('rejects unknown extensions, missing files and empty scripts', async () => { + const failures: string[] = []; + for (const input of [ + { file: path.join(dir, 'a.txt') }, + { file: path.join(dir, 'missing.sh') }, + { content: ' ' }, + { content: 'x', type: 'bash' }, + ]) { + try { + await resolveScriptInput(input); + } catch (error) { + failures.push(error.message); + } + } + + expect(failures[0]).to.include('.sh or .ps1'); + expect(failures[1]).to.include('does not exist'); + expect(failures[2]).to.include('cannot be empty'); + expect(failures[3]).to.include('must be one of'); + }); + }); +}); From 9a589203d8c80363727b7a60b1dbc750e97db230 Mon Sep 17 00:00:00 2001 From: Amin Ehterami Date: Sat, 14 Nov 2026 04:25:59 +0330 Subject: [PATCH 2/7] feat(vm): add resize, reset-password, unfreeze, reset-network, ip, events, plans and os commands --- package.json | 15 +++++ src/commands/vm/events.ts | 62 +++++++++++++++++ src/commands/vm/ip/add.ts | 104 +++++++++++++++++++++++++++++ src/commands/vm/ip/remove.ts | 96 +++++++++++++++++++++++++++ src/commands/vm/os.ts | 51 ++++++++++++++ src/commands/vm/plans.ts | 51 ++++++++++++++ src/commands/vm/reset-network.ts | 85 ++++++++++++++++++++++++ src/commands/vm/reset-password.ts | 67 +++++++++++++++++++ src/commands/vm/resize.ts | 107 ++++++++++++++++++++++++++++++ src/commands/vm/unfreeze.ts | 42 ++++++++++++ 10 files changed, 680 insertions(+) create mode 100644 src/commands/vm/events.ts create mode 100644 src/commands/vm/ip/add.ts create mode 100644 src/commands/vm/ip/remove.ts create mode 100644 src/commands/vm/os.ts create mode 100644 src/commands/vm/plans.ts create mode 100644 src/commands/vm/reset-network.ts create mode 100644 src/commands/vm/reset-password.ts create mode 100644 src/commands/vm/resize.ts create mode 100644 src/commands/vm/unfreeze.ts diff --git a/package.json b/package.json index fbb49b00..cec1c61c 100644 --- a/package.json +++ b/package.json @@ -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" } } }, diff --git a/src/commands/vm/events.ts b/src/commands/vm/events.ts new file mode 100644 index 00000000..36d8728c --- /dev/null +++ b/src/commands/vm/events.ts @@ -0,0 +1,62 @@ +import { Flags, ux } from '@oclif/core'; + +import VmCommand from '../../vm-command.js'; +import { createDebugLogger } from '../../utils/output.js'; +import { formatDateTime } from '../../utils/vm.js'; + +export default class VmEvents extends VmCommand { + static description = 'list the operations (events) of a vm'; + + static flags = { + ...VmCommand.flags, + ...ux.table.flags(), + vm: Flags.string({ + char: 'v', + description: 'vm name', + }), + }; + + static aliases = ['vm:operations']; + + public async run(): Promise { + const { flags } = await this.parse(VmEvents); + const debug = createDebugLogger(flags.debug); + + await this.prepare(flags); + + try { + const vm = await this.selectVm(flags.vm, { + notFound: 'vm does not exist.', + filter: (vm) => vm.state !== 'DELETING', + }); + + const operations = await this.getVMOperations(vm); + + if (operations.length === 0) { + this.log(`There are no events for vm "${vm.name}".`); + return; + } + + ux.table( + [...operations] + .sort((a, b) => b.createdAt.localeCompare(a.createdAt)) + .map((operation) => ({ + Name: operation.name, + State: operation.state, + 'Created At': formatDateTime(operation.createdAt), + })), + { + Name: {}, + State: {}, + 'Created At': {}, + }, + flags, + ); + } catch (error) { + this.fail(error, debug, { + 400: 'Invalid vm ID.', + 404: 'Could not find the vm.', + }); + } + } +} diff --git a/src/commands/vm/ip/add.ts b/src/commands/vm/ip/add.ts new file mode 100644 index 00000000..9053d8ed --- /dev/null +++ b/src/commands/vm/ip/add.ts @@ -0,0 +1,104 @@ +import { Flags } from '@oclif/core'; + +import VmCommand from '../../../vm-command.js'; +import { + VM_IPV4_HOURLY_PRICE, + VM_IPV4_MONTHLY_PRICE, +} from '../../../constants.js'; +import { createDebugLogger } from '../../../utils/output.js'; +import { FROZEN_VM_MESSAGE } from '../../../utils/vm.js'; + +export default class VmIpAdd extends VmCommand { + static description = 'add an extra IPv4 address to a vm'; + + static flags = { + ...VmCommand.flags, + vm: Flags.string({ + char: 'v', + description: 'vm name', + }), + force: Flags.boolean({ + char: 'f', + description: 'skip the confirmation', + }), + detach: Flags.boolean({ + char: 'd', + description: 'run command in detach mode', + }), + }; + + static aliases = ['vm:ip:create']; + + public async run(): Promise { + const { flags } = await this.parse(VmIpAdd); + const debug = createDebugLogger(flags.debug); + + await this.prepare(flags); + + try { + const selected = await this.selectVm(flags.vm, { + notFound: 'vm does not exist.', + filter: (vm) => vm.state !== 'DELETING', + }); + + if (selected.state === 'FROZEN') { + this.error(FROZEN_VM_MESSAGE); + } + + const vm = await this.getVmDetails(selected); + const ipCount = vm.IPs.length; + const monthly = + vm.planDetails?.IPv4MonthlyPrice?.[ipCount] ?? VM_IPV4_MONTHLY_PRICE; + const hourly = + vm.planDetails?.IPv4HourlyPrice?.[ipCount] ?? VM_IPV4_HOURLY_PRICE; + + if ( + !flags.force && + !(await this.confirm( + `An extra IPv4 address costs ${hourly.toLocaleString()} Tomans/Hour (${monthly.toLocaleString()} Tomans/Month). Add it to "${vm.name}"?`, + )) + ) { + return; + } + + await this.got.post(`vm/extra-ip/${vm._id}`); + + if (flags.detach) { + this.spinner.succeed( + `The request has been submitted. The IP will be assigned to vm "${vm.name}" shortly. Use "liara vm info" to see it.`, + ); + return; + } + + this.spinner.start(`assigning an IP to vm "${vm.name}"...`); + const details = await this.waitForVm( + vm, + (current) => current.IPs.length > ipCount, + ); + + if (!details) { + this.spinner.warn( + 'The IP is not assigned yet. Use "liara vm info" to check it later.', + ); + return; + } + + const added = details.IPs[details.IPs.length - 1]; + this.spinner.succeed( + `The IP ${added.address} has been assigned to vm "${vm.name}".`, + ); + this.log( + 'To make the new IP reachable, power off the vm and run "liara vm reset-network".', + ); + } catch (error) { + this.spinner.stop(); + this.fail(error, debug, { + 400: 'Invalid vm ID.', + 403: 'This vm has reached the maximum number of IPs.', + 404: 'Could not find the vm.', + 429: 'An IP request is still in progress. Please wait until it finishes.', + 503: 'There is no assignable IP right now. Please try again in a few hours.', + }); + } + } +} diff --git a/src/commands/vm/ip/remove.ts b/src/commands/vm/ip/remove.ts new file mode 100644 index 00000000..7b7b2b3e --- /dev/null +++ b/src/commands/vm/ip/remove.ts @@ -0,0 +1,96 @@ +import { Flags } from '@oclif/core'; + +import VmCommand from '../../../vm-command.js'; +import { createDebugLogger } from '../../../utils/output.js'; +import { FROZEN_VM_MESSAGE } from '../../../utils/vm.js'; + +export default class VmIpRemove extends VmCommand { + static description = 'remove the extra IPv4 address of a vm'; + + static flags = { + ...VmCommand.flags, + vm: Flags.string({ + char: 'v', + description: 'vm name', + }), + force: Flags.boolean({ + char: 'f', + description: 'skip the confirmation', + }), + detach: Flags.boolean({ + char: 'd', + description: 'run command in detach mode', + }), + }; + + static aliases = ['vm:ip:delete', 'vm:ip:rm']; + + public async run(): Promise { + const { flags } = await this.parse(VmIpRemove); + const debug = createDebugLogger(flags.debug); + + await this.prepare(flags); + + try { + const selected = await this.selectVm(flags.vm, { + notFound: 'vm does not exist.', + filter: (vm) => vm.state !== 'DELETING', + }); + + if (selected.state === 'FROZEN') { + this.error(FROZEN_VM_MESSAGE); + } + + const vm = await this.getVmDetails(selected); + const ipCount = vm.IPs.length; + + if (ipCount < 2) { + this.error('This vm has no extra IP.'); + } + + const extraIp = vm.IPs[ipCount - 1]; + + if ( + !flags.force && + !(await this.confirm( + `Services that use ${extraIp.address} will no longer be reachable and you may not get the same IP again. Remove it from "${vm.name}"?`, + )) + ) { + return; + } + + await this.got.delete(`vm/extra-ip/${vm._id}`); + + if (flags.detach) { + this.spinner.succeed( + `The request has been submitted. The IP ${extraIp.address} will be removed from vm "${vm.name}" shortly.`, + ); + return; + } + + this.spinner.start(`removing ${extraIp.address} from vm "${vm.name}"...`); + const details = await this.waitForVm( + vm, + (current) => current.IPs.length < ipCount, + ); + + if (details) { + this.spinner.succeed( + `The IP ${extraIp.address} has been removed from vm "${vm.name}".`, + ); + } else { + this.spinner.warn( + 'The IP is not removed yet. Use "liara vm info" to check it later.', + ); + } + } catch (error) { + this.spinner.stop(); + this.fail(error, debug, { + 400: 'Invalid vm ID.', + 403: 'This vm has no extra IP.', + 404: 'Could not find the vm.', + 429: 'An IP request is still in progress. Please wait until it finishes.', + }); + } + } +} diff --git a/src/commands/vm/os.ts b/src/commands/vm/os.ts new file mode 100644 index 00000000..22657222 --- /dev/null +++ b/src/commands/vm/os.ts @@ -0,0 +1,51 @@ +import { ux } from '@oclif/core'; + +import VmCommand from '../../vm-command.js'; +import { IGETOperatingSystemsResponse } from '../../types/vm.js'; +import { createDebugLogger } from '../../utils/output.js'; + +export default class VmOs extends VmCommand { + static description = + 'list the operating systems and one-click apps available for vms'; + + static flags = { + ...VmCommand.flags, + ...ux.table.flags(), + }; + + static aliases = ['vm:oss', 'vm:images']; + + public async run(): Promise { + const { flags } = await this.parse(VmOs); + const debug = createDebugLogger(flags.debug); + + await this.prepare(flags); + + try { + this.spinner.start('Loading...'); + const oss = await this.got('oss').json(); + this.spinner.stop(); + + const { 'one-click-apps': apps, ...systems } = oss; + const rows = [ + ...Object.entries(systems as { [key: string]: string[] }).map( + ([name, versions]) => ({ + Name: name, + Type: 'OS', + Versions: versions.join(', '), + }), + ), + ...Object.entries(apps || {}).map(([name, versions]) => ({ + Name: name, + Type: 'App', + Versions: versions.join(', '), + })), + ]; + + ux.table(rows, { Name: {}, Type: {}, Versions: {} }, flags); + } catch (error) { + this.spinner.stop(); + this.fail(error, debug); + } + } +} diff --git a/src/commands/vm/plans.ts b/src/commands/vm/plans.ts new file mode 100644 index 00000000..539eb7f0 --- /dev/null +++ b/src/commands/vm/plans.ts @@ -0,0 +1,51 @@ +import { ux } from '@oclif/core'; + +import VmCommand from '../../vm-command.js'; +import { IGetVMPlansResponse } from '../../types/vm.js'; +import { createDebugLogger } from '../../utils/output.js'; +import { getSelectablePlans } from '../../utils/vm.js'; + +export default class VmPlans extends VmCommand { + static description = 'list the available vm plans'; + + static flags = { + ...VmCommand.flags, + ...ux.table.flags(), + }; + + static aliases = ['vm:plan:list']; + + public async run(): Promise { + const { flags } = await this.parse(VmPlans); + const debug = createDebugLogger(flags.debug); + + await this.prepare(flags); + + try { + this.spinner.start('Loading...'); + const { plans } = await this.got('plans').json(); + this.spinner.stop(); + + ux.table( + getSelectablePlans(plans).map((key) => ({ + Plan: key, + RAM: plans[key].RAM.amount, + CPU: plans[key].CPU.amount, + Disk: plans[key].volume, + Price: plans[key].monthlyPrice.toLocaleString(), + })), + { + Plan: {}, + RAM: { header: 'RAM(GB)' }, + CPU: { header: 'CPU(Core)' }, + Disk: { header: 'Disk(GB SSD)' }, + Price: { header: 'Price(Tomans/Month)' }, + }, + flags, + ); + } catch (error) { + this.spinner.stop(); + this.fail(error, debug); + } + } +} diff --git a/src/commands/vm/reset-network.ts b/src/commands/vm/reset-network.ts new file mode 100644 index 00000000..d1b30d7e --- /dev/null +++ b/src/commands/vm/reset-network.ts @@ -0,0 +1,85 @@ +import { Flags } from '@oclif/core'; + +import VmCommand from '../../vm-command.js'; +import { createDebugLogger } from '../../utils/output.js'; +import { FROZEN_VM_MESSAGE, isWindowsOS } from '../../utils/vm.js'; + +export default class VmResetNetwork extends VmCommand { + static description = + 'reset the network settings of a vm (the vm must be powered off)'; + + static flags = { + ...VmCommand.flags, + vm: Flags.string({ + char: 'v', + description: 'vm name', + }), + force: Flags.boolean({ + char: 'f', + description: 'skip the confirmation', + }), + detach: Flags.boolean({ + char: 'd', + description: 'run command in detach mode', + }), + }; + + static aliases = ['vm:reset:network']; + + public async run(): Promise { + const { flags } = await this.parse(VmResetNetwork); + const debug = createDebugLogger(flags.debug); + + await this.prepare(flags); + + try { + const vm = await this.selectVm(flags.vm, { + notFound: 'vm does not exist.', + filter: (vm) => vm.state !== 'DELETING', + }); + + if (vm.state === 'FROZEN') { + this.error(FROZEN_VM_MESSAGE); + } + + if (isWindowsOS(vm.OS)) { + this.error('Resetting the network of a Windows vm is not supported.'); + } + + if ( + !flags.force && + !(await this.confirm( + `The network settings of "${vm.name}" will be reset to their defaults. Continue?`, + )) + ) { + return; + } + + const after = flags.detach + ? undefined + : await this.getLatestOperationTime(vm); + + await this.got.post(`vm/reset-network/${vm._id}`); + + if (flags.detach) { + this.spinner.succeed( + `Network reset request submitted for vm "${vm.name}". Use "liara vm events" to follow it.`, + ); + return; + } + + await this.followOperation(vm, after, { + doing: `resetting the network of vm "${vm.name}"...`, + succeeded: `The network of vm "${vm.name}" has been reset.`, + failed: `Failed to reset the network of vm "${vm.name}".`, + }); + } catch (error) { + this.spinner.stop(); + this.fail(error, debug, { + 400: 'Resetting the network of a Windows vm is not supported.', + 404: 'Could not find the vm.', + 409: 'Please power off the vm first, using "liara vm stop".', + }); + } + } +} diff --git a/src/commands/vm/reset-password.ts b/src/commands/vm/reset-password.ts new file mode 100644 index 00000000..f86fa04b --- /dev/null +++ b/src/commands/vm/reset-password.ts @@ -0,0 +1,67 @@ +import { Flags } from '@oclif/core'; + +import VmCommand from '../../vm-command.js'; +import { IVMResetPasswordResponse } from '../../types/vm.js'; +import { createDebugLogger } from '../../utils/output.js'; +import { FROZEN_VM_MESSAGE, getRootUsername } from '../../utils/vm.js'; + +export default class VmResetPassword extends VmCommand { + static description = + 'reset the root (or Administrator) password of a vm (the vm must be powered off)'; + + static flags = { + ...VmCommand.flags, + vm: Flags.string({ + char: 'v', + description: 'vm name', + }), + force: Flags.boolean({ + char: 'f', + description: 'skip the confirmation', + }), + }; + + static aliases = ['vm:reset:password']; + + public async run(): Promise { + const { flags } = await this.parse(VmResetPassword); + const debug = createDebugLogger(flags.debug); + + await this.prepare(flags); + + try { + const vm = await this.selectVm(flags.vm, { + notFound: 'vm does not exist.', + filter: (vm) => vm.state !== 'DELETING', + }); + + if (vm.state === 'FROZEN') { + this.error(FROZEN_VM_MESSAGE); + } + + const username = getRootUsername(vm.OS); + + if ( + !flags.force && + !(await this.confirm( + `The ${username} password of "${vm.name}" will be reset and the vm will start again. Continue?`, + )) + ) { + return; + } + + const { password } = await this.got + .post(`vm/reset-password/${vm._id}`) + .json(); + + this.log(`The ${username} password of vm "${vm.name}" was reset.`); + this.log(`New password: ${password}`); + } catch (error) { + this.fail(error, debug, { + 400: 'Invalid vm ID.', + 404: 'Could not find the vm.', + 409: 'Please power off the vm first, using "liara vm stop".', + }); + } + } +} diff --git a/src/commands/vm/resize.ts b/src/commands/vm/resize.ts new file mode 100644 index 00000000..aac1c477 --- /dev/null +++ b/src/commands/vm/resize.ts @@ -0,0 +1,107 @@ +import { Flags } from '@oclif/core'; +import inquirer from 'inquirer'; + +import VmCommand from '../../vm-command.js'; +import { IGetVMPlansResponse, IVMPlan } from '../../types/vm.js'; +import { createDebugLogger } from '../../utils/output.js'; +import { + FROZEN_VM_MESSAGE, + formatPlanChoice, + getSelectablePlans, +} from '../../utils/vm.js'; + +export default class VmResize extends VmCommand { + static description = 'change the plan of a vm (the vm must be powered off)'; + + static flags = { + ...VmCommand.flags, + vm: Flags.string({ + char: 'v', + description: 'vm name', + }), + plan: Flags.string({ + char: 'p', + description: 'the new plan (see "liara vm plans")', + }), + }; + + static aliases = ['vm:change-plan']; + + public async run(): Promise { + const { flags } = await this.parse(VmResize); + const debug = createDebugLogger(flags.debug); + + await this.prepare(flags); + + try { + const vm = await this.selectVm(flags.vm, { + notFound: 'vm does not exist.', + filter: (vm) => vm.state !== 'DELETING', + }); + + if (vm.state === 'FROZEN') { + this.error(FROZEN_VM_MESSAGE); + } + + const plan = await this.getPlan(vm.OS, vm.plan, flags.plan); + + await this.got.patch(`vm/resize/${vm._id}`, { json: { plan } }); + + this.log(`The plan of vm "${vm.name}" changed to "${plan}".`); + } catch (error) { + this.fail(error, debug, { + 400: 'Invalid vm ID.', + 404: 'Could not find the vm.', + 409: 'Please power off the vm first, using "liara vm stop".', + 410: 'The plan of a free vm cannot be changed.', + 428: 'The disk usage of the vm is more than the new plan allows. Please reduce the extra space first.', + }); + } + } + + async getPlan( + os: string, + currentPlan: string, + planFlag: string | undefined, + ): Promise { + this.spinner.start('Loading...'); + let plans: { [key: string]: IVMPlan }; + try { + ({ plans } = await this.got('plans').json()); + } finally { + this.spinner.stop(); + } + + const available = getSelectablePlans(plans, os); + + if (planFlag) { + if (!available.includes(planFlag)) { + this.error( + `The plan "${planFlag}" is not available for this vm. Use "liara vm plans" to see the available plans.`, + ); + } + + if (planFlag === currentPlan) { + this.error(`The vm is already on the plan "${planFlag}".`); + } + + return planFlag; + } + + const { plan } = (await inquirer.prompt({ + name: 'plan', + type: 'list', + message: 'Please select the new plan:', + choices: available.map((key) => ({ + value: key, + name: `${formatPlanChoice(plans[key])}${key === currentPlan ? ' (current)' : ''}`, + })), + })) as { plan: string }; + + if (plan === currentPlan) { + this.error(`The vm is already on the plan "${plan}".`); + } + + return plan; + } +} diff --git a/src/commands/vm/unfreeze.ts b/src/commands/vm/unfreeze.ts new file mode 100644 index 00000000..c9b61294 --- /dev/null +++ b/src/commands/vm/unfreeze.ts @@ -0,0 +1,42 @@ +import { Flags } from '@oclif/core'; + +import VmCommand from '../../vm-command.js'; +import { createDebugLogger } from '../../utils/output.js'; + +export default class VmUnfreeze extends VmCommand { + static description = 'unfreeze a frozen vm'; + + static flags = { + ...VmCommand.flags, + vm: Flags.string({ + char: 'v', + description: 'vm name', + }), + }; + + public async run(): Promise { + const { flags } = await this.parse(VmUnfreeze); + const debug = createDebugLogger(flags.debug); + + await this.prepare(flags); + + try { + const vm = await this.selectVm(flags.vm, { + notFound: 'No frozen vms found.', + filter: (vm) => vm.state === 'FROZEN', + }); + + await this.got.post(`vm/unfreeze/${vm._id}`); + + this.log( + `vm "${vm.name}" is being activated. Use "liara vm list" to follow its state.`, + ); + } catch (error) { + this.fail(error, debug, { + 400: 'Invalid vm ID.', + 402: 'Your credit is not enough. You need at least the usage of the next hour.', + 404: 'Could not find the vm.', + }); + } + } +} From 906d20222e21cc41888245bdd4374fd528a502a0 Mon Sep 17 00:00:00 2001 From: Amin Ehterami Date: Sat, 14 Nov 2026 04:26:00 +0330 Subject: [PATCH 3/7] feat(vm): add disk and snapshot commands --- src/commands/vm/disk/create.ts | 66 +++++++++++++++++ src/commands/vm/disk/extend.ts | 98 ++++++++++++++++++++++++++ src/commands/vm/disk/list.ts | 59 ++++++++++++++++ src/commands/vm/snapshot/create.ts | 98 ++++++++++++++++++++++++++ src/commands/vm/snapshot/delete.ts | 108 ++++++++++++++++++++++++++++ src/commands/vm/snapshot/list.ts | 67 ++++++++++++++++++ src/commands/vm/snapshot/revert.ts | 109 +++++++++++++++++++++++++++++ 7 files changed, 605 insertions(+) create mode 100644 src/commands/vm/disk/create.ts create mode 100644 src/commands/vm/disk/extend.ts create mode 100644 src/commands/vm/disk/list.ts create mode 100644 src/commands/vm/snapshot/create.ts create mode 100644 src/commands/vm/snapshot/delete.ts create mode 100644 src/commands/vm/snapshot/list.ts create mode 100644 src/commands/vm/snapshot/revert.ts diff --git a/src/commands/vm/disk/create.ts b/src/commands/vm/disk/create.ts new file mode 100644 index 00000000..4f3885e9 --- /dev/null +++ b/src/commands/vm/disk/create.ts @@ -0,0 +1,66 @@ +import { Flags } from '@oclif/core'; +import inquirer from 'inquirer'; + +import VmCommand from '../../../vm-command.js'; +import { createDebugLogger } from '../../../utils/output.js'; +import { FROZEN_VM_MESSAGE } from '../../../utils/vm.js'; + +export default class VmDiskCreate extends VmCommand { + static description = 'create an extra disk for a vm'; + + static flags = { + ...VmCommand.flags, + vm: Flags.string({ + char: 'v', + description: 'vm name', + }), + size: Flags.integer({ + char: 's', + description: 'disk size in GB', + min: 1, + }), + }; + + public async run(): Promise { + const { flags } = await this.parse(VmDiskCreate); + const debug = createDebugLogger(flags.debug); + + await this.prepare(flags); + + try { + const vm = await this.selectVm(flags.vm, { + notFound: 'vm does not exist.', + filter: (vm) => vm.state !== 'DELETING', + }); + + if (vm.state === 'FROZEN') { + this.error(FROZEN_VM_MESSAGE); + } + + const size = flags.size ?? (await this.promptSize()); + + await this.got.post(`vm/disk/${vm._id}`, { json: { size } }); + + this.log(`A ${size} GB disk was created for vm "${vm.name}".`); + } catch (error) { + this.fail(error, debug, { + 400: 'Invalid vm ID or disk size.', + 404: 'Could not find the vm.', + 428: 'There is not enough space. Please upgrade the plan of the vm.', + }); + } + } + + async promptSize(): Promise { + const { size } = (await inquirer.prompt({ + name: 'size', + type: 'number', + message: 'Disk size (GB):', + validate: (input) => + (Number.isInteger(input) && input >= 1) || + 'The size must be a whole number of at least 1.', + })) as { size: number }; + + return size; + } +} diff --git a/src/commands/vm/disk/extend.ts b/src/commands/vm/disk/extend.ts new file mode 100644 index 00000000..d42a6df1 --- /dev/null +++ b/src/commands/vm/disk/extend.ts @@ -0,0 +1,98 @@ +import { Flags } from '@oclif/core'; +import inquirer from 'inquirer'; + +import VmCommand from '../../../vm-command.js'; +import { IGetVMDisksResponse } from '../../../types/vm.js'; +import { createDebugLogger } from '../../../utils/output.js'; +import { describeDisk } from '../../../utils/vm-disk-snapshot.js'; +import { FROZEN_VM_MESSAGE } from '../../../utils/vm.js'; + +export default class VmDiskExtend extends VmCommand { + static description = + 'increase the size of a vm disk (the vm must be powered off)'; + + static flags = { + ...VmCommand.flags, + vm: Flags.string({ + char: 'v', + description: 'vm name', + }), + disk: Flags.string({ + description: 'disk name or id', + }), + size: Flags.integer({ + char: 's', + description: 'the new size of the disk in GB', + min: 1, + }), + }; + + static aliases = ['vm:disk:resize']; + + public async run(): Promise { + const { flags } = await this.parse(VmDiskExtend); + const debug = createDebugLogger(flags.debug); + + await this.prepare(flags); + + try { + const vm = await this.selectVm(flags.vm, { + notFound: 'vm does not exist.', + filter: (vm) => vm.state !== 'DELETING', + }); + + if (vm.state === 'FROZEN') { + this.error(FROZEN_VM_MESSAGE); + } + + const { disks } = await this.got( + `vm/disk/${vm._id}`, + ).json(); + + if (disks.length === 0) { + this.error(`vm "${vm.name}" has no extra disks.`); + } + + const disk = await this.selectItem(disks, flags.disk, { + label: 'disk', + describe: describeDisk, + }); + + const size = flags.size ?? (await this.promptSize(disk.size)); + + if (size <= disk.size) { + this.error( + `The new size must be more than the current size of the disk (${disk.size} GB).`, + ); + } + + await this.got.post(`vm/disk/${vm._id}/${disk._id}`, { + json: { newSize: size }, + }); + + this.log( + `The size of disk "${disk.name}" is being increased to ${size} GB. Use "liara vm events" to follow it.`, + ); + } catch (error) { + this.fail(error, debug, { + 400: 'Invalid vm ID or disk size.', + 404: 'Could not find the disk.', + 409: 'Please power off the vm first, using "liara vm stop".', + 428: 'There is not enough space to extend the disk. Please upgrade the plan of the vm.', + }); + } + } + + async promptSize(current: number): Promise { + const { size } = (await inquirer.prompt({ + name: 'size', + type: 'number', + message: `New disk size (GB, currently ${current}):`, + validate: (input) => + (Number.isInteger(input) && input > current) || + `The size must be a whole number more than ${current}.`, + })) as { size: number }; + + return size; + } +} diff --git a/src/commands/vm/disk/list.ts b/src/commands/vm/disk/list.ts new file mode 100644 index 00000000..46957f2a --- /dev/null +++ b/src/commands/vm/disk/list.ts @@ -0,0 +1,59 @@ +import { Flags, ux } from '@oclif/core'; + +import VmCommand from '../../../vm-command.js'; +import { IGetVMDisksResponse } from '../../../types/vm.js'; +import { createDebugLogger } from '../../../utils/output.js'; +import { formatDateTime } from '../../../utils/vm.js'; + +export default class VmDiskList extends VmCommand { + static description = 'list the disks of a vm'; + + static flags = { + ...VmCommand.flags, + ...ux.table.flags(), + vm: Flags.string({ + char: 'v', + description: 'vm name', + }), + }; + + static aliases = ['vm:disk:ls']; + + public async run(): Promise { + const { flags } = await this.parse(VmDiskList); + const debug = createDebugLogger(flags.debug); + + await this.prepare(flags); + + try { + const vm = await this.selectVm(flags.vm, { + notFound: 'vm does not exist.', + filter: (vm) => vm.state !== 'DELETING', + }); + + const { disks } = await this.got( + `vm/disk/${vm._id}`, + ).json(); + + if (disks.length === 0) { + this.log(`vm "${vm.name}" has no extra disks.`); + return; + } + + ux.table( + disks.map((disk) => ({ + Name: disk.name, + 'Size(GB)': disk.size, + 'Created At': formatDateTime(disk.createdAt), + })), + { Name: {}, 'Size(GB)': {}, 'Created At': {} }, + flags, + ); + } catch (error) { + this.fail(error, debug, { + 400: 'Invalid vm ID.', + 404: 'Could not find the vm.', + }); + } + } +} diff --git a/src/commands/vm/snapshot/create.ts b/src/commands/vm/snapshot/create.ts new file mode 100644 index 00000000..882018be --- /dev/null +++ b/src/commands/vm/snapshot/create.ts @@ -0,0 +1,98 @@ +import { Flags } from '@oclif/core'; +import inquirer from 'inquirer'; + +import VmCommand from '../../../vm-command.js'; +import { createDebugLogger } from '../../../utils/output.js'; +import { SNAPSHOT_OPERATIONS } from '../../../utils/vm-disk-snapshot.js'; +import { FROZEN_VM_MESSAGE } from '../../../utils/vm.js'; + +export default class VmSnapshotCreate extends VmCommand { + static description = + 'create a snapshot of a vm (the snapshot contains the disk, not the RAM)'; + + static flags = { + ...VmCommand.flags, + vm: Flags.string({ + char: 'v', + description: 'vm name', + }), + name: Flags.string({ + char: 'n', + description: 'snapshot name', + }), + description: Flags.string({ + description: 'snapshot description', + }), + detach: Flags.boolean({ + char: 'd', + description: 'run command in detach mode', + }), + }; + + public async run(): Promise { + const { flags } = await this.parse(VmSnapshotCreate); + const debug = createDebugLogger(flags.debug); + + await this.prepare(flags); + + try { + const vm = await this.selectVm(flags.vm, { + notFound: 'vm does not exist.', + filter: (vm) => vm.state !== 'DELETING', + }); + + if (vm.state === 'FROZEN') { + this.error(FROZEN_VM_MESSAGE); + } + + const name = flags.name ?? (await this.promptName()); + if (!name.trim()) { + this.error('The snapshot name cannot be empty.'); + } + + const description = flags.description?.trim() || undefined; + const after = flags.detach + ? undefined + : await this.getLatestOperationTime(vm); + + await this.got.post(`vm/take-snapshot/${vm._id}`, { + json: { name: name.trim(), description }, + }); + + if (flags.detach) { + this.spinner.succeed( + `The snapshot request has been submitted for vm "${vm.name}". Use "liara vm events" to follow it.`, + ); + return; + } + + await this.followOperation( + vm, + after, + { + doing: `creating the snapshot "${name}"...`, + succeeded: `The snapshot "${name}" has been created.`, + failed: `Failed to create the snapshot "${name}".`, + }, + SNAPSHOT_OPERATIONS.create, + ); + } catch (error) { + this.spinner.stop(); + this.fail(error, debug, { + 400: 'Invalid vm ID or snapshot data.', + 404: 'Could not find the vm.', + }); + } + } + + async promptName(): Promise { + const { name } = (await inquirer.prompt({ + name: 'name', + type: 'input', + message: 'Snapshot name:', + validate: (input) => input.trim().length > 0, + })) as { name: string }; + + return name; + } +} diff --git a/src/commands/vm/snapshot/delete.ts b/src/commands/vm/snapshot/delete.ts new file mode 100644 index 00000000..39db649f --- /dev/null +++ b/src/commands/vm/snapshot/delete.ts @@ -0,0 +1,108 @@ +import { Flags } from '@oclif/core'; + +import VmCommand from '../../../vm-command.js'; +import { IGetVMSnapshotsResponse } from '../../../types/vm.js'; +import { createDebugLogger } from '../../../utils/output.js'; +import { + SNAPSHOT_OPERATIONS, + describeSnapshot, +} from '../../../utils/vm-disk-snapshot.js'; +import { FROZEN_VM_MESSAGE } from '../../../utils/vm.js'; + +export default class VmSnapshotDelete extends VmCommand { + static description = 'delete a snapshot of a vm'; + + static flags = { + ...VmCommand.flags, + vm: Flags.string({ + char: 'v', + description: 'vm name', + }), + snapshot: Flags.string({ + char: 's', + description: 'snapshot name or id', + }), + force: Flags.boolean({ + char: 'f', + description: 'skip the confirmation', + }), + detach: Flags.boolean({ + char: 'd', + description: 'run command in detach mode', + }), + }; + + static aliases = ['vm:snapshot:rm']; + + public async run(): Promise { + const { flags } = await this.parse(VmSnapshotDelete); + const debug = createDebugLogger(flags.debug); + + await this.prepare(flags); + + try { + const vm = await this.selectVm(flags.vm, { + notFound: 'vm does not exist.', + filter: (vm) => vm.state !== 'DELETING', + }); + + if (vm.state === 'FROZEN') { + this.error(FROZEN_VM_MESSAGE); + } + + const snapshots = await this.got( + `vm/snapshot/${vm._id}`, + ).json(); + + if (snapshots.length === 0) { + this.error(`vm "${vm.name}" has no snapshots.`); + } + + const snapshot = await this.selectItem(snapshots, flags.snapshot, { + label: 'snapshot', + describe: describeSnapshot, + }); + + if ( + !flags.force && + !(await this.confirm( + `Are you sure you want to delete the snapshot "${snapshot.name}"?`, + )) + ) { + return; + } + + const after = flags.detach + ? undefined + : await this.getLatestOperationTime(vm); + + await this.got.post(`vm/delete-snapshot/${vm._id}`, { + json: { snapshotID: snapshot._id }, + }); + + if (flags.detach) { + this.spinner.succeed( + `The delete request has been submitted for the snapshot "${snapshot.name}". Use "liara vm events" to follow it.`, + ); + return; + } + + await this.followOperation( + vm, + after, + { + doing: `deleting the snapshot "${snapshot.name}"...`, + succeeded: `The snapshot "${snapshot.name}" has been deleted.`, + failed: `Failed to delete the snapshot "${snapshot.name}".`, + }, + SNAPSHOT_OPERATIONS.delete, + ); + } catch (error) { + this.spinner.stop(); + this.fail(error, debug, { + 400: 'Invalid vm ID or snapshot ID.', + 404: 'Could not find the snapshot.', + }); + } + } +} diff --git a/src/commands/vm/snapshot/list.ts b/src/commands/vm/snapshot/list.ts new file mode 100644 index 00000000..ebcdac32 --- /dev/null +++ b/src/commands/vm/snapshot/list.ts @@ -0,0 +1,67 @@ +import { Flags, ux } from '@oclif/core'; + +import VmCommand from '../../../vm-command.js'; +import { IGetVMSnapshotsResponse } from '../../../types/vm.js'; +import { createDebugLogger } from '../../../utils/output.js'; +import { formatBytes, formatDateTime } from '../../../utils/vm.js'; + +export default class VmSnapshotList extends VmCommand { + static description = 'list the snapshots of a vm'; + + static flags = { + ...VmCommand.flags, + ...ux.table.flags(), + vm: Flags.string({ + char: 'v', + description: 'vm name', + }), + }; + + static aliases = ['vm:snapshot:ls']; + + public async run(): Promise { + const { flags } = await this.parse(VmSnapshotList); + const debug = createDebugLogger(flags.debug); + + await this.prepare(flags); + + try { + const vm = await this.selectVm(flags.vm, { + notFound: 'vm does not exist.', + filter: (vm) => vm.state !== 'DELETING', + }); + + const snapshots = await this.got( + `vm/snapshot/${vm._id}`, + ).json(); + + if (snapshots.length === 0) { + this.log(`vm "${vm.name}" has no snapshots.`); + return; + } + + ux.table( + snapshots.map((snapshot) => ({ + Name: snapshot.name, + Description: snapshot.description || '-', + Size: formatBytes(snapshot.sizeB), + Current: snapshot.isCurrent ? 'yes' : '', + 'Created At': formatDateTime(snapshot.createdAt), + })), + { + Name: {}, + Description: {}, + Size: {}, + Current: {}, + 'Created At': {}, + }, + flags, + ); + } catch (error) { + this.fail(error, debug, { + 400: 'Invalid vm ID.', + 404: 'Could not find the vm.', + }); + } + } +} diff --git a/src/commands/vm/snapshot/revert.ts b/src/commands/vm/snapshot/revert.ts new file mode 100644 index 00000000..9a89d0f2 --- /dev/null +++ b/src/commands/vm/snapshot/revert.ts @@ -0,0 +1,109 @@ +import { Flags } from '@oclif/core'; + +import VmCommand from '../../../vm-command.js'; +import { IGetVMSnapshotsResponse } from '../../../types/vm.js'; +import { createDebugLogger } from '../../../utils/output.js'; +import { + SNAPSHOT_OPERATIONS, + describeSnapshot, +} from '../../../utils/vm-disk-snapshot.js'; +import { FROZEN_VM_MESSAGE } from '../../../utils/vm.js'; + +export default class VmSnapshotRevert extends VmCommand { + static description = + 'revert a vm to one of its snapshots (the current data of the vm is replaced)'; + + static flags = { + ...VmCommand.flags, + vm: Flags.string({ + char: 'v', + description: 'vm name', + }), + snapshot: Flags.string({ + char: 's', + description: 'snapshot name or id', + }), + force: Flags.boolean({ + char: 'f', + description: 'skip the confirmation', + }), + detach: Flags.boolean({ + char: 'd', + description: 'run command in detach mode', + }), + }; + + static aliases = ['vm:snapshot:restore']; + + public async run(): Promise { + const { flags } = await this.parse(VmSnapshotRevert); + const debug = createDebugLogger(flags.debug); + + await this.prepare(flags); + + try { + const vm = await this.selectVm(flags.vm, { + notFound: 'vm does not exist.', + filter: (vm) => vm.state !== 'DELETING', + }); + + if (vm.state === 'FROZEN') { + this.error(FROZEN_VM_MESSAGE); + } + + const snapshots = await this.got( + `vm/snapshot/${vm._id}`, + ).json(); + + if (snapshots.length === 0) { + this.error(`vm "${vm.name}" has no snapshots.`); + } + + const snapshot = await this.selectItem(snapshots, flags.snapshot, { + label: 'snapshot', + describe: describeSnapshot, + }); + + if ( + !flags.force && + !(await this.confirm( + `The current data of "${vm.name}" will be replaced with the snapshot "${snapshot.name}". Continue?`, + )) + ) { + return; + } + + const after = flags.detach + ? undefined + : await this.getLatestOperationTime(vm); + + await this.got.post(`vm/revert-snapshot/${vm._id}`, { + json: { snapshotID: snapshot._id }, + }); + + if (flags.detach) { + this.spinner.succeed( + `The revert request has been submitted for the snapshot "${snapshot.name}". Use "liara vm events" to follow it.`, + ); + return; + } + + await this.followOperation( + vm, + after, + { + doing: `reverting vm "${vm.name}" to the snapshot "${snapshot.name}"...`, + succeeded: `vm "${vm.name}" has been reverted to the snapshot "${snapshot.name}".`, + failed: `Failed to revert vm "${vm.name}" to the snapshot "${snapshot.name}".`, + }, + SNAPSHOT_OPERATIONS.revert, + ); + } catch (error) { + this.spinner.stop(); + this.fail(error, debug, { + 400: 'Invalid vm ID or snapshot ID.', + 404: 'Could not find the snapshot.', + }); + } + } +} From 65746e078bf651879303690fb8438a6ad4932053 Mon Sep 17 00:00:00 2001 From: Amin Ehterami Date: Sat, 14 Nov 2026 04:26:01 +0330 Subject: [PATCH 4/7] feat(vm): add init script commands --- src/commands/vm/script/create.ts | 74 ++++++++++++++++++++++ src/commands/vm/script/delete.ts | 65 ++++++++++++++++++++ src/commands/vm/script/download.ts | 65 ++++++++++++++++++++ src/commands/vm/script/list.ts | 53 ++++++++++++++++ src/commands/vm/script/update.ts | 98 ++++++++++++++++++++++++++++++ 5 files changed, 355 insertions(+) create mode 100644 src/commands/vm/script/create.ts create mode 100644 src/commands/vm/script/delete.ts create mode 100644 src/commands/vm/script/download.ts create mode 100644 src/commands/vm/script/list.ts create mode 100644 src/commands/vm/script/update.ts diff --git a/src/commands/vm/script/create.ts b/src/commands/vm/script/create.ts new file mode 100644 index 00000000..44e21350 --- /dev/null +++ b/src/commands/vm/script/create.ts @@ -0,0 +1,74 @@ +import { Flags } from '@oclif/core'; + +import VmCommand from '../../../vm-command.js'; +import { createDebugLogger } from '../../../utils/output.js'; +import { resolveScriptInput } from '../../../utils/vm-script.js'; +import { INIT_SCRIPT_TYPES } from '../../../utils/vm.js'; + +export default class VmScriptCreate extends VmCommand { + static description = 'create an init script for vms'; + + static flags = { + ...VmCommand.flags, + name: Flags.string({ + char: 'n', + description: 'script name', + }), + description: Flags.string({ + description: 'script description', + }), + type: Flags.string({ + char: 't', + description: + 'script type (defaults to the type of --file, or shell for --content)', + options: INIT_SCRIPT_TYPES, + }), + file: Flags.string({ + char: 'f', + description: 'path of a .sh or .ps1 file to read the script from', + }), + content: Flags.string({ + char: 'c', + description: 'the script itself', + }), + }; + + public async run(): Promise { + const { flags } = await this.parse(VmScriptCreate); + const debug = createDebugLogger(flags.debug); + + await this.prepare(flags); + + try { + let script; + try { + script = await resolveScriptInput(flags); + } catch (error) { + this.error(error.message); + } + + if (script.content === undefined) { + this.error('Please provide the script using --file or --content.'); + } + + const type = script.type || 'shell'; + + await this.got.post('init-scripts', { + json: { + name: flags.name?.trim() || undefined, + description: flags.description?.trim() || undefined, + type, + content: script.content, + }, + }); + + this.log( + `The ${type} script${flags.name ? ` "${flags.name}"` : ''} has been created.`, + ); + } catch (error) { + this.fail(error, debug, { + 400: `The script is not valid.`, + }); + } + } +} diff --git a/src/commands/vm/script/delete.ts b/src/commands/vm/script/delete.ts new file mode 100644 index 00000000..65df6000 --- /dev/null +++ b/src/commands/vm/script/delete.ts @@ -0,0 +1,65 @@ +import { Flags } from '@oclif/core'; + +import VmCommand from '../../../vm-command.js'; +import { IGetVMInitScriptsResponse } from '../../../types/vm.js'; +import { createDebugLogger } from '../../../utils/output.js'; +import { describeScript } from '../../../utils/vm-script.js'; + +export default class VmScriptDelete extends VmCommand { + static description = 'delete an init script'; + + static flags = { + ...VmCommand.flags, + script: Flags.string({ + char: 's', + description: 'script name or id', + }), + force: Flags.boolean({ + char: 'f', + description: 'skip the confirmation', + }), + }; + + static aliases = ['vm:script:rm']; + + public async run(): Promise { + const { flags } = await this.parse(VmScriptDelete); + const debug = createDebugLogger(flags.debug); + + await this.prepare(flags); + + try { + this.spinner.start('Loading...'); + const { initScripts } = + await this.got('init-scripts').json(); + this.spinner.stop(); + + if (initScripts.length === 0) { + this.error('There are no init scripts.'); + } + + const script = await this.selectItem(initScripts, flags.script, { + label: 'script', + describe: describeScript, + }); + + if ( + !flags.force && + !(await this.confirm( + `Are you sure you want to delete the script "${script.name}"? It can no longer be selected when creating a vm.`, + )) + ) { + return; + } + + await this.got.delete(`init-scripts/${script._id}`); + + this.log(`The script "${script.name}" has been deleted.`); + } catch (error) { + this.spinner.stop(); + this.fail(error, debug, { + 404: 'Could not find the script.', + }); + } + } +} diff --git a/src/commands/vm/script/download.ts b/src/commands/vm/script/download.ts new file mode 100644 index 00000000..23edfbf3 --- /dev/null +++ b/src/commands/vm/script/download.ts @@ -0,0 +1,65 @@ +import { Flags } from '@oclif/core'; +import fs from 'fs-extra'; + +import VmCommand from '../../../vm-command.js'; +import { IGetVMInitScriptsResponse } from '../../../types/vm.js'; +import { createDebugLogger } from '../../../utils/output.js'; +import { describeScript } from '../../../utils/vm-script.js'; + +export default class VmScriptDownload extends VmCommand { + static description = 'print an init script, or save it to a file'; + + static flags = { + ...VmCommand.flags, + script: Flags.string({ + char: 's', + description: 'script name or id', + }), + output: Flags.string({ + char: 'o', + description: 'save the script to this file instead of printing it', + }), + }; + + static aliases = ['vm:script:get']; + + public async run(): Promise { + const { flags } = await this.parse(VmScriptDownload); + const debug = createDebugLogger(flags.debug); + + await this.prepare(flags); + + try { + this.spinner.start('Loading...'); + const { initScripts } = + await this.got('init-scripts').json(); + this.spinner.stop(); + + if (initScripts.length === 0) { + this.error('There are no init scripts.'); + } + + const script = await this.selectItem(initScripts, flags.script, { + label: 'script', + describe: describeScript, + }); + + const content = await this.got( + `init-scripts/${script._id}/download`, + ).text(); + + if (flags.output) { + await fs.outputFile(flags.output, content); + this.log(`The script "${script.name}" was saved to ${flags.output}.`); + return; + } + + this.log(content); + } catch (error) { + this.spinner.stop(); + this.fail(error, debug, { + 404: 'Could not find the script.', + }); + } + } +} diff --git a/src/commands/vm/script/list.ts b/src/commands/vm/script/list.ts new file mode 100644 index 00000000..fe478e22 --- /dev/null +++ b/src/commands/vm/script/list.ts @@ -0,0 +1,53 @@ +import { ux } from '@oclif/core'; + +import VmCommand from '../../../vm-command.js'; +import { IGetVMInitScriptsResponse } from '../../../types/vm.js'; +import { createDebugLogger } from '../../../utils/output.js'; +import { formatDateTime } from '../../../utils/vm.js'; + +export default class VmScriptList extends VmCommand { + static description = + 'list the init scripts that can run when a vm is created'; + + static flags = { + ...VmCommand.flags, + ...ux.table.flags(), + }; + + static aliases = ['vm:script:ls']; + + public async run(): Promise { + const { flags } = await this.parse(VmScriptList); + const debug = createDebugLogger(flags.debug); + + await this.prepare(flags); + + try { + this.spinner.start('Loading...'); + const { initScripts } = + await this.got('init-scripts').json(); + this.spinner.stop(); + + if (initScripts.length === 0) { + this.log( + 'There are no init scripts. Create one using "liara vm script create".', + ); + return; + } + + ux.table( + initScripts.map((script) => ({ + Name: script.name, + Type: script.type, + Description: script.description || '-', + 'Created At': formatDateTime(script.createdAt), + })), + { Name: {}, Type: {}, Description: {}, 'Created At': {} }, + flags, + ); + } catch (error) { + this.spinner.stop(); + this.fail(error, debug); + } + } +} diff --git a/src/commands/vm/script/update.ts b/src/commands/vm/script/update.ts new file mode 100644 index 00000000..f3bd1192 --- /dev/null +++ b/src/commands/vm/script/update.ts @@ -0,0 +1,98 @@ +import { Flags } from '@oclif/core'; + +import VmCommand from '../../../vm-command.js'; +import { IGetVMInitScriptsResponse } from '../../../types/vm.js'; +import { createDebugLogger } from '../../../utils/output.js'; +import { + describeScript, + resolveScriptInput, +} from '../../../utils/vm-script.js'; +import { INIT_SCRIPT_TYPES } from '../../../utils/vm.js'; + +export default class VmScriptUpdate extends VmCommand { + static description = 'update an init script'; + + static flags = { + ...VmCommand.flags, + script: Flags.string({ + char: 's', + description: 'script name or id', + }), + name: Flags.string({ + char: 'n', + description: 'new script name', + }), + description: Flags.string({ + description: 'new script description', + }), + type: Flags.string({ + char: 't', + description: 'new script type', + options: INIT_SCRIPT_TYPES, + }), + file: Flags.string({ + char: 'f', + description: 'path of a .sh or .ps1 file to read the new script from', + }), + content: Flags.string({ + char: 'c', + description: 'the new script', + }), + }; + + public async run(): Promise { + const { flags } = await this.parse(VmScriptUpdate); + const debug = createDebugLogger(flags.debug); + + await this.prepare(flags); + + try { + let input; + try { + input = await resolveScriptInput(flags); + } catch (error) { + this.error(error.message); + } + + this.spinner.start('Loading...'); + const { initScripts } = + await this.got('init-scripts').json(); + this.spinner.stop(); + + if (initScripts.length === 0) { + this.error('There are no init scripts.'); + } + + const script = await this.selectItem(initScripts, flags.script, { + label: 'script', + describe: describeScript, + }); + + // The API replaces the whole script, so what is not changed is kept. + let content = input.content; + if (content === undefined) { + content = await this.got(`init-scripts/${script._id}/download`).text(); + } + + await this.got.put(`init-scripts/${script._id}`, { + json: { + name: flags.name?.trim() || script.name, + description: + flags.description === undefined + ? script.description + : flags.description.trim() || undefined, + type: input.type || script.type, + content, + }, + }); + + this.log(`The script "${script.name}" has been updated.`); + } catch (error) { + this.spinner.stop(); + this.fail(error, debug, { + 400: 'The script is not valid.', + 404: 'Could not find the script.', + }); + } + } +} From 0cc40f2a07431f3d48ac4bed1907813c8f844361 Mon Sep 17 00:00:00 2001 From: Amin Ehterami Date: Sat, 14 Nov 2026 04:26:02 +0330 Subject: [PATCH 5/7] feat(vm): add metrics and traffic commands --- src/commands/vm/metrics.ts | 134 +++++++++++++++++++++++++++++++++++++ src/commands/vm/traffic.ts | 99 +++++++++++++++++++++++++++ 2 files changed, 233 insertions(+) create mode 100644 src/commands/vm/metrics.ts create mode 100644 src/commands/vm/traffic.ts diff --git a/src/commands/vm/metrics.ts b/src/commands/vm/metrics.ts new file mode 100644 index 00000000..19a9f676 --- /dev/null +++ b/src/commands/vm/metrics.ts @@ -0,0 +1,134 @@ +import { Flags, ux } from '@oclif/core'; + +import VmCommand from '../../vm-command.js'; +import { + IVMMetricsHistoryResponse, + IVMMetricsSummaryResponse, +} from '../../types/vm.js'; +import { createDebugLogger } from '../../utils/output.js'; +import { + METRIC_RANGES, + VM_METRICS, + calculateSince, + formatDateTime, + formatDiskIO, + formatPercent, + normalizeDiskIOPoints, + normalizeScalarPoints, + normalizeSummary, +} from '../../utils/vm.js'; + +export default class VmMetrics extends VmCommand { + static description = + 'show the resource usage (cpu, memory, disk and disk io) of a vm'; + + static flags = { + ...VmCommand.flags, + ...ux.table.flags(), + vm: Flags.string({ + char: 'v', + description: 'vm name', + }), + metric: Flags.string({ + char: 'm', + description: 'show the history of one metric instead of the summary', + options: [...VM_METRICS], + }), + range: Flags.string({ + char: 'r', + description: 'time range of the history', + options: Object.keys(METRIC_RANGES), + default: '1h', + }), + }; + + static aliases = ['vm:usage']; + + public async run(): Promise { + const { flags } = await this.parse(VmMetrics); + const debug = createDebugLogger(flags.debug); + + await this.prepare(flags); + + try { + const vm = await this.selectVm(flags.vm, { + notFound: 'vm does not exist.', + filter: (vm) => vm.state !== 'DELETING', + }); + + if (!flags.metric) { + const summary = normalizeSummary( + await this.got( + `vm/${vm._id}/metrics/summary`, + ).json(), + ); + + if (!summary) { + this.log(`There are no metrics for vm "${vm.name}" yet.`); + return; + } + + ux.table( + [ + { + CPU: formatPercent(summary.cpu), + Memory: formatPercent(summary.memory), + Disk: formatPercent(summary.disk), + 'Disk Read': formatDiskIO(summary.diskIO.read), + 'Disk Write': formatDiskIO(summary.diskIO.write), + }, + ], + { + CPU: {}, + Memory: {}, + Disk: {}, + 'Disk Read': {}, + 'Disk Write': {}, + }, + flags, + ); + return; + } + + const since = calculateSince(flags.range, vm.createdAt); + const { result } = await this.got( + `vm/${vm._id}/metrics/${flags.metric}`, + { + searchParams: { since }, + }, + ).json(); + + if (!Array.isArray(result) || result.length === 0) { + this.log(`There is no ${flags.metric} data in this time range.`); + return; + } + + if (flags.metric === 'diskIO') { + ux.table( + normalizeDiskIOPoints(result).map((point) => ({ + Time: formatDateTime(point.time * 1000), + Read: formatDiskIO(point.read), + Write: formatDiskIO(point.write), + })), + { Time: {}, Read: {}, Write: {} }, + flags, + ); + return; + } + + ux.table( + normalizeScalarPoints(result).map((point) => ({ + Time: formatDateTime(point.time * 1000), + Usage: formatPercent(point.value), + })), + { Time: {}, Usage: {} }, + flags, + ); + } catch (error) { + this.fail(error, debug, { + 400: 'Invalid vm ID.', + 404: 'Could not find the vm.', + }); + } + } +} diff --git a/src/commands/vm/traffic.ts b/src/commands/vm/traffic.ts new file mode 100644 index 00000000..e8369ce5 --- /dev/null +++ b/src/commands/vm/traffic.ts @@ -0,0 +1,99 @@ +import { Flags, ux } from '@oclif/core'; + +import VmCommand from '../../vm-command.js'; +import { IVMDailyTrafficResponse, IVMTrafficResponse } from '../../types/vm.js'; +import { createDebugLogger } from '../../utils/output.js'; +import { + MAX_DAILY_TRAFFIC_DAYS, + TRAFFIC_RANGES, + aggregateTraffic, + formatBytes, + getDailyTrafficStart, + getTrafficSince, + normalizeDailyTraffic, +} from '../../utils/vm.js'; + +export default class VmTraffic extends VmCommand { + static description = 'show the outgoing traffic of a vm'; + + static flags = { + ...VmCommand.flags, + ...ux.table.flags(), + vm: Flags.string({ + char: 'v', + description: 'vm name', + }), + range: Flags.string({ + char: 'r', + description: 'time range of the traffic by destination', + options: Object.keys(TRAFFIC_RANGES), + default: '1h', + }), + daily: Flags.boolean({ + description: 'show the traffic and its cost for each of the last 30 days', + }), + }; + + static aliases = ['vm:bandwidth']; + + public async run(): Promise { + const { flags } = await this.parse(VmTraffic); + const debug = createDebugLogger(flags.debug); + + await this.prepare(flags); + + try { + const vm = await this.selectVm(flags.vm, { + notFound: 'vm does not exist.', + filter: (vm) => vm.state !== 'DELETING', + }); + + if (flags.daily) { + const start = getDailyTrafficStart( + MAX_DAILY_TRAFFIC_DAYS, + vm.createdAt, + ); + const { result } = await this.got(`vm/traffic-daily/${vm._id}`, { + searchParams: { startTimeUnix: start.unix() }, + }).json(); + + ux.table( + normalizeDailyTraffic(result?.daily || [], start).map((day) => ({ + Day: day.day, + Traffic: formatBytes(day.bytes), + 'Cost (Tomans)': Math.trunc(day.price).toLocaleString(), + })), + { Day: {}, Traffic: {}, 'Cost (Tomans)': {} }, + flags, + ); + return; + } + + const since = getTrafficSince(flags.range); + const { result } = await this.got(`vm/traffic-volume/${vm._id}`, { + searchParams: { startTimeUnix: since }, + }).json(); + + const destinations = aggregateTraffic(result); + + if (destinations.length === 0) { + this.log('There is no traffic in this time range.'); + return; + } + + ux.table( + destinations.map((destination) => ({ + Destination: destination.ip, + Traffic: formatBytes(destination.bytes), + })), + { Destination: {}, Traffic: {} }, + flags, + ); + } catch (error) { + this.fail(error, debug, { + 400: 'Invalid vm ID.', + 404: 'Could not find the vm.', + }); + } + } +} From efecacc3103d2b1b8f16fc2bd9a819310a67be04 Mon Sep 17 00:00:00 2001 From: Amin Ehterami Date: Sat, 14 Nov 2026 04:26:03 +0330 Subject: [PATCH 6/7] feat(vm): add create flags, info details and frozen vm checks --- src/commands/vm/create.ts | 278 ++++- src/commands/vm/info.ts | 7 + src/commands/vm/list.ts | 6 + src/commands/vm/restart.ts | 4 + src/commands/vm/start.ts | 4 + src/commands/vm/stop.ts | 5 + test/vm/commands.unit.test.ts | 1934 +++++++++++++++++++++++++++++++++ test/vm/vm.unit.test.ts | 2 + 8 files changed, 2198 insertions(+), 42 deletions(-) create mode 100644 test/vm/commands.unit.test.ts diff --git a/src/commands/vm/create.ts b/src/commands/vm/create.ts index 0b348e23..1d49e8ad 100644 --- a/src/commands/vm/create.ts +++ b/src/commands/vm/create.ts @@ -1,4 +1,4 @@ -import ora, { Ora } from 'ora'; +import ora from 'ora'; import inquirer from 'inquirer'; import { Flags } from '@oclif/core'; @@ -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 = { @@ -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', @@ -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, @@ -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 { + if (!flag && !interactive) { + return undefined; + } + + const type = getInitScriptTypeForOS(osName); + const { initScripts } = + await this.got('init-scripts').json(); + 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 { + 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 { + 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 { @@ -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; @@ -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); } diff --git a/src/commands/vm/info.ts b/src/commands/vm/info.ts index 020c7295..6bc71882 100644 --- a/src/commands/vm/info.ts +++ b/src/commands/vm/info.ts @@ -5,6 +5,7 @@ import ora from 'ora'; import { IGetVMResponse, IVMs } from '../../types/vm.js'; import { promptVMs } from '../../utils/prompt-vms.js'; import { createDebugLogger } from '../../utils/output.js'; +import { getRootUsername } from '../../utils/vm.js'; export default class Vminfo extends Command { static description = 'show vm information'; static aliases = ['vm:show', 'vm:inspect']; @@ -42,7 +43,10 @@ export default class Vminfo extends Command { OS: vm.OS, Power: vm.power, Hostname: vm.config.hostname, + Username: getRootUsername(vm.OS), Password: vm.config.rootPassword, + 'SSH Port': vm.config.sshPort || 22, + 'SSH Keys': (vm.config.SSHKeys || []).length, IPs: vm.IPs.map((ip) => ip.address).join('\n'), CPU: vm.planDetails.CPU.amount + 'Cores', RAM: vm.planDetails.RAM.amount + 'GB', @@ -55,7 +59,10 @@ export default class Vminfo extends Command { OS: {}, Power: {}, Hostname: {}, + Username: {}, Password: {}, + 'SSH Port': {}, + 'SSH Keys': {}, IPs: {}, CPU: {}, RAM: {}, diff --git a/src/commands/vm/list.ts b/src/commands/vm/list.ts index 2fed2601..2d807eae 100644 --- a/src/commands/vm/list.ts +++ b/src/commands/vm/list.ts @@ -54,5 +54,11 @@ export default class VmList extends Command { }, flags, ); + + if (vms.some((vm) => vm.state === 'FROZEN')) { + this.log( + '\nSome vms are frozen. Use "liara vm unfreeze" to activate them.', + ); + } } } diff --git a/src/commands/vm/restart.ts b/src/commands/vm/restart.ts index 5c492923..4d760752 100644 --- a/src/commands/vm/restart.ts +++ b/src/commands/vm/restart.ts @@ -5,6 +5,7 @@ import ora from 'ora'; import { createAction } from '../../utils/create-vm-actions.js'; import { promptVMs } from '../../utils/prompt-vms.js'; import { createDebugLogger } from '../../utils/output.js'; +import { FROZEN_VM_MESSAGE } from '../../utils/vm.js'; export default class VmRestart extends Command { static flags = { @@ -46,6 +47,9 @@ export default class VmRestart extends Command { this.error('vm is not running or does not exists.'); })() : await promptVMs(vms); + if (vm.state === 'FROZEN') { + this.error(FROZEN_VM_MESSAGE); + } await createAction(vm._id, 'reboot', this.got); if (flags.detach) { this.spinner.succeed( diff --git a/src/commands/vm/start.ts b/src/commands/vm/start.ts index f6cb2b85..4fa66b0e 100644 --- a/src/commands/vm/start.ts +++ b/src/commands/vm/start.ts @@ -5,6 +5,7 @@ import ora from 'ora'; import { createAction } from '../../utils/create-vm-actions.js'; import { promptVMs } from '../../utils/prompt-vms.js'; import { createDebugLogger } from '../../utils/output.js'; +import { FROZEN_VM_MESSAGE } from '../../utils/vm.js'; export default class VmStart extends Command { static flags = { @@ -46,6 +47,9 @@ export default class VmStart extends Command { throw new Error('vm is not ruuning or does not exists.'); })() : await promptVMs(vms); + if (vm.state === 'FROZEN') { + this.error(FROZEN_VM_MESSAGE); + } await createAction(vm._id, 'start', this.got); if (flags.detach) { this.spinner.succeed( diff --git a/src/commands/vm/stop.ts b/src/commands/vm/stop.ts index 1b04aa03..7ee52855 100644 --- a/src/commands/vm/stop.ts +++ b/src/commands/vm/stop.ts @@ -3,6 +3,7 @@ import Command, { IConfig } from '../../base.js'; import { IGetVMResponse, IVMs } from '../../types/vm.js'; import { IAAS_API_URL } from '../../constants.js'; import { createDebugLogger } from '../../utils/output.js'; +import { FROZEN_VM_MESSAGE } from '../../utils/vm.js'; import ora from 'ora'; import { promptVMs } from '../../utils/prompt-vms.js'; import { createAction } from '../../utils/create-vm-actions.js'; @@ -44,6 +45,10 @@ export default class VmStop extends Command { try { const vm: IVMs = await this.getVm(flags.vm); + if (vm.state === 'FROZEN') { + this.error(FROZEN_VM_MESSAGE); + } + if (flags.force) { await createAction(vm._id, 'stop', this.got); } else { diff --git a/test/vm/commands.unit.test.ts b/test/vm/commands.unit.test.ts new file mode 100644 index 00000000..317b13ca --- /dev/null +++ b/test/vm/commands.unit.test.ts @@ -0,0 +1,1934 @@ +import fs from 'fs-extra'; +import os from 'node:os'; +import path from 'node:path'; +import { runCommand } from '@oclif/test'; +import nock from 'nock'; +import sinon from 'sinon'; +import inquirer from 'inquirer'; +import { expect } from 'chai'; +import { stubGlobalConfig } from '../helpers/stubs.ts'; +import VmCommand from '../../src/vm-command.ts'; +import VmCreate from '../../src/commands/vm/create.ts'; + +const vm = (id: string, name: string, extra: Record = {}) => ({ + _id: id, + name, + power: 'POWERED_OFF', + state: 'CREATED', + plan: 'pro-g2', + OS: 'ubuntu-22.04', + createdAt: '2026-01-01T00:00:00.000Z', + ...extra, +}); + +const vms = { + vms: [ + vm('vm-1', 'my-vm'), + vm('vm-2', 'win-vm', { OS: 'windows-2022' }), + vm('vm-3', 'frozen-vm', { state: 'FROZEN' }), + ], +}; + +const details = (ips: string[], extra: Record = {}) => ({ + ...vm('vm-1', 'my-vm'), + config: { SSHKeys: ['k1', 'k2'], rootPassword: 'pw', hostname: 'host' }, + IPs: ips.map((address) => ({ address, version: '4' })), + planDetails: {}, + ...extra, +}); + +describe('vm commands (extended)', function () { + const api = nock('https://iaas-api.liara.ir'); + const team = { teamID: '' }; + + const expectVms = () => api.get('/vm').query(team).reply(200, vms); + const get = (url: string, query: Record = {}) => + api.get(url).query({ ...team, ...query }); + const post = (url: string, body?: any) => api.post(url, body).query(team); + + beforeEach(() => { + nock.disableNetConnect(); + stubGlobalConfig(); + // Polling must not make the tests wait. + sinon.stub(VmCommand.prototype, 'sleep').resolves(); + }); + + afterEach(() => { + try { + api.done(); + } finally { + nock.cleanAll(); + nock.enableNetConnect(); + sinon.restore(); + } + }); + + describe('vm:resize', () => { + const plans = { + plans: { + free: { + RAM: { amount: 1 }, + CPU: { amount: 1 }, + volume: 1, + monthlyPrice: 0, + }, + 'pro-g2': { + RAM: { amount: 4 }, + CPU: { amount: 2 }, + volume: 40, + monthlyPrice: 100, + }, + 'standard-base-g2': { + RAM: { amount: 1 }, + CPU: { amount: 1 }, + volume: 10, + monthlyPrice: 10, + }, + 'plus-g2': { + RAM: { amount: 8 }, + CPU: { amount: 4 }, + volume: 80, + monthlyPrice: 200, + }, + }, + }; + const resize = (plan = 'plus-g2') => + api.patch('/vm/resize/vm-1', { plan }).query(team); + + it('changes the plan', async () => { + expectVms(); + get('/plans').reply(200, plans); + resize().reply(200); + + const { stdout, error } = await runCommand([ + 'vm:resize', + '--vm', + 'my-vm', + '--plan', + 'plus-g2', + ]); + + expect(error).to.equal(undefined); + expect(stdout).to.include('The plan of vm "my-vm" changed to "plus-g2".'); + }); + + it('lets you pick the plan', async () => { + expectVms(); + get('/plans').reply(200, plans); + resize().reply(200); + const prompt = sinon + .stub(inquirer, 'prompt') + .resolves({ plan: 'plus-g2' }); + + const { error } = await runCommand(['vm:resize', '--vm', 'my-vm']); + + expect(error).to.equal(undefined); + const { choices } = prompt.firstCall.args[0] as any; + expect(choices.map((c: any) => c.value)).to.deep.equal([ + 'pro-g2', + 'standard-base-g2', + 'plus-g2', + ]); + expect(choices[0].name).to.include('(current)'); + }); + + it('rejects a plan that does not exist', async () => { + expectVms(); + get('/plans').reply(200, plans); + + const { error } = await runCommand([ + 'vm:resize', + '--vm', + 'my-vm', + '--plan', + 'nope', + ]); + + expect(error?.message).to.include('The plan "nope" is not available'); + }); + + it('rejects a plan that is disabled for windows', async () => { + expectVms(); + get('/plans').reply(200, plans); + + const { error } = await runCommand([ + 'vm:resize', + '--vm', + 'win-vm', + '--plan', + 'standard-base-g2', + ]); + + expect(error?.message).to.include('is not available'); + }); + + it('rejects the current plan', async () => { + expectVms(); + get('/plans').reply(200, plans); + + const { error } = await runCommand([ + 'vm:resize', + '--vm', + 'my-vm', + '--plan', + 'pro-g2', + ]); + + expect(error?.message).to.equal( + 'The vm is already on the plan "pro-g2".', + ); + }); + + it('refuses a frozen vm', async () => { + expectVms(); + + const { error } = await runCommand([ + 'vm:resize', + '--vm', + 'frozen-vm', + '--plan', + 'plus-g2', + ]); + + expect(error?.message).to.include('The vm is frozen'); + }); + + for (const [status, message] of [ + [409, 'Please power off the vm first'], + [410, 'The plan of a free vm cannot be changed.'], + [428, 'The disk usage of the vm is more than the new plan allows'], + [404, 'Could not find the vm.'], + ] as const) { + it(`explains a ${status} response`, async () => { + expectVms(); + get('/plans').reply(200, plans); + resize().reply(status); + + const { error } = await runCommand([ + 'vm:resize', + '--vm', + 'my-vm', + '--plan', + 'plus-g2', + ]); + + expect(error?.message).to.include(message); + }); + } + + it('explains a missing team permission', async () => { + expectVms(); + get('/plans').reply(200, plans); + resize().reply(403, { data: { code: 'no_permission' } }); + + const { error } = await runCommand([ + 'vm:resize', + '--vm', + 'my-vm', + '--plan', + 'plus-g2', + ]); + + expect(error?.message).to.include("don't have permission"); + }); + }); + + describe('vm:reset-password', () => { + const reset = () => post('/vm/reset-password/vm-1'); + + it('prints the new password', async () => { + expectVms(); + reset().reply(200, { password: 'new-secret' }); + + const { stdout, error } = await runCommand([ + 'vm:reset-password', + '--vm', + 'my-vm', + '--force', + ]); + + expect(error).to.equal(undefined); + expect(stdout).to.include('The root password of vm "my-vm" was reset.'); + expect(stdout).to.include('New password: new-secret'); + }); + + it('calls the user Administrator on windows', async () => { + expectVms(); + post('/vm/reset-password/vm-2').reply(200, { password: 'x' }); + + const { stdout } = await runCommand([ + 'vm:reset-password', + '--vm', + 'win-vm', + '--force', + ]); + + expect(stdout).to.include('The Administrator password'); + }); + + it('does nothing without confirmation', async () => { + sinon.stub(VmCommand.prototype, 'confirm').resolves(false); + expectVms(); + + const { stdout, error } = await runCommand([ + 'vm:reset-password', + '--vm', + 'my-vm', + ]); + + expect(error).to.equal(undefined); + expect(stdout).to.equal(''); + }); + + it('asks to power the vm off first', async () => { + expectVms(); + reset().reply(409); + + const { error } = await runCommand([ + 'vm:reset-password', + '--vm', + 'my-vm', + '--force', + ]); + + expect(error?.message).to.include('Please power off the vm first'); + }); + }); + + describe('vm:unfreeze', () => { + it('unfreezes the vm', async () => { + expectVms(); + post('/vm/unfreeze/vm-3').reply(200); + + const { stdout, error } = await runCommand([ + 'vm:unfreeze', + '--vm', + 'frozen-vm', + ]); + + expect(error).to.equal(undefined); + expect(stdout).to.include('vm "frozen-vm" is being activated.'); + }); + + it('only works on frozen vms', async () => { + expectVms(); + + const { error } = await runCommand(['vm:unfreeze', '--vm', 'my-vm']); + + expect(error?.message).to.equal('No frozen vms found.'); + }); + + it('explains when the credit is not enough', async () => { + expectVms(); + post('/vm/unfreeze/vm-3').reply(402); + + const { error } = await runCommand(['vm:unfreeze', '--vm', 'frozen-vm']); + + expect(error?.message).to.include('Your credit is not enough'); + }); + }); + + describe('vm:reset-network', () => { + const operations = (state: string, createdAt: string) => + get('/vm/operation/vm-1').reply(200, { + operations: [{ name: 'RESET_NETWORK', state, createdAt }], + }); + + it('resets the network in detach mode', async () => { + expectVms(); + post('/vm/reset-network/vm-1').reply(200); + + const { stderr, error } = await runCommand([ + 'vm:reset-network', + '--vm', + 'my-vm', + '--force', + '--detach', + ]); + + expect(error).to.equal(undefined); + expect(stderr).to.include( + 'Network reset request submitted for vm "my-vm"', + ); + }); + + it('waits for the operation to finish', async () => { + expectVms(); + operations('SUCCEEDED', '2026-01-01T00:00:00.000Z'); + post('/vm/reset-network/vm-1').reply(200); + operations('DOING', '2026-02-01T00:00:00.000Z'); + operations('SUCCEEDED', '2026-02-01T00:00:00.000Z'); + + const { stderr, error } = await runCommand([ + 'vm:reset-network', + '--vm', + 'my-vm', + '--force', + ]); + + expect(error).to.equal(undefined); + expect(stderr).to.include('The network of vm "my-vm" has been reset.'); + }); + + it('fails when the operation fails', async () => { + expectVms(); + get('/vm/operation/vm-1').reply(200, { operations: [] }); + post('/vm/reset-network/vm-1').reply(200); + operations('FAILED', '2026-02-01T00:00:00.000Z'); + + const { stderr, error } = await runCommand([ + 'vm:reset-network', + '--vm', + 'my-vm', + '--force', + ]); + + expect(stderr).to.include('Failed to reset the network of vm "my-vm".'); + expect(error).to.not.equal(undefined); + }); + + it('is not supported on windows', async () => { + expectVms(); + + const { error } = await runCommand([ + 'vm:reset-network', + '--vm', + 'win-vm', + '--force', + ]); + + expect(error?.message).to.include('not supported'); + }); + + it('asks to power the vm off first', async () => { + expectVms(); + get('/vm/operation/vm-1').reply(200, { operations: [] }); + post('/vm/reset-network/vm-1').reply(409); + + const { error } = await runCommand([ + 'vm:reset-network', + '--vm', + 'my-vm', + '--force', + ]); + + expect(error?.message).to.include('Please power off the vm first'); + }); + }); + + describe('vm:ip:add', () => { + it('adds an ip and waits for it', async () => { + expectVms(); + get('/vm/vm-1').reply(200, details(['1.1.1.1'])); + post('/vm/extra-ip/vm-1').reply(200); + get('/vm/vm-1').reply(200, details(['1.1.1.1'])); + get('/vm/vm-1').reply(200, details(['1.1.1.1', '2.2.2.2'])); + + const { stderr, stdout, error } = await runCommand([ + 'vm:ip:add', + '--vm', + 'my-vm', + '--force', + ]); + + expect(error).to.equal(undefined); + expect(stderr).to.include( + 'The IP 2.2.2.2 has been assigned to vm "my-vm".', + ); + expect(stdout).to.include('liara vm reset-network'); + }); + + it('shows the price of the plan in the confirmation', async () => { + const confirm = sinon + .stub(VmCommand.prototype, 'confirm') + .resolves(false); + expectVms(); + get('/vm/vm-1').reply( + 200, + details(['1.1.1.1'], { + planDetails: { + IPv4MonthlyPrice: { 1: 5000 }, + IPv4HourlyPrice: { 1: 7 }, + }, + }), + ); + + await runCommand(['vm:ip:add', '--vm', 'my-vm']); + + expect(confirm.firstCall.args[0]).to.include( + '7 Tomans/Hour (5,000 Tomans/Month)', + ); + }); + + it('falls back to the default price', async () => { + const confirm = sinon + .stub(VmCommand.prototype, 'confirm') + .resolves(false); + expectVms(); + get('/vm/vm-1').reply(200, details(['1.1.1.1'])); + + await runCommand(['vm:ip:add', '--vm', 'my-vm']); + + expect(confirm.firstCall.args[0]).to.include( + '277 Tomans/Hour (200,000 Tomans/Month)', + ); + }); + + it('submits the request in detach mode', async () => { + expectVms(); + get('/vm/vm-1').reply(200, details(['1.1.1.1'])); + post('/vm/extra-ip/vm-1').reply(200); + + const { stderr } = await runCommand([ + 'vm:ip:add', + '--vm', + 'my-vm', + '--force', + '--detach', + ]); + + expect(stderr).to.include('The request has been submitted.'); + }); + + for (const [status, message] of [ + [403, 'maximum number of IPs'], + [429, 'still in progress'], + [503, 'no assignable IP'], + ] as const) { + it(`explains a ${status} response`, async () => { + expectVms(); + get('/vm/vm-1').reply(200, details(['1.1.1.1'])); + post('/vm/extra-ip/vm-1').reply(status); + + const { error } = await runCommand([ + 'vm:ip:add', + '--vm', + 'my-vm', + '--force', + ]); + + expect(error?.message).to.include(message); + }); + } + }); + + describe('vm:ip:remove', () => { + it('removes the extra ip and waits for it', async () => { + expectVms(); + get('/vm/vm-1').reply(200, details(['1.1.1.1', '2.2.2.2'])); + api.delete('/vm/extra-ip/vm-1').query(team).reply(200); + get('/vm/vm-1').reply(200, details(['1.1.1.1'])); + + const { stderr, error } = await runCommand([ + 'vm:ip:remove', + '--vm', + 'my-vm', + '--force', + ]); + + expect(error).to.equal(undefined); + expect(stderr).to.include( + 'The IP 2.2.2.2 has been removed from vm "my-vm".', + ); + }); + + it('fails when the vm has no extra ip', async () => { + expectVms(); + get('/vm/vm-1').reply(200, details(['1.1.1.1'])); + + const { error } = await runCommand([ + 'vm:ip:remove', + '--vm', + 'my-vm', + '--force', + ]); + + expect(error?.message).to.equal('This vm has no extra IP.'); + }); + + it('does nothing without confirmation', async () => { + sinon.stub(VmCommand.prototype, 'confirm').resolves(false); + expectVms(); + get('/vm/vm-1').reply(200, details(['1.1.1.1', '2.2.2.2'])); + + const { error } = await runCommand(['vm:ip:remove', '--vm', 'my-vm']); + + expect(error).to.equal(undefined); + }); + }); + + describe('vm:events', () => { + it('lists the newest event first', async () => { + expectVms(); + get('/vm/operation/vm-1').reply(200, { + operations: [ + { + name: 'OLD_OP', + state: 'SUCCEEDED', + createdAt: '2026-01-01T00:00:00.000Z', + }, + { + name: 'NEW_OP', + state: 'DOING', + createdAt: '2026-02-01T00:00:00.000Z', + }, + ], + }); + + const { stdout, error } = await runCommand([ + 'vm:events', + '--vm', + 'my-vm', + ]); + + expect(error).to.equal(undefined); + expect(stdout.indexOf('NEW_OP')).to.be.greaterThan(-1); + expect(stdout.indexOf('NEW_OP')).to.be.lessThan(stdout.indexOf('OLD_OP')); + }); + + it('says when there are no events', async () => { + expectVms(); + get('/vm/operation/vm-1').reply(200, { operations: [] }); + + const { stdout } = await runCommand(['vm:events', '--vm', 'my-vm']); + + expect(stdout).to.include('There are no events for vm "my-vm".'); + }); + }); + + describe('vm:plans and vm:os', () => { + it('lists the plans without the free ones', async () => { + get('/plans').reply(200, { + plans: { + free: { + RAM: { amount: 1 }, + CPU: { amount: 1 }, + volume: 1, + monthlyPrice: 0, + }, + 'pro-g2': { + RAM: { amount: 4 }, + CPU: { amount: 2 }, + volume: 40, + monthlyPrice: 1234, + }, + }, + }); + + const { stdout, error } = await runCommand(['vm:plans']); + + expect(error).to.equal(undefined); + expect(stdout).to.include('pro-g2'); + expect(stdout).to.include((1234).toLocaleString()); + expect(stdout).to.not.match(/^\s*free\s/m); + }); + + it('lists the operating systems and the one-click apps', async () => { + get('/oss').reply(200, { + ubuntu: ['20.04', '22.04'], + 'one-click-apps': { gitlabce: ['16'] }, + }); + + const { stdout, error } = await runCommand(['vm:os']); + + expect(error).to.equal(undefined); + expect(stdout).to.match(/ubuntu\s+OS\s+20\.04, 22\.04/); + expect(stdout).to.match(/gitlabce\s+App\s+16/); + }); + }); + + describe('vm:disk', () => { + const disks = { + disks: [ + { + _id: 'd1', + name: 'data', + size: 10, + createdAt: '2026-01-01T00:00:00.000Z', + }, + { + _id: 'd2', + name: 'logs', + size: 20, + createdAt: '2026-01-01T00:00:00.000Z', + }, + ], + }; + + it('lists the disks', async () => { + expectVms(); + get('/vm/disk/vm-1').reply(200, disks); + + const { stdout, error } = await runCommand([ + 'vm:disk:list', + '--vm', + 'my-vm', + ]); + + expect(error).to.equal(undefined); + expect(stdout).to.match(/data\s+10/); + expect(stdout).to.match(/logs\s+20/); + }); + + it('says when the vm has no disks', async () => { + expectVms(); + get('/vm/disk/vm-1').reply(200, { disks: [] }); + + const { stdout } = await runCommand(['vm:disk:list', '--vm', 'my-vm']); + + expect(stdout).to.include('has no extra disks'); + }); + + it('creates a disk', async () => { + expectVms(); + post('/vm/disk/vm-1', { size: 5 }).reply(200); + + const { stdout, error } = await runCommand([ + 'vm:disk:create', + '--vm', + 'my-vm', + '--size', + '5', + ]); + + expect(error).to.equal(undefined); + expect(stdout).to.include('A 5 GB disk was created for vm "my-vm".'); + }); + + it('does not create a disk of size zero', async () => { + const { error } = await runCommand([ + 'vm:disk:create', + '--vm', + 'my-vm', + '--size', + '0', + ]); + + expect(error).to.not.equal(undefined); + }); + + it('explains when there is not enough space', async () => { + expectVms(); + post('/vm/disk/vm-1', { size: 500 }).reply(428); + + const { error } = await runCommand([ + 'vm:disk:create', + '--vm', + 'my-vm', + '--size', + '500', + ]); + + expect(error?.message).to.include('not enough space'); + }); + + it('extends a disk found by name', async () => { + expectVms(); + get('/vm/disk/vm-1').reply(200, disks); + post('/vm/disk/vm-1/d1', { newSize: 30 }).reply(200); + + const { stdout, error } = await runCommand([ + 'vm:disk:extend', + '--vm', + 'my-vm', + '--disk', + 'data', + '--size', + '30', + ]); + + expect(error).to.equal(undefined); + expect(stdout).to.include( + 'The size of disk "data" is being increased to 30 GB.', + ); + }); + + it('extends a disk found by id', async () => { + expectVms(); + get('/vm/disk/vm-1').reply(200, disks); + post('/vm/disk/vm-1/d2', { newSize: 30 }).reply(200); + + const { error } = await runCommand([ + 'vm:disk:extend', + '--vm', + 'my-vm', + '--disk', + 'd2', + '--size', + '30', + ]); + + expect(error).to.equal(undefined); + }); + + it('lets you pick the disk', async () => { + expectVms(); + get('/vm/disk/vm-1').reply(200, disks); + post('/vm/disk/vm-1/d2', { newSize: 30 }).reply(200); + sinon.stub(inquirer, 'prompt').resolves({ selected: 'd2' }); + + const { error } = await runCommand([ + 'vm:disk:extend', + '--vm', + 'my-vm', + '--size', + '30', + ]); + + expect(error).to.equal(undefined); + }); + + it('only accepts a bigger size', async () => { + expectVms(); + get('/vm/disk/vm-1').reply(200, disks); + + const { error } = await runCommand([ + 'vm:disk:extend', + '--vm', + 'my-vm', + '--disk', + 'data', + '--size', + '10', + ]); + + expect(error?.message).to.include( + 'must be more than the current size of the disk (10 GB)', + ); + }); + + it('fails for an unknown disk', async () => { + expectVms(); + get('/vm/disk/vm-1').reply(200, disks); + + const { error } = await runCommand([ + 'vm:disk:extend', + '--vm', + 'my-vm', + '--disk', + 'nope', + '--size', + '30', + ]); + + expect(error?.message).to.equal('The disk "nope" does not exist.'); + }); + + it('fails when two disks share a name', async () => { + expectVms(); + get('/vm/disk/vm-1').reply(200, { + disks: [disks.disks[0], { ...disks.disks[1], name: 'data' }], + }); + + const { error } = await runCommand([ + 'vm:disk:extend', + '--vm', + 'my-vm', + '--disk', + 'data', + '--size', + '30', + ]); + + expect(error?.message).to.include('More than one disk is named "data"'); + }); + + it('asks to power the vm off first', async () => { + expectVms(); + get('/vm/disk/vm-1').reply(200, disks); + post('/vm/disk/vm-1/d1', { newSize: 30 }).reply(409); + + const { error } = await runCommand([ + 'vm:disk:extend', + '--vm', + 'my-vm', + '--disk', + 'data', + '--size', + '30', + ]); + + expect(error?.message).to.include('Please power off the vm first'); + }); + }); + + describe('vm:snapshot', () => { + const snapshots = [ + { + _id: 's1', + name: 'before-upgrade', + description: 'safe point', + sizeB: 1048576, + createdAt: '2026-01-01T00:00:00.000Z', + isCurrent: true, + }, + { + _id: 's2', + name: 'old', + sizeB: 0, + createdAt: '2026-01-01T00:00:00.000Z', + }, + ]; + const op = (name: string, state: string, createdAt: string) => ({ + name, + state, + createdAt, + }); + + it('lists the snapshots', async () => { + expectVms(); + get('/vm/snapshot/vm-1').reply(200, snapshots); + + const { stdout, error } = await runCommand([ + 'vm:snapshot:list', + '--vm', + 'my-vm', + ]); + + expect(error).to.equal(undefined); + expect(stdout).to.match(/before-upgrade\s+safe point\s+1 MB\s+yes/); + expect(stdout).to.match(/old\s+-/); + }); + + it('says when there are no snapshots', async () => { + expectVms(); + get('/vm/snapshot/vm-1').reply(200, []); + + const { stdout } = await runCommand([ + 'vm:snapshot:list', + '--vm', + 'my-vm', + ]); + + expect(stdout).to.include('has no snapshots'); + }); + + it('creates a snapshot in detach mode', async () => { + expectVms(); + post('/vm/take-snapshot/vm-1', { + name: 'snap', + description: 'why', + }).reply(200); + + const { stderr, error } = await runCommand([ + 'vm:snapshot:create', + '--vm', + 'my-vm', + '--name', + 'snap', + '--description', + 'why', + '--detach', + ]); + + expect(error).to.equal(undefined); + expect(stderr).to.include( + 'The snapshot request has been submitted for vm "my-vm".', + ); + }); + + it('waits for the snapshot operation, ignoring other operations', async () => { + expectVms(); + get('/vm/operation/vm-1').reply(200, { operations: [] }); + post('/vm/take-snapshot/vm-1', { name: 'snap' }).reply(200); + get('/vm/operation/vm-1').reply(200, { + operations: [op('REBOOT', 'SUCCEEDED', '2026-02-01T00:00:00.000Z')], + }); + get('/vm/operation/vm-1').reply(200, { + operations: [ + op('REBOOT', 'SUCCEEDED', '2026-02-01T00:00:00.000Z'), + op('CREATE_VM_SNAPSHOT', 'SUCCEEDED', '2026-02-01T00:00:01.000Z'), + ], + }); + + const { stderr, error } = await runCommand([ + 'vm:snapshot:create', + '--vm', + 'my-vm', + '--name', + 'snap', + ]); + + expect(error).to.equal(undefined); + expect(stderr).to.include('The snapshot "snap" has been created.'); + }); + + it('asks for the name when it is not given', async () => { + sinon.stub(inquirer, 'prompt').resolves({ name: 'asked' }); + expectVms(); + post('/vm/take-snapshot/vm-1', { name: 'asked' }).reply(200); + + const { error } = await runCommand([ + 'vm:snapshot:create', + '--vm', + 'my-vm', + '--detach', + ]); + + expect(error).to.equal(undefined); + }); + + it('refuses an empty name', async () => { + expectVms(); + + const { error } = await runCommand([ + 'vm:snapshot:create', + '--vm', + 'my-vm', + '--name=" "', + '--detach', + ]); + + expect(error?.message).to.equal('The snapshot name cannot be empty.'); + }); + + it('reverts a snapshot found by name', async () => { + expectVms(); + get('/vm/snapshot/vm-1').reply(200, snapshots); + post('/vm/revert-snapshot/vm-1', { snapshotID: 's1' }).reply(200); + + const { stderr, error } = await runCommand([ + 'vm:snapshot:revert', + '--vm', + 'my-vm', + '--snapshot', + 'before-upgrade', + '--force', + '--detach', + ]); + + expect(error).to.equal(undefined); + expect(stderr).to.include( + 'The revert request has been submitted for the snapshot "before-upgrade".', + ); + }); + + it('does not revert without confirmation', async () => { + sinon.stub(VmCommand.prototype, 'confirm').resolves(false); + expectVms(); + get('/vm/snapshot/vm-1').reply(200, snapshots); + + const { error } = await runCommand([ + 'vm:snapshot:revert', + '--vm', + 'my-vm', + '--snapshot', + 's1', + ]); + + expect(error).to.equal(undefined); + }); + + it('waits for a revert to finish', async () => { + expectVms(); + get('/vm/snapshot/vm-1').reply(200, snapshots); + get('/vm/operation/vm-1').reply(200, { operations: [] }); + post('/vm/revert-snapshot/vm-1', { snapshotID: 's2' }).reply(200); + get('/vm/operation/vm-1').reply(200, { + operations: [ + op('REVERT_VM_SNAPSHOT', 'FAILED', '2026-02-01T00:00:00.000Z'), + ], + }); + + const { stderr, error } = await runCommand([ + 'vm:snapshot:revert', + '--vm', + 'my-vm', + '--snapshot', + 'old', + '--force', + ]); + + expect(stderr).to.include( + 'Failed to revert vm "my-vm" to the snapshot "old".', + ); + expect(error).to.not.equal(undefined); + }); + + it('deletes a snapshot', async () => { + expectVms(); + get('/vm/snapshot/vm-1').reply(200, snapshots); + post('/vm/delete-snapshot/vm-1', { snapshotID: 's2' }).reply(200); + + const { stderr, error } = await runCommand([ + 'vm:snapshot:delete', + '--vm', + 'my-vm', + '--snapshot', + 'old', + '--force', + '--detach', + ]); + + expect(error).to.equal(undefined); + expect(stderr).to.include( + 'The delete request has been submitted for the snapshot "old".', + ); + }); + + it('waits for a delete to finish', async () => { + expectVms(); + get('/vm/snapshot/vm-1').reply(200, snapshots); + get('/vm/operation/vm-1').reply(200, { operations: [] }); + post('/vm/delete-snapshot/vm-1', { snapshotID: 's2' }).reply(200); + get('/vm/operation/vm-1').reply(200, { + operations: [ + op('DELETE_VM_SNAPSHOT', 'SUCCEEDED', '2026-02-01T00:00:00.000Z'), + ], + }); + + const { stderr, error } = await runCommand([ + 'vm:snapshot:delete', + '--vm', + 'my-vm', + '--snapshot', + 'old', + '--force', + ]); + + expect(error).to.equal(undefined); + expect(stderr).to.include('The snapshot "old" has been deleted.'); + }); + + it('fails for an unknown snapshot', async () => { + expectVms(); + get('/vm/snapshot/vm-1').reply(200, snapshots); + + const { error } = await runCommand([ + 'vm:snapshot:delete', + '--vm', + 'my-vm', + '--snapshot', + 'nope', + '--force', + ]); + + expect(error?.message).to.equal('The snapshot "nope" does not exist.'); + }); + + it('fails when the vm has no snapshots', async () => { + expectVms(); + get('/vm/snapshot/vm-1').reply(200, []); + + const { error } = await runCommand([ + 'vm:snapshot:revert', + '--vm', + 'my-vm', + '--force', + ]); + + expect(error?.message).to.equal('vm "my-vm" has no snapshots.'); + }); + + it('refuses a frozen vm', async () => { + expectVms(); + + const { error } = await runCommand([ + 'vm:snapshot:create', + '--vm', + 'frozen-vm', + '--name', + 'x', + ]); + + expect(error?.message).to.include('The vm is frozen'); + }); + + it('gives up waiting after too many attempts', async () => { + sinon.stub(VmCommand.prototype, 'maxPollAttempts').get(() => 2); + expectVms(); + get('/vm/operation/vm-1').reply(200, { operations: [] }); + post('/vm/take-snapshot/vm-1', { name: 'snap' }).reply(200); + get('/vm/operation/vm-1').times(2).reply(200, { operations: [] }); + + const { stderr, error } = await runCommand([ + 'vm:snapshot:create', + '--vm', + 'my-vm', + '--name', + 'snap', + ]); + + expect(error).to.equal(undefined); + expect(stderr).to.include('still in progress'); + }); + }); + + describe('vm:script', () => { + const scripts = { + initScripts: [ + { + _id: 'sc1', + name: 'setup', + description: 'installs stuff', + type: 'shell', + createdAt: '2026-01-01T00:00:00.000Z', + }, + { + _id: 'sc2', + name: 'win-setup', + type: 'powershell', + createdAt: '2026-01-01T00:00:00.000Z', + }, + ], + }; + let dir: string; + + beforeEach(async () => { + dir = await fs.mkdtemp(path.join(os.tmpdir(), 'liara-vm-script-cmd-')); + }); + + afterEach(async () => { + await fs.remove(dir); + }); + + it('lists the scripts', async () => { + get('/init-scripts').reply(200, scripts); + + const { stdout, error } = await runCommand(['vm:script:list']); + + expect(error).to.equal(undefined); + expect(stdout).to.match(/setup\s+shell\s+installs stuff/); + expect(stdout).to.match(/win-setup\s+powershell\s+-/); + }); + + it('says when there are no scripts', async () => { + get('/init-scripts').reply(200, { initScripts: [] }); + + const { stdout } = await runCommand(['vm:script:list']); + + expect(stdout).to.include('There are no init scripts.'); + }); + + it('creates a script from a file', async () => { + const file = path.join(dir, 'init.ps1'); + await fs.writeFile(file, 'Write-Host hi'); + post('/init-scripts', { + name: 'mine', + description: 'desc', + type: 'powershell', + content: 'Write-Host hi', + }).reply(200); + + const { stdout, error } = await runCommand([ + 'vm:script:create', + '--name', + 'mine', + '--description', + 'desc', + '--file', + file, + ]); + + expect(error).to.equal(undefined); + expect(stdout).to.include( + 'The powershell script "mine" has been created.', + ); + }); + + it('creates a shell script from --content', async () => { + post('/init-scripts', { + name: 'mine', + type: 'shell', + content: 'echo hi', + }).reply(200); + + const { error } = await runCommand([ + 'vm:script:create', + '--name', + 'mine', + '--content', + '"echo hi"', + ]); + + expect(error).to.equal(undefined); + }); + + it('needs a script', async () => { + const { error } = await runCommand([ + 'vm:script:create', + '--name', + 'mine', + ]); + + expect(error?.message).to.equal( + 'Please provide the script using --file or --content.', + ); + }); + + it('rejects an unknown type', async () => { + const { error } = await runCommand([ + 'vm:script:create', + '--content', + 'x', + '--type', + 'bash', + ]); + + expect(error).to.not.equal(undefined); + }); + + it('shows the reason a script is not valid', async () => { + post('/init-scripts').reply(400); + + const { error } = await runCommand([ + 'vm:script:create', + '--content', + '"echo hi"', + ]); + + expect(error?.message).to.equal('The script is not valid.'); + }); + + it('updates only what changed and keeps the old content', async () => { + get('/init-scripts').reply(200, scripts); + get('/init-scripts/sc1/download').reply(200, 'echo old'); + api + .put('/init-scripts/sc1', { + name: 'renamed', + description: 'installs stuff', + type: 'shell', + content: 'echo old', + }) + .query(team) + .reply(200); + + const { stdout, error } = await runCommand([ + 'vm:script:update', + '--script', + 'setup', + '--name', + 'renamed', + ]); + + expect(error).to.equal(undefined); + expect(stdout).to.include('The script "setup" has been updated.'); + }); + + it('updates the content', async () => { + get('/init-scripts').reply(200, scripts); + api + .put('/init-scripts/sc1', { + name: 'setup', + description: 'installs stuff', + type: 'shell', + content: 'echo new', + }) + .query(team) + .reply(200); + + const { error } = await runCommand([ + 'vm:script:update', + '--script', + 'sc1', + '--content', + '"echo new"', + ]); + + expect(error).to.equal(undefined); + }); + + it('prints a script', async () => { + get('/init-scripts').reply(200, scripts); + get('/init-scripts/sc1/download').reply(200, 'echo hi'); + + const { stdout, error } = await runCommand([ + 'vm:script:download', + '--script', + 'setup', + ]); + + expect(error).to.equal(undefined); + expect(stdout).to.equal('echo hi\n'); + }); + + it('saves a script to a file', async () => { + const output = path.join(dir, 'nested', 'out.sh'); + get('/init-scripts').reply(200, scripts); + get('/init-scripts/sc1/download').reply(200, 'echo hi'); + + const { stdout } = await runCommand([ + 'vm:script:download', + '--script', + 'setup', + '--output', + output, + ]); + + expect(stdout).to.include(`was saved to ${output}`); + expect(await fs.readFile(output, 'utf8')).to.equal('echo hi'); + }); + + it('deletes a script', async () => { + get('/init-scripts').reply(200, scripts); + api.delete('/init-scripts/sc2').query(team).reply(200); + + const { stdout, error } = await runCommand([ + 'vm:script:delete', + '--script', + 'win-setup', + '--force', + ]); + + expect(error).to.equal(undefined); + expect(stdout).to.include('The script "win-setup" has been deleted.'); + }); + + it('does not delete without confirmation', async () => { + sinon.stub(VmCommand.prototype, 'confirm').resolves(false); + get('/init-scripts').reply(200, scripts); + + const { stdout } = await runCommand([ + 'vm:script:delete', + '--script', + 'setup', + ]); + + expect(stdout).to.equal(''); + }); + + it('fails for an unknown script', async () => { + get('/init-scripts').reply(200, scripts); + + const { error } = await runCommand([ + 'vm:script:delete', + '--script', + 'nope', + '--force', + ]); + + expect(error?.message).to.equal('The script "nope" does not exist.'); + }); + }); + + describe('vm:metrics', () => { + it('shows the summary', async () => { + expectVms(); + get('/vm/vm-1/metrics/summary').reply(200, { + result: { + cpu: 12.34, + memory: 50, + disk: 7, + diskIO: { read: 1.5, write: 0.25 }, + }, + }); + + const { stdout, error } = await runCommand([ + 'vm:metrics', + '--vm', + 'my-vm', + ]); + + expect(error).to.equal(undefined); + expect(stdout).to.match(/12\.3%\s+50%\s+7%\s+1\.5 MB\/s\s+0\.25 MB\/s/); + }); + + it('says when there are no metrics yet', async () => { + expectVms(); + get('/vm/vm-1/metrics/summary').reply(200, { result: null }); + + const { stdout } = await runCommand(['vm:metrics', '--vm', 'my-vm']); + + expect(stdout).to.include('There are no metrics for vm "my-vm" yet.'); + }); + + it('shows the history of a metric since the range start', async () => { + expectVms(); + api + .get('/vm/vm-1/metrics/cpu') + .query((q) => q.teamID === '' && Number(q.since) > 0) + .reply(200, { result: [{ timestamp: 1_700_000_000, value: 42 }] }); + + const { stdout, error } = await runCommand([ + 'vm:metrics', + '--vm', + 'my-vm', + '--metric', + 'cpu', + '--range', + '24h', + ]); + + expect(error).to.equal(undefined); + expect(stdout).to.match(/42%/); + }); + + it('shows disk io history', async () => { + expectVms(); + api + .get('/vm/vm-1/metrics/diskIO') + .query(true) + .reply(200, { + result: [{ timestamp: 1_700_000_000, value: { read: 2, write: 3 } }], + }); + + const { stdout } = await runCommand([ + 'vm:metrics', + '--vm', + 'my-vm', + '--metric', + 'diskIO', + ]); + + expect(stdout).to.match(/2 MB\/s\s+3 MB\/s/); + }); + + it('says when a range has no data', async () => { + expectVms(); + api.get('/vm/vm-1/metrics/memory').query(true).reply(200, { result: [] }); + + const { stdout } = await runCommand([ + 'vm:metrics', + '--vm', + 'my-vm', + '--metric', + 'memory', + ]); + + expect(stdout).to.include('There is no memory data in this time range.'); + }); + + it('rejects an unknown range', async () => { + const { error } = await runCommand([ + 'vm:metrics', + '--vm', + 'my-vm', + '--range', + '2y', + ]); + + expect(error).to.not.equal(undefined); + }); + }); + + describe('vm:traffic', () => { + it('sums the traffic by destination', async () => { + expectVms(); + api + .get('/vm/traffic-volume/vm-1') + .query((q) => q.teamID === '' && Number(q.startTimeUnix) > 0) + .reply(200, { + result: [ + { dstip: '1.1.1.1', sumbytes: 1024 }, + { dstip: '2.2.2.2', sumbytes: 1_048_576 }, + { dstip: '1.1.1.1', sumbytes: 1024 }, + ], + }); + + const { stdout, error } = await runCommand([ + 'vm:traffic', + '--vm', + 'my-vm', + '--range', + '3h', + ]); + + expect(error).to.equal(undefined); + expect(stdout.indexOf('2.2.2.2')).to.be.lessThan( + stdout.indexOf('1.1.1.1'), + ); + expect(stdout).to.match(/2\.2\.2\.2\s+1 MB/); + expect(stdout).to.match(/1\.1\.1\.1\s+2 KB/); + }); + + it('says when there is no traffic', async () => { + expectVms(); + api.get('/vm/traffic-volume/vm-1').query(true).reply(200, { result: [] }); + + const { stdout } = await runCommand(['vm:traffic', '--vm', 'my-vm']); + + expect(stdout).to.include('There is no traffic in this time range.'); + }); + + it('shows the daily traffic and cost', async () => { + expectVms(); + const today = new Date(); + const key = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')}`; + api + .get('/vm/traffic-daily/vm-1') + .query((q) => q.teamID === '' && Number(q.startTimeUnix) > 0) + .reply(200, { + result: { daily: [{ day: key, bytes: 1_048_576, price: 1500.9 }] }, + }); + + const { stdout, error } = await runCommand([ + 'vm:traffic', + '--vm', + 'my-vm', + '--daily', + ]); + + expect(error).to.equal(undefined); + expect(stdout).to.match(/1 MB\s+1,500/); + }); + }); + + describe('vm:create flags', () => { + const oss = { + ubuntu: ['22.04'], + windows: ['2022'], + bigbluebutton: ['2.7'], + 'one-click-apps': {}, + }; + const plans = { + plans: { + free: { + RAM: { amount: 1 }, + CPU: { amount: 1 }, + volume: 1, + monthlyPrice: 0, + }, + 'pro-g2': { + RAM: { amount: 4 }, + CPU: { amount: 2 }, + volume: 40, + monthlyPrice: 1, + }, + 'standard-base-g2': { + RAM: { amount: 1 }, + CPU: { amount: 1 }, + volume: 1, + monthlyPrice: 1, + }, + }, + }; + const scripts = { + initScripts: [ + { _id: 'sh1', name: 'setup', type: 'shell', createdAt: '' }, + { _id: 'ps1', name: 'win', type: 'powershell', createdAt: '' }, + ], + }; + const base = [ + 'vm:create', + '--vm', + 'new-vm', + '--os', + 'ubuntu', + '--os-version', + '22.04', + '--plan', + 'pro-g2', + '--detach', + ]; + + beforeEach(() => { + get('/oss').reply(200, oss); + get('/plans').reply(200, plans); + }); + + it('creates a vm without any prompt', async () => { + post('/vm', { OS: 'ubuntu-22.04', name: 'new-vm', plan: 'pro-g2' }).reply( + 200, + ); + const prompt = sinon.stub(inquirer, 'prompt'); + + const { stderr, error } = await runCommand(base); + + expect(error).to.equal(undefined); + expect(prompt.called).to.equal(false); + expect(stderr).to.include('creation request submitted successfully'); + }); + + it('sends the ssh keys, port and init script', async () => { + get('/init-scripts').reply(200, scripts); + post('/vm', { + OS: 'ubuntu-22.04', + name: 'new-vm', + plan: 'pro-g2', + config: { + SSHKeys: ['ssh-ed25519 AAA a@b', 'ssh-rsa BBB'], + sshPort: 2222, + InitScriptID: 'sh1', + }, + }).reply(200); + + const { error } = await runCommand([ + ...base, + '--ssh-key', + '"ssh-ed25519 AAA a@b"', + '--ssh-key', + '"ssh-rsa BBB"', + '--ssh-port', + '2222', + '--init-script', + 'setup', + ]); + + expect(error).to.equal(undefined); + }); + + it('offers only powershell scripts on windows', async () => { + get('/init-scripts').reply(200, scripts); + post('/vm', { + OS: 'windows-2022', + name: 'new-vm', + plan: 'pro-g2', + config: { InitScriptID: 'ps1' }, + }).reply(200); + + const { error } = await runCommand([ + 'vm:create', + '--vm', + 'new-vm', + '--os', + 'windows', + '--os-version', + '2022', + '--plan', + 'pro-g2', + '--init-script', + 'win', + '--detach', + ]); + + expect(error).to.equal(undefined); + }); + + it('rejects a shell script on windows', async () => { + get('/init-scripts').reply(200, scripts); + + const { error } = await runCommand([ + 'vm:create', + '--vm', + 'new-vm', + '--os', + 'windows', + '--os-version', + '2022', + '--plan', + 'pro-g2', + '--init-script', + 'setup', + '--detach', + ]); + + expect(error?.message).to.include( + 'Could not find a powershell init script named "setup"', + ); + }); + + it('rejects ssh keys and port on windows', async () => { + const keys = await runCommand([ + 'vm:create', + '--vm', + 'new-vm', + '--os', + 'windows', + '--os-version', + '2022', + '--plan', + 'pro-g2', + '--ssh-key', + '"ssh-rsa AAA"', + '--detach', + ]); + expect(keys.error?.message).to.include( + 'SSH keys are not supported on Windows', + ); + }); + + it('rejects an ssh port for bigbluebutton', async () => { + const { error } = await runCommand([ + 'vm:create', + '--vm', + 'new-vm', + '--os', + 'bigbluebutton', + '--os-version', + '2.7', + '--plan', + 'pro-g2', + '--ssh-port', + '2222', + '--detach', + ]); + + expect(error?.message).to.equal( + 'The SSH port cannot be set for bigbluebutton.', + ); + }); + + it('rejects a plan disabled for the os', async () => { + const { error } = await runCommand([ + 'vm:create', + '--vm', + 'new-vm', + '--os', + 'windows', + '--os-version', + '2022', + '--plan', + 'standard-base-g2', + '--detach', + ]); + + expect(error?.message).to.include( + 'The plan "standard-base-g2" is not available for windows-2022', + ); + }); + + it('rejects a free plan', async () => { + const { error } = await runCommand([ + 'vm:create', + '--vm', + 'new-vm', + '--os', + 'ubuntu', + '--os-version', + '22.04', + '--plan', + 'free', + '--detach', + ]); + + expect(error?.message).to.include('is not available'); + }); + + it('rejects an invalid ssh key', async () => { + const { error } = await runCommand([ + ...base, + '--ssh-key', + '"ssh-rsa AA\u200bAA"', + ]); + + expect(error?.message).to.include('not valid'); + }); + + it('rejects an invalid ssh port', async () => { + const port25 = await runCommand([...base, '--ssh-port', '25']); + expect(port25.error?.message).to.include('Port 25'); + }); + + it('rejects an unknown os', async () => { + nock.cleanAll(); + get('/oss').reply(200, oss); + const unknown = await runCommand([ + 'vm:create', + '--vm', + 'new-vm', + '--os', + 'nope', + '--plan', + 'pro-g2', + '--detach', + ]); + expect(unknown.error?.message).to.include( + 'Unknown operating system "nope"', + ); + }); + + it('rejects an unknown version', async () => { + nock.cleanAll(); + get('/oss').reply(200, oss); + const { error } = await runCommand([ + 'vm:create', + '--vm', + 'new-vm', + '--os', + 'ubuntu', + '--os-version', + '1', + '--plan', + 'pro-g2', + '--detach', + ]); + + expect(error?.message).to.include( + 'Unknown version "1" for ubuntu. Available versions: 22.04.', + ); + }); + + it('rejects an invalid name before calling the api', async () => { + nock.cleanAll(); + + const { error } = await runCommand([ + 'vm:create', + '--vm', + '-bad-', + '--os', + 'ubuntu', + '--plan', + 'pro-g2', + ]); + + expect(error?.message).to.include('Invalid vm name'); + }); + + it('prompts for the ssh port and init script when running interactively', async () => { + sinon.stub(inquirer, 'prompt').resolves({ plan: 'pro-g2' }); + sinon.stub(VmCreate.prototype, 'promptSSHKey').resolves([]); + sinon.stub(VmCreate.prototype, 'promptSSHPort').resolves(2200); + sinon.stub(VmCreate.prototype, 'promptInitScript').resolves('sh1'); + get('/init-scripts').reply(200, scripts); + post('/vm', { + OS: 'ubuntu-22.04', + name: 'new-vm', + plan: 'pro-g2', + config: { sshPort: 2200, InitScriptID: 'sh1' }, + }).reply(200); + + const { error } = await runCommand([ + 'vm:create', + '--vm', + 'new-vm', + '--os', + 'ubuntu', + '--os-version', + '22.04', + '--detach', + ]); + + expect(error).to.equal(undefined); + }); + }); + + describe('existing power commands with a frozen vm', () => { + for (const command of ['vm:start', 'vm:restart', 'vm:stop']) { + it(`${command} refuses it`, async () => { + api + .get('/vm') + .query(team) + .reply(200, { + vms: [ + vm('vm-3', 'frozen-vm', { + state: 'FROZEN', + power: command === 'vm:start' ? 'POWERED_OFF' : 'POWERED_ON', + }), + ], + }); + + const { error } = await runCommand([ + command, + '--vm', + 'frozen-vm', + '--detach', + ]); + + expect(error?.message).to.include('The vm is frozen'); + }); + } + }); + + describe('vm:info', () => { + it('shows the ssh port, keys and username', async () => { + expectVms(); + get('/vm/vm-1').reply( + 200, + details(['1.1.1.1'], { + config: { + SSHKeys: ['a', 'b'], + rootPassword: 'pw', + hostname: 'host', + sshPort: 2222, + }, + planDetails: { CPU: { amount: 2 }, RAM: { amount: 4 }, volume: 40 }, + }), + ); + + const { stdout, error } = await runCommand(['vm:info', '--vm', 'my-vm']); + + expect(error).to.equal(undefined); + expect(stdout).to.match(/root\s+pw\s+2222\s+2/); + }); + }); +}); diff --git a/test/vm/vm.unit.test.ts b/test/vm/vm.unit.test.ts index 4b1fa890..876f3def 100644 --- a/test/vm/vm.unit.test.ts +++ b/test/vm/vm.unit.test.ts @@ -259,6 +259,8 @@ describe('vm commands', function () { .resolves('22.04'); sinon.stub(VmCreate.prototype, 'promptPlan').resolves('g1'); sinon.stub(VmCreate.prototype, 'promptSSHKey').resolves([]); + sinon.stub(VmCreate.prototype, 'promptSSHPort').resolves(undefined); + sinon.stub(VmCreate.prototype, 'getInitScript').resolves(undefined); }); it('submits the vm', async () => { From d80be7666320d8cdc2d65c019a32474285a40768 Mon Sep 17 00:00:00 2001 From: Amin Ehterami Date: Sun, 15 Nov 2026 14:11:50 +0330 Subject: [PATCH 7/7] chore(os): remove images alias --- src/commands/vm/os.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/commands/vm/os.ts b/src/commands/vm/os.ts index 22657222..59dc38ee 100644 --- a/src/commands/vm/os.ts +++ b/src/commands/vm/os.ts @@ -13,7 +13,7 @@ export default class VmOs extends VmCommand { ...ux.table.flags(), }; - static aliases = ['vm:oss', 'vm:images']; + static aliases = ['vm:oss']; public async run(): Promise { const { flags } = await this.parse(VmOs);