-
Notifications
You must be signed in to change notification settings - Fork 522
/
NetCoreDebugHelper.ts
330 lines (288 loc) · 17.3 KB
/
NetCoreDebugHelper.ts
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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See LICENSE.md in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as fse from 'fs-extra';
import * as path from 'path';
import { DebugConfiguration, MessageItem, ProgressLocation, window } from 'vscode';
import { DialogResponses, IActionContext, UserCancelledError } from 'vscode-azureextensionui';
import { DockerOSType } from '../../docker/Common';
import { ext } from '../../extensionVariables';
import { localize } from '../../localize';
import { NetCoreTaskHelper, NetCoreTaskOptions } from '../../tasks/netcore/NetCoreTaskHelper';
import { ContainerTreeItem } from '../../tree/containers/ContainerTreeItem';
import { CommandLineBuilder } from '../../utils/commandLineBuilder';
import { getNetCoreProjectInfo } from '../../utils/netCoreUtils';
import { getDockerOSType, isArm64Mac } from '../../utils/osUtils';
import { pathNormalize } from '../../utils/pathNormalize';
import { PlatformOS } from '../../utils/platform';
import { unresolveWorkspaceFolder } from '../../utils/resolveVariables';
import { execAsync } from '../../utils/spawnAsync';
import { DebugHelper, DockerDebugContext, DockerDebugScaffoldContext, inferContainerName, ResolvedDebugConfiguration, resolveDockerServerReadyAction } from '../DebugHelper';
import { DockerAttachConfiguration, DockerDebugConfiguration } from '../DockerDebugConfigurationProvider';
import { exportCertificateIfNecessary, getHostSecretsFolders, trustCertificateIfNecessary } from './AspNetSslHelper';
import { installDebuggersIfNecessary, vsDbgInstallBasePath, VsDbgType } from './VsDbgHelper';
export interface NetCoreDebugOptions extends NetCoreTaskOptions {
appOutput?: string;
debuggerPath?: string;
}
export interface NetCoreDockerDebugConfiguration extends DebugConfiguration {
netCore?: NetCoreDebugOptions;
}
export interface NetCoreDebugScaffoldingOptions {
appProject?: string;
}
export class NetCoreDebugHelper implements DebugHelper {
public async provideDebugConfigurations(context: DockerDebugScaffoldContext, options?: NetCoreDebugScaffoldingOptions): Promise<DockerDebugConfiguration[]> {
options = options || {};
options.appProject = options.appProject || await NetCoreTaskHelper.inferAppProject(context.folder); // This method internally checks the user-defined input first
return [
{
name: 'Docker .NET Core Launch',
type: 'docker',
request: 'launch',
preLaunchTask: 'docker-run: debug',
netCore: {
appProject: unresolveWorkspaceFolder(options.appProject, context.folder)
}
}
];
}
public async resolveDebugConfiguration(context: DockerDebugContext, debugConfiguration: DockerDebugConfiguration): Promise<ResolvedDebugConfiguration | undefined> {
switch (debugConfiguration.request) {
case 'launch':
return this.resolveLaunchDebugConfiguration(context, debugConfiguration);
case 'attach':
return this.resolveAttachDebugConfiguration(context, debugConfiguration);
default:
throw Error(localize('vscode-docker.debug.netcore.unknownDebugRequest', 'Unknown request {0} specified in the debug config.', debugConfiguration.request));
}
}
private async resolveLaunchDebugConfiguration(context: DockerDebugContext, debugConfiguration: DockerDebugConfiguration): Promise<ResolvedDebugConfiguration | undefined> {
debugConfiguration.netCore = debugConfiguration.netCore || {};
debugConfiguration.netCore.appProject = await NetCoreTaskHelper.inferAppProject(context.folder, debugConfiguration.netCore); // This method internally checks the user-defined input first
const { configureSsl, containerName, platformOS } = await this.loadExternalInfo(context, debugConfiguration);
const appOutput = await this.inferAppOutput(debugConfiguration.netCore);
if (context.cancellationToken && context.cancellationToken.isCancellationRequested) {
// inferAppOutput is slow, give a chance to cancel
return undefined;
}
await this.acquireDebuggers(platformOS);
if (context.cancellationToken && context.cancellationToken.isCancellationRequested) {
// acquireDebuggers is slow, give a chance to cancel
return undefined;
}
if (configureSsl) {
await this.configureSsl(debugConfiguration, appOutput);
if (context.cancellationToken && context.cancellationToken.isCancellationRequested) {
// configureSsl is slow, give a chance to cancel
return undefined;
}
}
const additionalProbingPathsArgs = NetCoreDebugHelper.getAdditionalProbingPathsArgs(platformOS);
const containerAppOutput = NetCoreDebugHelper.getContainerAppOutput(debugConfiguration, appOutput, platformOS);
const dockerServerReadyAction = resolveDockerServerReadyAction(
debugConfiguration,
{
containerName: containerName,
pattern: '^\\s*Now listening on:\\s+(https?://\\S+)',
action: 'openExternally',
uriFormat: '%s://localhost:%s',
},
configureSsl || await NetCoreTaskHelper.isWebApp(debugConfiguration.netCore.appProject) // For .NET Core Console we won't create a DockerServerReadyAction unless at least part of one is user-provided
);
return {
...debugConfiguration, // Gets things like name, preLaunchTask, serverReadyAction, etc.
type: 'coreclr',
request: 'launch',
program: debugConfiguration.program || 'dotnet',
args: debugConfiguration.args || [additionalProbingPathsArgs, containerAppOutput].join(' '),
cwd: debugConfiguration.cwd || platformOS === 'Windows' ? 'C:\\app' : '/app',
dockerOptions: {
containerName: containerName,
dockerServerReadyAction: dockerServerReadyAction,
removeContainerAfterDebug: debugConfiguration.removeContainerAfterDebug
},
pipeTransport: {
pipeProgram: 'docker',
/* eslint-disable no-template-curly-in-string */
pipeArgs: ['exec', '-i', containerName, '${debuggerCommand}'],
pipeCwd: '${workspaceFolder}',
/* eslint-enable no-template-curly-in-string */
debuggerPath: platformOS === 'Windows' ?
'C:\\remote_debugger\\win7-x64\\latest\\vsdbg' :
'/remote_debugger/vsdbg',
quoteArgs: false,
},
sourceFileMap: debugConfiguration.sourceFileMap || {
'/app/Views': path.join(path.dirname(debugConfiguration.netCore.appProject), 'Views'),
}
};
}
private async resolveAttachDebugConfiguration(context: DockerDebugContext, debugConfiguration: DockerAttachConfiguration): Promise<ResolvedDebugConfiguration | undefined> {
// Get Container Name if missing
const containerName: string = debugConfiguration.containerName ?? await this.getContainerNameToAttach(context.actionContext);
let debuggerPath: string = debugConfiguration.netCore?.debuggerPath;
// If debugger path is not specified, then install the debugger if it doesn't exist in the container
if (!debuggerPath) {
const containerOS = await getDockerOSType(context.actionContext);
await this.acquireDebuggers(containerOS === 'windows' ? 'Windows' : 'Linux');
const debuggerDirectory = containerOS === 'windows' ? 'C:\\remote_debugger' : '/remote_debugger';
debuggerPath = containerOS === 'windows'
? path.win32.join(debuggerDirectory, 'win7-x64', 'latest', 'vsdbg.exe')
: path.posix.join(debuggerDirectory, 'vsdbg');
const isDebuggerInstalled: boolean = await this.isDebuggerInstalled(containerName, debuggerPath, containerOS);
if (!isDebuggerInstalled) {
await this.copyDebuggerToContainer(context.actionContext, containerName, debuggerDirectory, containerOS);
}
}
return {
...debugConfiguration, // Gets things like name, preLaunchTask, serverReadyAction, etc.
type: 'coreclr',
request: 'attach',
justMyCode: false,
// if processId is specified in the debugConfiguration, then it will take precedence
// and processName will be undefined.
processName: debugConfiguration.processId ? undefined : debugConfiguration.processName || 'dotnet',
pipeTransport: {
pipeProgram: 'docker',
pipeArgs: ['exec', '-i', containerName],
// eslint-disable-next-line no-template-curly-in-string
pipeCwd: '${workspaceFolder}',
debuggerPath: debuggerPath,
quoteArgs: false,
},
sourceFileMap: debugConfiguration.sourceFileMap || {
// eslint-disable-next-line no-template-curly-in-string
'/src': '${workspaceFolder}'
}
};
}
private async inferAppOutput(helperOptions: NetCoreDebugOptions): Promise<string> {
const projectInfo = await getNetCoreProjectInfo('GetProjectProperties', helperOptions.appProject);
if (projectInfo.length < 3) {
throw new Error(localize('vscode-docker.debug.netcore.unknownOutputPath', 'Unable to determine assembly output path.'));
}
return projectInfo[2]; // First line is assembly name, second is target framework, third+ are output path(s)
}
private async loadExternalInfo(context: DockerDebugContext, debugConfiguration: DockerDebugConfiguration): Promise<{ configureSsl: boolean, containerName: string, platformOS: PlatformOS }> {
const associatedTask = context.runDefinition;
return {
configureSsl: !!(associatedTask?.netCore?.configureSsl),
containerName: inferContainerName(debugConfiguration, context, context.folder.name),
platformOS: associatedTask?.dockerRun?.os || 'Linux',
};
}
private async acquireDebuggers(platformOS: PlatformOS): Promise<void> {
await window.withProgress(
{
location: ProgressLocation.Notification,
title: localize('vscode-docker.debug.netcore.acquiringDebuggers', 'Acquiring .NET Debugger...'),
}, async () => {
if (platformOS === 'Windows') {
await installDebuggersIfNecessary([{ runtime: 'win7-x64', version: 'latest' }]);
} else {
const debuggers: VsDbgType[] = [
{ runtime: 'linux-x64', version: 'latest' },
{ runtime: 'linux-musl-x64', version: 'latest' },
];
//
// NOTE: As OmniSharp doesn't yet support arm64 in general, we only install arm64 debuggers when
// on an arm64 Mac (e.g. M1), even though there may be other platforms that could theoretically
// run arm64 images. We are often asked to install the debugger before images are created or
// pulled, which means we don't know a-priori the architecture of the image, so we install all
// of them, just in case. Because we do not have a good way to distinguish between a Mac attached
// to its local (Linux-based) Docker host (where arm64/amd64 are valid) or a Mac attached to a
// remote (Linux-based) Docker host (where arm64 may *not* be valid), installing every debugger
// is really our only choice.
//
if (isArm64Mac()) {
debuggers.push(
{ runtime: 'linux-arm64', version: 'latest' },
{ runtime: 'linux-musl-arm64', version: 'latest' });
}
await installDebuggersIfNecessary(debuggers);
}
}
);
const debuggerScriptPath = path.join(ext.context.asAbsolutePath('resources'), 'netCore', 'vsdbg');
const destPath = path.join(vsDbgInstallBasePath, 'vsdbg');
await fse.copyFile(debuggerScriptPath, destPath);
await fse.chmod(destPath, 0o755); // Give all read and execute permissions
}
private async configureSsl(debugConfiguration: DockerDebugConfiguration, appOutput: string): Promise<void> {
const appOutputName = path.parse(appOutput).name;
const certificateExportPath = path.join(getHostSecretsFolders().hostCertificateFolder, `${appOutputName}.pfx`);
await trustCertificateIfNecessary();
await exportCertificateIfNecessary(debugConfiguration.netCore.appProject, certificateExportPath);
}
private static getAdditionalProbingPathsArgs(platformOS: PlatformOS): string {
const additionalProbingPaths = platformOS === 'Windows'
? [
'C:\\.nuget\\packages',
'C:\\.nuget\\fallbackpackages'
]
: [
'/root/.nuget/packages',
'/root/.nuget/fallbackpackages'
];
return additionalProbingPaths.map(probingPath => `--additionalProbingPath ${probingPath}`).join(' ');
}
private static getContainerAppOutput(debugConfiguration: DockerDebugConfiguration, appOutput: string, platformOS: PlatformOS): string {
const result = platformOS === 'Windows' ?
path.win32.join('C:\\app', appOutput) :
path.posix.join('/app', appOutput);
return pathNormalize(result, platformOS);
}
private async copyDebuggerToContainer(context: IActionContext, containerName: string, containerDebuggerDirectory: string, containerOS: DockerOSType): Promise<void> {
if (containerOS === 'windows') {
const containerInfo = await ext.dockerClient.inspectContainer(context, containerName);
if (containerInfo?.HostConfig?.Isolation === 'hyperv') {
context.errorHandling.suppressReportIssue = true;
throw new Error(localize('vscode-docker.debug.netcore.isolationNotSupported', 'Attaching a debugger to a Hyper-V container is not supported.'));
}
}
const yesItem: MessageItem = DialogResponses.yes;
const message = localize('vscode-docker.debug.netcore.attachingRequiresDebugger', 'Attaching to container requires .NET Core debugger in the container. Do you want to copy the debugger to the container?');
const install = (yesItem === await window.showInformationMessage(message, ...[DialogResponses.yes, DialogResponses.no]));
if (!install) {
throw new UserCancelledError();
}
if (containerOS === 'windows') {
await this.acquireDebuggers('Windows');
} else {
await this.acquireDebuggers('Linux');
}
const containerDebuggerPath = `${containerName}:${containerDebuggerDirectory}`;
await window.withProgress({
location: ProgressLocation.Notification,
title: localize('vscode-docker.debug.netcore.copyDebugger', 'Copying the .NET Core debugger to the container ({0} --> {1})...', vsDbgInstallBasePath, containerDebuggerDirectory),
}, async () => {
const command = CommandLineBuilder
.create('docker', 'cp')
.withQuotedArg(vsDbgInstallBasePath)
.withQuotedArg(containerDebuggerPath)
.build();
await execAsync(command);
});
}
private async isDebuggerInstalled(containerName: string, debuggerPath: string, containerOS: DockerOSType): Promise<boolean> {
const command = CommandLineBuilder
.create('docker', 'exec', '-i')
.withQuotedArg(containerName)
.withArg(containerOS === 'windows' ? 'cmd /C' : '/bin/sh -c')
.withQuotedArg(containerOS === 'windows' ? `IF EXIST "${debuggerPath}" (echo true) else (echo false)` : `if [ -f ${debuggerPath} ]; then echo true; fi;`)
.build();
const { stdout } = await execAsync(command);
return /true/ig.test(stdout);
}
private async getContainerNameToAttach(context: IActionContext): Promise<string> {
await ext.containersTree.refresh(context);
const containerItem: ContainerTreeItem = await ext.containersTree.showTreeItemPicker(ContainerTreeItem.runningContainerRegExp, {
...context,
noItemFoundErrorMessage: localize('vscode-docker.debug.netcore.noContainers', 'No running containers are available to attach.')
});
return containerItem.containerName;
}
}
export const netCoreDebugHelper = new NetCoreDebugHelper();