Esempio n. 1
0
        /// <inheritdoc />
        public async ValueTask DisposeAsync()
        {
            lock (synchronizationLock)
            {
                if (disposed)
                {
                    return;
                }
                disposed = true;
            }

            logger.LogTrace("Disposing...");
            if (!released)
            {
                process.Terminate();
                byondLock.Dispose();
            }

            process.Dispose();
            bridgeRegistration?.Dispose();
            reattachInformation.Dmb?.Dispose();             // will be null when released
            chatTrackingContext.Dispose();
            reattachTopicCts.Dispose();

            if (!released)
            {
                // finish the async callback
                await Lifetime.ConfigureAwait(false);
            }
        }
Esempio n. 2
0
        public void Stop()
        {
            if (!IsRunning)
            {
                throw new InvalidOperationException("No job is running.");
            }

            UnsubscribeFromEvents(_process);

            _process.Kill();
            _process.WaitForExit(500);
            _process.Dispose();

            _process        = null;
            _sourceDuration = TimeSpan.Zero;
        }
 public void Dispose()
 {
     _tcs.TrySetCanceled();
     _process.Dispose();
     _ctRegistration.Dispose();
     _timeoutCts?.Dispose();
 }
Esempio n. 4
0
 /// <inheritdoc/>
 protected override void Dispose(bool disposing)
 {
     if (disposing)
     {
         // Do not Kill() the process; we didn't start it.
         process.Dispose();
     }
     base.Dispose(disposing);
 }
Esempio n. 5
0
        private void DisposeBrokerProcess()
        {
            try {
                _brokerProcess?.Kill();
            } catch (Exception) {
            }

            _brokerProcess?.Dispose();
        }
Esempio n. 6
0
        private async Task ConnectToBrokerWorkerAsync(CancellationToken cancellationToken)
        {
            Trace.Assert(_brokerProcess == null);
            var fs      = _services.FileSystem();
            var locator = new BrokerExecutableLocator(fs);

            var rhostBrokerExe = locator.GetBrokerExecutablePath();

            // _services.UI().LogMessage($"R Host broker: {rhostBrokerExe}");
            if (!fs.FileExists(rhostBrokerExe))
            {
                throw new RHostBrokerBinaryMissingException();
            }

            IProcess process = null;

            try {
                var pipeName = Guid.NewGuid().ToString();
                var cts      = new CancellationTokenSource(Debugger.IsAttached ? 500000 : 100000);

                using (var processConnectCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, cts.Token))
                    using (var serverUriPipe = new NamedPipeServerStream(pipeName, PipeDirection.In, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous)) {
                        var psi = GetProcessStartInfo(rhostBrokerExe, pipeName);
                        // _services.UI().LogMessage($"Starting R Host broker: {rhostBrokerExe}");
                        process         = StartBroker(psi);
                        process.Exited += delegate {
                            cts.Cancel();
                            _brokerProcess = null;
                            _connectLock.EnqueueReset();
                        };

                        var uri = await GetBrokerUri(serverUriPipe, processConnectCts.Token, cts.Token);

                        CreateHttpClient(uri);
                    }

                if (DisposableBag.TryAdd(DisposeBrokerProcess))
                {
                    _brokerProcess = process;
                }
            } catch (Exception ex) {
                _services.UI().LogMessage($"Unable to start R Host broker process. Exception {ex.Message}");
                throw;
            } finally {
                if (_brokerProcess == null)
                {
                    try {
                        process?.Kill();
                    } catch (Exception) {
                    } finally {
                        process?.Dispose();
                    }
                }
            }
        }
Esempio n. 7
0
        public void OpenInBrowser(Uri url)
        {
            IProcess start = null;

            try
            {
                start = _processWrapper.Start(url.ToString());
            }
            catch (TimeoutException)
            {
                //TODO: Remove this code as it is never used
                start?.Kill();
                start?.Dispose();
            }
            catch (System.Runtime.InteropServices.COMException)
            {
                //TODO: Remove this code as it is never used
                start?.Kill();
                start?.Dispose();
            }
        }
 protected override void DetachProfilingInternal()
 {
     if (ProcessId != 0)
     {
         IProcess process = _processProvider.GetProcessById(ProcessId);
         if (!process.HasExited)
         {
             process.Kill();
             process.Dispose();
         }
     }
 }
Esempio n. 9
0
            private void DisposeImpl(bool disposing)
            {
                if (!_disposed)
                {
                    if (disposing)
                    {
                        _process.WriteStandardInput(QuitLine);
                        _process.WaitForExit();
                        _process.Dispose();
                    }

                    _disposable.Dispose();
                    _disposed = true;
                }
            }
Esempio n. 10
0
            private void DisposeProcess(IProcess process)
            {
                lock (_mediaEncoder._runningProcesses)
                {
                    _mediaEncoder._runningProcesses.Remove(this);
                }

                try
                {
                    process.Dispose();
                }
                catch
                {
                }
            }
        /// <summary>
        /// Implements the <see cref="IDisposable"/> pattern
        /// </summary>
        /// <param name="disposing">If this function was NOT called by the finalizer</param>
        void Dispose(bool disposing)
        {
            lock (synchronizationLock)
            {
                if (disposed)
                {
                    return;
                }
                if (disposing)
                {
                    if (!released)
                    {
                        process.Terminate();
                        byondLock.Dispose();
                    }

                    process.Dispose();
                    bridgeRegistration.Dispose();
                    Dmb?.Dispose();                     // will be null when released
                    chatTrackingContext.Dispose();
                    reattachTopicCts.Dispose();
                    disposed = true;
                }
                else
                {
                    if (logger != null)
                    {
                        logger.LogError("Being disposed via finalizer!");
                    }
                    if (!released)
                    {
                        if (process != null)
                        {
                            process.Terminate();
                        }
                        else if (logger != null)
                        {
                            logger.LogCritical("Unable to terminate active DreamDaemon session due to finalizer ordering!");
                        }
                    }
                }
            }
        }
Esempio n. 12
0
        /// <summary>
        /// Implements the <see cref="IDisposable"/> pattern
        /// </summary>
        /// <param name="disposing">If this function was NOT called by the finalizer</param>
        void Dispose(bool disposing)
        {
            lock (this)
            {
                if (disposed)
                {
                    return;
                }
                if (disposing)
                {
                    if (!released)
                    {
                        process.Terminate();
                        byondLock.Dispose();
                    }

                    process.Dispose();
                    interopContext.Dispose();
                    Dmb?.Dispose();                     // will be null when released
                    chatJsonTrackingContext.Dispose();
                    disposed = true;
                }
                else
                {
                    if (logger != null)
                    {
                        logger.LogError("Being disposed via finalizer!");
                    }
                    if (!released)
                    {
                        if (process != null)
                        {
                            process.Terminate();
                        }
                        else if (logger != null)
                        {
                            logger.LogCritical("Unable to terminate active DreamDaemon session due to finalizer ordering!");
                        }
                    }
                }
            }
        }
Esempio n. 13
0
 public void Dispose()
 {
     decoratedProcess.ErrorDataReceived  -= this.OnErrorLineReceived;
     decoratedProcess.OutputDataReceived -= this.OnErrorLineReceived;
     decoratedProcess.Dispose();
 }
Esempio n. 14
0
 public virtual void Dispose()
 {
     _process.Dispose();
 }
Esempio n. 15
0
 /// <summary>
 /// Ejecuta dispose del procesador específico
 /// </summary>
 public void Dispose()
 {
     _processManager.Dispose();
 }
 public void Dispose()
 {
     serverProcess?.Dispose();
     clientStream?.Dispose();
 }
 public void Dispose()
 {
     _process.Dispose();
     _thread.Dispose();
 }
Esempio n. 18
0
 private void DisposeProcess()
 {
     _process.Dispose();
     _ctRegistration.Dispose();
     _timeoutCts?.Dispose();
 }
Esempio n. 19
0
        private void ExecuteProcess(IProcessDetails pd, HandlerEventArgs hargs)
        {
            IProcess        process  = null;
            IExecuteResults execRes  = null;
            var             transId  = Guid.NewGuid();
            Stopwatch       durWatch = null;
            long?           duration = null;

            bool hasDuration = false;

            try
            {
                IArguments pargs = null;

                // if there are any constructors with 1
                var ctors = pd.ProcessType.GetConstructors()
                            .Where(c => c.GetParameters().Count() == 1);

                if (ctors.Any())
                {
                    if (hargs is DirWatcherEventArgs)
                    {
                        var wa = (DirWatcherEventArgs)hargs;
                        pargs = new WatcherArguments(new TieFileInfo(wa.FullePath), pd.Id, pd.Name, DateTime.Now,
                                                     hargs.TriggerId, hargs.TriggerName, transId);

                        process = (TieProcess <WatcherArguments>)Activator.CreateInstance(pd.ProcessType, pargs);
                    }
                    else
                    {
                        var sa = (CronSchedulerEventArgs)hargs;
                        pargs = new SchedulerArguments(sa.QuartzCronExpression, pd.Id, pd.Name, DateTime.Now,
                                                       hargs.TriggerId, hargs.TriggerName, transId);


                        process = (TieProcess <SchedulerArguments>)Activator.CreateInstance(pd.ProcessType, pargs);
                    }
                }
                else
                {
                    // check if default constructor is present
                    var dctor = pd.ProcessType.GetConstructor(Type.EmptyTypes);

                    if (dctor != null)
                    {
                        process = (IProcess)Activator.CreateInstance(pd.ProcessType);
                    }
                }

                if (process != null)
                {
                    this._activeProcesses.Add(process);

                    durWatch = Stopwatch.StartNew();

                    execRes = process.Execute();

                    duration = durWatch.ElapsedMilliseconds;
                    durWatch.Stop();

                    hasDuration = true;
                }
            }
            catch (Exception pex)
            {
                // log error
                if (execRes == null)
                {
                    execRes = new ExecuteResults(false, ExecutionState.Failed, transId);
                }

                execRes.Errors.Add(pex.ToString());
            }
            finally
            {
                if (!hasDuration)
                {
                    duration = durWatch?.ElapsedMilliseconds;
                }


                if (execRes == null)
                {// here for backwards compatibility
                    execRes = new ExecuteResults(true, ExecutionState.ProcessCompatExec, transId);
                }

                ProcessExecutionResults(execRes, pd);

                if (process != null)
                {
                    this._activeProcesses.TryTake(out process);
                    this._logger.LogMessage(new StatusMessage("tie", $"{this._activeProcesses.Count} active processes"), process.GetHashCode().ToString());

                    process.Dispose();
                    process = null;
                }
                else
                {
                    // log that process was null and no work was performed
                    // give hargs details
                }
            }
        }
Esempio n. 20
0
        private async Task ConnectToBrokerWorker(CancellationToken cancellationToken)
        {
            Trace.Assert(_brokerProcess == null);

            var rhostExe = Path.Combine(_rhostDirectory, RHostExe);

            if (!_services.FileSystem().FileExists(rhostExe))
            {
                throw new RHostBinaryMissingException();
            }

            var rhostBrokerExe = Path.Combine(_rhostDirectory, RHostBrokerExe);

            if (!_services.FileSystem().FileExists(rhostBrokerExe))
            {
                throw new RHostBrokerBinaryMissingException();
            }

            IProcess process = null;

            try {
                var pipeName = Guid.NewGuid().ToString();
                var cts      = new CancellationTokenSource(100000);

                using (var processConnectCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, cts.Token))
                    using (var serverUriPipe = new NamedPipeServerStream(pipeName, PipeDirection.In, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous)) {
                        var psi = new ProcessStartInfo {
                            FileName        = rhostBrokerExe,
                            UseShellExecute = false,
                            Arguments       =
                                $" --logging:logFolder \"{Log.Folder.TrimTrailingSlash()}\"" +
                                $" --logging:logHostOutput {Log.LogVerbosity >= LogVerbosity.Normal}" +
                                $" --logging:logPackets {Log.LogVerbosity == LogVerbosity.Traffic}" +
                                $" --urls http://127.0.0.1:0" + // :0 means first available ephemeral port
                                $" --startup:name \"{Name}\"" +
                                $" --startup:writeServerUrlsToPipe {pipeName}" +
                                $" --lifetime:parentProcessId {Process.GetCurrentProcess().Id}" +
                                $" --security:secret \"{_credentials.Password}\"" +
                                $" --R:autoDetect false" +
                                $" --R:interpreters:{InterpreterId}:name \"{Name}\"" +
                                $" --R:interpreters:{InterpreterId}:basePath \"{_rHome.TrimTrailingSlash()}\""
                        };

                        if (!ShowConsole)
                        {
                            psi.CreateNoWindow = true;
                        }

                        process = StartBroker(psi);

                        process.Exited += delegate {
                            cts.Cancel();
                            _brokerProcess = null;
                            _connectLock.EnqueueReset();
                        };

                        await serverUriPipe.WaitForConnectionAsync(processConnectCts.Token);

                        var serverUriData = new MemoryStream();
                        try {
                            // Pipes are special in that a zero-length read is not an indicator of end-of-stream.
                            // Stream.CopyTo uses a zero-length read as indicator of end-of-stream, so it cannot
                            // be used here. Instead, copy the data manually, using PipeStream.IsConnected to detect
                            // when the other side has finished writing and closed the pipe.
                            var buffer = new byte[0x1000];
                            do
                            {
                                var count = await serverUriPipe.ReadAsync(buffer, 0, buffer.Length, cts.Token);

                                serverUriData.Write(buffer, 0, count);
                            } while (serverUriPipe.IsConnected);
                        } catch (OperationCanceledException) {
                            throw new RHostDisconnectedException("Timed out while waiting for broker process to report its endpoint URI");
                        }

                        var   serverUriStr = Encoding.UTF8.GetString(serverUriData.ToArray());
                        Uri[] serverUri;
                        try {
                            serverUri = Json.DeserializeObject <Uri[]>(serverUriStr);
                        } catch (JsonSerializationException ex) {
                            throw new RHostDisconnectedException($"Invalid JSON for endpoint URIs received from broker ({ex.Message}): {serverUriStr}");
                        }
                        if (serverUri?.Length != 1)
                        {
                            throw new RHostDisconnectedException($"Unexpected number of endpoint URIs received from broker: {serverUriStr}");
                        }

                        CreateHttpClient(serverUri[0]);
                    }

                if (DisposableBag.TryAdd(DisposeBrokerProcess))
                {
                    _brokerProcess = process;
                }
            } finally {
                if (_brokerProcess == null)
                {
                    try {
                        process?.Kill();
                    } catch (Exception) {
                    } finally {
                        process?.Dispose();
                    }
                }
            }
        }
Esempio n. 21
0
 public void Dispose()
 {
     _process.Dispose();
 }
Esempio n. 22
0
        public async Task StartAsync(Action exited)
        {
            var rhostExe = Path.Combine(_rhostDirectory, RHostExe);

            if (!_fileSystem.FileExists(rhostExe))
            {
                throw new RHostBinaryMissingException();
            }

            var rhostBrokerExe = Path.Combine(_rhostBrokerDirectory, RHostBrokerExe);

            if (!_fileSystem.FileExists(rhostBrokerExe))
            {
                throw new RHostBrokerBinaryMissingException();
            }

            var rHome = _installations.GetCompatibleEngines().First().InstallPath;

            IProcess process = null;

            try {
                var psi = new ProcessStartInfo {
                    FileName        = rhostBrokerExe,
                    UseShellExecute = false,
                    CreateNoWindow  = false,
                    Arguments       =
                        $" --logging:logFolder \"{_logFolder.TrimTrailingSlash()}\"" +
                        $" --logging:logHostOutput true" +
                        $" --logging:logPackets true" +
                        $" --urls http://127.0.0.1:0" + // :0 means first available ephemeral port
                        $" --startup:name \"{_name}\"" +
                        $" --lifetime:parentProcessId {Process.GetCurrentProcess().Id}" +
                        $" --security:secret \"{Password}\"" +
                        $" --R:autoDetect false" +
                        $" --R:interpreters:test:name \"{_name}\"" +
                        $" --R:interpreters:test:basePath \"{rHome.TrimTrailingSlash()}\""
                };

                process         = StartBroker(psi);
                process.Exited += (sender, e) => exited();

                var port = ProcessUtils.GetPortByProcessId(process.Id).FirstOrDefault();
                while (port == 0)
                {
                    await Task.Delay(100);

                    port = ProcessUtils.GetPortByProcessId(process.Id).FirstOrDefault();
                }

                Address        = $"http://127.0.0.1:{port}";
                _brokerProcess = process;
            } finally {
                if (_brokerProcess == null)
                {
                    try {
                        process?.Kill();
                    } catch (Exception) {
                    } finally {
                        process?.Dispose();
                    }
                }
            }
        }
Esempio n. 23
0
 public override void Dispose()
 {
     _process.Dispose();
 }
        public static async Task <CMakeConversation> Start(IProcessManager processManager,
                                                           IBinariesLocator binariesLocator,
                                                           IOutputFormatterPool formatterPool,
                                                           VirtualDirectory tempDirectory, bool isWindowsSystem,
                                                           ExecutionContext executionContext,
                                                           VirtualDirectory sourceDirectory,
                                                           VirtualDirectory binaryDirectory)
        {
            IProcess process = null;
            NamedPipeClientStream pipeClient = null;

            try
            {
                string pipeName = isWindowsSystem
                                      ? $"{tempDirectory.FullName}\\.cmakeserver"
                                      : $"/tmp/cmake-server-{Guid.NewGuid().ToByteString()}";
                string serverCommand = isWindowsSystem
                                           ? $"-E server --experimental --pipe=\"\\\\?\\pipe\\{pipeName}\""
                                           : $"-E server --experimental --pipe={pipeName}";
                process    = processManager.StartProcess(binariesLocator.GetExecutableCommand("cmake"), serverCommand, executionContext);
                pipeClient = new NamedPipeClientStream(".", pipeName,
                                                       PipeDirection.InOut, PipeOptions.Asynchronous,
                                                       TokenImpersonationLevel.Impersonation);
                pipeClient.Connect(CMakeServerTimeout);
                if (!pipeClient.IsConnected)
                {
                    throw new FormattableException("Could not connect to server");
                }

                FormatterParameters parameters = new FormatterParameters();
                parameters.Add("cmake-json", MessageFormat);
                IUserInterface jsonCmakeInterface = formatterPool.GetFormatter(parameters, executionContext);

                CMakeServerStream serverStream = new CMakeServerStream(pipeClient, executionContext);
                CMakeHelloMessage hello        = null;
                do
                {
                    foreach (string singleMessage in await serverStream.ReadMessage()
                             .TimeoutAfter(CMakeServerTimeout)
                             .ConfigureAwait(false))
                    {
                        hello = CMakeMessage.Parse <CMakeMessage>(singleMessage, jsonCmakeInterface) as CMakeHelloMessage;
                    }
                } while (hello == null);

                if (hello.SupportedProtocolVersions.All(v => v.Major != 1))
                {
                    throw new FormattableException("CMake server does not support the protocol version 1.X. " +
                                                   $"Supported versions are {string.Join(", ", hello.SupportedProtocolVersions)}");
                }

                CMakeConversation conversation = new CMakeConversation(process, pipeClient, serverStream, jsonCmakeInterface);

                await conversation.Handshake(sourceDirectory.FullName.Replace('\\', '/'),
                                             binaryDirectory.FullName.Replace('\\', '/'))
                .ConfigureAwait(false);

                await conversation.Configure().ConfigureAwait(false);

                return(conversation);
            }
            catch (Exception)
            {
                pipeClient?.Dispose();
                process?.Dispose();
                throw;
            }
        }