Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve output and activity logs for deployContainerApp #806

Merged
merged 13 commits into from
Dec 20, 2024
10 changes: 3 additions & 7 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -96,8 +96,8 @@
"category": "Azure Container Apps"
},
{
"command": "containerApps.deployWorkspaceProjectToContainerApp",
"title": "%containerApps.deployWorkspaceProjectToContainerApp%",
"command": "containerApps.deployContainerApp",
"title": "%containerApps.deployContainerApp%",
"category": "Azure Container Apps"
},
{
Expand Down Expand Up @@ -366,7 +366,7 @@
"group": "1@2"
},
{
"command": "containerApps.deployWorkspaceProjectToContainerApp",
"command": "containerApps.deployContainerApp",
"when": "view =~ /(azureResourceGroups|azureFocusView)/ && viewItem =~ /containerAppItem/i",
"group": "2@1"
},
Expand Down Expand Up @@ -566,10 +566,6 @@
"command": "containerApps.createContainerAppFromWorkspace",
"when": "never"
},
{
"command": "containerApps.deployWorkspaceProjectToContainerApp",
"when": "never"
},
{
"command": "containerApps.deployWorkspaceProjectApi",
"when": "never"
Expand Down
2 changes: 1 addition & 1 deletion package.nls.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
"containerApps.deployImageApi": "Deploy Image to Container App (API)...",
"containerApps.deployWorkspaceProject": "Deploy Project from Workspace...",
"containerApps.deployWorkspaceProjectApi": "Deploy Project from Workspace (API)...",
"containerApps.deployWorkspaceProjectToContainerApp": "Deploy Workspace to Container App...",
"containerApps.deployContainerApp": "Deploy to Container App...",
"containerApps.deleteContainerApp": "Delete Container App...",
"containerApps.disableIngress": "Disable Ingress for Container App",
"containerApps.enableIngress": "Enable Ingress for Container App...",
Expand Down
2 changes: 1 addition & 1 deletion src/commands/createContainerApp/createContainerApp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ export async function createContainerApp(context: IActionContext, node?: Managed
};

if (isAzdExtensionInstalled()) {
wizardContext.telemetry.properties.isAzdWorkspaceProject = 'true';
wizardContext.telemetry.properties.isAzdExtensionInstalled = 'true';
}

// Use the same resource group and location as the parent resource (managed environment)
Expand Down
12 changes: 12 additions & 0 deletions src/commands/deployContainerApp/ContainerAppDeployContext.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/

import { type IResourceGroupWizardContext } from '@microsoft/vscode-azext-azureutils';
import { type ExecuteActivityContext } from '@microsoft/vscode-azext-utils';
import { type IContainerAppContext } from '../IContainerAppContext';
import { type ImageSourceBaseContext } from '../image/imageSource/ImageSourceContext';
import { type IngressBaseContext } from '../ingress/IngressContext';

export type ContainerAppDeployContext = IResourceGroupWizardContext & ImageSourceBaseContext & IngressBaseContext & IContainerAppContext & ExecuteActivityContext;
100 changes: 100 additions & 0 deletions src/commands/deployContainerApp/deployContainerApp.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/

import { type ResourceGroup } from "@azure/arm-resources";
import { LocationListStep, ResourceGroupListStep } from "@microsoft/vscode-azext-azureutils";
import { activityInfoIcon, activitySuccessContext, AzureWizard, createSubscriptionContext, createUniversallyUniqueContextValue, GenericTreeItem, nonNullProp, nonNullValue, type IActionContext, type ISubscriptionActionContext, type ISubscriptionContext } from "@microsoft/vscode-azext-utils";
import { ImageSource } from "../../constants";
import { ext } from "../../extensionVariables";
import { type ContainerAppItem } from "../../tree/ContainerAppItem";
import { createActivityContext } from "../../utils/activityUtils";
import { isAzdExtensionInstalled } from "../../utils/azdUtils";
import { getManagedEnvironmentFromContainerApp } from "../../utils/getResourceUtils";
import { getVerifyProvidersStep } from "../../utils/getVerifyProvidersStep";
import { localize } from "../../utils/localize";
import { pickContainerApp } from "../../utils/pickItem/pickContainerApp";
import { deployWorkspaceProject } from "../deployWorkspaceProject/deployWorkspaceProject";
import { ContainerAppUpdateStep } from "../image/imageSource/ContainerAppUpdateStep";
import { ImageSourceListStep } from "../image/imageSource/ImageSourceListStep";
import { type ContainerAppDeployContext } from "./ContainerAppDeployContext";

export async function deployContainerApp(context: IActionContext, node?: ContainerAppItem): Promise<void> {
const item: ContainerAppItem = node ?? await pickContainerApp(context);
const subscriptionContext: ISubscriptionContext = createSubscriptionContext(item.subscription);
const subscriptionActionContext: ISubscriptionActionContext = { ...context, ...subscriptionContext };

// Prompt for image source before initializing the wizard in case we need to redirect the call to 'deployWorkspaceProject' instead
const imageSource: ImageSource = await promptImageSource(subscriptionActionContext);
if (imageSource === ImageSource.RemoteAcrBuild) {
await deployWorkspaceProject(context, item);
return;
}

const wizardContext: ContainerAppDeployContext = {
...subscriptionActionContext,
...await createActivityContext(true),
subscription: item.subscription,
containerApp: item.containerApp,
managedEnvironment: await getManagedEnvironmentFromContainerApp(subscriptionActionContext, item.containerApp),
imageSource,
};

if (isAzdExtensionInstalled()) {
wizardContext.telemetry.properties.isAzdExtensionInstalled = 'true';
}

const resourceGroups: ResourceGroup[] = await ResourceGroupListStep.getResourceGroups(wizardContext);
wizardContext.resourceGroup = nonNullValue(
resourceGroups.find(rg => rg.name === item.containerApp.resourceGroup),
localize('containerAppResourceGroup', 'Expected to find the container app\'s resource group.'),
);

// Log resource group
wizardContext.activityChildren?.push(
new GenericTreeItem(undefined, {
contextValue: createUniversallyUniqueContextValue(['useExistingResourceGroupInfoItem', activitySuccessContext]),
label: localize('useResourceGroup', 'Using resource group "{0}"', wizardContext.resourceGroup.name),
iconPath: activityInfoIcon
})
);
ext.outputChannel.appendLog(localize('usingResourceGroup', 'Using resource group "{0}".', wizardContext.resourceGroup.name));

// Log container app
wizardContext.activityChildren?.push(
new GenericTreeItem(undefined, {
contextValue: createUniversallyUniqueContextValue(['useExistingContainerAppInfoItem', activitySuccessContext]),
label: localize('useContainerApp', 'Using container app "{0}"', wizardContext.containerApp?.name),
iconPath: activityInfoIcon
})
);
ext.outputChannel.appendLog(localize('usingContainerApp', 'Using container app "{0}".', wizardContext.containerApp?.name));

await LocationListStep.setLocation(wizardContext, item.containerApp.location);

const wizard: AzureWizard<ContainerAppDeployContext> = new AzureWizard(wizardContext, {
title: localize('deployContainerAppTitle', 'Deploy image to container app'),
promptSteps: [
new ImageSourceListStep(),
],
executeSteps: [
getVerifyProvidersStep<ContainerAppDeployContext>(),
new ContainerAppUpdateStep(),
],
showLoadingPrompt: true
});

await wizard.prompt();
wizardContext.activityTitle = localize('deployContainerAppActivityTitle', 'Deploy image to container app "{0}"', wizardContext.containerApp?.name);
await wizard.execute();
}

async function promptImageSource(context: ISubscriptionActionContext): Promise<ImageSource> {
const promptContext: ISubscriptionActionContext & { imageSource?: ImageSource } = context;

const imageSourceStep: ImageSourceListStep = new ImageSourceListStep();
await imageSourceStep.prompt(promptContext);

return nonNullProp(promptContext, 'imageSource');
}
53 changes: 45 additions & 8 deletions src/commands/image/imageSource/ContainerAppUpdateStep.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,16 @@
*--------------------------------------------------------------------------------------------*/

import { type Ingress } from "@azure/arm-appcontainers";
import { AzureWizardExecuteStep, GenericParentTreeItem, GenericTreeItem, activityFailContext, activityFailIcon, activitySuccessContext, activitySuccessIcon, createUniversallyUniqueContextValue, nonNullProp, type ExecuteActivityOutput } from "@microsoft/vscode-azext-utils";
import { activityFailContext, activityFailIcon, activitySuccessContext, activitySuccessIcon, AzureWizardExecuteStep, createUniversallyUniqueContextValue, GenericParentTreeItem, GenericTreeItem, nonNullProp, type ExecuteActivityOutput } from "@microsoft/vscode-azext-utils";
import * as retry from "p-retry";
import { type Progress } from "vscode";
import { ext } from "../../../extensionVariables";
import { getContainerEnvelopeWithSecrets, type ContainerAppModel } from "../../../tree/ContainerAppItem";
import { localize } from "../../../utils/localize";
import { type IngressContext } from "../../ingress/IngressContext";
import { enabledIngressDefaults } from "../../ingress/enableIngress/EnableIngressStep";
import { DisableIngressStep } from "../../ingress/disableIngress/DisableIngressStep";
import { enabledIngressDefaults, EnableIngressStep } from "../../ingress/enableIngress/EnableIngressStep";
import { RegistryCredentialType } from "../../registryCredentials/RegistryCredentialsAddConfigurationListStep";
import { updateContainerApp } from "../../updateContainerApp";
import { type ImageSourceContext } from "./ImageSourceContext";
import { getContainerNameForImage } from "./containerRegistry/getContainerNameForImage";
Expand All @@ -37,6 +40,17 @@ export class ContainerAppUpdateStep<T extends ImageSourceContext & IngressContex
ingress = containerAppEnvelope.configuration.ingress;
}

// Display ingress log outputs
if (ingress) {
const { item, message } = EnableIngressStep.createSuccessOutput({ ...context, enableExternal: ingress.external, targetPort: ingress.targetPort });
item && context.activityChildren?.push(item);
message && ext.outputChannel.appendLog(message);
} else {
const { item, message } = DisableIngressStep.createSuccessOutput({ ...context, enableIngress: false });
item && context.activityChildren?.push(item);
message && ext.outputChannel.appendLog(message);
}

containerAppEnvelope.configuration.ingress = ingress;
containerAppEnvelope.configuration.secrets = context.secrets;
containerAppEnvelope.configuration.registries = context.registryCredentials;
Expand All @@ -51,13 +65,36 @@ export class ContainerAppUpdateStep<T extends ImageSourceContext & IngressContex
name: getContainerNameForImage(nonNullProp(context, 'image')),
});

const updating = localize('updatingContainerApp', 'Updating container app...', containerApp.name);
progress.report({ message: updating });
// Related: https://github.com/microsoft/vscode-azurecontainerapps/pull/805
const retries = 4;
await retry(
async (currentAttempt: number): Promise<void> => {
if (currentAttempt === 2) {
const reason: string = localize('authenticationRequired', 'Container registry authentication was rejected due to unauthorized access. This may be due to internal permissions still propagating. Authentication will be attempted up to {0} times.', retries + 1);
ext.outputChannel.appendLog(reason);
}

await ext.state.runWithTemporaryDescription(containerApp.id, localize('updating', 'Updating...'), async () => {
context.containerApp = await updateContainerApp(context, context.subscription, containerAppEnvelope);
ext.state.notifyChildrenChanged(containerApp.managedEnvironmentId);
});
const message: string = currentAttempt === 1 ?
localize('updatingContainerApp', 'Updating container app...') :
localize('updatingContainerAppAttempt', 'Updating container app (Attempt {0}/{1})...', currentAttempt, retries + 1);
progress.report({ message: message });
ext.outputChannel.appendLog(message);

await ext.state.runWithTemporaryDescription(containerApp.id, localize('updating', 'Updating...'), async () => {
context.containerApp = await updateContainerApp(context, context.subscription, containerAppEnvelope);
ext.state.notifyChildrenChanged(containerApp.managedEnvironmentId);
});
},
{
onFailedAttempt: (err: retry.FailedAttemptError) => {
if (context.newRegistryCredentialType !== RegistryCredentialType.DockerLogin || !/authentication\srequired/i.test(err.message)) {
throw err;
}
},
retries,
minTimeout: 2 * 1000,
}
);
}

public shouldExecute(context: T): boolean {
Expand Down
24 changes: 15 additions & 9 deletions src/commands/image/imageSource/EnvironmentVariablesListStep.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,7 @@ export class EnvironmentVariablesListStep extends AzureWizardPromptStep<Environm
private _setEnvironmentVariableOption?: SetEnvironmentVariableOption;

public async prompt(context: EnvironmentVariablesContext): Promise<void> {
// since we only allow one container, we can assume that we want the first container's env settings
const existingData = context.containerApp?.template?.containers?.[0].env;
const existingData = context.containerApp?.template?.containers?.[context.containersIdx ?? 0].env;
context.envPath ??= await this.promptForEnvPath(context, !!existingData /** showHasExistingData */);

if (!context.envPath && existingData) {
Expand Down Expand Up @@ -94,7 +93,6 @@ export class EnvironmentVariablesListStep extends AzureWizardPromptStep<Environm
return !!envFileUris.length;
}

// Todo: It might be nice to add a direct command to update just the environment variables rather than having to suggest to re-run the entire command again
private outputLogs(context: EnvironmentVariablesContext, setEnvironmentVariableOption: SetEnvironmentVariableOption): void {
context.telemetry.properties.setEnvironmentVariableOption = setEnvironmentVariableOption;

Expand All @@ -115,19 +113,27 @@ export class EnvironmentVariablesListStep extends AzureWizardPromptStep<Environm

const logMessage: string = localize('skippedEnvVarsMessage',
'Skipped environment variable configuration for the container app' +
(setEnvironmentVariableOption === SetEnvironmentVariableOption.NoDotEnv ? ' because no .env files were detected. ' : '. ') +
'If you would like to update your environment variables later, try re-running the container app update or deploy command.'
(setEnvironmentVariableOption === SetEnvironmentVariableOption.NoDotEnv ? ' because no .env files were detected.' : '.')
);
ext.outputChannel.appendLog(logMessage);
} else {
} else if (setEnvironmentVariableOption === SetEnvironmentVariableOption.ProvideFile) {
context.activityChildren?.push(
new GenericTreeItem(undefined, {
contextValue: createUniversallyUniqueContextValue(['environmentVariablesListStepSuccessItem', setEnvironmentVariableOption, activitySuccessContext]),
label: localize('saveEnvVarsLabel', 'Save environment variable configuration'),
contextValue: createUniversallyUniqueContextValue(['environmentVariablesListStepSuccessItem', activitySuccessContext]),
label: localize('saveEnvVarsFileLabel', 'Save environment variables using provided .env file'),
iconPath: activitySuccessIcon
})
);
ext.outputChannel.appendLog(localize('savedEnvVarsFileMessage', 'Saved environment variables using provided .env file "{0}".', context.envPath));
} else if (setEnvironmentVariableOption === SetEnvironmentVariableOption.UseExisting) {
context.activityChildren?.push(
new GenericTreeItem(undefined, {
contextValue: createUniversallyUniqueContextValue(['environmentVariablesListStepSuccessItem', activitySuccessContext]),
label: localize('useExistingEnvVarsLabel', 'Use existing environment variable configuration'),
iconPath: activitySuccessIcon
})
);
ext.outputChannel.appendLog(localize('savedEnvVarsMessage', 'Saved environment variable configuration.'));
ext.outputChannel.appendLog(localize('useExistingEnvVarsMessage', 'Used existing environment variable configuration.'));
}
}
}
1 change: 1 addition & 0 deletions src/commands/image/imageSource/ImageSourceContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ export interface ImageSourceBaseContext extends RegistryCredentialsContext, ICon
imageSource?: ImageSource;
showQuickStartImage?: boolean;

containersIdx?: number;
image?: string;

envPath?: string;
Expand Down
Loading