|
| 1 | +/*! |
| 2 | + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. |
| 3 | + * SPDX-License-Identifier: Apache-2.0 |
| 4 | + */ |
| 5 | +import { |
| 6 | + EC2Client, |
| 7 | + Instance, |
| 8 | + InstanceStateName, |
| 9 | + GetConsoleOutputRequest, |
| 10 | + Filter, |
| 11 | + paginateDescribeInstances, |
| 12 | + DescribeInstancesRequest, |
| 13 | + Reservation, |
| 14 | + Tag, |
| 15 | + paginateDescribeInstanceStatus, |
| 16 | + StartInstancesCommandOutput, |
| 17 | + StartInstancesCommand, |
| 18 | + StopInstancesCommand, |
| 19 | + StopInstancesCommandOutput, |
| 20 | + RebootInstancesCommand, |
| 21 | + IamInstanceProfileAssociation, |
| 22 | + paginateDescribeIamInstanceProfileAssociations, |
| 23 | + IamInstanceProfile, |
| 24 | + GetConsoleOutputCommand, |
| 25 | +} from '@aws-sdk/client-ec2' |
| 26 | +import { Timeout } from '../utilities/timeoutUtils' |
| 27 | +import { showMessageWithCancel } from '../utilities/messages' |
| 28 | +import { ToolkitError, isAwsError } from '../errors' |
| 29 | +import { decodeBase64 } from '../utilities/textUtilities' |
| 30 | +import { ClientWrapper } from './clientWrapper' |
| 31 | + |
| 32 | +/** |
| 33 | + * A wrapper around EC2.Instance where we can safely assume InstanceId field exists. |
| 34 | + */ |
| 35 | +export interface SafeEc2Instance extends Instance { |
| 36 | + InstanceId: string |
| 37 | + Name?: string |
| 38 | + LastSeenStatus: InstanceStateName |
| 39 | +} |
| 40 | + |
| 41 | +interface SafeEc2GetConsoleOutputResult extends GetConsoleOutputRequest { |
| 42 | + Output: string |
| 43 | + InstanceId: string |
| 44 | +} |
| 45 | + |
| 46 | +export class Ec2Client extends ClientWrapper<EC2Client> { |
| 47 | + public constructor(public override readonly regionCode: string) { |
| 48 | + super(regionCode, EC2Client) |
| 49 | + } |
| 50 | + |
| 51 | + public async getInstances(filters?: Filter[]): Promise<SafeEc2Instance[]> { |
| 52 | + const reservations = await this.makePaginatedRequest( |
| 53 | + paginateDescribeInstances, |
| 54 | + filters ? { Filters: filters } : ({} satisfies DescribeInstancesRequest), |
| 55 | + (page) => page.Reservations |
| 56 | + ) |
| 57 | + |
| 58 | + return await this.updateInstancesDetail(this.getInstancesFromReservations(reservations)) |
| 59 | + } |
| 60 | + |
| 61 | + /** Updates status and name in-place for displaying to humans. */ |
| 62 | + public async updateInstancesDetail( |
| 63 | + instances: Instance[], |
| 64 | + getStatus: (i: string) => Promise<InstanceStateName> = this.getInstanceStatus.bind(this) |
| 65 | + ): Promise<SafeEc2Instance[]> { |
| 66 | + const instanceWithId = instances.filter(hasId) |
| 67 | + const instanceWithStatus = await Promise.all(instanceWithId.map(addStatus)) |
| 68 | + return instanceWithStatus.map((i) => (instanceHasName(i) ? { ...i, Name: lookupTagKey(i.Tags, 'Name') } : i)) |
| 69 | + |
| 70 | + function hasId(i: Instance): i is Instance & { InstanceId: string } { |
| 71 | + return i.InstanceId !== undefined |
| 72 | + } |
| 73 | + |
| 74 | + async function addStatus(instance: Instance & { InstanceId: string }) { |
| 75 | + return { ...instance, LastSeenStatus: await getStatus(instance.InstanceId) } |
| 76 | + } |
| 77 | + } |
| 78 | + |
| 79 | + public getInstancesFromReservations(reservations: Reservation[]): (Instance & { InstanceId: string })[] { |
| 80 | + return reservations |
| 81 | + .map((r) => r.Instances) |
| 82 | + .flat() |
| 83 | + .filter(isNotEmpty) |
| 84 | + |
| 85 | + function isNotEmpty(i: Instance | undefined): i is Instance & { InstanceId: string } { |
| 86 | + return i !== undefined && i.InstanceId !== undefined |
| 87 | + } |
| 88 | + } |
| 89 | + |
| 90 | + public async getInstanceStatus(instanceId: string): Promise<InstanceStateName> { |
| 91 | + const instanceStatuses = await this.makePaginatedRequest( |
| 92 | + paginateDescribeInstanceStatus, |
| 93 | + { InstanceIds: [instanceId], IncludeAllInstances: true }, |
| 94 | + (page) => page.InstanceStatuses |
| 95 | + ) |
| 96 | + |
| 97 | + return instanceStatuses[0].InstanceState!.Name! |
| 98 | + } |
| 99 | + |
| 100 | + public async isInstanceRunning(instanceId: string): Promise<boolean> { |
| 101 | + const status = await this.getInstanceStatus(instanceId) |
| 102 | + return status === 'running' |
| 103 | + } |
| 104 | + |
| 105 | + public getInstancesFilter(instanceIds: string[]): Filter[] { |
| 106 | + return [ |
| 107 | + { |
| 108 | + Name: 'instance-id', |
| 109 | + Values: instanceIds, |
| 110 | + }, |
| 111 | + ] |
| 112 | + } |
| 113 | + |
| 114 | + private handleStatusError(instanceId: string, err: unknown) { |
| 115 | + if (isAwsError(err)) { |
| 116 | + throw new ToolkitError(`EC2: failed to change status of instance ${instanceId}`, { |
| 117 | + cause: err as Error, |
| 118 | + }) |
| 119 | + } else { |
| 120 | + throw err |
| 121 | + } |
| 122 | + } |
| 123 | + |
| 124 | + public async assertNotInStatus( |
| 125 | + instanceId: string, |
| 126 | + targetStatus: string, |
| 127 | + getStatus: (i: string) => Promise<InstanceStateName> = this.getInstanceStatus.bind(this) |
| 128 | + ) { |
| 129 | + const isAlreadyInStatus = (await getStatus(instanceId)) === targetStatus |
| 130 | + if (isAlreadyInStatus) { |
| 131 | + throw new ToolkitError( |
| 132 | + `EC2: Instance is currently ${targetStatus}. Unable to update status of ${instanceId}.` |
| 133 | + ) |
| 134 | + } |
| 135 | + } |
| 136 | + |
| 137 | + public async startInstance(instanceId: string): Promise<StartInstancesCommandOutput> { |
| 138 | + return await this.makeRequest(StartInstancesCommand, { InstanceIds: [instanceId] }) |
| 139 | + } |
| 140 | + |
| 141 | + public async startInstanceWithCancel(instanceId: string): Promise<void> { |
| 142 | + const timeout = new Timeout(5000) |
| 143 | + |
| 144 | + await showMessageWithCancel(`EC2: Starting instance ${instanceId}`, timeout) |
| 145 | + |
| 146 | + try { |
| 147 | + await this.assertNotInStatus(instanceId, 'running') |
| 148 | + await this.startInstance(instanceId) |
| 149 | + } catch (err) { |
| 150 | + this.handleStatusError(instanceId, err) |
| 151 | + } finally { |
| 152 | + timeout.cancel() |
| 153 | + } |
| 154 | + } |
| 155 | + |
| 156 | + public async stopInstance(instanceId: string): Promise<StopInstancesCommandOutput> { |
| 157 | + return await this.makeRequest(StopInstancesCommand, { InstanceIds: [instanceId] }) |
| 158 | + } |
| 159 | + |
| 160 | + public async stopInstanceWithCancel(instanceId: string): Promise<void> { |
| 161 | + const timeout = new Timeout(5000) |
| 162 | + |
| 163 | + await showMessageWithCancel(`EC2: Stopping instance ${instanceId}`, timeout) |
| 164 | + |
| 165 | + try { |
| 166 | + await this.assertNotInStatus(instanceId, 'stopped') |
| 167 | + await this.stopInstance(instanceId) |
| 168 | + } catch (err) { |
| 169 | + this.handleStatusError(instanceId, err) |
| 170 | + } finally { |
| 171 | + timeout.cancel() |
| 172 | + } |
| 173 | + } |
| 174 | + |
| 175 | + public async rebootInstance(instanceId: string): Promise<void> { |
| 176 | + return await this.makeRequest(RebootInstancesCommand, { InstanceIds: [instanceId] }) |
| 177 | + } |
| 178 | + |
| 179 | + public async rebootInstanceWithCancel(instanceId: string): Promise<void> { |
| 180 | + const timeout = new Timeout(5000) |
| 181 | + |
| 182 | + await showMessageWithCancel(`EC2: Rebooting instance ${instanceId}`, timeout) |
| 183 | + |
| 184 | + try { |
| 185 | + await this.rebootInstance(instanceId) |
| 186 | + } catch (err) { |
| 187 | + this.handleStatusError(instanceId, err) |
| 188 | + } finally { |
| 189 | + timeout.cancel() |
| 190 | + } |
| 191 | + } |
| 192 | + |
| 193 | + /** |
| 194 | + * Retrieve IAM Association for a given EC2 instance. |
| 195 | + * @param instanceId target EC2 instance ID |
| 196 | + * @returns IAM Association for instance |
| 197 | + */ |
| 198 | + private async getIamInstanceProfileAssociation(instanceId: string): Promise<IamInstanceProfileAssociation> { |
| 199 | + const instanceFilter = this.getInstancesFilter([instanceId]) |
| 200 | + |
| 201 | + const associations = await this.makePaginatedRequest( |
| 202 | + paginateDescribeIamInstanceProfileAssociations, |
| 203 | + { Filters: instanceFilter }, |
| 204 | + (page) => page.IamInstanceProfileAssociations |
| 205 | + ) |
| 206 | + |
| 207 | + return associations[0]! |
| 208 | + } |
| 209 | + |
| 210 | + /** |
| 211 | + * Gets the IAM Instance Profile (not role) attached to given EC2 instance. |
| 212 | + * @param instanceId target EC2 instance ID |
| 213 | + * @returns IAM Instance Profile associated with instance or undefined if none exists. |
| 214 | + */ |
| 215 | + public async getAttachedIamInstanceProfile(instanceId: string): Promise<IamInstanceProfile | undefined> { |
| 216 | + const association = await this.getIamInstanceProfileAssociation(instanceId) |
| 217 | + return association ? association.IamInstanceProfile : undefined |
| 218 | + } |
| 219 | + |
| 220 | + public async getConsoleOutput(instanceId: string, latest: boolean): Promise<SafeEc2GetConsoleOutputResult> { |
| 221 | + const response = await this.makeRequest(GetConsoleOutputCommand, { InstanceId: instanceId, Latest: latest }) |
| 222 | + |
| 223 | + return { |
| 224 | + ...response, |
| 225 | + InstanceId: instanceId, |
| 226 | + Output: response.Output ? decodeBase64(response.Output) : '', |
| 227 | + } |
| 228 | + } |
| 229 | +} |
| 230 | + |
| 231 | +export function getNameOfInstance(instance: Instance): string | undefined { |
| 232 | + return instanceHasName(instance) ? lookupTagKey(instance.Tags!, 'Name')! : undefined |
| 233 | +} |
| 234 | + |
| 235 | +export function instanceHasName(instance: Instance): instance is Instance & { Tags: Tag[] } { |
| 236 | + return instance.Tags !== undefined && instance.Tags.some((tag) => tag.Key === 'Name') |
| 237 | +} |
| 238 | + |
| 239 | +function lookupTagKey(tags: Tag[], targetKey: string) { |
| 240 | + return tags.filter((tag) => tag.Key === targetKey)[0].Value |
| 241 | +} |
0 commit comments