-
Notifications
You must be signed in to change notification settings - Fork 315
/
DesignModeClient.cs
422 lines (364 loc) · 17.6 KB
/
DesignModeClient.cs
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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.VisualStudio.TestPlatform.Client.DesignMode
{
using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestPlatform.Client.RequestHelper;
using Microsoft.VisualStudio.TestPlatform.Common.Logging;
using Microsoft.VisualStudio.TestPlatform.Common.Utilities;
using Microsoft.VisualStudio.TestPlatform.CommunicationUtilities;
using Microsoft.VisualStudio.TestPlatform.CommunicationUtilities.Interfaces;
using Microsoft.VisualStudio.TestPlatform.CommunicationUtilities.ObjectModel;
using Microsoft.VisualStudio.TestPlatform.CoreUtilities.Helpers;
using Microsoft.VisualStudio.TestPlatform.ObjectModel;
using Microsoft.VisualStudio.TestPlatform.ObjectModel.Client;
using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging;
using Microsoft.VisualStudio.TestPlatform.PlatformAbstractions;
using Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.Interfaces;
using CommunicationUtilitiesResources = Microsoft.VisualStudio.TestPlatform.CommunicationUtilities.Resources.Resources;
using CoreUtilitiesConstants = Microsoft.VisualStudio.TestPlatform.CoreUtilities.Constants;
/// <summary>
/// The design mode client.
/// </summary>
public class DesignModeClient : IDesignModeClient
{
private readonly ICommunicationManager communicationManager;
private readonly IDataSerializer dataSerializer;
private object ackLockObject = new object();
private ProtocolConfig protocolConfig = Constants.DefaultProtocolConfig;
private IEnvironment platformEnvironment;
protected Action<Message> onAckMessageReceived;
private TestSessionMessageLogger testSessionMessageLogger;
/// <summary>
/// Initializes a new instance of the <see cref="DesignModeClient"/> class.
/// </summary>
public DesignModeClient()
: this(new SocketCommunicationManager(), JsonDataSerializer.Instance, new PlatformEnvironment())
{
}
/// <summary>
/// Initializes a new instance of the <see cref="DesignModeClient"/> class.
/// </summary>
/// <param name="communicationManager">
/// The communication manager.
/// </param>
/// <param name="dataSerializer">
/// The data Serializer.
/// </param>
/// <param name="platformEnvironment">
/// The platform Environment
/// </param>
internal DesignModeClient(ICommunicationManager communicationManager, IDataSerializer dataSerializer, IEnvironment platformEnvironment)
{
this.communicationManager = communicationManager;
this.dataSerializer = dataSerializer;
this.platformEnvironment = platformEnvironment;
this.testSessionMessageLogger = TestSessionMessageLogger.Instance;
this.testSessionMessageLogger.TestRunMessage += this.TestRunMessageHandler;
}
/// <summary>
/// Property exposing the Instance
/// </summary>
public static IDesignModeClient Instance { get; private set; }
/// <summary>
/// Initializes DesignMode
/// </summary>
public static void Initialize()
{
Instance = new DesignModeClient();
}
/// <summary>
/// Creates a client and waits for server to accept connection asynchronously
/// </summary>
/// <param name="port">
/// Port number to connect
/// </param>
/// <param name="testRequestManager">
/// The test Request Manager.
/// </param>
public void ConnectToClientAndProcessRequests(int port, ITestRequestManager testRequestManager)
{
EqtTrace.Info("Trying to connect to server on port : {0}", port);
this.communicationManager.SetupClientAsync(new IPEndPoint(IPAddress.Loopback, port));
var connectionTimeoutInSecs = EnvironmentHelper.GetConnectionTimeout();
// Wait for the connection to the server and listen for requests.
if (this.communicationManager.WaitForServerConnection(connectionTimeoutInSecs * 1000))
{
this.communicationManager.SendMessage(MessageType.SessionConnected);
this.ProcessRequests(testRequestManager);
}
else
{
EqtTrace.Error("DesignModeClient : ConnectToClientAndProcessRequests : Client timed out while connecting to the server.");
this.Dispose();
throw new TimeoutException(
string.Format(
CultureInfo.CurrentUICulture,
CommunicationUtilitiesResources.ConnectionTimeoutErrorMessage,
CoreUtilitiesConstants.VstestConsoleProcessName,
"translation layer",
connectionTimeoutInSecs,
EnvironmentHelper.VstestConnectionTimeout)
);
}
}
public void HandleParentProcessExit()
{
// Dispose off the communications to end the session
// this should end the "ProcessRequests" loop with an exception
this.Dispose();
EqtTrace.Info("DesignModeClient: Parent process exited, Exiting myself..");
this.platformEnvironment.Exit(1);
}
/// <summary>
/// Process Requests from the IDE
/// </summary>
/// <param name="testRequestManager">
/// The test Request Manager.
/// </param>
private void ProcessRequests(ITestRequestManager testRequestManager)
{
var isSessionEnd = false;
do
{
try
{
var message = this.communicationManager.ReceiveMessage();
if (EqtTrace.IsInfoEnabled)
{
EqtTrace.Info("DesignModeClient.ProcessRequests: Processing Message: {0}", message);
}
switch (message.MessageType)
{
case MessageType.VersionCheck:
{
var version = this.dataSerializer.DeserializePayload<int>(message);
this.protocolConfig.Version = Math.Min(version, this.protocolConfig.Version);
this.communicationManager.SendMessage(MessageType.VersionCheck, this.protocolConfig.Version);
break;
}
case MessageType.ExtensionsInitialize:
{
// Do not filter the Editor/IDE provided extensions by name
var extensionPaths = this.communicationManager.DeserializePayload<IEnumerable<string>>(message);
testRequestManager.InitializeExtensions(extensionPaths, skipExtensionFilters: true);
break;
}
case MessageType.StartDiscovery:
{
var discoveryPayload = this.dataSerializer.DeserializePayload<DiscoveryRequestPayload>(message);
this.StartDiscovery(discoveryPayload, testRequestManager);
break;
}
case MessageType.GetTestRunnerProcessStartInfoForRunAll:
case MessageType.GetTestRunnerProcessStartInfoForRunSelected:
{
var testRunPayload =
this.communicationManager.DeserializePayload<TestRunRequestPayload>(
message);
this.StartTestRun(testRunPayload, testRequestManager, skipTestHostLaunch: true);
break;
}
case MessageType.TestRunAllSourcesWithDefaultHost:
case MessageType.TestRunSelectedTestCasesDefaultHost:
{
var testRunPayload =
this.communicationManager.DeserializePayload<TestRunRequestPayload>(
message);
this.StartTestRun(testRunPayload, testRequestManager, skipTestHostLaunch: false);
break;
}
case MessageType.CancelDiscovery:
{
testRequestManager.CancelDiscovery();
break;
}
case MessageType.CancelTestRun:
{
testRequestManager.CancelTestRun();
break;
}
case MessageType.AbortTestRun:
{
testRequestManager.AbortTestRun();
break;
}
case MessageType.CustomTestHostLaunchCallback:
{
this.onAckMessageReceived?.Invoke(message);
break;
}
case MessageType.SessionEnd:
{
EqtTrace.Info("DesignModeClient: Session End message received from server. Closing the connection.");
isSessionEnd = true;
this.Dispose();
break;
}
default:
{
EqtTrace.Info("DesignModeClient: Invalid Message received: {0}", message);
break;
}
}
}
catch (Exception ex)
{
EqtTrace.Error("DesignModeClient: Error processing request: {0}", ex);
isSessionEnd = true;
this.Dispose();
}
}
while (!isSessionEnd);
}
/// <summary>
/// Send a custom host launch message to IDE
/// </summary>
/// <param name="testProcessStartInfo">
/// The test Process Start Info.
/// </param>
/// <param name="cancellationToken">
/// The cancellation token.
/// </param>
/// <returns>
/// The <see cref="int"/>.
/// </returns>
public int LaunchCustomHost(TestProcessStartInfo testProcessStartInfo, CancellationToken cancellationToken)
{
lock (ackLockObject)
{
var waitHandle = new AutoResetEvent(false);
Message ackMessage = null;
this.onAckMessageReceived = (ackRawMessage) =>
{
ackMessage = ackRawMessage;
waitHandle.Set();
};
this.communicationManager.SendMessage(MessageType.CustomTestHostLaunch, testProcessStartInfo);
// LifeCycle of the TP through DesignModeClient is maintained by the IDEs or user-facing-clients like LUTs, who call TestPlatform
// TP is handing over the control of launch to these IDEs and so, TP has to wait indefinite
// Even if TP has a timeout here, there is no way TP can abort or stop the thread/task that is hung in IDE or LUT
// Even if TP can abort the API somehow, TP is essentially putting IDEs or Clients in inconsistent state without having info on
// Since the IDEs own user-UI-experience here, TP will let the custom host launch as much time as IDEs define it for their users
WaitHandle.WaitAny(new WaitHandle[] { waitHandle, cancellationToken.WaitHandle });
cancellationToken.ThrowTestPlatformExceptionIfCancellationRequested();
this.onAckMessageReceived = null;
var ackPayload = this.dataSerializer.DeserializePayload<CustomHostLaunchAckPayload>(ackMessage);
if (ackPayload.HostProcessId > 0)
{
return ackPayload.HostProcessId;
}
else
{
throw new TestPlatformException(ackPayload.ErrorMessage);
}
}
}
/// <summary>
/// Send the raw messages to IDE
/// </summary>
/// <param name="rawMessage"></param>
public void SendRawMessage(string rawMessage)
{
this.communicationManager.SendRawMessage(rawMessage);
}
/// <inheritdoc />
public void SendTestMessage(TestMessageLevel level, string message)
{
var payload = new TestMessagePayload { MessageLevel = level, Message = message };
this.communicationManager.SendMessage(MessageType.TestMessage, payload);
}
/// <summary>
/// Sends the test session logger warning and error messages to IDE;
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void TestRunMessageHandler(object sender, TestRunMessageEventArgs e)
{
if (e.Level == TestMessageLevel.Error || e.Level == TestMessageLevel.Warning)
{
var payload = new TestMessagePayload { MessageLevel = e.Level, Message = e.Message };
this.communicationManager.SendMessage(MessageType.TestMessage, payload);
}
}
private void StartTestRun(TestRunRequestPayload testRunPayload, ITestRequestManager testRequestManager, bool skipTestHostLaunch)
{
Task.Run(
delegate
{
try
{
testRequestManager.ResetOptions();
var customLauncher = skipTestHostLaunch ?
DesignModeTestHostLauncherFactory.GetCustomHostLauncherForTestRun(this, testRunPayload) : null;
testRequestManager.RunTests(testRunPayload, customLauncher, new DesignModeTestEventsRegistrar(this), this.protocolConfig);
}
catch (Exception ex)
{
EqtTrace.Error("DesignModeClient: Exception in StartTestRun: " + ex);
var testMessagePayload = new TestMessagePayload { MessageLevel = TestMessageLevel.Error, Message = ex.ToString() };
this.communicationManager.SendMessage(MessageType.TestMessage, testMessagePayload);
var runCompletePayload = new TestRunCompletePayload()
{
TestRunCompleteArgs = new TestRunCompleteEventArgs(null, false, true, ex, null, TimeSpan.MinValue),
LastRunTests = null
};
// Send run complete to translation layer
this.communicationManager.SendMessage(MessageType.ExecutionComplete, runCompletePayload);
}
});
}
private void StartDiscovery(DiscoveryRequestPayload discoveryRequestPayload, ITestRequestManager testRequestManager)
{
Task.Run(
delegate
{
try
{
testRequestManager.ResetOptions();
testRequestManager.DiscoverTests(discoveryRequestPayload, new DesignModeTestEventsRegistrar(this), this.protocolConfig);
}
catch (Exception ex)
{
EqtTrace.Error("DesignModeClient: Exception in StartDiscovery: " + ex);
var testMessagePayload = new TestMessagePayload { MessageLevel = TestMessageLevel.Error, Message = ex.ToString() };
this.communicationManager.SendMessage(MessageType.TestMessage, testMessagePayload);
var payload = new DiscoveryCompletePayload()
{
IsAborted = true,
LastDiscoveredTests = null,
TotalTests = -1
};
// Send run complete to translation layer
this.communicationManager.SendMessage(MessageType.DiscoveryComplete, payload);
}
});
}
#region IDisposable Support
private bool disposedValue = false; // To detect redundant calls
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
this.communicationManager?.StopClient();
}
disposedValue = true;
}
}
// This code added to correctly implement the disposable pattern.
public void Dispose()
{
// Do not change this code. Put cleanup code in Dispose(bool disposing) above.
Dispose(true);
}
#endregion
}
}