|
| 1 | +/*--------------------------------------------------------------------------------------------- |
| 2 | + * Copyright (c) Microsoft Corporation. All rights reserved. |
| 3 | + * Licensed under the MIT License. See License.txt in the project root for license information. |
| 4 | + *--------------------------------------------------------------------------------------------*/ |
| 5 | + |
| 6 | +import { KnownRevisionProvisioningState, KnownRevisionRunningState, type ContainerAppsAPIClient, type Revision } from "@azure/arm-appcontainers"; |
| 7 | +import { LogsQueryResultStatus, type LogsTable } from "@azure/monitor-query"; |
| 8 | +import { parseAzureResourceId, uiUtils } from "@microsoft/vscode-azext-azureutils"; |
| 9 | +import { AzureWizardExecuteStepWithActivityOutput, createSubscriptionContext, maskUserInfo, nonNullValueAndProp, parseError, type IParsedError, type LogActivityAttributes } from "@microsoft/vscode-azext-utils"; |
| 10 | +import { type Progress } from "vscode"; |
| 11 | +import { ext } from "../../../extensionVariables"; |
| 12 | +import { type ContainerAppStartVerificationTelemetryProps } from "../../../telemetry/ContainerAppStartVerificationTelemetryProps"; |
| 13 | +import { type SetTelemetryProps } from "../../../telemetry/SetTelemetryProps"; |
| 14 | +import { createContainerAppsAPIClient, createLogsQueryClientPublicCloud } from "../../../utils/azureClients"; |
| 15 | +import { delayWithExponentialBackoff } from "../../../utils/delay"; |
| 16 | +import { localize } from "../../../utils/localize"; |
| 17 | +import { type IngressContext } from "../../ingress/IngressContext"; |
| 18 | +import { type ImageSourceContext } from "./ImageSourceContext"; |
| 19 | + |
| 20 | +type ContainerAppStartVerificationContext = ImageSourceContext & IngressContext & SetTelemetryProps<ContainerAppStartVerificationTelemetryProps>; |
| 21 | + |
| 22 | +/** |
| 23 | + * Verifies that the recently deployed container app did not have any startup issues. |
| 24 | + * |
| 25 | + * Note: Sometimes an image builds and deploys successfully but fails to run. |
| 26 | + * This leads to the Azure Container Apps service silently reverting to the last successful revision. |
| 27 | + */ |
| 28 | +export class ContainerAppStartVerificationStep<T extends ContainerAppStartVerificationContext> extends AzureWizardExecuteStepWithActivityOutput<T> { |
| 29 | + public priority: number = 690; |
| 30 | + public stepName: string = 'containerAppStartVerificationStep'; |
| 31 | + |
| 32 | + private _client: ContainerAppsAPIClient; |
| 33 | + |
| 34 | + protected getOutputLogSuccess = (context: T): string => localize('verifyContainerAppSuccess', 'Verified container app "{0}" deployment started successfully.', context.containerApp?.name); |
| 35 | + protected getOutputLogFail = (context: T): string => localize('updateContainerAppFail', 'Failed to verify container app "{0}" deployment started successfully.', context.containerApp?.name); |
| 36 | + protected getTreeItemLabel = (): string => localize('verifyContainerAppLabel', 'Verify container app deployment started successfully'); |
| 37 | + |
| 38 | + public async execute(context: T, progress: Progress<{ message?: string | undefined; increment?: number | undefined }>): Promise<void> { |
| 39 | + progress.report({ message: localize('verifyingContainerApp', 'Verifying container app startup status...') }); |
| 40 | + const containerAppName: string = nonNullValueAndProp(context.containerApp, 'name'); |
| 41 | + |
| 42 | + // Estimated time (n=1): 1s |
| 43 | + const revisionId: string | undefined = await this.waitAndGetRevisionId(context, 1000 * 10 /** maxWaitTimeMs */); |
| 44 | + if (!revisionId) { |
| 45 | + throw new Error(localize('revisionCheckTimeout', 'Status check timed out before retrieving the latest deployed container app revision.')); |
| 46 | + } |
| 47 | + |
| 48 | + // Estimated time (n=1): 20s |
| 49 | + const revisionStatus: string | undefined = await this.waitAndGetRevisionStatus(context, revisionId, containerAppName, 1000 * 60 /** maxWaitTimeMs */); |
| 50 | + |
| 51 | + const parsedResource = parseAzureResourceId(revisionId); |
| 52 | + if (!revisionStatus) { |
| 53 | + throw new Error(localize('revisionStatusTimeout', 'Status check timed out for the deployed container app revision "{0}".', parsedResource.resourceName)); |
| 54 | + } else if (revisionStatus !== KnownRevisionRunningState.Running) { |
| 55 | + try { |
| 56 | + context.telemetry.properties.targetCloud = context.environment.name; |
| 57 | + |
| 58 | + // Try to query and provide any logs to the LLM before throwing |
| 59 | + await this.tryAddLogAttributes(context, parsedResource.resourceName); |
| 60 | + context.telemetry.properties.addedContainerAppStartLogs = 'true'; |
| 61 | + } catch (error) { |
| 62 | + const perr: IParsedError = parseError(error); |
| 63 | + ext.outputChannel.appendLog(localize('logQueryError', 'Error encountered while trying to verify container app revision logs through log query platform.')); |
| 64 | + ext.outputChannel.appendLog(perr.message); |
| 65 | + context.telemetry.properties.addedContainerAppStartLogs = 'false'; |
| 66 | + context.telemetry.properties.getLogsQueryError = maskUserInfo(perr.message, []); |
| 67 | + } |
| 68 | + |
| 69 | + throw new Error(localize( |
| 70 | + 'unexpectedRevisionState', |
| 71 | + 'The deployed container app revision "{0}" has failed to start. If you are updating an existing container app, the service will try to revert to the previous working revision. Inspect the application logs to check for any known startup issues.', |
| 72 | + parsedResource.resourceName, |
| 73 | + )); |
| 74 | + } |
| 75 | + } |
| 76 | + |
| 77 | + public shouldExecute(context: T): boolean { |
| 78 | + return !!context.containerApp; |
| 79 | + } |
| 80 | + |
| 81 | + private async waitAndGetRevisionId(context: T, maxWaitTimeMs: number): Promise<string | undefined> { |
| 82 | + this._client ??= await createContainerAppsAPIClient([context, createSubscriptionContext(context.subscription)]); |
| 83 | + |
| 84 | + const resourceGroupName: string = nonNullValueAndProp(context.containerApp, 'resourceGroup'); |
| 85 | + const containerAppName: string = nonNullValueAndProp(context.containerApp, 'name'); |
| 86 | + |
| 87 | + let revision: Revision | undefined; |
| 88 | + let revisions: Revision[]; |
| 89 | + |
| 90 | + let attempt: number = 1; |
| 91 | + const start: number = Date.now(); |
| 92 | + |
| 93 | + while (true) { |
| 94 | + if ((Date.now() - start) > maxWaitTimeMs) { |
| 95 | + break; |
| 96 | + } |
| 97 | + |
| 98 | + await delayWithExponentialBackoff(attempt, 1000 /** baseDelayMs */, maxWaitTimeMs); |
| 99 | + attempt++; |
| 100 | + |
| 101 | + revisions = await uiUtils.listAllIterator(this._client.containerAppsRevisions.listRevisions(resourceGroupName, containerAppName)); |
| 102 | + revision = revisions.find(r => r.name === context.containerApp?.latestRevisionName && r.template?.containers?.[context.containersIdx ?? 0].image === context.image); |
| 103 | + |
| 104 | + if (revision) { |
| 105 | + return revision.id; |
| 106 | + } |
| 107 | + } |
| 108 | + |
| 109 | + return undefined; |
| 110 | + } |
| 111 | + |
| 112 | + private async waitAndGetRevisionStatus(context: T, revisionId: string, containerAppName: string, maxWaitTimeMs: number): Promise<string | undefined> { |
| 113 | + this._client ??= await createContainerAppsAPIClient([context, createSubscriptionContext(context.subscription)]); |
| 114 | + const parsedRevision = parseAzureResourceId(revisionId); |
| 115 | + |
| 116 | + let revision: Revision; |
| 117 | + let attempt: number = 1; |
| 118 | + const start: number = Date.now(); |
| 119 | + |
| 120 | + while (true) { |
| 121 | + if ((Date.now() - start) > maxWaitTimeMs) { |
| 122 | + break; |
| 123 | + } |
| 124 | + |
| 125 | + await delayWithExponentialBackoff(attempt, 1000 /** baseDelayMs */, maxWaitTimeMs); |
| 126 | + attempt++; |
| 127 | + |
| 128 | + revision = await this._client.containerAppsRevisions.getRevision(parsedRevision.resourceGroup, containerAppName, parsedRevision.resourceName); |
| 129 | + |
| 130 | + if ( |
| 131 | + revision.provisioningState === KnownRevisionProvisioningState.Deprovisioning || |
| 132 | + revision.provisioningState === KnownRevisionProvisioningState.Provisioning || |
| 133 | + revision.runningState === KnownRevisionRunningState.Processing || |
| 134 | + revision.runningState === 'Activating' // For some reason this isn't listed in the known enum |
| 135 | + ) { |
| 136 | + continue; |
| 137 | + } |
| 138 | + |
| 139 | + return revision.runningState; |
| 140 | + } |
| 141 | + |
| 142 | + return undefined; |
| 143 | + } |
| 144 | + |
| 145 | + /** |
| 146 | + * Try to query for any logs associated with the revision and add them to the Copilot activity attributes |
| 147 | + */ |
| 148 | + private async tryAddLogAttributes(context: T, revisionName: string) { |
| 149 | + // Basic validation check since we're including a name directly in the query |
| 150 | + if (revisionName.length > 54 || !/^[\w-]+$/.test(revisionName)) { |
| 151 | + const invalidName: string = localize('unexpectedRevisionName', 'Internal warning: Encountered an unexpected revision name format "{0}". Skipping log query for the revision status check.', revisionName); |
| 152 | + ext.outputChannel.appendLog(invalidName); |
| 153 | + throw new Error(invalidName); |
| 154 | + } |
| 155 | + |
| 156 | + const workspaceId = context.managedEnvironment.appLogsConfiguration?.logAnalyticsConfiguration?.customerId; |
| 157 | + if (!workspaceId) { |
| 158 | + return; |
| 159 | + } |
| 160 | + |
| 161 | + const logsQueryClient = await createLogsQueryClientPublicCloud(context); |
| 162 | + const query = ` |
| 163 | +ContainerAppConsoleLogs_CL |
| 164 | +| where RevisionName_s == "${revisionName}" |
| 165 | +| project TimeGenerated, Stream_s, Log_s |
| 166 | +| order by TimeGenerated desc |
| 167 | +`; |
| 168 | + |
| 169 | + const queryResult = await logsQueryClient.queryWorkspace(workspaceId, query, { |
| 170 | + // <= 5 min ago (ISO 8601) |
| 171 | + duration: 'PT5M' |
| 172 | + }); |
| 173 | + |
| 174 | + if (queryResult.status !== LogsQueryResultStatus.Success) { |
| 175 | + return; |
| 176 | + } |
| 177 | + |
| 178 | + const lines: string[] = []; |
| 179 | + const table: LogsTable = queryResult.tables[0]; |
| 180 | + |
| 181 | + if (!table.rows.length) { |
| 182 | + // Note: Often times we will only be able to find logs when the image source was for `RemoteAcrBuild` |
| 183 | + throw new Error(localize('noQueryLogs', 'No query logs were found for revision "{0}".', revisionName)); |
| 184 | + } |
| 185 | + |
| 186 | + lines.push(table.columnDescriptors.map(c => c.name ?? '{columnName}').join(',')); |
| 187 | + for (const row of table.rows) { |
| 188 | + if (!Array.isArray(row)) { |
| 189 | + continue; |
| 190 | + } |
| 191 | + lines.push(row.map(r => r instanceof Date ? r.toLocaleString() : String(r)).join(' ')); |
| 192 | + } |
| 193 | + |
| 194 | + const logs: LogActivityAttributes = { |
| 195 | + name: 'Container App Console Logs', |
| 196 | + description: `Container runtime logs for revision "${revisionName}" (<= 5 min ago). When a container app update was unsuccessful, these should be inspected to help identify the root cause.`, |
| 197 | + content: lines.join('\n'), |
| 198 | + }; |
| 199 | + |
| 200 | + context.activityAttributes ??= {}; |
| 201 | + context.activityAttributes.logs ??= []; |
| 202 | + context.activityAttributes?.logs.push(logs); |
| 203 | + } |
| 204 | +} |
0 commit comments