-
Notifications
You must be signed in to change notification settings - Fork 149
Expand file tree
/
Copy pathFunctionAppCreateStep.ts
More file actions
302 lines (265 loc) · 14.7 KB
/
FunctionAppCreateStep.ts
File metadata and controls
302 lines (265 loc) · 14.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { type NameValuePair, type Site, type SiteConfig, type WebSiteManagementClient } from '@azure/arm-appservice';
import { type Identity } from '@azure/arm-resources';
import { BlobServiceClient } from '@azure/storage-blob';
import { ParsedSite, WebsiteOS, type CustomLocation, type IAppServiceWizardContext } from '@microsoft/vscode-azext-azureappservice';
import { LocationListStep } from '@microsoft/vscode-azext-azureutils';
import { AzureWizardExecuteStepWithActivityOutput, maskUserInfo, parseError, randomUtils } from '@microsoft/vscode-azext-utils';
import { type AppResource } from '@microsoft/vscode-azext-utils/hostapi';
import { type Progress } from 'vscode';
import { FuncVersion, getMajorVersion } from '../../FuncVersion';
import { ConnectionKey, ProjectLanguage, contentConnectionStringKey, contentShareKey, extensionVersionKey, runFromPackageKey, webProvider } from '../../constants';
import { ext } from '../../extensionVariables';
import { localize } from '../../localize';
import { createWebSiteClient } from '../../utils/azureClients';
import { getRandomHexString } from '../../utils/fs';
import { createAzureWebJobsStorageManagedIdentitySettings } from '../../utils/managedIdentityUtils';
import { nonNullProp } from '../../utils/nonNull';
import { getStorageConnectionString } from '../appSettings/connectionSettings/getLocalConnectionSetting';
import { enableFileLogging } from '../logstream/enableFileLogging';
import { type FullFunctionAppStack, type IFlexFunctionAppWizardContext, type IFunctionAppWizardContext } from './IFunctionAppWizardContext';
import { type Sku } from './stacks/models/FlexSkuModel';
import { type FunctionAppRuntimeSettings, } from './stacks/models/FunctionAppStackModel';
export class FunctionAppCreateStep extends AzureWizardExecuteStepWithActivityOutput<IFunctionAppWizardContext> {
stepName: string = 'createFunctionAppStep';
public priority: number = 1000;
public async execute(context: IFlexFunctionAppWizardContext, _progress: Progress<{ message?: string; increment?: number }>): Promise<void> {
const os: WebsiteOS = nonNullProp(context, 'newSiteOS');
const stack: FullFunctionAppStack = nonNullProp(context, 'newSiteStack');
context.telemetry.properties.newSiteOS = os;
context.telemetry.properties.newSiteStack = stack.stack.value;
context.telemetry.properties.newSiteMajorVersion = stack.majorVersion.value;
context.telemetry.properties.newSiteMinorVersion = stack.minorVersion.value;
context.telemetry.properties.planSkuTier = context.plan?.sku?.tier;
const siteName: string = nonNullProp(context, 'newSiteName');
const rgName: string = nonNullProp(nonNullProp(context, 'resourceGroup'), 'name');
context.site = await this.createFunctionApp(context, rgName, siteName, stack);
context.activityResult = context.site as AppResource;
const site = new ParsedSite(context.site, context);
if (!site.isLinux) { // not supported on linux
try {
await enableFileLogging(context, site);
} catch (error) {
// optional part of creating function app, so not worth blocking on error
context.telemetry.properties.fileLoggingError = maskUserInfo(parseError(error).message, []);
}
}
}
public shouldExecute(context: IFunctionAppWizardContext): boolean {
return !context.site;
}
private async getNewSite(context: IFunctionAppWizardContext, stack: FullFunctionAppStack): Promise<Site> {
const site: Site = await this.createNewSite(context, stack);
site.reserved = context.newSiteOS === WebsiteOS.linux; // The secret property - must be set to true to make it a Linux plan. Confirmed by the team who owns this API.
if (context.customLocation) {
this.addCustomLocationProperties(site, context.customLocation);
}
// Always on setting added for App Service plans excluding the free tier https://github.com/microsoft/vscode-azurefunctions/issues/3037
if (context.plan?.sku?.family) {
const isNotFree = context.plan.sku.family.toLowerCase() !== 'f';
const isNotElasticPremium = context.plan.sku.family.toLowerCase() !== 'ep';
const isNotConsumption: boolean = context.plan.sku.family.toLowerCase() !== 'y';
if (isNotFree && isNotElasticPremium && isNotConsumption) {
nonNullProp(site, 'siteConfig').alwaysOn = true;
}
}
return site;
}
private addCustomLocationProperties(site: Site, customLocation: CustomLocation): void {
nonNullProp(site, 'siteConfig').alwaysOn = true;
site.extendedLocation = { name: customLocation.id, type: 'customLocation' };
}
private async getNewFlexSite(context: IFlexFunctionAppWizardContext, sku: Sku): Promise<Site> {
const site: Site = await this.createNewSite(context);
site.functionAppConfig = {
deployment: {
storage: {
type: 'blobContainer',
value: `${context.storageAccount?.primaryEndpoints?.blob}app-package-${context.newSiteName?.substring(0, 32)}-${randomUtils.getRandomHexString(7)}`,
authentication: {
userAssignedIdentityResourceId: undefined,
type: 'StorageAccountConnectionString',
storageAccountConnectionStringName: 'DEPLOYMENT_STORAGE_CONNECTION_STRING'
}
}
},
runtime: {
name: sku.functionAppConfigProperties.runtime.name,
version: sku.functionAppConfigProperties.runtime.version
},
scaleAndConcurrency: {
maximumInstanceCount: context.newFlexMaximumInstanceCount ?? sku.maximumInstanceCount.defaultValue,
instanceMemoryMB: context.newFlexInstanceMemoryMB ?? sku.instanceMemoryMB.find(im => im.isDefault)?.size ?? 2048,
alwaysReady: [],
triggers: undefined
},
}
return site;
}
private async createNewSite(context: IFunctionAppWizardContext, stack?: FullFunctionAppStack): Promise<Site> {
const location = await LocationListStep.getLocation(context, webProvider);
let identity: Identity | undefined = undefined;
if (context.managedIdentity) {
const userAssignedIdentities = {};
userAssignedIdentities[nonNullProp(context.managedIdentity, 'id')] =
{ principalId: context.managedIdentity?.principalId, clientId: context.managedIdentity?.clientId };
identity = { type: 'UserAssigned', userAssignedIdentities }
}
return {
name: context.newSiteName,
kind: getSiteKind(context),
location: nonNullProp(location, 'name'),
serverFarmId: context.plan?.id,
clientAffinityEnabled: false,
siteConfig: await this.getNewSiteConfig(context, stack),
identity
};
}
private async getNewSiteConfig(context: IFunctionAppWizardContext, stack?: FullFunctionAppStack): Promise<SiteConfig> {
let newSiteConfig: SiteConfig = {};
const storageConnectionString: string = (await getStorageConnectionString(context)).connectionString;
let appSettings: NameValuePair[] = [];
if (context.managedIdentity) {
appSettings.push(...createAzureWebJobsStorageManagedIdentitySettings(context));
} else {
appSettings.push({
name: ConnectionKey.Storage,
value: storageConnectionString
});
}
if (stack) {
const stackSettings: FunctionAppRuntimeSettings = nonNullProp(stack.minorVersion.stackSettings, context.newSiteOS === WebsiteOS.linux ? 'linuxRuntimeSettings' : 'windowsRuntimeSettings');
newSiteConfig = stackSettings.siteConfigPropertiesDictionary;
appSettings = appSettings.concat(
[{
name: extensionVersionKey,
value: '~' + getMajorVersion(context.version)
}],
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
...Object.entries(stackSettings.appSettingsDictionary).map(([name, value]) => { return { name, value }; }));
}
// This setting only applies for v1 https://github.com/Microsoft/vscode-azurefunctions/issues/640
if (context.version === FuncVersion.v1) {
appSettings.push({
name: 'AzureWebJobsDashboard',
value: storageConnectionString
});
}
const isElasticPremium: boolean = context.plan?.sku?.family?.toLowerCase() === 'ep';
const isConsumption: boolean = context.plan?.sku?.family?.toLowerCase() === 'y';
// no stack means it's a flex app
const isFlex: boolean = !stack;
if (isConsumption || isElasticPremium) {
// WEBSITE_CONTENT* settings are added for consumption/premium plans, but not dedicated
// https://github.com/microsoft/vscode-azurefunctions/issues/1702
appSettings.push({
name: contentConnectionStringKey,
value: storageConnectionString
});
appSettings.push({
name: contentShareKey,
value: getNewFileShareName(nonNullProp(context, 'newSiteName'))
});
} else if (isFlex) {
appSettings.push({
name: 'DEPLOYMENT_STORAGE_CONNECTION_STRING',
value: storageConnectionString
})
}
// This setting is not required, but we will set it since it has many benefits https://docs.microsoft.com/en-us/azure/azure-functions/run-functions-from-deployment-package
// That being said, it doesn't work on v1 C# Script https://github.com/Microsoft/vscode-azurefunctions/issues/684
// It also doesn't apply for Linux
if (context.newSiteOS === WebsiteOS.windows && !(context.language === ProjectLanguage.CSharpScript && context.version === FuncVersion.v1)) {
appSettings.push({
name: runFromPackageKey,
value: '1'
});
}
if (context.appInsightsComponent) {
appSettings.push({
name: 'APPLICATIONINSIGHTS_CONNECTION_STRING',
value: context.appInsightsComponent.connectionString
});
if (isElasticPremium && context.newSiteStack?.stack.value === 'java') {
// turn on full monitoring for Java on Elastic Premium
appSettings.push({
name: 'APPLICATIONINSIGHTS_ENABLE_AGENT',
value: 'true'
});
}
}
newSiteConfig.appSettings = appSettings;
return newSiteConfig;
}
async createFunctionApp(context: IFlexFunctionAppWizardContext, rgName: string, siteName: string, stack: FullFunctionAppStack): Promise<Site> {
const client: WebSiteManagementClient = await createWebSiteClient(context);
const site = context.newFlexSku ?
await this.getNewFlexSite(context, context.newFlexSku) :
await this.getNewSite(context, stack);
const result = await client.webApps.beginCreateOrUpdateAndWait(rgName, siteName, site);
if (context.newFlexSku) {
const storageConnectionString: string = (await getStorageConnectionString(context)).connectionString;
await tryCreateStorageContainer(result, storageConnectionString);
}
return result;
}
protected getTreeItemLabel(context: IFunctionAppWizardContext): string {
const siteName: string = nonNullProp(context, 'newSiteName');
return localize('creatingNewApp', 'Create new function app "{0}"', siteName);
}
protected getOutputLogSuccess(context: IFunctionAppWizardContext): string {
const siteName: string = nonNullProp(context, 'newSiteName');
return localize('createdNewApp', 'Successfully created new function app "{0}".', siteName);
}
protected getOutputLogFail(context: IFunctionAppWizardContext): string {
const siteName: string = nonNullProp(context, 'newSiteName');
return localize('failedToCreateNewApp', 'Failed to create new function app "{0}".', siteName);
}
protected getOutputLogProgress(context: IFunctionAppWizardContext): string {
const siteName: string = nonNullProp(context, 'newSiteName');
return localize('creatingNewApp', 'Creating new function app "{0}"...', siteName);
}
}
function getNewFileShareName(siteName: string): string {
const randomLetters: number = 6;
const maxFileShareNameLength: number = 63;
return siteName.toLowerCase().substr(0, maxFileShareNameLength - randomLetters) + getRandomHexString(randomLetters);
}
function getSiteKind(context: IAppServiceWizardContext): string {
let kind: string = context.newSiteKind;
if (context.newSiteOS === 'linux') {
kind += ',linux';
}
if (context.customLocation) {
kind += ',kubernetes';
}
return kind;
}
// storage container is needed for flex deployment, but it is not created automatically
async function tryCreateStorageContainer(site: Site, storageConnectionString: string): Promise<void> {
try {
const blobClient = BlobServiceClient.fromConnectionString(storageConnectionString);
const containerUrl: string | undefined = site.functionAppConfig?.deployment?.storage?.value;
if (containerUrl) {
const containerName = containerUrl.split('/').pop();
if (containerName) {
const client = blobClient.getContainerClient(containerName);
if (!await client.exists()) {
await blobClient.createContainer(containerName);
} else {
ext.outputChannel.appendLog(localize('deploymentStorageExists', 'Deployment storage container "{0}" already exists.', containerName));
return;
}
}
}
} catch (error) {
// ignore error, we will show a warning in the output channel
const parsedError = parseError(error);
ext.outputChannel.appendLog(localize('failedToCreateDeploymentStorage', 'Failed to create deployment storage container. {0}', parsedError.message));
}
ext.outputChannel.appendLog(localize('noDeploymentStorage', 'No deployment storage specified in function app.'));
return;
}