Skip to content

Commit

Permalink
Sync Remotely with latest integration changes.
Browse files Browse the repository at this point in the history
  • Loading branch information
bitbound committed Apr 25, 2023
1 parent 0fa41e8 commit bb2126b
Show file tree
Hide file tree
Showing 31 changed files with 278 additions and 381 deletions.
1 change: 0 additions & 1 deletion Agent.Installer.Win/Services/InstallerService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -380,7 +380,6 @@ private void InstallService()
Description = "Background service that maintains a connection to the Remotely server. The service is used for remote support and maintenance by this computer's administrators.",
ServiceName = "Remotely_Service",
StartType = ServiceStartMode.Automatic,
DelayedAutoStart = true,
Parent = new ServiceProcessInstaller()
};

Expand Down
1 change: 0 additions & 1 deletion Agent/Interfaces/IDeviceInformationService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,5 @@ public interface IDeviceInformationService
(double usedGB, double totalGB) GetMemoryInGB();
string GetAgentVersion();
List<Drive> GetAllDrives();
Task<double> GetCpuUtilization();
}
}
3 changes: 2 additions & 1 deletion Agent/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
using System.Diagnostics;
using System.IO;
using System.ServiceProcess;
using System.Threading;
using System.Threading.Tasks;
using System.Runtime.Versioning;
using Remotely.Agent.Services.Linux;
Expand Down Expand Up @@ -55,6 +54,8 @@ private static void BuildServices()

// TODO: All these should be registered as interfaces.
serviceCollection.AddSingleton<IAgentHubConnection, AgentHubConnection>();
serviceCollection.AddSingleton<ICpuUtilizationSampler, CpuUtilizationSampler>();
serviceCollection.AddHostedService(services => services.GetRequiredService<ICpuUtilizationSampler>());
serviceCollection.AddScoped<ChatClientService>();
serviceCollection.AddTransient<PSCore>();
serviceCollection.AddTransient<ExternalScriptingShell>();
Expand Down
5 changes: 1 addition & 4 deletions Agent/Services/AgentHubConnection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -489,10 +489,7 @@ private void RegisterMessageHandlers()
}
});

_hubConnection.On("TriggerHeartbeat", async () =>
{
await SendHeartbeat().ConfigureAwait(false);
});
_hubConnection.On("TriggerHeartbeat", SendHeartbeat);
}

private async Task<bool> VerifyServer()
Expand Down
21 changes: 17 additions & 4 deletions Agent/Services/CpuUtilizationSampler.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Diagnostics;
Expand All @@ -9,24 +10,36 @@

namespace Remotely.Agent.Services;


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

internal class CpuUtilizationSampler : BackgroundService, ICpuUtilizationSampler
{
private readonly ILogger<CpuUtilizationSampler> _logger;
private double _currentUtilization;

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

public double CurrentUtilization => _currentUtilization;

protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
var currentUtil = await GetCpuUtilization(stoppingToken);
Interlocked.Exchange(ref _currentUtilization, currentUtil);
try
{
var currentUtil = await GetCpuUtilization(stoppingToken);
Interlocked.Exchange(ref _currentUtilization, currentUtil);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error while getting CPU utilization sample.");
}
await Task.Delay(TimeSpan.FromSeconds(5), stoppingToken);
}
}
Expand Down
62 changes: 12 additions & 50 deletions Agent/Services/DeviceInfoGeneratorBase.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.Services;
using Remotely.Shared.Utilities;
using System;
Expand All @@ -14,6 +15,13 @@ namespace Remotely.Agent.Services
{
public class DeviceInfoGeneratorBase
{
protected readonly ILogger<DeviceInfoGeneratorBase> _logger;

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

public Device GetDeviceBase(string deviceID, string orgID)
{

Expand Down Expand Up @@ -63,7 +71,7 @@ public Device GetDeviceBase(string deviceID, string orgID)
}
catch (Exception ex)
{
Logger.Write(ex, "Error getting system drive info.");
_logger.LogError(ex, "Error getting system drive info.");
}

return (0, 0);
Expand All @@ -80,7 +88,7 @@ public string GetAgentVersion()
}
catch (Exception ex)
{
Logger.Write(ex, "Error getting agent version.");
_logger.LogError(ex, "Error getting agent version.");
}

return "0.0.0.0";
Expand All @@ -103,55 +111,9 @@ public List<Drive> GetAllDrives()
}
catch (Exception ex)
{
Logger.Write(ex, "Error getting drive info.");
_logger.LogError(ex, "Error getting drive info.");
return null;
}
}

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

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

await Task.Delay(500);

foreach (var kvp in utilizations)
{
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;
}

}
}
20 changes: 14 additions & 6 deletions Agent/Services/Linux/DeviceInfoGeneratorLinux.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Remotely.Agent.Interfaces;
using Microsoft.Extensions.Logging;
using Remotely.Agent.Interfaces;
using Remotely.Shared.Models;
using Remotely.Shared.Services;
using Remotely.Shared.Utilities;
Expand All @@ -13,12 +14,19 @@ namespace Remotely.Agent.Services.Linux
public class DeviceInfoGeneratorLinux : DeviceInfoGeneratorBase, IDeviceInformationService
{
private readonly IProcessInvoker _processInvoker;
private readonly ICpuUtilizationSampler _cpuUtilSampler;

public DeviceInfoGeneratorLinux(IProcessInvoker processInvoker)
public DeviceInfoGeneratorLinux(
IProcessInvoker processInvoker,
ICpuUtilizationSampler cpuUtilSampler,
ILogger<DeviceInfoGeneratorLinux> logger)
: base(logger)
{
_processInvoker = processInvoker;
_cpuUtilSampler = cpuUtilSampler;
}
public async Task<Device> CreateDevice(string deviceId, string orgId)

public Task<Device> CreateDevice(string deviceId, string orgId)
{
var device = GetDeviceBase(deviceId, orgId);

Expand All @@ -34,15 +42,15 @@ public async Task<Device> CreateDevice(string deviceId, string orgId)
device.TotalStorage = totalStorage;
device.UsedMemory = usedMemory;
device.TotalMemory = totalMemory;
device.CpuUtilization = await GetCpuUtilization();
device.CpuUtilization = _cpuUtilSampler.CurrentUtilization;
device.AgentVersion = GetAgentVersion();
}
catch (Exception ex)
{
Logger.Write(ex, "Error getting device info.");
_logger.LogError(ex, "Error getting device info.");
}

return device;
return Task.FromResult(device);
}

private string GetCurrentUser()
Expand Down
61 changes: 31 additions & 30 deletions Agent/Services/MacOS/DeviceInfoGeneratorMac.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using Microsoft.Extensions.Logging;
using Remotely.Agent.Interfaces;
using Remotely.Shared.Models;
using Remotely.Shared.Services;
Expand All @@ -15,7 +16,8 @@ public class DeviceInfoGeneratorMac : DeviceInfoGeneratorBase, IDeviceInformatio
{
private readonly IProcessInvoker _processInvoker;

public DeviceInfoGeneratorMac(IProcessInvoker processInvoker)
public DeviceInfoGeneratorMac(IProcessInvoker processInvoker, ILogger<DeviceInfoGeneratorMac> logger)
: base(logger)
{
_processInvoker = processInvoker;
}
Expand All @@ -40,40 +42,12 @@ public async Task<Device> CreateDevice(string deviceId, string orgId)
}
catch (Exception ex)
{
Logger.Write(ex, "Error getting device info.");
_logger.LogError(ex, "Error getting device info.");
}

return device;
}

public new Task<double> GetCpuUtilization()
{
try
{
var cpuPercentStrings = _processInvoker.InvokeProcessOutput("zsh", "-c \"ps -A -o %cpu\"");

double cpuPercent = 0;
cpuPercentStrings
.Split(Environment.NewLine)
.ToList()
.ForEach(x =>
{
if (double.TryParse(x, out var result))
{
cpuPercent += result;
}
});

return Task.FromResult(cpuPercent / Environment.ProcessorCount / 100);
}
catch (Exception ex)
{
Logger.Write(ex, "Error while getting CPU utilization.");
}

return Task.FromResult((double)0);
}

public (double usedGB, double totalGB) GetMemoryInGB()
{
try
Expand Down Expand Up @@ -114,6 +88,33 @@ public async Task<Device> CreateDevice(string deviceId, string orgId)
}
}

private Task<double> GetCpuUtilization()
{
try
{
var cpuPercentStrings = _processInvoker.InvokeProcessOutput("zsh", "-c \"ps -A -o %cpu\"");

double cpuPercent = 0;
cpuPercentStrings
.Split(Environment.NewLine)
.ToList()
.ForEach(x =>
{
if (double.TryParse(x, out var result))
{
cpuPercent += result;
}
});

return Task.FromResult(cpuPercent / Environment.ProcessorCount / 100);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error while getting CPU utilization.");
}

return Task.FromResult((double)0);
}
private string GetCurrentUser()
{
var users = _processInvoker.InvokeProcessOutput("users", "");
Expand Down
21 changes: 16 additions & 5 deletions Agent/Services/Windows/DeviceInfoGeneratorWin.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Remotely.Agent.Interfaces;
using Microsoft.Extensions.Logging;
using Remotely.Agent.Interfaces;
using Remotely.Shared.Models;
using Remotely.Shared.Utilities;
using Remotely.Shared.Win32;
Expand All @@ -12,7 +13,17 @@ namespace Remotely.Agent.Services.Windows
{
public class DeviceInfoGeneratorWin : DeviceInfoGeneratorBase, IDeviceInformationService
{
public async Task<Device> CreateDevice(string deviceId, string orgId)
private readonly ICpuUtilizationSampler _cpuUtilSampler;

public DeviceInfoGeneratorWin(
ICpuUtilizationSampler cpuUtilSampler,
ILogger<DeviceInfoGeneratorWin> logger)
: base(logger)
{
_cpuUtilSampler = cpuUtilSampler;
}

public Task<Device> CreateDevice(string deviceId, string orgId)
{
var device = GetDeviceBase(deviceId, orgId);

Expand All @@ -28,15 +39,15 @@ public async Task<Device> CreateDevice(string deviceId, string orgId)
device.TotalStorage = totalStorage;
device.UsedMemory = usedMemory;
device.TotalMemory = totalMemory;
device.CpuUtilization = await GetCpuUtilization();
device.CpuUtilization = _cpuUtilSampler.CurrentUtilization;
device.AgentVersion = GetAgentVersion();
}
catch (Exception ex)
{
Logger.Write(ex, "Error getting device info.");
_logger.LogError(ex, "Error getting device info.");
}

return device;
return Task.FromResult(device);
}

public (double usedGB, double totalGB) GetMemoryInGB()
Expand Down
5 changes: 3 additions & 2 deletions Desktop.Linux/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -66,11 +66,12 @@
var result = await provider.UseRemoteControlClient(
args,
"The remote control client for Remotely.",
serverUrl);
serverUrl,
false);

if (!result.IsSuccess)
{
logger.LogError(result.Exception, "Failed to remote control client.");
logger.LogError(result.Exception, "Failed to start remote control client.");
Environment.Exit(1);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ https://go.microsoft.com/fwlink/?LinkID=208121.
<Configuration>Release</Configuration>
<Platform>x64</Platform>
<TargetFramework>.net7.0</TargetFramework>
<PublishDir>..\Agent\bin\Release\.net7.0\linux-x64\publish\Desktop</PublishDir>
<PublishDir>..\Agent\bin\Release\net7.0\linux-x64\publish\Desktop</PublishDir>
<RuntimeIdentifier>linux-x64</RuntimeIdentifier>
<SelfContained>true</SelfContained>
<PublishSingleFile>False</PublishSingleFile>
Expand Down
Loading

0 comments on commit bb2126b

Please sign in to comment.