-
Notifications
You must be signed in to change notification settings - Fork 149
Expand file tree
/
Copy pathpickFuncProcess.ts
More file actions
276 lines (243 loc) · 13.3 KB
/
pickFuncProcess.ts
File metadata and controls
276 lines (243 loc) · 13.3 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
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { sendRequestWithTimeout, type AzExtRequestPrepareOptions } from '@microsoft/vscode-azext-azureutils';
import { callWithTelemetryAndErrorHandling, parseError, UserCancelledError, type IActionContext } from '@microsoft/vscode-azext-utils';
import psTree, { type PS } from 'ps-tree';
import * as vscode from 'vscode';
import { hostStartTaskName } from '../constants';
import { preDebugValidate, type IPreDebugValidateResult } from '../debug/validatePreDebug';
import { ext } from '../extensionVariables';
import { buildPathToWorkspaceFolderMap, getFuncPortFromTaskOrProject, isFuncHostTask, resolveAndNormalizeCwd, runningFuncTaskMap, stopFuncTaskIfRunning, type IRunningFuncTask } from '../funcCoreTools/funcHostTask';
import { localize } from '../localize';
import { delay } from '../utils/delay';
import { requestUtils } from '../utils/requestUtils';
import { taskUtils } from '../utils/taskUtils';
import { getWindowsProcessTree, ProcessDataFlag, type IProcessInfo, type IWindowsProcessTree } from '../utils/windowsProcessTree';
import { getWorkspaceSetting } from '../vsCodeConfig/settings';
const funcTaskReadyEmitter = new vscode.EventEmitter<vscode.WorkspaceFolder>();
export const onDotnetFuncTaskReady = funcTaskReadyEmitter.event;
export function disposeFuncTaskReadyEmitter(): void {
funcTaskReadyEmitter.dispose();
}
/**
* Result returned from starting a function host process via the API.
*/
export interface IStartFuncProcessResult {
/**
* The process ID of the started function host.
*/
processId: string;
/**
* Whether the function host was successfully started.
*/
success: boolean;
/**
* Error message if the function host failed to start.
*/
error: string;
/**
* An async iterable stream of terminal output from the function host task.
* This stream provides real-time access to the output of the `func host start` command,
* allowing consumers to monitor host status, capture logs, and detect errors.
*
* The stream will be undefined if the host failed to start or if output streaming is not available.
* Consumers should iterate over the stream asynchronously to read output lines as they are produced.
* The stream remains active for the lifetime of the function host process.
*/
stream: AsyncIterable<string> | undefined;
}
export async function startFuncProcessFromApi(
buildPath: string,
args: string[],
env: { [key: string]: string }
): Promise<IStartFuncProcessResult> {
const result: IStartFuncProcessResult = {
processId: '',
success: false,
error: '',
stream: undefined
};
let funcHostStartCmd: string = 'func host start';
if (args) {
funcHostStartCmd += ` ${args.join(' ')}`;
}
await callWithTelemetryAndErrorHandling('azureFunctions.api.startFuncProcess', async (context: IActionContext) => {
try {
let workspaceFolder: vscode.WorkspaceFolder | undefined = buildPathToWorkspaceFolderMap.get(buildPath);
if (workspaceFolder === undefined) {
workspaceFolder = {
uri: vscode.Uri.parse(buildPath),
name: buildPath,
index: -1
};
}
await waitForPrevFuncTaskToStop(workspaceFolder);
buildPathToWorkspaceFolderMap.set(buildPath, workspaceFolder);
const funcTask = new vscode.Task({ type: `func ${buildPath}` },
workspaceFolder,
hostStartTaskName,
`func`,
new vscode.ShellExecution(funcHostStartCmd, {
cwd: buildPath,
env
}));
// funcTask.execution?.options.cwd to get build path for later reference
const taskInfo = await startFuncTask(context, workspaceFolder, buildPath, funcTask);
result.processId = await pickChildProcess(taskInfo);
result.success = true;
result.stream = taskInfo.stream;
} catch (err) {
const pError = parseError(err);
result.error = pError.message;
}
});
return result;
}
export async function pickFuncProcess(context: IActionContext, debugConfig: vscode.DebugConfiguration): Promise<string | undefined> {
const result: IPreDebugValidateResult = await preDebugValidate(context, debugConfig);
if (!result.shouldContinue) {
throw new UserCancelledError('preDebugValidate');
}
const preLaunchTaskName: string | undefined = debugConfig.preLaunchTask;
const tasks: vscode.Task[] = await vscode.tasks.fetchTasks();
const funcTask: vscode.Task | undefined = tasks.find(t => {
return t.scope === result.workspace && (preLaunchTaskName ? t.name === preLaunchTaskName : isFuncHostTask(t));
});
if (!funcTask) {
throw new Error(localize('noFuncTask', 'Failed to find "{0}" task.', preLaunchTaskName || hostStartTaskName));
}
const buildPath: string = (funcTask.execution as vscode.ShellExecution)?.options?.cwd || result.workspace.uri.fsPath;
await waitForPrevFuncTaskToStop(result.workspace, buildPath);
const taskInfo = await startFuncTask(context, result.workspace, buildPath, funcTask);
return await pickChildProcess(taskInfo);
}
async function waitForPrevFuncTaskToStop(workspaceFolder: vscode.WorkspaceFolder, buildPath?: string): Promise<void> {
await stopFuncTaskIfRunning(workspaceFolder, buildPath);
const normalizedBuildPath = resolveAndNormalizeCwd(workspaceFolder, buildPath);
const timeoutInSeconds: number = 30;
const maxTime: number = Date.now() + timeoutInSeconds * 1000;
while (Date.now() < maxTime) {
if (!runningFuncTaskMap.has(workspaceFolder, normalizedBuildPath)) {
return;
}
await delay(1000);
}
throw new Error(localize('failedToFindFuncHost', 'Failed to stop previous running Functions host within "{0}" seconds. Make sure the task has stopped before you debug again.', timeoutInSeconds));
}
async function startFuncTask(context: IActionContext, workspaceFolder: vscode.WorkspaceFolder, buildPath: string, funcTask: vscode.Task): Promise<IRunningFuncTask> {
const settingKey: string = 'pickProcessTimeout';
const settingValue: number | undefined = getWorkspaceSetting<number>(settingKey);
const timeoutInSeconds: number = Number(settingValue);
if (isNaN(timeoutInSeconds)) {
throw new Error(localize('invalidSettingValue', 'The setting "{0}" must be a number, but instead found "{1}".', settingKey, settingValue));
}
context.telemetry.properties.timeoutInSeconds = timeoutInSeconds.toString();
let taskError: Error | undefined;
const errorListener: vscode.Disposable = vscode.tasks.onDidEndTaskProcess((e: vscode.TaskProcessEndEvent) => {
if (e.execution.task.scope === workspaceFolder && e.exitCode !== 0) {
context.errorHandling.suppressReportIssue = true;
// Throw if _any_ task fails, not just funcTask (since funcTask often depends on build/clean tasks)
taskError = new Error(localize('taskFailed', 'Error exists after running preLaunchTask "{0}". View task output for more information.', e.execution.task.name, e.exitCode));
errorListener.dispose();
}
});
try {
// The "IfNotActive" part helps when the user starts, stops and restarts debugging quickly in succession. We want to use the already-active task to avoid two func tasks causing a port conflict error
// The most common case we hit this is if the "clean" or "build" task is running when we get here. It's unlikely the "func host start" task is active, since we would've stopped it in `waitForPrevFuncTaskToStop` above
await taskUtils.executeIfNotActive(funcTask);
const intervalMs: number = 500;
const funcPort: string = await getFuncPortFromTaskOrProject(context, funcTask, workspaceFolder);
let statusRequestTimeout: number = intervalMs;
const maxTime: number = Date.now() + timeoutInSeconds * 1000;
while (Date.now() < maxTime) {
if (taskError !== undefined) {
throw taskError;
}
const taskInfo: IRunningFuncTask | undefined = runningFuncTaskMap.get(workspaceFolder, resolveAndNormalizeCwd(workspaceFolder, buildPath));
if (taskInfo) {
for (const scheme of ['http', 'https']) {
const statusRequest: AzExtRequestPrepareOptions = { url: `${scheme}://localhost:${funcPort}/admin/host/status`, method: 'GET' };
if (scheme === 'https') {
statusRequest.rejectUnauthorized = false;
}
try {
// wait for status url to indicate functions host is running
const response = await sendRequestWithTimeout(context, statusRequest, statusRequestTimeout, undefined);
if (response.parsedBody.state.toLowerCase() === 'running') {
funcTaskReadyEmitter.fire(workspaceFolder);
return taskInfo;
}
} catch (error) {
if (requestUtils.isTimeoutError(error)) {
// Timeout likely means localhost isn't ready yet, but we'll increase the timeout each time it fails just in case it's a slow computer that can't handle a request that fast
statusRequestTimeout *= 2;
context.telemetry.measurements.maxStatusTimeout = statusRequestTimeout;
} else {
// ignore
}
}
}
}
await delay(intervalMs);
}
throw new Error(localize('failedToFindFuncHost', 'Failed to detect running Functions host within "{0}" seconds. You may want to adjust the "{1}" setting.', timeoutInSeconds, `${ext.prefix}.${settingKey}`));
} finally {
errorListener.dispose();
}
}
type OSAgnosticProcess = { command: string | undefined; pid: number | string };
/**
* Picks the child process that we want to use. Scenarios to keep in mind:
* 1. On Windows, the rootPid is almost always the parent PowerShell process
* 2. On Unix, the rootPid may be a wrapper around the main func exe if installed with npm
* 3. Starting with the .NET 5 worker, Windows sometimes has an inner process we _don't_ want like 'conhost.exe'
* The only processes we should want to attach to are the "func" process itself or a "dotnet" process running a dll, so we will pick the innermost one of those
*/
async function pickChildProcess(taskInfo: IRunningFuncTask): Promise<string> {
// Workaround for https://github.com/microsoft/vscode-azurefunctions/issues/2656
if (!isRunning(taskInfo.processId) && vscode.window.activeTerminal) {
const terminalPid = await vscode.window.activeTerminal.processId;
if (terminalPid) {
// NOTE: Intentionally updating the object so that `runningFuncTaskMap` is affected, too
taskInfo.processId = terminalPid;
}
}
const children: OSAgnosticProcess[] = process.platform === 'win32' ? await getWindowsChildren(taskInfo.processId) : await getUnixChildren(taskInfo.processId);
const child: OSAgnosticProcess | undefined = children.reverse().find(c => /(dotnet|func)(\.exe|)$/i.test(c.command || ''));
return child ? child.pid.toString() : String(taskInfo.processId);
}
// Looks like this bug was fixed, but never merged:
// https://github.com/indexzero/ps-tree/issues/18
type ActualUnixPS = PS & { COMM?: string };
async function getUnixChildren(pid: number): Promise<OSAgnosticProcess[]> {
const processes: ActualUnixPS[] = await new Promise((resolve, reject): void => {
psTree(pid, (error: Error | null, result: PS[]) => {
if (error) {
reject(error);
} else {
resolve(result);
}
});
});
return processes.map(c => { return { command: c.COMMAND || c.COMM, pid: c.PID }; });
}
async function getWindowsChildren(pid: number): Promise<OSAgnosticProcess[]> {
const windowsProcessTree: IWindowsProcessTree = getWindowsProcessTree();
const processes: (IProcessInfo[] | undefined) = await new Promise((resolve): void => {
windowsProcessTree.getProcessList(pid, resolve, ProcessDataFlag.None);
});
return (processes || []).map(c => { return { command: c.name, pid: c.pid }; });
}
function isRunning(pid: number): boolean {
try {
// https://nodejs.org/api/process.html#process_process_kill_pid_signal
// This method will throw an error if the target pid does not exist. As a special case, a signal of 0 can be used to test for the existence of a process.
// Even though the name of this function is process.kill(), it is really just a signal sender, like the kill system call.
process.kill(pid, 0);
return true;
} catch {
return false;
}
}