forked from SeleniumHQ/selenium
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDriverService.cs
431 lines (384 loc) · 16.8 KB
/
DriverService.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
423
424
425
426
427
428
429
430
431
// <copyright file="DriverService.cs" company="WebDriver Committers">
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC licenses this file
// to you under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
using OpenQA.Selenium.Remote;
using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
namespace OpenQA.Selenium
{
/// <summary>
/// Exposes the service provided by a native WebDriver server executable.
/// </summary>
public abstract class DriverService : ICommandServer
{
private string driverServicePath;
private string driverServiceExecutableName;
private string driverServiceHostName = "localhost";
private int driverServicePort;
private bool silent;
private bool hideCommandPromptWindow;
private bool isDisposed;
private Process driverServiceProcess;
private TimeSpan initializationTimeout = TimeSpan.FromSeconds(20);
/// <summary>
/// Initializes a new instance of the <see cref="DriverService"/> class.
/// </summary>
/// <param name="servicePath">The full path to the directory containing the executable providing the service to drive the browser.</param>
/// <param name="port">The port on which the driver executable should listen.</param>
/// <param name="driverServiceExecutableName">The file name of the driver service executable.</param>
/// <exception cref="ArgumentException">
/// If the path specified is <see langword="null"/> or an empty string.
/// </exception>
/// <exception cref="DriverServiceNotFoundException">
/// If the specified driver service executable does not exist in the specified directory.
/// </exception>
protected DriverService(string servicePath, int port, string driverServiceExecutableName)
{
this.driverServicePath = servicePath;
this.driverServiceExecutableName = driverServiceExecutableName;
this.driverServicePort = port;
}
/// <summary>
/// Occurs when the driver process is starting.
/// </summary>
public event EventHandler<DriverProcessStartingEventArgs> DriverProcessStarting;
/// <summary>
/// Occurs when the driver process has completely started.
/// </summary>
public event EventHandler<DriverProcessStartedEventArgs> DriverProcessStarted;
/// <summary>
/// Gets the Uri of the service.
/// </summary>
public Uri ServiceUrl
{
get { return new Uri(string.Format(CultureInfo.InvariantCulture, "http://{0}:{1}", this.driverServiceHostName, this.driverServicePort)); }
}
/// <summary>
/// Gets or sets the host name of the service. Defaults to "localhost."
/// </summary>
/// <remarks>
/// Most driver service executables do not allow connections from remote
/// (non-local) machines. This property can be used as a workaround so
/// that an IP address (like "127.0.0.1" or "::1") can be used instead.
/// </remarks>
public string HostName
{
get { return this.driverServiceHostName; }
set { this.driverServiceHostName = value; }
}
/// <summary>
/// Gets or sets the port of the service.
/// </summary>
public int Port
{
get { return this.driverServicePort; }
set { this.driverServicePort = value; }
}
/// <summary>
/// Gets or sets a value indicating whether the initial diagnostic information is suppressed
/// when starting the driver server executable. Defaults to <see langword="false"/>, meaning
/// diagnostic information should be shown by the driver server executable.
/// </summary>
public bool SuppressInitialDiagnosticInformation
{
get { return this.silent; }
set { this.silent = value; }
}
/// <summary>
/// Gets a value indicating whether the service is running.
/// </summary>
public bool IsRunning
{
get { return this.driverServiceProcess != null && !this.driverServiceProcess.HasExited; }
}
/// <summary>
/// Gets or sets a value indicating whether the command prompt window of the service should be hidden.
/// </summary>
public bool HideCommandPromptWindow
{
get { return this.hideCommandPromptWindow; }
set { this.hideCommandPromptWindow = value; }
}
/// <summary>
/// Gets the process ID of the running driver service executable. Returns 0 if the process is not running.
/// </summary>
public int ProcessId
{
get
{
if (this.IsRunning)
{
// There's a slight chance that the Process object is running,
// but does not have an ID set. This should be rare, but we
// definitely don't want to throw an exception.
try
{
return this.driverServiceProcess.Id;
}
catch (InvalidOperationException)
{
}
}
return 0;
}
}
/// <summary>
/// Gets or sets a value indicating the time to wait for an initial connection before timing out.
/// </summary>
public TimeSpan InitializationTimeout
{
get { return this.initializationTimeout; }
set { this.initializationTimeout = value; }
}
/// <summary>
/// Gets or sets the executable file name of the driver service.
/// </summary>
public string DriverServiceExecutableName
{
get { return this.driverServiceExecutableName; }
set { this.driverServiceExecutableName = value; }
}
/// <summary>
/// Gets or sets the path of the driver service.
/// </summary>
public string DriverServicePath
{
get { return this.driverServicePath; }
set { this.driverServicePath = value; }
}
/// <summary>
/// Gets the command-line arguments for the driver service.
/// </summary>
protected virtual string CommandLineArguments
{
get { return string.Format(CultureInfo.InvariantCulture, "--port={0}", this.driverServicePort); }
}
/// <summary>
/// Gets a value indicating the time to wait for the service to terminate before forcing it to terminate.
/// </summary>
protected virtual TimeSpan TerminationTimeout
{
get { return TimeSpan.FromSeconds(10); }
}
/// <summary>
/// Gets a value indicating whether the service has a shutdown API that can be called to terminate
/// it gracefully before forcing a termination.
/// </summary>
protected virtual bool HasShutdown
{
get { return true; }
}
/// <summary>
/// Gets a value indicating whether the service is responding to HTTP requests.
/// </summary>
protected virtual bool IsInitialized
{
get
{
bool isInitialized = false;
try
{
using (var httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.ConnectionClose = true;
httpClient.Timeout = TimeSpan.FromSeconds(5);
Uri serviceHealthUri = new Uri(this.ServiceUrl, new Uri(DriverCommand.Status, UriKind.Relative));
using (var response = Task.Run(async () => await httpClient.GetAsync(serviceHealthUri)).GetAwaiter().GetResult())
{
// Checking the response from the 'status' end point. Note that we are simply checking
// that the HTTP status returned is a 200 status, and that the resposne has the correct
// Content-Type header. A more sophisticated check would parse the JSON response and
// validate its values. At the moment we do not do this more sophisticated check.
isInitialized = response.StatusCode == HttpStatusCode.OK && response.Content.Headers.ContentType.MediaType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase);
}
}
}
catch (Exception ex) when (ex is HttpRequestException || ex is TaskCanceledException)
{
// do nothing: the exception is expected, meaning driver service is not initialized
}
return isInitialized;
}
}
/// <summary>
/// Releases all resources associated with this <see cref="DriverService"/>.
/// </summary>
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Starts the DriverService if it is not already running.
/// </summary>
public void Start()
{
if (this.driverServiceProcess != null)
{
return;
}
this.driverServiceProcess = new Process();
if (this.driverServicePath != null)
{
this.driverServiceProcess.StartInfo.FileName = Path.Combine(this.driverServicePath, this.driverServiceExecutableName);
}
else
{
this.driverServiceProcess.StartInfo.FileName = new DriverFinder(this.GetDefaultDriverOptions()).GetDriverPath();
}
this.driverServiceProcess.StartInfo.Arguments = this.CommandLineArguments;
this.driverServiceProcess.StartInfo.UseShellExecute = false;
this.driverServiceProcess.StartInfo.CreateNoWindow = this.hideCommandPromptWindow;
DriverProcessStartingEventArgs eventArgs = new DriverProcessStartingEventArgs(this.driverServiceProcess.StartInfo);
this.OnDriverProcessStarting(eventArgs);
this.driverServiceProcess.Start();
bool serviceAvailable = this.WaitForServiceInitialization();
DriverProcessStartedEventArgs processStartedEventArgs = new DriverProcessStartedEventArgs(this.driverServiceProcess);
this.OnDriverProcessStarted(processStartedEventArgs);
if (!serviceAvailable)
{
string msg = "Cannot start the driver service on " + this.ServiceUrl;
throw new WebDriverException(msg);
}
}
/// <summary>
/// The browser options instance that corresponds to the driver service
/// </summary>
/// <returns></returns>
protected abstract DriverOptions GetDefaultDriverOptions();
/// <summary>
/// Releases all resources associated with this <see cref="DriverService"/>.
/// </summary>
/// <param name="disposing"><see langword="true"/> if the Dispose method was explicitly called; otherwise, <see langword="false"/>.</param>
protected virtual void Dispose(bool disposing)
{
if (!this.isDisposed)
{
if (disposing)
{
this.Stop();
}
this.isDisposed = true;
}
}
/// <summary>
/// Raises the <see cref="DriverProcessStarting"/> event.
/// </summary>
/// <param name="eventArgs">A <see cref="DriverProcessStartingEventArgs"/> that contains the event data.</param>
protected void OnDriverProcessStarting(DriverProcessStartingEventArgs eventArgs)
{
if (eventArgs == null)
{
throw new ArgumentNullException(nameof(eventArgs), "eventArgs must not be null");
}
if (this.DriverProcessStarting != null)
{
this.DriverProcessStarting(this, eventArgs);
}
}
/// <summary>
/// Raises the <see cref="DriverProcessStarted"/> event.
/// </summary>
/// <param name="eventArgs">A <see cref="DriverProcessStartedEventArgs"/> that contains the event data.</param>
protected void OnDriverProcessStarted(DriverProcessStartedEventArgs eventArgs)
{
if (eventArgs == null)
{
throw new ArgumentNullException(nameof(eventArgs), "eventArgs must not be null");
}
if (this.DriverProcessStarted != null)
{
this.DriverProcessStarted(this, eventArgs);
}
}
/// <summary>
/// Stops the DriverService.
/// </summary>
private void Stop()
{
if (this.IsRunning)
{
if (this.HasShutdown)
{
Uri shutdownUrl = new Uri(this.ServiceUrl, "/shutdown");
DateTime timeout = DateTime.Now.Add(this.TerminationTimeout);
using (var httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.ConnectionClose = true;
while (this.IsRunning && DateTime.Now < timeout)
{
try
{
// Issue the shutdown HTTP request, then wait a short while for
// the process to have exited. If the process hasn't yet exited,
// we'll retry. We wait for exit here, since catching the exception
// for a failed HTTP request due to a closed socket is particularly
// expensive.
using (var response = Task.Run(async () => await httpClient.GetAsync(shutdownUrl)).GetAwaiter().GetResult())
{
}
this.driverServiceProcess.WaitForExit(3000);
}
catch (Exception ex) when (ex is HttpRequestException || ex is TimeoutException)
{
}
}
}
}
// If at this point, the process still hasn't exited, wait for one
// last-ditch time, then, if it still hasn't exited, kill it. Note
// that falling into this branch of code should be exceedingly rare.
if (this.IsRunning)
{
this.driverServiceProcess.WaitForExit(Convert.ToInt32(this.TerminationTimeout.TotalMilliseconds));
if (!this.driverServiceProcess.HasExited)
{
this.driverServiceProcess.Kill();
}
}
this.driverServiceProcess.Dispose();
this.driverServiceProcess = null;
}
}
/// <summary>
/// Waits until a the service is initialized, or the timeout set
/// by the <see cref="InitializationTimeout"/> property is reached.
/// </summary>
/// <returns><see langword="true"/> if the service is properly started and receiving HTTP requests;
/// otherwise; <see langword="false"/>.</returns>
private bool WaitForServiceInitialization()
{
bool isInitialized = false;
DateTime timeout = DateTime.Now.Add(this.InitializationTimeout);
while (!isInitialized && DateTime.Now < timeout)
{
// If the driver service process has exited, we can exit early.
if (!this.IsRunning)
{
break;
}
isInitialized = this.IsInitialized;
}
return isInitialized;
}
}
}