Compare commits

...
Sign in to create a new pull request.

10 commits
master ... net8

Author SHA1 Message Date
kkb
62c22d057b backend metrics implementation 2024-01-11 10:26:08 +01:00
kkb
a4ed1a5956 before server asp convertion 2024-01-10 16:49:56 +01:00
kkb
ce99053a10 net8, language features, bugfixes 2023-12-18 16:31:00 +01:00
kkb
1591618c2c optimization update, web scheduler test-integration 2023-12-14 11:09:03 +01:00
kkb
3c9ccaafeb testing remote stuff 2023-11-17 17:12:41 +01:00
Kevin Kai Berthold
1e05d4576d syntax updates 2023-09-22 22:16:56 +02:00
Kevin Kai Berthold
283fa1abc2 web-proxy rewrite 2023-09-21 23:44:05 +02:00
Kevin Kai Berthold
26c741ad03 update packages 2023-09-21 22:32:40 +02:00
Kevin Kai Berthold
450a6f2796 refactor (networking) 2023-09-21 22:10:55 +02:00
Kevin Kai Berthold
febc4d9488 fixed chatservice 2023-09-21 20:45:37 +02:00
685 changed files with 28767 additions and 17956 deletions

View file

@ -1,8 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net7.0</TargetFramework>
</PropertyGroup>
</Project>

View file

@ -27,15 +27,19 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Api", "Api", "{35BA5DCB-BEC
EndProject EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Insight.Api", "src\Api\Insight.Api\Insight.Api.csproj", "{EF3188D7-338D-43DA-BF6B-D26E5BDAC3A6}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Insight.Api", "src\Api\Insight.Api\Insight.Api.csproj", "{EF3188D7-338D-43DA-BF6B-D26E5BDAC3A6}"
EndProject EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Insight.Server", "src\Server\Insight.Server\Insight.Server.csproj", "{1E75F7E9-E6AA-44E7-A2F3-DB4CA85E0118}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Insight.Updater", "src\Updater\Insight.Updater\Insight.Updater.csproj", "{4875D70F-A96B-4EBA-99BE-218886D29BEB}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Insight.Updater", "src\Updater\Insight.Updater\Insight.Updater.csproj", "{4875D70F-A96B-4EBA-99BE-218886D29BEB}"
EndProject EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Insight.Web.Assets", "src\Web\Insight.Web.Assets\Insight.Web.Assets.csproj", "{EBB8A2A8-453B-4867-A8E2-072530391DD0}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Insight.Agent", "src\Agent\Insight.Agent\Insight.Agent.csproj", "{2A391CA2-F96B-4DB7-80AA-0668A5141640}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Insight.Agent", "src\Agent\Insight.Agent\Insight.Agent.csproj", "{2A391CA2-F96B-4DB7-80AA-0668A5141640}"
EndProject EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Insight.Agent.Assets", "src\Agent\Insight.Agent.Assets\Insight.Agent.Assets.csproj", "{4C2B66EA-4EE1-47BF-BAEE-DDBAF6FCB324}" Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Remote", "Remote", "{D4D7BF4A-B2E3-470A-A14C-FC658FF7461D}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Insight.Remote.Shared", "src\Remote\Insight.Remote.Shared\Insight.Remote.Shared.csproj", "{5C4697BD-BC97-484F-9DB1-CA87E2BEAA4B}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Insight.Remote.Windows", "src\Remote\Insight.Remote.Windows\Insight.Remote.Windows.csproj", "{AF313B47-3079-407F-91D1-9989C1E1AF2A}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Insight.Infrastructure.Web", "src\Core\Insight.Infrastructure.Web\Insight.Infrastructure.Web.csproj", "{39B81A0D-A88C-44D3-9624-1A19C78A4310}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Insight.Server", "src\Server\Insight.Server\Insight.Server.csproj", "{FCAE9C42-1DCE-4C2E-BAE0-251C147903B4}"
EndProject EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution
@ -63,26 +67,30 @@ Global
{EF3188D7-338D-43DA-BF6B-D26E5BDAC3A6}.Debug|Any CPU.Build.0 = Debug|Any CPU {EF3188D7-338D-43DA-BF6B-D26E5BDAC3A6}.Debug|Any CPU.Build.0 = Debug|Any CPU
{EF3188D7-338D-43DA-BF6B-D26E5BDAC3A6}.Release|Any CPU.ActiveCfg = Release|Any CPU {EF3188D7-338D-43DA-BF6B-D26E5BDAC3A6}.Release|Any CPU.ActiveCfg = Release|Any CPU
{EF3188D7-338D-43DA-BF6B-D26E5BDAC3A6}.Release|Any CPU.Build.0 = Release|Any CPU {EF3188D7-338D-43DA-BF6B-D26E5BDAC3A6}.Release|Any CPU.Build.0 = Release|Any CPU
{1E75F7E9-E6AA-44E7-A2F3-DB4CA85E0118}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{1E75F7E9-E6AA-44E7-A2F3-DB4CA85E0118}.Debug|Any CPU.Build.0 = Debug|Any CPU
{1E75F7E9-E6AA-44E7-A2F3-DB4CA85E0118}.Release|Any CPU.ActiveCfg = Release|Any CPU
{1E75F7E9-E6AA-44E7-A2F3-DB4CA85E0118}.Release|Any CPU.Build.0 = Release|Any CPU
{4875D70F-A96B-4EBA-99BE-218886D29BEB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {4875D70F-A96B-4EBA-99BE-218886D29BEB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{4875D70F-A96B-4EBA-99BE-218886D29BEB}.Debug|Any CPU.Build.0 = Debug|Any CPU {4875D70F-A96B-4EBA-99BE-218886D29BEB}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4875D70F-A96B-4EBA-99BE-218886D29BEB}.Release|Any CPU.ActiveCfg = Release|Any CPU {4875D70F-A96B-4EBA-99BE-218886D29BEB}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4875D70F-A96B-4EBA-99BE-218886D29BEB}.Release|Any CPU.Build.0 = Release|Any CPU {4875D70F-A96B-4EBA-99BE-218886D29BEB}.Release|Any CPU.Build.0 = Release|Any CPU
{EBB8A2A8-453B-4867-A8E2-072530391DD0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{EBB8A2A8-453B-4867-A8E2-072530391DD0}.Debug|Any CPU.Build.0 = Debug|Any CPU
{EBB8A2A8-453B-4867-A8E2-072530391DD0}.Release|Any CPU.ActiveCfg = Release|Any CPU
{EBB8A2A8-453B-4867-A8E2-072530391DD0}.Release|Any CPU.Build.0 = Release|Any CPU
{2A391CA2-F96B-4DB7-80AA-0668A5141640}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {2A391CA2-F96B-4DB7-80AA-0668A5141640}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{2A391CA2-F96B-4DB7-80AA-0668A5141640}.Debug|Any CPU.Build.0 = Debug|Any CPU {2A391CA2-F96B-4DB7-80AA-0668A5141640}.Debug|Any CPU.Build.0 = Debug|Any CPU
{2A391CA2-F96B-4DB7-80AA-0668A5141640}.Release|Any CPU.ActiveCfg = Release|Any CPU {2A391CA2-F96B-4DB7-80AA-0668A5141640}.Release|Any CPU.ActiveCfg = Release|Any CPU
{2A391CA2-F96B-4DB7-80AA-0668A5141640}.Release|Any CPU.Build.0 = Release|Any CPU {2A391CA2-F96B-4DB7-80AA-0668A5141640}.Release|Any CPU.Build.0 = Release|Any CPU
{4C2B66EA-4EE1-47BF-BAEE-DDBAF6FCB324}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {5C4697BD-BC97-484F-9DB1-CA87E2BEAA4B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{4C2B66EA-4EE1-47BF-BAEE-DDBAF6FCB324}.Debug|Any CPU.Build.0 = Debug|Any CPU {5C4697BD-BC97-484F-9DB1-CA87E2BEAA4B}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4C2B66EA-4EE1-47BF-BAEE-DDBAF6FCB324}.Release|Any CPU.ActiveCfg = Release|Any CPU {5C4697BD-BC97-484F-9DB1-CA87E2BEAA4B}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4C2B66EA-4EE1-47BF-BAEE-DDBAF6FCB324}.Release|Any CPU.Build.0 = Release|Any CPU {5C4697BD-BC97-484F-9DB1-CA87E2BEAA4B}.Release|Any CPU.Build.0 = Release|Any CPU
{AF313B47-3079-407F-91D1-9989C1E1AF2A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{AF313B47-3079-407F-91D1-9989C1E1AF2A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{AF313B47-3079-407F-91D1-9989C1E1AF2A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{AF313B47-3079-407F-91D1-9989C1E1AF2A}.Release|Any CPU.Build.0 = Release|Any CPU
{39B81A0D-A88C-44D3-9624-1A19C78A4310}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{39B81A0D-A88C-44D3-9624-1A19C78A4310}.Debug|Any CPU.Build.0 = Debug|Any CPU
{39B81A0D-A88C-44D3-9624-1A19C78A4310}.Release|Any CPU.ActiveCfg = Release|Any CPU
{39B81A0D-A88C-44D3-9624-1A19C78A4310}.Release|Any CPU.Build.0 = Release|Any CPU
{FCAE9C42-1DCE-4C2E-BAE0-251C147903B4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{FCAE9C42-1DCE-4C2E-BAE0-251C147903B4}.Debug|Any CPU.Build.0 = Debug|Any CPU
{FCAE9C42-1DCE-4C2E-BAE0-251C147903B4}.Release|Any CPU.ActiveCfg = Release|Any CPU
{FCAE9C42-1DCE-4C2E-BAE0-251C147903B4}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection EndGlobalSection
GlobalSection(SolutionProperties) = preSolution GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE HideSolutionNode = FALSE
@ -93,11 +101,12 @@ Global
{CA99B8CF-520A-4B48-ACCE-0A301C35A7FE} = {15D04093-4974-4B2F-AE8A-F3721F31767A} {CA99B8CF-520A-4B48-ACCE-0A301C35A7FE} = {15D04093-4974-4B2F-AE8A-F3721F31767A}
{375EF474-512A-4410-86CF-46974E07C1F7} = {3F000016-069D-477E-ACA3-F643880B57E8} {375EF474-512A-4410-86CF-46974E07C1F7} = {3F000016-069D-477E-ACA3-F643880B57E8}
{EF3188D7-338D-43DA-BF6B-D26E5BDAC3A6} = {35BA5DCB-BECC-4F51-8DD0-694C555D205A} {EF3188D7-338D-43DA-BF6B-D26E5BDAC3A6} = {35BA5DCB-BECC-4F51-8DD0-694C555D205A}
{1E75F7E9-E6AA-44E7-A2F3-DB4CA85E0118} = {038C3821-E554-496D-B585-A3BC193B7913}
{4875D70F-A96B-4EBA-99BE-218886D29BEB} = {F2D241DB-7692-46DB-8A6A-958B365DAAF8} {4875D70F-A96B-4EBA-99BE-218886D29BEB} = {F2D241DB-7692-46DB-8A6A-958B365DAAF8}
{EBB8A2A8-453B-4867-A8E2-072530391DD0} = {3F000016-069D-477E-ACA3-F643880B57E8}
{2A391CA2-F96B-4DB7-80AA-0668A5141640} = {140F73DD-29D3-4C44-809B-5B470880AA0D} {2A391CA2-F96B-4DB7-80AA-0668A5141640} = {140F73DD-29D3-4C44-809B-5B470880AA0D}
{4C2B66EA-4EE1-47BF-BAEE-DDBAF6FCB324} = {140F73DD-29D3-4C44-809B-5B470880AA0D} {5C4697BD-BC97-484F-9DB1-CA87E2BEAA4B} = {D4D7BF4A-B2E3-470A-A14C-FC658FF7461D}
{AF313B47-3079-407F-91D1-9989C1E1AF2A} = {D4D7BF4A-B2E3-470A-A14C-FC658FF7461D}
{39B81A0D-A88C-44D3-9624-1A19C78A4310} = {88B03853-2215-4E52-8986-0E76602E5F21}
{FCAE9C42-1DCE-4C2E-BAE0-251C147903B4} = {038C3821-E554-496D-B585-A3BC193B7913}
EndGlobalSection EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {F376A326-7590-4E7E-AB9B-76CED8527AB0} SolutionGuid = {F376A326-7590-4E7E-AB9B-76CED8527AB0}

View file

@ -1,14 +0,0 @@
namespace Insight.Agent.Enums
{
public enum CategoryEnum
{
Network = 1,
System = 2,
Application = 3,
Security = 4,
Monitoring = 5,
Task = 6,
Printer = 7,
RDP = 8
}
}

View file

@ -1,9 +0,0 @@
namespace Insight.Agent.Enums
{
public enum DispatchEnum
{
Pending = 1,
Failure = 2,
Success = 3,
}
}

View file

@ -1,9 +0,0 @@
namespace Insight.Agent.Enums
{
public enum StatusEnum
{
Information = 1,
Warning = 2,
Error = 3
}
}

View file

@ -1,30 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<ImplicitUsings>true</ImplicitUsings>
<Nullable>enable</Nullable>
<AssemblyName>Insight.Agent.Assets</AssemblyName>
<RootNamespace>Insight.Agent</RootNamespace>
<Product>Insight</Product>
<AssemblyVersion>2023.9.14.0</AssemblyVersion>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<DebugType>none</DebugType>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
<DebugType>none</DebugType>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Vaitr.Network" Version="2023.9.13" />
<PackageReference Include="Vaitr.Snmp" Version="2023.3.3" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\Core\Insight.Domain\Insight.Domain.csproj" />
</ItemGroup>
</Project>

View file

@ -1,9 +0,0 @@
using Insight.Agent.Messages;
namespace Insight.Agent.Interfaces
{
public partial interface IAgentMessageHandler<TSender>
{
ValueTask HandleAsync<TMessage>(TSender sender, TMessage message, CancellationToken cancellationToken) where TMessage : IAgentMessage;
}
}

View file

@ -1,41 +0,0 @@
using MemoryPack;
using System.Runtime.InteropServices;
namespace Insight.Agent.Messages
{
[MemoryPackUnion(120, typeof(Application))]
[MemoryPackUnion(121, typeof(ApplicationList))]
public partial interface IAgentMessage { }
[MemoryPackable]
public partial class Application : IAgentMessage
{
[MemoryPackOrder(0)]
public string? Name { get; set; }
[MemoryPackOrder(1)]
public string? Publisher { get; set; }
[MemoryPackOrder(2)]
public string? Version { get; set; }
[MemoryPackOrder(3)]
public string? Location { get; set; }
[MemoryPackOrder(4)]
public string? Source { get; set; }
[MemoryPackOrder(5)]
public string? Uninstall { get; set; }
[MemoryPackOrder(6)]
public DateTime? InstallDate { get; set; }
[MemoryPackOrder(7)]
public Architecture? Architecture { get; set; }
}
[MemoryPackable(GenerateType.Collection)]
public partial class ApplicationList : List<Application>, IAgentMessage { }
}

View file

@ -1,34 +0,0 @@
using MemoryPack;
namespace Insight.Agent.Messages
{
[MemoryPackUnion(1, typeof(Authentication))]
[MemoryPackUnion(2, typeof(AuthenticationRequest))]
public partial interface IAgentMessage { }
[MemoryPackable]
public partial class Authentication : IAgentMessage
{
[MemoryPackOrder(0)]
public PlatformType? Platform { get; set; }
[MemoryPackOrder(1)]
public Guid Serial { get; set; }
[MemoryPackOrder(2)]
public Version? Version { get; set; }
[MemoryPackOrder(3)]
public string? Hostname { get; set; }
public enum PlatformType
{
Unknown = 0,
Windows = 1,
Unix = 2
}
}
[MemoryPackable]
public partial class AuthenticationRequest : IAgentMessage { }
}

View file

@ -1,10 +0,0 @@
using MemoryPack;
namespace Insight.Agent.Messages
{
[MemoryPackUnion(2000, typeof(GetInventory))]
public partial interface IAgentMessage { }
[MemoryPackable]
public partial class GetInventory : IAgentMessage { }
}

View file

@ -1,49 +0,0 @@
using MemoryPack;
namespace Insight.Agent.Messages
{
[MemoryPackUnion(1000, typeof(ConsoleQuery))]
[MemoryPackUnion(1001, typeof(ConsoleQueryRequest))]
public partial interface IAgentMessage { }
[MemoryPackable]
public partial class ConsoleQuery : IAgentMessage
{
[MemoryPackOrder(0)]
public string? Id { get; set; }
[MemoryPackOrder(1)]
public string? HostId { get; set; }
[MemoryPackOrder(2)]
public string? Query { get; set; }
[MemoryPackOrder(3)]
public string? Data { get; set; }
[MemoryPackOrder(4)]
public string? Errors { get; set; }
[MemoryPackOrder(5)]
public bool IsString { get; set; }
[MemoryPackOrder(6)]
public bool IsArray { get; set; }
[MemoryPackOrder(7)]
public bool HadErrors { get; set; }
}
[MemoryPackable]
public partial class ConsoleQueryRequest : IAgentMessage
{
[MemoryPackOrder(0)]
public string? Id { get; set; }
[MemoryPackOrder(1)]
public string? HostId { get; set; }
[MemoryPackOrder(2)]
public string? Query { get; set; }
}
}

View file

@ -1,103 +0,0 @@
using MemoryPack;
namespace Insight.Agent.Messages
{
[MemoryPackUnion(50, typeof(Drive))]
[MemoryPackUnion(51, typeof(DriveList))]
public partial interface IAgentMessage { }
[MemoryPackable]
public partial class Drive : IAgentMessage
{
[MemoryPackOrder(0)]
public uint? Index { get; set; }
[MemoryPackOrder(1)]
public string? Id { get; set; }
[MemoryPackOrder(2)]
public string? Name { get; set; }
[MemoryPackOrder(3)]
public string? Manufacturer { get; set; }
[MemoryPackOrder(4)]
public string? SerialNumber { get; set; }
[MemoryPackOrder(5)]
public ulong? Size { get; set; }
[MemoryPackOrder(6)]
public string? Status { get; set; }
[MemoryPackOrder(7)]
public string? InterfaceType { get; set; }
[MemoryPackOrder(8)]
public string? FirmwareRevision { get; set; }
[MemoryPackOrder(9)]
public string? PNPDeviceID { get; set; }
[MemoryPackOrder(10)]
public List<Volume>? Volumes { get; set; }
}
[MemoryPackable(GenerateType.Collection)]
public partial class DriveList : List<Drive>, IAgentMessage { }
[MemoryPackable]
public partial class Volume : IAgentMessage
{
[MemoryPackOrder(0)]
public uint? Index { get; set; }
[MemoryPackOrder(1)]
public string? Id { get; set; }
[MemoryPackOrder(2)]
public string? Name { get; set; }
[MemoryPackOrder(3)]
public string? SerialNumber { get; set; }
[MemoryPackOrder(4)]
public ulong? Size { get; set; }
[MemoryPackOrder(5)]
public ulong? FreeSpace { get; set; }
[MemoryPackOrder(6)]
public string? Type { get; set; }
[MemoryPackOrder(7)]
public string? FileSystem { get; set; }
[MemoryPackOrder(8)]
public bool? Compressed { get; set; }
[MemoryPackOrder(9)]
public bool? Bootable { get; set; }
[MemoryPackOrder(10)]
public bool? PrimaryPartition { get; set; }
[MemoryPackOrder(11)]
public bool? BootPartition { get; set; }
[MemoryPackOrder(12)]
public ulong? BlockSize { get; set; }
[MemoryPackOrder(13)]
public ulong? NumberOfBlocks { get; set; }
[MemoryPackOrder(14)]
public ulong? StartingOffset { get; set; }
[MemoryPackOrder(15)]
public DriveType? DriveType { get; set; }
[MemoryPackOrder(16)]
public string? ProviderName { get; set; }
}
}

View file

@ -1,41 +0,0 @@
using MemoryPack;
namespace Insight.Agent.Messages
{
[MemoryPackUnion(10, typeof(Event))]
public partial interface IAgentMessage { }
[MemoryPackable]
public partial class Event : IAgentMessage
{
[MemoryPackOrder(0)]
public DateTime? Timestamp { get; set; }
[MemoryPackOrder(1)]
public StatusType? Status { get; set; }
[MemoryPackOrder(2)]
public string? Source { get; set; }
[MemoryPackOrder(3)]
public string? Category { get; set; }
[MemoryPackOrder(4)]
public int? EventId { get; set; }
[MemoryPackOrder(5)]
public string? Task { get; set; }
[MemoryPackOrder(6)]
public string? Message { get; set; }
public enum StatusType
{
Unknown = 0,
Information = 1,
Warning = 2,
Error = 3,
Critical = 4
}
}
}

View file

@ -1,7 +0,0 @@
using MemoryPack;
namespace Insight.Agent.Messages
{
[MemoryPackable]
public partial interface IAgentMessage { }
}

View file

@ -1,195 +0,0 @@
using MemoryPack;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
namespace Insight.Agent.Messages
{
[MemoryPackUnion(70, typeof(Interface))]
[MemoryPackUnion(71, typeof(InterfaceList))]
public partial interface IAgentMessage { }
[MemoryPackable]
public partial class Interface : IAgentMessage
{
[MemoryPackOrder(0)]
public uint? Index { get; set; }
[MemoryPackOrder(1)]
public Guid? Guid { get; set; }
[MemoryPackOrder(2)]
public string? Mac { get; set; }
[MemoryPackOrder(3)]
public string? Name { get; set; }
[MemoryPackOrder(4)]
public string? Description { get; set; }
[MemoryPackOrder(5)]
public string? Manufacturer { get; set; }
[MemoryPackOrder(6)]
public string? Suffix { get; set; }
[MemoryPackOrder(7)]
public bool? Physical { get; set; }
[MemoryPackOrder(8)]
public NetworkInterfaceType? Type { get; set; }
[MemoryPackOrder(9)]
public OperationalStatus? Status { get; set; }
[MemoryPackOrder(10)]
public long? Speed { get; set; }
[MemoryPackOrder(11)]
public long? Ipv4Mtu { get; set; }
[MemoryPackOrder(12)]
public bool? Ipv4Dhcp { get; set; }
[MemoryPackOrder(13)]
public bool? Ipv4Forwarding { get; set; }
[MemoryPackOrder(14)]
public long? Ipv6Mtu { get; set; }
[MemoryPackOrder(15)]
public long? Sent { get; set; }
[MemoryPackOrder(16)]
public long? Received { get; set; }
[MemoryPackOrder(17)]
public long? IncomingPacketsDiscarded { get; set; }
[MemoryPackOrder(18)]
public long? IncomingPacketsWithErrors { get; set; }
[MemoryPackOrder(19)]
public long? IncomingUnknownProtocolPackets { get; set; }
[MemoryPackOrder(20)]
public long? OutgoingPacketsDiscarded { get; set; }
[MemoryPackOrder(21)]
public long? OutgoingPacketsWithErrors { get; set; }
[MemoryPackOrder(22)]
public List<Unicast>? Addresses { get; set; }
[MemoryPackOrder(23)]
public List<IPAddress2>? Gateways { get; set; }
[MemoryPackOrder(24)]
public List<IPAddress2>? Dns { get; set; }
[MemoryPackOrder(25)]
public List<IPAddress2>? Dhcp { get; set; }
[MemoryPackOrder(26)]
public List<Route>? Routes { get; set; }
}
[MemoryPackable(GenerateType.Collection)]
public partial class InterfaceList : List<Interface>, IAgentMessage { }
[MemoryPackable]
public partial class Unicast : IAgentMessage
{
[MemoryPackOrder(0)]
public IPAddress2? IpAddress { get; set; }
[MemoryPackOrder(1)]
public IPAddress2? Ipv4Mask { get; set; }
[MemoryPackOrder(2)]
public long? AddressPreferredLifetime { get; set; }
[MemoryPackOrder(3)]
public long? AddressValidLifetime { get; set; }
[MemoryPackOrder(4)]
public long? DhcpLeaseLifetime { get; set; }
[MemoryPackOrder(5)]
public DuplicateAddressDetectionState? DuplicateAddressDetectionState { get; set; }
[MemoryPackOrder(6)]
public int? PrefixLength { get; set; }
[MemoryPackOrder(7)]
public PrefixOrigin? PrefixOrigin { get; set; }
[MemoryPackOrder(8)]
public SuffixOrigin? SuffixOrigin { get; set; }
}
[MemoryPackable]
public partial class Route : IAgentMessage
{
[MemoryPackOrder(0)]
public uint? InterfaceIndex { get; set; }
[MemoryPackOrder(1)]
public IPAddress2? Destination { get; set; }
[MemoryPackOrder(2)]
public IPAddress2? Gateway { get; set; }
[MemoryPackOrder(3)]
public string? Mask { get; set; }
[MemoryPackOrder(4)]
public int? Metric { get; set; }
}
[MemoryPackable]
public partial class IPAddress2 : IAgentMessage
{
[MemoryPackOrder(0)]
public AddressFamily? AddressFamily { get; set; }
[MemoryPackOrder(1)]
public string? Address { get; set; }
[MemoryPackOrder(2)]
public bool? IsIPv6Teredo { get; set; }
[MemoryPackOrder(3)]
public bool? IsIPv6SiteLocal { get; set; }
[MemoryPackOrder(4)]
public bool? IsIPv6Multicast { get; set; }
[MemoryPackOrder(5)]
public bool? IsIPv6LinkLocal { get; set; }
[MemoryPackOrder(6)]
public bool? IsIPv4MappedToIPv6 { get; set; }
[MemoryPackOrder(7)]
public bool? IsIPv6UniqueLocal { get; set; }
[MemoryPackConstructor]
public IPAddress2()
{
}
public IPAddress2(IPAddress address)
{
AddressFamily = address.AddressFamily;
Address = address.ToString();
IsIPv4MappedToIPv6 = address.IsIPv4MappedToIPv6;
IsIPv6LinkLocal = address.IsIPv6LinkLocal;
IsIPv6Multicast = address.IsIPv6Multicast;
IsIPv6SiteLocal = address.IsIPv6SiteLocal;
IsIPv6Teredo = address.IsIPv6Teredo;
IsIPv6UniqueLocal = address.IsIPv6UniqueLocal;
}
}
}

View file

@ -1,10 +0,0 @@
using MemoryPack;
namespace Insight.Agent.Messages
{
[MemoryPackUnion(0, typeof(Keepalive))]
public partial interface IAgentMessage { }
[MemoryPackable]
public partial class Keepalive : IAgentMessage { }
}

View file

@ -1,29 +0,0 @@
using MemoryPack;
namespace Insight.Agent.Messages
{
[MemoryPackUnion(20, typeof(Mainboard))]
public partial interface IAgentMessage { }
[MemoryPackable]
public partial class Mainboard : IAgentMessage
{
[MemoryPackOrder(0)]
public string? Manufacturer { get; set; }
[MemoryPackOrder(1)]
public string? Model { get; set; }
[MemoryPackOrder(2)]
public string? Serial { get; set; }
[MemoryPackOrder(3)]
public string? BiosManufacturer { get; set; }
[MemoryPackOrder(4)]
public string? BiosVersion { get; set; }
[MemoryPackOrder(5)]
public DateTime? BiosDate { get; set; }
}
}

View file

@ -1,67 +0,0 @@
using MemoryPack;
namespace Insight.Agent.Messages
{
[MemoryPackUnion(40, typeof(Memory))]
[MemoryPackUnion(41, typeof(MemoryList))]
public partial interface IAgentMessage { }
[MemoryPackable]
public partial class Memory : IAgentMessage
{
[MemoryPackOrder(0)]
public uint? Index { get; set; }
[MemoryPackOrder(1)]
public string? Tag { get; set; }
[MemoryPackOrder(2)]
public string? Location { get; set; }
[MemoryPackOrder(3)]
public string? Manufacturer { get; set; }
[MemoryPackOrder(4)]
public string? Model { get; set; }
[MemoryPackOrder(5)]
public string? Serial { get; set; }
[MemoryPackOrder(6)]
public ulong? Capacity { get; set; }
[MemoryPackOrder(7)]
public uint? Speed { get; set; }
[MemoryPackOrder(8)]
public uint? Voltage { get; set; }
[MemoryPackOrder(9)]
public uint? ConfiguredSpeed { get; set; }
[MemoryPackOrder(10)]
public uint? ConfiguredVoltage { get; set; }
}
[MemoryPackable(GenerateType.Collection)]
public partial class MemoryList : List<Memory>, IAgentMessage { }
[MemoryPackable]
public partial class MemoryMetric : IAgentMessage
{
[MemoryPackOrder(0)]
public DateTime? Timestamp { get; set; }
[MemoryPackOrder(1)]
public float? MemoryAvailable { get; set; }
[MemoryPackOrder(2)]
public float? MemoryAvailablePercentage { get; set; }
[MemoryPackOrder(3)]
public float? MemoryUsed { get; set; }
[MemoryPackOrder(4)]
public float? MemoryUsagePercentage { get; set; }
}
}

View file

@ -1,30 +0,0 @@
using MemoryPack;
using System.Runtime.InteropServices;
namespace Insight.Agent.Messages
{
[MemoryPackUnion(90, typeof(OperationSystem))]
public partial interface IAgentMessage { }
[MemoryPackable]
public partial class OperationSystem : IAgentMessage
{
[MemoryPackOrder(0)]
public string? Name { get; set; }
[MemoryPackOrder(1)]
public string? Version { get; set; }
[MemoryPackOrder(2)]
public string? SerialNumber { get; set; }
[MemoryPackOrder(3)]
public Architecture? Architecture { get; set; }
[MemoryPackOrder(4)]
public bool? Virtual { get; set; }
[MemoryPackOrder(5)]
public DateTime? InstallDate { get; set; }
}
}

View file

@ -1,30 +0,0 @@
using MemoryPack;
namespace Insight.Agent.Messages
{
[MemoryPackUnion(140, typeof(Printer))]
[MemoryPackUnion(141, typeof(PrinterList))]
public partial interface IAgentMessage { }
[MemoryPackable]
public partial class Printer : IAgentMessage
{
[MemoryPackOrder(0)]
public string? Name { get; set; }
[MemoryPackOrder(1)]
public string? Driver { get; set; }
[MemoryPackOrder(2)]
public string? Port { get; set; }
[MemoryPackOrder(3)]
public string? Location { get; set; }
[MemoryPackOrder(4)]
public string? Comment { get; set; }
}
[MemoryPackable(GenerateType.Collection)]
public partial class PrinterList : List<Printer>, IAgentMessage { }
}

View file

@ -1,70 +0,0 @@
using MemoryPack;
namespace Insight.Agent.Messages
{
[MemoryPackUnion(30, typeof(Processor))]
[MemoryPackUnion(31, typeof(ProcessorList))]
public partial interface IAgentMessage { }
[MemoryPackable]
public partial class Processor : IAgentMessage
{
[MemoryPackOrder(0)]
public uint? Index { get; set; }
[MemoryPackOrder(1)]
public string? Name { get; set; }
[MemoryPackOrder(2)]
public string? Manufacturer { get; set; }
[MemoryPackOrder(3)]
public string? SerialNumber { get; set; }
[MemoryPackOrder(4)]
public string? Socket { get; set; }
[MemoryPackOrder(5)]
public string? Version { get; set; }
[MemoryPackOrder(6)]
public string? DeviceId { get; set; }
[MemoryPackOrder(7)]
public uint? Cores { get; set; }
[MemoryPackOrder(8)]
public uint? LogicalCores { get; set; }
[MemoryPackOrder(9)]
public uint? CurrentSpeed { get; set; }
[MemoryPackOrder(10)]
public uint? MaxSpeed { get; set; }
[MemoryPackOrder(11)]
public uint? L1Size { get; set; }
[MemoryPackOrder(12)]
public uint? L2Size { get; set; }
[MemoryPackOrder(13)]
public uint? L3Size { get; set; }
[MemoryPackOrder(14)]
public bool? Virtualization { get; set; }
}
[MemoryPackable(GenerateType.Collection)]
public partial class ProcessorList : List<Processor>, IAgentMessage { }
[MemoryPackable]
public partial class ProcessorMetric : IAgentMessage
{
[MemoryPackOrder(0)]
public DateTime? Timestamp { get; set; }
[MemoryPackOrder(1)]
public float? ProcessorUsagePercentage { get; set; }
}
}

View file

@ -1,64 +0,0 @@
using MemoryPack;
namespace Insight.Agent.Messages
{
[MemoryPackUnion(130, typeof(Service))]
[MemoryPackUnion(131, typeof(ServiceList))]
public partial interface IAgentMessage { }
[MemoryPackable]
public partial class Service : IAgentMessage
{
[MemoryPackOrder(0)]
public uint? ProcessId { get; set; }
[MemoryPackOrder(1)]
public string? Name { get; set; }
[MemoryPackOrder(2)]
public string? Display { get; set; }
[MemoryPackOrder(3)]
public string? Description { get; set; }
[MemoryPackOrder(4)]
public string? PathName { get; set; }
[MemoryPackOrder(5)]
public string? Account { get; set; }
[MemoryPackOrder(6)]
public bool? Delay { get; set; }
[MemoryPackOrder(7)]
public ServiceStatus? Status { get; set; }
[MemoryPackOrder(8)]
public ServiceMode? StartMode { get; set; }
public enum ServiceStatus
{
Unknown = -1,
Stopped = 1,
StartPending = 2,
StopPending = 3,
Running = 4,
ContinuePending = 5,
PausePending = 6,
Paused = 7
}
public enum ServiceMode
{
Unknown = -1,
Boot = 0,
System = 1,
Automatic = 2,
Manual = 3,
Disabled = 4
}
}
[MemoryPackable(GenerateType.Collection)]
public partial class ServiceList : List<Service>, IAgentMessage { }
}

View file

@ -1,30 +0,0 @@
using MemoryPack;
namespace Insight.Agent.Messages
{
[MemoryPackUnion(110, typeof(Session))]
[MemoryPackUnion(111, typeof(SessionList))]
public partial interface IAgentMessage { }
[MemoryPackable]
public partial class Session : IAgentMessage
{
[MemoryPackOrder(0)]
public string? Sid { get; set; }
[MemoryPackOrder(1)]
public string? User { get; set; }
[MemoryPackOrder(2)]
public string? Type { get; set; }
[MemoryPackOrder(3)]
public string? Status { get; set; }
[MemoryPackOrder(4)]
public string? Remote { get; set; }
}
[MemoryPackable(GenerateType.Collection)]
public partial class SessionList : List<Session>, IAgentMessage { }
}

View file

@ -1,17 +0,0 @@
using MemoryPack;
namespace Insight.Agent.Messages
{
[MemoryPackUnion(3, typeof(Status))]
public partial interface IAgentMessage { }
[MemoryPackable]
public partial class Status : IAgentMessage
{
[MemoryPackOrder(0)]
public DateTime Timestamp { get; } = DateTime.Now;
[MemoryPackOrder(1)]
public TimeSpan Uptime { get; set; }
}
}

View file

@ -1,302 +0,0 @@
using MemoryPack;
namespace Insight.Agent.Messages
{
[MemoryPackUnion(160, typeof(StoragePool))]
[MemoryPackUnion(161, typeof(StoragePoolList))]
public partial interface IAgentMessage { }
[MemoryPackable]
public partial class StoragePool : IAgentMessage
{
[MemoryPackOrder(0)]
public string? UniqueId { get; set; }
[MemoryPackOrder(1)]
public string? Name { get; set; }
[MemoryPackOrder(2)]
public string? FriendlyName { get; set; }
[MemoryPackOrder(3)]
public List<OperationalState>? States { get; set; }
[MemoryPackOrder(4)]
public HealthState? Health { get; set; }
[MemoryPackOrder(5)]
public RetireMissingPhysicalDisksEnum? RetireMissingPhysicalDisks { get; set; }
[MemoryPackOrder(6)]
public string? Resiliency { get; set; }
[MemoryPackOrder(7)]
public bool? IsPrimordial { get; set; }
[MemoryPackOrder(8)]
public bool? IsReadOnly { get; set; }
[MemoryPackOrder(9)]
public bool? IsClustered { get; set; }
[MemoryPackOrder(10)]
public ulong? Size { get; set; }
[MemoryPackOrder(11)]
public ulong? AllocatedSize { get; set; }
[MemoryPackOrder(12)]
public ulong? SectorSize { get; set; }
[MemoryPackOrder(13)]
public List<PhysicalDisk>? PhysicalDisks { get; set; }
[MemoryPackOrder(14)]
public List<VirtualDisk>? VirtualDisks { get; set; }
public enum OperationalState
{
Unknown = 0,
Other = 1,
OK = 2,
Degraded = 3,
Stressed = 4,
Predictive_Failure = 5,
Error = 6,
Non_Recoverable_Error = 7,
Starting = 8,
Stopping = 9,
Stopped = 10,
In_Service = 11,
No_Contact = 12,
Lost_Communication = 13,
Aborted = 14,
Dormant = 15,
Supporting_Entity_In_Error = 16,
Completed = 17,
Power_Mode = 18,
Relocating = 19
}
public enum HealthState
{
Healthy = 0,
Warning = 1,
Unhealthy = 2,
Unknown = 3
}
public enum RetireMissingPhysicalDisksEnum
{
Auto = 1,
Always = 2,
Never = 3
}
}
[MemoryPackable(GenerateType.Collection)]
public partial class StoragePoolList : List<StoragePool>, IAgentMessage { }
[MemoryPackable]
public partial class PhysicalDisk : IAgentMessage
{
[MemoryPackOrder(0)]
public string? UniqueId { get; set; }
[MemoryPackOrder(1)]
public string? DeviceId { get; set; }
[MemoryPackOrder(2)]
public string? FriendlyName { get; set; }
[MemoryPackOrder(3)]
public string? Manufacturer { get; set; }
[MemoryPackOrder(4)]
public string? Model { get; set; }
[MemoryPackOrder(5)]
public ushort? MediaType { get; set; }
[MemoryPackOrder(6)]
public ushort? BusType { get; set; }
[MemoryPackOrder(7)]
public List<OperationalState>? States { get; set; }
[MemoryPackOrder(8)]
public HealthState? Health { get; set; }
[MemoryPackOrder(9)]
public List<SupportedUsagesEnum>? SupportedUsages { get; set; }
[MemoryPackOrder(10)]
public ushort? Usage { get; set; }
[MemoryPackOrder(11)]
public string? PhysicalLocation { get; set; }
[MemoryPackOrder(12)]
public string? SerialNumber { get; set; }
[MemoryPackOrder(13)]
public string? FirmwareVersion { get; set; }
[MemoryPackOrder(14)]
public ulong? Size { get; set; }
[MemoryPackOrder(15)]
public ulong? AllocatedSize { get; set; }
[MemoryPackOrder(16)]
public ulong? LogicalSectorSize { get; set; }
[MemoryPackOrder(17)]
public ulong? PhysicalSectorSize { get; set; }
[MemoryPackOrder(18)]
public ulong? VirtualDiskFootprint { get; set; }
public enum OperationalState
{
Unknown = 0,
Other = 1,
OK = 2,
Degraded = 3,
Stressed = 4,
Predictive_Failure = 5,
Error = 6,
Non_Recoverable_Error = 7,
Starting = 8,
Stopping = 9,
Stopped = 10,
In_Service = 11,
No_Contact = 12,
Lost_Communication = 13,
Aborted = 14,
Dormant = 15,
Supporting_Entity_In_Error = 16,
Completed = 17,
Power_Mode = 18,
Relocating = 19
}
public enum HealthState
{
Healthy = 0,
Warning = 1,
Unhealthy = 2,
Unknown = 3
}
public enum SupportedUsagesEnum
{
Unknown = 0,
Auto_Select = 1,
Manual_Select = 2,
Hot_Spare = 3,
Retired = 4,
Journal = 5
}
}
[MemoryPackable]
public partial class VirtualDisk : IAgentMessage
{
[MemoryPackOrder(0)]
public string? UniqueId { get; set; }
[MemoryPackOrder(1)]
public string? Name { get; set; }
[MemoryPackOrder(2)]
public string? FriendlyName { get; set; }
[MemoryPackOrder(3)]
public List<OperationalState>? States { get; set; }
[MemoryPackOrder(4)]
public HealthState? Health { get; set; }
[MemoryPackOrder(5)]
public AccessTypeEnum? AccessType { get; set; }
[MemoryPackOrder(6)]
public ProvisioningTypeEnum? ProvisioningType { get; set; }
[MemoryPackOrder(7)]
public ushort? PhysicalDiskRedundancy { get; set; }
[MemoryPackOrder(8)]
public string? ResiliencySettingName { get; set; }
[MemoryPackOrder(9)]
public bool? Deduplication { get; set; }
[MemoryPackOrder(10)]
public bool? IsSnapshot { get; set; }
[MemoryPackOrder(11)]
public ulong? Size { get; set; }
[MemoryPackOrder(12)]
public ulong? AllocatedSize { get; set; }
[MemoryPackOrder(13)]
public ulong? FootprintOnPool { get; set; }
[MemoryPackOrder(14)]
public ulong? ReadCacheSize { get; set; }
[MemoryPackOrder(15)]
public ulong? WriteCacheSize { get; set; }
public enum OperationalState
{
Unknown = 0,
Other = 1,
OK = 2,
Degraded = 3,
Stressed = 4,
Predictive_Failure = 5,
Error = 6,
Non_Recoverable_Error = 7,
Starting = 8,
Stopping = 9,
Stopped = 10,
In_Service = 11,
No_Contact = 12,
Lost_Communication = 13,
Aborted = 14,
Dormant = 15,
Supporting_Entity_In_Error = 16,
Completed = 17,
Power_Mode = 18,
Relocating = 19
}
public enum HealthState
{
Healthy = 0,
Warning = 1,
Unhealthy = 2,
Unknown = 3
}
public enum AccessTypeEnum
{
Unknown = 0,
Readable = 1,
Writeable = 2,
Read_Write = 3,
Write_Once = 4
}
public enum ProvisioningTypeEnum
{
Unknown = 0,
Thin = 1,
Fixed = 2
}
}
}

View file

@ -1,23 +0,0 @@
using MemoryPack;
namespace Insight.Agent.Messages
{
[MemoryPackUnion(80, typeof(SystemInfo))]
public partial interface IAgentMessage { }
[MemoryPackable]
public partial class SystemInfo : IAgentMessage
{
[MemoryPackOrder(0)]
public DateTime? LastBootUpTime { get; set; }
[MemoryPackOrder(1)]
public DateTime? LocalDateTime { get; set; }
[MemoryPackOrder(2)]
public uint? Processes { get; set; }
[MemoryPackOrder(3)]
public string? License { get; set; }
}
}

View file

@ -1,29 +0,0 @@
using MemoryPack;
namespace Insight.Agent.Messages
{
[MemoryPackUnion(11, typeof(Trap))]
public partial interface IAgentMessage { }
[MemoryPackable]
public partial class Trap : IAgentMessage
{
[MemoryPackOrder(0)]
public DateTime? Timestamp { get; set; }
[MemoryPackOrder(1)]
public string? Endpoint { get; set; }
[MemoryPackOrder(2)]
public string? Hostname { get; set; }
[MemoryPackOrder(3)]
public string? Version { get; set; }
[MemoryPackOrder(4)]
public string? Community { get; set; }
[MemoryPackOrder(5)]
public List<KeyValuePair<string, string?>>? Data { get; set; }
}
}

View file

@ -1,83 +0,0 @@
using MemoryPack;
namespace Insight.Agent.Messages
{
[MemoryPackUnion(100, typeof(Update))]
[MemoryPackUnion(101, typeof(UpdateList))]
public partial interface IAgentMessage { }
[MemoryPackable]
public partial class Update : IAgentMessage
{
[MemoryPackOrder(0)]
public string? Id { get; set; }
[MemoryPackOrder(1)]
public DateTime? Date { get; set; }
[MemoryPackOrder(2)]
public string? Name { get; set; }
[MemoryPackOrder(3)]
public string? Description { get; set; }
[MemoryPackOrder(4)]
public string? SupportUrl { get; set; }
[MemoryPackOrder(5)]
public string? Hotfix { get; set; }
// if installed
[MemoryPackOrder(6)]
public OsUpdateResultCodeEnum? Result { get; set; }
// if pending
[MemoryPackOrder(7)]
public OsUpdateTypeEnum? Type { get; set; }
[MemoryPackOrder(8)]
public decimal? Size { get; set; }
[MemoryPackOrder(9)]
public bool? IsDownloaded { get; set; }
[MemoryPackOrder(10)]
public bool? CanRequestUserInput { get; set; }
[MemoryPackOrder(11)]
public OsUpdateRebootBehaviorEnum? RebootBehavior { get; set; }
public enum OsUpdateRebootBehaviorEnum
{
NeverReboots = 1,
AlwaysRequiresReboot = 2,
CanRequestReboot = 3
}
public enum OsUpdateResultCodeEnum
{
NotStarted = 1,
InProgress = 2,
Succeeded = 3,
SucceededWithErrors = 4,
Failed = 5,
Aborted = 6
}
public enum OsUpdateTypeEnum
{
Software = 1,
Driver = 2
}
}
[MemoryPackable]
public partial class UpdateList : IAgentMessage
{
[MemoryPackOrder(0)]
public List<Update>? Installed { get; set; }
[MemoryPackOrder(1)]
public List<Update>? Pending { get; set; }
}
}

View file

@ -1,73 +0,0 @@
using MemoryPack;
namespace Insight.Agent.Messages
{
[MemoryPackUnion(150, typeof(User))]
[MemoryPackUnion(151, typeof(UserList))]
public partial interface IAgentMessage { }
[MemoryPackable]
public partial class User : IAgentMessage
{
[MemoryPackOrder(0)]
public string? Sid { get; set; }
[MemoryPackOrder(1)]
public string? Domain { get; set; }
[MemoryPackOrder(2)]
public string? Name { get; set; }
[MemoryPackOrder(3)]
public string? FullName { get; set; }
[MemoryPackOrder(4)]
public string? Description { get; set; }
[MemoryPackOrder(5)]
public string? Status { get; set; }
[MemoryPackOrder(6)]
public bool? LocalAccount { get; set; }
[MemoryPackOrder(7)]
public bool? Disabled { get; set; }
[MemoryPackOrder(8)]
public bool? Lockout { get; set; }
[MemoryPackOrder(9)]
public bool? PasswordChangeable { get; set; }
[MemoryPackOrder(10)]
public bool? PasswordExpires { get; set; }
[MemoryPackOrder(11)]
public bool? PasswordRequired { get; set; }
[MemoryPackOrder(12)]
public List<Group>? Groups { get; set; }
}
[MemoryPackable(GenerateType.Collection)]
public partial class UserList : List<User>, IAgentMessage { }
[MemoryPackable]
public partial class Group : IAgentMessage
{
[MemoryPackOrder(0)]
public string? Sid { get; set; }
[MemoryPackOrder(1)]
public string? Domain { get; set; }
[MemoryPackOrder(2)]
public string? Name { get; set; }
[MemoryPackOrder(3)]
public string? Description { get; set; }
[MemoryPackOrder(4)]
public bool? LocalAccount { get; set; }
}
}

View file

@ -1,30 +0,0 @@
using MemoryPack;
namespace Insight.Agent.Messages
{
[MemoryPackUnion(60, typeof(Videocard))]
[MemoryPackUnion(61, typeof(VideocardList))]
public partial interface IAgentMessage { }
[MemoryPackable]
public partial class Videocard : IAgentMessage
{
[MemoryPackOrder(0)]
public string? DeviceId { get; set; }
[MemoryPackOrder(1)]
public string? Model { get; set; }
[MemoryPackOrder(2)]
public ulong Memory { get; set; }
[MemoryPackOrder(3)]
public DateTime DriverDate { get; set; }
[MemoryPackOrder(4)]
public string? DriverVersion { get; set; }
}
[MemoryPackable(GenerateType.Collection)]
public partial class VideocardList : List<Videocard>, IAgentMessage { }
}

View file

@ -1,265 +0,0 @@
using MemoryPack;
namespace Insight.Agent.Messages
{
[MemoryPackUnion(170, typeof(VirtualMaschine))]
[MemoryPackUnion(171, typeof(VirtualMaschineList))]
public partial interface IAgentMessage { }
[MemoryPackable]
public partial class VirtualMaschine : IAgentMessage
{
[MemoryPackOrder(0)]
public Guid? Id { get; set; }
[MemoryPackOrder(1)]
public uint? ProcessId { get; set; }
[MemoryPackOrder(2)]
public string? Caption { get; set; }
[MemoryPackOrder(3)]
public string? Name { get; set; }
[MemoryPackOrder(4)]
public string? Notes { get; set; }
[MemoryPackOrder(5)]
public EnabledEnum? Enabled { get; set; }
[MemoryPackOrder(6)]
public EnabledDefaultEnum? EnabledDefault { get; set; }
[MemoryPackOrder(7)]
public HealthStatusEnum? HealthState { get; set; }
[MemoryPackOrder(8)]
public string? Status { get; set; }
[MemoryPackOrder(9)]
public ulong? OnTime { get; set; }
[MemoryPackOrder(10)]
public uint? ReplicationMode { get; set; }
[MemoryPackOrder(11)]
public ReplicationStateEnum? ReplicationState { get; set; }
[MemoryPackOrder(12)]
public ReplicationHealthEnum? ReplicationHealth { get; set; }
[MemoryPackOrder(13)]
public string? ConfigurationVersion { get; set; }
[MemoryPackOrder(14)]
public IntegrationServicesVersionStateEnum? IntegrationServicesVersionState { get; set; }
[MemoryPackOrder(15)]
public uint? NumberOfProcessors { get; set; }
[MemoryPackOrder(16)]
public uint? ProcessorLoad { get; set; }
[MemoryPackOrder(17)]
public int? MemoryAvailable { get; set; }
[MemoryPackOrder(18)]
public ulong? MemoryUsage { get; set; }
[MemoryPackOrder(19)]
public DateTime? InstallDate { get; set; }
[MemoryPackOrder(20)]
public DateTime? TimeOfLastConfigurationChange { get; set; }
[MemoryPackOrder(21)]
public DateTime? TimeOfLastStateChange { get; set; }
[MemoryPackOrder(22)]
public DateTime? LastReplicationTime { get; set; }
[MemoryPackOrder(23)]
public string? GuestOperatingSystem { get; set; }
[MemoryPackOrder(24)]
public List<VirtualMaschineConfiguration>? Configurations { get; set; }
public enum EnabledEnum
{
Unbekannt = 0,
Andere = 1,
Aktiviert = 2,
Deaktiviert = 3,
Herunterfahren = 4,
Nicht_Verfügbar = 5,
Aktiviert_Offline = 6,
In_Test = 7,
Latent = 8,
Eingeschränkt = 9,
Wird_gestartet = 10
}
public enum EnabledDefaultEnum
{
Aktiviert = 2,
Deaktiviert = 3,
Aktiviert_Offline = 6
}
public enum HealthStatusEnum
{
OK = 5,
Hauptfehler = 20,
Kritischer_Fehler = 25
}
public enum ReplicationStateEnum
{
Deaktiviert = 0,
Bereit = 1,
Warten_auf_Erstreplikation = 2,
Replikat = 3,
Synchronisierte_Replication_abgeschlossen = 4,
Wiederhergestellt = 5,
Commit = 6,
Angehalten = 7,
Kritisch = 8,
Warten_auf_die_Neusynchronisierung = 9,
Resynchronisierung = 10,
Resynchronisierung_angehalten = 11,
Failover_in_Bearbeitung = 12,
Failback_in_Fortschritt = 13,
Failback_abgeschlossen = 14,
Datenträgerupdate_in_Bearbeitung = 15,
Datenträgeraktualisierung_kritisch = 16,
Unbekannt = 17,
Repurpose_Replikation_in_Bearbeitung = 18,
Vorbereitet_für_die_Synchronisierungsreplikation = 19,
Vorbereitet_für_die_Umgekehrte_Replikation_der_Gruppe = 20,
Failover_in_Fortschritt = 21
}
public enum ReplicationHealthEnum
{
OK = 1,
Warnung = 2,
Kritisch = 3
}
public enum IntegrationServicesVersionStateEnum
{
Unknown = 0,
UpToDate = 1,
Mismatch = 2
}
}
[MemoryPackable(GenerateType.Collection)]
public partial class VirtualMaschineList : List<VirtualMaschine>, IAgentMessage { }
[MemoryPackable]
public partial class VirtualMaschineConfiguration : IAgentMessage
{
[MemoryPackOrder(0)]
public string? Id { get; set; }
[MemoryPackOrder(1)]
public string? ParentId { get; set; }
[MemoryPackOrder(2)]
public string? Type { get; set; }
[MemoryPackOrder(3)]
public string? Name { get; set; }
[MemoryPackOrder(4)]
public DateTime? CreationTime { get; set; }
[MemoryPackOrder(5)]
public string? Generation { get; set; }
[MemoryPackOrder(6)]
public string? Architecture { get; set; }
[MemoryPackOrder(7)]
public AutomaticStartupActionEnum? AutomaticStartupAction { get; set; }
//public DateTime? AutomaticStartupActionDelay { get; set; }
[MemoryPackOrder(8)]
public AutomaticShutdownActionEnum? AutomaticShutdownAction { get; set; }
[MemoryPackOrder(9)]
public AutomaticRecoveryActionEnum? AutomaticRecoveryAction { get; set; }
[MemoryPackOrder(10)]
public bool? AutomaticSnapshotsEnabled { get; set; }
[MemoryPackOrder(11)]
public string? BaseBoardSerialNumber { get; set; }
[MemoryPackOrder(12)]
public string? BIOSGUID { get; set; }
[MemoryPackOrder(13)]
public string? BIOSSerialNumber { get; set; }
[MemoryPackOrder(14)]
public ushort[]? BootOrder { get; set; }
[MemoryPackOrder(15)]
public string? ConfigurationDataRoot { get; set; }
[MemoryPackOrder(16)]
public string? ConfigurationFile { get; set; }
[MemoryPackOrder(17)]
public string? GuestStateDataRoot { get; set; }
[MemoryPackOrder(18)]
public string? GuestStateFile { get; set; }
[MemoryPackOrder(19)]
public string? SnapshotDataRoot { get; set; }
[MemoryPackOrder(20)]
public string? SuspendDataRoot { get; set; }
[MemoryPackOrder(21)]
public string? SwapFileDataRoot { get; set; }
[MemoryPackOrder(22)]
public bool? SecureBootEnabled { get; set; }
[MemoryPackOrder(23)]
public bool? IsAutomaticSnapshot { get; set; }
[MemoryPackOrder(24)]
public string[]? Notes { get; set; }
[MemoryPackOrder(25)]
public List<VirtualMaschineConfiguration>? Childs { get; set; }
//public string[]? HostResource { get; set; }
public enum AutomaticStartupActionEnum
{
Nothing = 2,
RestartIfLastStateActive = 3,
Alway = 4
}
public enum AutomaticShutdownActionEnum
{
Ausschalten = 2,
Speichern = 3,
Herunterfahren = 4
}
public enum AutomaticRecoveryActionEnum
{
Keine = 2,
Neustart = 3,
Rollback = 4
}
}
}

View file

@ -1,7 +0,0 @@
namespace Insight.Agent.Models
{
public class Config
{
public Guid? Serial { get; set; }
}
}

View file

@ -1,10 +1,9 @@
namespace Insight.Agent namespace Insight.Agent;
public static class Appsettings
{ {
public static class Appsettings
{
public const string Api = "api"; public const string Api = "api";
public const string ServerHost = "server.host"; public const string ServerHost = "server.host";
public const string ServerPort = "server.port"; public const string ServerPort = "server.port";
public const string TrapPort = "trap.port"; public const string TrapPort = "trap.port";
}
} }

View file

@ -1,7 +1,7 @@
namespace Insight.Agent.Constants namespace Insight.Agent.Constants;
public static class Deploy
{ {
public static class Deploy
{
public static class Updater public static class Updater
{ {
public const string Name = "Updater"; public const string Name = "Updater";
@ -17,5 +17,4 @@
public static Uri GetUpdateHref(Uri api, string appName) public static Uri GetUpdateHref(Uri api, string appName)
=> new($"{api.AbsoluteUri}/update/{appName.ToLower()}/windows"); => new($"{api.AbsoluteUri}/update/{appName.ToLower()}/windows");
}
} }

View file

@ -1,14 +0,0 @@
using Microsoft.Extensions.Configuration;
namespace Insight.Agent.Extensions
{
public static class ConfigurationExtensions
{
public static IConfigurationBuilder Defaults(this IConfigurationBuilder configuration)
{
configuration.Sources.Clear();
configuration.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
return configuration.AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json", optional: true, reloadOnChange: true);
}
}
}

View file

@ -1,32 +0,0 @@
using System.Diagnostics;
using System.Runtime.Versioning;
namespace Insight.Agent.Extensions
{
public static class Linux
{
[SupportedOSPlatform("linux")]
public static string Bash(this string cmd)
{
var escaped = cmd.Replace("\"", "\\\"");
using var proc = new Process()
{
StartInfo = new ProcessStartInfo
{
FileName = "/bin/bash",
Arguments = $"-c \"{escaped}\"",
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true,
}
};
proc.Start();
var result = proc.StandardOutput.ReadToEnd();
proc.WaitForExit();
return result;
}
}
}

View file

@ -0,0 +1,33 @@
using Insight.Agent.Network;
using Insight.Agent.Network.Handlers;
using Insight.Domain.Interfaces;
using Microsoft.Extensions.DependencyInjection;
using System.Runtime.Versioning;
namespace Insight.Agent.Extensions;
internal static class ServiceExtensions
{
[SupportedOSPlatform("windows")]
internal static IServiceCollection InjectWindowsHandler(this IServiceCollection services)
{
services.AddSingleton<IMessageHandler<AgentSession>, DriveHandler>();
services.AddSingleton<IMessageHandler<AgentSession>, InterfaceHandler>();
services.AddSingleton<IMessageHandler<AgentSession>, MainboardHandler>();
services.AddSingleton<IMessageHandler<AgentSession>, MemoryHandler>();
services.AddSingleton<IMessageHandler<AgentSession>, OperationSystemHandler>();
services.AddSingleton<IMessageHandler<AgentSession>, PrinterHandler>();
services.AddSingleton<IMessageHandler<AgentSession>, ProcessorHandler>();
services.AddSingleton<IMessageHandler<AgentSession>, ServiceHandler>();
services.AddSingleton<IMessageHandler<AgentSession>, SessionHandler>();
services.AddSingleton<IMessageHandler<AgentSession>, SoftwareHandler>();
services.AddSingleton<IMessageHandler<AgentSession>, StoragePoolHandler>();
services.AddSingleton<IMessageHandler<AgentSession>, SystemInfoHandler>();
services.AddSingleton<IMessageHandler<AgentSession>, UpdateHandler>();
services.AddSingleton<IMessageHandler<AgentSession>, UserHandler>();
services.AddSingleton<IMessageHandler<AgentSession>, VideocardHandler>();
services.AddSingleton<IMessageHandler<AgentSession>, VirtualMaschineHandler>();
return services;
}
}

View file

@ -2,13 +2,16 @@
<PropertyGroup> <PropertyGroup>
<OutputType>Exe</OutputType> <OutputType>Exe</OutputType>
<TargetFramework>net7.0</TargetFramework> <TargetFramework>net8.0</TargetFramework>
<LangVersion>latest</LangVersion>
<RootNamespace>Insight.Agent</RootNamespace> <RootNamespace>Insight.Agent</RootNamespace>
<Product>Insight</Product> <Product>Insight</Product>
<AssemblyName>agent</AssemblyName> <AssemblyName>agent</AssemblyName>
<AssemblyVersion>2023.9.14.0</AssemblyVersion> <AssemblyVersion>2023.12.14.0</AssemblyVersion>
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
<SatelliteResourceLanguages>none</SatelliteResourceLanguages>
<InvariantGlobalization>true</InvariantGlobalization>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'"> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
@ -20,17 +23,17 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="7.0.0" /> <PackageReference Include="Microsoft.Extensions.Hosting.Systemd" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Hosting.Systemd" Version="7.0.0" /> <PackageReference Include="Microsoft.Extensions.Hosting.WindowsServices" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Hosting.WindowsServices" Version="7.0.1" /> <PackageReference Include="Microsoft.PowerShell.SDK" Version="7.4.0" />
<PackageReference Include="Serilog.Extensions.Logging.File" Version="3.0.0" /> <PackageReference Include="Serilog.Extensions.Logging.File" Version="3.0.0" />
<PackageReference Include="System.Management" Version="7.0.2" /> <PackageReference Include="System.Management" Version="8.0.0" />
<PackageReference Include="System.ServiceProcess.ServiceController" Version="7.0.1" /> <PackageReference Include="System.ServiceProcess.ServiceController" Version="8.0.0" />
<PackageReference Include="Microsoft.PowerShell.SDK" Version="7.3.7" /> <PackageReference Include="Vaitr.Snmp" Version="2023.12.15.1" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\Insight.Agent.Assets\Insight.Agent.Assets.csproj" /> <ProjectReference Include="..\..\Core\Insight.Domain\Insight.Domain.csproj" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>

View file

@ -0,0 +1,6 @@
namespace Insight.Agent;
internal sealed class Config
{
public Guid? Serial { get; set; }
}

View file

@ -0,0 +1,68 @@
using System.Management;
using System.Runtime.Versioning;
namespace Insight.Agent;
public static class ManagmentExtensions
{
[SupportedOSPlatform("windows")]
public static HashSet<string> GetPropertyHashes(this ManagementBaseObject @object)
{
var properties = new HashSet<string>();
foreach (var property in @object.Properties)
{
properties.Add(property.Name);
}
return properties;
}
[SupportedOSPlatform("windows")]
internal static bool TryGet(this ManagementObjectSearcher searcher, out ManagementObjectCollection collection)
{
collection = searcher.Get();
try
{
_ = collection.Count;
return true;
}
catch (ManagementException)
{
collection.Dispose();
return false;
}
}
[SupportedOSPlatform("windows")]
internal static T? GetValue<T>(this ManagementObject @object, HashSet<string> properties, string key)
{
if (@object is null || properties is null || key is null) return default;
if (properties.Contains(key, StringComparer.OrdinalIgnoreCase) is false) return default;
if (@object[key] is not T obj)
{
return default;
}
return obj;
}
[SupportedOSPlatform("windows")]
internal static bool TryGetValue<T>(this ManagementBaseObject @object, HashSet<string> properties, string key, out T? value)
{
value = default;
if (@object is null || properties is null || key is null) return default;
if (properties.Contains(key, StringComparer.OrdinalIgnoreCase) is false) return false;
if (@object[key] is not T obj)
{
return false;
}
value = obj;
return true;
}
}

View file

@ -0,0 +1,43 @@
using System.Runtime.Versioning;
using System.ServiceProcess;
using System.Text;
namespace Insight.Agent;
internal class Helpers
{
internal static string? EscapeWql(string text)
{
if (text == null) return null;
var sb = new StringBuilder(text.Length);
foreach (var c in text)
{
if (c == '\\' || c == '\'' || c == '"')
{
sb.Append('\\');
}
sb.Append(c);
}
return sb.ToString();
}
[SupportedOSPlatform("windows")]
internal static bool ForceWinRmStart()
{
var winRm = ServiceController
.GetServices()
.First(x => x.ServiceName
.ToLower()
.Equals("winrm", StringComparison.Ordinal));
if (winRm.Status is not ServiceControllerStatus.Running)
{
winRm.Start();
winRm.WaitForStatus(ServiceControllerStatus.Running);
}
if (winRm.Status != ServiceControllerStatus.Running) return false;
return true;
}
}

View file

@ -1,69 +0,0 @@
using System.Management;
using System.Runtime.Versioning;
namespace Insight.Agent
{
public static class ManagmentExtensions
{
[SupportedOSPlatform("windows")]
public static HashSet<string> GetPropertyHashes(this ManagementBaseObject @object)
{
var properties = new HashSet<string>();
foreach (var property in @object.Properties)
{
properties.Add(property.Name);
}
return properties;
}
[SupportedOSPlatform("windows")]
internal static bool TryGet(this ManagementObjectSearcher searcher, out ManagementObjectCollection collection)
{
collection = searcher.Get();
try
{
_ = collection.Count;
return true;
}
catch (ManagementException)
{
collection.Dispose();
return false;
}
}
[SupportedOSPlatform("windows")]
internal static T? GetValue<T>(this ManagementObject @object, HashSet<string> properties, string key)
{
if (@object is null || properties is null || key is null) return default;
if (properties.Contains(key, StringComparer.OrdinalIgnoreCase) is false) return default;
if (@object[key] is not T obj)
{
return default;
}
return obj;
}
[SupportedOSPlatform("windows")]
internal static bool TryGetValue<T>(this ManagementBaseObject @object, HashSet<string> properties, string key, out T? value)
{
value = default;
if (@object is null || properties is null || key is null) return default;
if (properties.Contains(key, StringComparer.OrdinalIgnoreCase) is false) return false;
if (@object[key] is not T obj)
{
return false;
}
value = obj;
return true;
}
}
}

View file

@ -1,44 +0,0 @@
using System.Runtime.Versioning;
using System.ServiceProcess;
using System.Text;
namespace Insight.Agent
{
internal class Helpers
{
internal static string? EscapeWql(string text)
{
if (text == null) return null;
var sb = new StringBuilder(text.Length);
foreach (var c in text)
{
if (c == '\\' || c == '\'' || c == '"')
{
sb.Append('\\');
}
sb.Append(c);
}
return sb.ToString();
}
[SupportedOSPlatform("windows")]
internal static bool ForceWinRmStart()
{
var winRm = ServiceController
.GetServices()
.First(x => x.ServiceName
.ToLower()
.Equals("winrm", StringComparison.Ordinal));
if (winRm.Status is not ServiceControllerStatus.Running)
{
winRm.Start();
winRm.WaitForStatus(ServiceControllerStatus.Running);
}
if (winRm.Status != ServiceControllerStatus.Running) return false;
return true;
}
}
}

View file

@ -1,18 +1,17 @@
using Insight.Agent.Interfaces; using Insight.Agent.Services;
using Insight.Agent.Messages; using Insight.Domain.Constants;
using Insight.Domain.Interfaces;
using Insight.Domain.Network;
using Insight.Domain.Network.Agent.Messages;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Vaitr.Network; using Vaitr.Network;
namespace Insight.Agent.Network namespace Insight.Agent.Network;
{
public class AgentSession : TcpSession<IAgentMessage>
{
private readonly IEnumerable<IAgentMessageHandler<AgentSession>> _handlers;
public AgentSession(IEnumerable<IAgentMessageHandler<AgentSession>> handlers, ISerializer<IAgentMessage> serializer, ILogger<AgentSession> logger) : base(serializer, logger) public class AgentSession(IEnumerable<IMessageHandler<AgentSession>> handlers, ISerializer<IMessage> serializer, ILogger<AgentSession> logger)
{ : TcpSession<IMessage>(serializer, logger)
_handlers = handlers; {
} private readonly IEnumerable<IMessageHandler<AgentSession>> _handlers = handlers;
protected override ValueTask OnConnectedAsync(CancellationToken cancellationToken) protected override ValueTask OnConnectedAsync(CancellationToken cancellationToken)
{ {
@ -26,15 +25,20 @@ namespace Insight.Agent.Network
return default; return default;
} }
protected override ValueTask OnSentAsync(IPacketContext<IAgentMessage> context, CancellationToken cancellationToken) protected override ValueTask OnSentAsync(IPacketContext<IMessage> context, CancellationToken cancellationToken)
{ {
return base.OnSentAsync(context, cancellationToken); return base.OnSentAsync(context, cancellationToken);
} }
protected override async ValueTask OnReceivedAsync(IPacketContext<IAgentMessage> context, CancellationToken cancellationToken) protected override async ValueTask OnReceivedAsync(IPacketContext<IMessage> context, CancellationToken cancellationToken)
{ {
await base.OnReceivedAsync(context, cancellationToken); await base.OnReceivedAsync(context, cancellationToken);
// catch authentication request
if (context.Packet is AuthenticationRequest)
await OnAuthenticationAsync(cancellationToken);
// pass message to handlers
foreach (var handler in _handlers) foreach (var handler in _handlers)
{ {
try try
@ -53,5 +57,31 @@ namespace Insight.Agent.Network
_logger.LogInformation("Agent ({ep?}) Heartbeat", RemoteEndPoint); _logger.LogInformation("Agent ({ep?}) Heartbeat", RemoteEndPoint);
return default; return default;
} }
private async ValueTask OnAuthenticationAsync(CancellationToken cancellationToken)
{
Config? config = null;
try
{
config = await Configurator.ReadAsync<Config>(Configuration.DefaultConfig, cancellationToken).ConfigureAwait(false);
}
catch (Exception ex)
{
_logger.LogError("Config ({config}) read error ({exception})", Configuration.DefaultConfig, ex);
}
if (config is null)
{
config = new Config { Serial = Guid.NewGuid() };
await Configurator.WriteAsync(config, Configuration.DefaultConfig, cancellationToken).ConfigureAwait(false);
}
await SendAsync(new AuthenticationResponse
{
Serial = config.Serial ?? throw new InvalidDataException(nameof(config.Serial)),
Version = Configuration.Version,
Hostname = Configuration.Hostname
}, cancellationToken).ConfigureAwait(false);
} }
} }

View file

@ -1,38 +0,0 @@
using Insight.Agent.Interfaces;
using Insight.Agent.Messages;
using Insight.Agent.Models;
using Insight.Agent.Services;
using Insight.Domain.Constants;
namespace Insight.Agent.Network.Handlers
{
public class AuthenticationHandler : IAgentMessageHandler<AgentSession>
{
public async ValueTask HandleAsync<TMessage>(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IAgentMessage
{
if (message is AuthenticationRequest)
{
Config? config = null;
try
{
config = await Configurator.ReadAsync<Config>(Configuration.DefaultConfig, cancellationToken).ConfigureAwait(false);
}
catch (Exception) { }
if (config is null)
{
config = new Config { Serial = Guid.NewGuid() };
await Configurator.WriteAsync(config, Configuration.DefaultConfig, cancellationToken).ConfigureAwait(false);
}
await sender.SendAsync(new Authentication
{
Serial = config.Serial ?? throw new InvalidDataException(nameof(config.Serial)),
Version = Configuration.Version,
Hostname = Configuration.Hostname
}, cancellationToken);
}
}
}
}

View file

@ -0,0 +1,33 @@
using Insight.Agent.Services;
using Insight.Domain.Interfaces;
using Insight.Domain.Network;
using Insight.Domain.Network.Agent.Messages;
namespace Insight.Agent.Network.Handlers;
public class CustomHandler(ScriptService scriptService) : IMessageHandler<AgentSession>
{
private readonly ScriptService _scriptService = scriptService;
public async ValueTask HandleAsync<TMessage>(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IMessage
{
switch (message)
{
case Request request:
await OnRequestAsync(sender, request, cancellationToken);
break;
}
}
private async ValueTask OnRequestAsync(AgentSession sender, Request request, CancellationToken cancellationToken)
{
if (request.RequestData is null) return;
var result = await _scriptService.QueryAsync(request.RequestData);
await sender.SendAsync(new Response(request)
{
ResponseData = result.HadErrors ? result.Errors : result.Data,
ResponseError = result.HadErrors
}, cancellationToken);
}
}

View file

@ -1,21 +1,26 @@
using Insight.Agent.Interfaces; using Insight.Domain.Interfaces;
using Insight.Agent.Messages; using Insight.Domain.Network;
using Insight.Domain.Network.Agent.Messages;
using System.Management; using System.Management;
using System.Runtime.Versioning; using System.Runtime.Versioning;
namespace Insight.Agent.Network.Handlers namespace Insight.Agent.Network.Handlers;
[SupportedOSPlatform("windows")]
public class DriveHandler : IMessageHandler<AgentSession>
{ {
[SupportedOSPlatform("windows")] public async ValueTask HandleAsync<TMessage>(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IMessage
public class DriveHandler : IAgentMessageHandler<AgentSession>
{ {
public async ValueTask HandleAsync<TMessage>(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IAgentMessage switch (message)
{ {
if (message is GetInventory) case InventoryRequest:
{ {
var result = new DriveList(); var result = new Collection<Drive>();
result.AddRange(GetDrives()); result.AddRange(GetDrives());
await sender.SendAsync(result, cancellationToken); await sender.SendAsync(result, cancellationToken);
break;
}
} }
} }
@ -54,7 +59,7 @@ namespace Insight.Agent.Network.Handlers
drive.InterfaceType = @object.GetValue<string>(properties, "interfacetype")?.Trim(); drive.InterfaceType = @object.GetValue<string>(properties, "interfacetype")?.Trim();
drive.FirmwareRevision = @object.GetValue<string>(properties, "firmwarerevision")?.Trim(); drive.FirmwareRevision = @object.GetValue<string>(properties, "firmwarerevision")?.Trim();
drive.PNPDeviceID = @object.GetValue<string>(properties, "pnpdeviceid")?.Trim(); drive.PNPDeviceID = @object.GetValue<string>(properties, "pnpdeviceid")?.Trim();
drive.Volumes = new List<Volume>(); drive.Volumes = [];
var diskpartition = @object.GetRelated("win32_diskpartition"); var diskpartition = @object.GetRelated("win32_diskpartition");
using (diskpartition) using (diskpartition)
@ -150,7 +155,7 @@ namespace Insight.Agent.Network.Handlers
{ {
using (collection2) using (collection2)
{ {
foreach (ManagementObject @object2 in collection2) foreach (ManagementObject @object2 in collection2.Cast<ManagementObject>())
{ {
var properties2 = @object2.GetPropertyHashes(); var properties2 = @object2.GetPropertyHashes();
@ -174,5 +179,4 @@ namespace Insight.Agent.Network.Handlers
return volumes; return volumes;
} }
}
} }

View file

@ -1,32 +1,36 @@
using Insight.Agent.Interfaces; using Insight.Domain.Interfaces;
using Insight.Agent.Messages; using Insight.Domain.Network;
using Insight.Domain.Network.Agent.Messages;
using System.Management; using System.Management;
using System.Net; using System.Net;
using System.Net.NetworkInformation; using System.Net.NetworkInformation;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Runtime.Versioning; using System.Runtime.Versioning;
using Route = Insight.Agent.Messages.Route;
namespace Insight.Agent.Network.Handlers namespace Insight.Agent.Network.Handlers;
[SupportedOSPlatform("windows")]
public class InterfaceHandler : IMessageHandler<AgentSession>
{ {
[SupportedOSPlatform("windows")] public async ValueTask HandleAsync<TMessage>(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IMessage
public class InterfaceHandler : IAgentMessageHandler<AgentSession>
{ {
public async ValueTask HandleAsync<TMessage>(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IAgentMessage switch (message)
{ {
if (message is GetInventory) case InventoryRequest:
{ {
var result = new InterfaceList(); var result = new Collection<Interface>();
result.AddRange(GetInterfaces()); if (GetInterfaces() is List<Interface> interfaces) result.AddRange(interfaces);
await sender.SendAsync(result, cancellationToken); await sender.SendAsync(result, cancellationToken);
break;
}
} }
} }
private static List<Interface> GetInterfaces() private static List<Interface>? GetInterfaces()
{ {
if (NetworkInterface.GetIsNetworkAvailable() is false) return null; if (NetworkInterface.GetIsNetworkAvailable() is false) return null;
if (NetworkInterface.GetAllNetworkInterfaces().Any() is false) return null; if (NetworkInterface.GetAllNetworkInterfaces().Length == 0) return null;
var interfaces = new List<Interface>(); var interfaces = new List<Interface>();
@ -95,7 +99,7 @@ namespace Insight.Agent.Network.Handlers
using (collection) using (collection)
{ {
foreach (ManagementObject @object in collection) foreach (ManagementObject @object in collection.Cast<ManagementObject>())
{ {
var properties = @object.GetPropertyHashes(); var properties = @object.GetPropertyHashes();
@ -181,7 +185,7 @@ namespace Insight.Agent.Network.Handlers
{ {
var addresses = new List<Unicast>(); var addresses = new List<Unicast>();
if (unicastCollection.Any() is false) return addresses; if (unicastCollection.Count == 0) return addresses;
foreach (var unicast in unicastCollection) foreach (var unicast in unicastCollection)
{ {
@ -206,7 +210,7 @@ namespace Insight.Agent.Network.Handlers
{ {
var addresses = new List<IPAddress2>(); var addresses = new List<IPAddress2>();
if (addressCollection.Any() is false) return addresses; if (addressCollection.Count == 0) return addresses;
foreach (var address in addressCollection) foreach (var address in addressCollection)
{ {
@ -220,7 +224,7 @@ namespace Insight.Agent.Network.Handlers
{ {
var addresses = new List<IPAddress2>(); var addresses = new List<IPAddress2>();
if (addressCollection.Any() is false) return addresses; if (addressCollection.Count == 0) return addresses;
foreach (var address in addressCollection) foreach (var address in addressCollection)
{ {
@ -270,5 +274,4 @@ namespace Insight.Agent.Network.Handlers
_ => null, _ => null,
}; };
} }
}
} }

View file

@ -1,22 +1,25 @@
using Insight.Agent.Interfaces; using Insight.Domain.Interfaces;
using Insight.Agent.Messages; using Insight.Domain.Network;
using Insight.Domain.Network.Agent.Messages;
using System.Management; using System.Management;
using System.Runtime.Versioning; using System.Runtime.Versioning;
namespace Insight.Agent.Network.Handlers namespace Insight.Agent.Network.Handlers;
[SupportedOSPlatform("windows")]
public class MainboardHandler : IMessageHandler<AgentSession>
{ {
[SupportedOSPlatform("windows")] public async ValueTask HandleAsync<TMessage>(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IMessage
public class MainboardHandler : IAgentMessageHandler<AgentSession>
{ {
public async ValueTask HandleAsync<TMessage>(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IAgentMessage switch (message)
{ {
if (message is GetInventory) case InventoryRequest:
{ if (GetMainboard() is Mainboard mainboard) await sender.SendAsync(mainboard, cancellationToken);
await sender.SendAsync(GetMainboard(), cancellationToken); break;
} }
} }
private static Mainboard GetMainboard() private static Mainboard? GetMainboard()
{ {
using var searcher = new ManagementObjectSearcher using var searcher = new ManagementObjectSearcher
{ {
@ -82,5 +85,4 @@ namespace Insight.Agent.Network.Handlers
return mainboard; return mainboard;
} }
}
} }

View file

@ -1,21 +1,26 @@
using Insight.Agent.Interfaces; using Insight.Domain.Interfaces;
using Insight.Agent.Messages; using Insight.Domain.Network;
using Insight.Domain.Network.Agent.Messages;
using System.Management; using System.Management;
using System.Runtime.Versioning; using System.Runtime.Versioning;
namespace Insight.Agent.Network.Handlers namespace Insight.Agent.Network.Handlers;
[SupportedOSPlatform("windows")]
public class MemoryHandler : IMessageHandler<AgentSession>
{ {
[SupportedOSPlatform("windows")] public async ValueTask HandleAsync<TMessage>(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IMessage
public class MemoryHandler : IAgentMessageHandler<AgentSession>
{ {
public async ValueTask HandleAsync<TMessage>(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IAgentMessage switch (message)
{ {
if (message is GetInventory) case InventoryRequest:
{ {
var result = new MemoryList(); var result = new Collection<Memory>();
result.AddRange(GetMemory()); result.AddRange(GetMemory());
await sender.SendAsync(result, cancellationToken); await sender.SendAsync(result, cancellationToken);
break;
}
} }
} }
@ -119,5 +124,4 @@ namespace Insight.Agent.Network.Handlers
// metric.MemoryAvailablePercentage = 100 - metric.MemoryUsagePercentage; // metric.MemoryAvailablePercentage = 100 - metric.MemoryUsagePercentage;
// return metric; // return metric;
//} //}
}
} }

View file

@ -1,21 +1,24 @@
using Insight.Agent.Interfaces; using Insight.Domain.Interfaces;
using Insight.Agent.Messages; using Insight.Domain.Network;
using Insight.Domain.Network.Agent.Messages;
using Microsoft.Win32; using Microsoft.Win32;
using System.Management; using System.Management;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Runtime.Versioning; using System.Runtime.Versioning;
using System.Security.AccessControl; using System.Security.AccessControl;
namespace Insight.Agent.Network.Handlers namespace Insight.Agent.Network.Handlers;
[SupportedOSPlatform("windows")]
public class OperationSystemHandler : IMessageHandler<AgentSession>
{ {
[SupportedOSPlatform("windows")] public async ValueTask HandleAsync<TMessage>(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IMessage
public class OperationSystemHandler : IAgentMessageHandler<AgentSession>
{ {
public async ValueTask HandleAsync<TMessage>(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IAgentMessage switch (message)
{
if (message is GetInventory)
{ {
case InventoryRequest:
await sender.SendAsync(GetOperatingSystem(), cancellationToken); await sender.SendAsync(GetOperatingSystem(), cancellationToken);
break;
} }
} }
@ -38,7 +41,7 @@ namespace Insight.Agent.Network.Handlers
using (collection) using (collection)
{ {
foreach (ManagementObject @object in collection) foreach (ManagementObject @object in collection.Cast<ManagementObject>())
{ {
var properties = @object.GetPropertyHashes(); var properties = @object.GetPropertyHashes();
@ -48,7 +51,8 @@ namespace Insight.Agent.Network.Handlers
if (@object.TryGetValue<string>(properties, "osarchitecture", out var architecture)) if (@object.TryGetValue<string>(properties, "osarchitecture", out var architecture))
{ {
if (architecture is not null && architecture.ToLower().Contains("64")) os.Architecture = Architecture.X64; if (architecture is not null && architecture.Contains("64", StringComparison.CurrentCultureIgnoreCase))
os.Architecture = Architecture.X64;
} }
else else
{ {
@ -87,5 +91,4 @@ namespace Insight.Agent.Network.Handlers
return os; return os;
} }
}
} }

View file

@ -1,21 +1,26 @@
using Insight.Agent.Interfaces; using Insight.Domain.Interfaces;
using Insight.Agent.Messages; using Insight.Domain.Network;
using Insight.Domain.Network.Agent.Messages;
using System.Management; using System.Management;
using System.Runtime.Versioning; using System.Runtime.Versioning;
namespace Insight.Agent.Network.Handlers namespace Insight.Agent.Network.Handlers;
[SupportedOSPlatform("windows")]
public class PrinterHandler : IMessageHandler<AgentSession>
{ {
[SupportedOSPlatform("windows")] public async ValueTask HandleAsync<TMessage>(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IMessage
public class PrinterHandler : IAgentMessageHandler<AgentSession>
{ {
public async ValueTask HandleAsync<TMessage>(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IAgentMessage switch (message)
{ {
if (message is GetInventory) case InventoryRequest:
{ {
var result = new PrinterList(); var result = new Collection<Printer>();
result.AddRange(GetPrinters()); result.AddRange(GetPrinters());
await sender.SendAsync(result, cancellationToken); await sender.SendAsync(result, cancellationToken);
break;
}
} }
} }
@ -56,5 +61,4 @@ namespace Insight.Agent.Network.Handlers
return printers; return printers;
} }
}
} }

View file

@ -1,21 +1,26 @@
using Insight.Agent.Interfaces; using Insight.Domain.Interfaces;
using Insight.Agent.Messages; using Insight.Domain.Network;
using Insight.Domain.Network.Agent.Messages;
using System.Management; using System.Management;
using System.Runtime.Versioning; using System.Runtime.Versioning;
namespace Insight.Agent.Network.Handlers namespace Insight.Agent.Network.Handlers;
[SupportedOSPlatform("windows")]
public class ProcessorHandler : IMessageHandler<AgentSession>
{ {
[SupportedOSPlatform("windows")] public async ValueTask HandleAsync<TMessage>(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IMessage
public class ProcessorHandler : IAgentMessageHandler<AgentSession>
{ {
public async ValueTask HandleAsync<TMessage>(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IAgentMessage switch (message)
{ {
if (message is GetInventory) case InventoryRequest:
{ {
var result = new ProcessorList(); var result = new Collection<Processor>();
result.AddRange(GetProcessors()); result.AddRange(GetProcessors());
await sender.SendAsync(result, cancellationToken); await sender.SendAsync(result, cancellationToken);
break;
}
} }
} }
@ -139,5 +144,4 @@ namespace Insight.Agent.Network.Handlers
// metric.ProcessorUsagePercentage = ProcessorTimeCounter?.NextValue(); // metric.ProcessorUsagePercentage = ProcessorTimeCounter?.NextValue();
// return metric; // return metric;
//} //}
}
} }

View file

@ -0,0 +1,37 @@
using Insight.Agent.Services;
using Insight.Domain.Interfaces;
using Insight.Domain.Network;
using Insight.Domain.Network.Agent.Messages;
namespace Insight.Agent.Network.Handlers;
public class ProxyHandler(ScriptService scriptService) : IMessageHandler<AgentSession>
{
private readonly ScriptService _scriptService = scriptService;
public async ValueTask HandleAsync<TMessage>(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IMessage
{
switch (message)
{
case Proxy<Request> proxyRequest:
await OnProxyRequestAsync(sender, proxyRequest, cancellationToken);
break;
}
}
private async ValueTask OnProxyRequestAsync(AgentSession sender, Proxy<Request> proxyRequest, CancellationToken cancellationToken)
{
if (proxyRequest.Message?.RequestData is null) return;
var result = await _scriptService.QueryAsync(proxyRequest.Message.RequestData);
await sender.SendAsync(new Proxy<Response>()
{
ProxyId = proxyRequest.ProxyId,
Message = new Response(proxyRequest.Message)
{
ResponseData = result.HadErrors ? result.Errors : result.Data,
ResponseError = result.HadErrors
}
}, cancellationToken);
}
}

View file

@ -1,22 +1,27 @@
using Insight.Agent.Interfaces; using Insight.Domain.Interfaces;
using Insight.Agent.Messages; using Insight.Domain.Network;
using Insight.Domain.Network.Agent.Messages;
using System.Management; using System.Management;
using System.Runtime.Versioning; using System.Runtime.Versioning;
using System.ServiceProcess; using System.ServiceProcess;
namespace Insight.Agent.Network.Handlers namespace Insight.Agent.Network.Handlers;
[SupportedOSPlatform("windows")]
public class ServiceHandler : IMessageHandler<AgentSession>
{ {
[SupportedOSPlatform("windows")] public async ValueTask HandleAsync<TMessage>(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IMessage
public class ServiceHandler : IAgentMessageHandler<AgentSession>
{ {
public async ValueTask HandleAsync<TMessage>(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IAgentMessage switch (message)
{ {
if (message is GetInventory) case InventoryRequest:
{ {
var result = new ServiceList(); var result = new Collection<Service>();
result.AddRange(GetServices()); result.AddRange(GetServices());
await sender.SendAsync(result, cancellationToken); await sender.SendAsync(result, cancellationToken);
break;
}
} }
} }
@ -25,7 +30,7 @@ namespace Insight.Agent.Network.Handlers
var services = new List<Service>(); var services = new List<Service>();
var serviceControllers = ServiceController.GetServices()?.OrderBy(s => s.DisplayName)?.ToList(); var serviceControllers = ServiceController.GetServices()?.OrderBy(s => s.DisplayName)?.ToList();
if (serviceControllers is null || serviceControllers.Any() is false) throw new InvalidOperationException("SERVICE Collection NULL"); if (serviceControllers is null || serviceControllers.Count == 0) throw new InvalidOperationException("SERVICE Collection NULL");
foreach (var sc in serviceControllers) foreach (var sc in serviceControllers)
{ {
@ -97,7 +102,7 @@ namespace Insight.Agent.Network.Handlers
} }
} }
if (services2.Any() is false) return services; if (services2.Count == 0) return services;
foreach (var svc in services) foreach (var svc in services)
{ {
@ -112,7 +117,6 @@ namespace Insight.Agent.Network.Handlers
svc.Delay = map.Delay; svc.Delay = map.Delay;
} }
return services.OrderBy(x => x.Name).ToList(); return [.. services.OrderBy(x => x.Name)];
}
} }
} }

View file

@ -1,28 +1,31 @@
using Insight.Agent.Interfaces; using Insight.Domain.Interfaces;
using Insight.Agent.Messages; using Insight.Domain.Network;
using Insight.Domain.Network.Agent.Messages;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Runtime.Versioning; using System.Runtime.Versioning;
namespace Insight.Agent.Network.Handlers namespace Insight.Agent.Network.Handlers;
[SupportedOSPlatform("windows")]
public class SessionHandler : IMessageHandler<AgentSession>
{ {
[SupportedOSPlatform("windows")] public async ValueTask HandleAsync<TMessage>(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IMessage
public class SessionHandler : IAgentMessageHandler<AgentSession>
{ {
public async ValueTask HandleAsync<TMessage>(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IAgentMessage switch (message)
{ {
if (message is GetInventory) case InventoryRequest:
{ {
var result = new SessionList(); var result = new Collection<Session>();
result.AddRange(GetSessions()); result.AddRange(GetSessions());
await sender.SendAsync(result, cancellationToken); await sender.SendAsync(result, cancellationToken);
break;
}
} }
} }
private static List<Session> GetSessions() private static List<Session> GetSessions()
{ {
var query = NativeMethods.GetSessions();
var sessions = new List<Session>(); var sessions = new List<Session>();
foreach (var s in NativeMethods.GetSessions()) foreach (var s in NativeMethods.GetSessions())
@ -45,7 +48,7 @@ namespace Insight.Agent.Network.Handlers
//public const int WTS_CURRENT_SESSION = -1; //public const int WTS_CURRENT_SESSION = -1;
[DllImport("wtsapi32.dll")] [DllImport("wtsapi32.dll")]
static extern int WTSEnumerateSessions( private static extern int WTSEnumerateSessions(
nint pServer, nint pServer,
[MarshalAs(UnmanagedType.U4)] int iReserved, [MarshalAs(UnmanagedType.U4)] int iReserved,
[MarshalAs(UnmanagedType.U4)] int iVersion, [MarshalAs(UnmanagedType.U4)] int iVersion,
@ -61,7 +64,7 @@ namespace Insight.Agent.Network.Handlers
out uint iBytesReturned); out uint iBytesReturned);
[DllImport("wtsapi32.dll")] [DllImport("wtsapi32.dll")]
static extern void WTSFreeMemory( private static extern void WTSFreeMemory(
nint pMemory); nint pMemory);
[StructLayout(LayoutKind.Sequential)] [StructLayout(LayoutKind.Sequential)]
@ -248,5 +251,4 @@ namespace Insight.Agent.Network.Handlers
return sessions; return sessions;
} }
} }
}
} }

View file

@ -1,30 +1,35 @@
using Insight.Agent.Interfaces; using Insight.Domain.Interfaces;
using Insight.Agent.Messages; using Insight.Domain.Network;
using Insight.Domain.Network.Agent.Messages;
using Microsoft.Win32; using Microsoft.Win32;
using System.Globalization; using System.Globalization;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Runtime.Versioning; using System.Runtime.Versioning;
using System.Security.AccessControl; using System.Security.AccessControl;
namespace Insight.Agent.Network.Handlers namespace Insight.Agent.Network.Handlers;
[SupportedOSPlatform("windows")]
internal class SoftwareHandler : IMessageHandler<AgentSession>
{ {
[SupportedOSPlatform("windows")] public async ValueTask HandleAsync<TMessage>(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IMessage
internal class SoftwareHandler : IAgentMessageHandler<AgentSession>
{ {
public async ValueTask HandleAsync<TMessage>(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IAgentMessage switch (message)
{ {
if (message is GetInventory) case InventoryRequest:
{ {
var x64 = Task.Run(() => ApplicationRegistryQuery(RegistryView.Registry64), cancellationToken); var x64 = Task.Run(() => ApplicationRegistryQuery(RegistryView.Registry64), cancellationToken);
var x86 = Task.Run(() => ApplicationRegistryQuery(RegistryView.Registry32), cancellationToken); var x86 = Task.Run(() => ApplicationRegistryQuery(RegistryView.Registry32), cancellationToken);
await Task.WhenAll(x64, x86).ConfigureAwait(false); await Task.WhenAll(x64, x86).ConfigureAwait(false);
var result = new ApplicationList(); var result = new Collection<Application>();
result.AddRange(x64.Result); result.AddRange(x64.Result);
result.AddRange(x86.Result.Where(p => result.All(app => p.Name != app.Name && p.Version != app.Version))); result.AddRange(x86.Result.Where(p => result.All(app => p.Name != app.Name && p.Version != app.Version)));
await sender.SendAsync(result, cancellationToken); await sender.SendAsync(result, cancellationToken);
break;
}
} }
} }
@ -115,5 +120,4 @@ namespace Insight.Agent.Network.Handlers
return apps; return apps;
} }
}
} }

View file

@ -1,24 +1,29 @@
using Insight.Agent.Interfaces; using Insight.Domain.Interfaces;
using Insight.Agent.Messages; using Insight.Domain.Network;
using Insight.Domain.Network.Agent.Messages;
using System.Management; using System.Management;
using System.Runtime.Versioning; using System.Runtime.Versioning;
using static Insight.Agent.Messages.PhysicalDisk; using static Insight.Domain.Network.Agent.Messages.PhysicalDisk;
using static Insight.Agent.Messages.StoragePool; using static Insight.Domain.Network.Agent.Messages.StoragePool;
using static Insight.Agent.Messages.VirtualDisk; using static Insight.Domain.Network.Agent.Messages.VirtualDisk;
namespace Insight.Agent.Network.Handlers namespace Insight.Agent.Network.Handlers;
[SupportedOSPlatform("windows")]
public class StoragePoolHandler : IMessageHandler<AgentSession>
{ {
[SupportedOSPlatform("windows")] public async ValueTask HandleAsync<TMessage>(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IMessage
public class StoragePoolHandler : IAgentMessageHandler<AgentSession>
{ {
public async ValueTask HandleAsync<TMessage>(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IAgentMessage switch (message)
{ {
if (message is GetInventory) case InventoryRequest:
{ {
var result = new StoragePoolList(); var result = new Collection<StoragePool>();
result.AddRange(GetStoragePool()); result.AddRange(GetStoragePool());
await sender.SendAsync(result, cancellationToken); await sender.SendAsync(result, cancellationToken);
break;
}
} }
} }
@ -84,121 +89,6 @@ namespace Insight.Agent.Network.Handlers
return pools; return pools;
} }
private static List<PhysicalDisk> GetPhysicalDisks()
{
using var searcher = new ManagementObjectSearcher
{
Scope = new ManagementScope(@"root\microsoft\windows\storage"),
Query = new ObjectQuery("select objectid, uniqueid, name, friendlyname from msft_physicaldisk")
};
if (searcher.TryGet(out var collection) is false)
{
searcher.Query = new ObjectQuery("select * from msft_physicaldisk");
if (searcher.TryGet(out collection) is false) throw new InvalidOperationException("WMI Collection NULL");
}
var disks = new List<PhysicalDisk>();
using (collection)
{
foreach (ManagementObject @object in collection.Cast<ManagementObject>())
{
var disk = new PhysicalDisk();
var properties = @object.GetPropertyHashes();
disk.UniqueId = @object.GetValue<string>(properties, "uniqueid")?.Trim();
disk.FriendlyName = @object.GetValue<string>(properties, "friendlyname")?.Trim();
disk.Manufacturer = @object.GetValue<string>(properties, "manufacturer")?.Trim();
disk.Model = @object.GetValue<string>(properties, "model")?.Trim();
disk.MediaType = @object.GetValue<ushort>(properties, "mediatype");
disk.BusType = @object.GetValue<ushort>(properties, "bustype");
if (@object.TryGetValue<ushort[]>(properties, "operationalstatus", out var operationals) && operationals is not null)
{
disk.States = operationals.Select(p => (PhysicalDisk.OperationalState)p).ToList();
}
disk.Health = (PhysicalDisk.HealthState)@object.GetValue<ushort>(properties, "healthstatus");
if (@object.TryGetValue<ushort[]>(properties, "supportedusages", out var supportedusages) && supportedusages is not null)
{
disk.SupportedUsages = supportedusages.Select(p => (SupportedUsagesEnum)p).ToList();
}
disk.Usage = @object.GetValue<ushort>(properties, "usage");
disk.PhysicalLocation = @object.GetValue<string>(properties, "physicallocation")?.Trim();
disk.SerialNumber = @object.GetValue<string>(properties, "serialnumber")?.Trim();
disk.FirmwareVersion = @object.GetValue<string>(properties, "firmwareversion")?.Trim();
disk.Size = @object.GetValue<ulong>(properties, "size");
disk.AllocatedSize = @object.GetValue<ulong>(properties, "allocatedsize");
disk.LogicalSectorSize = @object.GetValue<ulong>(properties, "logicalsectorsize");
disk.PhysicalSectorSize = @object.GetValue<ulong>(properties, "physicalsectorsize");
disk.VirtualDiskFootprint = @object.GetValue<ulong>(properties, "virtualdiskfootprint");
disks.Add(disk);
}
}
return disks;
}
private static List<VirtualDisk> GetVirtualDisks()
{
using var searcher = new ManagementObjectSearcher
{
Scope = new ManagementScope(@"root\microsoft\windows\storage"),
Query = new ObjectQuery("select objectid, uniqueid, name, friendlyname, access, provisioningtype, physicaldiskredundancy, resiliencysettingname, isdeduplicationenabled, issnapshot, operationalstatus, healthstatus, size, allocatedsize, footprintonpool, readcachesize, writecachesize from msft_virtualdisk")
};
if (searcher.TryGet(out var collection) is false)
{
searcher.Query = new ObjectQuery("select * from msft_virtualdisk");
if (searcher.TryGet(out collection) is false) throw new InvalidOperationException("WMI Collection NULL");
}
var disks = new List<VirtualDisk>();
using (collection)
{
foreach (ManagementObject @object in collection.Cast<ManagementObject>())
{
var disk = new VirtualDisk();
var properties = @object.GetPropertyHashes();
disk.UniqueId = @object.GetValue<string>(properties, "uniqueid")?.Trim();
disk.Name = @object.GetValue<string>(properties, "name")?.Trim();
disk.FriendlyName = @object.GetValue<string>(properties, "friendlyname")?.Trim();
disk.AccessType = (AccessTypeEnum)@object.GetValue<ushort>(properties, "access");
disk.ProvisioningType = (ProvisioningTypeEnum)@object.GetValue<ushort>(properties, "provisioningtype");
disk.PhysicalDiskRedundancy = @object.GetValue<ushort>(properties, "physicaldiskredundancy");
disk.ResiliencySettingName = @object.GetValue<string>(properties, "resiliencysettingname")?.Trim();
disk.Deduplication = @object.GetValue<bool>(properties, "isdeduplicationenabled");
disk.IsSnapshot = @object.GetValue<bool>(properties, "issnapshot");
if (@object.TryGetValue<ushort[]>(properties, "operationalstatus", out var operationals) && operationals is not null)
{
disk.States = operationals.Select(p => (VirtualDisk.OperationalState)p).ToList();
}
disk.Health = (VirtualDisk.HealthState)@object.GetValue<ushort>(properties, "healthstatus");
disk.Size = @object.GetValue<ulong>(properties, "size");
disk.AllocatedSize = @object.GetValue<ulong>(properties, "allocatedsize");
disk.FootprintOnPool = @object.GetValue<ulong>(properties, "footprintonpool");
disk.ReadCacheSize = @object.GetValue<ulong>(properties, "readcachesize");
disk.WriteCacheSize = @object.GetValue<ulong>(properties, "writecachesize");
disks.Add(disk);
}
}
return disks;
}
private static List<PhysicalDisk> QueryPhysicalDisksByStoragePool(string storagePoolObjectId) private static List<PhysicalDisk> QueryPhysicalDisksByStoragePool(string storagePoolObjectId)
{ {
using var searcher = new ManagementObjectSearcher using var searcher = new ManagementObjectSearcher
@ -213,7 +103,7 @@ namespace Insight.Agent.Network.Handlers
using (collection) using (collection)
{ {
foreach (ManagementObject @object in collection) foreach (ManagementObject @object in collection.Cast<ManagementObject>())
{ {
var disk = new PhysicalDisk(); var disk = new PhysicalDisk();
@ -270,7 +160,7 @@ namespace Insight.Agent.Network.Handlers
using (collection) using (collection)
{ {
foreach (ManagementObject @object in collection) foreach (ManagementObject @object in collection.Cast<ManagementObject>())
{ {
var disk = new VirtualDisk(); var disk = new VirtualDisk();
@ -304,5 +194,4 @@ namespace Insight.Agent.Network.Handlers
return disks; return disks;
} }
}
} }

View file

@ -1,20 +1,23 @@
using Insight.Agent.Interfaces; using Insight.Domain.Interfaces;
using Insight.Agent.Messages; using Insight.Domain.Network;
using Insight.Domain.Network.Agent.Messages;
using Microsoft.Win32; using Microsoft.Win32;
using System.Collections; using System.Collections;
using System.Management; using System.Management;
using System.Runtime.Versioning; using System.Runtime.Versioning;
namespace Insight.Agent.Network.Handlers namespace Insight.Agent.Network.Handlers;
[SupportedOSPlatform("windows")]
public class SystemInfoHandler : IMessageHandler<AgentSession>
{ {
[SupportedOSPlatform("windows")] public async ValueTask HandleAsync<TMessage>(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IMessage
public class SystemInfoHandler : IAgentMessageHandler<AgentSession>
{ {
public async ValueTask HandleAsync<TMessage>(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IAgentMessage switch (message)
{
if (message is GetInventory)
{ {
case InventoryRequest:
await sender.SendAsync(GetSystem(), cancellationToken); await sender.SendAsync(GetSystem(), cancellationToken);
break;
} }
} }
@ -84,7 +87,6 @@ namespace Insight.Agent.Network.Handlers
private static string GetWindowsProductKeyFromDigitalProductId(byte[] digitalProductId, DigitalProductIdVersion digitalProductIdVersion) private static string GetWindowsProductKeyFromDigitalProductId(byte[] digitalProductId, DigitalProductIdVersion digitalProductIdVersion)
{ {
var productKey = digitalProductIdVersion == DigitalProductIdVersion.Windows8AndUp var productKey = digitalProductIdVersion == DigitalProductIdVersion.Windows8AndUp
? DecodeProductKeyWin8AndUp(digitalProductId) ? DecodeProductKeyWin8AndUp(digitalProductId)
: DecodeProductKey(digitalProductId); : DecodeProductKey(digitalProductId);
@ -121,7 +123,7 @@ namespace Insight.Agent.Network.Handlers
var digitMapIndex = 0; var digitMapIndex = 0;
for (var j = decodeStringLength - 1; j >= 0; j--) for (var j = decodeStringLength - 1; j >= 0; j--)
{ {
var byteValue = digitMapIndex << 8 | (byte)hexPid[j]; var byteValue = digitMapIndex << 8 | (byte)hexPid[j]!;
hexPid[j] = (byte)(byteValue / 24); hexPid[j] = (byte)(byteValue / 24);
digitMapIndex = byteValue % 24; digitMapIndex = byteValue % 24;
decodedChars[i] = digits[digitMapIndex]; decodedChars[i] = digits[digitMapIndex];
@ -145,17 +147,17 @@ namespace Insight.Agent.Network.Handlers
var current = 0; var current = 0;
for (var j = 14; j >= 0; j--) for (var j = 14; j >= 0; j--)
{ {
current = current * 256; current *= 256;
current = digitalProductId[j + keyOffset] + current; current = digitalProductId[j + keyOffset] + current;
digitalProductId[j + keyOffset] = (byte)(current / 24); digitalProductId[j + keyOffset] = (byte)(current / 24);
current = current % 24; current %= 24;
last = current; last = current;
} }
key = digits[current] + key; key = digits[current] + key;
} }
var keypart1 = key.Substring(1, last); var keypart1 = key.Substring(1, last);
var keypart2 = key.Substring(last + 1, key.Length - (last + 1)); var keypart2 = key[(last + 1)..];
key = keypart1 + "N" + keypart2; key = keypart1 + "N" + keypart2;
for (var i = 5; i < key.Length; i += 6) for (var i = 5; i < key.Length; i += 6)
@ -171,5 +173,4 @@ namespace Insight.Agent.Network.Handlers
UpToWindows7, UpToWindows7,
Windows8AndUp Windows8AndUp
} }
}
} }

View file

@ -1,30 +1,29 @@
using Insight.Agent.Interfaces; using Insight.Domain.Interfaces;
using Insight.Agent.Messages; using Insight.Domain.Network;
using Insight.Domain.Network.Agent.Messages;
using System.Runtime.Versioning; using System.Runtime.Versioning;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using WUApiLib; using WUApiLib;
using static Insight.Agent.Messages.Update; using static Insight.Domain.Network.Agent.Messages.Update;
using UpdateCollection = Insight.Domain.Network.Agent.Messages.UpdateCollection;
namespace Insight.Agent.Network.Handlers namespace Insight.Agent.Network.Handlers;
[SupportedOSPlatform("windows")]
public partial class UpdateHandler : IMessageHandler<AgentSession>
{ {
[SupportedOSPlatform("windows")] public async ValueTask HandleAsync<TMessage>(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IMessage
public class UpdateHandler : IAgentMessageHandler<AgentSession>
{ {
public async ValueTask HandleAsync<TMessage>(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IAgentMessage switch (message)
{ {
if (message is GetInventory) case InventoryRequest:
{ await sender.SendAsync(new UpdateCollection
await sender.SendAsync(GetUpdates(), cancellationToken);
}
}
private static UpdateList GetUpdates()
{
return new UpdateList
{ {
Installed = QueryInstalledUpdates(), Installed = QueryInstalledUpdates(),
Pending = QueryPendingUpdates() Pending = QueryPendingUpdates()
}; }, cancellationToken);
break;
}
} }
private static List<Update> QueryInstalledUpdates() private static List<Update> QueryInstalledUpdates()
@ -61,7 +60,7 @@ namespace Insight.Agent.Network.Handlers
try try
{ {
var rx = new Regex(@"KB(\d+)"); var rx = KnowledgeBaseRegex();
update.Hotfix = rx.Match(wupdate.Title).Value; update.Hotfix = rx.Match(wupdate.Title).Value;
} }
catch (Exception) catch (Exception)
@ -126,5 +125,7 @@ namespace Insight.Agent.Network.Handlers
return updates; return updates;
} }
}
[GeneratedRegex(@"KB(\d+)")]
private static partial Regex KnowledgeBaseRegex();
} }

View file

@ -1,21 +1,26 @@
using Insight.Agent.Interfaces; using Insight.Domain.Interfaces;
using Insight.Agent.Messages; using Insight.Domain.Network;
using Insight.Domain.Network.Agent.Messages;
using System.Management; using System.Management;
using System.Runtime.Versioning; using System.Runtime.Versioning;
namespace Insight.Agent.Network.Handlers namespace Insight.Agent.Network.Handlers;
[SupportedOSPlatform("windows")]
public class UserHandler : IMessageHandler<AgentSession>
{ {
[SupportedOSPlatform("windows")] public async ValueTask HandleAsync<TMessage>(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IMessage
public class UserHandler : IAgentMessageHandler<AgentSession>
{ {
public async ValueTask HandleAsync<TMessage>(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IAgentMessage switch (message)
{ {
if (message is GetInventory) case InventoryRequest:
{ {
var result = new UserList(); var result = new Collection<User>();
result.AddRange(GetUsers()); result.AddRange(GetUsers());
await sender.SendAsync(result, cancellationToken); await sender.SendAsync(result, cancellationToken);
break;
}
} }
} }
@ -27,7 +32,7 @@ namespace Insight.Agent.Network.Handlers
foreach (var u in users) foreach (var u in users)
{ {
u.Groups = new List<Group>(); u.Groups = [];
foreach (var ug in usergrouping.Where(ug => ug.UserDomain == u.Domain && ug.UserName == u.Name)) foreach (var ug in usergrouping.Where(ug => ug.UserDomain == u.Domain && ug.UserName == u.Name))
{ {
@ -62,7 +67,7 @@ namespace Insight.Agent.Network.Handlers
using (collection) using (collection)
{ {
foreach (ManagementObject @object in collection) foreach (ManagementObject @object in collection.Cast<ManagementObject>())
{ {
var group = new Group(); var group = new Group();
@ -78,7 +83,7 @@ namespace Insight.Agent.Network.Handlers
} }
} }
return groups.OrderBy(x => x.Name)?.ToList(); return [.. groups.OrderBy(x => x.Name)];
} }
private static List<User> QueryUsers() private static List<User> QueryUsers()
@ -100,7 +105,7 @@ namespace Insight.Agent.Network.Handlers
using (collection) using (collection)
{ {
foreach (ManagementObject @object in collection) foreach (ManagementObject @object in collection.Cast<ManagementObject>())
{ {
var user = new User(); var user = new User();
@ -145,7 +150,7 @@ namespace Insight.Agent.Network.Handlers
using (collection) using (collection)
{ {
foreach (ManagementObject @object in collection) foreach (ManagementObject @object in collection.Cast<ManagementObject>())
{ {
var usergroup = new UserGroupMap(); var usergroup = new UserGroupMap();
@ -184,5 +189,4 @@ namespace Insight.Agent.Network.Handlers
public string? UserDomain { get; set; } public string? UserDomain { get; set; }
public string? UserName { get; set; } public string? UserName { get; set; }
} }
}
} }

View file

@ -1,21 +1,26 @@
using Insight.Agent.Interfaces; using Insight.Domain.Interfaces;
using Insight.Agent.Messages; using Insight.Domain.Network;
using Insight.Domain.Network.Agent.Messages;
using System.Management; using System.Management;
using System.Runtime.Versioning; using System.Runtime.Versioning;
namespace Insight.Agent.Network.Handlers namespace Insight.Agent.Network.Handlers;
[SupportedOSPlatform("windows")]
public class VideocardHandler : IMessageHandler<AgentSession>
{ {
[SupportedOSPlatform("windows")] public async ValueTask HandleAsync<TMessage>(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IMessage
public class VideocardHandler : IAgentMessageHandler<AgentSession>
{ {
public async ValueTask HandleAsync<TMessage>(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IAgentMessage switch (message)
{ {
if (message is GetInventory) case InventoryRequest:
{ {
var result = new VideocardList(); var result = new Collection<Videocard>();
result.AddRange(GetVideocards()); result.AddRange(GetVideocards());
await sender.SendAsync(result, cancellationToken); await sender.SendAsync(result, cancellationToken);
break;
}
} }
} }
@ -60,5 +65,4 @@ namespace Insight.Agent.Network.Handlers
return videocards; return videocards;
} }
}
} }

View file

@ -1,23 +1,28 @@
using Insight.Agent.Interfaces; using Insight.Domain.Interfaces;
using Insight.Agent.Messages; using Insight.Domain.Network;
using Insight.Domain.Network.Agent.Messages;
using System.Management; using System.Management;
using System.Runtime.Versioning; using System.Runtime.Versioning;
using static Insight.Agent.Messages.VirtualMaschine; using static Insight.Domain.Network.Agent.Messages.VirtualMaschine;
using static Insight.Agent.Messages.VirtualMaschineConfiguration; using static Insight.Domain.Network.Agent.Messages.VirtualMaschineConfiguration;
namespace Insight.Agent.Network.Handlers namespace Insight.Agent.Network.Handlers;
[SupportedOSPlatform("windows")]
public class VirtualMaschineHandler : IMessageHandler<AgentSession>
{ {
[SupportedOSPlatform("windows")] public async ValueTask HandleAsync<TMessage>(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IMessage
public class VirtualMaschineHandler : IAgentMessageHandler<AgentSession>
{ {
public async ValueTask HandleAsync<TMessage>(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IAgentMessage switch (message)
{ {
if (message is GetInventory) case InventoryRequest:
{ {
var result = new VirtualMaschineList(); var result = new Collection<VirtualMaschine>();
result.AddRange(GetVirtualMaschines()); result.AddRange(GetVirtualMaschines());
await sender.SendAsync(result, cancellationToken); await sender.SendAsync(result, cancellationToken);
break;
}
} }
} }
@ -336,7 +341,7 @@ namespace Insight.Agent.Network.Handlers
{ {
conf.ParentId = parentGuid.ToString(); conf.ParentId = parentGuid.ToString();
parentConfig.Childs ??= new List<VirtualMaschineConfiguration>(); parentConfig.Childs ??= [];
parentConfig.Childs.Add(conf); parentConfig.Childs.Add(conf);
} }
else else
@ -355,5 +360,4 @@ namespace Insight.Agent.Network.Handlers
return vms; return vms;
} }
}
} }

View file

@ -1,21 +1,23 @@
using Insight.Agent.Extensions; using Insight.Agent.Extensions;
using Insight.Agent.Interfaces;
using Insight.Agent.Messages;
using Insight.Agent.Network; using Insight.Agent.Network;
using Insight.Agent.Network.Handlers; using Insight.Agent.Network.Handlers;
using Insight.Agent.Services; using Insight.Agent.Services;
using Insight.Domain.Constants; using Insight.Domain.Constants;
using Insight.Domain.Extensions;
using Insight.Domain.Interfaces;
using Insight.Domain.Network;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using System.Diagnostics;
using Vaitr.Network; using Vaitr.Network;
using Vaitr.Network.Hosting; using Vaitr.Network.Hosting;
namespace Insight.Agent.Windows namespace Insight.Agent.Windows;
internal class Program
{ {
internal class Program
{
public static async Task Main(string[] args) public static async Task Main(string[] args)
{ {
var builder = Host.CreateDefaultBuilder(args); var builder = Host.CreateDefaultBuilder(args);
@ -38,49 +40,37 @@ namespace Insight.Agent.Windows
options.SingleLine = true; options.SingleLine = true;
options.TimestampFormat = "yyyy-MM-dd HH:mm:ss.fff "; options.TimestampFormat = "yyyy-MM-dd HH:mm:ss.fff ";
}); });
options.AddFile(Configuration.AppDirectory?.FullName + "/logs/" + Process.GetCurrentProcess().ProcessName + "_{Date}.log", LogLevel.Trace, fileSizeLimitBytes: 104857600, retainedFileCountLimit: 10, outputTemplate: "{Timestamp:o} [{Level:u3}] {Message} {NewLine}{Exception}");
options.AddFile($"{Configuration.AppDirectory?.FullName}/" + "logs/agent_{Date}.log", LogLevel.Trace, fileSizeLimitBytes: 104857600, retainedFileCountLimit: 10, outputTemplate: "{Timestamp:o} [{Level:u3}] {Message} {NewLine}{Exception}");
}); });
builder.ConfigureServices((host, services) => builder.ConfigureServices((host, services) =>
{ {
// SERVICES // HOST-SERVICES
services.AddHostedService<UpdateService>(); services.AddHostedService<UpdateService>();
services.AddHostedService<TrapService>(); services.AddHostedService<TrapService>();
// SERVICES (WINDOWS) // SERVICES (WINDOWS)
if (OperatingSystem.IsWindows()) services.AddHostedService<EventService>(); if (OperatingSystem.IsWindows()) services.AddHostedService<EventService>();
if (OperatingSystem.IsWindows()) services.AddSingleton<ScriptService>();
// AGENT NETWORKING // AGENT NETWORKING
services.UseHostedClient<AgentSession, IAgentMessage>(options => services.UseHostedClient<AgentSession, IMessage>(options =>
{ {
options.Host = host.Configuration.GetValue<string?>(Appsettings.ServerHost) ?? throw new Exception($"{Appsettings.ServerHost} value not set (appsettings)"); options.Host = host.Configuration.GetValue<string?>(Appsettings.ServerHost) ?? throw new Exception($"{Appsettings.ServerHost} value not set (appsettings)");
options.Port = host.Configuration.GetValue<int?>(Appsettings.ServerPort) ?? throw new Exception($"{Appsettings.ServerPort} value not set (appsettings)"); options.Port = host.Configuration.GetValue<int?>(Appsettings.ServerPort) ?? throw new Exception($"{Appsettings.ServerPort} value not set (appsettings)");
options.Keepalive = 10000; options.Keepalive = 10000;
options.Timeout = 30000; options.Timeout = 30000;
options.Compression = true;
options.Encryption = Encryption.Tls12; options.Encryption = Encryption.Tls12;
options.UseSerializer<MemPackSerializer<IAgentMessage>, IAgentMessage>(); options.UseSerializer<AgentSession, IMessage, MemPackSerializer<IMessage>>();
}); });
services.AddSingleton<IAgentMessageHandler<AgentSession>, AuthenticationHandler>(); services.AddSingleton<IMessageHandler<AgentSession>, ProxyHandler>();
services.AddSingleton<IAgentMessageHandler<AgentSession>, DriveHandler>(); services.AddSingleton<IMessageHandler<AgentSession>, CustomHandler>();
services.AddSingleton<IAgentMessageHandler<AgentSession>, InterfaceHandler>();
services.AddSingleton<IAgentMessageHandler<AgentSession>, MainboardHandler>(); if (OperatingSystem.IsWindows()) ServiceExtensions.InjectWindowsHandler(services);
services.AddSingleton<IAgentMessageHandler<AgentSession>, MemoryHandler>();
services.AddSingleton<IAgentMessageHandler<AgentSession>, OperationSystemHandler>();
services.AddSingleton<IAgentMessageHandler<AgentSession>, PrinterHandler>();
services.AddSingleton<IAgentMessageHandler<AgentSession>, ProcessorHandler>();
services.AddSingleton<IAgentMessageHandler<AgentSession>, ServiceHandler>();
services.AddSingleton<IAgentMessageHandler<AgentSession>, SessionHandler>();
services.AddSingleton<IAgentMessageHandler<AgentSession>, SoftwareHandler>();
services.AddSingleton<IAgentMessageHandler<AgentSession>, StoragePoolHandler>();
services.AddSingleton<IAgentMessageHandler<AgentSession>, SystemInfoHandler>();
services.AddSingleton<IAgentMessageHandler<AgentSession>, UpdateHandler>();
services.AddSingleton<IAgentMessageHandler<AgentSession>, UserHandler>();
services.AddSingleton<IAgentMessageHandler<AgentSession>, VideocardHandler>();
services.AddSingleton<IAgentMessageHandler<AgentSession>, VirtualMaschineHandler>();
services.AddSingleton<IAgentMessageHandler<AgentSession>, ConsoleHandler>();
// GLOBAL DEPENDENCIES // GLOBAL DEPENDENCIES
services.AddTransient(provider => new HttpClient(new HttpClientHandler services.AddTransient(provider => new HttpClient(new HttpClientHandler
@ -93,5 +83,4 @@ namespace Insight.Agent.Windows
var host = builder.Build(); var host = builder.Build();
await host.RunAsync().ConfigureAwait(false); await host.RunAsync().ConfigureAwait(false);
} }
}
} }

View file

@ -2,16 +2,10 @@
using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Logging.Abstractions;
using System.Runtime.Versioning; using System.Runtime.Versioning;
namespace Insight.Agent.Services namespace Insight.Agent.Services;
{
[SupportedOSPlatform("linux")]
public partial class CollectorService
{
public ILogger<CollectorService> Logger { get; }
public CollectorService(ILogger<CollectorService>? logger = null) [SupportedOSPlatform("linux")]
{ public partial class CollectorService(ILogger<CollectorService>? logger = null)
Logger = logger ?? NullLogger<CollectorService>.Instance; {
} public ILogger<CollectorService> Logger { get; } = logger ?? NullLogger<CollectorService>.Instance;
}
} }

View file

@ -1,15 +1,17 @@
using System.Text.Json; using System.Text.Json;
namespace Insight.Agent.Services namespace Insight.Agent.Services;
public static class Configurator
{ {
public static class Configurator private static readonly JsonSerializerOptions _serializerOptions = new() { PropertyNameCaseInsensitive = true, WriteIndented = true };
{
public static async ValueTask<TConfig> ReadAsync<TConfig>(string file, CancellationToken cancellationToken = default) public static async ValueTask<TConfig> ReadAsync<TConfig>(string file, CancellationToken cancellationToken = default)
where TConfig : class where TConfig : class
{ {
var json = await File.ReadAllTextAsync(file, cancellationToken); var json = await File.ReadAllTextAsync(file, cancellationToken);
if (JsonSerializer.Deserialize<TConfig>(json, new JsonSerializerOptions { PropertyNameCaseInsensitive = true, WriteIndented = true }) is not TConfig config) if (JsonSerializer.Deserialize<TConfig>(json, _serializerOptions) is not TConfig config)
{ {
throw new InvalidDataException($"Failed to deserialize ({file})"); throw new InvalidDataException($"Failed to deserialize ({file})");
} }
@ -31,7 +33,7 @@ namespace Insight.Agent.Services
{ {
var json = await File.ReadAllTextAsync(file, cancellationToken); var json = await File.ReadAllTextAsync(file, cancellationToken);
if (JsonSerializer.Deserialize<IDictionary<string, object>>(json, new JsonSerializerOptions { PropertyNameCaseInsensitive = true, WriteIndented = true }) is not IDictionary<string, object> config) if (JsonSerializer.Deserialize<IDictionary<string, object>>(json, _serializerOptions) is not IDictionary<string, object> config)
{ {
throw new InvalidDataException($"Failed to deserialize ({file})"); throw new InvalidDataException($"Failed to deserialize ({file})");
} }
@ -89,9 +91,8 @@ namespace Insight.Agent.Services
private static async ValueTask WriteToFileAsync<TData>(TData data, string file, CancellationToken cancellationToken) private static async ValueTask WriteToFileAsync<TData>(TData data, string file, CancellationToken cancellationToken)
{ {
var json = JsonSerializer.Serialize(data, new JsonSerializerOptions { WriteIndented = true }); var json = JsonSerializer.Serialize(data, _serializerOptions);
await File.WriteAllTextAsync(file, json, cancellationToken); await File.WriteAllTextAsync(file, json, cancellationToken);
} }
}
} }

View file

@ -1,24 +1,25 @@
using Insight.Agent.Messages; using Insight.Agent.Network;
using Insight.Agent.Network; using Insight.Domain.Network;
using Insight.Domain.Network.Agent.Messages;
using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using System.Diagnostics.Eventing.Reader; using System.Diagnostics.Eventing.Reader;
using System.Runtime.Versioning; using System.Runtime.Versioning;
using System.Threading.Channels; using System.Threading.Channels;
using Vaitr.Network; using Vaitr.Network;
using static Insight.Agent.Messages.Event; using static Insight.Domain.Network.Agent.Messages.Event;
using EventLevel = System.Diagnostics.Tracing.EventLevel; using EventLevel = System.Diagnostics.Tracing.EventLevel;
namespace Insight.Agent.Services namespace Insight.Agent.Services;
[SupportedOSPlatform("windows")]
internal class EventService : BackgroundService
{ {
[SupportedOSPlatform("windows")]
internal class EventService : BackgroundService
{
private readonly Channel<Event> _queue; private readonly Channel<Event> _queue;
private readonly ISessionPool<AgentSession, IAgentMessage> _pool; private readonly ISessionPool<AgentSession, IMessage> _pool;
private readonly ILogger<EventService> _logger; private readonly ILogger<EventService> _logger;
public EventService(ISessionPool<AgentSession, IAgentMessage> pool, ILogger<EventService> logger) public EventService(ISessionPool<AgentSession, IMessage> pool, ILogger<EventService> logger)
{ {
_pool = pool; _pool = pool;
_logger = logger; _logger = logger;
@ -162,9 +163,8 @@ namespace Insight.Agent.Services
}; };
} }
_queue.Writer.WriteAsync(@event, default); _ = _queue.Writer.WriteAsync(@event, default);
} }
catch (Exception) { } // app crash catch (Exception) { } // app crash
} }
}
} }

View file

@ -1,37 +1,17 @@
using Insight.Agent.Interfaces; using Microsoft.Extensions.Logging;
using Insight.Agent.Messages;
using System.Management.Automation; using System.Management.Automation;
using System.Management.Automation.Runspaces; using System.Management.Automation.Runspaces;
namespace Insight.Agent.Network.Handlers; namespace Insight.Agent.Services;
public class ConsoleHandler : IAgentMessageHandler<AgentSession> public class ScriptService(ILogger<ScriptService> logger)
{ {
public async ValueTask HandleAsync<TMessage>(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IAgentMessage private readonly ILogger<ScriptService> _logger = logger;
{
if (message is ConsoleQueryRequest consoleQueryRequest)
{
await OnConsoleQueryRequestAsync(sender, consoleQueryRequest, cancellationToken);
}
}
private async ValueTask OnConsoleQueryRequestAsync(AgentSession sender, ConsoleQueryRequest consoleQueryRequest, CancellationToken cancellationToken) public async Task<QueryResult> QueryAsync(string query)
{ {
var result = await QueryScriptAsync(consoleQueryRequest.Query); _logger.LogDebug("QueryAsync ({query})", query);
await sender.SendAsync(new ConsoleQuery
{
Id = consoleQueryRequest.Id,
HostId = consoleQueryRequest.HostId,
Query = consoleQueryRequest.Query,
Data = result.Data,
Errors = result.Errors,
HadErrors = result.HadErrors
}, cancellationToken);
}
private static async Task<QueryResult> QueryScriptAsync(string query)
{
var result = new QueryResult(); var result = new QueryResult();
var errors = new List<string>(); var errors = new List<string>();
@ -44,7 +24,7 @@ public class ConsoleHandler : IAgentMessageHandler<AgentSession>
using var ps = PowerShell.Create(runspace); using var ps = PowerShell.Create(runspace);
ps.AddScript("Set-ExecutionPolicy unrestricted -Scope Process"); ps.AddScript("Set-ExecutionPolicy unrestricted -Scope Process");
ps.AddScript(query); ps.AddScript(query);
ps.AddCommand("ConvertTo-Json"); // -Depth 10 //ps.AddCommand("ConvertTo-Json"); // -Depth 10
result.Query = query; result.Query = query;
@ -57,7 +37,15 @@ public class ConsoleHandler : IAgentMessageHandler<AgentSession>
} }
else else
{ {
result.Data = queryResult[0].ToString(); var newLine = false;
foreach (var data in queryResult)
{
if (newLine) result.Data += "\n";
else newLine = true;
result.Data += data.ToString();
}
//if (string.IsNullOrWhiteSpace(jsonString)) return result; //if (string.IsNullOrWhiteSpace(jsonString)) return result;
@ -100,12 +88,12 @@ public class ConsoleHandler : IAgentMessageHandler<AgentSession>
result.Errors = string.Join("\n", errors); result.Errors = string.Join("\n", errors);
return result; return result;
} }
}
public class QueryResult public class QueryResult
{ {
public bool HadErrors { get; set; } public bool HadErrors { get; set; }
public string? Query { get; set; } public string? Query { get; set; }
public string? Data { get; set; } public string? Data { get; set; }
public string? Errors { get; set; } public string? Errors { get; set; }
}
} }

View file

@ -1,5 +1,6 @@
using Insight.Agent.Messages; using Insight.Agent.Network;
using Insight.Agent.Network; using Insight.Domain.Network;
using Insight.Domain.Network.Agent.Messages;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
@ -9,19 +10,18 @@ using System.Net.Sockets;
using System.Threading.Channels; using System.Threading.Channels;
using Vaitr.Network; using Vaitr.Network;
namespace Insight.Agent.Services namespace Insight.Agent.Services;
public class TrapService : BackgroundService
{ {
public class TrapService : BackgroundService
{
private static IPEndPoint EndpointCache { get; } = new(IPAddress.Any, 0); private static IPEndPoint EndpointCache { get; } = new(IPAddress.Any, 0);
private readonly Channel<Trap> _queue; private readonly Channel<Trap> _queue;
private readonly int _port; private readonly int _port;
private readonly ISessionPool<AgentSession, IAgentMessage> _pool; private readonly ISessionPool<AgentSession, IMessage> _pool;
private readonly ILogger<TrapService> _logger; private readonly ILogger<TrapService> _logger;
public TrapService(ISessionPool<AgentSession, IAgentMessage> pool, IConfiguration configuration, ILogger<TrapService> logger) public TrapService(ISessionPool<AgentSession, IMessage> pool, IConfiguration configuration, ILogger<TrapService> logger)
{ {
_port = configuration.GetValue<int?>(Appsettings.TrapPort) ?? throw new Exception($"{Appsettings.TrapPort} value not set (appsettings)"); _port = configuration.GetValue<int?>(Appsettings.TrapPort) ?? throw new Exception($"{Appsettings.TrapPort} value not set (appsettings)");
_pool = pool; _pool = pool;
@ -196,5 +196,4 @@ namespace Insight.Agent.Services
return data; return data;
} }
}
} }

View file

@ -10,21 +10,14 @@ using System.Runtime.Versioning;
using System.ServiceProcess; using System.ServiceProcess;
using System.Text.Json; using System.Text.Json;
namespace Insight.Agent.Services namespace Insight.Agent.Services;
internal class UpdateService(HttpClient httpClient, IConfiguration configuration, ILogger<UpdateService> logger) : BackgroundService
{ {
internal class UpdateService : BackgroundService private readonly Uri _uri = configuration.GetValue<Uri?>("api") ?? throw new Exception($"api value not set (appsettings)");
{
private readonly Uri _uri;
private readonly HttpClient _httpClient; private readonly HttpClient _httpClient = httpClient;
private readonly ILogger<UpdateService> _logger; private readonly ILogger<UpdateService> _logger = logger;
public UpdateService(HttpClient httpClient, IConfiguration configuration, ILogger<UpdateService> logger)
{
_httpClient = httpClient;
_uri = configuration.GetValue<Uri?>("api") ?? throw new Exception($"api value not set (appsettings)");
_logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken cancellationToken) protected override async Task ExecuteAsync(CancellationToken cancellationToken)
{ {
@ -42,7 +35,7 @@ namespace Insight.Agent.Services
_logger.LogInformation("Update Result: {result}", result?.Success); _logger.LogInformation("Update Result: {result}", result?.Success);
if (result?.UpdateErrors is not null) if (result?.UpdateErrors is not null)
{ {
_logger.LogError("Update Errors: {errors}", string.Concat(result?.UpdateErrors)); _logger.LogError("Update Errors: {errors}", string.Concat(result.UpdateErrors));
} }
} }
catch (OperationCanceledException) { } catch (OperationCanceledException) { }
@ -198,7 +191,7 @@ namespace Insight.Agent.Services
await File.WriteAllBytesAsync(updateFile.FullName, await update.Content.ReadAsByteArrayAsync(cancellationToken), cancellationToken); await File.WriteAllBytesAsync(updateFile.FullName, await update.Content.ReadAsByteArrayAsync(cancellationToken), cancellationToken);
// extract update archive from temp to app dir (overwrite) // extract update archive from temp to app dir (overwrite)
ZipFile.ExtractToDirectory(updateFile.FullName, bin.Directory?.FullName, true); ZipFile.ExtractToDirectory(updateFile.FullName, bin.Directory!.FullName, true);
// delete temp folder // delete temp folder
if (temp.Exists) temp.Delete(true); if (temp.Exists) temp.Delete(true);
@ -229,7 +222,7 @@ namespace Insight.Agent.Services
var matched = System.Diagnostics.Process.GetProcessesByName(bin.FullName); var matched = System.Diagnostics.Process.GetProcessesByName(bin.FullName);
if (matched is null || matched.Any() is false) return false; if (matched is null || matched.Length == 0) return false;
if (matched.Any(p => if (matched.Any(p =>
p.MainModule is not null && p.MainModule is not null &&
@ -262,7 +255,7 @@ namespace Insight.Agent.Services
var matched = System.Diagnostics.Process.GetProcessesByName(bin.FullName); var matched = System.Diagnostics.Process.GetProcessesByName(bin.FullName);
if (matched is null || matched.Any() is false) return true; if (matched is null || matched.Length == 0) return true;
foreach (var procsInfo in matched.Where(p => foreach (var procsInfo in matched.Where(p =>
p.MainModule is not null && p.MainModule is not null &&
@ -312,7 +305,7 @@ namespace Insight.Agent.Services
await File.WriteAllBytesAsync(updateFile.FullName, await update.Content.ReadAsByteArrayAsync(cancellationToken), cancellationToken); await File.WriteAllBytesAsync(updateFile.FullName, await update.Content.ReadAsByteArrayAsync(cancellationToken), cancellationToken);
// extract update archive from temp to app dir (overwrite) // extract update archive from temp to app dir (overwrite)
ZipFile.ExtractToDirectory(updateFile.FullName, bin.Directory?.FullName, true); ZipFile.ExtractToDirectory(updateFile.FullName, bin.Directory!.FullName, true);
// delete temp folder // delete temp folder
if (temp.Exists) temp.Delete(true); if (temp.Exists) temp.Delete(true);
@ -353,8 +346,7 @@ namespace Insight.Agent.Services
public bool ApiAvailable { get; set; } = false; public bool ApiAvailable { get; set; } = false;
public bool UpdateAvailable { get; set; } = false; public bool UpdateAvailable { get; set; } = false;
public bool Success { get; set; } = false; public bool Success { get; set; } = false;
public List<string> ApiErrors { get; } = new(); public List<string> ApiErrors { get; } = [];
public List<string> UpdateErrors { get; } = new(); public List<string> UpdateErrors { get; } = [];
}
} }
} }

View file

@ -1,12 +1,12 @@
using Insight.Agent.Extensions; using Insight.Domain.Extensions;
using Insight.Agent.Messages; using Insight.Domain.Network.Agent.Messages;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
namespace Insight.Agent.Services namespace Insight.Agent.Services;
public partial class CollectorService
{ {
public partial class CollectorService
{
public OperationSystem? GetOperatingSystem() public OperationSystem? GetOperatingSystem()
{ {
Logger.LogTrace("GetOperatingSystem"); Logger.LogTrace("GetOperatingSystem");
@ -21,10 +21,9 @@ namespace Insight.Agent.Services
output = stream.ReadToEnd(); output = stream.ReadToEnd();
// clean output // clean output
var clean = Regex var clean = CleanRegex().Replace(output
.Replace(output
.Trim() .Trim()
.Replace("\t", " "), @"[ ]{2,}", " "); .Replace("\t", " "), " ");
var elements = clean.Split(Array.Empty<char>(), StringSplitOptions.RemoveEmptyEntries); var elements = clean.Split(Array.Empty<char>(), StringSplitOptions.RemoveEmptyEntries);
@ -36,13 +35,12 @@ namespace Insight.Agent.Services
// linebreak list conversion // linebreak list conversion
var lines = new List<string>(output var lines = new List<string>(output
.Split(new string[] { "\n", "\r\n" }, StringSplitOptions.RemoveEmptyEntries)) .Split(separator, StringSplitOptions.RemoveEmptyEntries))
.Select(l => .Select(l =>
{ {
return Regex return CleanRegex().Replace(l
.Replace(l
.Trim() .Trim()
.Replace("\t", " "), @"[ ]{2,}", " "); .Replace("\t", " "), " ");
}) })
.ToList(); .ToList();
@ -62,13 +60,12 @@ namespace Insight.Agent.Services
// linebreak list conversion // linebreak list conversion
lines = new List<string>(output lines = new List<string>(output
.Split(new string[] { "\n", "\r\n" }, StringSplitOptions.RemoveEmptyEntries)) .Split(separator, StringSplitOptions.RemoveEmptyEntries))
.Select(l => .Select(l =>
{ {
return Regex return CleanRegex().Replace(l
.Replace(l
.Trim() .Trim()
.Replace("\t", " "), @"[ ]{2,}", " "); .Replace("\t", " "), " ");
}) })
.ToList(); .ToList();
@ -102,5 +99,9 @@ namespace Insight.Agent.Services
return os; return os;
} }
}
private static readonly string[] separator = ["\n", "\r\n"];
[GeneratedRegex(@"[ ]{2,}")]
private static partial Regex CleanRegex();
} }

View file

@ -1,12 +1,12 @@
using Insight.Agent.Extensions; using Insight.Domain.Extensions;
using Insight.Agent.Messages; using Insight.Domain.Network.Agent.Messages;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
namespace Insight.Agent.Services namespace Insight.Agent.Services;
public partial class CollectorService
{ {
public partial class CollectorService
{
public List<Session>? GetSessions() public List<Session>? GetSessions()
{ {
Logger.LogTrace("GetSessions"); Logger.LogTrace("GetSessions");
@ -17,11 +17,11 @@ namespace Insight.Agent.Services
var output = "w".Bash(); var output = "w".Bash();
// linebreak list conversion // linebreak list conversion
var lines = output.Split(new string[] { "\n", "\r\n" }, StringSplitOptions.RemoveEmptyEntries).ToList(); var lines = output.Split(separatorArray, StringSplitOptions.RemoveEmptyEntries).ToList();
lines = lines.Select(l => lines = lines.Select(l =>
{ {
return Regex.Replace(l.Trim().Replace("\t", " "), @"[ ]{2,}", " "); return CleanOutputRegex().Replace(l.Trim().Replace("\t", " "), " ");
}).ToList(); }).ToList();
// cleaning // cleaning
@ -46,5 +46,9 @@ namespace Insight.Agent.Services
return sessions; return sessions;
} }
}
private static readonly string[] separatorArray = ["\n", "\r\n"];
[GeneratedRegex(@"[ ]{2,}")]
private static partial Regex CleanOutputRegex();
} }

View file

@ -1,9 +1,8 @@
using Insight.Domain.Constants; using Insight.Domain.Constants;
namespace Insight.Api namespace Insight.Api;
public static class Locations
{ {
public static class Locations
{
public static DirectoryInfo UpdatesPath { get; } = new DirectoryInfo($"{Configuration.AppDirectory?.FullName}/files/updates"); public static DirectoryInfo UpdatesPath { get; } = new DirectoryInfo($"{Configuration.AppDirectory?.FullName}/files/updates");
}
} }

View file

@ -1,31 +1,29 @@
using Insight.Api.Models; using Insight.Api.Models;
using Insight.Infrastructure.Entities;
using Insight.Infrastructure.Models; using Insight.Infrastructure.Models;
using Insight.Infrastructure.Services; using Insight.Infrastructure.Services;
using Insight.Infrastructure.Web;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using MongoDB.Driver;
namespace Insight.Api.Controllers namespace Insight.Api.Controllers;
[ApiController, Route("api/accounts")]
public class AccountController(IdentityService identityService, IServiceScopeFactory scopeFactory) : ControllerBase
{ {
[ApiController, Route("api/accounts")] private readonly IdentityService _identityService = identityService;
public class AccountController : ControllerBase private readonly IServiceScopeFactory _scopeFactory = scopeFactory;
{
private readonly IdentityService _identityService;
private readonly AccountService _accountService;
private readonly ILogger<AccountController> _logger;
public AccountController(IdentityService identityService, AccountService accountService, ILogger<AccountController> logger)
{
_identityService = identityService;
_accountService = accountService;
_logger = logger;
}
[HttpGet, Authorize] [HttpGet, Authorize]
public async Task<IActionResult> Get([FromQuery] PagedDataRequest request, CancellationToken cancellationToken) public async Task<IActionResult> Get([FromQuery] PagedDataRequest request, CancellationToken cancellationToken)
{ {
using var scope = _scopeFactory.CreateScope();
var collection = scope.ServiceProvider.GetRequiredService<IMongoDatabase>().User();
try try
{ {
var result = await _accountService.GetAsync( var result = await collection.GetPagedAsync(
offset: request.Offset, offset: request.Offset,
limit: request.Limit, limit: request.Limit,
request: Request, request: Request,
@ -72,5 +70,4 @@ namespace Insight.Api.Controllers
return Ok(model.Email); return Ok(model.Email);
} }
}
} }

View file

@ -1,28 +1,26 @@
using Insight.Infrastructure.Models; using Insight.Infrastructure.Entities;
using Insight.Infrastructure.Services; using Insight.Infrastructure.Models;
using Insight.Infrastructure.Web;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using MongoDB.Driver;
namespace Insight.Api.Controllers namespace Insight.Api.Controllers;
[ApiController, Route("api/agents")]
public class AgentController(IServiceScopeFactory scopeFactory) : ControllerBase
{ {
[ApiController, Route("api/agents")] private readonly IServiceScopeFactory _scopeFactory = scopeFactory;
public class AgentController : ControllerBase
{
private readonly AgentService _agentService;
private readonly ILogger<AgentController> _logger;
public AgentController(AgentService agentService, ILogger<AgentController> logger)
{
_agentService = agentService;
_logger = logger;
}
[HttpGet, Authorize] [HttpGet, Authorize]
public async Task<IActionResult> Get([FromQuery] PagedDataRequest request, CancellationToken cancellationToken) public async Task<IActionResult> Get([FromQuery] PagedDataRequest request, CancellationToken cancellationToken)
{ {
using var scope = _scopeFactory.CreateScope();
var collection = scope.ServiceProvider.GetRequiredService<IMongoDatabase>().Agent();
try try
{ {
var result = await _agentService.GetAsync( var result = await collection.GetPagedAsync(
offset: request.Offset, offset: request.Offset,
limit: request.Limit, limit: request.Limit,
request: Request, request: Request,
@ -40,5 +38,4 @@ namespace Insight.Api.Controllers
return BadRequest(ex.Message); return BadRequest(ex.Message);
} }
} }
}
} }

View file

@ -1,28 +1,26 @@
using Insight.Infrastructure.Models; using Insight.Infrastructure.Entities;
using Insight.Infrastructure.Services; using Insight.Infrastructure.Models;
using Insight.Infrastructure.Web;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using MongoDB.Driver;
namespace Insight.Api.Controllers namespace Insight.Api.Controllers;
[ApiController, Route("api/customers")]
public class CustomerController(IServiceScopeFactory scopeFactory) : ControllerBase
{ {
[ApiController, Route("api/customers")] private readonly IServiceScopeFactory _scopeFactory = scopeFactory;
public class CustomerController : ControllerBase
{
private readonly CustomerService _customerService;
private readonly ILogger<CustomerController> _logger;
public CustomerController(CustomerService customerService, ILogger<CustomerController> logger)
{
_customerService = customerService;
_logger = logger;
}
[HttpGet, Authorize] [HttpGet, Authorize]
public async Task<IActionResult> Get([FromQuery] PagedDataRequest request, CancellationToken cancellationToken) public async Task<IActionResult> Get([FromQuery] PagedDataRequest request, CancellationToken cancellationToken)
{ {
using var scope = _scopeFactory.CreateScope();
var collection = scope.ServiceProvider.GetRequiredService<IMongoDatabase>().Customer();
try try
{ {
var result = await _customerService.GetAsync( var result = await collection.GetPagedAsync(
offset: request.Offset, offset: request.Offset,
limit: request.Limit, limit: request.Limit,
request: Request, request: Request,
@ -40,5 +38,4 @@ namespace Insight.Api.Controllers
return BadRequest(ex.Message); return BadRequest(ex.Message);
} }
} }
}
} }

View file

@ -1,28 +1,26 @@
using Insight.Infrastructure.Models; using Insight.Infrastructure.Entities;
using Insight.Infrastructure.Services; using Insight.Infrastructure.Models;
using Insight.Infrastructure.Web;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using MongoDB.Driver;
namespace Insight.Api.Controllers namespace Insight.Api.Controllers;
[ApiController, Route("api/hosts")]
public class HostController(IServiceScopeFactory scopeFactory) : ControllerBase
{ {
[ApiController, Route("api/hosts")] private readonly IServiceScopeFactory _scopeFactory = scopeFactory;
public class HostController : ControllerBase
{
private readonly HostService _hostService;
private readonly ILogger<HostController> _logger;
public HostController(HostService hostService, ILogger<HostController> logger)
{
_hostService = hostService;
_logger = logger;
}
[HttpGet, Authorize] [HttpGet, Authorize]
public async Task<IActionResult> Get([FromQuery] PagedDataRequest request, CancellationToken cancellationToken) public async Task<IActionResult> Get([FromQuery] PagedDataRequest request, CancellationToken cancellationToken)
{ {
using var scope = _scopeFactory.CreateScope();
var collection = scope.ServiceProvider.GetRequiredService<IMongoDatabase>().Host();
try try
{ {
var result = await _hostService.GetAsync( var result = await collection.GetPagedAsync(
offset: request.Offset, offset: request.Offset,
limit: request.Limit, limit: request.Limit,
request: Request, request: Request,
@ -40,5 +38,4 @@ namespace Insight.Api.Controllers
return BadRequest(ex.Message); return BadRequest(ex.Message);
} }
} }
}
} }

View file

@ -1,6 +1,6 @@
using Insight.Infrastructure.Entities; using Insight.Infrastructure.Entities;
using Insight.Infrastructure.Models; using Insight.Infrastructure.Models;
using Insight.Infrastructure.Services; using Insight.Infrastructure.Web;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using MongoDB.Bson; using MongoDB.Bson;
@ -8,23 +8,19 @@ using MongoDB.Driver;
using System.Text.Json.Serialization; using System.Text.Json.Serialization;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
namespace Insight.Api.Controllers namespace Insight.Api.Controllers;
{
[ApiController, Route("api/inventory")]
public class InventoryController : ControllerBase
{
private readonly InventoryService _inventoryService;
private readonly ILogger<InventoryController> _logger;
public InventoryController(InventoryService inventoryService, ILogger<InventoryController> logger) [ApiController, Route("api/inventory")]
{ public class InventoryController(IServiceScopeFactory scopeFactory) : ControllerBase
_inventoryService = inventoryService; {
_logger = logger; private readonly IServiceScopeFactory _scopeFactory = scopeFactory;
}
[HttpGet, Authorize] [HttpGet, Authorize]
public async Task<IActionResult> Get([FromQuery] HostApplicationEntity request, [FromQuery] PagedDataRequest meta, CancellationToken cancellationToken) public async Task<IActionResult> Get([FromQuery] HostApplicationEntity request, [FromQuery] PagedDataRequest meta, CancellationToken cancellationToken)
{ {
using var scope = _scopeFactory.CreateScope();
var collection = scope.ServiceProvider.GetRequiredService<IMongoDatabase>().HostApplication();
try try
{ {
var filter = Builders<HostApplicationEntity>.Filter.Empty; var filter = Builders<HostApplicationEntity>.Filter.Empty;
@ -38,7 +34,7 @@ namespace Insight.Api.Controllers
if (request.Name is not null) if (request.Name is not null)
filter &= Builders<HostApplicationEntity>.Filter.Regex(p => p.Name, new BsonRegularExpression(new Regex(request.Name, RegexOptions.IgnoreCase))); filter &= Builders<HostApplicationEntity>.Filter.Regex(p => p.Name, new BsonRegularExpression(new Regex(request.Name, RegexOptions.IgnoreCase)));
var result = await _inventoryService.GetAsync( var result = await collection.GetPagedAsync(
filter: filter, filter: filter,
offset: meta.Offset, offset: meta.Offset,
limit: meta.Limit, limit: meta.Limit,
@ -69,5 +65,4 @@ namespace Insight.Api.Controllers
[JsonPropertyName("name")] [JsonPropertyName("name")]
public string? Name { get; set; } public string? Name { get; set; }
} }
}
} }

View file

@ -1,16 +1,11 @@
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
namespace Insight.Server.Controllers namespace Insight.Server.Controllers;
{
[ApiController, Route("api/setup")]
public class SetupController : ControllerBase
{
private readonly ILogger<SetupController> _logger;
public SetupController(ILogger<SetupController> logger) [ApiController, Route("api/setup")]
{ public class SetupController(ILogger<SetupController> logger) : ControllerBase
_logger = logger; {
} private readonly ILogger<SetupController> _logger = logger;
[HttpGet("windows")] [HttpGet("windows")]
public async Task<IActionResult> GetAsync(CancellationToken cancellationToken) public async Task<IActionResult> GetAsync(CancellationToken cancellationToken)
@ -26,5 +21,4 @@ namespace Insight.Server.Controllers
return File(await System.IO.File.ReadAllBytesAsync(files.OrderBy(p => p.LastWriteTime).First().FullName, cancellationToken), "application/zip", "setup-win64.zip"); return File(await System.IO.File.ReadAllBytesAsync(files.OrderBy(p => p.LastWriteTime).First().FullName, cancellationToken), "application/zip", "setup-win64.zip");
} }
}
} }

View file

@ -3,17 +3,12 @@ using Insight.Infrastructure.Services;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
namespace Insight.Api.Controllers namespace Insight.Api.Controllers;
{
[ApiController, Route("api/token", Order = 0)]
public class TokenController : ControllerBase
{
private readonly TokenService _tokenService;
public TokenController(TokenService tokenService) [ApiController, Route("api/token", Order = 0)]
{ public class TokenController(TokenService tokenService) : ControllerBase
_tokenService = tokenService; {
} private readonly TokenService _tokenService = tokenService;
/// <remarks> /// <remarks>
/// Access Token Request /// Access Token Request
@ -21,6 +16,9 @@ namespace Insight.Api.Controllers
[HttpPost, AllowAnonymous] [HttpPost, AllowAnonymous]
public async Task<IActionResult> Authentication([FromBody] TokenRequest request) public async Task<IActionResult> Authentication([FromBody] TokenRequest request)
{ {
if (request.Username is null) return BadRequest("username is null");
if (request.Password is null) return BadRequest("password is null");
try try
{ {
var result = await _tokenService.GetAsync(request.Username, request.Password, request.Code, HttpContext.Connection.RemoteIpAddress).ConfigureAwait(false); var result = await _tokenService.GetAsync(request.Username, request.Password, request.Code, HttpContext.Connection.RemoteIpAddress).ConfigureAwait(false);
@ -81,5 +79,4 @@ namespace Insight.Api.Controllers
return BadRequest(ex.Message); return BadRequest(ex.Message);
} }
} }
}
} }

View file

@ -2,17 +2,12 @@
using Insight.Domain.Models; using Insight.Domain.Models;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
namespace Insight.Server.Controllers namespace Insight.Server.Controllers;
{
[ApiController, Route("api/update")]
public class UpdateController : ControllerBase
{
private readonly ILogger<UpdateController> _logger;
public UpdateController(ILogger<UpdateController> logger) [ApiController, Route("api/update")]
{ public class UpdateController(ILogger<UpdateController> logger) : ControllerBase
_logger = logger; {
} private readonly ILogger<UpdateController> _logger = logger;
[HttpGet("updater/windows")] [HttpGet("updater/windows")]
public IActionResult UpdaterWindows() public IActionResult UpdaterWindows()
@ -35,7 +30,7 @@ namespace Insight.Server.Controllers
var versions = updateDir.GetFiles("*.zip", SearchOption.TopDirectoryOnly); var versions = updateDir.GetFiles("*.zip", SearchOption.TopDirectoryOnly);
if (versions is null || versions.Any() is false) return NotFound(); if (versions is null || versions.Length == 0) return NotFound();
var latest = versions.OrderBy(x => x.Name).FirstOrDefault(); var latest = versions.OrderBy(x => x.Name).FirstOrDefault();
@ -73,7 +68,7 @@ namespace Insight.Server.Controllers
var versions = updateDir.GetFiles("*.zip", SearchOption.TopDirectoryOnly); var versions = updateDir.GetFiles("*.zip", SearchOption.TopDirectoryOnly);
if (versions is null || versions.Any() is false) return NotFound(); if (versions is null || versions.Length == 0) return NotFound();
var latest = versions.OrderBy(x => x.Name).FirstOrDefault(); var latest = versions.OrderBy(x => x.Name).FirstOrDefault();
@ -89,5 +84,4 @@ namespace Insight.Server.Controllers
Uri = new Uri($"{Request.Scheme}://{Request.Host}/api/{relPath}") Uri = new Uri($"{Request.Scheme}://{Request.Host}/api/{relPath}")
}); });
} }
}
} }

View file

@ -1,15 +1,49 @@
using Microsoft.AspNetCore.Authentication.JwtBearer; using Insight.Infrastructure;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Models;
using OpenTelemetry.Metrics;
using OpenTelemetry.Resources;
using System.Reflection; using System.Reflection;
namespace Insight.Api.Hosting namespace Insight.Api.Extensions;
internal static class ServiceExtensions
{ {
public static class ServiceExtensions internal static WebApplicationBuilder AddMetrics(this WebApplicationBuilder builder)
{ {
internal static IServiceCollection AddSwaggerServices(this IServiceCollection services, IConfiguration configuration) builder.Services.AddOpenTelemetry()
.WithMetrics(provider =>
{ {
services.AddEndpointsApiExplorer(); provider.ConfigureResource(configure =>
services.AddSwaggerGen(options => {
configure.Clear();
configure.AddService(builder.Configuration.GetValue<string?>(Appsettings.Influx.Service) ?? throw new Exception($"{Appsettings.Influx.Service} value not set (appsettings)"));
})
.AddRuntimeInstrumentation()
.AddProcessInstrumentation()
.AddAspNetCoreInstrumentation()
.AddHttpClientInstrumentation()
//.AddMeter("test")
.AddInfluxDBMetricsExporter(configure =>
{
configure.Endpoint = builder.Configuration.GetValue<Uri?>(Appsettings.Influx.Endpoint) ?? throw new Exception($"{Appsettings.Influx.Endpoint} value not set (appsettings)");
configure.Token = builder.Configuration.GetValue<string?>(Appsettings.Influx.Token) ?? throw new Exception($"{Appsettings.Influx.Token} value not set (appsettings)");
configure.Org = builder.Configuration.GetValue<string?>(Appsettings.Influx.Organization) ?? throw new Exception($"{Appsettings.Influx.Organization} value not set (appsettings)");
configure.Bucket = builder.Configuration.GetValue<string?>(Appsettings.Influx.Bucket) ?? throw new Exception($"{Appsettings.Influx.Bucket} value not set (appsettings)");
configure.MetricExportIntervalMilliseconds = 1000;
});
}
);
//builder.Services.AddSingleton<BasicMetrics>();
return builder;
}
internal static WebApplicationBuilder AddSwagger(this WebApplicationBuilder builder)
{
builder.Services.AddSwaggerGen(options =>
{ {
options.SwaggerDoc("v1", new OpenApiInfo options.SwaggerDoc("v1", new OpenApiInfo
{ {
@ -53,7 +87,23 @@ namespace Insight.Api.Hosting
options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xmlFilename)); options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xmlFilename));
}); });
return services; return builder;
} }
internal static WebApplication ConfigureSwagger(this WebApplication app)
{
app.UseSwagger(options =>
{
options.RouteTemplate = "api/swagger/{documentName}/swagger.json";
});
app.UseSwaggerUI(options =>
{
options.DefaultModelsExpandDepth(-1);
options.SwaggerEndpoint("/api/swagger/v1/swagger.json", "v1");
options.RoutePrefix = "api/swagger";
});
return app;
} }
} }

View file

@ -1,49 +1,41 @@
<Project Sdk="Microsoft.NET.Sdk.Web"> <Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup> <PropertyGroup>
<TargetFramework>net7.0</TargetFramework> <TargetFramework>net8.0</TargetFramework>
<LangVersion>latest</LangVersion>
<Product>Insight</Product> <Product>Insight</Product>
<AssemblyName>api</AssemblyName> <AssemblyName>api</AssemblyName>
<AssemblyVersion>2023.8.23.1</AssemblyVersion> <AssemblyVersion>2023.12.15.0</AssemblyVersion>
<RootNamespace>Insight.Api</RootNamespace> <RootNamespace>Insight.Api</RootNamespace>
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
<UserSecretsId>4ae1d3bf-869e-4963-8a19-35634507d3b3</UserSecretsId> <UserSecretsId>4ae1d3bf-869e-4963-8a19-35634507d3b3</UserSecretsId>
<PublishAot>false</PublishAot> <PublishAot>false</PublishAot>
<PublishTrimmed>false</PublishTrimmed> <PublishTrimmed>false</PublishTrimmed>
<!--<ServerGarbageCollection>false</ServerGarbageCollection> <!--<ServerGarbageCollection>false</ServerGarbageCollection>
<ConcurrentGarbageCollection>false</ConcurrentGarbageCollection>--> <ConcurrentGarbageCollection>false</ConcurrentGarbageCollection>-->
<GenerateDocumentationFile>True</GenerateDocumentationFile> <GenerateDocumentationFile>True</GenerateDocumentationFile>
<NoWarn>$(NoWarn);1591</NoWarn> <NoWarn>$(NoWarn);1591</NoWarn>
</PropertyGroup> <SatelliteResourceLanguages>none</SatelliteResourceLanguages>
<InvariantGlobalization>true</InvariantGlobalization>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<DebugType>none</DebugType>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
<DebugType>none</DebugType>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.Extensions.Hosting.Systemd" Version="7.0.0" /> <PackageReference Include="Microsoft.Extensions.Hosting.Systemd" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Hosting.WindowsServices" Version="7.0.1" /> <PackageReference Include="Microsoft.Extensions.Hosting.WindowsServices" Version="8.0.0" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="7.0.11" /> <PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="8.0.1" />
<PackageReference Include="OpenTelemetry.Exporter.InfluxDB" Version="1.0.0-alpha.3" />
<PackageReference Include="OpenTelemetry.Extensions.Hosting" Version="1.7.0" />
<PackageReference Include="OpenTelemetry.Instrumentation.AspNetCore" Version="1.7.0" />
<PackageReference Include="OpenTelemetry.Instrumentation.Http" Version="1.7.0" />
<PackageReference Include="OpenTelemetry.Instrumentation.Process" Version="0.5.0-beta.4" />
<PackageReference Include="OpenTelemetry.Instrumentation.Runtime" Version="1.7.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" /> <PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" />
<PackageReference Include="Serilog.Extensions.Logging.File" Version="3.0.0" /> <PackageReference Include="Serilog.Extensions.Logging.File" Version="3.0.0" />
<!--Unix Serilog stuff-->
<PackageReference Include="System.IO.FileSystem.Primitives" Version="4.3.0" />
<PackageReference Include="System.Text.Encoding.Extensions" Version="4.3.0" />
<PackageReference Include="System.Runtime.Handles" Version="4.3.0" />
<PackageReference Include="System.IO" Version="4.3.0" />
<PackageReference Include="System.Runtime.InteropServices" Version="4.3.0" />
<PackageReference Include="System.Threading" Version="4.3.0" />
<PackageReference Include="System.Threading.Tasks" Version="4.3.0" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\..\Core\Insight.Infrastructure.Web\Insight.Infrastructure.Web.csproj" />
<ProjectReference Include="..\..\Core\Insight.Infrastructure\Insight.Infrastructure.csproj" /> <ProjectReference Include="..\..\Core\Insight.Infrastructure\Insight.Infrastructure.csproj" />
</ItemGroup> </ItemGroup>

View file

@ -1,9 +1,9 @@
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
namespace Insight.Api.Models namespace Insight.Api.Models;
public class RegistrationModel
{ {
public class RegistrationModel
{
public string? FirstName { get; set; } public string? FirstName { get; set; }
public string? LastName { get; set; } public string? LastName { get; set; }
@ -19,5 +19,4 @@ namespace Insight.Api.Models
[DataType(DataType.Password)] [DataType(DataType.Password)]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")] [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string? ConfirmPassword { get; set; } public string? ConfirmPassword { get; set; }
}
} }

View file

@ -1,59 +1,50 @@
using Insight.Api.Hosting; using Insight.Api.Extensions;
using Insight.Domain.Constants; using Insight.Domain.Constants;
using Insight.Infrastructure; using Insight.Infrastructure;
using Microsoft.Extensions.FileProviders; using Microsoft.Extensions.FileProviders;
using System.Diagnostics;
namespace Insight.Api namespace Insight.Api;
internal class Program
{ {
public class Program
{
public static async Task Main(string[] args) public static async Task Main(string[] args)
{ {
var builder = WebApplication.CreateBuilder(args); var builder = WebApplication.CreateBuilder(args);
builder.Host.UseWindowsService(); builder.Host.UseWindowsService();
builder.Host.UseSystemd(); builder.Host.UseSystemd();
// LOGGER // Configuration
builder.Configuration.Defaults();
// Logging
builder.Logging.ClearProviders(); builder.Logging.ClearProviders();
builder.Logging.SetMinimumLevel(LogLevel.Trace); builder.Logging.SetMinimumLevel(LogLevel.Trace);
builder.Logging.AddFilter("Microsoft.AspNetCore", LogLevel.Warning); builder.Logging.AddFilter("Microsoft.AspNetCore", LogLevel.Warning);
builder.Logging.AddSimpleConsole(options => builder.Logging.AddSimpleConsole(options =>
{ {
options.IncludeScopes = true; options.IncludeScopes = true;
options.SingleLine = true; options.SingleLine = true;
options.TimestampFormat = "yyyy-MM-dd HH:mm:ss.fff "; options.TimestampFormat = "yyyy-MM-dd HH:mm:ss.fff ";
}); });
builder.Logging.AddFile(Configuration.AppDirectory?.FullName + "/logs/" + Process.GetCurrentProcess().ProcessName + "_{Date}.log", LogLevel.Trace, fileSizeLimitBytes: 104857600, retainedFileCountLimit: 10, outputTemplate: "{Timestamp:o} [{Level:u3}] {Message} {NewLine}{Exception}");
builder.Logging.AddFile($"{Configuration.AppDirectory?.FullName}/" + "logs/api_{Date}.log", LogLevel.Trace, fileSizeLimitBytes: 104857600, retainedFileCountLimit: 10, outputTemplate: "{Timestamp:o} [{Level:u3}] {Message} {NewLine}{Exception}"); // Services
// INFRASTRUCTURE
builder.Services.AddDatabase(builder.Configuration); builder.Services.AddDatabase(builder.Configuration);
builder.Services.AddInfrastructureServices(); builder.Services.AddIdentity(builder.Configuration);
builder.Services.AddIdentityServices();
// IDENTITY
builder.Services.AddIdentityServices(builder.Configuration);
builder.Services.AddBearerAuthentication(builder.Configuration); builder.Services.AddBearerAuthentication(builder.Configuration);
builder.Services.AddTokenServices(builder.Configuration); builder.Services.AddTokenServices(builder.Configuration);
// SECURITY
builder.Services.AddAuthorization(); builder.Services.AddAuthorization();
// WEBSERVICES // Modules
builder.Services.AddProxyServices(builder.Configuration); builder.AddDefaults();
builder.Services.AddRoutingServices(builder.Configuration); builder.AddApiDefaults();
builder.Services.AddControllers(); builder.AddMetrics();
builder.AddSwagger();
// SWAGGER
builder.Services.AddSwaggerServices(builder.Configuration);
//builder.Services.AddControllers();
//builder.Services.AddEndpointsApiExplorer();
//builder.Services.AddSwaggerGen();
// HTTP Pipeline
var app = builder.Build(); var app = builder.Build();
// Configure the HTTP request pipeline.
app.UseForwardedHeaders(); app.UseForwardedHeaders();
if (app.Environment.IsDevelopment()) if (app.Environment.IsDevelopment())
@ -61,17 +52,7 @@ namespace Insight.Api
} }
app.UseSwagger(options => app.ConfigureSwagger();
{
options.RouteTemplate = "api/swagger/{documentName}/swagger.json";
});
app.UseSwaggerUI(options =>
{
options.DefaultModelsExpandDepth(-1);
options.SwaggerEndpoint("/api/swagger/v1/swagger.json", "v1");
options.RoutePrefix = "api/swagger";
});
app.UseCors(x => x app.UseCors(x => x
.AllowAnyOrigin() .AllowAnyOrigin()
@ -93,7 +74,6 @@ namespace Insight.Api
ServeUnknownFileTypes = true ServeUnknownFileTypes = true
}); });
await app.RunAsync(); await app.RunAsync().ConfigureAwait(false);
}
} }
} }

View file

@ -1,7 +1,16 @@
{ {
"AllowedHosts": "*", "AllowedHosts": "*",
"Urls": "http://127.0.0.1:5000", "Urls": "http://127.0.0.1:5000",
"database": "mongodb://db.insight.local:27017",
// set in env vars
//"influx.endpoint": "http://127.0.0.1:8086",
//"influx.token": "",
"influx.org": "insight",
"influx.bucket": "insight",
"influx.service": "api",
"mongo.connection": "mongodb://db.insight.local:27017",
"jwt.key": "x5dcaE8fiBmHfgsNrwIEtSWzZkz6gpouzKOIgEiVjxJnW28V1aUnYXF19IcnF5x", "jwt.key": "x5dcaE8fiBmHfgsNrwIEtSWzZkz6gpouzKOIgEiVjxJnW28V1aUnYXF19IcnF5x",
"jwt.exp": 3600, "jwt.exp": 3600,
"jwt.audience": "http://127.0.0.1:5000", "jwt.audience": "http://127.0.0.1:5000",

View file

@ -1,7 +1,16 @@
{ {
"AllowedHosts": "*", "AllowedHosts": "*",
"Urls": "http://127.0.0.1:5000", "Urls": "http://127.0.0.1:5000",
"database": "mongodb://127.0.0.1:27017",
// set in env vars
//"influx.endpoint": "http://127.0.0.1:8086",
//"influx.token": "",
"influx.org": "insight",
"influx.bucket": "insight",
"influx.service": "api",
"mongo.connection": "mongodb://127.0.0.1:27017",
"jwt.key": "x5dcaE8fiBmHfgsNrwIEtSWzZkz6gpouzKOIgEiVjxJnW28V1aUnYXF19IcnF5x", "jwt.key": "x5dcaE8fiBmHfgsNrwIEtSWzZkz6gpouzKOIgEiVjxJnW28V1aUnYXF19IcnF5x",
"jwt.exp": 3600, "jwt.exp": 3600,
"jwt.audience": "https://insight.webmatic.de/api", "jwt.audience": "https://insight.webmatic.de/api",

View file

@ -1,13 +1,21 @@
using System.Net; using System.Diagnostics;
using System.Net;
using System.Reflection; using System.Reflection;
namespace Insight.Domain.Constants namespace Insight.Domain.Constants;
public static class Configuration
{ {
public static class Configuration
{
public static string Hostname => Dns.GetHostEntry("localhost").HostName; public static string Hostname => Dns.GetHostEntry("localhost").HostName;
public static Version Version => Assembly.GetEntryAssembly()?.GetName().Version ?? throw new ArgumentNullException("Version"); public static Version Version => Assembly.GetEntryAssembly()?.GetName().Version ?? throw new ArgumentNullException("Version");
public static DirectoryInfo? AppDirectory => string.IsNullOrWhiteSpace(Environment.ProcessPath) ? null : new DirectoryInfo(Environment.ProcessPath).Parent; public static DirectoryInfo? AppDirectory => AppDirectoryHelper();
public static string DefaultConfig => Path.Combine(AppDirectory?.FullName ?? string.Empty, "config.json"); public static string DefaultConfig => Path.Combine(AppDirectory?.FullName ?? string.Empty, "config.json");
private static DirectoryInfo? AppDirectoryHelper()
{
using var proc = Process.GetCurrentProcess();
if (proc?.MainModule?.FileName is null) throw new InvalidOperationException("MainModule not found");
return new DirectoryInfo(proc.MainModule.FileName).Parent;
} }
} }

View file

@ -0,0 +1,14 @@
namespace Insight.Domain.Enums;
public enum CategoryEnum
{
None = 0,
Network = 1,
System = 2,
Application = 3,
Security = 4,
Monitoring = 5,
Task = 6,
Printer = 7,
RDP = 8
}

View file

@ -0,0 +1,8 @@
namespace Insight.Domain.Enums;
public enum DispatchEnum
{
Pending = 1,
Failure = 2,
Success = 3,
}

View file

@ -0,0 +1,8 @@
namespace Insight.Domain.Enums;
public enum RemoteControlMode
{
Unknown,
Unattended,
Attended
}

View file

@ -0,0 +1,7 @@
namespace Insight.Domain.Enums;
public enum SessionEndReasons
{
Logoff = 1,
SystemShutdown = 2
}

View file

@ -0,0 +1,14 @@
namespace Insight.Domain.Enums;
public enum SessionSwitchReason
{
ConsoleConnect = 1,
ConsoleDisconnect = 2,
RemoteConnect = 3,
RemoteDisconnect = 4,
SessionLogon = 5,
SessionLogoff = 6,
SessionLock = 7,
SessionUnlock = 8,
SessionRemoteControl = 9
}

View file

@ -0,0 +1,8 @@
namespace Insight.Domain.Enums;
public enum StatusEnum
{
Information = 1,
Warning = 2,
Error = 3
}

View file

@ -0,0 +1,16 @@
using Microsoft.Extensions.Configuration;
namespace Insight.Domain.Extensions;
public static class ConfigurationExtensions
{
public static IConfigurationBuilder Defaults(this IConfigurationBuilder configuration)
{
configuration.Sources.Clear();
configuration.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
configuration.AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json", optional: true, reloadOnChange: true);
configuration.AddEnvironmentVariables();
return configuration;
}
}

View file

@ -0,0 +1,31 @@
using System.Diagnostics;
using System.Runtime.Versioning;
namespace Insight.Domain.Extensions;
public static class Linux
{
[SupportedOSPlatform("linux")]
public static string Bash(this string cmd)
{
var escaped = cmd.Replace("\"", "\\\"");
using var proc = new Process()
{
StartInfo = new ProcessStartInfo
{
FileName = "/bin/bash",
Arguments = $"-c \"{escaped}\"",
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true,
}
};
proc.Start();
var result = proc.StandardOutput.ReadToEnd();
proc.WaitForExit();
return result;
}
}

View file

@ -1,20 +1,25 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<TargetFramework>net7.0</TargetFramework> <TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>true</ImplicitUsings> <LangVersion>latest</LangVersion>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
<RootNamespace>Insight.Domain</RootNamespace> <RootNamespace>Insight.Domain</RootNamespace>
<Product>Insight</Product> <Product>Insight</Product>
<AssemblyVersion>2023.7.3.0</AssemblyVersion> <AssemblyVersion>2023.12.15.0</AssemblyVersion>
<SatelliteResourceLanguages>none</SatelliteResourceLanguages>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'"> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<DebugType>none</DebugType> <!--Ignore MemoryPack Warning-->
<NoWarn>9193</NoWarn>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'"> <ItemGroup>
<DebugType>none</DebugType> <PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="8.0.0" />
</PropertyGroup> <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" />
<PackageReference Include="Vaitr.Network" Version="2024.1.8" />
</ItemGroup>
</Project> </Project>

View file

@ -0,0 +1,8 @@
using Insight.Domain.Network;
namespace Insight.Domain.Interfaces;
public partial interface IMessageHandler<TSender>
{
ValueTask HandleAsync<TMessage>(TSender sender, TMessage message, CancellationToken cancellationToken) where TMessage : IMessage;
}

View file

@ -0,0 +1,147 @@
using MessagePack;
using System.Runtime.Serialization;
using System.Text.Json.Serialization;
namespace RemoteControl.Shared;
/// <summary>
/// Describes the success or failure of any kind of operation.
/// </summary>
[DataContract]
public class Result
{
/// <summary>
/// For serialization only.
/// </summary>
[SerializationConstructor]
[JsonConstructor]
public Result() { }
public Result(bool isSuccess, string reason = "", Exception? exception = null)
{
if (!isSuccess && exception is null && string.IsNullOrWhiteSpace(reason))
{
throw new ArgumentException("A reason or exception must be supplied for an unsuccessful result.");
}
IsSuccess = isSuccess;
Exception = exception;
Reason = reason;
}
[IgnoreDataMember]
public Exception? Exception { get; set; }
[IgnoreDataMember]
//[MemberNotNullWhen(true, nameof(Exception))]
public bool HadException => Exception is not null;
[DataMember]
public bool IsSuccess { get; set; }
[DataMember]
public string Reason { get; set; } = string.Empty;
public static Result Fail(string reason)
{
return new Result(false, reason);
}
public static Result Fail(Exception ex)
{
return new Result(false, string.Empty, ex);
}
public static Result<T> Fail<T>(string reason)
{
return new Result<T>(reason);
}
public static Result<T> Fail<T>(Exception ex)
{
return new Result<T>(ex);
}
public static Result Ok()
{
return new Result(true);
}
public static Result<T> Ok<T>(T value)
{
return new Result<T>(value);
}
}
/// <summary>
/// Describes the success or failure of any kind of operation.
/// </summary>
[DataContract]
public class Result<T>
{
/// <summary>
/// Returns a successful result with the given value.
/// </summary>
/// <param name="value"></param>
public Result(T value)
{
IsSuccess = true;
Value = value;
}
/// <summary>
/// Returns an unsuccessful result with the given exception.
/// </summary>
/// <param name="exception"></param>
public Result(Exception exception)
{
IsSuccess = false;
Exception = exception;
Reason = exception.Message;
}
/// <summary>
/// Returns an unsuccessful result with the given reason.
/// </summary>
/// <param name="errorMessage"></param>
/// <exception cref="ArgumentException"></exception>
public Result(string reason)
{
IsSuccess = false;
Reason = reason;
}
/// <summary>
/// For serialization only.
/// </summary>
[SerializationConstructor]
[JsonConstructor]
public Result() { }
public Result(Exception? exception, bool isSuccess, string reason, T? value)
{
Exception = exception;
IsSuccess = isSuccess;
Reason = reason;
Value = value;
}
[IgnoreDataMember]
public Exception? Exception { get; set; }
[IgnoreDataMember]
//[MemberNotNullWhen(true, nameof(Exception))]
public bool HadException => Exception is not null;
[DataMember]
//[MemberNotNullWhen(true, nameof(Value))]
public bool IsSuccess { get; set; }
[DataMember]
public string Reason { get; set; } = string.Empty;
[DataMember]
public T? Value { get; set; }
}

View file

@ -1,55 +1,43 @@
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
using System.Text.Json.Serialization; using System.Text.Json.Serialization;
namespace Insight.Domain.Models namespace Insight.Domain.Models;
public class TokenRequest
{ {
public class TokenRequest
{
[JsonPropertyName("username"), EmailAddress, Required] [JsonPropertyName("username"), EmailAddress, Required]
public string Username { get; set; } public string? Username { get; set; }
[JsonPropertyName("password"), DataType(DataType.Password), Required] [JsonPropertyName("password"), DataType(DataType.Password), Required]
public string Password { get; set; } public string? Password { get; set; }
[JsonPropertyName("code"), DataType(DataType.Text)] [JsonPropertyName("code"), DataType(DataType.Text)]
public string? Code { get; set; } public string? Code { get; set; }
} }
public class TokenResponse public class TokenResponse
{ {
[JsonPropertyName("access_token")] [JsonPropertyName("access_token")]
public string AccessToken { get; set; } public string? AccessToken { get; set; }
[JsonPropertyName("expires_in")] [JsonPropertyName("expires_in")]
public int ExpireInSeconds { get; set; } public int ExpireInSeconds { get; set; }
[JsonPropertyName("refresh_token")] [JsonPropertyName("refresh_token")]
public string RefreshToken { get; set; } public string? RefreshToken { get; set; }
} }
public class TokenRevokeRequest public class TokenRevokeRequest(string token, string? reason)
{ {
[JsonPropertyName("token"), Required] [JsonPropertyName("token"), Required]
public string Token { get; set; } public string? Token { get; set; } = token;
[JsonPropertyName("reason")] [JsonPropertyName("reason")]
public string? Reason { get; set; } public string? Reason { get; set; } = reason;
}
public TokenRevokeRequest(string token, string? reason)
{ public class TokenRefreshRequest(string token)
Token = token; {
Reason = reason; [JsonPropertyName("token"), Required]
} public string? Token { get; set; } = token;
}
public class TokenRefreshRequest
{
[JsonPropertyName("token"), Required]
public string Token { get; set; }
public TokenRefreshRequest(string token)
{
Token = token;
}
}
} }

Some files were not shown because too many files have changed in this diff Show more