-
Notifications
You must be signed in to change notification settings - Fork 149
Expand file tree
/
Copy pathvalidatePreDebug.ts
More file actions
213 lines (184 loc) · 12.5 KB
/
validatePreDebug.ts
File metadata and controls
213 lines (184 loc) · 12.5 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
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { BlobServiceClient } from '@azure/storage-blob';
import { maskUserInfo, parseError, type IActionContext } from "@microsoft/vscode-azext-utils";
import * as semver from 'semver';
import * as vscode from 'vscode';
import { type ISetConnectionSettingContext } from '../commands/appSettings/connectionSettings/ISetConnectionSettingContext';
import { tryGetFunctionProjectRoot } from '../commands/createNewProject/verifyIsProject';
import { CodeAction, ConnectionKey, DurableBackend, localSettingsFileName, projectLanguageModelSetting, projectLanguageSetting, workerRuntimeKey } from "../constants";
import { MismatchBehavior, getLocalSettingsConnectionString, setLocalAppSetting } from "../funcConfig/local.settings";
import { getLocalFuncCoreToolsVersion } from '../funcCoreTools/getLocalFuncCoreToolsVersion';
import { validateFuncCoreToolsInstalled } from '../funcCoreTools/validateFuncCoreToolsInstalled';
import { localize } from '../localize';
import { durableUtils } from '../utils/durableUtils';
import { isPythonV2Plus } from '../utils/programmingModelUtils';
import { getDebugConfigs, isDebugConfigEqual } from '../vsCodeConfig/launch';
import { getWorkspaceSetting, tryGetFunctionsWorkerRuntimeForProject } from "../vsCodeConfig/settings";
import { getTasks } from '../vsCodeConfig/tasks';
import { getPreLaunchTaskChain } from './getPreLaunchTaskChain';
import { validateDTSConnectionPreDebug } from './storageProviders/validateDTSConnectionPreDebug';
import { validateNetheriteConnectionPreDebug } from './storageProviders/validateNetheriteConnectionPreDebug';
import { validateSQLConnectionPreDebug } from './storageProviders/validateSQLConnectionPreDebug';
import { validateStorageConnectionPreDebug } from './storageProviders/validateStorageConnectionPreDebug';
export interface IPreDebugValidateResult {
workspace: vscode.WorkspaceFolder;
shouldContinue: boolean;
}
export interface IPreDebugContext extends Omit<ISetConnectionSettingContext, 'projectPath'> {
projectPath?: string;
}
const emulatorTaskRegExp: RegExp = /azurite|emulator/i;
export async function preDebugValidate(actionContext: IActionContext, debugConfig: vscode.DebugConfiguration): Promise<IPreDebugValidateResult> {
const context: IPreDebugContext = Object.assign(actionContext, { action: CodeAction.Debug });
const workspace: vscode.WorkspaceFolder = getMatchingWorkspace(debugConfig);
let shouldContinue: boolean;
context.telemetry.properties.debugType = debugConfig.type;
// If one of the `preLaunchTasks` already handles starting emulators, assume the user is already on top of automating this part of the setup
const preLaunchTaskName: string | undefined = debugConfig.preLaunchTask;
const preLaunchTaskChain: string[] = typeof preLaunchTaskName === 'string' ? getPreLaunchTaskChain(getTasks(workspace), preLaunchTaskName) : [];
const hasEmulatorTask: boolean = preLaunchTaskChain.some(label => emulatorTaskRegExp.test(label));
const forceEmulatorValidation: boolean = !!getWorkspaceSetting<boolean>('forceEmulatorValidation', workspace.uri.fsPath);
const skipEmulatorValidation: boolean = hasEmulatorTask && !forceEmulatorValidation;
context.telemetry.properties.hasEmulatorTask = String(hasEmulatorTask);
context.telemetry.properties.forceEmulatorValidation = String(forceEmulatorValidation);
try {
context.telemetry.properties.lastValidateStep = 'funcInstalled';
const message: string = localize('installFuncTools', 'You must have the Azure Functions Core Tools installed to debug your local functions.');
shouldContinue = await validateFuncCoreToolsInstalled(context, message, workspace.uri.fsPath);
if (shouldContinue) {
context.telemetry.properties.lastValidateStep = 'getProjectRoot';
context.projectPath = await tryGetFunctionProjectRoot(context, workspace);
if (context.projectPath) {
const projectLanguage: string | undefined = getWorkspaceSetting(projectLanguageSetting, context.projectPath);
const projectLanguageModel: number | undefined = getWorkspaceSetting(projectLanguageModelSetting, context.projectPath);
const durableStorageType: DurableBackend | undefined = await durableUtils.getStorageTypeFromWorkspace(projectLanguage, context.projectPath);
context.telemetry.properties.projectLanguage = projectLanguage;
context.telemetry.properties.projectLanguageModel = projectLanguageModel?.toString();
context.telemetry.properties.durableStorageType = durableStorageType;
context.telemetry.properties.lastValidateStep = 'functionVersion';
shouldContinue = await validateFunctionVersion(context, projectLanguage, projectLanguageModel, workspace.uri.fsPath);
context.telemetry.properties.lastValidateStep = 'workerRuntime';
await validateWorkerRuntime(context, projectLanguage, context.projectPath);
if (!skipEmulatorValidation) {
switch (durableStorageType) {
case DurableBackend.DTS:
context.telemetry.properties.lastValidateStep = 'dtsConnection';
await validateDTSConnectionPreDebug(context, context.projectPath);
break;
case DurableBackend.Netherite:
context.telemetry.properties.lastValidateStep = 'netheriteConnection';
await validateNetheriteConnectionPreDebug(context, context.projectPath);
break;
case DurableBackend.SQL:
context.telemetry.properties.lastValidateStep = 'sqlDbConnection';
await validateSQLConnectionPreDebug(context, context.projectPath);
break;
case DurableBackend.Storage:
default:
}
context.telemetry.properties.lastValidateStep = 'azureWebJobsStorage';
await validateAzureWebJobsStorage(context, context.projectPath);
context.telemetry.properties.lastValidateStep = 'emulatorRunning';
shouldContinue = await validateEmulatorIsRunning(context, context.projectPath);
}
}
}
} catch (error) {
const pe = parseError(error);
if (pe.isUserCancelledError) {
shouldContinue = false;
} else {
// Don't block debugging for "unexpected" errors. The func cli might still work
shouldContinue = true;
context.telemetry.properties.preDebugValidateError = maskUserInfo(pe.message, []);
}
}
context.telemetry.properties.shouldContinue = String(shouldContinue);
return { workspace, shouldContinue };
}
function getMatchingWorkspace(debugConfig: vscode.DebugConfiguration): vscode.WorkspaceFolder {
if (vscode.workspace.workspaceFolders) {
for (const workspace of vscode.workspace.workspaceFolders) {
try {
const configs: vscode.DebugConfiguration[] = getDebugConfigs(workspace);
if (configs.some(c => isDebugConfigEqual(c, debugConfig))) {
return workspace;
}
} catch {
// ignore and try next workspace
}
}
}
throw new Error(localize('noDebug', 'Failed to find launch config matching name "{0}", request "{1}", and type "{2}".', debugConfig.name, debugConfig.request, debugConfig.type));
}
/**
* Ensure that that Python V2+ projects have an appropriate version of Functions tools installed.
*/
async function validateFunctionVersion(context: IActionContext, projectLanguage: string | undefined, projectLanguageModel: number | undefined, workspacePath: string): Promise<boolean> {
const validateTools = getWorkspaceSetting<boolean>('validateFuncCoreTools', workspacePath) !== false;
if (validateTools && isPythonV2Plus(projectLanguage, projectLanguageModel)) {
const version = await getLocalFuncCoreToolsVersion(context, workspacePath);
// NOTE: This is the latest version available as of this commit,
// but not necessarily the final "preview release" version.
// The Functions team is ok with using this version as the
// minimum bar.
const expectedVersionRange = '>=4.0.4742';
if (version && !semver.satisfies(version, expectedVersionRange)) {
const message: string = localize('invalidFunctionVersion', 'The version of installed Functions tools "{0}" is not sufficient for this project type ("{1}").', version, expectedVersionRange);
const debugAnyway: vscode.MessageItem = { title: localize('debugWithInvalidFunctionVersionAnyway', 'Debug anyway') };
const result: vscode.MessageItem = await context.ui.showWarningMessage(message, { modal: true, stepName: 'failedWithInvalidFunctionVersion' }, debugAnyway);
return result === debugAnyway;
}
}
return true;
}
/**
* Automatically add worker runtime setting since it's required to debug, but often gets deleted since it's stored in "local.settings.json" which isn't tracked in source control
*/
async function validateWorkerRuntime(context: IActionContext, projectLanguage: string | undefined, projectPath: string): Promise<void> {
const runtime: string | undefined = await tryGetFunctionsWorkerRuntimeForProject(context, projectLanguage, projectPath);
if (runtime) {
// Not worth handling mismatched runtimes since it's so unlikely
await setLocalAppSetting(context, projectPath, workerRuntimeKey, runtime, MismatchBehavior.DontChange);
}
}
async function validateAzureWebJobsStorage(context: IPreDebugContext, projectPath: string): Promise<void> {
// most programming models require the `AzureWebJobsStorage` connection now so we should just validate it for every runtime/trigger
await validateStorageConnectionPreDebug(context, projectPath);
}
/**
* If AzureWebJobsStorage is set, pings the emulator to make sure it's actually running
*/
async function validateEmulatorIsRunning(context: IActionContext, projectPath: string): Promise<boolean> {
const [azureWebJobsStorage, isEmulator] = await getLocalSettingsConnectionString(context, ConnectionKey.Storage, projectPath);
if (azureWebJobsStorage && isEmulator) {
try {
const client = BlobServiceClient.fromConnectionString(azureWebJobsStorage, { retryOptions: { maxTries: 1 } });
await client.getProperties();
} catch (_error) {
// azurite.azurite Check to see if azurite extension is installed
const azuriteExtension = vscode.extensions.getExtension('azurite.azurite');
const installOrRun: vscode.MessageItem = azuriteExtension ? { title: localize('runAzurite', 'Run Emulator') } : { title: localize('installAzurite', 'Install Azurite') };
const message: string = localize('failedToConnectEmulator', 'Failed to verify "{0}" connection specified in "{1}". Is the local emulator installed and running?', ConnectionKey.Storage, localSettingsFileName);
const learnMoreLink: string = process.platform === 'win32' ? 'https://aka.ms/AA4ym56' : 'https://aka.ms/AA4yef8';
const debugAnyway: vscode.MessageItem = { title: localize('debugAnyway', 'Debug anyway') };
const result: vscode.MessageItem = await context.ui.showWarningMessage(message, { learnMoreLink, modal: true, stepName: 'failedToConnectEmulator' }, debugAnyway, installOrRun);
if (result === installOrRun) {
if (azuriteExtension) {
await vscode.commands.executeCommand('azurite.start_blob');
await vscode.commands.executeCommand('azurite.start_table');
await vscode.commands.executeCommand('azurite.start_queue');
}
else {
await vscode.commands.executeCommand('workbench.extensions.installExtension', 'azurite.azurite');
}
return await validateEmulatorIsRunning(context, projectPath);
}
return result === debugAnyway;
}
}
return true;
}