ServiceHubRemoteHostClient.cs 12.6 KB
Newer Older
H
Heejae Chang 已提交
1 2
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

3
using System;
H
Heejae Chang 已提交
4 5 6 7
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
8
using Microsoft.CodeAnalysis;
9
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
H
Heejae Chang 已提交
10
using Microsoft.CodeAnalysis.ErrorReporting;
H
Heejae Chang 已提交
11
using Microsoft.CodeAnalysis.Execution;
H
Heejae Chang 已提交
12
using Microsoft.CodeAnalysis.Internal.Log;
H
Heejae Chang 已提交
13 14
using Microsoft.CodeAnalysis.Remote;
using Microsoft.ServiceHub.Client;
15
using Microsoft.VisualStudio.LanguageServices.Implementation;
16
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
17
using Microsoft.VisualStudio.Telemetry;
H
Heejae Chang 已提交
18 19 20 21 22
using Roslyn.Utilities;
using StreamJsonRpc;

namespace Microsoft.VisualStudio.LanguageServices.Remote
{
23 24
    using Workspace = Microsoft.CodeAnalysis.Workspace;

25
    internal sealed partial class ServiceHubRemoteHostClient : RemoteHostClient
H
Heejae Chang 已提交
26
    {
27 28
        private static int s_instanceId = 0;

H
Heejae Chang 已提交
29 30
        private readonly HubClient _hubClient;
        private readonly JsonRpc _rpc;
H
Heejae Chang 已提交
31
        private readonly HostGroup _hostGroup;
32
        private readonly TimeSpan _timeout;
H
Heejae Chang 已提交
33

34 35
        public static async Task<RemoteHostClient> CreateAsync(
            Workspace workspace, CancellationToken cancellationToken)
H
Heejae Chang 已提交
36
        {
H
Heejae Chang 已提交
37 38
            using (Logger.LogBlock(FunctionId.ServiceHubRemoteHostClient_CreateAsync, cancellationToken))
            {
39 40 41
                // let each client to have unique id so that we can distinguish different clients when service is restarted
                var currentInstanceId = Interlocked.Add(ref s_instanceId, 1);

H
Heejae Chang 已提交
42
                var primary = new HubClient("ManagedLanguage.IDE.RemoteHostClient");
43
                var current = $"VS ({Process.GetCurrentProcess().Id}) ({currentInstanceId})";
44

H
Heejae Chang 已提交
45
                var hostGroup = new HostGroup(current);
46 47
                var timeout = TimeSpan.FromMilliseconds(workspace.Options.GetOption(RemoteHostOptions.RequestServiceTimeoutInMS));
                var remoteHostStream = await RequestServiceAsync(primary, WellKnownRemoteHostServices.RemoteHostService, hostGroup, timeout, cancellationToken).ConfigureAwait(false);
H
Heejae Chang 已提交
48

H
Heejae Chang 已提交
49
                var instance = new ServiceHubRemoteHostClient(workspace, primary, hostGroup, remoteHostStream);
H
Heejae Chang 已提交
50

H
Heejae Chang 已提交
51
                // make sure connection is done right
52
                var host = await instance._rpc.InvokeAsync<string>(nameof(IRemoteHostService.Connect), current, TelemetryService.DefaultSession.SerializeSettings()).ConfigureAwait(false);
H
Heejae Chang 已提交
53

H
Heejae Chang 已提交
54 55
                // TODO: change this to non fatal watson and make VS to use inproc implementation
                Contract.ThrowIfFalse(host == current.ToString());
H
Heejae Chang 已提交
56

57
                instance.Started();
H
Heejae Chang 已提交
58

59 60
                // Create a workspace host to hear about workspace changes.  We'll 
                // remote those changes over to the remote side when they happen.
61
                await RegisterWorkspaceHostAsync(workspace, instance).ConfigureAwait(false);
62

H
Heejae Chang 已提交
63 64 65
                // return instance
                return instance;
            }
H
Heejae Chang 已提交
66 67
        }

68
        private static async Task RegisterWorkspaceHostAsync(Workspace workspace, RemoteHostClient client)
69 70 71 72
        {
            var vsWorkspace = workspace as VisualStudioWorkspaceImpl;
            if (vsWorkspace == null)
            {
73
                return;
74 75
            }

76 77
            // don't block UI thread while initialize workspace host
            var host = new WorkspaceHost(vsWorkspace, client);
78 79 80 81

            // Initialize the remote side with whatever data we have currently for the workspace.
            // As workspace changes happen, this host will get notified, and it can remote those
            // changes appropriately over to the remote size.
82 83
            await host.InitializeAsync().ConfigureAwait(false);

H
Heejae Chang 已提交
84 85
            // RegisterWorkspaceHost is required to be called from UI thread so push the code
            // to UI thread to run. 
86
            await Task.Factory.SafeStartNew(() =>
H
Heejae Chang 已提交
87
            {
88
                vsWorkspace.GetProjectTrackerAndInitializeIfNecessary(Shell.ServiceProvider.GlobalProvider).RegisterWorkspaceHost(host);
89 90 91 92 93 94 95 96 97

                // There may have been notifications fired by the workspace between the time we 
                // were created and now when we let it know about us.  Because of that, we need
                // to do another initialization pass to make sure all the current workpsace
                // state is pushed over to the remote side.
                // 
                // We can do this in a fire and forget manner.  We don't want to block the UI
                // thread while we're pushing this data over.
                Task.Run(() => host.InitializeAsync());
98
            }, CancellationToken.None, ForegroundThreadAffinitizedObject.CurrentForegroundThreadData.TaskScheduler).ConfigureAwait(false);
99 100
        }

101
        private ServiceHubRemoteHostClient(
H
Heejae Chang 已提交
102
            Workspace workspace, HubClient hubClient, HostGroup hostGroup, Stream stream) :
H
Heejae Chang 已提交
103 104 105
            base(workspace)
        {
            _hubClient = hubClient;
106
            _hostGroup = hostGroup;
107
            _timeout = TimeSpan.FromMilliseconds(workspace.Options.GetOption(RemoteHostOptions.RequestServiceTimeoutInMS));
H
Heejae Chang 已提交
108

109
            _rpc = new JsonRpc(new JsonRpcMessageHandler(stream, stream), target: this);
110
            _rpc.JsonSerializer.Converters.Add(AggregateJsonConverter.Instance);
H
Heejae Chang 已提交
111 112 113

            // handle disconnected situation
            _rpc.Disconnected += OnRpcDisconnected;
114 115

            _rpc.StartListening();
H
Heejae Chang 已提交
116 117
        }

118
        public override async Task<Connection> TryCreateConnectionAsync(string serviceName, object callbackTarget, CancellationToken cancellationToken)
H
Heejae Chang 已提交
119 120
        {
            // get stream from service hub to communicate snapshot/asset related information
121
            // this is the back channel the system uses to move data between VS and remote host for solution related information
122
            var snapshotStream = await RequestServiceAsync(_hubClient, WellKnownServiceHubServices.SnapshotService, _hostGroup, _timeout, cancellationToken).ConfigureAwait(false);
H
Heejae Chang 已提交
123 124 125

            // get stream from service hub to communicate service specific information
            // this is what consumer actually use to communicate information
126
            var serviceStream = await RequestServiceAsync(_hubClient, serviceName, _hostGroup, _timeout, cancellationToken).ConfigureAwait(false);
H
Heejae Chang 已提交
127

128
            return new ServiceHubJsonRpcConnection(callbackTarget, serviceStream, snapshotStream, cancellationToken);
H
Heejae Chang 已提交
129 130
        }

131
        protected override void OnStarted()
H
Heejae Chang 已提交
132 133 134
        {
        }

135
        protected override void OnStopped()
H
Heejae Chang 已提交
136
        {
137
            // we are asked to stop. unsubscribe and dispose to disconnect.
138 139 140 141 142
            // there are 2 ways to get disconnected. one is Roslyn decided to disconnect with RemoteHost (ex, cancellation or recycle OOP) and
            // the other is external thing disconnecting remote host from us (ex, user killing OOP process).
            // the Disconnected event we subscribe is to detect #2 case. and this method is for #1 case. so when we are willingly disconnecting
            // we don't need the event, otherwise, Disconnected event will be called twice.
            _rpc.Disconnected -= OnRpcDisconnected;
H
Heejae Chang 已提交
143 144 145 146 147
            _rpc.Dispose();
        }

        private void OnRpcDisconnected(object sender, JsonRpcDisconnectedEventArgs e)
        {
148
            Stopped();
H
Heejae Chang 已提交
149
        }
150

151 152 153 154 155 156
        private static async Task<Stream> RequestServiceAsync(
            HubClient client,
            string serviceName,
            HostGroup hostGroup,
            TimeSpan timeout,
            CancellationToken cancellationToken = default(CancellationToken))
157
        {
H
Heejae Chang 已提交
158 159 160
            const int max_retry = 10;
            const int retry_delayInMS = 50;

161 162 163 164 165
            Exception lastException = null;

            var descriptor = new ServiceDescriptor(serviceName) { HostGroup = hostGroup };

            // call to get service can fail due to this bug - devdiv#288961 or more.
H
Heejae Chang 已提交
166 167
            // until root cause is fixed, we decide to have retry rather than fail right away
            for (var i = 0; i < max_retry; i++)
168 169 170 171 172 173 174
            {
                try
                {
                    return await RequestServiceAsync(client, descriptor, timeout, cancellationToken).ConfigureAwait(false);
                }
                catch (RemoteInvocationException ex)
                {
175 176 177 178 179 180 181 182 183
                    // save info only if it failed with different issue than before.
                    if (lastException?.Message != ex.Message)
                    {
                        // RequestServiceAsync should never fail unless service itself is actually broken.
                        // So far, we catched multiple issues from this NFW. so we will keep this NFW.
                        WatsonReporter.Report("RequestServiceAsync Failed", ex, ReportDetailInfo);

                        lastException = ex;
                    }
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
                }

                // wait for retry_delayInMS before next try
                await Task.Delay(retry_delayInMS, cancellationToken).ConfigureAwait(false);
            }

            // crash right away to get better dump. otherwise, we will get dump from async exception
            // which most likely lost all valuable data
            FatalError.ReportUnlessCanceled(lastException);
            GC.KeepAlive(lastException);

            // unreachable
            throw ExceptionUtilities.Unreachable;
        }

        private static async Task<Stream> RequestServiceAsync(HubClient client, ServiceDescriptor descriptor, TimeSpan timeout, CancellationToken cancellationToken = default(CancellationToken))
        {
            // we are wrapping HubClient.RequestServiceAsync since we can't control its internal timeout value ourselves.
            // we have bug opened to track the issue.
            // https://devdiv.visualstudio.com/DefaultCollection/DevDiv/Editor/_workitems?id=378757&fullScreen=false&_a=edit
            const int retry_delayInMS = 50;

            var start = DateTime.UtcNow;
            while (start - DateTime.UtcNow < timeout)
208
            {
H
Heejae Chang 已提交
209 210 211 212 213 214
                cancellationToken.ThrowIfCancellationRequested();

                try
                {
                    return await client.RequestServiceAsync(descriptor, cancellationToken).ConfigureAwait(false);
                }
215 216 217 218 219 220 221 222 223 224
                catch (OperationCanceledException)
                {
                    // if it is our own cancellation token, then rethrow
                    // otherwise, let us retry.
                    //
                    // we do this since HubClient itself can throw its own cancellation token
                    // when it couldn't connect to service hub service for some reasons
                    // (ex, OOP process GC blocked and not responding to request)
                    cancellationToken.ThrowIfCancellationRequested();
                }
H
Heejae Chang 已提交
225 226 227

                // wait for retry_delayInMS before next try
                await Task.Delay(retry_delayInMS, cancellationToken).ConfigureAwait(false);
228
            }
H
Heejae Chang 已提交
229

230 231
            // request service to HubClient timed out, more than we are willing to wait
            throw new TimeoutException("RequestServiceAsync timed out");
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

        private static int ReportDetailInfo(IFaultUtility faultUtility)
        {
            // 0 means send watson, otherwise, cancel watson
            // we always send watson since dump itself can have valuable data
            var exitCode = 0;

            try
            {
                var logPath = Path.Combine(Path.GetTempPath(), "servicehub", "logs");
                if (!Directory.Exists(logPath))
                {
                    return exitCode;
                }

                // attach all log files that are modified less than 1 day before.
                var now = DateTime.UtcNow;
                var oneDay = TimeSpan.FromDays(1);

                foreach (var file in Directory.EnumerateFiles(logPath, "*.log"))
                {
                    var lastWrite = File.GetLastWriteTimeUtc(file);
                    if (now - lastWrite > oneDay)
                    {
                        continue;
                    }

                    faultUtility.AddFile(file);
                }
            }
            catch (Exception ex) when (ReportNonIOException(ex))
            {
            }

            return exitCode;
        }

        private static bool ReportNonIOException(Exception ex)
        {
            // IOException is expected. log other exceptions
            if (!(ex is IOException))
            {
                WatsonReporter.Report(ex);
            }

            // catch all exception. not worth crashing VS.
            return true;
        }
H
Heejae Chang 已提交
281
    }
282
}