Skip to content

Commit

Permalink
Extract interfaces from all agent services. Replace use of static Log…
Browse files Browse the repository at this point in the history
…ger.
  • Loading branch information
bitbound committed Jun 24, 2023
1 parent 402d5b0 commit 7459f2f
Show file tree
Hide file tree
Showing 14 changed files with 182 additions and 106 deletions.
12 changes: 6 additions & 6 deletions Agent/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -94,12 +94,12 @@ private static void RegisterServices(IServiceCollection services)
services.AddSingleton<ICpuUtilizationSampler, CpuUtilizationSampler>();
services.AddSingleton<IWakeOnLanService, WakeOnLanService>();
services.AddHostedService(services => services.GetRequiredService<ICpuUtilizationSampler>());
services.AddScoped<ChatClientService>();
services.AddTransient<PSCore>();
services.AddTransient<ExternalScriptingShell>();
services.AddScoped<ConfigService>();
services.AddScoped<Uninstaller>();
services.AddScoped<ScriptExecutor>();
services.AddScoped<IChatClientService, ChatClientService>();
services.AddTransient<IPSCore, PSCore>();
services.AddTransient<IExternalScriptingShell, ExternalScriptingShell>();
services.AddScoped<IConfigService, ConfigService>();
services.AddScoped<IUninstaller, Uninstaller>();
services.AddScoped<IScriptExecutor, ScriptExecutor>();
services.AddScoped<IProcessInvoker, ProcessInvoker>();
services.AddScoped<IUpdateDownloader, UpdateDownloader>();

Expand Down
22 changes: 9 additions & 13 deletions Agent/Services/AgentHubConnection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,31 +29,27 @@ public interface IAgentHubConnection
public class AgentHubConnection : IAgentHubConnection, IDisposable
{
private readonly IAppLauncher _appLauncher;

private readonly ChatClientService _chatService;

private readonly ConfigService _configService;

private readonly IChatClientService _chatService;
private readonly IConfigService _configService;
private readonly IDeviceInformationService _deviceInfoService;
private readonly IHttpClientFactory _httpFactory;
private readonly IWakeOnLanService _wakeOnLanService;
private readonly ILogger<AgentHubConnection> _logger;
private readonly ILogger _fileLogger;
private readonly ScriptExecutor _scriptExecutor;

private readonly Uninstaller _uninstaller;

private readonly IScriptExecutor _scriptExecutor;
private readonly IUninstaller _uninstaller;
private readonly IUpdater _updater;

private ConnectionInfo _connectionInfo;
private HubConnection _hubConnection;
private Timer _heartbeatTimer;
private bool _isServerVerified;

public AgentHubConnection(ConfigService configService,
Uninstaller uninstaller,
ScriptExecutor scriptExecutor,
ChatClientService chatService,
public AgentHubConnection(
IConfigService configService,
IUninstaller uninstaller,
IScriptExecutor scriptExecutor,
IChatClientService chatService,
IAppLauncher appLauncher,
IUpdater updater,
IDeviceInformationService deviceInfoService,
Expand Down
37 changes: 23 additions & 14 deletions Agent/Services/ChatClientService.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using Immense.RemoteControl.Shared.Models;
using Microsoft.AspNetCore.SignalR.Client;
using Microsoft.Extensions.Logging;
using Remotely.Agent.Interfaces;
using Remotely.Agent.Models;
using Remotely.Shared.Models;
Expand All @@ -15,18 +16,19 @@

namespace Remotely.Agent.Services
{
public class ChatClientService
public interface IChatClientService
{
Task SendMessage(string senderName, string message, string orgName, string orgId, bool disconnected, string senderConnectionID, HubConnection hubConnection);
}

public class ChatClientService : IChatClientService
{
private readonly IAppLauncher _appLauncher;
private readonly ILogger<ChatClientService> _logger;
private readonly MemoryCache _chatClients = new("ChatClients");
private readonly SemaphoreSlim _messageLock = new(1,1);

public ChatClientService(IAppLauncher appLauncher)
{
_appLauncher = appLauncher;
}
private readonly SemaphoreSlim _messageLock = new(1, 1);

private CacheItemPolicy CacheItemPolicy { get; } = new()
private readonly CacheItemPolicy _cacheItemPolicy = new()
{
SlidingExpiration = TimeSpan.FromMinutes(10),
RemovedCallback = new CacheEntryRemovedCallback(args =>
Expand All @@ -48,6 +50,13 @@ public ChatClientService(IAppLauncher appLauncher)
})
};

public ChatClientService(
IAppLauncher appLauncher,
ILogger<ChatClientService> logger)
{
_appLauncher = appLauncher;
_logger = logger;
}

public async Task SendMessage(
string senderName,
Expand All @@ -60,7 +69,7 @@ public async Task SendMessage(
{
if (!await _messageLock.WaitAsync(30000))
{
Logger.Write("Timed out waiting for chat message lock.", Shared.Enums.EventType.Warning);
_logger.LogWarning("Timed out waiting for chat message lock.");
return;
}

Expand All @@ -80,24 +89,24 @@ public async Task SendMessage(

if (procID > 0)
{
Logger.Write($"Chat app started. Process ID: {procID}");
_logger.LogInformation("Chat app started. Process ID: {procID}", procID);
}
else
{
Logger.Write($"Chat app did not start successfully.");
_logger.LogError($"Chat app did not start successfully.");
return;
}

var clientPipe = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.Asynchronous);
clientPipe.Connect(15000);
if (!clientPipe.IsConnected)
{
Logger.Write("Failed to connect to chat host.");
_logger.LogError("Failed to connect to chat host.");
return;
}
chatSession = new ChatSession() { PipeStream = clientPipe, ProcessID = procID };
_ = Task.Run(async () => { await ReadFromStream(chatSession.PipeStream, senderConnectionID, hubConnection); });
_chatClients.Add(senderConnectionID, chatSession, CacheItemPolicy);
_chatClients.Add(senderConnectionID, chatSession, _cacheItemPolicy);
}

chatSession = (ChatSession)_chatClients.Get(senderConnectionID);
Expand All @@ -116,7 +125,7 @@ public async Task SendMessage(
}
catch (Exception ex)
{
Logger.Write(ex);
_logger.LogError(ex, "Error while sending chat message.");
}
finally
{
Expand Down
19 changes: 16 additions & 3 deletions Agent/Services/ConfigService.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Remotely.Shared.Models;
using Microsoft.Extensions.Logging;
using Remotely.Shared.Models;
using Remotely.Shared.Utilities;
using System;
using System.Collections.Generic;
Expand All @@ -8,11 +9,23 @@

namespace Remotely.Agent.Services
{
public class ConfigService
public interface IConfigService
{
ConnectionInfo GetConnectionInfo();
void SaveConnectionInfo(ConnectionInfo connectionInfo);
}

public class ConfigService : IConfigService
{
private static readonly object _fileLock = new();
private ConnectionInfo _connectionInfo;
private readonly string _debugGuid = "f2b0a595-5ea8-471b-975f-12e70e0f3497";
private readonly ILogger<ConfigService> _logger;

public ConfigService(ILogger<ConfigService> logger)
{
_logger = logger;
}

private Dictionary<string, string> _commandLineArgs;
private Dictionary<string, string> CommandLineArgs
Expand Down Expand Up @@ -74,7 +87,7 @@ public ConnectionInfo GetConnectionInfo()
{
if (!File.Exists("ConnectionInfo.json"))
{
Logger.Write(new Exception("No connection info available. Please create ConnectionInfo.json file with appropriate values."));
_logger.LogError("No connection info available. Please create ConnectionInfo.json file with appropriate values.");
return null;
}
_connectionInfo = JsonSerializer.Deserialize<ConnectionInfo>(File.ReadAllText("ConnectionInfo.json"));
Expand Down
2 changes: 1 addition & 1 deletion Agent/Services/DeviceInfoGeneratorBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@

namespace Remotely.Agent.Services
{
public class DeviceInfoGeneratorBase
public abstract class DeviceInfoGeneratorBase
{
protected readonly ILogger<DeviceInfoGeneratorBase> _logger;

Expand Down
14 changes: 10 additions & 4 deletions Agent/Services/ExternalScriptingShell.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Remotely.Shared.Enums;
using Remotely.Shared.Models;
using Remotely.Shared.Utilities;
Expand All @@ -15,19 +16,23 @@ namespace Remotely.Agent.Services
{
public interface IExternalScriptingShell
{

ScriptResult WriteInput(string input, TimeSpan timeout);
}

public class ExternalScriptingShell : IExternalScriptingShell
{
private static readonly ConcurrentDictionary<string, ExternalScriptingShell> _sessions = new();
private readonly ConfigService _configService;
private readonly IConfigService _configService;
private readonly ILogger<ExternalScriptingShell> _logger;
private string _lineEnding;
private ScriptingShell _shell;

public ExternalScriptingShell(ConfigService configService)
public ExternalScriptingShell(
IConfigService configService,
ILogger<ExternalScriptingShell> logger)
{
_configService = configService;
_logger = logger;
}

private string ErrorOut { get; set; }
Expand All @@ -46,6 +51,7 @@ public ExternalScriptingShell(ConfigService configService)

private Stopwatch Stopwatch { get; set; }

// TODO: Turn into cache and factory.
public static ExternalScriptingShell GetCurrent(ScriptingShell shell, string senderConnectionId)
{
if (_sessions.TryGetValue($"{shell}-{senderConnectionId}", out var session) &&
Expand Down Expand Up @@ -112,7 +118,7 @@ public ScriptResult WriteInput(string input, TimeSpan timeout)
}
catch (Exception ex)
{
Logger.Write(ex);
_logger.LogError(ex, "Error while writing input to scripting shell.");
ErrorOut += Environment.NewLine + ex.Message;

// Something's wrong. Let the next command start a new session.
Expand Down
2 changes: 1 addition & 1 deletion Agent/Services/Linux/AppLauncherLinux.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ public class AppLauncherLinux : IAppLauncher
private readonly ILogger<AppLauncherLinux> _logger;

public AppLauncherLinux(
ConfigService configService,
IConfigService configService,
IProcessInvoker processInvoker,
ILogger<AppLauncherLinux> logger)
{
Expand Down
4 changes: 2 additions & 2 deletions Agent/Services/Linux/UpdaterLinux.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ namespace Remotely.Agent.Services.Linux
public class UpdaterLinux : IUpdater
{
private readonly SemaphoreSlim _checkForUpdatesLock = new(1, 1);
private readonly ConfigService _configService;
private readonly IConfigService _configService;
private readonly IUpdateDownloader _updateDownloader;
private readonly IHttpClientFactory _httpClientFactory;
private readonly ILogger<UpdaterLinux> _logger;
Expand All @@ -29,7 +29,7 @@ public class UpdaterLinux : IUpdater
private DateTimeOffset _lastUpdateFailure;

public UpdaterLinux(
ConfigService configService,
IConfigService configService,
IUpdateDownloader updateDownloader,
IHttpClientFactory httpClientFactory,
ILogger<UpdaterLinux> logger)
Expand Down
4 changes: 2 additions & 2 deletions Agent/Services/MacOS/UpdaterMac.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ public class UpdaterMac : IUpdater
{
private readonly string _achitecture = RuntimeInformation.OSArchitecture.ToString().ToLower();
private readonly SemaphoreSlim _checkForUpdatesLock = new(1, 1);
private readonly ConfigService _configService;
private readonly IConfigService _configService;
private readonly IHttpClientFactory _httpClientFactory;
private readonly IUpdateDownloader _updateDownloader;
private readonly ILogger<UpdaterMac> _logger;
Expand All @@ -30,7 +30,7 @@ public class UpdaterMac : IUpdater
private readonly System.Timers.Timer _updateTimer = new(TimeSpan.FromHours(6).TotalMilliseconds);

public UpdaterMac(
ConfigService configService,
IConfigService configService,
IUpdateDownloader updateDownloader,
IHttpClientFactory httpClientFactory,
ILogger<UpdaterMac> logger)
Expand Down
Loading

0 comments on commit 7459f2f

Please sign in to comment.