log actions messages

master
Tudor Stanciu 2022-01-12 18:53:22 +02:00
parent b308913d9e
commit 6411f29723
5 changed files with 56 additions and 53 deletions

View File

@ -3,5 +3,6 @@
public interface ICliService public interface ICliService
{ {
(bool success, string message) Execute(string command); (bool success, string message) Execute(string command);
(bool success, string message) Shutdown(string arguments);
} }
} }

View File

@ -9,5 +9,10 @@ namespace NetworkResurrector.Agent.Application.Services.Linux
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public (bool success, string message) Shutdown(string arguments)
{
throw new NotImplementedException();
}
} }
} }

View File

@ -7,15 +7,13 @@ namespace NetworkResurrector.Agent.Application.Services.Windows
{ {
internal class CmdService : ICliService internal class CmdService : ICliService
{ {
public CmdService() public (bool success, string message) Execute(string command) => Run("cmd.exe", command);
{ public (bool success, string message) Shutdown(string arguments) => Run("shutdown.exe", arguments);
}
public (bool success, string message) Execute(string command) private (bool success, string message) Run(string fileName, string arguments)
{ {
var msg = new StringBuilder();
var commandOutput = new StringBuilder(); var commandOutput = new StringBuilder();
var commandError = new StringBuilder(); var commandErrors = new StringBuilder();
var process = new Process(); var process = new Process();
process.StartInfo.RedirectStandardError = true; process.StartInfo.RedirectStandardError = true;
@ -23,27 +21,25 @@ namespace NetworkResurrector.Agent.Application.Services.Windows
process.StartInfo.RedirectStandardInput = true; process.StartInfo.RedirectStandardInput = true;
process.StartInfo.CreateNoWindow = true; process.StartInfo.CreateNoWindow = true;
process.StartInfo.UseShellExecute = false; process.StartInfo.UseShellExecute = false;
process.StartInfo.FileName = "cmd.exe"; process.StartInfo.FileName = fileName;
commandOutput.Clear(); commandOutput.Clear();
commandError.Clear(); commandErrors.Clear();
process.OutputDataReceived += new DataReceivedEventHandler( process.OutputDataReceived += new DataReceivedEventHandler((s, e) =>
(s, e) =>
{ {
if (!string.IsNullOrEmpty(e.Data)) if (!string.IsNullOrEmpty(e.Data))
commandOutput.Append(e.Data + "\n"); commandOutput.Append($"{e.Data}{Environment.NewLine}");
}); });
process.ErrorDataReceived += new DataReceivedEventHandler(
(s, e) => process.ErrorDataReceived += new DataReceivedEventHandler((s, e) =>
{ {
if (!string.IsNullOrEmpty(e.Data)) if (!string.IsNullOrEmpty(e.Data))
commandError.Append(e.Data + "\n"); commandErrors.Append($"{e.Data}{Environment.NewLine}");
}); });
msg.Append($"\nProcess started at: {DateTime.Now}\n");
process.Start(); process.Start();
process.StandardInput.WriteLine(command); process.StandardInput.WriteLine(arguments);
process.StandardInput.Flush(); process.StandardInput.Flush();
process.StandardInput.Close(); process.StandardInput.Close();
@ -51,11 +47,16 @@ namespace NetworkResurrector.Agent.Application.Services.Windows
process.BeginErrorReadLine(); process.BeginErrorReadLine();
process.WaitForExit(); process.WaitForExit();
msg.Append($"Output:\n {commandOutput}\n");
msg.Append($"Errors:\n {commandError}\n");
msg.Append($"Process ended at: {DateTime.Now}");
return (commandError.Length == 0, msg.ToString()); var msg = new StringBuilder();
if (commandOutput.Length > 0)
msg.Append($"Output:{Environment.NewLine}{commandOutput}{Environment.NewLine}");
if (commandErrors.Length > 0)
msg.Append($"Errors:{Environment.NewLine}{commandErrors}{Environment.NewLine}");
return (commandErrors.Length == 0, msg.ToString());
} }
} }
} }

View File

@ -2,7 +2,6 @@
using NetworkResurrector.Agent.Application.Services.Abstractions; using NetworkResurrector.Agent.Application.Services.Abstractions;
using NetworkResurrector.Agent.Domain.Models; using NetworkResurrector.Agent.Domain.Models;
using System; using System;
using System.Diagnostics;
using System.Security.Principal; using System.Security.Principal;
namespace NetworkResurrector.Agent.Application.Services.Windows namespace NetworkResurrector.Agent.Application.Services.Windows
@ -18,17 +17,6 @@ namespace NetworkResurrector.Agent.Application.Services.Windows
_cliService=cliService; _cliService=cliService;
} }
private void StartShutdownProcess(string arguments)
{
var psi = new ProcessStartInfo("shutdown.exe", arguments)
{
CreateNoWindow = true,
UseShellExecute = false
};
Process.Start(psi);
}
private string SetOptions(string arguments, PowerOptions options) private string SetOptions(string arguments, PowerOptions options)
{ {
if (options == null) if (options == null)
@ -49,12 +37,12 @@ namespace NetworkResurrector.Agent.Application.Services.Windows
private bool IsSystemUser() private bool IsSystemUser()
{ {
bool isSystem; bool isSystem;
#pragma warning disable CA1416 // Validate platform compatibility #pragma warning disable CA1416 // Validate platform compatibility
using (var identity = WindowsIdentity.GetCurrent()) using (var identity = WindowsIdentity.GetCurrent())
{ {
isSystem = identity.IsSystem; isSystem = identity.IsSystem;
} }
#pragma warning restore CA1416 // Validate platform compatibility #pragma warning restore CA1416 // Validate platform compatibility
return isSystem; return isSystem;
} }
@ -66,14 +54,22 @@ namespace NetworkResurrector.Agent.Application.Services.Windows
throw new Exception("This action is not available for system users."); throw new Exception("This action is not available for system users.");
} }
private void ManageExecutionResponse((bool success, string message) input)
{
var (success, message) = input;
if (success)
_logger.LogDebug(message);
else
throw new Exception(message);
}
public void Shutdown(PowerOptions options) public void Shutdown(PowerOptions options)
{ {
var arguments = "-s"; var arguments = "-s";
arguments = SetOptions(arguments, options); arguments = SetOptions(arguments, options);
_logger.LogInformation($"Shutdown arguments: {arguments}"); _logger.LogInformation($"Shutdown arguments: {arguments}");
var result =_cliService.Shutdown(arguments);
StartShutdownProcess(arguments); ManageExecutionResponse(result);
} }
public void Restart(PowerOptions options) public void Restart(PowerOptions options)
@ -81,7 +77,8 @@ namespace NetworkResurrector.Agent.Application.Services.Windows
var arguments = "-r"; var arguments = "-r";
arguments = SetOptions(arguments, options); arguments = SetOptions(arguments, options);
_logger.LogInformation($"Restart arguments: {arguments}"); _logger.LogInformation($"Restart arguments: {arguments}");
StartShutdownProcess(arguments); var result = _cliService.Shutdown(arguments);
ManageExecutionResponse(result);
} }
public void Sleep(PowerOptions options) public void Sleep(PowerOptions options)
@ -89,30 +86,29 @@ namespace NetworkResurrector.Agent.Application.Services.Windows
var arguments = "-h"; var arguments = "-h";
arguments = SetOptions(arguments, options); arguments = SetOptions(arguments, options);
_logger.LogInformation($"Sleep arguments: {arguments}"); _logger.LogInformation($"Sleep arguments: {arguments}");
StartShutdownProcess(arguments); var result =_cliService.Shutdown(arguments);
ManageExecutionResponse(result);
} }
public void Logout() public void Logout()
{ {
ValidateLocalOrDomainUser(); ValidateLocalOrDomainUser();
StartShutdownProcess("-l"); var result = _cliService.Shutdown("-l");
ManageExecutionResponse(result);
} }
public void Lock() public void Lock()
{ {
ValidateLocalOrDomainUser(); ValidateLocalOrDomainUser();
var command = "rundll32.exe user32.dll,LockWorkStation"; var command = "rundll32.exe user32.dll,LockWorkStation";
var (success, message) = _cliService.Execute(command); var result = _cliService.Execute(command);
var msg = $"Command: {command} | ExecutionLog: {message}"; ManageExecutionResponse(result);
if (success)
_logger.LogDebug(msg);
else
throw new Exception(msg);
} }
public void Cancel() public void Cancel()
{ {
StartShutdownProcess("-a"); var result = _cliService.Shutdown("-a");
ManageExecutionResponse(result);
} }
} }
} }

View File

@ -6,7 +6,7 @@
}, },
"Logging": { "Logging": {
"LogLevel": { "LogLevel": {
"Default": "Information", "Default": "Debug",
"Microsoft": "Warning", "Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information" "Microsoft.Hosting.Lifetime": "Information"
} }