forked from DonJayamanne/pythonVSCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpythonDaemon.ts
More file actions
296 lines (291 loc) · 14.7 KB
/
pythonDaemon.ts
File metadata and controls
296 lines (291 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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
'use strict';
import { ChildProcess } from 'child_process';
import * as os from 'os';
import { Subject } from 'rxjs/Subject';
import * as util from 'util';
import { MessageConnection, NotificationType, RequestType, RequestType0 } from 'vscode-jsonrpc';
import { traceError, traceInfo, traceVerbose, traceWarning } from '../logger';
import { IDisposable } from '../types';
import { createDeferred, Deferred } from '../utils/async';
import { noop } from '../utils/misc';
import { Architecture } from '../utils/platform';
import { parsePythonVersion } from '../utils/version';
import {
ExecutionResult,
InterpreterInfomation,
IPythonDaemonExecutionService,
IPythonExecutionService,
ObservableExecutionResult,
Output,
PythonVersionInfo,
SpawnOptions,
StdErrError
} from './types';
type ErrorResponse = { error?: string };
export class ConnectionClosedError extends Error {
constructor(public readonly message: string){
super();
}
}
export class PythonDaemonExecutionService implements IPythonDaemonExecutionService {
private connectionClosedMessage: string = '';
private outputObservale = new Subject<Output<string>>();
// tslint:disable-next-line: no-any
private readonly connectionClosedDeferred: Deferred<any>;
private disposables: IDisposable[] = [];
public get isAlive(): boolean {
return this.connectionClosedMessage === '';
}
constructor(
protected readonly pythonExecutionService: IPythonExecutionService,
protected readonly pythonPath: string,
public readonly proc: ChildProcess,
public readonly connection: MessageConnection
) {
// tslint:disable-next-line: no-any
this.connectionClosedDeferred = createDeferred<any>();
// This promise gets used conditionally, if it doesn't get used, and the promise is rejected,
// then node logs errors. We don't want that, hence add a dummy error handler.
this.connectionClosedDeferred.promise.catch(noop);
this.monitorConnection();
}
public dispose() {
try {
// The daemon should die as a result of this.
this.connection.sendNotification(new NotificationType('exit'));
} catch {
noop();
}
this.disposables.forEach(item => item.dispose());
}
public async getInterpreterInformation(): Promise<InterpreterInfomation | undefined> {
this.throwIfRPCConnectionIsDead();
try {
type InterpreterInfoResponse = ErrorResponse & { versionInfo: PythonVersionInfo; sysPrefix: string; sysVersion: string; is64Bit: boolean };
const request = new RequestType0<InterpreterInfoResponse, void, void>('get_interpreter_information');
const response = await this.sendRequestWithoutArgs(request);
const versionValue = response.versionInfo.length === 4 ? `${response.versionInfo.slice(0, 3).join('.')}-${response.versionInfo[3]}` : response.versionInfo.join('.');
return {
architecture: response.is64Bit ? Architecture.x64 : Architecture.x86,
path: this.pythonPath,
version: parsePythonVersion(versionValue),
sysVersion: response.sysVersion,
sysPrefix: response.sysPrefix
};
} catch {
return this.pythonExecutionService.getInterpreterInformation();
}
}
public async getExecutablePath(): Promise<string> {
this.throwIfRPCConnectionIsDead();
try {
type ExecutablePathResponse = ErrorResponse & { path: string };
const request = new RequestType0<ExecutablePathResponse, void, void>('get_executable');
const response = await this.sendRequestWithoutArgs(request);
if (response.error) {
throw new Error(response.error);
}
return response.path;
} catch {
return this.pythonExecutionService.getExecutablePath();
}
}
public async isModuleInstalled(moduleName: string): Promise<boolean> {
this.throwIfRPCConnectionIsDead();
try {
type ModuleInstalledResponse = ErrorResponse & { exists: boolean };
const request = new RequestType<{ module_name: string }, ModuleInstalledResponse, void, void>('is_module_installed');
const response = await this.sendRequest(request, { module_name: moduleName });
if (response.error) {
throw new Error(response.error);
}
return response.exists;
} catch {
return this.pythonExecutionService.isModuleInstalled(moduleName);
}
}
public execObservable(args: string[], options: SpawnOptions): ObservableExecutionResult<string> {
this.throwIfRPCConnectionIsDead();
if (this.canExecFileUsingDaemon(args, options)) {
return this.execFileWithDaemonAsObservable(args[0], args.slice(1), options);
} else {
return this.pythonExecutionService.execObservable(args, options);
}
}
public execModuleObservable(moduleName: string, args: string[], options: SpawnOptions): ObservableExecutionResult<string> {
this.throwIfRPCConnectionIsDead();
if (this.canExecModuleUsingDaemon(moduleName, args, options)) {
return this.execModuleWithDaemonAsObservable(moduleName, args, options);
} else {
return this.pythonExecutionService.execModuleObservable(moduleName, args, options);
}
}
public async exec(args: string[], options: SpawnOptions): Promise<ExecutionResult<string>> {
this.throwIfRPCConnectionIsDead();
if (this.canExecFileUsingDaemon(args, options)) {
return this.execFileWithDaemon(args[0], args.slice(1), options);
} else {
return this.pythonExecutionService.exec(args, options);
}
}
public async execModule(moduleName: string, args: string[], options: SpawnOptions): Promise<ExecutionResult<string>> {
this.throwIfRPCConnectionIsDead();
if (this.canExecModuleUsingDaemon(moduleName, args, options)) {
return this.execModuleWithDaemon(moduleName, args, options);
} else {
return this.pythonExecutionService.execModule(moduleName, args, options);
}
}
protected canExecFileUsingDaemon(args: string[], options: SpawnOptions): boolean {
return args[0].toLowerCase().endsWith('.py') && this.areOptionsSupported(options);
}
protected canExecModuleUsingDaemon(_moduleName: string, _args: string[], options: SpawnOptions): boolean {
return this.areOptionsSupported(options);
}
protected areOptionsSupported(options: SpawnOptions): boolean {
const daemonSupportedSpawnOptions: (keyof SpawnOptions)[] = ['cwd', 'env', 'throwOnStdErr', 'token', 'encoding', 'mergeStdOutErr'];
// tslint:disable-next-line: no-any
return Object.keys(options).every(item => daemonSupportedSpawnOptions.indexOf(item as any) >= 0);
}
private sendRequestWithoutArgs<R, E, RO>(type: RequestType0<R, E, RO>): Thenable<R> {
return Promise.race([this.connection.sendRequest(type), this.connectionClosedDeferred.promise]);
}
private sendRequest<P, R, E, RO>(type: RequestType<P, R, E, RO>, params?: P): Thenable<R> {
// Throw an error if the connection has been closed.
return Promise.race([this.connection.sendRequest(type, params), this.connectionClosedDeferred.promise]);
}
/**
* Process the response.
*
* @private
* @param {{ error?: string | undefined; stdout: string; stderr?: string }} response
* @param {SpawnOptions} options
* @memberof PythonDaemonExecutionService
*/
private processResponse(response: { error?: string | undefined; stdout: string; stderr?: string }, options: SpawnOptions) {
if (response.error) {
throw new StdErrError(`Failed to execute using the daemon, ${response.error}`);
}
// Throw an error if configured to do so if there's any output in stderr.
if (response.stderr && options.throwOnStdErr) {
throw new StdErrError(response.stderr);
}
// Merge stdout and stderr into on if configured to do so.
if (response.stderr && options.mergeStdOutErr) {
response.stdout = `${response.stdout || ''}${os.EOL}${response.stderr}`;
}
}
private async execFileWithDaemon(fileName: string, args: string[], options: SpawnOptions): Promise<ExecutionResult<string>> {
type ExecResponse = ErrorResponse & { stdout: string; stderr?: string };
// tslint:disable-next-line: no-any
const request = new RequestType<{ file_name: string; args: string[]; cwd?: string; env?: any }, ExecResponse, void, void>('exec_file');
const response = await this.sendRequest(request, { file_name: fileName, args, cwd: options.cwd, env: options.env });
this.processResponse(response, options);
return response;
}
private execFileWithDaemonAsObservable(fileName: string, args: string[], options: SpawnOptions): ObservableExecutionResult<string> {
return this.execAsObservable({ fileName }, args, options);
}
private async execModuleWithDaemon(moduleName: string, args: string[], options: SpawnOptions): Promise<ExecutionResult<string>> {
type ExecResponse = ErrorResponse & { stdout: string; stderr?: string };
// tslint:disable-next-line: no-any
const request = new RequestType<{ module_name: string; args: string[]; cwd?: string; env?: any }, ExecResponse, void, void>('exec_module');
const response = await this.sendRequest(request, { module_name: moduleName, args, cwd: options.cwd, env: options.env });
this.processResponse(response, options);
return response;
}
private execModuleWithDaemonAsObservable(moduleName: string, args: string[], options: SpawnOptions): ObservableExecutionResult<string> {
return this.execAsObservable({ moduleName }, args, options);
}
private execAsObservable(moduleOrFile: { moduleName: string } | { fileName: string }, args: string[], options: SpawnOptions): ObservableExecutionResult<string> {
const subject = new Subject<Output<string>>();
const start = async () => {
type ExecResponse = ErrorResponse & { stdout: string; stderr?: string };
let response: ExecResponse;
if ('fileName' in moduleOrFile) {
// tslint:disable-next-line: no-any
const request = new RequestType<{ file_name: string; args: string[]; cwd?: string; env?: any }, ExecResponse, void, void>('exec_file_observable');
response = await this.sendRequest(request, { file_name: moduleOrFile.fileName, args, cwd: options.cwd, env: options.env });
} else {
// tslint:disable-next-line: no-any
const request = new RequestType<{ module_name: string; args: string[]; cwd?: string; env?: any }, ExecResponse, void, void>('exec_module_observable');
response = await this.sendRequest(request, { module_name: moduleOrFile.moduleName, args, cwd: options.cwd, env: options.env });
}
// Might not get a response object back, as its observable.
if (response && response.error){
throw new StdErrError(response.error);
}
};
let stdErr = '';
this.proc.stderr.on('data', (output: string | Buffer) => (stdErr += output.toString()));
// Wire up stdout/stderr.
const subscription = this.outputObservale.subscribe(out => {
if (out.source === 'stderr' && options.throwOnStdErr) {
subject.error(new StdErrError(out.out));
} else if (out.source === 'stderr' && options.mergeStdOutErr) {
subject.next({ source: 'stdout', out: out.out });
} else {
subject.next(out);
}
});
start()
.catch(ex => {
const errorMsg = `Failed to run ${'fileName' in moduleOrFile ? moduleOrFile.fileName : moduleOrFile.moduleName} as observable with args ${args.join(' ')}`;
traceError(errorMsg, ex);
subject.next({ source: 'stderr', out: `${errorMsg}\n${stdErr}` });
subject.error(ex);
})
.finally(() => {
// Wait until all messages are received.
setTimeout(() => {
subscription.unsubscribe();
subject.complete();
}, 100);
})
.ignoreErrors();
return {
proc: this.proc,
dispose: () => this.dispose(),
out: subject
};
}
private monitorConnection() {
// tslint:disable-next-line: no-any
const logConnectionStatus = (msg: string, ex?: any) => {
this.connectionClosedMessage += msg + (ex ? `, With Error: ${util.format(ex)}` : '');
this.connectionClosedDeferred.reject(new ConnectionClosedError(this.connectionClosedMessage));
traceWarning(msg);
if (ex) {
traceError('Connection errored', ex);
}
};
this.disposables.push(this.connection.onClose(() => logConnectionStatus('Daemon Connection Closed')));
this.disposables.push(this.connection.onDispose(() => logConnectionStatus('Daemon Connection disposed')));
this.disposables.push(this.connection.onError(ex => logConnectionStatus('Daemon Connection errored', ex)));
// this.proc.on('error', error => logConnectionStatus('Daemon Processed died with error', error));
this.proc.on('exit', code => logConnectionStatus('Daemon Processed died with exit code', code));
// Wire up stdout/stderr.
const OuputNotification = new NotificationType<Output<string>, void>('output');
this.connection.onNotification(OuputNotification, output => this.outputObservale.next(output));
const logNotification = new NotificationType<{level: 'WARN'|'WARNING'|'INFO'|'DEBUG'|'NOTSET'; msg: string}, void>('log');
this.connection.onNotification(logNotification, output => {
if (output.level === 'DEBUG' || output.level === 'NOTSET'){
traceVerbose(output.msg);
} else if (output.level === 'INFO'){
traceInfo(output.msg);
} else if (output.level === 'WARN' || output.level === 'WARNING') {
traceWarning(output.msg);
} else {
traceError(output.msg);
}
});
this.connection.onUnhandledNotification(traceError);
}
private throwIfRPCConnectionIsDead() {
if (this.connectionClosedMessage) {
throw new Error(this.connectionClosedMessage);
}
}
}