-
Notifications
You must be signed in to change notification settings - Fork 677
/
server.ts
611 lines (485 loc) · 20.5 KB
/
server.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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { EventEmitter } from 'events';
import { ChildProcess, exec } from 'child_process';
import { ReadLine, createInterface } from 'readline';
import { launchOmniSharp } from './launcher';
import { Options } from './options';
import { Logger } from '../logger';
import { DelayTracker } from './delayTracker';
import { LaunchTarget, findLaunchTargets } from './launcher';
import { Request, RequestQueueCollection } from './requestQueue';
import TelemetryReporter from 'vscode-extension-telemetry';
import * as os from 'os';
import * as path from 'path';
import * as protocol from './protocol';
import * as vscode from 'vscode';
enum ServerState {
Starting,
Started,
Stopped
}
module Events {
export const StateChanged = 'stateChanged';
export const StdOut = 'stdout';
export const StdErr = 'stderr';
export const Error = 'Error';
export const ServerError = 'ServerError';
export const UnresolvedDependencies = 'UnresolvedDependencies';
export const PackageRestoreStarted = 'PackageRestoreStarted';
export const PackageRestoreFinished = 'PackageRestoreFinished';
export const ProjectChanged = 'ProjectChanged';
export const ProjectAdded = 'ProjectAdded';
export const ProjectRemoved = 'ProjectRemoved';
export const MsBuildProjectDiagnostics = 'MsBuildProjectDiagnostics';
export const TestMessage = 'TestMessage';
export const BeforeServerInstall = 'BeforeServerInstall';
export const BeforeServerStart = 'BeforeServerStart';
export const ServerStart = 'ServerStart';
export const ServerStop = 'ServerStop';
export const MultipleLaunchTargets = 'server:MultipleLaunchTargets';
export const Started = 'started';
}
const TelemetryReportingDelay = 2 * 60 * 1000; // two minutes
export class OmniSharpServer {
private static _nextId = 1;
private _debugMode: boolean = false;
private _readLine: ReadLine;
private _disposables: vscode.Disposable[] = [];
private _reporter: TelemetryReporter;
private _delayTrackers: { [requestName: string]: DelayTracker };
private _telemetryIntervalId: NodeJS.Timer = undefined;
private _eventBus = new EventEmitter();
private _state: ServerState = ServerState.Stopped;
private _launchTarget: LaunchTarget;
private _requestQueue: RequestQueueCollection;
private _channel: vscode.OutputChannel;
private _logger: Logger;
private _isDebugEnable: boolean = false;
private _serverProcess: ChildProcess;
private _options: Options;
constructor(reporter: TelemetryReporter) {
this._reporter = reporter;
this._channel = vscode.window.createOutputChannel('OmniSharp Log');
this._logger = new Logger(message => this._channel.append(message));
const logger = this._debugMode
? this._logger
: new Logger(message => { });
this._requestQueue = new RequestQueueCollection(logger, 8, request => this._makeRequest(request));
}
public isRunning(): boolean {
return this._state === ServerState.Started;
}
private _getState(): ServerState {
return this._state;
}
private _setState(value: ServerState): void {
if (typeof value !== 'undefined' && value !== this._state) {
this._state = value;
this._fireEvent(Events.StateChanged, this._state);
}
}
private _recordRequestDelay(requestName: string, elapsedTime: number) {
let tracker = this._delayTrackers[requestName];
if (!tracker) {
tracker = new DelayTracker(requestName);
this._delayTrackers[requestName] = tracker;
}
tracker.reportDelay(elapsedTime);
}
private _reportTelemetry() {
const delayTrackers = this._delayTrackers;
for (const requestName in delayTrackers) {
const tracker = delayTrackers[requestName];
const eventName = 'omnisharp' + requestName;
if (tracker.hasMeasures()) {
const measures = tracker.getMeasures();
tracker.clearMeasures();
this._reporter.sendTelemetryEvent(eventName, null, measures);
}
}
}
public getSolutionPathOrFolder(): string {
return this._launchTarget
? this._launchTarget.target
: undefined;
}
public getChannel(): vscode.OutputChannel {
return this._channel;
}
public isDebugEnable(): boolean {
return this._isDebugEnable;
}
// --- eventing
public onStdout(listener: (e: string) => any, thisArg?: any) {
return this._addListener(Events.StdOut, listener, thisArg);
}
public onStderr(listener: (e: string) => any, thisArg?: any) {
return this._addListener(Events.StdErr, listener, thisArg);
}
public onError(listener: (e: protocol.ErrorMessage) => any, thisArg?: any) {
return this._addListener(Events.Error, listener, thisArg);
}
public onServerError(listener: (err: any) => any, thisArg?: any) {
return this._addListener(Events.ServerError, listener, thisArg);
}
public onUnresolvedDependencies(listener: (e: protocol.UnresolvedDependenciesMessage) => any, thisArg?: any) {
return this._addListener(Events.UnresolvedDependencies, listener, thisArg);
}
public onBeforePackageRestore(listener: () => any, thisArg?: any) {
return this._addListener(Events.PackageRestoreStarted, listener, thisArg);
}
public onPackageRestore(listener: () => any, thisArg?: any) {
return this._addListener(Events.PackageRestoreFinished, listener, thisArg);
}
public onProjectChange(listener: (e: protocol.ProjectInformationResponse) => any, thisArg?: any) {
return this._addListener(Events.ProjectChanged, listener, thisArg);
}
public onProjectAdded(listener: (e: protocol.ProjectInformationResponse) => any, thisArg?: any) {
return this._addListener(Events.ProjectAdded, listener, thisArg);
}
public onProjectRemoved(listener: (e: protocol.ProjectInformationResponse) => any, thisArg?: any) {
return this._addListener(Events.ProjectRemoved, listener, thisArg);
}
public onMsBuildProjectDiagnostics(listener: (e: protocol.MSBuildProjectDiagnostics) => any, thisArg?: any) {
return this._addListener(Events.MsBuildProjectDiagnostics, listener, thisArg);
}
public onTestMessage(listener: (e: protocol.V2.TestMessageEvent) => any, thisArg?: any) {
return this._addListener(Events.TestMessage, listener, thisArg);
}
public onBeforeServerInstall(listener: () => any) {
return this._addListener(Events.BeforeServerInstall, listener);
}
public onBeforeServerStart(listener: (e: string) => any) {
return this._addListener(Events.BeforeServerStart, listener);
}
public onServerStart(listener: (e: string) => any) {
return this._addListener(Events.ServerStart, listener);
}
public onServerStop(listener: () => any) {
return this._addListener(Events.ServerStop, listener);
}
public onMultipleLaunchTargets(listener: (targets: LaunchTarget[]) => any, thisArg?: any) {
return this._addListener(Events.MultipleLaunchTargets, listener, thisArg);
}
public onOmnisharpStart(listener: () => any) {
return this._addListener(Events.Started, listener);
}
private _addListener(event: string, listener: (e: any) => any, thisArg?: any): vscode.Disposable {
listener = thisArg ? listener.bind(thisArg) : listener;
this._eventBus.addListener(event, listener);
return new vscode.Disposable(() => this._eventBus.removeListener(event, listener));
}
protected _fireEvent(event: string, args: any): void {
this._eventBus.emit(event, args);
}
// --- start, stop, and connect
private _start(launchTarget: LaunchTarget): Promise<void> {
this._setState(ServerState.Starting);
this._launchTarget = launchTarget;
const solutionPath = launchTarget.target;
const cwd = path.dirname(solutionPath);
this._options = Options.Read();
let args = [
'-s', solutionPath,
'--hostPID', process.pid.toString(),
'--stdio',
'DotNet:enablePackageRestore=false',
'--encoding', 'utf-8',
'--loglevel', this._options.loggingLevel
];
if (this._options.waitForDebugger === true) {
args.push('--debug');
}
this._logger.appendLine(`Starting OmniSharp server at ${new Date().toLocaleString()}`);
this._logger.increaseIndent();
this._logger.appendLine(`Target: ${solutionPath}`);
this._logger.decreaseIndent();
this._logger.appendLine();
this._fireEvent(Events.BeforeServerStart, solutionPath);
return launchOmniSharp(cwd, args).then(value => {
if (value.usingMono) {
this._logger.appendLine(`OmniSharp server started wth Mono`);
}
else {
this._logger.appendLine(`OmniSharp server started`);
}
this._logger.increaseIndent();
this._logger.appendLine(`Path: ${value.command}`);
this._logger.appendLine(`PID: ${value.process.pid}`);
this._logger.decreaseIndent();
this._logger.appendLine();
this._serverProcess = value.process;
this._delayTrackers = {};
this._setState(ServerState.Started);
this._fireEvent(Events.ServerStart, solutionPath);
return this._doConnect();
}).then(() => {
return vscode.commands.getCommands()
.then(commands => {
if (commands.find(c => c === 'vscode.startDebug')) {
this._isDebugEnable = true;
}
});
}).then(() => {
// Start telemetry reporting
this._telemetryIntervalId = setInterval(() => this._reportTelemetry(), TelemetryReportingDelay);
}).then(() => {
this._requestQueue.drain();
}).catch(err => {
this._fireEvent(Events.ServerError, err);
return this.stop();
});
}
public stop(): Promise<void> {
while (this._disposables.length) {
this._disposables.pop().dispose();
}
let cleanupPromise: Promise<void>;
if (this._telemetryIntervalId !== undefined) {
// Stop reporting telemetry
clearInterval(this._telemetryIntervalId);
this._telemetryIntervalId = undefined;
this._reportTelemetry();
}
if (!this._serverProcess) {
// nothing to kill
cleanupPromise = Promise.resolve();
}
else if (process.platform === 'win32') {
// when killing a process in windows its child
// processes are *not* killed but become root
// processes. Therefore we use TASKKILL.EXE
cleanupPromise = new Promise<void>((resolve, reject) => {
const killer = exec(`taskkill /F /T /PID ${this._serverProcess.pid}`, (err, stdout, stderr) => {
if (err) {
return reject(err);
}
});
killer.on('exit', resolve);
killer.on('error', reject);
});
}
else {
// Kill Unix process
this._serverProcess.kill('SIGTERM');
cleanupPromise = Promise.resolve();
}
return cleanupPromise.then(() => {
this._serverProcess = null;
this._setState(ServerState.Stopped);
this._fireEvent(Events.ServerStop, this);
});
}
public restart(launchTarget: LaunchTarget = this._launchTarget): Promise<void> {
if (launchTarget) {
return this.stop().then(() => {
this._start(launchTarget);
});
}
}
public autoStart(preferredPath: string): Thenable<void> {
return findLaunchTargets().then(launchTargets => {
// If there aren't any potential launch targets, we create file watcher and try to
// start the server again once a *.sln, *.csproj, project.json or CSX file is created.
if (launchTargets.length === 0) {
return new Promise<void>((resolve, reject) => {
// 1st watch for files
let watcher = vscode.workspace.createFileSystemWatcher('{**/*.sln,**/*.csproj,**/project.json,**/*.csx}',
/*ignoreCreateEvents*/ false,
/*ignoreChangeEvents*/ true,
/*ignoreDeleteEvents*/ true);
watcher.onDidCreate(uri => {
watcher.dispose();
resolve();
});
}).then(() => {
// 2nd try again
return this.autoStart(preferredPath);
});
}
// If there's more than one launch target, we start the server if one of the targets
// matches the preferred path. Otherwise, we fire the "MultipleLaunchTargets" event,
// which is handled in status.ts to display the launch target selector.
if (launchTargets.length > 1 && preferredPath) {
for (let launchTarget of launchTargets) {
if (launchTarget.target === preferredPath) {
// start preferred path
return this.restart(launchTarget);
}
}
this._fireEvent(Events.MultipleLaunchTargets, launchTargets);
return Promise.reject<void>(undefined);
}
// If there's only one target, just start
return this.restart(launchTargets[0]);
});
}
// --- requests et al
public makeRequest<TResponse>(command: string, data?: any, token?: vscode.CancellationToken): Promise<TResponse> {
if (this._getState() !== ServerState.Started) {
return Promise.reject<TResponse>('server has been stopped or not started');
}
let startTime: number;
let request: Request;
let promise = new Promise<TResponse>((resolve, reject) => {
startTime = Date.now();
request = {
command,
data,
onSuccess: value => resolve(value),
onError: err => reject(err)
};
this._requestQueue.enqueue(request);
});
if (token) {
token.onCancellationRequested(() => {
this._requestQueue.cancelRequest(request);
});
}
return promise.then(response => {
let endTime = Date.now();
let elapsedTime = endTime - startTime;
this._recordRequestDelay(command, elapsedTime);
return response;
});
}
private _doConnect(): Promise<void> {
this._serverProcess.stderr.on('data', (data: any) => {
this._fireEvent('stderr', String(data));
});
this._readLine = createInterface({
input: this._serverProcess.stdout,
output: this._serverProcess.stdin,
terminal: false
});
const promise = new Promise<void>((resolve, reject) => {
let listener: vscode.Disposable;
// Convert the timeout from the seconds to milliseconds, which is required by setTimeout().
const timeoutDuration = this._options.projectLoadTimeout * 1000;
// timeout logic
const handle = setTimeout(() => {
if (listener) {
listener.dispose();
}
reject(new Error("OmniSharp server load timed out. Use the 'omnisharp.projectLoadTimeout' setting to override the default delay (one minute)."));
}, timeoutDuration);
// handle started-event
listener = this.onOmnisharpStart(() => {
if (listener) {
listener.dispose();
}
clearTimeout(handle);
resolve();
});
});
const lineReceived = this._onLineReceived.bind(this);
this._readLine.addListener('line', lineReceived);
this._disposables.push(new vscode.Disposable(() => {
this._readLine.removeListener('line', lineReceived);
}));
return promise;
}
private _onLineReceived(line: string) {
if (line[0] !== '{') {
this._logger.appendLine(line);
return;
}
let packet: protocol.WireProtocol.Packet;
try {
packet = JSON.parse(line);
}
catch (err) {
// This isn't JSON
return;
}
if (!packet.Type) {
// Bogus packet
return;
}
switch (packet.Type) {
case 'response':
this._handleResponsePacket(<protocol.WireProtocol.ResponsePacket>packet);
break;
case 'event':
this._handleEventPacket(<protocol.WireProtocol.EventPacket>packet);
break;
default:
console.warn(`Unknown packet type: ${packet.Type}`);
break;
}
}
private _handleResponsePacket(packet: protocol.WireProtocol.ResponsePacket) {
const request = this._requestQueue.dequeue(packet.Command, packet.Request_seq);
if (!request) {
this._logger.appendLine(`Received response for ${packet.Command} but could not find request.`);
return;
}
if (this._debugMode) {
this._logger.appendLine(`handleResponse: ${packet.Command} (${packet.Request_seq})`);
}
if (packet.Success) {
request.onSuccess(packet.Body);
}
else {
request.onError(packet.Message || packet.Body);
}
this._requestQueue.drain();
}
private _handleEventPacket(packet: protocol.WireProtocol.EventPacket): void {
if (packet.Event === 'log') {
const entry = <{ LogLevel: string; Name: string; Message: string; }>packet.Body;
this._logOutput(entry.LogLevel, entry.Name, entry.Message);
}
else {
// fwd all other events
this._fireEvent(packet.Event, packet.Body);
}
}
private _makeRequest(request: Request) {
const id = OmniSharpServer._nextId++;
const requestPacket: protocol.WireProtocol.RequestPacket = {
Type: 'request',
Seq: id,
Command: request.command,
Arguments: request.data
};
if (this._debugMode) {
this._logger.append(`makeRequest: ${request.command} (${id})`);
if (request.data) {
this._logger.append(`, data=${JSON.stringify(request.data)}`);
}
this._logger.appendLine();
}
this._serverProcess.stdin.write(JSON.stringify(requestPacket) + '\n');
return id;
}
private static getLogLevelPrefix(logLevel: string) {
switch (logLevel) {
case "TRACE": return "trce";
case "DEBUG": return "dbug";
case "INFORMATION": return "info";
case "WARNING": return "warn";
case "ERROR": return "fail";
case "CRITICAL": return "crit";
default: throw new Error(`Unknown log level value: ${logLevel}`);
}
}
private _isFilterableOutput(logLevel: string, name: string, message: string) {
// filter messages like: /codecheck: 200 339ms
const timing200Pattern = /^\/[\/\w]+: 200 \d+ms/;
return logLevel === "INFORMATION"
&& name === "OmniSharp.Middleware.LoggingMiddleware"
&& timing200Pattern.test(message);
}
private _logOutput(logLevel: string, name: string, message: string) {
if (this._debugMode || !this._isFilterableOutput(logLevel, name, message)) {
let output = `[${OmniSharpServer.getLogLevelPrefix(logLevel)}]: ${name}${os.EOL}${message}`;
const newLinePlusPadding = os.EOL + " ";
output = output.replace(os.EOL, newLinePlusPadding);
this._logger.appendLine(output);
}
}
}