Ejemplo n.º 1
0
        /// <summary>
        /// Triggered when the application host is ready to start the service.
        /// </summary>
        /// <param name="cancellationToken">Indicates that the start process has been aborted.</param>
        /// <returns>Task.</returns>
        /// <autogeneratedoc />
        public Task StartAsync(CancellationToken cancellationToken)
        {
            ServiceHostStatus  = ServiceHostStatus.StartPending;
            LocalNetworkDevice = DiscoverLocalNetworkDevice();

            _logger?.LogInformation("NetworkMap Service Started on Primary Network: {PrimaryIPAddressSubnet}",
                                    LocalNetworkDevice?.LocalNetworks?.PrimaryNetwork?.NetworkIPAddressSubnet);

            ServiceHostStatus = ServiceHostStatus.Running;
            return(Task.CompletedTask);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Discovers the local network device.
        /// </summary>
        /// <returns>ILocalNetworkDevice.</returns>
        /// <autogeneratedoc />
        private ILocalNetworkDevice DiscoverLocalNetworkDevice()
        {
            var localComputer = new LocalComputer(CommonNetworkServices, DeviceType.LocalComputer);

            var networkAdapters = localComputer.NetworkAdapters;

            if (networkAdapters.Count == 0)
            {
                _logger.LogInformation("LocalComputer: No Network Adapters Found");
            }

            return(localComputer);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Stops the service listener if in started state.
        /// </summary>
        /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
        /// <exception cref="InvalidOperationException">SocketListener is not active and must be started before stopping</exception>
        public bool Stop()
        {
            try
            {
                if (!IsActive)
                {
                    throw new InvalidOperationException(
                              "SocketListener is not active and must be started before stopping");
                }

                IsActive = false;

                Logger?.LogInformation("SocketListener stopped listening for requests on {LocalEndPoint}",
                                       Socket.LocalEndPoint);

                return(true);
            }
            catch (Exception ex)
            {
                Logger?.LogError(ex, "SocketLister stop failed");
            }

            return(false);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Runs a process, optionally killing the process if it has not completed
        /// in the given timeout. Returns the combined contents of stdout/stderr,
        /// along with whether the job completed in the given timeout.
        /// </summary>
        /// <param name="path">The path.</param>
        /// <param name="args">The arguments.</param>
        /// <param name="timeout">The timeout.</param>
        /// <returns>Task&lt;ProcessResult&gt;.</returns>
        /// <exception cref="ArgumentNullException">
        /// path
        /// or
        /// args
        /// </exception>
        /// <autogeneratedoc />
        public async Task <ProcessResult> RunProcessAsync(
            string path,
            string[] args,
            TimeSpan?timeout)
        {
            if (path == null)
            {
                throw new ArgumentNullException(nameof(path));
            }
            if (args == null)
            {
                throw new ArgumentNullException(nameof(args));
            }

            var output     = new ConcurrentQueue <string>();
            var processTcs = new TaskCompletionSource <bool>();

            var process = new Process
            {
                StartInfo = new ProcessStartInfo
                {
                    FileName  = path,
                    Arguments = string.Join(" ", args),
                    RedirectStandardOutput = true,
                    RedirectStandardError  = true,
                    UseShellExecute        = false,
                    CreateNoWindow         = true
                },

                EnableRaisingEvents = true
            };

            process.OutputDataReceived += (sender, e) => { output.Enqueue(e.Data); };

            process.ErrorDataReceived += (sender, e) => { output.Enqueue(e.Data); };

            process.Exited += (sender, e) => { processTcs.TrySetResult(true); };

            _logger?.LogInformation("Starting process {processName} with arguments {arguments}.",
                                    process.StartInfo.FileName,
                                    process.StartInfo.Arguments);

            process.Start();
            process.BeginOutputReadLine();
            process.BeginErrorReadLine();

            if (timeout != null)
            {
                await Task.WhenAny(processTcs.Task, Task.Delay(timeout.Value));
            }
            else
            {
                await processTcs.Task;
            }

            var completed = process.HasExited;

            if (!completed)
            {
                process.Kill();
            }

            var cRetries = 5;

            // Add delay to allow output to be processed
            while (output.Count == 0 && cRetries-- > 0)
            {
                // Wait 100 ms
                await Task.Delay(100);
            }

            var outputStr = string.Join("\n", output);

            var truncatedOutputStr = outputStr.Length > 1000
                ? outputStr.Substring(outputStr.Length - 1000)
                : outputStr;

            _logger?.LogInformation
            (
                "Process {processName} with arguments {arguments} finished with status {status}",
                process.StartInfo.FileName,
                process.StartInfo.Arguments,
                completed ? "Completed" : "Timeout"
            );

            _logger?.LogTrace("Process {processName} with arguments {arguments} truncated output: \n{output}",
                              process.StartInfo.FileName,
                              process.StartInfo.Arguments,
                              truncatedOutputStr);

            return(new ProcessResult(completed, outputStr));
        }