Skip to content

Commit

Permalink
Refactor to align with changes in submodule.
Browse files Browse the repository at this point in the history
  • Loading branch information
bitbound committed Apr 18, 2023
1 parent 19805a8 commit c0b10ef
Show file tree
Hide file tree
Showing 34 changed files with 336 additions and 342 deletions.
3 changes: 1 addition & 2 deletions Agent/Agent.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,8 @@

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.SignalR.Protocols.MessagePack" Version="6.0.9" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.Http" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.EventLog" Version="6.0.0" />
<PackageReference Include="Microsoft.AspNetCore.SignalR.Client" Version="6.0.9" />
<PackageReference Include="Microsoft.PowerShell.SDK" Version="7.2.6" />
Expand Down
19 changes: 12 additions & 7 deletions Agent/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@
using System.Threading;
using System.Threading.Tasks;
using System.Runtime.Versioning;
using Remotely.Agent.Services.Linux;
using Remotely.Agent.Services.MacOS;
using Remotely.Agent.Services.Windows;

namespace Remotely.Agent
{
Expand All @@ -24,6 +27,7 @@ public static async Task Main(string[] args)
{
try
{
// TODO: Convert to generic host.
BuildServices();

await Init();
Expand All @@ -45,7 +49,8 @@ private static void BuildServices()
serviceCollection.AddLogging(builder =>
{
builder.AddConsole().AddDebug();
builder.AddProvider(new FileLoggerProvider("Remotely_Agent"));
var version = typeof(Program).Assembly.GetName().Version?.ToString() ?? "0.0.0";
builder.AddProvider(new FileLoggerProvider("Remotely_Agent", version));
});

// TODO: All these should be registered as interfaces.
Expand All @@ -59,23 +64,23 @@ private static void BuildServices()
serviceCollection.AddScoped<IProcessInvoker, ProcessInvoker>();
serviceCollection.AddScoped<IUpdateDownloader, UpdateDownloader>();

if (EnvironmentHelper.IsWindows)
if (OperatingSystem.IsWindows())
{
serviceCollection.AddScoped<IAppLauncher, AppLauncherWin>();
serviceCollection.AddSingleton<IUpdater, UpdaterWin>();
serviceCollection.AddSingleton<IDeviceInformationService, DeviceInformationServiceWin>();
serviceCollection.AddSingleton<IDeviceInformationService, DeviceInfoGeneratorWin>();
}
else if (EnvironmentHelper.IsLinux)
else if (OperatingSystem.IsLinux())
{
serviceCollection.AddScoped<IAppLauncher, AppLauncherLinux>();
serviceCollection.AddSingleton<IUpdater, UpdaterLinux>();
serviceCollection.AddSingleton<IDeviceInformationService, DeviceInformationServiceLinux>();
serviceCollection.AddSingleton<IDeviceInformationService, DeviceInfoGeneratorLinux>();
}
else if (EnvironmentHelper.IsMac)
else if (OperatingSystem.IsMacOS())
{
serviceCollection.AddScoped<IAppLauncher, AppLauncherMac>();
serviceCollection.AddSingleton<IUpdater, UpdaterMac>();
serviceCollection.AddSingleton<IDeviceInformationService, DeviceInformationServiceMac>();
serviceCollection.AddSingleton<IDeviceInformationService, DeviceInfoGeneratorMac>();
}
else
{
Expand Down
2 changes: 2 additions & 0 deletions Agent/Services/AgentHubConnection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@ public async Task Connect()

_logger.LogInformation("Connected to server.");

// TODO: Move CPU sampler to background service.
var device = await _deviceInfoService.CreateDevice(_connectionInfo.DeviceID, _connectionInfo.OrganizationID);

var result = await _hubConnection.InvokeAsync<bool>("DeviceCameOnline", device);
Expand All @@ -132,6 +133,7 @@ public async Task Connect()
continue;
}

// TODO: Move to background service.
_heartbeatTimer?.Dispose();
_heartbeatTimer = new Timer(TimeSpan.FromMinutes(5).TotalMilliseconds);
_heartbeatTimer.Elapsed += HeartbeatTimer_Elapsed;
Expand Down
88 changes: 88 additions & 0 deletions Agent/Services/CpuUtilizationSampler.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Remotely.Agent.Services;


internal interface ICpuUtilizationSampler : IHostedService
{
double CurrentUtilization { get; }
}

internal class CpuUtilizationSampler : BackgroundService, ICpuUtilizationSampler
{
private double _currentUtilization;

public double CurrentUtilization => _currentUtilization;

protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
var currentUtil = await GetCpuUtilization(stoppingToken);
Interlocked.Exchange(ref _currentUtilization, currentUtil);
await Task.Delay(TimeSpan.FromSeconds(5), stoppingToken);
}
}

private static async Task<double> GetCpuUtilization(CancellationToken cancelToken)
{
double totalUtilization = 0;
var utilizations = new Dictionary<int, Tuple<DateTimeOffset, TimeSpan>>();
var processes = Process.GetProcesses();

foreach (var proc in processes)
{
if (cancelToken.IsCancellationRequested)
{
return 0;
}

try
{
var startTime = DateTimeOffset.Now;
var startCpuUsage = proc.TotalProcessorTime;
utilizations.Add(proc.Id, new Tuple<DateTimeOffset, TimeSpan>(startTime, startCpuUsage));
}
catch
{
continue;
}
}

await Task.Delay(1_000, cancelToken);

foreach (var kvp in utilizations)
{
if (cancelToken.IsCancellationRequested)
{
return 0;
}

var endTime = DateTimeOffset.Now;
try
{
var proc = Process.GetProcessById(kvp.Key);
var startTime = kvp.Value.Item1;
var startCpuUsage = kvp.Value.Item2;
var endCpuUsage = proc.TotalProcessorTime;
var cpuUsedMs = (endCpuUsage - startCpuUsage).TotalMilliseconds;
var totalMsPassed = (endTime - startTime).TotalMilliseconds;
var cpuUsageTotal = cpuUsedMs / (Environment.ProcessorCount * totalMsPassed);
totalUtilization += cpuUsageTotal;
}
catch
{
continue;
}
}

return totalUtilization;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@

namespace Remotely.Agent.Services
{
public class DeviceInformationServiceBase
public class DeviceInfoGeneratorBase
{
public Device GetDeviceBase(string deviceID, string orgID)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
using System.Threading.Tasks;
using System.Web.Services.Description;

namespace Remotely.Agent.Services
namespace Remotely.Agent.Services.Linux
{

public class AppLauncherLinux : IAppLauncher
Expand All @@ -24,7 +24,7 @@ public class AppLauncherLinux : IAppLauncher
private readonly ILogger<AppLauncherLinux> _logger;

public AppLauncherLinux(
ConfigService configService,
ConfigService configService,
IProcessInvoker processInvoker,
ILogger<AppLauncherLinux> logger)
{
Expand Down Expand Up @@ -157,7 +157,7 @@ await hubConnection.SendAsync("DisplayMessage",

// Start Desktop app.
await hubConnection.SendAsync("DisplayMessage", "Starting remote control.", "Starting remote control.", "bg-success", userConnectionId);
var args =
var args =
_rcBinaryPath +
$" --mode Unattended" +
$" --host {_connectionInfo.Host}" +
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,13 @@
using System.Text;
using System.Threading.Tasks;

namespace Remotely.Agent.Services
namespace Remotely.Agent.Services.Linux
{
public class DeviceInformationServiceLinux : DeviceInformationServiceBase, IDeviceInformationService
public class DeviceInfoGeneratorLinux : DeviceInfoGeneratorBase, IDeviceInformationService
{
private readonly IProcessInvoker _processInvoker;

public DeviceInformationServiceLinux(IProcessInvoker processInvoker)
public DeviceInfoGeneratorLinux(IProcessInvoker processInvoker)
{
_processInvoker = processInvoker;
}
Expand Down Expand Up @@ -75,8 +75,8 @@ private string GetCurrentUser()
.Split(' ')
.First(); // 16637468

var freeGB = Math.Round((double.Parse(freeKB) / 1024 / 1024), 2);
var totalGB = Math.Round((double.Parse(totalKB) / 1024 / 1024), 2);
var freeGB = Math.Round(double.Parse(freeKB) / 1024 / 1024, 2);
var totalGB = Math.Round(double.Parse(totalKB) / 1024 / 1024, 2);

return (totalGB - freeGB, totalGB);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,9 @@
using System.Threading;
using System.Threading.Tasks;

namespace Remotely.Agent.Services
namespace Remotely.Agent.Services.Linux
{

public class UpdaterLinux : IUpdater
{
private readonly SemaphoreSlim _checkForUpdatesLock = new(1, 1);
Expand All @@ -27,10 +27,10 @@ public class UpdaterLinux : IUpdater
private readonly SemaphoreSlim _installLatestVersionLock = new(1, 1);
private readonly System.Timers.Timer _updateTimer = new(TimeSpan.FromHours(6).TotalMilliseconds);
private DateTimeOffset _lastUpdateFailure;

public UpdaterLinux(
ConfigService configService,
IUpdateDownloader updateDownloader,
ConfigService configService,
IUpdateDownloader updateDownloader,
IHttpClientFactory httpClientFactory,
ILogger<UpdaterLinux> logger)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
using Microsoft.AspNetCore.SignalR.Client;
using Remotely.Agent.Interfaces;

namespace Remotely.Agent.Services
namespace Remotely.Agent.Services.MacOS
{
public class AppLauncherMac : IAppLauncher
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,13 @@
using System.Text;
using System.Threading.Tasks;

namespace Remotely.Agent.Services
namespace Remotely.Agent.Services.MacOS
{
public class DeviceInformationServiceMac : DeviceInformationServiceBase, IDeviceInformationService
public class DeviceInfoGeneratorMac : DeviceInfoGeneratorBase, IDeviceInformationService
{
private readonly IProcessInvoker _processInvoker;

public DeviceInformationServiceMac(IProcessInvoker processInvoker)
public DeviceInfoGeneratorMac(IProcessInvoker processInvoker)
{
_processInvoker = processInvoker;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
using System.Threading.Tasks;


namespace Remotely.Agent.Services
namespace Remotely.Agent.Services.MacOS
{
public class UpdaterMac : IUpdater
{
Expand All @@ -30,8 +30,8 @@ public class UpdaterMac : IUpdater
private readonly System.Timers.Timer _updateTimer = new(TimeSpan.FromHours(6).TotalMilliseconds);

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

0 comments on commit c0b10ef

Please sign in to comment.