BuildClient.cs 16.5 KB
Newer Older
1 2 3 4 5 6 7
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Pipes;
8
using System.Linq;
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CompilerServer;
using static Microsoft.CodeAnalysis.BuildTasks.NativeMethods;
using static Microsoft.CodeAnalysis.CompilerServer.BuildProtocolConstants;
using static Microsoft.CodeAnalysis.CompilerServer.CompilerServerLogger;

namespace Microsoft.CodeAnalysis.BuildTasks
{
    /// <summary>
    /// Client class that handles communication to the server.
    /// </summary>
    internal static class BuildClient
    {
27
        private const string s_serverName = "VBCSCompiler.exe";
28 29 30 31 32
        // Spend up to 1s connecting to existing process (existing processes should be always responsive).
        private const int TimeOutMsExistingProcess = 1000;
        // Spend up to 20s connecting to a new process, to allow time for it to start.
        private const int TimeOutMsNewProcess = 20000; 

33 34 35 36 37 38 39
        /// <summary>
        /// Run a compilation through the compiler server and print the output
        /// to the console. If the compiler server fails, run the fallback
        /// compiler.
        /// </summary>
        public static int RunWithConsoleOutput(
            string[] args,
40 41
            string clientDir,
            string workingDir,
42
            RequestLanguage language,
43
            Func<string, string[], int> fallbackCompiler)
44
        {
45
            args = args.Select(arg => arg.Trim()).ToArray();
46

47
            bool hasShared;
48 49 50 51 52 53 54 55 56
            string keepAlive;
            string errorMessage;
            List<string> parsedArgs;
            if (!CommandLineParser.TryParseClientArgs(
                    args,
                    out parsedArgs,
                    out hasShared,
                    out keepAlive,
                    out errorMessage))
57 58 59 60 61
            {
                Console.Out.WriteLine(errorMessage);
                return CommonCompiler.Failed;
            }

62
            if (hasShared)
63
            {
64 65
                var responseTask = TryRunServerCompilation(
                    language,
66 67
                    clientDir,
                    workingDir,
68
                    parsedArgs,
69
                    default(CancellationToken),
70
                    keepAlive: keepAlive,
71 72 73 74 75 76 77
                    libEnvVariable: Environment.GetEnvironmentVariable("LIB"));

                var response = responseTask.Result;
                if (response != null)
                {
                    return HandleResponse(response);
                }
78 79
            }

80
            return fallbackCompiler(clientDir, parsedArgs.ToArray());
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
        }

        private static int HandleResponse(BuildResponse response)
        {
            if (response.Type == BuildResponse.ResponseType.Completed)
            {
                var completedResponse = (CompletedBuildResponse)response;
                var origEncoding = Console.OutputEncoding;
                try
                {
                    if (completedResponse.Utf8Output && Console.IsOutputRedirected)
                    {
                        Console.OutputEncoding = Encoding.UTF8;
                    }
                    Console.Out.Write(completedResponse.Output);
                    Console.Error.Write(completedResponse.ErrorOutput);
                }
                finally
                {
                    try
                    {
                        Console.OutputEncoding = origEncoding;
                    }
                    catch
                    { // Try to reset the output encoding, ignore if we can't
                    }
                }
                return completedResponse.ReturnCode;
            }
            else
            {
                Console.Error.WriteLine(CommandLineParser.MismatchedVersionErrorText);
                return CommonCompiler.Failed;
            }
        }

117 118 119 120 121 122
        /// <summary>
        /// Returns a Task with a null BuildResponse if no server
        /// response was received.
        /// </summary>
        public static Task<BuildResponse> TryRunServerCompilation(
            RequestLanguage language,
123
            string clientDir, 
124 125 126
            string workingDir,
            IList<string> arguments,
            CancellationToken cancellationToken,
127
            string keepAlive = null,
128
            string libEnvVariable = null)
129
        {
130
            try
131
            {
132
                NamedPipeClientStream pipe;
133

134 135 136
                if (clientDir == null)
                    return Task.FromResult<BuildResponse>(null);

137
                var pipeName = GetPipeName(clientDir);
138 139
                bool holdsMutex;
                using (var mutex = new Mutex(initiallyOwned: true,
140
                                             name: pipeName,
141 142 143
                                             createdNew: out holdsMutex))
                {
                    try
144 145
                    {

146
                        if (!holdsMutex)
147
                        {
148 149
                            try
                            {
J
Jared Parsons 已提交
150
                                holdsMutex = mutex.WaitOne(TimeOutMsNewProcess);
151 152 153 154 155
                            }
                            catch (AbandonedMutexException)
                            {
                                holdsMutex = true;
                            }
156
                        }
157 158

                        if (holdsMutex)
159
                        {
160
                            var request = BuildRequest.Create(language, workingDir, arguments, keepAlive, libEnvVariable);
161
                            // Check for already running processes in case someone came in before us
162 163 164
                            if (null != (pipe = TryConnectToProcess(pipeName,
                                                                    TimeOutMsExistingProcess,
                                                                    cancellationToken)))
165 166 167
                            {
                                return TryCompile(pipe, request, cancellationToken);
                            }
168 169
                            else
                            {
170 171
                                if (TryCreateServerProcess(clientDir) &&
                                    null != (pipe = TryConnectToProcess(pipeName,
172 173 174 175 176 177 178 179 180 181
                                                                        TimeOutMsNewProcess,
                                                                        cancellationToken)))
                                {
                                    // Let everyone else access our process
                                    mutex.ReleaseMutex();
                                    holdsMutex = false;

                                    return TryCompile(pipe, request, cancellationToken);
                                }
                            }
182 183
                        }
                    }
184 185 186 187 188
                    finally
                    {
                        if (holdsMutex)
                            mutex.ReleaseMutex();
                    }
189 190
                }
            }
191 192 193 194 195 196 197
            // Swallow all unhandled exceptions from server compilation. If
            // they are show-stoppers then they will crash the in-proc
            // compilation as well
            // TODO: Put in non-fatal Watson code so we still get info
            // when things unexpectedely fail
            catch { }
            return Task.FromResult<BuildResponse>(null);
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
        }

        /// <summary>
        /// Try to compile using the server. Returns null if a response from the
        /// server cannot be retrieved.
        /// </summary>
        private static async Task<BuildResponse> TryCompile(NamedPipeClientStream pipeStream,
                                                            BuildRequest request,
                                                            CancellationToken cancellationToken)
        {
            BuildResponse response;
            using (pipeStream)
            {
                // Write the request
                try
                {
                    Log("Begin writing request");
                    await request.WriteAsync(pipeStream, cancellationToken).ConfigureAwait(false);
                    Log("End writing request");
                }
                catch (Exception e)
                {
                    LogException(e, "Error writing build request.");
                    return null;
                }

                // Wait for the compilation and a monitor to dectect if the server disconnects
                var serverCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);

                Log("Begin reading response");

                var responseTask = BuildResponse.ReadAsync(pipeStream, serverCts.Token);
                var monitorTask = CreateMonitorDisconnectTask(pipeStream, serverCts.Token);
                await Task.WhenAny(responseTask, monitorTask).ConfigureAwait(false);

                Log("End reading response");

                if (responseTask.IsCompleted)
                {
                    // await the task to log any exceptions
                    try
                    {
                        response = await responseTask.ConfigureAwait(false);
                    }
                    catch (Exception e)
                    {
                        LogException(e, "Error reading response");
                        response = null;
                    }
                }
                else
                {
                    Log("Server disconnect");
                    response = null;
                }

                // Cancel whatever task is still around
                serverCts.Cancel();
                return response;
            }
        }

        /// <summary>
        /// The IsConnected property on named pipes does not detect when the client has disconnected
        /// if we don't attempt any new I/O after the client disconnects. We start an async I/O here
        /// which serves to check the pipe for disconnection. 
        ///
        /// This will return true if the pipe was disconnected.
        /// </summary>
        private static async Task CreateMonitorDisconnectTask(
            NamedPipeClientStream pipeStream,
            CancellationToken cancellationToken)
        {
            var buffer = new byte[0];

            while (!cancellationToken.IsCancellationRequested && pipeStream.IsConnected)
            {
                // Wait a tenth of a second before trying again
                await Task.Delay(100, cancellationToken).ConfigureAwait(false);

                try
                {
                    Log("Before poking pipe.");
                    await pipeStream.ReadAsync(buffer, 0, 0, cancellationToken).ConfigureAwait(false);
                    Log("After poking pipe.");
                }
                // Ignore cancellation
                catch (OperationCanceledException) { }
                catch (Exception e)
                {
                    // It is okay for this call to fail.  Errors will be reflected in the 
                    // IsConnected property which will be read on the next iteration of the 
                    LogException(e, "Error poking pipe");
                }
            }
        }

        /// <summary>
        /// Get the file path of the executable that started this process.
        /// </summary>
        /// <param name="processHandle"></param>
        /// <param name="flags">Should always be 0: Win32 path format.</param>
        /// <param name="exeNameBuffer">Buffer for the name</param>
        /// <param name="bufferSize">
        /// Size of the buffer coming in, chars written coming out.
        /// </param>
        [DllImport("Kernel32.dll", EntryPoint = "QueryFullProcessImageNameW", CharSet = CharSet.Unicode)]
        static extern bool QueryFullProcessImageName(
            IntPtr processHandle,
            int flags,
            StringBuilder exeNameBuffer,
            ref int bufferSize);

        private const int MAX_PATH_SIZE = 260;

        /// <summary>
314
        /// Connect to the pipe for a given directory and return it.
315 316
        /// Throws on cancellation.
        /// </summary>
317
        /// <param name="pipeName">Name of the named pipe to connect to.</param>
318 319 320 321 322 323
        /// <param name="timeoutMs">Timeout to allow in connecting to process.</param>
        /// <param name="cancellationToken">Cancellation token to cancel connection to server.</param>
        /// <returns>
        /// An open <see cref="NamedPipeClientStream"/> to the server process or null on failure.
        /// </returns>
        private static NamedPipeClientStream TryConnectToProcess(
324
            string pipeName,
325 326 327 328 329 330 331
            int timeoutMs,
            CancellationToken cancellationToken)
        {
            NamedPipeClientStream pipeStream;
            try
            {
                // Machine-local named pipes are named "\\.\pipe\<pipename>".
332
                // We use the SHA1 of the directory the compiler exes live in as the pipe name.
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
                // The NamedPipeClientStream class handles the "\\.\pipe\" part for us.
                Log("Attempt to open named pipe '{0}'", pipeName);

                pipeStream = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.Asynchronous);
                cancellationToken.ThrowIfCancellationRequested();

                Log("Attempt to connect named pipe '{0}'", pipeName);
                pipeStream.Connect(timeoutMs);
                Log("Named pipe '{0}' connected", pipeName);

                cancellationToken.ThrowIfCancellationRequested();

                // Verify that we own the pipe.
                SecurityIdentifier currentIdentity = WindowsIdentity.GetCurrent().Owner;
                PipeSecurity remoteSecurity = pipeStream.GetAccessControl();
                IdentityReference remoteOwner = remoteSecurity.GetOwner(typeof(SecurityIdentifier));
                if (remoteOwner != currentIdentity)
                {
                    Log("Owner of named pipe is incorrect");
                    return null;
                }

                return pipeStream;
            }
            catch (Exception e) when (!(e is TaskCanceledException))
            {
                LogException(e, "Exception while connecting to process");
                return null;
            }
        }

        /// <summary>
365 366
        /// Create a new instance of the server process, returning true on success
        /// and false otherwise.
367
        /// </summary>
368
        private static bool TryCreateServerProcess(string clientDir)
369
        {
370 371 372 373 374 375
            // The server should be in the same directory as the client
            string expectedPath = Path.Combine(clientDir, s_serverName);

            if (!File.Exists(expectedPath))
                return false;

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
            // As far as I can tell, there isn't a way to use the Process class to 
            // create a process with no stdin/stdout/stderr, so we use P/Invoke.
            // This code was taken from MSBuild task starting code.

            STARTUPINFO startInfo = new STARTUPINFO();
            startInfo.cb = Marshal.SizeOf(startInfo);
            startInfo.hStdError = InvalidIntPtr;
            startInfo.hStdInput = InvalidIntPtr;
            startInfo.hStdOutput = InvalidIntPtr;
            startInfo.dwFlags = STARTF_USESTDHANDLES;
            uint dwCreationFlags = NORMAL_PRIORITY_CLASS | CREATE_NO_WINDOW;

            PROCESS_INFORMATION processInfo;

            Log("Attempting to create process '{0}'", expectedPath);

            bool success = CreateProcess(
                expectedPath,
                null,            // command line
                NullPtr,         // process attributes
                NullPtr,         // thread attributes
                false,           // don't inherit handles
                dwCreationFlags,
                NullPtr,         // inherit environment
                Path.GetDirectoryName(expectedPath),    // current directory
                ref startInfo,
                out processInfo);

            if (success)
            {
                Log("Successfully created process with process id {0}", processInfo.dwProcessId);
                CloseHandle(processInfo.hProcess);
                CloseHandle(processInfo.hThread);
            }
            else
            {
                Log("Failed to create process. GetLastError={0}", Marshal.GetLastWin32Error());
            }
414
            return success;
415 416 417
        }
    }
}