RemoteEndPoint.cs 17.3 KB
Newer Older
J
Jonathon Marolf 已提交
1 2 3
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27

#nullable enable

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Pipes;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.ErrorReporting;
using Newtonsoft.Json;
using Roslyn.Utilities;
using StreamJsonRpc;

namespace Microsoft.CodeAnalysis.Remote
{
    /// <summary>
    /// Helper type that abstract out JsonRpc communication with extra capability of
    /// using raw stream to move over big chunk of data
    /// </summary>
    internal sealed class RemoteEndPoint : IDisposable
    {
28
        private const string UnexpectedExceptionLogMessage = "Unexpected exception from JSON-RPC";
29 30 31 32 33 34 35 36 37 38

        private static readonly JsonRpcTargetOptions s_jsonRpcTargetOptions = new JsonRpcTargetOptions()
        {
            // Do not allow JSON-RPC to automatically subscribe to events and remote their calls.
            NotifyClientOfEvents = false,

            // Only allow public methods (may be on internal types) to be invoked remotely.
            AllowNonPublicInvocation = false
        };

39 40 41
        private static int s_id;

        private readonly int _id;
42 43 44 45
        private readonly TraceSource _logger;
        private readonly JsonRpc _rpc;

        private bool _startedListening;
46
        private JsonRpcDisconnectedEventArgs? _disconnectedReason;
47 48 49 50 51 52 53 54 55

        public event Action<JsonRpcDisconnectedEventArgs>? Disconnected;
        public event Action<Exception>? UnexpectedExceptionThrown;

        public RemoteEndPoint(Stream stream, TraceSource logger, object? incomingCallTarget, IEnumerable<JsonConverter>? jsonConverters = null)
        {
            RoslynDebug.Assert(stream != null);
            RoslynDebug.Assert(logger != null);

56
            _id = Interlocked.Increment(ref s_id);
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
            _logger = logger;

            var jsonFormatter = new JsonMessageFormatter();

            if (jsonConverters != null)
            {
                jsonFormatter.JsonSerializer.Converters.AddRange(jsonConverters);
            }

            jsonFormatter.JsonSerializer.Converters.Add(AggregateJsonConverter.Instance);

            _rpc = new JsonRpc(new HeaderDelimitedMessageHandler(stream, jsonFormatter))
            {
                CancelLocallyInvokedMethodsWhenConnectionIsClosed = true,
                TraceSource = logger
            };

            if (incomingCallTarget != null)
            {
                _rpc.AddLocalRpcTarget(incomingCallTarget, s_jsonRpcTargetOptions);
            }

            _rpc.Disconnected += OnDisconnected;
        }

        /// <summary>
        /// Must be called before any communication commences.
        /// See https://github.com/dotnet/roslyn/issues/16900#issuecomment-277378950.
        /// </summary>
        public void StartListening()
        {
            _rpc.StartListening();
            _startedListening = true;
        }

        public bool IsDisposed
            => _rpc.IsDisposed;

        public void Dispose()
        {
            _rpc.Disconnected -= OnDisconnected;
            _rpc.Dispose();
        }

        public async Task InvokeAsync(string targetName, IReadOnlyList<object?> arguments, CancellationToken cancellationToken)
        {
            Contract.ThrowIfFalse(_startedListening);

105
            // if this end-point is already disconnected do not log more errors:
106
            var logError = _disconnectedReason == null;
107

108 109
            try
            {
110
                await _rpc.InvokeWithCancellationAsync(targetName, arguments, cancellationToken).ConfigureAwait(false);
111
            }
112
            catch (Exception ex) when (!logError || ReportUnlessCanceled(ex, cancellationToken))
113 114 115 116 117 118 119 120 121
            {
                // Remote call may fail with different exception even when our cancellation token is signaled
                // (e.g. on shutdown if the connection is dropped):
                cancellationToken.ThrowIfCancellationRequested();

                throw CreateSoftCrashException(ex, cancellationToken);
            }
        }

122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
        public async Task TryInvokeAsync(string targetName, IReadOnlyList<object?> arguments, CancellationToken cancellationToken)
        {
            Contract.ThrowIfFalse(_startedListening);

            if (_rpc.IsDisposed)
            {
                return;
            }

            try
            {
                await _rpc.InvokeWithCancellationAsync(targetName, arguments, cancellationToken).ConfigureAwait(false);
            }
            catch
            {
                // ignore
            }
        }

141 142 143 144
        public async Task<T> InvokeAsync<T>(string targetName, IReadOnlyList<object?> arguments, CancellationToken cancellationToken)
        {
            Contract.ThrowIfFalse(_startedListening);

145
            // if this end-point is already disconnected do not log more errors:
146
            var logError = _disconnectedReason == null;
147

148 149
            try
            {
150
                return await _rpc.InvokeWithCancellationAsync<T>(targetName, arguments, cancellationToken).ConfigureAwait(false);
151
            }
152
            catch (Exception ex) when (!logError || ReportUnlessCanceled(ex, cancellationToken))
153 154 155 156 157 158 159 160 161 162
            {
                // Remote call may fail with different exception even when our cancellation token is signaled
                // (e.g. on shutdown if the connection is dropped):
                cancellationToken.ThrowIfCancellationRequested();

                throw CreateSoftCrashException(ex, cancellationToken);
            }
        }

        /// <summary>
163 164 165 166 167 168
        /// Invokes a remote method <paramref name="targetName"/> with specified <paramref name="arguments"/> and
        /// establishes a pipe through which the target method may transfer large binary data. The name of the pipe is
        /// passed to the target method as an additional argument following the specified <paramref name="arguments"/>.
        /// The target method is expected to use
        /// <see cref="WriteDataToNamedPipeAsync{TData}(string, TData, Func{Stream, TData, CancellationToken, Task}, CancellationToken)"/>
        /// to write the data to the pipe stream.
169 170 171 172 173 174 175
        /// </summary>
        public async Task<T> InvokeAsync<T>(string targetName, IReadOnlyList<object?> arguments, Func<Stream, CancellationToken, Task<T>> dataReader, CancellationToken cancellationToken)
        {
            const int BufferSize = 12 * 1024;

            Contract.ThrowIfFalse(_startedListening);

176
            // if this end-point is already disconnected do not log more errors:
177
            var logError = _disconnectedReason == null;
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
            using var linkedCancellationSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);

            var pipeName = Guid.NewGuid().ToString();

            var pipe = new NamedPipeServerStream(pipeName, PipeDirection.In, maxNumberOfServerInstances: 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous);

            try
            {
                // Transfer ownership of the pipe to BufferedStream, it will dispose it:
                using var stream = new BufferedStream(pipe, BufferSize);

                // send request to asset source
                var task = _rpc.InvokeWithCancellationAsync(targetName, arguments.Concat(pipeName).ToArray(), cancellationToken);

                // if invoke throws an exception, make sure we raise cancellation.
                RaiseCancellationIfInvokeFailed(task, linkedCancellationSource, cancellationToken);

                // wait for asset source to respond
                await pipe.WaitForConnectionAsync(linkedCancellationSource.Token).ConfigureAwait(false);

                // run user task with direct stream
                var result = await dataReader(stream, linkedCancellationSource.Token).ConfigureAwait(false);

                // wait task to finish
                await task.ConfigureAwait(false);

                return result;
            }
207
            catch (Exception ex) when (!logError || ReportUnlessCanceled(ex, linkedCancellationSource.Token, cancellationToken))
208 209 210 211 212 213 214 215 216 217 218
            {
                // Remote call may fail with different exception even when our cancellation token is signaled
                // (e.g. on shutdown if the connection is dropped).
                // It's important to use cancelationToken here rather than linked token as there is a slight 
                // delay in between linked token being signaled and cancellation token being signaled.
                cancellationToken.ThrowIfCancellationRequested();

                throw CreateSoftCrashException(ex, cancellationToken);
            }
        }

219 220
        public static Task WriteDataToNamedPipeAsync<TData>(string pipeName, TData data, Func<ObjectWriter, TData, CancellationToken, Task> dataWriter, CancellationToken cancellationToken)
            => WriteDataToNamedPipeAsync(pipeName, data,
221
                async (stream, data, cancellationToken) =>
222
                {
223 224
                    using var objectWriter = new ObjectWriter(stream, leaveOpen: true, cancellationToken);
                    await dataWriter(objectWriter, data, cancellationToken).ConfigureAwait(false);
225 226 227
                }, cancellationToken);

        public static async Task WriteDataToNamedPipeAsync<TData>(string pipeName, TData data, Func<Stream, TData, CancellationToken, Task> dataWriter, CancellationToken cancellationToken)
228 229 230 231 232 233 234
        {
            const int BufferSize = 4 * 1024;

            try
            {
                var pipe = new NamedPipeClientStream(serverName: ".", pipeName, PipeDirection.Out);

235
                var success = false;
236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
                try
                {
                    await ConnectPipeAsync(pipe, cancellationToken).ConfigureAwait(false);
                    success = true;
                }
                finally
                {
                    if (!success)
                    {
                        pipe.Dispose();
                    }
                }

                // Transfer ownership of the pipe to BufferedStream, it will dispose it:
                using var stream = new BufferedStream(pipe, BufferSize);

252
                await dataWriter(stream, data, cancellationToken).ConfigureAwait(false);
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
                await stream.FlushAsync(cancellationToken).ConfigureAwait(false);
            }
            catch (Exception) when (cancellationToken.IsCancellationRequested)
            {
                // The stream has closed before we had chance to check cancellation.
                cancellationToken.ThrowIfCancellationRequested();
            }
        }

        private static async Task ConnectPipeAsync(NamedPipeClientStream pipe, CancellationToken cancellationToken)
        {
            const int ConnectWithoutTimeout = 1;
            const int MaxRetryAttemptsForFileNotFoundException = 3;
            const int ErrorSemTimeoutHResult = unchecked((int)0x80070079);
            var connectRetryInterval = TimeSpan.FromMilliseconds(20);

            var retryCount = 0;
            while (true)
            {
                try
                {
                    // Try connecting without wait.
                    // Connecting with anything else will consume CPU causing a spin wait.
                    pipe.Connect(ConnectWithoutTimeout);
                    return;
                }
                catch (ObjectDisposedException)
                {
                    // Prefer to throw OperationCanceledException if the caller requested cancellation.
                    cancellationToken.ThrowIfCancellationRequested();
                    throw;
                }
                catch (IOException ex) when (ex.HResult == ErrorSemTimeoutHResult)
                {
                    // Ignore and retry.
                }
                catch (TimeoutException)
                {
                    // Ignore and retry.
                }
                catch (FileNotFoundException) when (retryCount < MaxRetryAttemptsForFileNotFoundException)
                {
                    // Ignore and retry
                    retryCount++;
                }

                cancellationToken.ThrowIfCancellationRequested();
                await Task.Delay(connectRetryInterval, cancellationToken).ConfigureAwait(false);
            }
        }

        private static void RaiseCancellationIfInvokeFailed(Task task, CancellationTokenSource linkedCancellationSource, CancellationToken cancellationToken)
        {
            // if invoke throws an exception, make sure we raise cancellation
            _ = task.ContinueWith(p =>
            {
                try
                {
                    // now, we allow user to kill OOP process, when that happen, 
                    // just raise cancellation. 
                    // otherwise, stream.WaitForDirectConnectionAsync can stuck there forever since
                    // cancellation from user won't be raised
                    linkedCancellationSource.Cancel();
                }
                catch (ObjectDisposedException)
                {
                    // merged cancellation is already disposed
                }
            }, cancellationToken, TaskContinuationOptions.NotOnRanToCompletion | TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
        }

324
        private static bool ReportUnlessCanceled(Exception ex, CancellationToken linkedCancellationToken, CancellationToken cancellationToken)
325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347
        {
            // check whether we are in cancellation mode

            // things are either cancelled by us (cancellationToken) or cancelled by OOP (linkedCancellationToken). 
            // "cancelled by us" means operation user invoked is cancelled by another user action such as explicit cancel, or typing.
            // "cancelled by OOP" means operation user invoked is cancelled due to issue on OOP such as user killed OOP process.

            if (cancellationToken.IsCancellationRequested)
            {
                // we are under our own cancellation, we don't care what the exception is.
                // due to the way we do cancellation (forcefully closing connection in the middle of reading/writing)
                // various exceptions can be thrown. for example, if we close our own named pipe stream in the middle of
                // object reader/writer using it, we could get invalid operation exception or invalid cast exception.
                return true;
            }

            if (linkedCancellationToken.IsCancellationRequested)
            {
                // Connection can be closed when the remote process is killed.
                // That will manifest as remote token cancellation.
                return true;
            }

348
            ReportNonFatalWatson(ex);
349 350 351
            return true;
        }

352
        private static bool ReportUnlessCanceled(Exception ex, CancellationToken cancellationToken)
353 354 355
        {
            if (!cancellationToken.IsCancellationRequested)
            {
356
                ReportNonFatalWatson(ex);
357 358 359 360 361
            }

            return true;
        }

362
        private static void ReportNonFatalWatson(Exception exception)
363
        {
364
            FatalError.ReportWithoutCrash(exception);
365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380
        }

        private SoftCrashException CreateSoftCrashException(Exception ex, CancellationToken cancellationToken)
        {
            // TODO: revisit https://github.com/dotnet/roslyn/issues/40476
            // We are getting unexpected exception from service hub. Rather than doing hard crash on unexpected exception,
            // we decided to do soft crash where we show info bar to users saying "VS got corrupted and users should save
            // their works and close VS"

            UnexpectedExceptionThrown?.Invoke(ex);

            // throw soft crash exception
            return new SoftCrashException(UnexpectedExceptionLogMessage, ex, cancellationToken);
        }

        private void LogError(string message)
381 382 383 384
        {
            var currentProcess = Process.GetCurrentProcess();
            _logger.TraceEvent(TraceEventType.Error, _id, $" [{currentProcess.ProcessName}:{currentProcess.Id}] {message}");
        }
385

386
        private void LogDisconnectInfo(JsonRpcDisconnectedEventArgs? e)
387 388 389
        {
            if (e != null)
            {
390
                LogError($@"Stream disconnected unexpectedly:  {e.Reason}, '{e.Description}', LastMessage: {e.LastMessage}, Exception: {e.Exception?.Message}");
391 392 393 394 395 396 397 398 399
            }
        }

        /// <summary>
        /// Handle disconnection event, so that we detect disconnection as soon as it happens
        /// without waiting for the next failing remote call. The remote call may not happen 
        /// if there is an issue with the connection. E.g. the client end point might not receive
        /// a callback from server, or the server end point might not receive a call from client.
        /// </summary>
400
        private void OnDisconnected(object? sender, JsonRpcDisconnectedEventArgs e)
401
        {
402
            _disconnectedReason = e;
403 404 405 406 407

            // Don't log info in cases that are common - such as if we dispose the connection or the remote host process shuts down.
            if (e.Reason != DisconnectedReason.LocallyDisposed &&
                e.Reason != DisconnectedReason.RemotePartyTerminated)
            {
408
                LogDisconnectInfo(e);
409 410 411 412 413 414
            }

            Disconnected?.Invoke(e);
        }
    }
}